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/Code-on-every-error · L-261015-694798 (#1444)
Louis Choquele0213df87674
diff --git a/.drift/acks/cli-docs.toml b/.drift/acks/cli-docs.tomlindex d543e5479..95c423347 100644--- a/.drift/acks/cli-docs.toml+++ b/.drift/acks/cli-docs.toml@@ -1,8 +1,8 @@contract = "cli-docs"-digest = "sha256:6e4c4adafc41b29144d9050309870127e58bbc085b899894e2b93e9a543dca63"+digest = "sha256:50fca9184cd1ec73cf925205ddb1cc75ee36db1d45ef3e025ef213fbe4bf4e95"reviewed_by = "Louis Choquel"-reviewed_at = "2026-10-17T05:02:24Z"-rationale = "real-catch: the auto-detected inputs file is now read through a descriptor opened without following a link and judged by fstat, and its bytes flow to the parsers, so docs/tools/cli/run.md says it is read without following a link and that a link the tree holds refuses the tree itself; the sentences saying the inputs file stays out of the method tree, true only from the mthds release implementing the run-inputs default, are removed from run.md and build/inputs.md. agent-cli.md stays accurate, and pipelex/cli/agent_cli/CLAUDE.md describes no inputs auto-detection."+reviewed_at = "2026-10-18T10:27:01Z"+rationale = "clean-pass: merging the error registry branch, which carries dev's v0.89.0, into the code-on-every-error branch combines changes each side reviewed; the merge only gives dev's AutoDetectedInputsFileError and the empty-folder MethodEntryError their codes and applies the ModelDeckPresetValidationError rename to dev's report_agent_init_failure. docs/tools/cli/run.md and agent-cli.md, and pipelex/cli/agent_cli/CLAUDE.md, already describe both sides correctly."[trigger_files]"pipelex/cli/__init__.py" = "blob:8b137891791fe96927ad78e64b0aad7bded08bdc"@@ -10,14 +10,14 @@ rationale = "real-catch: the auto-detected inputs file is now read through a des"pipelex/cli/agent_cli/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391""pipelex/cli/agent_cli/_agent_cli.py" = "blob:ad97a597f92ece45d06e571792f77c5b4805826e""pipelex/cli/agent_cli/commands/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"-"pipelex/cli/agent_cli/commands/agent_cli_factory.py" = "blob:512ca7ac621f660a9bfafda298583aef1ce28a71"-"pipelex/cli/agent_cli/commands/agent_output.py" = "blob:10588465f86eb7ce7d0bed3985304612b154d013"+"pipelex/cli/agent_cli/commands/agent_cli_factory.py" = "blob:1e816dea1a7439e0bd0030754a5c519112aeead0"+"pipelex/cli/agent_cli/commands/agent_output.py" = "blob:bdc4f04b61c8824de88afdf76cf394a41e102a82""pipelex/cli/agent_cli/commands/bundle_path_resolver.py" = "blob:93dd3c074626be471437c3815e51b6783cb52d13""pipelex/cli/agent_cli/commands/check_model_cmd.py" = "blob:3a9c93daecadf266b3eba466904b3d005d448d40""pipelex/cli/agent_cli/commands/codegen/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391""pipelex/cli/agent_cli/commands/codegen/app.py" = "blob:56130b89fe9efec5ad3d014ed6bc16bef1bd1645""pipelex/cli/agent_cli/commands/codegen/check_cmd.py" = "blob:9e8beb084a9f04f39e8acca9e6ae2554d40cb667"-"pipelex/cli/agent_cli/commands/codegen/types_cmd.py" = "blob:5c78bd70803a8f32616ccba9c57538ed49ab2d60"+"pipelex/cli/agent_cli/commands/codegen/types_cmd.py" = "blob:7ada455f0bbe20dc30cff73cbc33c397bcf86f39""pipelex/cli/agent_cli/commands/doctor_cmd.py" = "blob:948be63cf4fab165846c83b4bd2517bd4a46be5e""pipelex/cli/agent_cli/commands/fix/__init__.py" = "blob:65662c86f17f610ad55ecfc3e27a022b9aa26e8b""pipelex/cli/agent_cli/commands/fix/app.py" = "blob:fbf3b1ff8298b0cd18f0b712b7623652c5975662"@@ -30,7 +30,7 @@ rationale = "real-catch: the auto-detected inputs file is now read through a des"pipelex/cli/agent_cli/commands/inputs/app.py" = "blob:b30915d6fce2f524af4f0b2a50a37ffd7eaffab6""pipelex/cli/agent_cli/commands/inputs/bundle_cmd.py" = "blob:fedf9fb6f37b37f80dd73be5380a603e23248bfa""pipelex/cli/agent_cli/commands/inputs/method_cmd.py" = "blob:604e91b2e65d951fd9a6eeed924a01f04fe2096f"-"pipelex/cli/agent_cli/commands/inputs/pipe_cmd.py" = "blob:5c9c233b00d626599dea4907b148b4f08cdd58a0"+"pipelex/cli/agent_cli/commands/inputs/pipe_cmd.py" = "blob:73b79e57c9c71da282723711b5cbe9ade8838779""pipelex/cli/agent_cli/commands/lint_cmd.py" = "blob:91ad9cb4d618ba4c0b7da366cde2f74f38d350df""pipelex/cli/agent_cli/commands/migrate_cmd.py" = "blob:dbe1f689607ccea0b1f5f1dadca20f19f65ce400""pipelex/cli/agent_cli/commands/models_cmd.py" = "blob:f48a921fa89d8275c585b3e15f135f5585ac01aa"@@ -42,27 +42,27 @@ rationale = "real-catch: the auto-detected inputs file is now read through a des"pipelex/cli/agent_cli/commands/run/app.py" = "blob:7546d9b31ea2dc22b1ddae538edfbc8e7f7d08df""pipelex/cli/agent_cli/commands/run/bundle_cmd.py" = "blob:6ee1041a4b5201cca1863fe9acaa3850c70faf03""pipelex/cli/agent_cli/commands/run/method_cmd.py" = "blob:776d1cf4bfbdce645f3cbfcd28be46bfb97174b0"-"pipelex/cli/agent_cli/commands/run/pipe_cmd.py" = "blob:f421c75ee696c18f85a7f63805455ef23637302f"-"pipelex/cli/agent_cli/commands/run/stdin_resolver.py" = "blob:5349c102b62136e7dc26ad74a319f219a40e5a60"+"pipelex/cli/agent_cli/commands/run/pipe_cmd.py" = "blob:f6be2d8b0a5e20c087a12fdaf8c42eb2549dfb00"+"pipelex/cli/agent_cli/commands/run/stdin_resolver.py" = "blob:847552a863af5f8e98a4ce1c473c2e828b86a5d6""pipelex/cli/agent_cli/commands/validate/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391""pipelex/cli/agent_cli/commands/validate/_validate_core.py" = "blob:b15fb5ee5b3d84cb229f3eb3353df8354cfd488d""pipelex/cli/agent_cli/commands/validate/app.py" = "blob:1982684a2aae81e0d634bb3b262457a5f187d979""pipelex/cli/agent_cli/commands/validate/bundle_cmd.py" = "blob:ee5dd482fdf03eb2530afcdebfc393fe68646893""pipelex/cli/agent_cli/commands/validate/method_cmd.py" = "blob:0f4cf76d99b39422610c5daf6b5a0500de234818"-"pipelex/cli/agent_cli/commands/validate/pipe_cmd.py" = "blob:9a315ab32c89430c8ea111a0a50e629ed1acd6bf"-"pipelex/cli/bundle_target_resolution.py" = "blob:a712accba29d18c2a89e64fdc2b04854c5dd4ea8"-"pipelex/cli/cli_factory.py" = "blob:310ad1a2d055469cdc4f4728c82b9e83a9ff5852"+"pipelex/cli/agent_cli/commands/validate/pipe_cmd.py" = "blob:c945950c88d4049b5c6400111ccb85b0cb4cc657"+"pipelex/cli/bundle_target_resolution.py" = "blob:0a8fb2b29a9386a9b488d000756da2914713060c"+"pipelex/cli/cli_factory.py" = "blob:9768ead842eecbfc9509dc68aafca31957a27439""pipelex/cli/commands/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391""pipelex/cli/commands/build/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391""pipelex/cli/commands/build/app.py" = "blob:d3205e1dc0268a9d32a517e4f9a9a3b4647e8889""pipelex/cli/commands/build/inputs/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"-"pipelex/cli/commands/build/inputs/_inputs_core.py" = "blob:e5c2bd98e3b9afa438a5dcda538506cb85e8f17d"+"pipelex/cli/commands/build/inputs/_inputs_core.py" = "blob:30246cd2cdafd7c885c5f635181d743d075c5362""pipelex/cli/commands/build/inputs/app.py" = "blob:553e285ae7d1a9bf356b98ec268ba44bb1c30244""pipelex/cli/commands/build/inputs/bundle_cmd.py" = "blob:bd26ee8bd660ae5c09a7fa8a00720930c9854749""pipelex/cli/commands/build/inputs/method_cmd.py" = "blob:2fcaea4f05df4947d6ec1a49b2fa23b52c23ca3c""pipelex/cli/commands/build/inputs/pipe_cmd.py" = "blob:00625740fd29837e3165d31be692e40e96065fc8""pipelex/cli/commands/build/output/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"-"pipelex/cli/commands/build/output/_output_core.py" = "blob:52549b3657f34ac0ff9f9a620ed212a284e97f2b"+"pipelex/cli/commands/build/output/_output_core.py" = "blob:e8a78b33c7113afe192ab9ba4d2680c35be6bcb0""pipelex/cli/commands/build/output/app.py" = "blob:2bd9575e2093f13a1b5240f49b6f5a6a88bd1fee""pipelex/cli/commands/build/output/bundle_cmd.py" = "blob:0209b48f1c221fae59cf5bede2fbd92558a87f56""pipelex/cli/commands/build/output/method_cmd.py" = "blob:242434d518aff0b9706b910e7f937b53a601fde1"@@ -74,7 +74,7 @@ rationale = "real-catch: the auto-detected inputs file is now read through a des"pipelex/cli/commands/codegen/check_cmd.py" = "blob:329f410bca90eb022fad2abc729e8b5203138c02""pipelex/cli/commands/codegen/inputs_cmd.py" = "blob:7e1db7c76857e77c1af2c68d0c8a14d52746fc73""pipelex/cli/commands/codegen/types_cmd.py" = "blob:23ad05431006dfe74ad7840b916eab74d769cebe"-"pipelex/cli/commands/crate_loading.py" = "blob:3d7d651931ecf1a15a3e2d72411b3212b55d74ef"+"pipelex/cli/commands/crate_loading.py" = "blob:3e02d407446ef745116ade9cd08a81990c97bbf8""pipelex/cli/commands/doctor_cmd.py" = "blob:a991d210787c0df68d9cc6bac29361df89e8e9c7""pipelex/cli/commands/fix/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391""pipelex/cli/commands/fix/_diff_sandbox.py" = "blob:d05eb4351f7065eaa45f63089f2daae0b02457dd"@@ -82,7 +82,7 @@ rationale = "real-catch: the auto-detected inputs file is now read through a des"pipelex/cli/commands/fix/app.py" = "blob:61ed114633c679a252fa7d9367d4cf8e800f86ee""pipelex/cli/commands/fix/bundle_cmd.py" = "blob:83bf3fda431fb5d81f1763be28835730df0a9872""pipelex/cli/commands/fix/function_names_cmd.py" = "blob:b645a3d7687f01f18474446d29e23df4f1acc751"-"pipelex/cli/commands/graph_cmd.py" = "blob:d215ad2b66c4421364c90f2d8f875b6312dadfe4"+"pipelex/cli/commands/graph_cmd.py" = "blob:6876a99877752f23369436c4bd7e3eb8726c8401""pipelex/cli/commands/init/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391""pipelex/cli/commands/init/backends.py" = "blob:0cc3543c78f832149ebbbf3cc8beafee619e4f63""pipelex/cli/commands/init/command.py" = "blob:4747c1b9dff00163ca5cd48595ea8545a3b02b4b"@@ -91,7 +91,7 @@ rationale = "real-catch: the auto-detected inputs file is now read through a des"pipelex/cli/commands/init/ide_extension.py" = "blob:9f0ec1494c07062246ecc906bc55b7f2cf95c715""pipelex/cli/commands/init/init_usage_stats.py" = "blob:fca415ba8fef02967cef142f0011a016990274e2""pipelex/cli/commands/init/routing.py" = "blob:c73927deb99804556cb545cdaa6eabf8d1fc3450"-"pipelex/cli/commands/init/setup_path.py" = "blob:6485fae3ee6dd1b112badffdc956f1b734dc1b10"+"pipelex/cli/commands/init/setup_path.py" = "blob:44e664e7c4222c18f635ec83a159e1e7b32bfd95""pipelex/cli/commands/init/telemetry.py" = "blob:07a33b6540e1fc4146d0777463c93abd4ea70231""pipelex/cli/commands/init/ui/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391""pipelex/cli/commands/init/ui/backends_ui.py" = "blob:a5250ebf7f2865da6ca12fc292b75fa7f5e8a690"@@ -101,13 +101,13 @@ rationale = "real-catch: the auto-detected inputs file is now read through a des"pipelex/cli/commands/init/ui/types.py" = "blob:e263802d8e9c9f9687435de1eb992afa5336544f""pipelex/cli/commands/login/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391""pipelex/cli/commands/login/api_key_store.py" = "blob:3a64ee921b54131dcba8c829880c060b5195e2ed"-"pipelex/cli/commands/login/command.py" = "blob:d277c28bf331f073c96c2980182a3bd543830088"+"pipelex/cli/commands/login/command.py" = "blob:94bba64de3140bfe4de34f33a90c46da8af948cf""pipelex/cli/commands/login/loopback.py" = "blob:b66eaa021caa1270a64237169f5a2585267f488c""pipelex/cli/commands/migrate_cmd.py" = "blob:3839424ccbf1c7f8e7af8a7f124a062cba18cece""pipelex/cli/commands/plugins_cmd.py" = "blob:9657b713c3650ff4a929e92ae68af453d896393e""pipelex/cli/commands/resolve_cmd.py" = "blob:88237df0f048bbf5a02e585baef932bfc355e1ee""pipelex/cli/commands/run/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"-"pipelex/cli/commands/run/_hosted_sources.py" = "blob:d2e7efc8e0f9bb5f061d30afc586165c47d2dac8"+"pipelex/cli/commands/run/_hosted_sources.py" = "blob:c38ae7b75c51fe17d565462f9df5e716e634d5cb""pipelex/cli/commands/run/_inputs_file_loader.py" = "blob:8039ca6b29f4f9091d0ea7406c8b8a4590848131""pipelex/cli/commands/run/_inputs_path_resolver.py" = "blob:c8ec89d98718e18af7aaaded44c9f545be60adab""pipelex/cli/commands/run/_main_stuff_file.py" = "blob:ca806e55085aa2e5748492751521296ce1f42960"@@ -116,10 +116,10 @@ rationale = "real-catch: the auto-detected inputs file is now read through a des"pipelex/cli/commands/run/_run_output_folder.py" = "blob:5834889a5e35e6457acf24761b408bc6a7bbfd6c""pipelex/cli/commands/run/app.py" = "blob:e312b159625e0a72bc9a18d3bfd2c73e7ac59f24""pipelex/cli/commands/run/bundle_cmd.py" = "blob:50b6c6e1f931f41a611a979b081f08e560773ce8"-"pipelex/cli/commands/run/exceptions.py" = "blob:84a90e632e2a1ede6aa9de15ab566b7f3b23b8d6"+"pipelex/cli/commands/run/exceptions.py" = "blob:badc192d5239fe402d4d7a18504bb4a01e9c260a""pipelex/cli/commands/run/method_cmd.py" = "blob:924bca6e242d8490e32eeb9ed2329db3d1b58b8d"-"pipelex/cli/commands/run/pipe_cmd.py" = "blob:eafdc4bcf3f3f84042ecf9644e0f17fc355e0e17"-"pipelex/cli/commands/show_cmd.py" = "blob:4c87c70058ea3b15827d03a370f3345569a2b705"+"pipelex/cli/commands/run/pipe_cmd.py" = "blob:c967729a039518a718d7bc28d77797423ce20fc4"+"pipelex/cli/commands/show_cmd.py" = "blob:764665c787525a52d44bff1fb6e64acd008729aa""pipelex/cli/commands/update_cmd.py" = "blob:b2db6170ddd9c67f17d88096ba1f1796a897557d""pipelex/cli/commands/usage_stats_cmd.py" = "blob:b3723c64f911d1b69e1e1aa126610a132a16e3da""pipelex/cli/commands/validate/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"@@ -127,14 +127,14 @@ rationale = "real-catch: the auto-detected inputs file is now read through a des"pipelex/cli/commands/validate/app.py" = "blob:457e110f0458bbe042a5489f58bba91acd885ebd""pipelex/cli/commands/validate/bundle_cmd.py" = "blob:1bf408a2d49b92476c87fa080b850b82cc870a88""pipelex/cli/commands/validate/method_cmd.py" = "blob:f12ee233fc985d04a4512f1fef6b9ea02a1b9644"-"pipelex/cli/commands/validate/pipe_cmd.py" = "blob:791b9a693f4ec52f727b42dab4b102af46a4ee22"+"pipelex/cli/commands/validate/pipe_cmd.py" = "blob:ab8cca9c5c8c5d7dce005deba6d2d8b32dc2e81e""pipelex/cli/commands/which_cmd.py" = "blob:5febd14510603f09ef0fb29d5ef97c35b7a6692f""pipelex/cli/deck_notice.py" = "blob:542877125e89e35b02bc969cfee952155b0d7c2c"-"pipelex/cli/error_handlers.py" = "blob:346737863adac1992351e685294f56394712f476"-"pipelex/cli/exceptions.py" = "blob:1d51c3a53ddd3f6cf8de566fa2ade3fa75ab7a3a"-"pipelex/cli/installed_methods.py" = "blob:f7818b7857a8350389cf196e32630e7b3c51818c"+"pipelex/cli/error_handlers.py" = "blob:bbe95242b498478557832dcab625dc4fe2694f44"+"pipelex/cli/exceptions.py" = "blob:5c66f20b0a06c8ae8c20b94f92e2c30b78f5b6c5"+"pipelex/cli/installed_methods.py" = "blob:1de9b36e7717786fe0454af69011e05ef50610ba""pipelex/cli/judged_target.py" = "blob:8d3f3b3359992feeeca2bd4acd1d404262cbaf87"-"pipelex/cli/method_resolver.py" = "blob:34612bb21e9aae60cd5244abfa111d554443533a"+"pipelex/cli/method_resolver.py" = "blob:54fe2e6036b637c2e298f18bbfd10cfc616ef4a8""pipelex/cli/readiness.py" = "blob:6d185324ed0784663e1dc78d1194a28312c54798""pipelex/cli/usage_stats_cli.py" = "blob:d04e2191e6f6a18027558a3e063f945be7b77679""pipelex/cli/version_report.py" = "blob:f4a2311bb629bd77196ea2f6b031c166db0d362a"diff --git a/.drift/acks/pipelex-kernel-docs.toml b/.drift/acks/pipelex-kernel-docs.tomlindex fc27965dd..a1071e60e 100644--- a/.drift/acks/pipelex-kernel-docs.toml+++ b/.drift/acks/pipelex-kernel-docs.toml@@ -1,31 +1,31 @@contract = "pipelex-kernel-docs"-digest = "sha256:1061433dfa5c3faf0162436f54ac70663d3b0cf518d68d158cdf44c2aaf7b8d1"+digest = "sha256:4d57f0b48f71d64483bf0b6eaae5fdb46e569781477e23f31625ba2e4a49f4aa"reviewed_by = "Louis Choquel"-reviewed_at = "2026-10-16T02:18:50Z"-rationale = "real-catch: func_ops.py replaces call_registered_function with call_function, which is handed the resolved function, and run_func takes function= instead of function_name=; docs/under-the-hood/pipelex-kernel.md now names call_function and says the kernel is handed the callable while the interpreter resolves a PipeFunc's import path from its method tree. The kernel boot contract test hands run_func the function."+reviewed_at = "2026-10-16T21:33:18Z"+rationale = "real-catch: the kernel split call_function into invoke_function and coerce_function_output, and the coercion refuses a list holding anything but stuff contents; docs/under-the-hood/pipelex-kernel.md now names the two halves, says the in-process executor calls them apart so only the call is the function's failure, and that a list holding anything else fails as FuncOutputTypeError with pipe.output_invalid."[trigger_files]"pipelex/kernel/__init__.py" = "blob:c4f1b0fe2ccc17db9110733f71b612f4ac1ba4ce""pipelex/kernel/compose_ops.py" = "blob:ccd8ba141246380eb5e9d55e693fa6fedf38233a""pipelex/kernel/compose_results.py" = "blob:a837ae9680c7d4d0eb4dee37d4657c410e5b5cea"-"pipelex/kernel/exceptions.py" = "blob:ec784b58d732cca19b9278c83afd009422792e81"-"pipelex/kernel/extract_ops.py" = "blob:19d556f0254017d7d52c30f4f1a46e2235289042"+"pipelex/kernel/exceptions.py" = "blob:9d6d9a91e728a0b6e4c3b40e87d9b3bf8b724fb7"+"pipelex/kernel/extract_ops.py" = "blob:85a020968d63a283f434bc0eab66a295cef53cbe""pipelex/kernel/extract_results.py" = "blob:79405a56760f3d4b483660d76441fff95f58c64d"-"pipelex/kernel/func_ops.py" = "blob:4a1f8cf0df1a8e493fefeb9313c53dd469565b84"+"pipelex/kernel/func_ops.py" = "blob:7bac824ea53a9571bf3f21855100dc3277f0ab4f""pipelex/kernel/func_results.py" = "blob:a7425a0ddc21571f23c53b92f5d7559ffdd08b71"-"pipelex/kernel/img_gen_ops.py" = "blob:b85360f6c118e93be53bf8d1a04504ccb7552469"+"pipelex/kernel/img_gen_ops.py" = "blob:42858061ef4a9a162bb79281a5a44799268613d4""pipelex/kernel/img_gen_prompt.py" = "blob:c653190d40e4323f763b9da511bd55a4a1646888""pipelex/kernel/img_gen_results.py" = "blob:46b4ca11c70d906ae6d58ce66461f9b3414f1bfa"-"pipelex/kernel/judgment_ops.py" = "blob:68316783e27e9a55b95a66929d661c1ed5d6d5a3"+"pipelex/kernel/judgment_ops.py" = "blob:6bf523ecd35390e76a8150755a71295d24977698""pipelex/kernel/judgment_results.py" = "blob:4dbbcb204309265999de59a179f4420a0f83be93"-"pipelex/kernel/llm_ops.py" = "blob:d37a9c3718a37f5e7d1550d1512dddbf79032cae"+"pipelex/kernel/llm_ops.py" = "blob:ce23b49ee5050ac38af7ba518fc6a632216f78fb""pipelex/kernel/llm_prompt_content.py" = "blob:f996cead6e7789494f01f69c128ae71d6dcf8466""pipelex/kernel/llm_results.py" = "blob:6e3b8a2878b5bb284ece5fac10262fb59ac2029d""pipelex/kernel/memory_ops.py" = "blob:7fbbfaaec99f9712d8e215520cb02e26aad3fb40""pipelex/kernel/pipelex_kernel.py" = "blob:c7d40db1572aaca00d1c04a1039f5e3e564d6f87"-"pipelex/kernel/prompt_assembly.py" = "blob:7559725bc0d813cd136bf258b8178d96a8f49194"+"pipelex/kernel/prompt_assembly.py" = "blob:47ed529296780eb21f3956849081f3108e18ffa4""pipelex/kernel/prompt_references.py" = "blob:a4a8c5535c7e51a16ac6c8d1296439b331192a7f"-"pipelex/kernel/search_ops.py" = "blob:b7de7ff62c45dde7f7aa8a9f409aecf3b664cce5"+"pipelex/kernel/search_ops.py" = "blob:30d2af78f0ef00c4d8b3647f52cc7cb4a01bf236""pipelex/kernel/search_results.py" = "blob:101b70dc96cc5ee1721c9f6b1cb725a5ca78ff70""pipelex/kernel/templating_style_ops.py" = "blob:395473806d600dfc4f124c07f2afebb951fc086b""tests/unit/pipelex/kernel/test_kernel_boot_contract.py" = "blob:88ec91a8b7cc9a0819756e3499a5bbb661fe1b01"diff --git a/.test_durations b/.test_durationsindex 56af8b33e..e02874ce4 100644--- a/.test_durations+++ b/.test_durations@@ -16206,16 +16206,6 @@"tests/unit/pipelex/test_pipelex_error_message_init.py::TestPipelexErrorMessageInit::test_message_set_and_error_report_succeeds[ConstructFieldBlueprintValueError]": 0.0005,"tests/unit/pipelex/test_pipelex_error_message_init.py::TestPipelexErrorMessageInit::test_message_set_and_error_report_succeeds[RoutingProfileBlueprintValueError]": 0.0012,"tests/unit/pipelex/test_pipelex_error_message_init.py::TestPipelexErrorMessageInit::test_no_subclass_shadows_message_setting_init": 0.8693,- "tests/unit/pipelex/test_pipelex_error_title_and_type_uri.py::TestPipelexErrorTitleAndTypeUri::test_auto_derive_title": 0.0003,- "tests/unit/pipelex/test_pipelex_error_title_and_type_uri.py::TestPipelexErrorTitleAndTypeUri::test_curated_titles_for_high_traffic_classes": 0.0014,- "tests/unit/pipelex/test_pipelex_error_title_and_type_uri.py::TestPipelexErrorTitleAndTypeUri::test_declared_title_does_not_leak_through_inheritance": 0.0004,- "tests/unit/pipelex/test_pipelex_error_title_and_type_uri.py::TestPipelexErrorTitleAndTypeUri::test_declared_title_wins_over_auto_derive": 0.0002,- "tests/unit/pipelex/test_pipelex_error_title_and_type_uri.py::TestPipelexErrorTitleAndTypeUri::test_declared_type_uri_wins_over_auto_derive": 0.0011,- "tests/unit/pipelex/test_pipelex_error_title_and_type_uri.py::TestPipelexErrorTitleAndTypeUri::test_mthds_parser_error_identity_is_pinned": 0.0007,- "tests/unit/pipelex/test_pipelex_error_title_and_type_uri.py::TestPipelexErrorTitleAndTypeUri::test_round_trip_preserves_title_and_type_uri": 0.1211,- "tests/unit/pipelex/test_pipelex_error_title_and_type_uri.py::TestPipelexErrorTitleAndTypeUri::test_to_error_report_populates_title_and_type_uri": 0.8928,- "tests/unit/pipelex/test_pipelex_error_type_uri_uniqueness.py::TestPipelexErrorTypeUriUniqueness::test_all_derived_type_uris_are_unique": 0.119,- "tests/unit/pipelex/test_pipelex_error_type_uri_uniqueness.py::TestPipelexErrorTypeUriUniqueness::test_all_pipelex_error_subclasses_have_unique_type_uris": 1.1115,"tests/unit/pipelex/test_registry_models_split.py::TestRegistryModelsSplit::test_every_pipe_kind_declares_the_factory_that_gets_looked_up_for_it": 0.9532,"tests/unit/pipelex/test_registry_models_split.py::TestRegistryModelsSplit::test_every_registered_model_is_live_in_the_booted_class_registry": 0.1094,"tests/unit/pipelex/test_registry_models_split.py::TestRegistryModelsSplit::test_no_two_registered_models_share_a_class_name": 0.0011,diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bcccbf0c8..6b8e1df14 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,18 +8,40 @@- **`pipelex.errors.registry.pipelex_codes`**: `PipelexErrorCode`, a member per code of the Pipelex error registry, and for each code a closed, frozen and strict parameters model typed as the registry declares, with the code and its operator-only parameters as class attributes, `PIPELEX_ERROR_PARAMS` mapping each code to its model.- **A documentation page per error code**: docs.pipelex.com documents each code of the Pipelex error registry on its own page, under the Error Codes index at `errors/`, and its type URI, `https://docs.pipelex.com/errors/<code>`, leads to that page once a release documenting the code is the latest.- **`pipelex-dev generate-error-registry` and `pipelex-dev check-error-registry`** (`make ger`, `make cer`): generate the registry's snapshot, its typed Python and its pages from the source, refusing a source the format's JSON Schema, the typed model or the registry's rules refuse, or check that every derived file is what the generator writes; `pipelex-dev write-error-type-redirects` writes the redirects that make a code's type URI resolve, which every documentation deploy runs.--### Changed-+- **Every error carries its registry code**: every `PipelexError` subclass declares in `error_code` the code it raises, a code of the MTHDS core registry or of the Pipelex error registry, or else an `ErrorCodeSet` its raise sites choose from with `with_error_code()`, its cause's code (`InheritsCause`, with a fallback), or `ABSTRACT_ERROR` for a base never raised itself. `resolve_error_code()` gives the code an error reports, the first one named along its cause chain, and `runtime.unexpected` when none is; `pipelex.errors.error_codes` reads any code's title, domain, retry verdict, status and steps (`error_code_spec`, `parse_error_code`).+- **`PluginRegistrar.declare_error_codes`**: a plugin, a closed one included, declares the public codes it raises while it registers, and a code neither the MTHDS core nor the Pipelex registry defines refuses the boot with `PluginErrorCodeNotRegisteredError` (`pipelex.plugin.broken`), naming the plugin and the code.+- **`PipelexRequestError`**: the runtime's own refusal of a request it cannot serve is a `PipelineRequestError` of the mthds package carrying the core code `request.invalid` (or `request.unsupported`) and its problem document, so a client reads the same refusal whether the runtime or the standard's client raised it.++### Changed++- **`ErrorReport` reads from its code (Breaking)**: `ErrorReport` gains the required `code`, and its `title`, `type_uri`, `error_domain` and `retryable` are the code's: the type URI is the code's page, `https://mthds.ai/errors/<code>` for a core code and `https://docs.pipelex.com/errors/<code>` for a Pipelex code, the domain is read from the code's registry domain (input and method read `input`, account and operator read `config`) and is always set, and `retryable` is always set, `true` only when the code's retry verdict is `yes`. The problem document carries `code` as an extension member, and `ErrorReport.make_for_code()` builds the report of a code.+- **A run failure reports its root fault's code (Breaking)**: the root fault a run failure reports is the first error down its cause chain that declares a code of its own, and its `code`, `error_type`, `title`, `type_uri`, `error_domain` and `retryable` are the report's, with no `runtime` floor on the domain; a consumer that branched on the wrapper's `error_type` branches on `code`. A `PipeFunc` whose function raised reads `pipe.function_raised` whatever it raised, a coded error of a helper the function called included, which rides as the cause, while a failure of the executor running it, such as its timeout, keeps its own code, and an exception an executor lets through that is not a Pipelex error, such as an out-of-process executor's transport failure, reads `runtime.unexpected`.+- **The runner's request refusals carry their code (Breaking)**: a `/v1/execute` or `/v1/start` body the runner refuses beyond its schema (a bundle sent with `mthds_contents`, `method_ref` beside a bundle or `mthds_contents`, `resources` or `dependencies` without the files they belong to, no run source, a hosted-only field such as `method_id`) answers a 422 `PipelexRequestError` carrying `request.invalid` or `request.unsupported`, where it answered `ValidationError`, and the API's `ProblemDocument` schema documents `code`.+- **Pipe selection refusals carry the code of their case**: an entry pipe the selector names but no closure declares reads `request.pipe_not_found`, a request with no selector over a closure declaring no `main_pipe` `request.pipe_unspecified`, an ambiguous one `request.pipe_ambiguous`, and a manifest `main_pipe` the closure does not resolve `method.pipe_unresolved`, all still a 422.+- **`PipeIOContractError` is the method's (Breaking)**: a structure that cannot be projected into its IO contract answers a 422 carrying `method.concept_invalid`, where it answered a 500.+- **Storage and remote-file failures say whose they are**: an S3 or GCS refusal of the deployment's credentials (`AccessDenied`, an invalid or expired key, `Forbidden`) carries `pipelex.config.credential_refused`, a bucket that does not exist `pipelex.config.invalid` and missing credentials `pipelex.config.credential_missing`, apart from an outage, `pipelex.storage.unavailable`; a remote file that times out, refuses the connection or answers a 5xx, 408, 425 or 429 is `input.url_unreachable`, which a retry may cure, and any other failed fetch `input.file_unreadable`.+- **Builtins raised where a reader sees them are coded classes**: refusals that raised a bare `ValueError`, `RuntimeError`, `ImportError` or `NotImplementedError` raise a coded `PipelexError`, such as `RunParameterError` for a run's metadata, extras or storage scope (still a `ValueError`), `ExportedPipeNotFoundError` and `ExportedPipeAmbiguousError` for a CLI pipe selector, `BundleClosureEmptyError`, `StorageNotConfiguredError`, `UrlSyntaxError`, `LocalFileMissingError` and `UnsupportedImageMimeTypeError`, and the classes that were rooted outside `PipelexError` (`PipeValidationError`, `ConceptValueError`, `QualifiedRefError`, `SemVerError`, `MethodNotFoundError` and the like) join it.+- **Inference failures carry the code their classification picks (Breaking)**: the classification of a provider's failure picks a code with its category, a `ServiceErrorCode` a plugin contributes names its `error_code`, and a category that repeats the call within the run must pick a code that invites a retry; an error built with a category alone reports the category's code (`provider.unavailable` for `TRANSIENT`, `runtime.misconfigured` for `CONFIGURATION`, `provider.quota_exhausted` for `CAPACITY`, `provider.outcome_unknown` for `AMBIGUOUS`). A provider 400 that carries no content-policy signal is `runtime.unexpected`, answered 500, where it was the caller's 422, and a local extractor's `OSError` is `runtime.unexpected`, no longer repeated within the run.+- **A truncated completion says which limit cut it**: `LLMCompletionTruncatedError` carries `model.output_truncated` when the method's `max_tokens` cut the answer and `model.context_exceeded` when the context window did, both the method's to change.+- **`ModelDeckPresetValidationError` is spelt right (Breaking)**: the error a model deck preset that fails validation raises was `ModelDeckPresetValidatonError`, and its reports carried that `error_type`; a consumer that branched on the old name branches on the new one, or on its code, `pipelex.config.invalid`.+- **`pipelex-agent` reads `retryable` from the code (Breaking)**: the agent CLI's error envelope takes `retryable` from the report's code, and its table of retryable error types is gone, as are the domain-table entries of classes that now carry a code. The envelope names that code as `error_code`, the member a hosted refusal already carried, so an agent branches on the code whichever runner failed.- **`Jinja2TemplateSecurityError` is a `SecurityError` (Breaking)**: the template sandbox's refusal at render time now derives from `SecurityError`, like `UriReadRefusedError`, `SsrfBlockedError` and `UnsafeSchemaError`, instead of `ToolError`, so a host catching `SecurityError` catches it too and an `except ToolError` no longer does; it stays a type of its own, apart from `Jinja2TemplateRenderError`, and its `error_type`, title and classification are unchanged.+- **`mthds` 0.22.1 and `pipelex-sdk` 0.46.0 (Breaking)**: the exact pins move from `mthds==0.22.0` and `pipelex-sdk==0.45.0` to `mthds==0.22.1`, the release whose errors carry the MTHDS problem document read by its registry code, and `pipelex-sdk==0.46.0`, the release built on it; everyone downstream inherits those exact versions.### Fixed+- **A model deck's own unresolved default or override is the deployment's fault**: a deck default or override naming a model the deck does not define raises `ModelDeckChoiceUnresolvedError`, naming the deck setting and carrying `pipelex.config.invalid`, answered 500 and withheld under STRICT, where it read as the caller's unknown model, and a `PipeJudge` naming no model, whose default is resolved as its method loads, raises it rather than an `unknown_model` verdict item; a bad override is refused when the deck is built, and a handle the deck serves only as another type of model is `model.capability_unsupported`.+- **A host library that refuses to load is the deployment's fault**: a method of a server's own library directories that refuses to load beside a caller's bundles raises `HostLibraryLoadRefusalError`, carrying `pipelex.config.invalid`, which an API answers with a 500 whose message STRICT disclosure withholds, where it answered the caller a 422 verdict carrying the host library's text; the same refusal in the caller's own content, or in library directories the caller owns, stays the caller's 422 verdict.+- **A template error found only at render is a located refusal**: a template naming a filter or a test that does not exist, which Jinja2 only finds when the branch renders, fails the run at the pipe with `Jinja2TemplateInvalidError`, naming the unknown filter or test and none of the template, coded `method.template_invalid` (a 422 STRICT disclosure keeps) when the template is the method's, in a `PipeCondition` expression, a `PipeLLM` prompt or system prompt and a `PipeDocGen` template, and `runtime.unexpected` when it is one of Pipelex's own, such as the deployment's structure prompt rendered in a `PipeLLM` step, where it failed as an unclassified 500. A filter refusing its argument, which may be a value of the run's data, is `pipe.template_render_failed` rather than the template's fault.+- **A provider's 408 is retried**: a provider answering HTTP 408, that it gave up waiting, is a transient failure carrying `provider.timeout`, so the call is repeated within the run, a billed image call included, where it was read as the caller's input and the run failed on its first attempt.+- **A `PipeFunc` returning a list of anything but stuff contents fails its output**: a function returning a list that holds a value other than a stuff content, such as a dict or a number, fails the step with `FuncOutputTypeError` (`pipe.output_invalid`), where a dict became an empty content and any other value failed as though the function had raised.+- **A file-type refusal no longer quotes the file**: `FileTypeError`'s message gives the number of bytes it read, where it quoted up to 300 bytes of the file's content.- **Pre-release documentation is published**: a push to a `pre-release/` branch deploys its documentation under the `pre-release` alias of docs.pipelex.com, where the deploy workflow called a make target with no recipe and published nothing.### Removed-- **The per-class error pages (Breaking)**: the generated page every `PipelexError` class had under `docs/errors/`, `pipelex-dev generate-error-pages` (`make gep`) and `pipelex.errors.error_pages_generator` are gone; a class-derived `type_uri` names no page any more, and docs.pipelex.com sends such a URL to the Error Codes index.+- **The per-class error pages (Breaking)**: the generated page every `PipelexError` class had under `docs/errors/`, `pipelex-dev generate-error-pages` (`make gep`) and `pipelex.errors.error_pages_generator` are gone; a report's `type_uri` is now its code's page, and docs.pipelex.com redirects each retired page to the page of its class's code, or to the Error Codes index when the class is gone or raises no single code.+- **Class-level error classification (Breaking)**: an error class no longer declares `error_domain` or `retryable`, `PipelexError.title()` and `PipelexError.type_uri()` are gone, and so is `InferenceErrorCategory.error_domain`: the class declares its `error_code`, which decides all four, and an inference failure's category, which stays inside the runtime, picks the code its worker raises. `as_caller_fault()` marks the message caller-facing and names the next step, and no longer sets the domain.## [v0.89.0] - 2026-10-17diff --git a/api/pipelex_api/api_config.py b/api/pipelex_api/api_config.pyindex 7e3a83306..968c71bad 100644--- a/api/pipelex_api/api_config.py+++ b/api/pipelex_api/api_config.py@@ -32,6 +32,7 @@ from pydantic import BaseModel, ConfigDictfrom pipelex_api.error_types import ErrorTypefrom pipelex_api.errors import raise_forbidden+from pipelex_api.exceptions import ApiBootConfigErrorAPI_CONFIG_NAME = "api"@@ -110,8 +111,15 @@ def resolve_orchestration_mode(requested: str | None, *, config: ApiConfig) -> sraise_forbidden(msg, error_type=ErrorType.ORCHESTRATION_MODE_OVERRIDE_FORBIDDEN)-class ApiBootConfigError(ValueError):- """Raised at startup when the deployment's orchestration config cannot boot coherently."""+def is_callers_override(*, orchestration_mode: str, config: ApiConfig) -> bool:+ """Whether a resolved orchestration mode is a per-request override the caller named, not the deployment's default.++ :func:`resolve_orchestration_mode` returns the default unless the caller named a different mode the policy+ allows, so a resolved mode other than the default is always the caller's. A refusal of such a mode, such as+ one no installed plugin serves, is the caller's to change (``runtime.unsupported``), where the same refusal of+ the default is the operator's (``pipelex.plugin.not_found``).+ """+ return orchestration_mode != config.orchestration_modedef resolve_boot_orchestrator(config: ApiConfig) -> str | None:diff --git a/api/pipelex_api/disclosure.py b/api/pipelex_api/disclosure.pyindex 26fdc3ffc..fb1ab88ad 100644--- a/api/pipelex_api/disclosure.py+++ b/api/pipelex_api/disclosure.py@@ -16,11 +16,9 @@ disclosure mode is a security-relevant mistake the operator must see.from pipelex.base_exceptions import DisclosureModefrom pipelex.system.environment import get_optional_env-ERROR_DISCLOSURE_ENV_VAR = "ERROR_DISCLOSURE"-+from pipelex_api.exceptions import InvalidErrorDisclosureError-class InvalidErrorDisclosureError(ValueError):- """Raised at startup when `ERROR_DISCLOSURE` holds an unrecognized value."""+ERROR_DISCLOSURE_ENV_VAR = "ERROR_DISCLOSURE"def resolve_disclosure_mode() -> DisclosureMode:diff --git a/api/pipelex_api/error_uri.py b/api/pipelex_api/error_uri.pyindex 8d7e49e0a..a619d5c26 100644--- a/api/pipelex_api/error_uri.py+++ b/api/pipelex_api/error_uri.py@@ -1,22 +1,18 @@"""RFC 7807 `type` URI and `title` for API-authored errors.-A pipelex `ErrorReport` always carries its own `type_uri` and `title` (set-upstream by `PipelexError.type_uri()` / `PipelexError.title()`, both required-fields), so the global exception handler never needs these helpers for a-`PipelexError`.+A pipelex `ErrorReport` always carries its own `type_uri` and `title`, both+required fields and both the registry code's (`ErrorReport.make_for_code`): the+code's documentation page and the code's title. The global exception handler+never needs these helpers for a `PipelexError`.They exist for the *other* error source: the API's own 4xx responses(`raise_validation_error` and friends in `pipelex_api.errors`), authored from thestatic `pipelex_api.error_types.ErrorType` enum with no `ErrorReport` behind them.`build_problem_document_from_api_error` uses these to give an API-authored-error the same RFC 7807 `type` / `title` shape as a pipelex one. They also-serve as a defensive backstop should a future pipelex ever hand back a report-with an absent identity pair.--The URI namespace and the kebab / humanize transforms are deliberately the-same ones pipelex uses (`URLs.error_docs_base`, `pascal_case_to_kebab`,-`pascal_case_to_sentence`), so an API-authored error and a pipelex error are-indistinguishable in shape on the wire. Both functions are pure.+error an RFC 7807 `type` / `title` pair. Unlike a pipelex error's, that pair+is still derived from a class name (`URLs.error_docs_base`, `pascal_case_to_kebab`,+`pascal_case_to_sentence`) until every API-authored raise carries its own+registry code. Both functions are pure."""from pipelex.tools.misc.string_utils import pascal_case_to_kebab, pascal_case_to_sentence@@ -26,13 +22,12 @@ from pipelex.urls import URLsdef error_type_uri(error_type: str) -> str:"""Return the RFC 7807 `type` URI for an error type name.- `EnvVarNotFoundError` -> `https://docs.pipelex.com/latest/errors/env-var-not-found-error/`.- The URI is derived from the class name, trailing slash included, exactly as- `PipelexError.type_uri()` derives it upstream, so the two share one shape on- the wire. No page lives at it: the per-class error pages are retired, and the- docs site's 404 page sends such a URI to the Error Codes index. The type URI- stays class-derived until every raise carries its code from the error- registry, whose type URI names the code's page.+ `ValidationError` -> `https://docs.pipelex.com/latest/errors/validation-error/`.+ The URI is derived from the class name, trailing slash included. No page+ lives at it: the per-class error pages are retired, and the docs site's 404+ page sends such a URI to the Error Codes index. The type URI stays+ class-derived until every API-authored raise carries its code from the error+ registry, whose type URI names the code's page, as a pipelex error's already does."""return f"{URLs.error_docs_base}/{pascal_case_to_kebab(error_type)}/"@@ -41,9 +36,8 @@ def error_type_title(error_type: str) -> str:"""Return a human-readable RFC 7807 `title` for an error type name.`ValidationError` -> `Validation error`; `BadRequest` -> `Bad request`.- Sentence case via the same `pascal_case_to_sentence` transform pipelex uses- in `PipelexError.title()`. Unlike `PipelexError.title()` it does NOT strip a- trailing `Error`: an API `ErrorType` such as `ValidationError` must keep the- suffix — `"Validation"` alone would be a worse label than `"Validation error"`.+ Sentence case via `pascal_case_to_sentence`. It does NOT strip a trailing+ `Error`: an API `ErrorType` such as `ValidationError` must keep the suffix —+ `"Validation"` alone would be a worse label than `"Validation error"`."""return pascal_case_to_sentence(error_type)diff --git a/api/pipelex_api/exception_handlers.py b/api/pipelex_api/exception_handlers.pyindex 4158f0481..683248ea9 100644--- a/api/pipelex_api/exception_handlers.py+++ b/api/pipelex_api/exception_handlers.py@@ -297,6 +297,9 @@ def _json_safe_report(report: ErrorReport) -> ErrorReport:return report.model_copy(update={"provider_metadata": safe_metadata})+# Every error the runtime raises carries a code, and the code decides its domain, but the HTTP status still+# comes from that domain (`ErrorReport.http_status`): these rows keep the statuses the runner answered before+# the codes, until the status is read from the registry instead._ERROR_TYPE_STATUS_OVERRIDES: dict[str, int] = {# Async execution disabled is a deliberate deployment configuration, not# an unexpected runtime fault. Mapping it to 501 Not Implemented (rather@@ -310,16 +313,17 @@ _ERROR_TYPE_STATUS_OVERRIDES: dict[str, int] = {# tells clients "this id is currently in use": resubmit after the# in-flight run finishes, or pick a fresh id."PipelineManagerAlreadyExistsError": 409,- # The `method_ref` resolution failures (pipelex `MethodRefError` subclasses). The library- # declares no `error_domain` on them, so without an override each would default to 500 —- # wrong for what are overwhelmingly caller-fixable conditions. Each entry keeps the class- # name as the distinct `error_type` the caller (or an agent) branches on:+ # The `method_ref` resolution failures (pipelex `MethodRefError` subclasses), overwhelmingly+ # caller-fixable conditions. Each entry keeps the class name as the distinct `error_type`+ # the caller (or an agent) branches on, beside the `code` that names the fault:# - A reference that does not match the `<address>[@<tag>]` grammar: the caller's own# input, plainly fixable → 422."MethodRefParseError": 422,# - The repository could not be fetched (nonexistent repo, a `@tag` that is not a tag,# network refusal). The dominant cause is a mistyped address or tag — caller-fixable —- # so 422; the message carries git's own explanation for the rarer upstream faults.+ # so 422; the message carries git's own explanation for the rarer upstream faults, and+ # the code tells them apart where the raise site can (`method.not_found`,+ # `method.fetch_failed`, `pipelex.config.dependency_missing`)."MethodFetchError": 422,# - The repository was fetched but holds no package matching the address by manifest# identity: the referenced resource does not exist → 404 (mirroring the hosteddiff --git a/api/pipelex_api/exceptions.py b/api/pipelex_api/exceptions.pynew file mode 100644index 000000000..be6f8f76d--- /dev/null+++ b/api/pipelex_api/exceptions.py@@ -0,0 +1,32 @@+"""The runner's own error classes, each carrying its registry code.++Every class here is a :class:`~pipelex.base_exceptions.PipelexError` that declares its ``error_code`` in its own+body, as pipelex's error model requires (``pipelex/errors/error_code_declaration.py``), and the runner's gate test,+``tests/unit/test_error_code_gate.py``, fails the build on one that does not. They live in this module, rather than+beside the code that raises them, as every error class does: the same gate refuses one defined outside an+``exceptions.py`` or ``<topic>_exceptions.py`` module.++The API-authored refusals (``pipelex_api.errors.ApiError``, built from ``pipelex_api.error_types.ErrorType``) are a+separate family with no ``ErrorReport`` behind them.+"""++from pipelex.base_exceptions import PipelexError+from pipelex.errors.registry.pipelex_codes import PipelexErrorCode+++class ApiBootConfigError(PipelexError):+ """Raised at startup when the deployment's orchestration config cannot boot coherently."""++ error_code = PipelexErrorCode.CONFIG_INVALID+++class InvalidAuthModeError(PipelexError):+ """Raised at startup when `AUTH_MODE` holds a value that is not an `AuthMode` member."""++ error_code = PipelexErrorCode.CONFIG_INVALID+++class InvalidErrorDisclosureError(PipelexError):+ """Raised at startup when `ERROR_DISCLOSURE` holds an unrecognized value."""++ error_code = PipelexErrorCode.CONFIG_INVALIDdiff --git a/api/pipelex_api/method_cache.py b/api/pipelex_api/method_cache.pyindex beb6af907..c5fdbf0e9 100644--- a/api/pipelex_api/method_cache.py+++ b/api/pipelex_api/method_cache.py@@ -38,7 +38,9 @@ from contextlib import contextmanagerfrom functools import cachefrom pathlib import Path+from mthds.protocol.problem.registry import CoreCodefrom pipelex import log+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.methods.exceptions import MethodFetchErrorfrom pipelex.methods.fetching import FetchedMethodPackage, ensure_package_within_bounds, fetch_method_packagefrom pipelex.methods.method_ref import MethodRef@@ -69,13 +71,15 @@ def _run_ls_remote(*, clone_url: str, ref_patterns: list[str], ref_str: str) ->)except FileNotFoundError as exc:msg = "git is not installed or not found on PATH"- raise MethodFetchError(msg) from exc+ raise MethodFetchError(msg).with_error_code(PipelexErrorCode.CONFIG_DEPENDENCY_MISSING) from excexcept subprocess.CalledProcessError as exc:+ # One exit status covers a repository that does not exist and a host that does not answer, so the code is the+ # transient one until the fetch tells them apart (L-261015-09d338).msg = f"Failed to fetch method '{ref_str}': could not reach the repository ({exc.stderr.strip()})"- raise MethodFetchError(msg) from exc+ raise MethodFetchError(msg).with_error_code(CoreCode.METHOD_FETCH_FAILED) from excexcept subprocess.TimeoutExpired as exc:msg = f"Timed out resolving method '{ref_str}' against the remote repository"- raise MethodFetchError(msg) from exc+ raise MethodFetchError(msg).with_error_code(CoreCode.METHOD_FETCH_FAILED) from excpairs: list[tuple[str, str]] = []for line in result.stdout.strip().splitlines():@@ -121,12 +125,12 @@ def resolve_remote_commit_sha(*, ref: MethodRef, clone_url: str | None = None) -f"'{ref.tag}' in method reference '{ref.ref_str}' does not name a git tag on the repository — "f"`@<tag>` pins a git tag (recommended form vX.Y.Z); branch names are not accepted.")- raise MethodFetchError(msg)+ raise MethodFetchError(msg).with_error_code(CoreCode.METHOD_NOT_FOUND)pairs = _run_ls_remote(clone_url=effective_clone_url, ref_patterns=["HEAD"], ref_str=ref.ref_str)head = [sha for sha, name in pairs if name == "HEAD"]if not head:msg = f"The repository behind method reference '{ref.ref_str}' has no HEAD (empty repository?)"- raise MethodFetchError(msg)+ raise MethodFetchError(msg).with_error_code(CoreCode.METHOD_NOT_FOUND)return head[0]diff --git a/api/pipelex_api/method_source.py b/api/pipelex_api/method_source.pyindex 60932249c..cf8a7be6b 100644--- a/api/pipelex_api/method_source.py+++ b/api/pipelex_api/method_source.py@@ -43,7 +43,9 @@ from contextlib import contextmanagerfrom pathlib import Pathfrom typing import NamedTuple+from mthds.protocol.problem.registry import CoreCodefrom pipelex import log+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.libraries.method_trees import list_package_method_treefrom pipelex.methods.exceptions import MethodFetchErrorfrom pipelex.methods.fetching import FetchedMethodPackage, MethodProvenance@@ -104,13 +106,13 @@ def _run_git(*, clone_dir: Path, args: list[str], stdin: bytes | None, package_a)except FileNotFoundError as exc:msg = "git is not installed or not found on PATH"- raise MethodFetchError(msg) from exc+ raise MethodFetchError(msg).with_error_code(PipelexErrorCode.CONFIG_DEPENDENCY_MISSING) from excexcept subprocess.CalledProcessError as exc:msg = f"Could not read method package '{package_address}' from its commit: {exc.stderr.decode('utf-8', errors='replace').strip()}"- raise MethodFetchError(msg) from exc+ raise MethodFetchError(msg).with_error_code(CoreCode.METHOD_FETCH_FAILED) from excexcept subprocess.TimeoutExpired as exc:msg = f"Timed out reading method package '{package_address}' from its commit"- raise MethodFetchError(msg) from exc+ raise MethodFetchError(msg).with_error_code(CoreCode.METHOD_FETCH_FAILED) from excreturn result.stdout@@ -139,7 +141,7 @@ def _package_tree_entries(*, package: FetchedMethodPackage) -> list[_GitTreeEntrpath = raw_path.decode("utf-8")except UnicodeDecodeError as exc:msg = f"Method package '{package.full_address}' holds a file whose name is not UTF-8 text, which no method tree can hold."- raise MethodFetchError(msg) from exc+ raise MethodFetchError(msg).with_error_code(CoreCode.METHOD_PACKAGE_INVALID) from excif not path.startswith(prefix):continueentries.append(_GitTreeEntry(mode=mode, object_sha=object_sha, path=path.removeprefix(prefix)))@@ -168,7 +170,7 @@ def _read_git_objects(*, package: FetchedMethodPackage, object_shas: list[str])header = output[cursor:line_end].decode("ascii").split(" ")if len(header) != 3 or header[0] != object_sha:msg = f"Could not read the object {object_sha} of method package '{package.full_address}' from its commit."- raise MethodFetchError(msg)+ raise MethodFetchError(msg).with_error_code(CoreCode.METHOD_FETCH_FAILED)size = int(header[2])start = line_end + 1contents[object_sha] = output[start : start + size]diff --git a/api/pipelex_api/method_tree_request.py b/api/pipelex_api/method_tree_request.pyindex 10be07410..11f8970cf 100644--- a/api/pipelex_api/method_tree_request.py+++ b/api/pipelex_api/method_tree_request.py@@ -49,6 +49,7 @@ from mthds.method_tree.vocabulary import TreeRefusalCodefrom mthds.package.exceptions import ManifestErrorfrom mthds.package.manifest.parser import parse_methods_tomlfrom mthds.package.manifest.schema import MethodsManifest+from mthds.protocol.problem.registry import CoreCodefrom pipelex.cli.installed_methods import PROVENANCE_FILENAMEfrom pipelex.config import is_pipe_func_sandbox_hostedfrom pipelex.libraries.written_trees import WRITTEN_METHOD_TREES, write_method_tree@@ -454,10 +455,10 @@ def manifest_of(*, tree: RequestTree, label: str) -> MethodsManifest | None:return parse_methods_toml(manifest_bytes.decode("utf-8"))except UnicodeDecodeError as exc:msg = f"The {MANIFEST_NAME} of {label} is not UTF-8 text."- raise MethodEntryError(msg) from exc+ raise MethodEntryError(msg).with_error_code(CoreCode.METHOD_PACKAGE_INVALID) from excexcept ManifestError as exc:msg = f"The {MANIFEST_NAME} of {label} is not a valid manifest: {exc.message}"- raise MethodEntryError(msg) from exc+ raise MethodEntryError(msg).with_error_code(CoreCode.METHOD_PACKAGE_INVALID) from excdef is_package_dir_name(name: str) -> bool:@@ -695,7 +696,7 @@ def select_tree_entry(*, tree: RequestTree, method_label: str) -> MethodEntry:content = tree.contents[tree_path].decode("utf-8")except UnicodeDecodeError as exc:msg = f"The bundle '{tree_path}' of the method {method_label} is not UTF-8 text."- raise MethodEntryError(msg) from exc+ raise MethodEntryError(msg).with_error_code(CoreCode.METHOD_SYNTAX) from excwith translate_to_validate_bundle_error():blueprint = MthdsParser.make_pipelex_bundle_blueprint(mthds_content=content, mthds_source=tree_path)candidates.append(EntryCandidate.of_blueprint(tree_path=tree_path, blueprint=blueprint))diff --git a/api/pipelex_api/openapi_responses.py b/api/pipelex_api/openapi_responses.pyindex f6e349aa3..577912429 100644--- a/api/pipelex_api/openapi_responses.py+++ b/api/pipelex_api/openapi_responses.py@@ -43,20 +43,37 @@ class ProblemDocument(BaseModel):Standard RFC 7807 members (`type`, `title`, `status`, `detail`, `instance`)plus the extension members pipelex's classification adds. Only `type`,- `title`, `status`, `detail`, and `error_type` are always present: the rest- ride along when the originating error populates them, so a consumer must- treat them as optional. `extra="allow"` mirrors RFC 7807's open-ended- extension-member rule.+ `title`, `status`, `detail`, and `error_type` are always present, and `code`+ on every error the runtime raises: the rest ride along when the originating+ error populates them, so a consumer must treat them as optional.+ `extra="allow"` mirrors RFC 7807's open-ended extension-member rule."""model_config = ConfigDict(extra="allow")- type: str = Field(..., description="Stable URI for the error class: `https://docs.pipelex.com/latest/errors/<kebab-class-name>/`.")- title: str = Field(..., description="Short, human-readable summary of the error class.")+ type: str = Field(+ ...,+ description=(+ "Stable URI of the error's documentation page: the page of its `code` (`https://mthds.ai/errors/<code>` for a core code, "+ "`https://docs.pipelex.com/errors/<code>` for a Pipelex code), or `https://docs.pipelex.com/latest/errors/<kebab-error-type>/` "+ "for an API-authored error, which carries no `code` yet."+ ),+ )+ title: str = Field(+ ..., description="Short, human-readable summary: the title of the error's `code`, or of its `error_type` when it carries none."+ )status: int = Field(..., description="HTTP status code, repeated in the body per RFC 7807.")detail: str = Field(..., description="Human-readable explanation of this specific failure. Redacted under `ERROR_DISCLOSURE=strict`.")instance: str | None = Field(default=None, description="Path of the request that failed.")request_id: str | None = Field(default=None, description="Correlation id, echoed in the `X-Request-ID` response header.")+ code: str | None = Field(+ default=None,+ description=(+ "Registry code of the error, what a client branches on: a core code of the MTHDS standard (e.g. `request.invalid`) "+ "or a Pipelex code (e.g. `pipelex.config.invalid`). Present on every error the runtime raises, under every "+ "`ERROR_DISCLOSURE` mode; absent on an API-authored error."+ ),+ )error_type: str = Field(..., description="Stable class name of the originating error (e.g. `ValidateBundleError`, `Unauthenticated`).")error_domain: str | None = Field(default=None,@@ -65,8 +82,7 @@ class ProblemDocument(BaseModel):retryable: bool | None = Field(default=None,description=(- "Whether retrying the same request can plausibly succeed. Always present on API-authored errors; "- "on pipelex errors only when the originating error classifies it."+ "Whether retrying the same request can plausibly succeed. Always present: on an error carrying a `code`, it is that code's retry verdict."),)error_category: str | None = Field(default=None, description="Finer classification, when the originating error provides one (inference errors).")diff --git a/api/pipelex_api/routes/pipelex/crate_ops.py b/api/pipelex_api/routes/pipelex/crate_ops.pyindex 8ff895a61..2af8ef464 100644--- a/api/pipelex_api/routes/pipelex/crate_ops.py+++ b/api/pipelex_api/routes/pipelex/crate_ops.py@@ -29,6 +29,7 @@ from typing import Literal, NamedTuple, NoReturn, TypeVarfrom fastapi import Requestfrom fastapi.responses import JSONResponse+from mthds.protocol.problem.registry import CoreCodefrom pipelex.base_exceptions import ErrorReport, ValidationErrorItemfrom pipelex.cogt.inference.error_classification import UserAction, UserActionKindfrom pipelex.interpreter_hub import clear_current_library, get_current_library_id_or_none, get_library_manager, get_required_entry_pipe@@ -199,6 +200,14 @@ class PipeSelectionMissKind(StrEnum):AMBIGUOUS = "ambiguous"+class SelectorOrigin(StrEnum):+ """Where a pipe selector came from, which is what its refusal must tell the caller, and who must act on it."""++ REQUEST = "request"+ MANIFEST = "manifest"+ CLOSURE = "closure"++class PipeSelectionMiss(NamedTuple):"""A link of the pipe selection chain that selected no pipe, with the refusal a selection answers."""@@ -208,18 +217,14 @@ class PipeSelectionMiss(NamedTuple):message: str"""The detail of the `422` a selection that depends on this link raises."""+ origin: SelectorOrigin | None+ """Where the selector that missed came from, which picks the refusal's code; `None` when there was no selector+ at all, because the request named no pipe and the closure declares no single `main_pipe`."""+user_action: UserAction | None = None"""The fix to name instead of the error class's own, when the class's is wrong for this miss."""-class _SelectorOrigin(StrEnum):- """Where a pipe selector came from, which is what its refusal must tell the caller."""-- REQUEST = "request"- MANIFEST = "manifest"- CLOSURE = "closure"--def resolve_requested_pipe(crate: LibraryCrate, *, pipe_ref: str | None, manifest_main_pipe: str | None) -> RequestedPipe:"""Select the pipe a per-pipe route targets, defaulting to the manifest's, then the closure's, `main_pipe`.@@ -234,7 +239,7 @@ def resolve_requested_pipe(crate: LibraryCrate, *, pipe_ref: str | None, manifesMust be called from the `project` of `project_resolved_method`, while its library is loaded + current."""if pipe_ref is not None:- selected = _select_entry_pipe(pipe_ref, origin=_SelectorOrigin.REQUEST)+ selected = _select_entry_pipe(pipe_ref, origin=SelectorOrigin.REQUEST)else:selected = select_default_pipe(crate, manifest_main_pipe=manifest_main_pipe)if isinstance(selected, PipeSelectionMiss):@@ -257,12 +262,49 @@ def _raise_selection_refusal(miss: PipeSelectionMiss) -> NoReturn:The no-entry-pipe miss is a not-found and the several-`main_pipe`s miss an ambiguity, the way thepipe-selector design classifies them. Neither is a typo in a pipe code, so each carries its own`user_action`, which replaces the class's code-typo advice for that one error.++ The code says who must act, which is where the selector came from. A selector the request named that+ misses is the caller's (`request.pipe_not_found`, `request.pipe_ambiguous`), and so is a request naming no+ pipe where the closure gives no single `main_pipe` to default to (`request.pipe_unspecified` when it+ declares none, `request.pipe_ambiguous` when it declares several). A `main_pipe` the method itself+ declares, in the fetched package's manifest or in the closure, that names no pipe of the closure is the+ method's (`method.pipe_unresolved`), whose author fixes the declaration."""match miss.kind:case PipeSelectionMissKind.NOT_FOUND:- raise EntryPipeNotFoundError(miss.message).as_caller_fault(user_action=miss.user_action)+ match miss.origin:+ case SelectorOrigin.REQUEST:+ raise (+ EntryPipeNotFoundError(miss.message)+ .with_error_code(CoreCode.REQUEST_PIPE_NOT_FOUND)+ .as_caller_fault(user_action=miss.user_action)+ )+ case SelectorOrigin.MANIFEST | SelectorOrigin.CLOSURE:+ raise (+ EntryPipeNotFoundError(miss.message)+ .with_error_code(CoreCode.METHOD_PIPE_UNRESOLVED)+ .as_caller_fault(user_action=miss.user_action)+ )+ case None:+ raise (+ EntryPipeNotFoundError(miss.message)+ .with_error_code(CoreCode.REQUEST_PIPE_UNSPECIFIED)+ .as_caller_fault(user_action=miss.user_action)+ )case PipeSelectionMissKind.AMBIGUOUS:- raise EntryPipeAmbiguousError(miss.message).as_caller_fault(user_action=miss.user_action)+ match miss.origin:+ case SelectorOrigin.REQUEST | None:+ raise (+ EntryPipeAmbiguousError(miss.message)+ .with_error_code(CoreCode.REQUEST_PIPE_AMBIGUOUS)+ .as_caller_fault(user_action=miss.user_action)+ )+ case SelectorOrigin.MANIFEST | SelectorOrigin.CLOSURE:+ raise (+ EntryPipeAmbiguousError(miss.message)+ .with_error_code(CoreCode.METHOD_PIPE_UNRESOLVED)+ .as_caller_fault(user_action=miss.user_action)+ )def select_default_pipe(crate: LibraryCrate, *, manifest_main_pipe: str | None) -> RequestedPipe | PipeSelectionMiss:@@ -287,12 +329,13 @@ def select_default_pipe(crate: LibraryCrate, *, manifest_main_pipe: str | None)Must be called from the `project` of `project_resolved_method`, while its library is loaded + current."""if manifest_main_pipe:- return _select_entry_pipe(manifest_main_pipe, origin=_SelectorOrigin.MANIFEST)+ return _select_entry_pipe(manifest_main_pipe, origin=SelectorOrigin.MANIFEST)candidates = [f"{domain_code}.{domain.main_pipe}" for domain_code, domain in crate.domains.items() if domain.main_pipe]if not candidates:return PipeSelectionMiss(kind=PipeSelectionMissKind.NOT_FOUND,message="No `pipe_ref` was given and the closure declares no `main_pipe` — name the pipe explicitly.",+ origin=None,user_action=UserAction(kind=UserActionKind.CHANGE_INPUT,detail="Send a `pipe_ref` naming the pipe to select, since the closure declares no `main_pipe` to default to.",@@ -303,15 +346,16 @@ def select_default_pipe(crate: LibraryCrate, *, manifest_main_pipe: str | None)return PipeSelectionMiss(kind=PipeSelectionMissKind.AMBIGUOUS,message=f"No `pipe_ref` was given and the closure declares several `main_pipe`s ({joined}) — name the pipe explicitly.",+ origin=None,user_action=UserAction(kind=UserActionKind.CHANGE_INPUT,detail="Send a `pipe_ref` naming one of the declared `main_pipe`s.",),)- return _select_entry_pipe(candidates[0], origin=_SelectorOrigin.CLOSURE)+ return _select_entry_pipe(candidates[0], origin=SelectorOrigin.CLOSURE)-def _select_entry_pipe(selector: str, *, origin: _SelectorOrigin) -> RequestedPipe | PipeSelectionMiss:+def _select_entry_pipe(selector: str, *, origin: SelectorOrigin) -> RequestedPipe | PipeSelectionMiss:"""Look one selector up through the engine's entry lookup, the way every selection chain link does.The returned `ref` is read back off the **resolved pipe**, never echoed from the selector: the@@ -325,14 +369,14 @@ def _select_entry_pipe(selector: str, *, origin: _SelectorOrigin) -> RequestedPimissing, which would contradict the candidates in the same sentence."""match origin:- case _SelectorOrigin.REQUEST:+ case SelectorOrigin.REQUEST:described = f"Pipe '{selector}'"scope = "the submitted closure"- case _SelectorOrigin.MANIFEST:+ case SelectorOrigin.MANIFEST:# The caller never spelled this selector — say where it came from, or the 422 names a pipe out of nowhere.described = f"Pipe '{selector}' (the `main_pipe` of the method's manifest)"scope = "the method's closure"- case _SelectorOrigin.CLOSURE:+ case SelectorOrigin.CLOSURE:described = f"Pipe '{selector}' (the closure's declared `main_pipe`)"scope = "the submitted closure"try:@@ -341,9 +385,10 @@ def _select_entry_pipe(selector: str, *, origin: _SelectorOrigin) -> RequestedPireturn PipeSelectionMiss(kind=PipeSelectionMissKind.AMBIGUOUS,message=f"{described} matches pipes in several domains of {scope}, so it selects none: {exc}",+ origin=origin,)except PipeNotFoundError as exc:- return PipeSelectionMiss(kind=PipeSelectionMissKind.NOT_FOUND, message=f"{described} not found in {scope}: {exc}")+ return PipeSelectionMiss(kind=PipeSelectionMissKind.NOT_FOUND, message=f"{described} not found in {scope}: {exc}", origin=origin)return RequestedPipe(ref=the_pipe.pipe_ref, pipe=the_pipe)diff --git a/api/pipelex_api/routes/pipelex/pipeline.py b/api/pipelex_api/routes/pipelex/pipeline.pyindex fe76d61a9..edbb3ce02 100644--- a/api/pipelex_api/routes/pipelex/pipeline.py+++ b/api/pipelex_api/routes/pipelex/pipeline.py@@ -9,9 +9,11 @@ from typing import TYPE_CHECKING, Annotated, Any, NamedTuple, castfrom fastapi import APIRouter, Depends, Requestfrom fastapi.responses import JSONResponse-from mthds.protocol.exceptions import PipelineRequestError+from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import PipelexUnexpectedErrorfrom pipelex.config import get_configfrom pipelex.core.pipes.pipe_output import PipeOutput+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.libraries.method_requirements import ensure_served_method_requirements_metfrom pipelex.pipe_run.delivery_assignment import DeliveryAssignment, StorageTarget, WebhookTargetfrom pipelex.pipe_run.pipe_run_protocol import PipeRunProtocol@@ -29,7 +31,7 @@ from pipelex.system.storage_scope import LOCAL_STORAGE_SCOPE, SINGLE_TENANT_USERfrom pydantic import ValidationErrorfrom typing_extensions import override-from pipelex_api.api_config import get_api_config, resolve_orchestration_mode+from pipelex_api.api_config import ApiConfig, get_api_config, is_callers_override, resolve_orchestration_modefrom pipelex_api.blob_store import RunnerBlobStorefrom pipelex_api.bundle_resources import decode_bundle_resourcesfrom pipelex_api.error_types import ErrorType@@ -295,6 +297,24 @@ class _OrchestratorPipeRun(PipeRunProtocol):return _pipe_output_from_run_output(run_output)+def _missing_orchestrator_error(*, mode: str, api_config: ApiConfig) -> MissingOrchestratorError:+ """The refusal of a run whose orchestration mode no installed plugin serves, coded by whose choice the mode was.++ A mode the caller named as a per-request override is the caller's to change (`runtime.unsupported`); the+ deployment's own default is the operator's, who installs its plugin (`pipelex.plugin.not_found`).+ """+ if is_callers_override(orchestration_mode=mode, config=api_config):+ return MissingOrchestratorError(mode=mode).with_error_code(CoreCode.RUNTIME_UNSUPPORTED)+ return MissingOrchestratorError(mode=mode).with_error_code(PipelexErrorCode.PLUGIN_NOT_FOUND)+++def _missing_bundle_validator_error(*, mode: str, api_config: ApiConfig) -> MissingBundleValidatorError:+ """The `/validate` twin of `_missing_orchestrator_error`, coded the same way by whose choice the mode was."""+ if is_callers_override(orchestration_mode=mode, config=api_config):+ return MissingBundleValidatorError(mode=mode).with_error_code(CoreCode.RUNTIME_UNSUPPORTED)+ return MissingBundleValidatorError(mode=mode).with_error_code(PipelexErrorCode.PLUGIN_NOT_FOUND)++class ApiRunner(PipelexMTHDSProtocol):"""API runner that dispatches `execute`, `start`, and `validate` through the per-call plugin registries.@@ -349,10 +369,11 @@ class ApiRunner(PipelexMTHDSProtocol):"""# Resolve the effective orchestration mode FIRST — a per-request override the deployment# policy forbids is refused (403) here, before any library load / run registration. Mirrors start().- orchestration_mode = resolve_orchestration_mode(requested_orchestration_mode, config=get_api_config())+ api_config = get_api_config()+ orchestration_mode = resolve_orchestration_mode(requested_orchestration_mode, config=api_config)orchestrator = get_orchestrator_registry().get_optional(mode=orchestration_mode)if orchestrator is None:- raise MissingOrchestratorError(mode=orchestration_mode)+ raise _missing_orchestrator_error(mode=orchestration_mode, api_config=api_config)await self._ensure_served_method_requirements_met()# Dispatch the run through the mode-selected orchestrator by injecting it as this runner's@@ -419,17 +440,20 @@ class ApiRunner(PipelexMTHDSProtocol):`api.toml` policy and a forbidden override is refused with a 403."""if extra:+ # Nothing on the wire reaches `extra`: the route parses the extras itself and passes them by name, so a+ # value here is a fault of the in-process code calling this runner, never the caller's.msg = f"ApiRunner defines no extension args beyond its named ones; got {sorted(extra)}."- raise PipelineRequestError(msg)+ raise PipelexUnexpectedError(msg)# Resolve the effective orchestration mode FIRST — a per-request override the deployment# policy forbids is refused (403) here. Then look up the orchestrator and check its async# capability: `/start` is fire-and-forget, so a blocking-only orchestrator (direct on the# agnostic base) is refused HONESTLY with a 400 instead of silently running blocking and# acking. Both gates run BEFORE pipeline_run_setup so a doomed request never loads a library.- orchestration_mode = resolve_orchestration_mode(requested_orchestration_mode, config=get_api_config())+ api_config = get_api_config()+ orchestration_mode = resolve_orchestration_mode(requested_orchestration_mode, config=api_config)orchestrator = get_orchestrator_registry().get_optional(mode=orchestration_mode)if orchestrator is None:- raise MissingOrchestratorError(mode=orchestration_mode)+ raise _missing_orchestrator_error(mode=orchestration_mode, api_config=api_config)if not orchestrator.supports_fire_and_forget:msg = (f"Orchestration mode '{orchestration_mode}' cannot honor fire-and-forget delivery: /start requires an "@@ -587,10 +611,11 @@ class ApiRunner(PipelexMTHDSProtocol):"""# Resolve the effective mode FIRST — a per-request override the deployment policy forbids# is refused (403) here, before any validator dispatch / library load. Mirrors start().- orchestration_mode = resolve_orchestration_mode(requested_orchestration_mode, config=get_api_config())+ api_config = get_api_config()+ orchestration_mode = resolve_orchestration_mode(requested_orchestration_mode, config=api_config)validator = get_bundle_validator_registry().get_optional(mode=orchestration_mode)if validator is None:- raise MissingBundleValidatorError(mode=orchestration_mode)+ raise _missing_bundle_validator_error(mode=orchestration_mode, api_config=api_config)library_dirs = [Path(library_dir) for library_dir in self.library_dirs] if self.library_dirs else None# The method's requirements.txt is judged here, on the runner, which holds the method's files and the package set# its PipeFunc steps run with, before any dispatch: a dispatched validator never reads these directories. A@@ -793,12 +818,12 @@ async def _parse_request(request: Request) -> _ParsedRunRequest:extras = _validate_extras(request_data)try:run_request = RunRequest.from_body(request_data)- except (PipelineRequestError, ValidationError) as exc:- # `from_body` rejects a body where neither `pipe_code` nor- # `mthds_contents` is supplied (PipelineRequestError) and a body whose- # fields fail Pydantic coercion (ValidationError) — both are caller- # mistakes, not server faults, so they map to a 422 rather than- # escaping to the generic-500 fallback.+ except ValidationError as exc:+ # A body whose fields fail Pydantic coercion is a caller mistake, not a server fault, so it maps to+ # a 422 rather than escaping to the generic-500 fallback. A body naming its run source wrongly, or+ # none, is refused by `from_body` as a `PipelexRequestError` instead, which needs no catch here: it+ # is a `PipelexError` carrying `request.invalid` or `request.unsupported`, and the global handler+ # answers it with its code.raise_validation_error(message=str(exc))return _ParsedRunRequest(run_request=run_request, extras=extras, body=body)diff --git a/api/pipelex_api/schemas/models.py b/api/pipelex_api/schemas/models.pyindex 7a8af935f..40838b6d5 100644--- a/api/pipelex_api/schemas/models.py+++ b/api/pipelex_api/schemas/models.py@@ -12,12 +12,12 @@ from ipaddress import ip_addressfrom typing import Annotated, Any, Selffrom urllib.parse import urlparse-from mthds.protocol.exceptions import PipelineRequestErrorfrom mthds.protocol.pipe_output import VariableMultiplicityfrom mthds.protocol.pipeline_inputs import PipelineInputsfrom pipelex.core.pipes.pipe_output import PipeOutputfrom pipelex.methods.fetching import MethodProvenancefrom pipelex.pipeline.pipeline_response import PipelexRunResultExecute, PipelexRunResultStart+from pipelex.pipeline.request_exceptions import PipelexRequestErrorfrom pipelex.reporting.usage_records import TokensUsageRecordfrom pipelex.system.run_extras import validate_run_extrasfrom pipelex.system.storage_scope import validate_read_scope, validate_storage_scope@@ -191,6 +191,9 @@ class RunRequest(BaseModel):@model_validator(mode="before")@classmethoddef validate_request(cls, values: dict[str, Any]) -> dict[str, Any]:+ # Each refusal here raises `PipelexRequestError`, which pydantic does not wrap, since it is no `ValueError`:+ # it reaches the route as itself, a `PipelexError` carrying `request.invalid`, and the global handler+ # answers it with that code, as the protocol's `PipelineRequestError` it also is.# The protocol requires at least one of pipe_code / mthds_contents. A method bundle# (`bundle_b64` / `files`) carries its own `.mthds` — so it satisfies the precondition# on its own (the pipe to run comes from the bundle's `main_pipe`). Extension args carry@@ -204,37 +207,37 @@ class RunRequest(BaseModel):# pick which pipe in the bundle to run — is still fine).if has_bundle and values.get("mthds_contents"):msg = "A method bundle (bundle_b64 / files) and inline mthds_contents are mutually exclusive; send one or the other."- raise PipelineRequestError(msg)+ raise PipelexRequestError(msg, field="mthds_contents")# `method_ref` is a complete run source of its own (the fetched package carries its# `.mthds` and its entry pipe): exactly one source per request, so it excludes both# inline contents and a bundle. `pipe_code` beside it is fine — it overrides the# manifest's `main_pipe` to pick which pipe in the fetched package to run.if has_method_ref and values.get("mthds_contents"):msg = "method_ref and inline mthds_contents are mutually exclusive; send one or the other."- raise PipelineRequestError(msg)+ raise PipelexRequestError(msg, field="method_ref")if has_method_ref and has_bundle:msg = "method_ref and a method bundle (bundle_b64 / files) are mutually exclusive; send one or the other."- raise PipelineRequestError(msg)+ raise PipelexRequestError(msg, field="method_ref")# `resources` are the files the submitted bundle's steps read, so they accompany a bundle the request# carries: inline contents or a method bundle. A fetched package's files are its own.if values.get("resources"):if has_method_ref:msg = "resources accompany inline mthds_contents or a method bundle; a method_ref's files are the package's own."- raise PipelineRequestError(msg)+ raise PipelexRequestError(msg, field="resources")if not values.get("mthds_contents") and not values.get("mthds_content") and not has_bundle:msg = "resources accompany the bundle whose steps read them: send them with mthds_contents or a method bundle."- raise PipelineRequestError(msg)+ raise PipelexRequestError(msg, field="resources")# `dependencies` are the packages the method sent in `files` calls, so they accompany that tree.if values.get("dependencies") is not None and values.get("files") is None:msg = "dependencies accompany the method's own files: send the method's tree in files, and its dependencies beside it."- raise PipelineRequestError(msg)+ raise PipelexRequestError(msg, field="dependencies")if values.get("pipe_code") is None and not values.get("mthds_contents") and not has_bundle and not has_method_ref:msg = ("pipe_code and mthds_contents cannot both be empty. Either: both are provided, or if there are no mthds_contents, ""then pipe_code must be provided and must reference a pipe already registered in the library. ""If mthds_contents is provided but no pipe_code, the first content must have a main_pipe property.")- raise PipelineRequestError(msg)+ raise PipelexRequestError(msg, field="pipe_code")return values@classmethod@@ -278,7 +281,7 @@ class RunRequest(BaseModel):"deployment — a hosted-only selector such as `method_id` must be sent to the hosted API, ""which resolves it into a run source before any runner sees the request.")- raise PipelineRequestError(msg)+ raise PipelexRequestError(msg, field=unhandled_keys[0], unsupported_reason="hosted_only_extension")@classmethoddef from_body(cls, request_body: dict[str, Any]) -> RunRequest:diff --git a/api/pipelex_api/security.py b/api/pipelex_api/security.pyindex c1097a037..cad975fe1 100644--- a/api/pipelex_api/security.py+++ b/api/pipelex_api/security.py@@ -23,6 +23,7 @@ from pydantic import BaseModel, Fieldfrom pipelex_api.error_types import ErrorTypefrom pipelex_api.errors import raise_bad_request, raise_internal_server_error, raise_unauthenticated+from pipelex_api.exceptions import InvalidAuthModeErrorAUTH_MODE_ENV_VAR = "AUTH_MODE"@@ -145,10 +146,6 @@ def _set_request_user(request: Request, user_id: str) -> None:request.state.user = RequestUser(user_id=user_id)-class InvalidAuthModeError(ValueError):- """Raised at startup when `AUTH_MODE` holds a value that is not an `AuthMode` member."""--def get_auth_mode() -> AuthMode:"""Resolve `AUTH_MODE` to an `AuthMode`.diff --git a/api/tests/unit/test_api_config.py b/api/tests/unit/test_api_config.pyindex 83a8ed27a..db98ad32b 100644--- a/api/tests/unit/test_api_config.py+++ b/api/tests/unit/test_api_config.py@@ -12,9 +12,10 @@ import pytestfrom fastapi import FastAPIfrom fastapi.testclient import TestClient-from pipelex_api.api_config import ApiBootConfigError, ApiConfig, get_api_config, resolve_boot_orchestrator, resolve_orchestration_mode+from pipelex_api.api_config import ApiConfig, get_api_config, resolve_boot_orchestrator, resolve_orchestration_modefrom pipelex_api.errors import ApiErrorfrom pipelex_api.exception_handlers import register_exception_handlers+from pipelex_api.exceptions import ApiBootConfigErrorfrom pipelex_api.middleware import RequestIdMiddlewarefrom pipelex_api.routes.pipelex.pipeline import router as pipeline_routerfrom tests.unit._constants import VALID_MTHDSdiff --git a/api/tests/unit/test_bundle_resources_routes.py b/api/tests/unit/test_bundle_resources_routes.pyindex eb8610bc7..429f6236c 100644--- a/api/tests/unit/test_bundle_resources_routes.py+++ b/api/tests/unit/test_bundle_resources_routes.py@@ -296,8 +296,11 @@ class TestBundleResourcesRoutes:body.pop("mthds_contents", None)body.pop("files", None)body["method_ref"] = f"{STUB_METHOD_ADDRESS}@v0.1.0"+ # The run route refuses it in its request model, as the runtime's `request.invalid`; the crate+ # routes refuse it themselves, with the API-authored `ValidationError`.+ expected_error_type = "PipelexRequestError" if route == "/v1/execute" else "ValidationError"- detail = _assert_problem(_build_client().post(route, json=body), status=422, error_type="ValidationError")+ detail = _assert_problem(_build_client().post(route, json=body), status=422, error_type=expected_error_type)assert "method_ref" in detail@@ -338,7 +341,8 @@ class TestBundleResourcesRoutes:def test_resources_with_no_bundle_to_read_them_are_refused(self) -> None:response = _build_client().post("/v1/execute", json={"pipe_code": "print_invoice", "resources": {_TEMPLATE_PATH: _b64(_TEMPLATE_BYTES)}})- assert "resources accompany the bundle" in _assert_problem(response, status=422, error_type="ValidationError")+ assert "resources accompany the bundle" in _assert_problem(response, status=422, error_type="PipelexRequestError")+ assert response.json()["code"] == "request.invalid"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."""diff --git a/api/tests/unit/test_disclosure.py b/api/tests/unit/test_disclosure.pyindex df85388d8..cdc79a492 100644--- a/api/tests/unit/test_disclosure.py+++ b/api/tests/unit/test_disclosure.py@@ -3,7 +3,8 @@import pytestfrom pipelex.base_exceptions import DisclosureMode-from pipelex_api.disclosure import ERROR_DISCLOSURE_ENV_VAR, InvalidErrorDisclosureError, resolve_disclosure_mode+from pipelex_api.disclosure import ERROR_DISCLOSURE_ENV_VAR, resolve_disclosure_mode+from pipelex_api.exceptions import InvalidErrorDisclosureErrorclass TestDisclosure:diff --git a/api/tests/unit/test_error_code_gate.py b/api/tests/unit/test_error_code_gate.pynew file mode 100644index 000000000..fc079e383--- /dev/null+++ b/api/tests/unit/test_error_code_gate.py@@ -0,0 +1,124 @@+"""The runner's error-code gate: every `PipelexError` subclass the api member defines declares its registry code.++The library's gate, `tests/unit/pipelex/errors/test_error_code_gate.py` at the repository root, discovers the+classes of the `pipelex` package and reads the raise sites of both the package and the runner, but it never+imports `pipelex_api`, so the runner's own classes escape it. This test imports every module of the runner,+collects the `PipelexError` subclasses it defines, and holds them to the same rules: a code in the class's own+body, nothing the code decides declared beside it, the class in an error module, and every raise site of one of+them choosing only a code its class declares and never constructing an abstract base.+"""++import importlib+import pkgutil+from pathlib import Path++from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import PipelexError+from pipelex.errors.error_code_declaration import AbstractError, declared_error_codes, describe_error_code_declaration+from pipelex.errors.error_code_sites import iter_chosen_code_sites, iter_raised_class_sites+from pipelex.errors.error_codes import ErrorCode, error_code_spec+from pipelex.errors.registry.pipelex_codes import PipelexErrorCode++import pipelex_api++_PACKAGE_NAME = pipelex_api.__name__+_PACKAGE_ROOT = Path(pipelex_api.__file__).resolve().parent++# What a code decides, which a class no longer declares: `ErrorReport` reads all four from the code.+_ATTRIBUTES_THE_CODE_DECIDES: tuple[str, ...] = ("error_domain", "retryable", "_declared_title", "_declared_type_uri")+++def _runner_error_classes() -> dict[str, type[PipelexError]]:+ """Every `PipelexError` subclass the runner defines, by name, after importing every module of the runner."""+ for module_info in pkgutil.walk_packages(pipelex_api.__path__, prefix=f"{_PACKAGE_NAME}."):+ importlib.import_module(module_info.name)+ classes: dict[str, type[PipelexError]] = {}+ stack: list[type[PipelexError]] = [PipelexError]+ seen: set[type[PipelexError]] = set()+ while stack:+ cls = stack.pop()+ if cls in seen:+ continue+ seen.add(cls)+ if cls.__module__ == _PACKAGE_NAME or cls.__module__.startswith(f"{_PACKAGE_NAME}."):+ classes[cls.__name__] = cls+ stack.extend(cls.__subclasses__())+ return classes+++def _source_files() -> list[Path]:+ return [path for path in sorted(_PACKAGE_ROOT.rglob("*.py")) if "__pycache__" not in path.parts]+++def _relative(path: Path) -> str:+ return str(path.relative_to(_PACKAGE_ROOT.parent))+++class TestRunnerErrorCodeGate:+ def test_the_gate_reads_a_non_empty_set(self) -> None:+ """Anti-vacuity: the discovery found the runner's boot errors and its source files."""+ classes = _runner_error_classes()+ assert {"ApiBootConfigError", "InvalidAuthModeError", "InvalidErrorDisclosureError"} <= set(classes)+ assert _source_files()++ def test_every_runner_error_class_declares_its_code(self) -> None:+ missing = sorted(f"{cls.__module__}.{cls.__qualname__}" for cls in _runner_error_classes().values() if "error_code" not in cls.__dict__)+ assert not missing, (+ "These PipelexError subclasses of the runner declare no `error_code` in their own class body; declare the "+ "registry code, an ErrorCodeSet, InheritsCause or ABSTRACT_ERROR (pipelex/errors/error_code_declaration.py):\n"+ + "\n".join(f" - {name}" for name in missing)+ )++ def test_every_declared_code_is_registered(self) -> None:+ for cls in _runner_error_classes().values():+ for code in declared_error_codes(cls.error_code):+ assert isinstance(code, (CoreCode, PipelexErrorCode)), f"{cls.__name__} declares {code!r}, which is no registered code"+ assert error_code_spec(code).code == code++ def test_no_runner_error_class_declares_what_its_code_decides(self) -> None:+ offenders = sorted(+ f"{cls.__module__}.{cls.__qualname__}.{attribute}"+ for cls in _runner_error_classes().values()+ for attribute in _ATTRIBUTES_THE_CODE_DECIDES+ if attribute in cls.__dict__+ )+ assert not offenders, "These classes declare what their code decides; remove the attribute and choose the code instead:\n" + "\n".join(+ f" - {offender}" for offender in offenders+ )++ def test_every_runner_error_class_lives_in_an_error_module(self) -> None:+ offenders = sorted(+ f" - {cls.__module__}.{cls.__qualname__}"+ for cls in _runner_error_classes().values()+ if not (cls.__module__.rpartition(".")[2] == "exceptions" or cls.__module__.endswith("_exceptions"))+ )+ assert not offenders, "These error classes live outside an `exceptions.py` or `<topic>_exceptions.py` module:\n" + "\n".join(offenders)++ def test_no_abstract_runner_class_is_raised_directly(self) -> None:+ abstract_names = {name for name, cls in _runner_error_classes().items() if isinstance(cls.__dict__.get("error_code"), AbstractError)}+ offenders = [+ f" - {_relative(site.path)}:{site.line} raises {site.class_name}"+ for path in _source_files()+ for site in iter_raised_class_sites(path=path, source=path.read_text(encoding="utf-8"))+ if site.class_name in abstract_names+ ]+ assert not offenders, "These raise sites construct an abstract base; raise the subclass that names the fault:\n" + "\n".join(offenders)++ def test_every_chosen_code_is_one_its_runner_class_declares(self) -> None:+ classes = _runner_error_classes()+ offenders: list[str] = []+ for path in _source_files():+ for site in iter_chosen_code_sites(path=path, source=path.read_text(encoding="utf-8")):+ cls = classes.get(site.class_name)+ if cls is None:+ continue+ enum_class = CoreCode if site.enum_name == "CoreCode" else PipelexErrorCode+ chosen: ErrorCode | None = getattr(enum_class, site.member_name, None)+ where = f"{_relative(site.path)}:{site.line}"+ if chosen is None:+ offenders.append(f" - {where}: {site.enum_name}.{site.member_name} is no registered code")+ elif chosen not in declared_error_codes(cls.error_code):+ offenders.append(+ f" - {where}: {site.class_name} chooses {chosen}, but declares {describe_error_code_declaration(cls.error_code)}"+ )+ assert not offenders, "These raise sites choose a code their class does not declare:\n" + "\n".join(offenders)diff --git a/api/tests/unit/test_error_log_records.py b/api/tests/unit/test_error_log_records.pyindex c7f9b50a1..53cb87071 100644--- a/api/tests/unit/test_error_log_records.py+++ b/api/tests/unit/test_error_log_records.py@@ -131,10 +131,9 @@ class TestErrorLogRecords:assert payload["http.response.status_code"] == 500assert payload["error.type"] == "PipelexConfigError"assert payload["error_domain"] == "config"- # `retryable` is absent rather than false: pipelex populates it only on a classifiable- # failure, and a field with no value is dropped rather than written as a null a query- # filtering on presence would read as an answer.- assert "retryable" not in payload+ # `retryable` is the verdict of the error's code, which every error carries, so it is always+ # written: `pipelex.config.invalid` is no fault a repeat can cure.+ assert payload["retryable"] is False# `time` and `logger` come from the sink itself; an operator-actionable failure carries# its traceback under `exception` rather than spilling it across the line.assert payload["time"].endswith("Z")diff --git a/api/tests/unit/test_exception_handlers.py b/api/tests/unit/test_exception_handlers.pyindex acc21fb2b..2bacdb8ad 100644--- a/api/tests/unit/test_exception_handlers.py+++ b/api/tests/unit/test_exception_handlers.py@@ -16,10 +16,10 @@ from typing import Any, castimport pytestfrom fastapi import APIRouter, FastAPI, Requestfrom fastapi.testclient import TestClient+from mthds.protocol.problem.registry import CoreCodefrom pipelex.base_exceptions import (INTERNAL_ERROR_PLACEHOLDER,DisclosureMode,- ErrorDomain,ErrorReport,PipelexConfigError,PipelexError,@@ -28,6 +28,8 @@ from pipelex.cogt.exceptions import InferenceErrorCategory, LLMCompletionErrorfrom pipelex.cogt.inference.error_classification import ProviderErrorMetadata, UserAction, UserActionKindfrom pipelex.cogt.inference.provider_name import ProviderNamefrom pipelex.config import get_config+from pipelex.errors.error_codes import ErrorCode, error_code_spec+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.methods.exceptions import MethodPackageSymlinkErrorfrom pipelex.pipe_run.exceptions import AsyncExecutionNotEnabledErrorfrom pipelex.pipeline.exceptions import PipelineManagerAlreadyExistsError@@ -65,35 +67,43 @@ def _emitted_fields(log_spy: Any, *, as_error: bool) -> dict[str, Any]:return cast("dict[str, Any]", fields)+def _coded_report(*, code: ErrorCode, error_type: str, message: str, classification: dict[str, Any]) -> ErrorReport:+ """A report built the way pipelex builds one, for `code`, with the classification an inference failure adds."""+ return ErrorReport.make_for_code(code=code, error_type=error_type, message=message).model_copy(update=classification)++class _SimulatedLLMError(PipelexError):"""A `PipelexError` whose report mimics a provider rate-limit (429) failure."""+ error_code = CoreCode.PROVIDER_RATE_LIMITED+@overridedef to_error_report(self) -> ErrorReport:- return ErrorReport(+ return _coded_report(+ code=CoreCode.PROVIDER_RATE_LIMITED,error_type="LLMCompletionError",message="OpenAI returned 429 (rate_limit_exceeded)",- title="LLM completion error",- type_uri="https://docs.pipelex.com/latest/errors/llm-completion-error/",- error_category="transient",- error_domain="runtime",- retryable=True,- user_action=UserAction(kind=UserActionKind.WAIT_AND_RETRY, detail="Retry after 12s."),- model="gpt-4o-mini",- provider="openai",- provider_metadata=ProviderErrorMetadata(- provider=ProviderName.OPENAI,- sdk_exception_type="RateLimitError",- status_code=429,- retry_after_seconds=12.0,- request_id="req_provider_abc",- ),+ classification={+ "error_category": "transient",+ "user_action": UserAction(kind=UserActionKind.WAIT_AND_RETRY, detail="Retry after 12s."),+ "model": "gpt-4o-mini",+ "provider": "openai",+ "provider_metadata": ProviderErrorMetadata(+ provider=ProviderName.OPENAI,+ sdk_exception_type="RateLimitError",+ status_code=429,+ retry_after_seconds=12.0,+ request_id="req_provider_abc",+ ),+ },)class _CorruptReportError(PipelexError):"""A `PipelexError` whose `to_error_report` itself fails — the handler-of-handlers case."""+ error_code = CoreCode.RUNTIME_UNEXPECTED+@overridedef to_error_report(self) -> ErrorReport:msg = "to_error_report is deliberately broken"@@ -101,13 +111,13 @@ class _CorruptReportError(PipelexError):class _CallerFacingInputError(PipelexError):- """An `INPUT`-domain error whose message is genuine caller-facing copy.+ """A `method.syntax` error, which the caller fixes, whose message is genuine caller-facing copy.`_authors_caller_facing_message` makes STRICT disclosure keep the messageverbatim — the projection pipelex applies to a `.mthds` syntax error."""- error_domain = ErrorDomain.INPUT+ error_code = CoreCode.METHOD_SYNTAX_authors_caller_facing_message = True@@ -128,21 +138,20 @@ class _SyntheticOrchestratorError(PipelexError):transport exception."""+ error_code = CoreCode.RUN_FAILED+def _synthetic_transport_to_report(exc: Exception) -> ErrorReport:"""The mapper an orchestrator plugin would contribute: classify the bare transport fault.- Mirrors the classification the (now plugin-owned) Temporal transport mapper produces — a- retryable, `RUNTIME`-domain `transient` failure.+ Mirrors the classification the (now plugin-owned) Temporal transport mapper produces for an+ unreachable cluster — `runtime.unavailable`, a retryable `transient` failure."""- return ErrorReport(+ return _coded_report(+ code=CoreCode.RUNTIME_UNAVAILABLE,error_type="SyntheticTransportError",message=str(exc),- title="Synthetic transport error",- type_uri="https://docs.pipelex.com/latest/errors/synthetic-transport-error/",- error_category="transient",- error_domain=ErrorDomain.RUNTIME,- retryable=True,+ classification={"error_category": "transient"},)@@ -164,20 +173,19 @@ def _synthetic_http_error_mappers() -> dict[type[Exception], HttpErrorMapperFn]:def _report_with_retry(*, status_code: int, retry_after_seconds: float | None) -> ErrorReport:"""Build a provider-error report carrying a `retry_after_seconds` hint."""- return ErrorReport(+ return _coded_report(+ code=CoreCode.PROVIDER_RATE_LIMITED if status_code == 429 else CoreCode.PROVIDER_UNAVAILABLE,error_type="LLMCompletionError",message="provider error",- title="LLM completion error",- type_uri="https://docs.pipelex.com/latest/errors/llm-completion-error/",- error_category="transient",- error_domain="runtime",- retryable=True,- provider_metadata=ProviderErrorMetadata(- provider=ProviderName.OPENAI,- sdk_exception_type="RateLimitError",- status_code=status_code,- retry_after_seconds=retry_after_seconds,- ),+ classification={+ "error_category": "transient",+ "provider_metadata": ProviderErrorMetadata(+ provider=ProviderName.OPENAI,+ sdk_exception_type="RateLimitError",+ status_code=status_code,+ retry_after_seconds=retry_after_seconds,+ ),+ },)@@ -196,6 +204,8 @@ _RETRY_REPORTS: dict[str, ErrorReport] = {class _CraftedRetryError(PipelexError):"""A `PipelexError` whose report is selected by key — exercises `_retry_after_header`."""+ error_code = CoreCode.PROVIDER_RATE_LIMITED+def __init__(self, report_key: str) -> None:super().__init__("crafted retry-after scenario")self._report = _RETRY_REPORTS[report_key]@@ -471,8 +481,10 @@ class TestExceptionHandlers:assert response.status_code == 500assert response.headers["content-type"] == PROBLEM_JSON_MEDIA_TYPEbody = response.json()- assert body["type"].endswith("/pipelex-config-error/")- assert body["title"] == "Pipelex config"+ config_invalid = error_code_spec(PipelexErrorCode.CONFIG_INVALID)+ assert body["code"] == "pipelex.config.invalid"+ assert body["type"] == config_invalid.type_uri+ assert body["title"] == config_invalid.titleassert body["status"] == 500assert body["detail"] == "the gateway config is missing"assert body["error_type"] == "PipelexConfigError"@@ -505,12 +517,16 @@ class TestExceptionHandlers:input_response = client.get("/input-error")assert input_response.status_code == 422assert input_response.json()["detail"] == "your .mthds file has a syntax error on line 4"+ # STRICT keeps the code, whatever it redacts: it is what a caller branches on.+ assert config_response.json()["code"] == "pipelex.config.invalid"+ assert input_response.json()["code"] == "method.syntax"def test_provider_rate_limit_emits_retry_after(self):response = _build_client().get("/llm-error")assert response.status_code == 429assert response.headers["Retry-After"] == "12"body = response.json()+ assert body["code"] == "provider.rate_limited"assert body["error_type"] == "LLMCompletionError"assert body["retryable"] is Trueassert body["provider_metadata"]["status_code"] == 429@@ -583,12 +599,14 @@ class TestExceptionHandlers:pipelex_response = client.get("/orchestrator-pipelex-error")assert pipelex_response.status_code == 500assert pipelex_response.json()["error_type"] == "_SyntheticOrchestratorError"+ assert pipelex_response.json()["code"] == "run.failed"# A bare transport error — routed to the plugin's mapper-backed handler, which renders the# transport-transient classification the mapper produced.transport_response = client.get("/synthetic-transport-error")assert transport_response.status_code == 500transport_body = transport_response.json()+ assert transport_body["code"] == "runtime.unavailable"assert transport_body["error_type"] == "SyntheticTransportError"assert transport_body["error_category"] == "transient"assert transport_body["retryable"] is True@@ -941,8 +959,9 @@ class TestExceptionHandlers:assert crafted_detail not in message, f"caller input reached the message: {message!r}"def test_async_execution_not_enabled_maps_to_501(self):- # The pipelex-side ``AsyncExecutionNotEnabledError`` reports as- # ``CONFIG``-domain (-> 500 under the default mapping), but the+ # The pipelex-side ``AsyncExecutionNotEnabledError`` carries+ # ``runtime.unsupported``, an operator code that reads as the ``CONFIG``+ # domain (-> 500 under the default mapping), but the# API layer overrides it to 501 Not Implemented. 501 is more precise# for "this server does not provide async execution": it tells clients# the failure is permanent under the current deployment rather than a@@ -955,11 +974,13 @@ class TestExceptionHandlers:# the override path only bumped the header status and left the body at# 500, RFC 7807-aware clients would see a contradictory document.assert body["status"] == 501- assert body["title"] == "Async execution not enabled"+ runtime_unsupported = error_code_spec(CoreCode.RUNTIME_UNSUPPORTED)+ assert body["code"] == "runtime.unsupported"+ assert body["title"] == runtime_unsupported.titleassert body["error_type"] == "AsyncExecutionNotEnabledError"assert body["error_domain"] == "config"assert body["instance"] == "/async-execution-not-enabled"- assert body["type"].endswith("/async-execution-not-enabled-error/")+ assert body["type"] == runtime_unsupported.type_uriassert body["request_id"] == response.headers[REQUEST_ID_HEADER]def test_async_execution_not_enabled_logs_post_override_status(self, mocker: MockerFixture):@@ -978,8 +999,8 @@ class TestExceptionHandlers:assert fields["error_domain"] == "config"def test_pipeline_run_id_conflict_maps_to_409(self):- # ``PipelineManagerAlreadyExistsError`` carries no ``error_domain``- # (-> 500 under the default mapping), but a duplicate ``pipeline_run_id``+ # ``PipelineManagerAlreadyExistsError`` carries ``pipelex.run.already_exists``,+ # whose domain alone does not give 409, and a duplicate ``pipeline_run_id``# is a client-visible conflict, not a server fault: the API overrides it# to 409 Conflict so callers can tell "this id is currently in use"# (resubmit after the in-flight run finishes, or pick a fresh id) apart@@ -991,23 +1012,25 @@ class TestExceptionHandlers:# The body's ``status`` member must agree with the HTTP status (same# RFC 7807 agreement contract as the 501 override above).assert body["status"] == 409+ run_already_exists = error_code_spec(PipelexErrorCode.RUN_ALREADY_EXISTS)+ assert body["code"] == "pipelex.run.already_exists"assert body["error_type"] == "PipelineManagerAlreadyExistsError"- assert body["title"] == "Pipeline manager already exists"+ assert body["title"] == run_already_exists.titleassert body["instance"] == "/pipeline-run-id-conflict"- assert body["type"].endswith("/pipeline-manager-already-exists-error/")+ assert body["type"] == run_already_exists.type_uriassert body["request_id"] == response.headers[REQUEST_ID_HEADER]def test_method_package_symlink_maps_to_422(self, mocker: MockerFixture):- # ``MethodPackageSymlinkError`` carries no ``error_domain`` (-> 500 under the- # default mapping), but a symlink in a fetched package is a rule about the- # fetched content that its author fixes, not a server fault: the API overrides- # it to 422, like the fetched-package ceilings, and logs it at warning.+ # ``MethodPackageSymlinkError`` carries ``method.package_invalid``: a symlink in a+ # fetched package is a rule about the fetched content that its author fixes, not a+ # server fault, so it answers 422, like the fetched-package ceilings, and logs at warning.log_spy = mocker.patch("pipelex_api.exception_handlers.log")response = _build_client().get("/method-package-symlink")assert response.status_code == 422assert response.headers["content-type"] == PROBLEM_JSON_MEDIA_TYPEbody = response.json()assert body["status"] == 422+ assert body["code"] == "method.package_invalid"assert body["error_type"] == "MethodPackageSymlinkError"assert "contains a symlink ('vendored')" in body["detail"]assert body["request_id"] == response.headers[REQUEST_ID_HEADER]diff --git a/api/tests/unit/test_execute_dispatch.py b/api/tests/unit/test_execute_dispatch.pyindex 071afaa20..03a02ac6f 100644--- a/api/tests/unit/test_execute_dispatch.py+++ b/api/tests/unit/test_execute_dispatch.py@@ -389,3 +389,21 @@ class TestExecuteDispatch:)# The packaged default is `direct`; the empty registry holds no orchestrator for it.assert exc_info.value.mode == "direct"+ # The deployment's own default has no orchestrator: the operator installs its plugin.+ assert exc_info.value.to_error_report().code == "pipelex.plugin.not_found"++ @pytest.mark.asyncio+ async def test_missing_orchestrator_for_the_callers_override_is_unsupported(self, mocker: MockerFixture) -> None:+ """An override the caller named and the policy allows, which no installed plugin serves, is the caller's to change."""+ _force_config(mocker, mode="direct", allow_override=True)+ mocker.patch(f"{_PIPELINE_NS}.get_orchestrator_registry", return_value=OrchestratorRegistry({}))++ with pytest.raises(MissingOrchestratorError) as exc_info:+ await ApiRunner().execute(+ pipe_code="echo",+ mthds_contents=[VALID_MTHDS],+ inputs={"text": "hello"},+ requested_orchestration_mode="temporal",+ )+ assert exc_info.value.mode == "temporal"+ assert exc_info.value.to_error_report().code == "runtime.unsupported"diff --git a/api/tests/unit/test_method_cache.py b/api/tests/unit/test_method_cache.pyindex 75d2dd3fb..784aee2cb 100644--- a/api/tests/unit/test_method_cache.py+++ b/api/tests/unit/test_method_cache.py@@ -65,8 +65,9 @@ class TestMethodCloneCache:def test_branch_names_are_refused_as_tags(self, origin: tuple[str, Path]):clone_url, _ = originbranch_ref = parse_method_ref("github.com/pipelex/methods/documents@main")- with pytest.raises(MethodFetchError, match="does not name a git tag"):+ with pytest.raises(MethodFetchError, match="does not name a git tag") as exc_info:resolve_remote_commit_sha(ref=branch_ref, clone_url=clone_url)+ assert exc_info.value.to_error_report().code == "method.not_found"def test_a_cached_sha_is_never_recloned(self, origin: tuple[str, Path], tmp_path: Path, mocker: MockerFixture):clone_url, repo = origin@@ -183,5 +184,8 @@ class TestMethodCloneCache:assert third.clone_dir.is_dir()def test_nonexistent_repository_is_a_fetch_error(self, tmp_path: Path):- with pytest.raises(MethodFetchError, match="could not reach the repository"):+ with pytest.raises(MethodFetchError, match="could not reach the repository") as exc_info:resolve_remote_commit_sha(ref=_BARE_REF, clone_url=f"file://{tmp_path}/no-such-repo")+ # One exit status of `git ls-remote` covers a missing repository and an unreachable host, so the+ # code is the transient one until the fetch tells them apart.+ assert exc_info.value.to_error_report().code == "method.fetch_failed"diff --git a/api/tests/unit/test_method_ref_run.py b/api/tests/unit/test_method_ref_run.pyindex 2e17fade7..6cd484ac2 100644--- a/api/tests/unit/test_method_ref_run.py+++ b/api/tests/unit/test_method_ref_run.py@@ -219,6 +219,7 @@ class TestMethodRefRun:assert response.status_code == 422, response.textassert response.headers["content-type"] == "application/problem+json"assert response.json()["error_type"] == "MethodFetchError"+ assert response.json()["code"] == "method.fetch_failed"def test_python_package_forbidden_when_not_sandbox_hosted(self, mocker: MockerFixture, install_method_package: Callable[..., Path]):install_method_package(files={"documents.mthds": VALID_MTHDS, "funcs/pipe_func.py": _PIPE_FUNC_PY})diff --git a/api/tests/unit/test_method_tree_runs.py b/api/tests/unit/test_method_tree_runs.pyindex 8396b5c6f..2f4d6cb24 100644--- a/api/tests/unit/test_method_tree_runs.py+++ b/api/tests/unit/test_method_tree_runs.py@@ -268,6 +268,7 @@ class TestMethodTreeRuns:assert [(item["source"], item["line"], item["column"]) for item in run.json()["validation_errors"]] == [("bad.mthds", 1, 1)]assert run_from_the_entry.status_code == 422, run_from_the_entry.textassert run_from_the_entry.json()["error_type"] == "MethodEntryError"+ assert run_from_the_entry.json()["code"] == "method.syntax"assert "'bad.mthds'" in run_from_the_entry.json()["detail"]assert validated.status_code == 200, validated.textverdict = validated.json()diff --git a/api/tests/unit/test_pipe_io_route.py b/api/tests/unit/test_pipe_io_route.pyindex 7b8359c5b..d18175452 100644--- a/api/tests/unit/test_pipe_io_route.py+++ b/api/tests/unit/test_pipe_io_route.py@@ -224,7 +224,10 @@ class TestPipeIoRoute:assert body["pipe_ref"] is Noneassert body["default_pipe_ref"] is None_assert_keys(body, {"other.shout"})- detail = _assert_input_422(client.post(PIPE_IO_PATH, json={"method_ref": STUB_METHOD_REF}), error_type=PIPE_NOT_FOUND_ERROR)+ response = client.post(PIPE_IO_PATH, json={"method_ref": STUB_METHOD_REF})+ detail = _assert_input_422(response, error_type=PIPE_NOT_FOUND_ERROR)+ # The author's manifest names a pipe the method lacks: the method's fault, not the caller's selector.+ assert response.json()["code"] == "method.pipe_unresolved"assert "manifest" in detailassert "not found" in detail@@ -233,7 +236,9 @@ class TestPipeIoRoute:# ambiguous, naming both candidates, and a whole-method request states no default.install_method_package(files={"smoke.mthds": VALID_MTHDS, "twin.mthds": COLLIDING_ECHO_LIST_MTHDS})client = _build_client()- detail = _assert_input_422(client.post(PIPE_IO_PATH, json={"method_ref": STUB_METHOD_REF}), error_type=PIPE_AMBIGUOUS_ERROR)+ response = client.post(PIPE_IO_PATH, json={"method_ref": STUB_METHOD_REF})+ detail = _assert_input_422(response, error_type=PIPE_AMBIGUOUS_ERROR)+ assert response.json()["code"] == "method.pipe_unresolved"assert "manifest" in detailassert "several domains" in detailassert "smoke.echo" in detail@@ -247,7 +252,9 @@ class TestPipeIoRoute:def test_an_ambiguous_pipe_ref_says_ambiguous(self, all_pipes: bool):client = _build_client()payload = {"files": _files(VALID_MTHDS, COLLIDING_ECHO_LIST_MTHDS), "pipe_ref": "echo", "all_pipes": all_pipes}- detail = _assert_input_422(client.post(PIPE_IO_PATH, json=payload), error_type=PIPE_AMBIGUOUS_ERROR)+ response = client.post(PIPE_IO_PATH, json=payload)+ detail = _assert_input_422(response, error_type=PIPE_AMBIGUOUS_ERROR)+ assert response.json()["code"] == "request.pipe_ambiguous"assert "Pipe 'echo'" in detailassert "several domains" in detailassert "smoke.echo" in detail@@ -340,15 +347,20 @@ class TestPipeIoRoute:assert field_name not in body, f"the invalid arm never carries `{field_name}`"@pytest.mark.parametrize(- ("contents", "request_fields", "error_type", "detail_fragment", "fix_fragment"),+ ("contents", "request_fields", "refusal", "detail_fragment", "fix_fragment"),[pytest.param(- (VALID_MTHDS,), {"pipe_ref": "smoke.not_a_pipe"}, PIPE_NOT_FOUND_ERROR, "not found", "Check the pipe code", id="unknown-ref"+ (VALID_MTHDS,),+ {"pipe_ref": "smoke.not_a_pipe"},+ (PIPE_NOT_FOUND_ERROR, "request.pipe_not_found"),+ "not found",+ "Check the pipe code",+ id="unknown-ref",),pytest.param((VALID_MTHDS,),{"pipe_ref": "smoke.not_a_pipe", "all_pipes": True},- PIPE_NOT_FOUND_ERROR,+ (PIPE_NOT_FOUND_ERROR, "request.pipe_not_found"),"not found","Check the pipe code",id="unknown-ref-under-all-pipes",@@ -356,7 +368,7 @@ class TestPipeIoRoute:pytest.param((NO_MAIN_PIPE_MTHDS,),{},- PIPE_NOT_FOUND_ERROR,+ (PIPE_NOT_FOUND_ERROR, "request.pipe_unspecified"),"declares no `main_pipe`","Send a `pipe_ref` naming the pipe to select",id="no-entry-pipe",@@ -364,7 +376,7 @@ class TestPipeIoRoute:pytest.param((VALID_MTHDS, SECOND_MAIN_PIPE_MTHDS),{},- PIPE_AMBIGUOUS_ERROR,+ (PIPE_AMBIGUOUS_ERROR, "request.pipe_ambiguous"),"several `main_pipe`s","one of the declared `main_pipe`s",id="several-entry-pipes",@@ -372,17 +384,20 @@ class TestPipeIoRoute:],)def test_selection_refusals_carry_the_entry_lookup_error_type(- self, contents: tuple[str, ...], request_fields: dict[str, Any], error_type: str, detail_fragment: str, fix_fragment: str+ self, contents: tuple[str, ...], request_fields: dict[str, Any], refusal: tuple[str, str], detail_fragment: str, fix_fragment: str):# A selection refusal is an input 422 like a malformed request, but its `error_type` is the# pipelex entry-lookup class that names the failure, so a client branches on it; its problem# `type` names the selection too, and its `user_action` names the fix for this very miss —# a default chain that finds no entry pipe, or several, is no pipe-code typo.+ error_type, code = refusalclient = _build_client()response = client.post(PIPE_IO_PATH, json={"files": _files(*contents), **request_fields})detail = _assert_input_422(response, error_type=error_type)assert detail_fragment in detailproblem = response.json()+ assert problem["code"] == code+ assert problem["type"] == f"https://mthds.ai/errors/{code}"assert problem["type"] != client.post(PIPE_IO_PATH, json={}).json()["type"], "a selection refusal must not share the request-shape type"assert problem["user_action"]["kind"] == "change_input"assert fix_fragment in problem["user_action"]["detail"]@@ -440,7 +455,9 @@ class TestPipeIoRoute:# none. The manifest only ever adds a default, so the closure arm's refusal stands.install_method_package(files={"documents.mthds": NO_MAIN_PIPE_MTHDS}, manifest_toml=STUB_METHOD_MANIFEST_NO_MAIN_PIPE)client = _build_client()- detail = _assert_input_422(client.post(PIPE_IO_PATH, json={"method_ref": STUB_METHOD_REF}), error_type=PIPE_NOT_FOUND_ERROR)+ response = client.post(PIPE_IO_PATH, json={"method_ref": STUB_METHOD_REF})+ detail = _assert_input_422(response, error_type=PIPE_NOT_FOUND_ERROR)+ assert response.json()["code"] == "request.pipe_unspecified"assert "main_pipe" in detail@pytest.mark.parametrize(@@ -526,9 +543,10 @@ class TestPipeIoRoute:created_library_id, _ = open_spy.spy_returnteardown_spy.assert_called_once_with(library_id=created_library_id)- def test_an_underivable_artifact_is_a_no_verdict_500_and_still_tears_down(self, mocker: MockerFixture):- # `PipeIOContractError` is left to the global handler, exactly as on `/v1/validate`: a fault of- # the tool, not a verdict about the method. The library is still torn down.+ def test_an_underivable_artifact_is_a_no_verdict_problem_and_still_tears_down(self, mocker: MockerFixture):+ # `PipeIOContractError` is left to the global handler, exactly as on `/v1/validate`: no verdict,+ # a problem document carrying `method.concept_invalid`, since a concept's structure cannot be+ # described. The library is still torn down.mocker.patch("pipelex_api.routes.pipelex.pipe_io.build_pipe_io_artifacts",side_effect=PipeIOContractError(message="Failed to render the JSON Schema for the output of pipe 'smoke.echo'"),@@ -540,8 +558,9 @@ class TestPipeIoRoute:client = _build_client()response = client.post(PIPE_IO_PATH, json={"files": {"main.mthds": VALID_MTHDS}})- assert response.status_code == 500, response.text+ assert response.status_code == 422, response.textassert response.headers["content-type"] == "application/problem+json"assert "is_valid" not in response.json()+ assert response.json()["code"] == "method.concept_invalid"assert open_spy.call_count == 1assert teardown_spy.call_count == 1diff --git a/api/tests/unit/test_pipeline_bundle.py b/api/tests/unit/test_pipeline_bundle.pyindex 1b26c5748..e47e9baa7 100644--- a/api/tests/unit/test_pipeline_bundle.py+++ b/api/tests/unit/test_pipeline_bundle.py@@ -389,6 +389,8 @@ class TestPipelineBundle:response = client.post("/v1/execute", json={**body, "inputs": {"text": "hi"}})assert response.status_code == 422, response.text+ assert response.json()["code"] == "request.invalid"+ assert response.json()["error_type"] == "PipelexRequestError"assert "dependencies" in response.json()["detail"]assert snapshot == {}, "the runner was reached"diff --git a/api/tests/unit/test_problem_document.py b/api/tests/unit/test_problem_document.pyindex c2de44dfd..4a3858872 100644--- a/api/tests/unit/test_problem_document.py+++ b/api/tests/unit/test_problem_document.py@@ -1,9 +1,12 @@"""Unit tests for the RFC 7807 problem-document builder."""import pytest+from mthds.protocol.problem.registry import CoreCodefrom pipelex.base_exceptions import DisclosureMode, ErrorDomain, ErrorReport, PipelexConfigErrorfrom pipelex.cogt.inference.error_classification import ProviderErrorMetadata, UserAction, UserActionKindfrom pipelex.cogt.inference.provider_name import ProviderName+from pipelex.errors.error_codes import error_code_spec+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.system.exceptions import EnvVarNotFoundErrorfrom pytest_mock import MockerFixture@@ -13,24 +16,25 @@ from pipelex_api.problem_document import build_problem_document, build_problem_ddef _synthetic_llm_report() -> ErrorReport:"""A fully-populated report standing in for a provider rate-limit failure."""- return ErrorReport(+ report = ErrorReport.make_for_code(+ code=CoreCode.PROVIDER_RATE_LIMITED,error_type="LLMCompletionError",message="OpenAI returned 429 (rate_limit_exceeded)",- title="LLM completion error",- type_uri="https://docs.pipelex.com/latest/errors/llm-completion-error/",- error_category="transient",- error_domain="runtime",- retryable=True,user_action=UserAction(kind=UserActionKind.WAIT_AND_RETRY, detail="Retry after 12s."),- model="gpt-4o-mini",- provider="openai",- provider_metadata=ProviderErrorMetadata(- provider=ProviderName.OPENAI,- sdk_exception_type="RateLimitError",- status_code=429,- retry_after_seconds=12.0,- request_id="req_provider_abc",- ),+ )+ return report.model_copy(+ update={+ "error_category": "transient",+ "model": "gpt-4o-mini",+ "provider": "openai",+ "provider_metadata": ProviderErrorMetadata(+ provider=ProviderName.OPENAI,+ sdk_exception_type="RateLimitError",+ status_code=429,+ retry_after_seconds=12.0,+ request_id="req_provider_abc",+ ),+ })@@ -39,11 +43,12 @@ class TestProblemDocument:report = PipelexConfigError("the gateway config is missing").to_error_report()doc = build_problem_document(report, instance="/v1/validate", request_id="REQ2", disclosure_mode=DisclosureMode.VERBOSE)assert doc["status"] == 500+ assert doc["code"] == "pipelex.config.invalid"assert doc["error_domain"] == "config"assert doc["error_type"] == "PipelexConfigError"assert doc["detail"] == "the gateway config is missing"- assert doc["title"] == "Pipelex config"- assert doc["type"].endswith("/pipelex-config-error/")+ assert doc["title"] == error_code_spec(PipelexErrorCode.CONFIG_INVALID).title+ assert doc["type"] == "https://docs.pipelex.com/errors/pipelex.config.invalid"assert doc["instance"] == "/v1/validate"assert doc["request_id"] == "REQ2"@@ -52,8 +57,9 @@ class TestProblemDocument:report = EnvVarNotFoundError("Environment variable 'COMPLETION_CALLBACK_SECRET' is required but not set").to_error_report()doc = build_problem_document(report, instance="/v1/start", request_id="REQ1", disclosure_mode=DisclosureMode.VERBOSE)assert doc["status"] == 500- assert doc["type"] == "https://docs.pipelex.com/latest/errors/env-var-not-found-error/"- assert doc["title"] == "Environment variable not set"+ assert doc["code"] == "pipelex.config.variable_missing"+ assert doc["type"] == "https://docs.pipelex.com/errors/pipelex.config.variable_missing"+ assert doc["title"] == error_code_spec(PipelexErrorCode.CONFIG_VARIABLE_MISSING).titleassert "COMPLETION_CALLBACK_SECRET" in doc["detail"]assert doc["error_type"] == "EnvVarNotFoundError"assert doc["instance"] == "/v1/start"@@ -67,8 +73,9 @@ class TestProblemDocument:report = _synthetic_llm_report()doc = build_problem_document(report, instance="/v1/execute", request_id="REQ7", disclosure_mode=DisclosureMode.VERBOSE)assert doc["status"] == 429 # provider-429 passthrough- assert doc["type"] == "https://docs.pipelex.com/latest/errors/llm-completion-error/"- assert doc["title"] == "LLM completion error"+ assert doc["code"] == "provider.rate_limited"+ assert doc["type"] == "https://mthds.ai/errors/provider.rate_limited"+ assert doc["title"] == error_code_spec(CoreCode.PROVIDER_RATE_LIMITED).titleassert doc["detail"] == "OpenAI returned 429 (rate_limit_exceeded)"assert doc["error_type"] == "LLMCompletionError"assert doc["error_category"] == "transient"@@ -82,6 +89,14 @@ class TestProblemDocument:# provider_metadata.body is excluded from serialization by pipelex.assert "body" not in doc["provider_metadata"]+ @pytest.mark.parametrize("disclosure_mode", [DisclosureMode.VERBOSE, DisclosureMode.STRICT])+ def test_the_code_survives_every_disclosure_mode(self, disclosure_mode: DisclosureMode):+ """The code is what a caller branches on, so even STRICT, which redacts the message, keeps it."""+ report = PipelexConfigError("bad config").to_error_report()+ doc = build_problem_document(report, instance="/x", request_id="r", disclosure_mode=disclosure_mode)+ assert doc["code"] == "pipelex.config.invalid"+ assert doc["type"] == "https://docs.pipelex.com/errors/pipelex.config.invalid"+@pytest.mark.parametrize("disclosure_mode", [DisclosureMode.VERBOSE, DisclosureMode.STRICT])def test_forwards_disclosure_mode(self, mocker: MockerFixture, disclosure_mode: DisclosureMode):# The API only proves it forwards the mode unchanged; pipelex owns thediff --git a/api/tests/unit/test_run_refusals.py b/api/tests/unit/test_run_refusals.pyindex 421b9d6ea..161ddd970 100644--- a/api/tests/unit/test_run_refusals.py+++ b/api/tests/unit/test_run_refusals.py@@ -112,6 +112,7 @@ class TestRunRefusals:assert response.headers["content-type"].startswith("application/problem+json")body = response.json()assert body["error_type"] == "ValidateBundleError"+ assert body["code"] == "method.invalid"assert body["error_domain"] == "input"assert body["user_action"]["kind"] == "change_input"items: list[dict[str, Any]] = body["validation_errors"]@@ -138,7 +139,9 @@ class TestRunRefusals:body = response.json()# The root fault's class, not the run-level `PipelineExecutionError` that wraps it.assert body["error_type"] == "StuffFactoryError"- assert body["type"] == "https://docs.pipelex.com/latest/errors/stuff-factory-error/"+ # The code names the fault: a branch's multiplicity is not its field's.+ assert body["code"] == "pipe.output_multiplicity"+ assert body["type"] == "https://mthds.ai/errors/pipe.output_multiplicity"assert body["error_domain"] == "input"# Located at the failing step, with its path from the entry pipe, and kept under STRICT# because the fault is the caller's own method.diff --git a/api/tests/unit/test_run_source_precondition.py b/api/tests/unit/test_run_source_precondition.pyindex 8706ec7c3..7531bb1a4 100644--- a/api/tests/unit/test_run_source_precondition.py+++ b/api/tests/unit/test_run_source_precondition.py@@ -71,6 +71,10 @@ class TestRunSourcePrecondition:assert response.headers["content-type"] == "application/problem+json"problem = response.json()assert problem["error_domain"] == "input"+ # The runtime's own refusal of a field this runner does not take: `request.unsupported`.+ assert problem["code"] == "request.unsupported"+ assert problem["type"] == "https://mthds.ai/errors/request.unsupported"+ assert problem["error_type"] == "PipelexRequestError"detail = problem["detail"]assert "`method_id`" in detailassert "not handled by this deployment" in detail@@ -94,6 +98,7 @@ class TestRunSourcePrecondition:client, _ = _build_client(mocker)response = client.post("/v1/execute", json={})assert response.status_code == 422+ assert response.json()["code"] == "request.invalid"detail = response.json()["detail"]assert _BASE_PRECONDITION_FRAGMENT in detailassert "not handled by this deployment" not in detaildiff --git a/api/tests/unit/test_security_auth_mode.py b/api/tests/unit/test_security_auth_mode.pyindex 27fabf813..44b72fb69 100644--- a/api/tests/unit/test_security_auth_mode.py+++ b/api/tests/unit/test_security_auth_mode.py@@ -2,7 +2,8 @@import pytest-from pipelex_api.security import AUTH_MODE_ENV_VAR, AuthMode, InvalidAuthModeError, get_auth_dependency, get_auth_mode+from pipelex_api.exceptions import InvalidAuthModeError+from pipelex_api.security import AUTH_MODE_ENV_VAR, AuthMode, get_auth_dependency, get_auth_modeclass TestAuthMode:diff --git a/api/tests/unit/test_validate_caller_identity.py b/api/tests/unit/test_validate_caller_identity.pyindex 8cd48ddd5..cfcf32bb4 100644--- a/api/tests/unit/test_validate_caller_identity.py+++ b/api/tests/unit/test_validate_caller_identity.py@@ -19,6 +19,7 @@ from typing import Anyimport pytestfrom fastapi import FastAPI, Request, Responsefrom fastapi.testclient import TestClient+from mthds.protocol.problem.registry import CoreCodefrom pipelex.base_exceptions import ErrorReport, ValidationErrorCategory, ValidationErrorItemfrom pipelex.pipeline.validate_in_process import validate_bundles_in_processfrom pipelex.plugins.bundle_validator_registry import BundleValidatorRegistry@@ -70,11 +71,10 @@ class _RecordingBundleValidator:read_scope: str | None, # noqa: ARG002) -> ErrorReport:self.caller_identities.append(caller_identity)- return ErrorReport(+ return ErrorReport.make_for_code(+ code=CoreCode.METHOD_INVALID,error_type="ValidateBundleError",message="bundle is invalid",- title="Validate bundle error",- type_uri="https://errors.pipelex.com/validate-bundle-error/",validation_errors=[ValidationErrorItem(category=ValidationErrorCategory.BLUEPRINT_VALIDATION, message="bad ref")],)diff --git a/api/tests/unit/test_validate_dispatch.py b/api/tests/unit/test_validate_dispatch.pyindex af06243b8..61d2b9965 100644--- a/api/tests/unit/test_validate_dispatch.py+++ b/api/tests/unit/test_validate_dispatch.py@@ -17,6 +17,7 @@ from typing import Anyimport pytestfrom fastapi import FastAPIfrom fastapi.testclient import TestClient+from mthds.protocol.problem.registry import CoreCodefrom pipelex.base_exceptions import ErrorDomain, ErrorReport, PipelexConfigError, ValidationErrorCategory, ValidationErrorItemfrom pipelex.plugins.bundle_validator_registry import BundleValidatorRegistryfrom pipelex.runtime_bridge.exceptions import MissingBundleValidatorError@@ -96,11 +97,10 @@ def _register_stub_for_temporal(mocker: MockerFixture, stub: _StubBundleValidatoclass TestValidateDispatch:def test_non_direct_validators_invalid_verdict_maps_to_200_invalid_report(self, mocker: MockerFixture) -> None:"""A non-direct validator's returned ErrorReport is mapped to a 200 InvalidReport, threading the request."""- invalid_verdict = ErrorReport(+ invalid_verdict = ErrorReport.make_for_code(+ code=CoreCode.METHOD_INVALID,error_type="ValidateBundleError",message="bundle is invalid",- title="Validate bundle error",- type_uri="https://errors.pipelex.com/validate-bundle-error/",validation_errors=[ValidationErrorItem(category=ValidationErrorCategory.BLUEPRINT_VALIDATION, message="bad ref")],)stub = _StubBundleValidator(verdict=invalid_verdict)@@ -132,12 +132,10 @@ class TestValidateDispatch:def test_returned_non_verdict_error_report_maps_to_problem_json(self, mocker: MockerFixture) -> None:"""A registry-backed validator can return a classified backend fault report, not an invalid-bundle verdict."""- backend_fault = ErrorReport(+ backend_fault = ErrorReport.make_for_code(+ code=CoreCode.RUNTIME_UNAVAILABLE,error_type="TemporalTransportError",message="validator backend unavailable",- title="Temporal transport error",- type_uri="https://errors.pipelex.com/temporal-transport-error/",- error_domain=ErrorDomain.CONFIG,)stub = _StubBundleValidator(verdict=backend_fault)_register_stub_for_temporal(mocker, stub)@@ -148,8 +146,9 @@ class TestValidateDispatch:assert response.status_code == 500, response.textassert response.headers["content-type"].startswith("application/problem+json")body = response.json()+ assert body["code"] == "runtime.unavailable"assert body["error_type"] == "TemporalTransportError"- assert body["error_domain"] == ErrorDomain.CONFIG+ assert body["error_domain"] == ErrorDomain.RUNTIMEassert body["status"] == 500assert "is_valid" not in bodyassert "validation_errors" not in body@@ -168,6 +167,7 @@ class TestValidateDispatch:graph_pipe_code=None,)assert exc_info.value.mode == "direct"+ assert exc_info.value.to_error_report().code == "pipelex.plugin.not_found"def test_forbidden_orchestration_mode_override_is_a_403(self) -> None:"""The route threads orchestration_mode into the same override policy /start uses: a forbidden override is a 403."""diff --git a/api/tests/unit/test_validate_graph_target.py b/api/tests/unit/test_validate_graph_target.pyindex a9100d469..04cd3e50d 100644--- a/api/tests/unit/test_validate_graph_target.py+++ b/api/tests/unit/test_validate_graph_target.py@@ -14,6 +14,7 @@ from typing import Anyfrom fastapi import FastAPIfrom fastapi.testclient import TestClient+from mthds.protocol.problem.registry import CoreCodefrom pipelex.base_exceptions import ErrorReport, ValidationErrorCategory, ValidationErrorItemfrom pipelex.plugins.bundle_validator_registry import BundleValidatorRegistryfrom pipelex.system.caller_identity import CallerIdentity@@ -58,11 +59,10 @@ class _RecordingBundleValidator:read_scope: str | None, # noqa: ARG002) -> ErrorReport:self.graph_pipe_codes.append(graph_pipe_code)- return ErrorReport(+ return ErrorReport.make_for_code(+ code=CoreCode.METHOD_INVALID,error_type="ValidateBundleError",message="bundle is invalid",- title="Validate bundle error",- type_uri="https://errors.pipelex.com/validate-bundle-error/",validation_errors=[ValidationErrorItem(category=ValidationErrorCategory.BLUEPRINT_VALIDATION, message="bad ref")],)diff --git a/api/tests/unit/test_validate_read_scope.py b/api/tests/unit/test_validate_read_scope.pyindex 489a72e4a..9111659c4 100644--- a/api/tests/unit/test_validate_read_scope.py+++ b/api/tests/unit/test_validate_read_scope.py@@ -22,6 +22,7 @@ import pytestfrom fastapi import FastAPI, Request, Responsefrom fastapi.testclient import TestClientfrom mthds.method_tree.digest import digest_of_contents+from mthds.protocol.problem.registry import CoreCodefrom pipelex.base_exceptions import ErrorReport, ValidationErrorCategory, ValidationErrorItemfrom pipelex.plugins.bundle_validator_registry import BundleValidatorRegistryfrom pipelex.system.caller_identity import CallerIdentity@@ -67,11 +68,10 @@ class _RecordingBundleValidator:) -> ErrorReport:self.read_scopes.append(read_scope)self.held_keys.append(set(self._blob_storage.root))- return ErrorReport(+ return ErrorReport.make_for_code(+ code=CoreCode.METHOD_INVALID,error_type="ValidateBundleError",message="bundle is invalid",- title="Validate bundle error",- type_uri="https://errors.pipelex.com/validate-bundle-error/",validation_errors=[ValidationErrorItem(category=ValidationErrorCategory.BLUEPRINT_VALIDATION, message="bad ref")],)diff --git a/api/tests/unit/test_webhook_recovery.py b/api/tests/unit/test_webhook_recovery.pyindex 6fd5984c7..37a3a9ecd 100644--- a/api/tests/unit/test_webhook_recovery.py+++ b/api/tests/unit/test_webhook_recovery.py@@ -30,7 +30,8 @@ the document.from typing import Anyimport pytest-from pipelex.base_exceptions import DisclosureMode, ErrorDomain, ErrorReport+from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import DisclosureMode, ErrorReportfrom pipelex.cogt.inference.error_classification import ProviderErrorMetadata, UserAction, UserActionKindfrom pipelex.cogt.inference.provider_name import ProviderName@@ -44,6 +45,7 @@ from pipelex_api.problem_document import build_problem_document# the request-scoped extension members `instance`/`request_id` — those are# rightfully envelope-only._CLASSIFICATION_FIELDS_PRESERVED = (+ "code","error_type","error_domain","error_category",@@ -63,45 +65,43 @@ def _fully_populated_llm_report() -> ErrorReport:fixture: it pins the parity contract on the maximum field set the APIever surfaces."""- return ErrorReport(+ report = ErrorReport.make_for_code(+ code=CoreCode.PROVIDER_RATE_LIMITED,error_type="LLMCompletionError",message="OpenAI returned 429 (rate_limit_exceeded)",- title="LLM completion error",- type_uri="https://docs.pipelex.com/latest/errors/llm-completion-error/",- error_domain=ErrorDomain.RUNTIME,- error_category="rate_limit",- retryable=True,user_action=UserAction(kind=UserActionKind.WAIT_AND_RETRY,detail="The provider is rate-limiting your account. Retry after the indicated delay.",),- model="gpt-4o-mini",- provider="openai",- provider_metadata=ProviderErrorMetadata(- provider=ProviderName.OPENAI,- sdk_exception_type="RateLimitError",- status_code=429,- retry_after_seconds=12.0,- request_id="req_provider_abc",- ),+ )+ return report.model_copy(+ update={+ "error_category": "rate_limit",+ "model": "gpt-4o-mini",+ "provider": "openai",+ "provider_metadata": ProviderErrorMetadata(+ provider=ProviderName.OPENAI,+ sdk_exception_type="RateLimitError",+ status_code=429,+ retry_after_seconds=12.0,+ request_id="req_provider_abc",+ ),+ })def _caller_facing_input_report() -> ErrorReport:- """A caller-facing INPUT-domain report (the other half of the STRICT contract).+ """A caller-facing `method.syntax` report, which the caller fixes (the other half of the STRICT contract).Complements the LLM fixture: minimal classification but`caller_facing_message=True`, which is the trigger STRICT projectionkeys its `message` passthrough on. Used here to verify that the paritycontract holds across both message-disclosure provenances."""- return ErrorReport(+ return ErrorReport.make_for_code(+ code=CoreCode.METHOD_SYNTAX,error_type="MthdsParserError",message="Your .mthds file has a syntax error on line 4",- title="Pipelex interpreter error",- type_uri="https://docs.pipelex.com/latest/errors/pipelex-interpreter-error/",- error_domain=ErrorDomain.INPUT,- retryable=False,caller_facing_message=True,)diff --git a/docs/404.html b/docs/404.htmlindex ff074114c..0479233e3 100644--- a/docs/404.html+++ b/docs/404.html@@ -136,9 +136,10 @@'cookbook/using-inference-plugins': 'under-the-hood/writing-an-inference-plugin',};- // The retired per-class error pages, `errors/<kebab-class-name>/`, which a class-derived `type`- // URI still names: send them to the error codes' index. A code's page is several segments deep,- // so this never catches one.+ // A one-segment page under `errors/`, which a class-derived `type` URI names: an API-authored+ // error's, or a retired per-class page that a release without the static redirects of+ // mkdocs.yml's `redirect_maps` serves as missing. Send it to the error codes' index. A code's+ // page is several segments deep, so this never catches one.const retiredErrorPage = /^\/errors\/[a-z0-9]+(?:-[a-z0-9]+)*\/?$/;function rewritePath(p) {diff --git a/docs/api-server/error-responses.md b/docs/api-server/error-responses.mdindex 5e466569f..ad4526f07 100644--- a/docs/api-server/error-responses.md+++ b/docs/api-server/error-responses.md@@ -8,11 +8,12 @@ A failure response looks like this:```json{- "type": "https://docs.pipelex.com/latest/errors/validate-bundle-error/",- "title": "Validate bundle",+ "type": "https://mthds.ai/errors/method.invalid",+ "title": "The method does not validate","status": 422,"detail": "TOML syntax error at line 1, column 6: Expected '=' after a key in a key/value pair",- "instance": "/v1/validate",+ "instance": "/v1/execute",+ "code": "method.invalid","error_type": "ValidateBundleError","error_domain": "input","retryable": false,@@ -26,11 +27,12 @@ A failure response looks like this:**Standard RFC 7807 members** — `type`, `title`, `status`, `detail`, `instance`.-**Extension members** — only `error_type` is always present; the others appear when the originating error populates them:+**Extension members** — `error_type` and `retryable` are always present, and so are `code` and `error_domain` on an error the runtime raised; the others appear when the originating error populates them:-- `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`, `BundleResourcePathError`, as for the API-authored `InvalidResourcePath`); absent on pipelex errors that don't set it (e.g. `EnvVarNotFoundError`, `PipelexConfigError`).+- `code` — the registry code naming the fault, such as `method.invalid` or `pipelex.config.variable_missing`: a code of the MTHDS standard, or a `pipelex.` code of the Pipelex error registry, listed on the [Error Codes](../errors/index.md) page. The code decides `type`, `title`, `error_domain` and `retryable`, so a consumer branches on it rather than on the class that raised the error. API-authored errors (`ValidationError`, `Unauthenticated` and the rest of the API's own 4xx and 5xx) carry none. See [The `type` URI](#the-type-uri).+- `error_type` — stable class name of the originating error (`ValidateBundleError`, `EnvVarNotFoundError`, `WorkflowExecutionError`, …). Several classes can raise the same code, and one class can raise several, so it is the place to look in the server's logs, not the member to branch on.+- `error_domain` — one of `input`, `config`, `runtime`, read from the code's registry domain: a code the caller fixes, in its input or in the method it sent, reads `input`; one that the account's owner or the deployment's operator fixes reads `config`; and a runtime fault reads `runtime`. See [Status codes](#status-codes).+- `retryable` — whether retrying the same request can plausibly succeed: `true` only when the code's retry verdict is that a retry can succeed, as for an inference provider's rate limit, and `false` otherwise, including when the code cannot tell whether the request took effect. API-authored errors always carry `false`.- `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` in the [Error Model](../under-the-hood/error-model.md#inferenceerrorcategory)).- `user_action` — structured suggestion of what the caller should do next, when the error can author one.@@ -120,22 +122,24 @@ For `ensure_table` and `delete_table`, `table_path` addresses the table itself r## Run failures: the root fault, located at the failing pipe-When a run fails, the problem document describes the **root fault**, the innermost Pipelex error on the cause chain, never the run-level wrapper around it: `error_type`, `title` and `type` are the root fault's, and so are `error_domain`, the HTTP status and whether STRICT disclosure keeps the `detail`. The `detail` names the pipe that failed and its path from the entry pipe, `Pipe '<failing pipe>' failed (<entry pipe> → … → <failing pipe>): <the fault's own message>`, and `user_action` names the next step for that pipe. A consumer that branched on `error_type == "PipelineExecutionError"` branches on the root fault's type instead.+When a run fails, the problem document describes the **root fault**, never the run-level wrapper around it: the first Pipelex error down the cause chain that carries a code of its own, or the innermost one when none does. The wrappers that only locate the failure take their cause's code, so `code`, `error_type`, `title` and `type` are the root fault's, and so are `error_domain`, `retryable`, the HTTP status and whether STRICT disclosure keeps the `detail`. The `detail` names the pipe that failed and its path from the entry pipe, `Pipe '<failing pipe>' failed (<entry pipe> → … → <failing pipe>): <the fault's own message>`, and `user_action` names the next step for that pipe. A consumer that branched on `error_type == "PipelineExecutionError"` branches on `code` instead.-So a run the caller's own method refuses reads its reason even under STRICT: a `PipeCondition` whose outcome is `fail`, a `PipeParallel` branch whose multiplicity does not match its output field, a step started without a required input, or a model named inline that the deck does not define all answer a **422** in the `input` domain, with a `detail` that says what to change. A model the deck names but does not serve stays a redacted `config` failure, since the deployment, not the caller, has to fix it.+So a run the caller's own method refuses reads its reason even under STRICT: a `PipeCondition` whose outcome is `fail`, a `PipeParallel` branch whose multiplicity does not match its output field, a step started without a required input, or a model named inline that the deck does not define all answer a **422** whose code is the caller's own, in the `input` or the `method` domain, with a `detail` that says what to change. A model the deck names but does not serve is `model.unavailable`, a redacted `config` failure, since the deployment, not the caller, has to fix it.```httpHTTP/1.1 422 Unprocessable EntityContent-Type: application/problem+json{- "type": "https://docs.pipelex.com/latest/errors/stuff-factory-error/",- "title": "Stuff factory",+ "type": "https://mthds.ai/errors/pipe.output_multiplicity",+ "title": "A pipe's output does not have the declared multiplicity","status": 422,"detail": "Pipe 'analyze_topic' failed (review_topic → analyze_topic): PipeParallel 'analyze_topic' cannot combine its branch results into its output 'TopicReview'. Branch 'draft_idea' gives result 'ideas' as a single 'Idea', but field 'ideas' of 'TopicReview' holds a list. Declare the field as a single concept in the structure of 'TopicReview', with type 'concept' and concept_ref 'Idea', or make branch 'draft_idea' output 'Idea[]'.","instance": "/v1/execute",+ "code": "pipe.output_multiplicity","error_type": "StuffFactoryError","error_domain": "input",+ "retryable": false,"user_action": {"kind": "change_input","detail": "Branch 'draft_idea' gives result 'ideas' as a single 'Idea', but field 'ideas' of 'TopicReview' holds a list. Declare the field as a single concept in the structure of 'TopicReview', with type 'concept' and concept_ref 'Idea', or make branch 'draft_idea' output 'Idea[]'."@@ -167,7 +171,7 @@ A few specific statuses bypass the domain mapping:- **429** — an upstream inference provider rate-limited the run. `Retry-After` is set when the originating error carries `provider_metadata.retry_after_seconds`. Only `POST /v1/execute` runs inference, so only `/execute` can produce it.- **501** — a request shape the published contract accepts but this server cannot serve. `error_type = "AsyncExecutionNotEnabledError"`: this deployment does not provide async pipeline execution (`POST /v1/start`). `error_type = "MethodRefNotSupported"`: the request selected its closure by a **registry-form** `method_ref` — not a `github.com/...` address — and no server-side method registry resolves those yet. Address-form references are fetched and resolved server-side (see [Pipe Run](pipe-run.md#running-a-method-by-address-method_ref)); use one of those, or send the method's tree in `files`. Both 501s are permanent under the current deployment — do not retry.-The `method_ref` resolution errors are also mapped explicitly rather than through the domain table: `MethodRefParseError`, `MethodFetchError`, `MethodPackageAmbiguityError`, `MethodPackageTooLargeError` and `MethodPackageSymlinkError` are **422** (the caller can fix the reference, pin a tag, shrink the package, or remove the symlink it carries), `MethodPackageNotFoundError` is the **404** above, and `MethodStructuresRefusedError` is a **403**, whether the method was fetched by `method_ref` or sent as a tree. These pipelex `MethodRefError` subclasses do not classify an `error_domain`, so without the explicit mapping they would fall through to the 500 default — which would misreport caller-fixable failures as server faults.+The `method_ref` resolution errors are also mapped explicitly rather than through the domain table: `MethodRefParseError`, `MethodFetchError`, `MethodPackageAmbiguityError`, `MethodPackageTooLargeError` and `MethodPackageSymlinkError` are **422** (the caller can fix the reference, pin a tag, shrink the package, or remove the symlink it carries), `MethodPackageNotFoundError` is the **404** above, and `MethodStructuresRefusedError` is a **403**, whether the method was fetched by `method_ref` or sent as a tree. Each carries its own code (`request.invalid` for a reference that does not parse, `method.fetch_failed`, `method.ambiguous`, `method.package_invalid`, `method.not_found`, and `pipelex.deployment.python_structures_refused` for the structures refusal), and the explicit mapping keeps the statuses listed here while the HTTP status still follows `error_domain` rather than the code.Every route that takes a JSON body refuses one whose arrays and objects nest more than 128 levels deep, the body's own envelope included, with a **422** `InvalidJSON` whose `detail` says the body is nested too deeply. The depth is checked before the body is parsed, so the answer does not depend on the Python version or the stack size the server runs with. The bound is fixed rather than configurable, and real inputs stay far below it.@@ -193,7 +197,7 @@ The `ERROR_DISCLOSURE` env var controls how much of the originating error makes- `verbose` (default) — renders the full `ErrorReport`. Use in dev, staging, and any deployment where the caller is trusted.- `strict` — redacts `detail` and provider fields for errors that do not author caller-facing messages. Specifically:- - `detail` is preserved only when the error authored a caller-facing message: the bundle's validation verdict (`ValidateBundleError`), a parse error (`MthdsParserError`), and a failure the runtime classifies as the caller's own, such as a pipe refused while it is built or a run that the submitted method itself refuses (see [Run failures](#run-failures-the-root-fault-located-at-the-failing-pipe)). Everything else has `detail` replaced with a generic title-derived string.+ - `detail` is preserved only when the error authored a caller-facing message: the bundle's validation verdict (`ValidateBundleError`), a parse error (`MthdsParserError`), and a failure the runtime classifies as the caller's own, such as a pipe refused while it is built or a run that the submitted method itself refuses (see [Run failures](#run-failures-the-root-fault-located-at-the-failing-pipe)). Everything else has `detail` replaced with the fixed `"An internal error occurred."`, while `code`, `title` and `type` still say which fault it was.- `model`, `provider`, `provider_metadata` are always stripped — they have no business on a caller-facing surface.- The redaction is keyed on the **provenance of the message** (`_authors_caller_facing_message` ClassVar), not on `error_domain`. A `RuntimeError` raised `from` an `INPUT`-domain cause does not leak the wrapper's internal message.@@ -205,15 +209,18 @@ An unclassified failure is the one error a caller cannot diagnose from a request## The `type` URI-`type` is a stable URI derived from the originating error's class:+`type` is the page of the error's `code`:```-https://docs.pipelex.com/latest/errors/<kebab-class-name>/+https://mthds.ai/errors/<code> a code of the MTHDS standard, such as method.invalid+https://docs.pipelex.com/errors/<code> a pipelex. code, such as pipelex.config.variable_missing```-API-authored errors (`ValidationError`, `BadRequest`, `Unauthenticated`, etc.) follow the same convention with their own slugs.+Both families are listed on the [Error Codes](../errors/index.md) page, and `title` is the code's title. A Pipelex code's type URI names no documentation version: the documentation site answers it with the code's page in the latest release (see [The pages and the type URI](../contribute/error-registry.md#the-pages-and-the-type-uri)).-The per-class pages these URIs named are retired. Errors are moving to the codes of the MTHDS standard and of the Pipelex error registry, whose type URI is the code's page: `https://mthds.ai/errors/<code>` for a core code and `https://docs.pipelex.com/errors/<code>` for a `pipelex.` code, listed on the [Error Codes](../errors/index.md) page. Until a response carries its code, its class-derived `type` names no page of its own: the documentation site sends such a URL to the Error Codes index.+API-authored errors (`ValidationError`, `BadRequest`, `Unauthenticated`, etc.) carry no code, and their `type` is still derived from their name, `https://docs.pipelex.com/latest/errors/<kebab-name>/`, a URL the documentation site sends to the Error Codes index.++Before every error carried its code, the `type` of an error the runtime raised was derived from its class in the same way and named a page per class. Those pages are retired, and the documentation site redirects each one to the page of its class's code, or to the Error Codes index when the class is gone or raises no single code, so a stored `type` still leads somewhere useful.## Request correlation@@ -238,11 +245,12 @@ Content-Type: application/problem+jsonX-Request-ID: 9f2c1ab3-…{- "type": "https://docs.pipelex.com/latest/errors/validate-bundle-error/",- "title": "Validate bundle",+ "type": "https://mthds.ai/errors/method.invalid",+ "title": "The method does not validate","status": 422,"detail": "Value error, Invalid main pipe syntax 'Not A Valid Pipe Code!'. Must be in snake_case.","instance": "/v1/execute",+ "code": "method.invalid","error_type": "ValidateBundleError","error_domain": "input","user_action": {@@ -271,19 +279,22 @@ Content-Type: application/problem+jsonX-Request-ID: 9f2c1ab3-…{- "type": "https://docs.pipelex.com/latest/errors/env-var-not-found-error/",- "title": "Environment variable not set",+ "type": "https://docs.pipelex.com/errors/pipelex.config.variable_missing",+ "title": "A configuration variable is not set","status": 500,"detail": "Missing required environment variable: COMPLETION_CALLBACK_SECRET","instance": "/v1/start",+ "code": "pipelex.config.variable_missing","error_type": "EnvVarNotFoundError",+ "error_domain": "config",+ "retryable": false,"request_id": "9f2c1ab3-…"}```-`EnvVarNotFoundError` is a domain-less pipelex tool error — neither `error_domain` nor `retryable` is populated on the report, so both extension members are absent on the wire. The HTTP status is still **500** (the deployment, not the caller, has to fix it), but the classification fields only ride along when the originating error sets them. See [Fields](#fields).+`pipelex.config.variable_missing` is a code in the `operator` domain: the deployment, not the caller, has to fix it, so it reads `error_domain: "config"` and answers a **500**. See [Fields](#fields).-Under `ERROR_DISCLOSURE=strict` the same failure has `detail` redacted to `"Server configuration error"` — the env var name lives in the server log only.+Under `ERROR_DISCLOSURE=strict` the same failure has `detail` redacted to `"An internal error occurred."` — the env var name lives in the server log only, and `code` still names the fault.### 401 — missing bearer tokendiff --git a/docs/api-server/openapi/pipelex-api.openapi.yaml b/docs/api-server/openapi/pipelex-api.openapi.yamlindex df0353733..771b030cd 100644--- a/docs/api-server/openapi/pipelex-api.openapi.yaml+++ b/docs/api-server/openapi/pipelex-api.openapi.yaml@@ -6889,11 +6889,14 @@ components:type:type: stringtitle: Type- description: 'Stable URI for the error class: `https://docs.pipelex.com/latest/errors/<kebab-class-name>/`.'+ description: 'Stable URI of the error''s documentation page: the page of its `code` (`https://mthds.ai/errors/<code>`+ for a core code, `https://docs.pipelex.com/errors/<code>` for a Pipelex code), or `https://docs.pipelex.com/latest/errors/<kebab-error-type>/`+ for an API-authored error, which carries no `code` yet.'title:type: stringtitle: Title- description: Short, human-readable summary of the error class.+ description: 'Short, human-readable summary: the title of the error''s `code`, or of its `error_type` when it carries+ none.'status:type: integertitle: Status@@ -6914,6 +6917,14 @@ components:- type: 'null'title: Request Iddescription: Correlation id, echoed in the `X-Request-ID` response header.+ code:+ anyOf:+ - type: string+ - type: 'null'+ title: Code+ description: 'Registry code of the error, what a client branches on: a core code of the MTHDS standard (e.g. `request.invalid`)+ or a Pipelex code (e.g. `pipelex.config.invalid`). Present on every error the runtime raises, under every `ERROR_DISCLOSURE`+ mode; absent on an API-authored error.'error_type:type: stringtitle: Error Type@@ -6930,8 +6941,8 @@ components:- type: boolean- type: 'null'title: Retryable- description: Whether retrying the same request can plausibly succeed. Always present on API-authored errors; on- pipelex errors only when the originating error classifies it.+ description: 'Whether retrying the same request can plausibly succeed. Always present: on an error carrying a `code`,+ it is that code''s retry verdict.'error_category:anyOf:- type: string@@ -6987,13 +6998,13 @@ components:plus the extension members pipelex''s classification adds. Only `type`,- `title`, `status`, `detail`, and `error_type` are always present: the rest+ `title`, `status`, `detail`, and `error_type` are always present, and `code`- ride along when the originating error populates them, so a consumer must+ on every error the runtime raises: the rest ride along when the originating- treat them as optional. `extra="allow"` mirrors RFC 7807''s open-ended+ error populates them, so a consumer must treat them as optional.- extension-member rule.'+ `extra="allow"` mirrors RFC 7807''s open-ended extension-member rule.'PromptImageDetail:type: stringenum:@@ -8166,6 +8177,11 @@ components:const: truetitle: Is Validdefault: true+ warnings:+ items:+ $ref: '#/components/schemas/ValidationErrorItem'+ type: array+ title: Warningsbundle_blueprint:$ref: '#/components/schemas/PipelexBundleBlueprint'pipe_io_contracts:@@ -8203,11 +8219,6 @@ components:$ref: '#/components/schemas/ValidatedPipeEntry'type: arraytitle: Validated Pipes- warnings:- items:- $ref: '#/components/schemas/ValidationErrorItem'- type: array- title: Warningspending_signatures:items:type: stringdiff --git a/docs/api-server/pipe-io.md b/docs/api-server/pipe-io.mdindex 4a1623c31..a5b98fec1 100644--- a/docs/api-server/pipe-io.md+++ b/docs/api-server/pipe-io.md@@ -47,7 +47,7 @@ The closure is resolved first, so an invalid closure answers its invalid verdict- `EntryPipeNotFoundError` for a `pipe_ref` that names no pipe of the closure, for a manifest `main_pipe` the closure does not declare, and, without `all_pipes`, for a request with no `pipe_ref` whose closure declares no `main_pipe`;- `EntryPipeAmbiguousError` for a bare code that matches pipes in several domains, whether the request or the manifest spelled it, and, without `all_pipes`, for a request with no `pipe_ref` whose closure declares several `main_pipe`s.-The `detail` says which case it is and, for an ambiguity, names the qualified refs to choose from; the candidates are in the `detail` alone, with no structured list, as on the run routes. The problem's `type` and `title` are the class's. Its `user_action` is the class's too, advising a check of the pipe code, except for a request with no `pipe_ref` whose closure declares no `main_pipe` or several, where it asks for a `pipe_ref` instead.+The `detail` says which case it is and, for an ambiguity, names the qualified refs to choose from; the candidates are in the `detail` alone, with no structured list, as on the run routes. The problem's `code` tells the cases apart, and its `type` and `title` are the code's: `request.pipe_not_found` for a `pipe_ref` that names no pipe, `request.pipe_ambiguous` for an ambiguous one or a closure declaring several `main_pipe`s, `request.pipe_unspecified` for a request with no `pipe_ref` over a closure declaring none, and `method.pipe_unresolved` for a manifest `main_pipe` the closure does not declare or matches ambiguously. Its `user_action` is the class's too, advising a check of the pipe code, except for a request with no `pipe_ref` whose closure declares no `main_pipe` or several, where it asks for a `pipe_ref` instead.An unknown or ambiguous `pipe_ref` answers the `error_type` the run routes answer for the same `pipe_code`. A closure declaring no `main_pipe`, or several, has no run-route twin: this route refuses both as the pipe-selector design classifies them, while a run over such a closure today fails with a `500` or runs the first declaration.diff --git a/docs/api-server/pipe-run.md b/docs/api-server/pipe-run.mdindex e6bfdf354..d3fd0dafd 100644--- a/docs/api-server/pipe-run.md+++ b/docs/api-server/pipe-run.md@@ -275,7 +275,7 @@ The answer is `{"missing": [{"sha256": "…", "size": n, "upload": {"method": "PA method can call a pipe of another method package by its address, such as `github.com/Pipelex/methods/documents->documents.extract_page_contents_and_views`. A request can carry that package with the method, so the run needs no copy installed on the server and no fetch:-- **With `files`**, send each package in `dependencies`, a map from the package's address to the package's own map of file entries, its `METHODS.toml` at its root declaring that address. A package keyed by another address than its manifest declares is a `422 InvalidMethodFiles`, and so is `dependencies` without `files`.+- **With `files`**, send each package in `dependencies`, a map from the package's address to the package's own map of file entries, its `METHODS.toml` at its root declaring that address. A package keyed by another address than its manifest declares is a `422 InvalidMethodFiles`; `dependencies` without `files` is a `422` `PipelexRequestError` carrying the code `request.invalid`.- **In a `bundle_b64` archive**, put each package under `.mthds/methods/<name>/`, with its `METHODS.toml` at `.mthds/methods/<name>/METHODS.toml`, which is the layout of a local method store. The store's `.provenance.json` sidecar is left out of the package.```textdiff --git a/docs/building-methods/pipes/pipe-controllers/PipeCondition.md b/docs/building-methods/pipes/pipe-controllers/PipeCondition.mdindex 3bd9a231f..8e69ea3bf 100644--- a/docs/building-methods/pipes/pipe-controllers/PipeCondition.md+++ b/docs/building-methods/pipes/pipe-controllers/PipeCondition.md@@ -19,7 +19,7 @@ When the expression renders nothing, no outcome can be chosen and the pipe failsA dry run, which is what `pipelex validate` and `pipelex run … --dry-run` do, runs every outcome because it cannot know which one a live run would take. Each outcome runs on a copy of the memory the condition received, so no outcome reads what another one wrote, and the default outcome runs last: the steps after the condition read its output, which is what a live run falls back to when no key matches. The graph of a dry run draws the condition's output as one stuff that every outcome produces and the next step reads.-An expression that does not parse, whether written as `expression` or as `expression_template`, is refused when the bundle loads, before anything runs, and so is one the run could not compile, such as one naming a filter or a test that does not exist outside any conditional. Jinja2 resolves a name inside an `{% if %}` block or an inline `if` only when the expression renders, so a wrong name there fails the run rather than the load. `pipelex validate` reports either as an item on the condition naming the field and the line of it that fails, and a run of the bundle is refused with the same item, which a hosted run answers with HTTP 422. The item quotes none of the expression, which may be a host library's.+An expression that does not parse, whether written as `expression` or as `expression_template`, is refused when the bundle loads, before anything runs, and so is one the run could not compile, such as one naming a filter or a test that does not exist outside any conditional. `pipelex validate` reports either as an item on the condition naming the field and the line of it that fails, and a run of the bundle is refused with the same item, which a hosted run answers with HTTP 422. The item quotes none of the expression. Jinja2 resolves a name inside an `{% if %}` block or an inline `if` only when the expression renders, so a wrong name there fails the run rather than the load: the run fails at the condition with the code `method.template_invalid`, naming the unknown filter or test and none of the expression, with a next step, and a hosted run answers it with HTTP 422 too. A condition declared in the host's own library directories, rather than in the method you submit, is the deployment's fault when it does not parse: the load fails with `pipelex.config.invalid`, which an API answers with HTTP 500 and whose text STRICT disclosure withholds.## Configurationdiff --git a/docs/building-methods/pipes/pipe-operators/PipeLLM.md b/docs/building-methods/pipes/pipe-operators/PipeLLM.mdindex 9e6b667a3..48030f214 100644--- a/docs/building-methods/pipes/pipe-operators/PipeLLM.md+++ b/docs/building-methods/pipes/pipe-operators/PipeLLM.md@@ -259,6 +259,8 @@ A setting the model it resolves to cannot take is refused when the method loads,A text the model cannot finish within `max_tokens`, or within its context window, fails the pipe with `LLMCompletionTruncatedError` rather than passing the partial text on as the pipe's output; a text the model refuses or a safety filter stops fails it with `LLMCompletionRefusedError`. The first names the output tokens used and the limit sent, so raising `max_tokens` or shortening the input is the fix; a model that reasons spends its reasoning from the same limit.+A `prompt` or `system_prompt` that names a filter or a test Jinja2 does not know inside a conditional block loads, because Jinja2 resolves such a name only when the block renders. The run then fails at the pipe, before any model is called, with the code `method.template_invalid`: the message names the field and the unknown name, quotes none of the prompt, and comes with a next step, and a hosted run answers it with HTTP 422.+!!! tip "More on Reasoning"For provider-specific behavior and model-specific examples, see [Reasoning Controls](../../../under-the-hood/reasoning-controls.md).diff --git a/docs/configuration/config-technical/library-config.md b/docs/configuration/config-technical/library-config.mdindex 772dd8404..d75a8335d 100644--- a/docs/configuration/config-technical/library-config.md+++ b/docs/configuration/config-technical/library-config.md@@ -287,6 +287,8 @@ The structure classes and `@pipe_func()` functions of a library directory are diBefore any of that Python is imported, each tree of the load that holds Python and a `requirements.txt` at its root has its requirements checked against the interpreter Pipelex runs in, and a method whose requirements are not met, or whose file holds a line the MTHDS standard refuses, such as `-r base.txt` or `-e .`, refuses the load (see [Method Trees](../../building-methods/method-trees.md#python-packages-requirementstxt)). When a server loads its own library directories beside a caller's bundles, such a refusal is a `HostLibraryRequirementsError`, a fault of the server's configuration whose message, naming its paths, never reaches the caller, as a tree it cannot list is a `HostLibraryTreeError`. A project root handed over as a library directory is such a tree, so its own `requirements.txt` is read as its methods' declaration: hand over the folder holding your methods rather than the project root, or keep the root's file to plain PEP 508 requirements that the interpreter meets.+A method of a server's own library directories that refuses to load for any other reason, such as a pipe that does not validate, a template that does not parse or a model the deck does not define, is the deployment's fault too, never the caller's. Loaded beside a caller's bundles, its refusal becomes a `HostLibraryLoadRefusalError`, carrying `pipelex.config.invalid`, which an API answers with a `500` whose message never reaches the caller under STRICT disclosure, rather than an invalid verdict on the caller's bundles. The same refusal in the bundles the caller submits stays the caller's verdict, a `422`, and so does a refusal in library directories a local run declares the caller's own (`library_dirs_are_callers`), as the CLI's `-L` directories are.+## Project Organization**Golden rule:** Put `.mthds` files where they make sense in YOUR project. Pipelex finds them automatically.diff --git a/docs/configuration/config-technical/network-config.md b/docs/configuration/config-technical/network-config.mdindex c96157a79..7510d9fd3 100644--- a/docs/configuration/config-technical/network-config.md+++ b/docs/configuration/config-technical/network-config.md@@ -21,7 +21,7 @@ The value above is the default.With `is_fetch_ssrf_guard_enabled = true`, every download of a value's URL is checked when the connection opens, on the first request and on every redirect hop to a new host. The host is resolved, and the connection is refused when the name is `localhost` or a cloud metadata alias, or when any address it resolves to is not globally routable: private networks (`10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`), loopback, link-local (including the `169.254.169.254` metadata endpoint), carrier-grade NAT, multicast, reserved and unspecified addresses, in IPv4 and IPv6. Pipelex then connects to the address it checked, so a DNS record that changes between the check and the connection cannot slip through.-A refusal raises `SsrfBlockedError` and fails the pipe that needed the bytes. It is not treated as a failed download: where Pipelex would otherwise keep a generated image's remote URL after a download error, a refused URL fails the pipe instead. The error message names the host that was requested and never the address it resolved to.+A refusal raises `SsrfBlockedError`, with the code `security.input_url_refused`, and fails the pipe that needed the bytes. It is not treated as a failed download: where Pipelex would otherwise keep a generated image's remote URL after a download error, a refused URL fails the pipe instead. The error message names the host that was requested and never the address it resolved to.A URL passed to a provider as a URL, for a model that fetches images itself, is not downloaded by Pipelex and is not checked by this guard.diff --git a/docs/contribute/error-registry.md b/docs/contribute/error-registry.mdindex 597679f0c..efd6e17d7 100644--- a/docs/contribute/error-registry.md+++ b/docs/contribute/error-registry.md@@ -79,7 +79,7 @@ A code's type URI is the registry's base URL, a slash, then the whole code: `httThe type URI names no version, and the site is served by GitHub Pages from its `gh-pages` branch, with no server-side redirect of our own, so the documentation's deployment closes the gap. `make docs-deploy-root`, which every documentation deploy runs, calls `pipelex-dev write-error-type-redirects` on its checkout of the `gh-pages` branch: for every code whose page the `latest` version holds, it writes `errors/<code>/index.html` at the site's root, a page that redirects to the code's `/latest/` page, and it removes the stub of a code `latest` no longer documents. While `latest` documents at least one code, it also writes `errors/index.html`, which sends the base URL to the [Error Codes](../errors/index.md) index under `/latest/`; before a release that documents the codes is the latest, it writes no stub at all, removes a root stub it wrote earlier, and leaves the base URL to the site's `404.html`, which sends it to `/latest/errors/` as it sends any path without a version. It only ever removes a file that carries its stubs' marker. GitHub Pages answers a URL naming a directory without its trailing slash, as the type URI does, with a redirect to the same URL with the slash, whatever its last segment holds, and serves the stub there. A code's type URI therefore resolves once a release that documents it is the latest version.-Before the error registry, every `PipelexError` class had a generated page at `errors/<kebab-class-name>/`, which its class-derived `type_uri` named. Those pages are retired, and the site's `404.html` sends such a URL to the [Error Codes](../errors/index.md) index.+Before the error registry, every `PipelexError` class had a generated page at `errors/<kebab-class-name>/`, which its class-derived `type_uri` named. Those pages are retired, and a report's type URI is now its code's. A client may still hold an old one, from a stored report or a webhook delivery, so the documentation build keeps a static redirect for each retired page in `mkdocs.yml`'s `redirect_maps`, between the `BEGIN retired error class pages` and `END retired error class pages` markers: each is sent to the page of its class's code (the default of a class that raises a set, the fallback of one that takes its cause's code), a core code's page being the standard's, and a page whose class is gone or abstract to the [Error Codes](../errors/index.md) index. The keys are the closed record of the retired pages; the targets follow the classes, `make generate-error-identity` rewrites them, and `tests/unit/pipelex/errors/test_retired_error_page_redirects.py` fails when they drift (`pipelex/errors/retired_error_pages.py`). Any other one-segment page under `errors/`, such as the class-derived type URI of an API-authored error, is sent to the index by the site's `404.html`.## Adding or changing a codediff --git a/docs/contribute/inference-family-surface.md b/docs/contribute/inference-family-surface.mdindex 33ef82155..370144889 100644--- a/docs/contribute/inference-family-surface.md+++ b/docs/contribute/inference-family-surface.md@@ -12,7 +12,7 @@ Most of the list is enforced by the type checker: the matches over the family en1. **The family's package**, `pipelex/cogt/<family>/`, mirroring `pipelex/cogt/search/`: the question/request and answer models, the setting and its model-choice union, the job, the job factory, the usage report, the worker contract (`<Family>WorkerAbstract` with one template method and one abstract hook) and the worker factory, which resolves its worker through the inference-backend registry and holds no `match` over SDK strings.-2. **The family enums, together.** `InferenceFamily` in `pipelex/plugins/inference_backend_registry.py`, `ModelType` in `pipelex/cogt/model_backends/model_type.py`, `InferenceErrorFamily` in `pipelex/cogt/inference/error_render.py` with an entry in both its failure-class and not-found-class tables, and `ModelCategory` in `pipelex/cogt/models/model_listing.py`, which is what `pipelex-agent models` and `check-model` list from.+2. **The family enums, together.** `InferenceFamily` in `pipelex/plugins/inference_backend_registry.py`, `ModelType` in `pipelex/cogt/model_backends/model_type.py`, `InferenceErrorFamily` in `pipelex/cogt/inference/error_classify.py`, with an arm in its `is_idempotent` (a family whose call is not idempotent, such as image generation, reports a failure after the request was sent as `provider.outcome_unknown`) and an entry in both the failure-class and not-found-class tables of `pipelex/cogt/inference/error_render.py`, and `ModelCategory` in `pipelex/cogt/models/model_listing.py`, which is what `pipelex-agent models` and `check-model` list from.3. **The error classes** in `pipelex/cogt/exceptions.py`: a job failure, a model-not-found (subclassing `ModelNotFoundError`) and a handle-not-found. Then regenerate the identity snapshot (`make gei`); the snapshot test fails until you do. A code the family's errors need beyond those the error registry already declares is added to `pipelex/errors/registry/pipelex-error-registry.yaml`, followed by `make ger` to regenerate its outputs and `make cer` to check them ([The Error Registry](error-registry.md)).diff --git a/docs/errors/index.md b/docs/errors/index.mdindex 080182dc9..150218d62 100644--- a/docs/errors/index.md+++ b/docs/errors/index.md@@ -9,7 +9,7 @@ An error code names a situation a runner or a client can meet, and its type URIThese pages are generated from the Pipelex error registry, which follows the [MTHDS error registry format](https://mthds.ai/latest/spec/error-registry/) under the `pipelex` prefix the core registry registers to Pipelex. The registry is published with every Pipelex release, as the release asset `pipelex-error-registry.json` on [GitHub](https://github.com/Pipelex/pipelex/releases) and inside the `pipelex` package. This is version `0.89.0` of the registry. [The Error Registry](../contribute/error-registry.md) describes how it is maintained.-The registry declares the Pipelex codes, but Pipelex's errors do not carry them yet: an error still reports its `error_type` and a type URI derived from its class, and giving every error its code is the next step of this work, as the [Error Model](../under-the-hood/error-model.md#error-codes-and-the-pipelex-error-registry) describes.+Every Pipelex error carries a code, one of these or a core code: its problem document names it as `code`, and its `type` is the code's page. The [Error Model](../under-the-hood/error-model.md#error-codes-and-the-pipelex-error-registry) describes how an error class declares the code it raises.## pipelex.billing { #pipelex-billing }diff --git a/docs/tools/cli/agent-cli.md b/docs/tools/cli/agent-cli.mdindex 15ce91cf9..aacac40e3 100644--- a/docs/tools/cli/agent-cli.md+++ b/docs/tools/cli/agent-cli.md@@ -207,6 +207,7 @@ JSON commands return the result object directly. They are not wrapped in a `stat"error_type": "specific_error_type","message": "Human-readable description","error_domain": "input",+ "error_code": "method.invalid","hint": "Suggested fix or next step","retryable": false}@@ -214,9 +215,11 @@ JSON commands return the result object directly. They are not wrapped in a `statFor the structured commands, exactly one such object is written to stderr per failure, so the stream parses as a single JSON document.+`error_code` is the registry code of the error behind the failure, the stable name of its case (the [error codes](../../errors/index.md) page lists them), and it decides `error_domain` and `retryable`: branch on it rather than on `error_type`, which names a Pipelex class and can change between releases. An envelope whose cause is not a Pipelex error, a missing file or malformed JSON read by the command itself, carries no `error_code`, and its domain and hint come from the command's own table.+**A failed run** (`run pipe`, `run bundle`, `run method`) reports `"error_type": "PipelineExecutionError"` and adds four fields: `pipe_code` and `pipe_stack` name the pipe that failed and its path from the entry pipe, and `cause_type` and `cause_message` give the class and own message of the root fault, the innermost Pipelex error behind the failure. The `message` is that root fault's message prefixed with the failing pipe and its path (`Pipe 'summarize' failed (two_steps → summarize): …`), and the classification fields are the root fault's, so branch on `cause_type` to tell, say, a model that is not available from a failure to combine a parallel's results.-**A run the hosted API refuses** (`--runner hosted`, when the hosted API answers with a non-2xx status) reports what its problem document says, in the same envelope and the same markdown. `error_type` is the runner's error class: `ValidateBundleError` for a bundle refused before any pipe ran, as a local run reports it, or the root fault of a run that failed, such as `ModelNotFoundError` or `StuffFactoryError`, which a local run reports as `cause_type` under the `error_type` `PipelineExecutionError`. There is no `cause_type` on this path, so a consumer of a refused hosted run branches on `error_type`, which is `ApiResponseError` when the answer names no class, as a gateway's error page does not. The `message` quotes the request, the status and the runner's reason (`API POST /v1/start failed (422): Pipe 'condense_article' failed (digest_article → condense_article): …`), so on a failed run it names the failing pipe and its path. The `hint` is the runner's next step; `error_domain`, `error_category` and `retryable` are the runner's own; `validation_errors` holds the runner's items, rendered in markdown as the same grouped prose `validate` prints; `pipe_code` and `pipe_stack` appear when the problem document carries them; `error_code` is the problem's `code`, the stable code the hosted plane gives the refusals it authors itself (`rate_limited`, `unauthorized`); `retry_after_seconds` is the delay of a `Retry-After` header; and `http_status` and `request_id` are what to quote when the fault is the runner's. When the answer advised no next step, the `hint` follows its status, never the local advice kept for the runner's class: a 401 or a 403 points at `PIPELEX_API_KEY` and `pipelex login`; a 404 points at the method's address or id and at the origin (`--base-url`, else `PIPELEX_BASE_URL`, else `https://api.pipelex.com`, with no path such as `/v1`); a 429 says to wait and run again and marks the error `retryable` unless the answer said otherwise; a 503 says to wait too but warns that running again can repeat a paid run, because the service in front of the runner can answer it after the run completed, so it is `retryable` only when the answer says so; any other 4xx says to change what the message names; and any other status says to report the `request_id`, or the `http_status` when there is none.+**A run the hosted API refuses** (`--runner hosted`, when the hosted API answers with a non-2xx status) reports what its problem document says, in the same envelope and the same markdown. `error_type` is the runner's error class: `ValidateBundleError` for a bundle refused before any pipe ran, as a local run reports it, or the root fault of a run that failed, such as `ModelNotFoundError` or `StuffFactoryError`, which a local run reports as `cause_type` under the `error_type` `PipelineExecutionError`. There is no `cause_type` on this path, so a consumer of a refused hosted run branches on `error_type`, which is `ApiResponseError` when the answer names no class, as a gateway's error page does not. The `message` quotes the request, the status and the runner's reason (`API POST /v1/start failed (422): Pipe 'condense_article' failed (digest_article → condense_article): …`), so on a failed run it names the failing pipe and its path. The `hint` is the runner's next step; `error_domain`, `error_category` and `retryable` are the runner's own; `validation_errors` holds the runner's items, rendered in markdown as the same grouped prose `validate` prints; `pipe_code` and `pipe_stack` appear when the problem document carries them; `error_code` is the problem's `code`, the registry code a local failure carries in the same member, or the code the hosted plane gives a refusal it authors itself in front of the runner; `retry_after_seconds` is the delay of a `Retry-After` header; and `http_status` and `request_id` are what to quote when the fault is the runner's. When the answer advised no next step, the `hint` follows its status, never the local advice kept for the runner's class: a 401 or a 403 points at `PIPELEX_API_KEY` and `pipelex login`; a 404 points at the method's address or id and at the origin (`--base-url`, else `PIPELEX_BASE_URL`, else `https://api.pipelex.com`, with no path such as `/v1`); a 429 says to wait and run again and marks the error `retryable` unless the answer said otherwise; a 503 says to wait too but warns that running again can repeat a paid run, because the service in front of the runner can answer it after the run completed, so it is `retryable` only when the answer says so; any other 4xx says to change what the message names; and any other status says to report the `request_id`, or the `http_status` when there is none.**A hosted run that started and failed** reports its stored error report: `error_type` is the runner's class, `message` says the run's final status and reason, `hint` is the runner's next step, `error_domain`, `error_category`, `retryable`, `model`, `provider` and `validation_errors` are the report's when it carries them, and `pipeline_run_id` and `run_status` name the run. `retryable` is the runner's verdict whenever it gave one, `false` included, never the local default for its class. **A hosted run that failed on the way** carries its own class as `error_type`, with a next step for each: `ApiUnreachableError` (the network or the origin, `"error_domain": "config"`, only for a failure before the run request left this machine), `HostedRunOutcomeUnknownError` (the connection failed after the run request was sent, so a run may exist with no id returned: check the run history before running again), `RunTimeoutError` (the run keeps going on the hosted API past the wait), `PipelineExecuteTimeoutError` (a server that keeps no runs cut the blocking route before the result came back; the run may still be going, so it is `"retryable": false` and its hint points at the proxy's timeout or a base URL that keeps runs), `MissingMainStuffError` (the run completed and delivered no main output), `HostedRunPollingError` (the run started, then reading its result failed; it may still be running and is paid for, so look it up rather than run again), `HostedMethodInvalidError` (the method does not load, refused before any run starts when the inputs name a local file, its `validation_errors` naming each faulty file in `source`), `HostedLocalFileUploadUnavailableError` (the inputs name a local file and the method calls another one by its address: give the file as an `https://` URL), `InvalidLocalSourceError` (a local file in the inputs cannot be read), `UploadTransportError` (`config` when the upload never reached the hosted API, `runtime` when the hosted API failed it), `UploadAuthenticationError`, `RejectedAssetError` and the other upload failures, and `HostedBaseUrlError` for a base URL that is not an origin, refused before anything is sent. Every failure met once the hosted API acknowledged the run carries its `pipeline_run_id`. **An interrupted hosted run** (Ctrl-C) exits with `130` and the envelope `HostedRunInterruptedError`, whose `pipeline_run_id` names the run the hosted API had acknowledged: the run keeps going and is paid for. Interrupted before the acknowledgement, the envelope has no `pipeline_run_id` and its hint says to check the run history before running again. A configuration that cannot be read while deciding where the run executes gives the hint a failed local boot gives, and any other failure still leaves as this envelope, with the exception's class as `error_type`.diff --git a/docs/under-the-hood/distributed-content-generation.md b/docs/under-the-hood/distributed-content-generation.mdindex fb18c4c73..79c411e57 100644--- a/docs/under-the-hood/distributed-content-generation.md+++ b/docs/under-the-hood/distributed-content-generation.md@@ -184,9 +184,9 @@ A reference is only as safe as whoever reads it. A value can carry any URL its mOn a run whose read scope is set, a storage key is read only when it lies under the read scope, compared segment by segment, with no empty, `.` or `..` segment; a local path is never read; `https://` and `data:` URLs are untouched. The storage scope must lie under the read scope, since a run reads its own outputs back, and a mismatch is refused when the metadata is built. A run whose read scope is `None` (a laptop, a single-tenant server) reads exactly as before.-The check runs in the leaves, because both orchestration modes call the same leaves and every read of a value's URL happens while one of them handles an assignment. Each assignment declares the URLs it will read through `referenced_uris()` — the prompt's images and documents given by URI, an image generation's input images, the image or document to extract, the document to render as page views — and the leaf authorizes them as its first statement, before the dry-run branch and before any worker is built. A dry run therefore refuses the same method a live run would, and the check performs no IO. The input seam applies the same rule to what it reads itself: a table given as a CSV input, and a file the normalization would upload or link. A refused read raises `UriReadRefusedError`, a caller-facing input error answered as a 422, which names where the URL sat and never quotes it. A unit test walks every assignment model's fields for URL-shaped ones, so a new assignment or a new field that carries a URL fails until its `referenced_uris()` declares it.+The check runs in the leaves, because both orchestration modes call the same leaves and every read of a value's URL happens while one of them handles an assignment. Each assignment declares the URLs it will read through `referenced_uris()` — the prompt's images and documents given by URI, an image generation's input images, the image or document to extract, the document to render as page views — and the leaf authorizes them as its first statement, before the dry-run branch and before any worker is built. A dry run therefore refuses the same method a live run would, and the check performs no IO. The input seam applies the same rule to what it reads itself: a table given as a CSV input, and a file the normalization would upload or link. A refused read raises `UriReadRefusedError`, a caller-facing error answered as a 422 with the code `security.input_url_refused`, or `security.method_url_refused` where the reader knows the method named the URL, which names where the URL sat and never quotes it. A unit test walks every assignment model's fields for URL-shaped ones, so a new assignment or a new field that carries a URL fails until its `referenced_uris()` declares it.-The read scope leaves `https://` URLs alone because they are not the process's to scope: they are fetched over the network, and the network fetch has its own guard. Every leaf that needs the bytes behind a URL — prompt images and documents for a provider that does not take URLs, the document an extractor reads, the PDF rendered as page views, a generated image a provider returned as a link — goes through one fetch helper, and that helper connects through `SsrfGuardedTransport` unless `[runtime.network] is_fetch_ssrf_guard_enabled` is off. The transport resolves the host when each connection opens, on the first request and on every redirect hop to a new origin, refuses a name that resolves to any private, loopback, link-local or metadata address, and dials the address it vetted. A refusal raises `SsrfBlockedError`, a security error that no leaf's download fallback absorbs, so the pipe fails. The guard connects directly and ignores `HTTP(S)_PROXY`; a deployment whose egress goes through a proxy, or that reads documents from an intranet host, turns the switch off, as the [network configuration](../configuration/config-technical/network-config.md) explains. Checking in the fetch helper rather than in input normalization is deliberate: a construct, a structured output or a function result can produce a URL as easily as an input can.+The read scope leaves `https://` URLs alone because they are not the process's to scope: they are fetched over the network, and the network fetch has its own guard. Every leaf that needs the bytes behind a URL — prompt images and documents for a provider that does not take URLs, the document an extractor reads, the PDF rendered as page views, a generated image a provider returned as a link — goes through one fetch helper, and that helper connects through `SsrfGuardedTransport` unless `[runtime.network] is_fetch_ssrf_guard_enabled` is off. The transport resolves the host when each connection opens, on the first request and on every redirect hop to a new origin, refuses a name that resolves to any private, loopback, link-local or metadata address, and dials the address it vetted. A refusal raises `SsrfBlockedError`, a security error that no leaf's download fallback absorbs, so the pipe fails; its code is `security.input_url_refused` unless the reader knows the method or a provider's answer named the URL (`security.method_url_refused`, `security.provider_url_refused`). The guard connects directly and ignores `HTTP(S)_PROXY`; a deployment whose egress goes through a proxy, or that reads documents from an intranet host, turns the switch off, as the [network configuration](../configuration/config-technical/network-config.md) explains. Checking in the fetch helper rather than in input normalization is deliberate: a construct, a structured output or a function result can produce a URL as easily as an input can.---diff --git a/docs/under-the-hood/document-engine-plugins.md b/docs/under-the-hood/document-engine-plugins.mdindex 5108f9646..a47177f2d 100644--- a/docs/under-the-hood/document-engine-plugins.md+++ b/docs/under-the-hood/document-engine-plugins.md@@ -122,7 +122,7 @@ def render(self, *, job: RenderJob, resources: RenderResources) -> RenderedDocum- **`RenderResources.load(uri=…, position=…)`** is how an engine reads a file its document names, such as an image or a stylesheet. It resolves `pipelex-storage://` keys through the run's storage provider, decodes `data:` URLs, fetches `https://` through the SSRF guard, and refuses what the run's read scope does not allow, a local path included, with `UriReadRefusedError`. It reads a file of the document's method tree, named by a relative URL, as the next section describes. An engine reads nothing any other way. It returns a **`LoadedResource`**: the file's bytes as `data`, and as `mime_type` the media type the file's source gives it, described below.- **`RenderedDocument`** holds the bytes. Their MIME type and suffix are the format's.-`render` is synchronous and runs on a thread of a print pool of its own, never on the event loop's default executor, which the engine's reads need, while `RenderResources.load` hands each read back to the event loop the print started from. The print stage that calls it ends the print with the event every inference call ends with, `Inference call ends`, carrying no tokens and no cost since an engine reports none (see [Summary events](../tools/logging.md#summary-events)), logged on the coroutine that awaits the thread, so a print cancelled from outside ends `cancelled` while the thread finishes its render; an engine overrides `render` alone and logs nothing for the print itself. An engine keeps no state from one print into the next. It signals a document it cannot print by raising `DocGenRenderError`, which passes through; anything else it raises, beyond a Pipelex error, is reported as a `DocGenRenderError` naming the engine and the file. A Pipelex error raised by `RenderResources.load`, such as `UriReadRefusedError` or `TemplateUrlRefusedError`, is let through as it came, so the caller reads why the file was refused.+`render` is synchronous and runs on a thread of a print pool of its own, never on the event loop's default executor, which the engine's reads need, while `RenderResources.load` hands each read back to the event loop the print started from. The print stage that calls it ends the print with the event every inference call ends with, `Inference call ends`, carrying no tokens and no cost since an engine reports none (see [Summary events](../tools/logging.md#summary-events)), logged on the coroutine that awaits the thread, so a print cancelled from outside ends `cancelled` while the thread finishes its render; an engine overrides `render` alone and logs nothing for the print itself. An engine keeps no state from one print into the next. It signals a document it cannot print by raising `DocGenRenderError`, which passes through; anything else it raises, beyond a Pipelex error, is reported as a `DocGenRenderError` naming the engine and the file. The engine chooses the error's public code where it raises it, with `.with_error_code(...)`: `pipelex.docgen.content_unprintable` for the run's data it cannot lay out, an element taller than a page or an image that is not one, raised with `.as_caller_fault()` too, `pipelex.docgen.resource_refused` for a file the printed document may not name, `pipelex.docgen.template_invalid` for a template file it cannot read, and `runtime.unexpected`, the default, for its own failure. It declares those codes when it registers, as every plugin declares the codes its errors carry (see [Declaring the error codes a plugin raises](inference-backend-plugins.md#declaring-the-error-codes-a-plugin-raises)). A Pipelex error raised by `RenderResources.load`, such as `UriReadRefusedError` or `TemplateUrlRefusedError`, is let through as it came, so the caller reads why the file was refused.The contract is what an engine uses in `pipelex.cogt.doc_gen`: the worker; the render job, its resources, the `LoadedResource` they return and the rendered document (`render_job.py`); the formats and sources (`doc_gen_format.py`); `DocGenRenderError`, the one error of `exceptions.py` an engine raises, `MarkdownFormattingBudgetError`, the one the contract raises to an engine that formats Markdown outside a template render, and `TemplateUrlRefusedError`, the one `RenderResources.load` raises for a relative URL naming no file of the method tree; the layout tree (`layout_tree.py`); the template check request and the findings a checker returns (`template_check.py`), with the input shapes the request carries (`InputShape` and `InputShapeKind` in `input_shape.py`); and the modules of the next section. The rest of the package is Pipelex's own side of the print. An engine reaches Pipelex only through the contract and the registration seam every plugin uses, which also hands a worker its model spec, its backend, its SDK clients and its reporting delegate: anything else in Pipelex may move or change in an ordinary release, while a breaking change to the contract moves `PLUGIN_API_VERSION`. A piece an engine is missing is added to the contract, rather than imported from elsewhere in Pipelex.diff --git a/docs/under-the-hood/error-model.md b/docs/under-the-hood/error-model.mdindex 2e3a8bcff..14004eac0 100644--- a/docs/under-the-hood/error-model.md+++ b/docs/under-the-hood/error-model.md@@ -39,7 +39,7 @@ An error rises through a series of layers. Each layer has exactly one job.| **1 — Workers / SDK calls** | `pipelex/providers/*/` | **Catch the SDK exception → classify → raise `CogtError`** || **0 — Third-party SDKs** | OpenAI, Anthropic, Google, … | Raise raw, untyped provider exceptions |-Classification happens once, at **Layer 1**. Layers 2–5 are wrappers: they attach context as they catch and re-raise, but the `error_category`, `error_domain`, `model`, and `provider` set at Layer 1 reach Layer 5 unchanged (see [Cause-Chain Enrichment](#cause-chain-enrichment)). The worker states only the `error_category`; the matching `error_domain` is [derived from it](#the-cogterror-family-derives-its-domain-from-its-category), so a single Layer-1 decision settles both the retry question and the HTTP status.+Classification happens once, at **Layer 1**. Layers 2–5 are wrappers: they attach context as they catch and re-raise, but the registry code chosen at Layer 1, and the `error_category`, `model` and `provider` beside it, reach Layer 5 unchanged (see [Cause-Chain Enrichment](#cause-chain-enrichment)). The worker's classification picks the code, and the code decides the domain, the retry verdict and the HTTP status, so a single Layer-1 decision settles all three.---@@ -49,13 +49,14 @@ Classification happens once, at **Layer 1**. Layers 2–5 are wrappers: they att| Field | Type | Meaning ||-------|------|---------|+| `code` | `str` | The registry code the error resolved to, a core code of the MTHDS standard or a Pipelex code: see [Error codes](#error-codes-and-the-pipelex-error-registry) || `error_type` | `str` | The exception class name || `message` | `str` | Human-readable message |-| `title` | `str` | Stable human-readable summary — the RFC 7807 `title` |-| `type_uri` | `str` | Class-derived URI — the RFC 7807 `type`; the per-class pages it named are retired, see [Error codes](#error-codes-and-the-pipelex-error-registry) |-| `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`, `BundleResourcePathError`), except on the `CogtError` family where it is derived from `error_category`; left `None`, it is taken from the cause chain, or absent |+| `title` | `str` | The code's title — the RFC 7807 `title`, the same for every occurrence of the code |+| `type_uri` | `str` | The code's documentation page — the RFC 7807 `type`: `https://mthds.ai/errors/<code>` for a core code, `https://docs.pipelex.com/errors/<code>` for a Pipelex code |+| `error_category` | `str \| None` | `InferenceErrorCategory` value (inference errors only), the runtime's own classification that picked the code |+| `error_domain` | `str \| None` | `ErrorDomain` value — `input` / `config` / `runtime`, read from the domain the registry gives the code (see [ErrorDomain](#errordomain)) |+| `retryable` | `bool \| None` | Whether repeating the operation can succeed: `true` only when the code's retry verdict is `yes`, `false` for `no` and for `outcome_unknown` || `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 |@@ -64,13 +65,13 @@ Classification happens once, at **Layer 1**. Layers 2–5 are wrappers: they att`PipelexError.to_error_report()` is the entry point. `to_dict()` serializes, dropping `None` fields; `from_dict()` is its strict inverse.-### The identity triple, and why renaming an error class is a wire break+### The identity, and why renaming an error class or changing its code is a wire break-`error_type`, `title` and `type_uri` are the three identity fields on every report. `title` and `type_uri` are *presentation*, and each has a declaration hatch — set `_declared_title` or `_declared_type_uri` directly in a subclass body and that value is used verbatim instead of the auto-derived one (inheritance is deliberately bypassed via `cls.__dict__`, so a parent's curated title never captures its subclasses).+`code` and `error_type` are the two identity fields on every report. `title` and `type_uri` follow from the code, so no class declares them.-`error_type` has no such hatch: it is `type(self).__name__`, the Python class name with no indirection. That makes it the **machine contract** — consumers outside this repo `switch` on that string. Renaming an error class therefore breaks them *silently*: their build stays green and the branch simply stops matching, falling through to a generic error path.+`error_type` is `type(self).__name__`, the Python class name with no indirection, and consumers outside this repo `switch` on that string until the problem document moves the class name to the operator's diagnostics. Renaming an error class therefore breaks them *silently*: their build stays green and the branch simply stops matching, falling through to a generic error path. Changing the code a class declares breaks them the same way, and changes what every reader is told to do.-The guard against that is a committed snapshot of the full `(error_type, title, type_uri)` set at `tests/data/errors/error_identity.txt`, regenerated with `make generate-error-identity` (alias `make gei`) and gated by `tests/unit/pipelex/errors/test_error_identity_snapshot.py`. A rename cannot land without producing a reviewable one-line-pair diff on that file at the moment it is made — which is also the moment to plan the matching consumer updates.+The guard against both is a committed snapshot of every class's name and code declaration at `tests/data/errors/error_identity.txt`, regenerated with `make generate-error-identity` (alias `make gei`) and gated by `tests/unit/pipelex/errors/test_error_identity_snapshot.py`. A rename or a change of code cannot land without producing a reviewable diff on that file at the moment it is made — which is also the moment to plan the matching consumer updates. The same command rewrites the static redirects of the retired per-class error pages, described below.### Error codes and the Pipelex error registry@@ -78,7 +79,36 @@ The MTHDS standard names every error a runner or a client can meet with a code,The Pipelex codes are authored in one public file, `pipelex/errors/registry/pipelex-error-registry.yaml`, in the standard's registry format. Everything else is generated from it with `make generate-error-registry` (alias `make ger`): the JSON snapshot `pipelex-error-registry.json` beside it, which the package ships, every release publishes as an asset, and `load_pipelex_error_registry()` (`pipelex/errors/registry/registry_document.py`) reads; the typed Python of the codes, `pipelex/errors/registry/pipelex_codes.py`, with a `PipelexErrorCode` member and a closed parameters model per code; and one page per code under `docs/errors/`, which is where a Pipelex code's type URI, `https://docs.pipelex.com/errors/<code>`, leads. [The Error Registry](../contribute/error-registry.md) describes the format's checks and the workflow.-The registry does not yet drive the reports above: `error_type` and the class-derived `type_uri` are still what a report carries, and the per-class pages that `type_uri` named are retired. Moving each raise site and the API's problem documents onto the codes is the next step of this work.+#### Every error declares its code++Every `PipelexError` subclass declares, in its own class body, the code it raises (`pipelex/errors/error_code_declaration.py`):++- **A code**, a `CoreCode` from the `mthds` package or a `PipelexErrorCode`: every instance raises it.+- **A set**, `ErrorCodeSet(default=..., others=(...))`: the raise site that knows which applies chooses it with `with_error_code(code)`, and an instance whose raise site chose none carries the default. Two cases that need different verdicts are two codes, so a class whose raise sites need different readings declares a set, never a domain or a verdict of its own.+- **Its cause's code**, `InheritsCause(fallback=..., others=(...))`: a wrapper that adds no fact deciding the code takes its cause's, and carries its fallback when no error below it carries one. A raise site that knows the code itself may still choose the fallback or one of the `others`.+- **An abstract base**, `ABSTRACT_ERROR`: a class never raised directly.++```python+class PipeRunInputsError(PipeRunError):+ error_code = ErrorCodeSet(default=CoreCode.PIPE_INPUT_UNRESOLVED, others=(CoreCode.INPUT_MISSING,))+++raise PipeRunInputsError(msg).with_error_code(CoreCode.INPUT_MISSING)+```++`PipelexError.resolve_error_code()` walks the `__cause__` chain: it stops at the first error that carries a code by itself, the code its raise site chose or its class's, descends through every error that takes its cause's code, and stops at a cause that is not a Pipelex error. When no error on the way carries one, the error reports the code the deepest error implies (`implied_error_code`, which an inference error built with a category alone names, see below), else the fallback of the deepest wrapper, and `runtime.unexpected`, whose step is `report`, when none names one. It is one walk, guarded against a cyclic chain, and no error's code starts a walk of its own. So a wrapper that adds the fact deciding the code keeps its own over a coded cause, as `pipe.function_raised` does over any coded error raised inside the method's function (the in-process executor raises what the function raised as `PipeFuncRaisedError`, so a failure of the executor itself keeps its own code; an out-of-process executor must mark the function's failure the same way, with a Pipelex error carrying `pipe.function_raised`, since an exception that is not a Pipelex error, such as a transport failure, proves nothing about the function and reads `runtime.unexpected`), and a wrapper that adds nothing passes its cause's code through.++`ErrorReport.make_for_code()` builds every report from its code: the title, the documentation page, the domain and the retry verdict are the code's, read from the registries' generated tables (`pipelex/errors/error_codes.py`), so classifying an error is a pure lookup with no file read, safe inside a Temporal workflow's sandbox.++Four checks keep the declarations honest, in `tests/unit/pipelex/errors/test_error_code_gate.py`: every subclass declares a code in its own body, every declared code is registered, no subclass declares what its code decides (`error_domain`, `retryable`, a title or a type URI), and no raise constructs an abstract base. A fifth reads every `SomeError(...).with_error_code(Enum.MEMBER)` chain in the package and the runner, and fails on a code the class does not declare. A closed plugin declares at boot the public codes its errors raise, and a code neither registry holds refuses the boot.++#### Raises outside the root++An exception class outside the root carries no code, so a reader that meets one gets nothing better than the catch-all. Our own code therefore raises coded classes wherever a reader can see the raise, and `tests/unit/pipelex/errors/test_foreign_raises.py` catches a new foreign raise: `pipelex/errors/foreign_raises.py` reads every module of the package and the runner and allows by their shape the raises that are right (a builtin inside a pydantic validator, `NotImplementedError` in an abstract method, the data-model dunders Python and Jinja read, the framework carriers a library expects by type, and developer tooling), and every other foreign raise must be listed with its disposition in `tests/data/errors/foreign_raises.txt`: an invariant raised only on a bug of ours, which a boundary reports as `runtime.unexpected`, a builtin in a helper only validators call, a private class caught where it is defined, a carrier the scan cannot tell by its name (the import system's `ImportError`, the standard's method tree refusal its callers translate), developer tooling outside the exempt directories, or a builtin of a module that must import nothing of Pipelex and that its every caller catches. The check fails on an unlisted foreign raise and on a listed one that is gone.++#### The retired per-class pages++Before every error carried a code, each class had a page at `errors/<kebab-class-name>/`, which its class-derived type URI named. Those pages are retired. `mkdocs.yml`'s `redirect_maps` holds a static redirect for each, generated by `make generate-error-identity` (`pipelex/errors/retired_error_pages.py`), so a client following an old type URI, a non-browser one included, lands on the page of the class's code: the default of a set, the fallback of a class that takes its cause's code, or the error codes' index for a class that is abstract or gone. The site's `404.html` still sends any other single-segment error path to the index.### `validation_errors` — structured bundle-validation diagnostics@@ -97,13 +127,13 @@ The **structured-info invariant is total**: every invalid verdict carries a non-Besides `category` and `message`, each item carries whatever identity fields its stage produced — `error_type`, `pipe_code`, `concept_code`, `domain_code`, `field_path`, `field_name`, `variable_names`, `missing_concept_code`, `declared_concepts` (on an `unresolved_concept` item, the bare codes of the concepts the validated bundle declares in the domain the reference was looked up in, native concepts excluded, and never those a library loaded before it, which may be a host's own), the TOML position `line` and `column`, the unknown-model locators `model_reference`, `model_type` and `suggestions`, the template-check locators `template_file` and `template_location` (on a `template_check_warning`, which rides `warnings`), and a `source` (the declaring file path, or the per-content source the in-memory load path was given) that hands a consumer the owning file for cross-file diagnostic placement. When the error has a deterministic remedy, the item also carries a [`suggested_fix`](#suggested_fix-structured-deterministic-fixes).-**A verdict names no path on the host.** An item and the verdict's message are kept verbatim under STRICT disclosure, so neither names where the host keeps a file. A bundle of a package the method depends on by address is named by the package's address and the bundle's path inside the package, such as `github.com/acme/harbour-methods/tides/notices/tide_notices.mthds`, never by the directory the host installed the package in: that is the `source` of an item located inside the dependency and the file a duplicate declaration inside it names, on every surface, a local one included. When submitted content is validated or run, the library directories loaded beside it are the host's (installed libraries, the defaults, `PIPELEXPATH`) unless the caller says they are its own, so the verdict names none of their files: an item located in one carries no `source`, nor a `field_path` naming it, and is found by its `pipe_code` and `domain_code`, a warning found at a pipe of theirs carries no `template_file` (the sweep withholds it, `BundleValidator`'s `source_pipe_refs`), and a message that named one, named the template file a `PipeDocGen` step of theirs names (a step refused while they load, or one whose template the engine's check refuses in the dry run of a caller's pipe that runs it), or named the module a Python file of theirs was imported as (two `@pipe_func` functions of the same name, for instance), reads `<host library file>` in its place (`withholding_host_library_files` in `pipelex/pipeline/validate_bundle_translation.py`). A name only counts standing on its own, never inside a longer one, and neither a source the caller submitted nor a template file its own content names is ever withheld. A step can only name its template file relative to its bundle, so no message about one names a path on the host. A bundle validated from a file on the caller's own disk, and content validated or run against library directories that are the caller's (`library_dirs_are_callers`, an option of `validate_bundle`, of the in-process validator and of the local runtime `PipelexMTHDSProtocol`, whose `validate` and `execute` both read it), keep the full path of every file, since there the directories are the caller's own. `pipelex fix bundle --diff` leaves a dependency's address-named source as it is.+**A verdict names no path on the host.** An item and the verdict's message are kept verbatim under STRICT disclosure, so neither names where the host keeps a file. A bundle of a package the method depends on by address is named by the package's address and the bundle's path inside the package, such as `github.com/acme/harbour-methods/tides/notices/tide_notices.mthds`, never by the directory the host installed the package in: that is the `source` of an item located inside the dependency and the file a duplicate declaration inside it names, on every surface, a local one included. When submitted content is validated or run, the library directories loaded beside it are the host's (installed libraries, the defaults, `PIPELEXPATH`) unless the caller says they are its own, so the verdict names none of their files: an item located in one carries no `source`, nor a `field_path` naming it, and is found by its `pipe_code` and `domain_code`, a warning found at a pipe of theirs carries no `template_file` (the sweep withholds it, `BundleValidator`'s `source_pipe_refs`), and a message that named one, named the template file a `PipeDocGen` step of theirs names (one whose template the engine's check refuses in the dry run of a caller's pipe that runs it), or named the module a Python file of theirs was imported as (two `@pipe_func` functions of the same name, for instance), reads `<host library file>` in its place (`withholding_host_library_files` in `pipelex/pipeline/validate_bundle_translation.py`). A name only counts standing on its own, never inside a longer one, and neither a source the caller submitted nor a template file its own content names is ever withheld. A method of those directories that refuses to load is not an item at all: it is the deployment's configuration failing to validate, so `reporting_host_library_faults` in the same module raises it as a `HostLibraryLoadRefusalError`, carrying `pipelex.config.invalid`, which an API answers with a 500 and whose message, the host library's own text, STRICT disclosure withholds. A step can only name its template file relative to its bundle, so no message about one names a path on the host. A bundle validated from a file on the caller's own disk, and content validated or run against library directories that are the caller's (`library_dirs_are_callers`, an option of `validate_bundle`, of the in-process validator and of the local runtime `PipelexMTHDSProtocol`, whose `validate` and `execute` both read it), keep the full path of every file, since there the directories are the caller's own. `pipelex fix bundle --diff` leaves a dependency's address-named source as it is.-**Every refusal of the bundle is a verdict.** A validator answers either a verdict — valid, or invalid with located items — or *no verdict could be produced*, which is reserved for a failure of the tool or its environment. So a refusal raised while loading or validating a bundle becomes an item, never a no-verdict fault. After its class-specific arms, the shared cascade (`translate_to_validate_bundle_error` in `pipelex/pipeline/validate_bundle_translation.py`) turns any other `PipelexError` whose report is `input`-domained into a verdict with one item: `pipe_validation`, with the `pipe_code`, `domain_code` and `source`, when the library load located it on the pipe it was building, and `blueprint_validation` otherwise. That item carries no `error_type`, since a refusal with a closed code has an arm of its own. It keeps the refusal's message only when the refusal authored that message as caller-facing copy, and otherwise names the refusal's title, because the verdict as a whole is kept verbatim under STRICT disclosure. The location comes from the load loop in `LibraryManager.load_from_crate`, the one place that holds a pipe's code, domain and file when building it fails: it raises such a refusal again as a `PipeLoadRefusalError` naming the pipe and the file, `from` the original. A `config` or `runtime` fault, an unclassified one, a `SecurityError`, a `PipeNotFoundError` (which has its own not-found handler) and anything that is not a `PipelexError` still propagate as no verdict. The rule therefore reaches exactly the refusals whose class declares the `input` domain. The pipe factories' refusals do: `PipeLLMFactoryError`, `PipeComposeFactoryError`, `PipeExtractFactoryError`, `PipeConditionFactoryError` and `PipeParallelFactoryError` are raised only while a pipe is built, about its own blueprint, so each is `input`-domained and caller-facing, and a `PipeExtract` whose input is neither an image nor a document validates to one item on that pipe, saying which input to redeclare. `PipeImgGenFactoryError` is not among them: it is raised while an image-generation pipe runs, not while it is built.+**Every refusal of the bundle is a verdict.** A validator answers either a verdict — valid, or invalid with located items — or *no verdict could be produced*, which is reserved for a failure of the tool or its environment. So a refusal raised while loading or validating a bundle becomes an item, never a no-verdict fault. After its class-specific arms, the shared cascade (`translate_to_validate_bundle_error` in `pipelex/pipeline/validate_bundle_translation.py`) turns any other `PipelexError` whose code is the caller's to fix, in the `input` or the `method` domain, which a report reads as `input`, into a verdict with one item: `pipe_validation`, with the `pipe_code`, `domain_code` and `source`, when the library load located it on the pipe it was building, and `blueprint_validation` otherwise. That item carries no `error_type`, since a refusal with a closed code has an arm of its own. It keeps the refusal's message only when the refusal authored that message as caller-facing copy, and otherwise names the refusal's title, because the verdict as a whole is kept verbatim under STRICT disclosure. The location comes from the load loop in `LibraryManager.load_from_crate`, the one place that holds a pipe's code, domain and file when building it fails: it raises such a refusal again as a `PipeLoadRefusalError` naming the pipe and the file, `from` the original. A fault whose code an operator or the runtime must fix, a `LibraryError` among them (a library invariant of ours reads `runtime.unexpected`), a `SecurityError`, a `PipeNotFoundError` (which has its own not-found handler) and anything that is not a `PipelexError` still propagate as no verdict, and so does a missing document engine, `pipelex.docgen.engine_unavailable`, which the deployment has to install. The rule therefore reaches exactly the refusals whose code is the caller's. The pipe factories' refusals are: `PipeLLMFactoryError`, `PipeComposeFactoryError`, `PipeExtractFactoryError`, `PipeConditionFactoryError` and `PipeParallelFactoryError` are raised only while a pipe is built, about its own blueprint, so each declares a `method` code, `method.template_invalid` or `method.schema_violation`, and is caller-facing, and a `PipeExtract` whose input is neither an image nor a document validates to one item on that pipe, saying which input to redeclare. `PipeImgGenFactoryError` is not among them: it is raised while an image-generation pipe runs, not while it is built.-**The unknown model is the worked example.** A pipe whose model field names a handle, an alias, a preset or a waterfall the model deck does not define is refused when the pipe is built: the operator's deck check raises `ModelChoiceNotFoundError`, and the operator raises it again as a `PipeOperatorModelChoiceError` located on the pipe and on the field, to which the load adds the file. Every pipe type that names a model (`PipeLLM`, `PipeStructure`, `PipeImgGen`, `PipeExtract`, `PipeSearch`) does this through the same `PipeOperator.locating_model_choice` wrapper, so each gives the same item: `category: pipe_validation`, `error_type: unknown_model`, the `pipe_code`, `domain_code` and `source`, the `field_name` and a `field_path` of `pipe.<code>.model` (`pipe.<code>.model_to_structure` for a `PipeLLM`'s structuring model), the `model_reference` exactly as written, the `model_type` (`llm`, `text_extractor`, `img_gen` or `search`), and the deck's `suggestions` of the same kind, each spelled as a reference the field accepts. The suggestions stay in the item's `message` too, for consumers that keep only the message. When the deck offers exactly one suggestion, the item carries an `unsafe` `rename-model` fix, a `remap_value` of the field from the reference as written to that suggestion. It is unsafe because the suggestion is a fuzzy match over the deck's names, which can be a different model altogether, so `pipelex fix bundle` never applies it on its own; an author or an agent applies it deliberately. An inline setting table (`model = { model = "…", temperature = 0.2 }`) is not looked up in the deck, so it is not refused here. On a run the same refusal stops the bundle before any pipe runs, as the same `unknown_model` item (see the next paragraph).+**The unknown model is the worked example.** A pipe whose model field names a handle, an alias, a preset or a waterfall the model deck does not define is refused when the pipe is built: the operator's deck check raises `ModelChoiceNotFoundError`, and the operator raises it again as a `PipeOperatorModelChoiceError` located on the pipe and on the field, to which the load adds the file. Every pipe type that names a model (`PipeLLM`, `PipeStructure`, `PipeImgGen`, `PipeExtract`, `PipeSearch`) does this through the same `PipeOperator.locating_model_choice` wrapper, so each gives the same item: `category: pipe_validation`, `error_type: unknown_model`, the `pipe_code`, `domain_code` and `source`, the `field_name` and a `field_path` of `pipe.<code>.model` (`pipe.<code>.model_to_structure` for a `PipeLLM`'s structuring model), the `model_reference` exactly as written, the `model_type` (`llm`, `text_extractor`, `img_gen` or `search`), and the deck's `suggestions` of the same kind, each spelled as a reference the field accepts. The suggestions stay in the item's `message` too, for consumers that keep only the message. When the deck offers exactly one suggestion, the item carries an `unsafe` `rename-model` fix, a `remap_value` of the field from the reference as written to that suggestion. It is unsafe because the suggestion is a fuzzy match over the deck's names, which can be a different model altogether, so `pipelex fix bundle` never applies it on its own; an author or an agent applies it deliberately. An inline setting table (`model = { model = "…", temperature = 0.2 }`) is not looked up in the deck, so it is not refused here. A default the deck names itself, which a `PipeJudge` naming no model resolves as its method loads, is not the method's: the wrapper lets its `ModelDeckChoiceUnresolvedError` through unchanged, the deployment's fault and no verdict item. On a run the same refusal stops the bundle before any pipe runs, as the same `unknown_model` item (see the next paragraph).-**A run refuses an invalid bundle with the same verdict.** A run loads its bundle before any pipe runs, and the run path's `acquire_library` performs that load inside the same `translate_to_validate_bundle_error`, so a bundle the load refuses raises the `ValidateBundleError` with exactly the items validating it gives, before any inference is spent. `ValidateBundleError` is `input`-domained and caller-facing, so a hosted run route answers it as a 422 whose `validation_errors` STRICT disclosure keeps, where each refusal used to reach the host in its raw class: a misspelled concept as a `ConceptLibraryError` answered 500, a wiring mismatch as a `PipeValidationError` answered by the catch-all 500, a TOML fault as a 422 with no items, and a check firing inside a pipe's pydantic validator as a `runtime` `PipeExecutionError` reading "Input validation failed". The translation's own exceptions hold on this path too: an unknown entry pipe still raises its `PipeNotFoundError`, and a fault of the tool or its environment still propagates as itself. Two things differ from the validate path, both about whose files are loaded. The run path threads no source of its own onto its contents, so their items carry no `source`, even on a local run of a bundle file. A package the bundle depends on by address is loaded from the host's install directory within the same translation, as it is on the in-memory validate path, and a refusal inside it names the package by its address, never that directory. And the library directories load translated only when they are the caller's own, as on a local CLI run (`library_dirs_are_callers`); a host's directories (installed libraries, a temporary directory of shipped Python) load untranslated, because a fault there is not the caller's to fix. The local `pipelex run` renders the verdict with the grouped panel `pipelex validate` prints, and `pipelex-agent run` copies its `validation_errors` into the error envelope.+**A run refuses an invalid bundle with the same verdict.** A run loads its bundle before any pipe runs, and the run path's `acquire_library` performs that load inside the same `translate_to_validate_bundle_error`, so a bundle the load refuses raises the `ValidateBundleError` with exactly the items validating it gives, before any inference is spent. `ValidateBundleError` carries `method.invalid` and is caller-facing, so a hosted run route answers it as a 422 whose `validation_errors` STRICT disclosure keeps, where each refusal used to reach the host in its raw class: a misspelled concept as a `ConceptLibraryError` answered 500, a wiring mismatch as a `PipeValidationError` answered by the catch-all 500, a TOML fault as a 422 with no items, and a check firing inside a pipe's pydantic validator as a `runtime` `PipeExecutionError` reading "Input validation failed". The translation's own exceptions hold on this path too: an unknown entry pipe still raises its `PipeNotFoundError`, and a fault of the tool or its environment still propagates as itself. Two things differ from the validate path, both about whose files are loaded. The run path threads no source of its own onto its contents, so their items carry no `source`, even on a local run of a bundle file. A package the bundle depends on by address is loaded from the host's install directory within the same translation, as it is on the in-memory validate path, and a refusal inside it names the package by its address, never that directory. And the library directories load translated only when they are the caller's own, as on a local CLI run (`library_dirs_are_callers`); a host's directories (installed libraries, a temporary directory of shipped Python) load untranslated, because a fault there is not the caller's to fix: a refusal there is the `HostLibraryLoadRefusalError` described above, `pipelex.config.invalid`. The local `pipelex run` renders the verdict with the grouped panel `pipelex validate` prints, and `pipelex-agent run` copies its `validation_errors` into the error envelope.**Signatures are never an error.** An unimplemented `PipeSignature` reached during validation is a *runnability fact*, not a validation failure: the validator no longer raises on it. The assembled library's outstanding signatures ride the validation report's `pending_signatures`, and `is_runnable = not pending_signatures`. `allow_signatures` is a sweep-mechanics flag only (whether signature pipes are mock-run and listed in `validated_pipes`) — it does not change the verdict, so strict ≡ lenient in the report body. The "is this a failure?" decision moves to the consumer: the CLI exits non-zero on `not is_runnable` unless `--allow-signatures`; the HTTP caller reads `is_runnable`. (The **execute/run** path is different: running a stub still raises `PipeSignatureNotExecutableError`.)@@ -155,103 +185,66 @@ On the hosted API the same payload rides the wire verbatim as `validation_errors## Classification Enums-Two `StrEnum`s drive every downstream decision.+Two `StrEnum`s sit beside the code. Neither decides anything a reader branches on any more: the code does.### InferenceErrorCategory-Defined in `pipelex/cogt/exceptions.py`. It carries two derived properties: `is_retryable` drives retry decisions and is `True` only for `TRANSIENT`; `error_domain` drives the HTTP status the whole `CogtError` family answers with.+Defined in `pipelex/cogt/exceptions.py`. It stays inside the runtime as the classification that **picks a provider failure's code**: the worker's classification (`pipelex/cogt/inference/error_classify.py`) reads the provider's answer, assigns a category and a code together, and the rendered error carries both. The category also still drives one decision the code cannot carry: whether the Temporal activity may repeat a provider call within the run, through `is_retryable` and `find_inference_error_category_in_chain`. A call whose outcome is unknown (`AMBIGUOUS`) must never be repeated within the run, though its code, `provider.outcome_unknown`, says a new run may succeed.-| Category | Meaning | Retryable | Domain | Typical cause |-|----------|---------|-----------|--------|---------------|-| `TRANSIENT` | A brief, self-correcting failure | ✅ | `RUNTIME` | Rate limit, 5xx, connection blip |-| `CONFIGURATION` | The setup is wrong | ❌ | `CONFIG` | Bad API key, missing backend |-| `CONTENT` | The input or prompt is wrong | ❌ | **`INPUT`** | Content-policy violation, bad prompt |-| `CAPACITY` | Account quota / billing exhausted | ❌ | `RUNTIME` | `insufficient_quota`, HTTP 402 |-| `AMBIGUOUS` | Outcome unknown — may have committed | ❌ | `RUNTIME` | Connection dropped mid-request |-| `UNKNOWN` | Could not classify | ❌ | *none* | Unrecognized inner exception |+| Category | Meaning | Repeated within the run | Typical codes |+|----------|---------|-------------------------|---------------|+| `TRANSIENT` | A brief, self-correcting failure | ✅ | `provider.rate_limited`, `provider.unavailable`, `provider.timeout`, `provider.failed` |+| `CONFIGURATION` | The setup is wrong | ❌ | `provider.credential_refused`, `model.unavailable`, `pipelex.config.*` |+| `CONTENT` | The input or prompt is wrong | ❌ | `model.content_refused`, `model.context_exceeded`, `input.file_type_unsupported` |+| `CAPACITY` | Account quota / billing exhausted | ❌ | `provider.quota_exhausted` |+| `AMBIGUOUS` | Outcome unknown — may have committed | ❌ | `provider.outcome_unknown` |+| `UNKNOWN` | Could not classify | ❌ | `runtime.unexpected` |-```python-class InferenceErrorCategory(StrEnum):- TRANSIENT = "transient"- # ... CONFIGURATION, CONTENT, CAPACITY, AMBIGUOUS ...- UNKNOWN = "unknown"-- @property- def is_retryable(self) -> bool:- match self:- case InferenceErrorCategory.TRANSIENT:- return True- case _: # all other categories- return False-- @property- def error_domain(self) -> ErrorDomain | None:- match self:- case InferenceErrorCategory.CONTENT:- return ErrorDomain.INPUT- case InferenceErrorCategory.CONFIGURATION:- return ErrorDomain.CONFIG- # ... TRANSIENT / CAPACITY / AMBIGUOUS -> RUNTIME, UNKNOWN -> None ...-```+The category and the code are checked against each other. A classification whose category repeats the call within the run must pick a code whose verdict invites a retry, so `ClassificationResult` and a plugin's service error vocabulary both refuse a `TRANSIENT` entry naming a code such as `runtime.unexpected`. An error a worker or a plugin builds by hand with a category and no code reports its category's code, `InferenceErrorCategory.default_error_code`, when its class declares that code and nothing down its cause chain names one: `TRANSIENT` reads `provider.unavailable`, `CONFIGURATION` `runtime.misconfigured`, `CAPACITY` `provider.quota_exhausted` and `AMBIGUOUS` `provider.outcome_unknown`, while `CONTENT` and `UNKNOWN` name no code, since a content failure may be the caller's material or a request the runtime built, and such an error keeps its class's fallback. A local `OSError` on a local extractor is the machine's, not the input's and not a provider's, so it is `UNKNOWN` with a contact-support next step and `runtime.unexpected`, and it is not repeated within the run.!!! info "`AMBIGUOUS` vs `UNKNOWN`"`AMBIGUOUS` means the *error type is known* but the operation may or may not have committed — a blind retry is unsafe for a non-idempotent call. `UNKNOWN` means classification itself failed. Both are non-retryable, for different reasons.-!!! info "`UNKNOWN` maps to no domain at all"- `UNKNOWN` means the classification step itself failed, so claiming `RUNTIME` would assert something the code cannot support. An absent `error_domain` already renders 500 (see below), so the honest answer costs nothing at the HTTP boundary and keeps "could not classify" distinguishable from "classified as a server-side fault".-### ErrorDomain-Defined in `pipelex/base_exceptions.py`. Set as a class-level attribute on the exception, or on one error by the site that raises it (see [Classified where it is raised](#classified-where-it-is-raised)), drives HTTP status.--| Domain | Meaning | HTTP status | Who can fix it |-|--------|---------|-------------|----------------|-| `INPUT` | Caller sent something it can fix | **422** | The caller |-| `CONFIG` | Environment / configuration change needed | **500** | The operator |-| `RUNTIME` | A failure during execution | **500** | Depends on the cause |--`error_domain_to_http_status()` is the pure mapping table — it maps an unset or unrecognized domain to 500 as well. `ErrorReport.http_status` layers one rule on top: a provider 429 (`provider_metadata.status_code == 429`) takes precedence over the domain, so the API can emit a `Retry-After` header. That precedence is why `CAPACITY -> RUNTIME` does not swallow a rate-limit passthrough.--```python-class PipelexConfigError(PipelexError):- error_domain = ErrorDomain.CONFIG # class-level — every instance carries it-```--#### The `CogtError` family derives its domain from its category--The inference branch is the one place where `error_domain` is **not** declared per class. A worker has already decided whose fault the failure is when it assigns an `InferenceErrorCategory`, so `CogtError.to_error_report()` derives the domain from that category rather than asking several dozen leaf classes to state the same fact twice — which is also what keeps `error_domain` and `error_category` from ever contradicting each other on the wire.+Defined in `pipelex/base_exceptions.py`. A report's `error_domain` is read from the domain the registry gives its code, through `ErrorDomain.from_problem_domain()`, and drives the HTTP status until the problem document carries the code's own status and five-valued domain:-Precedence on the derived field mirrors every other field on that method: an `error_domain` declared explicitly on the leaf class wins, then the category derivation, then whatever the `__cause__` chain surfaced.+| Code's domain | `error_domain` | HTTP status | Who acts |+|---------------|----------------|-------------|----------|+| `input` | `INPUT` | **422** | The caller, by changing the request or its inputs |+| `method` | `INPUT` | **422** | The method's author, by changing the method |+| `account` | `CONFIG` | **500** | The account's owner |+| `operator` | `CONFIG` | **500** | Whoever runs the runtime |+| `runtime` | `RUNTIME` | **500** | Nobody beforehand: wait, retry or report |-```python-own_domain = self.error_category.error_domain if self.error_category is not None else None-"error_domain": self.error_domain or own_domain or base_report.error_domain,-```+`error_domain_to_http_status()` is the pure mapping table — it maps an unset or unrecognized domain to 500 as well. `ErrorReport.http_status` layers one rule on top: a provider 429 (`provider_metadata.status_code == 429`) takes precedence over the domain, so the API can emit a `Retry-After` header.-The consequence worth knowing at the HTTP boundary: a **content-classified inference failure answers 422, not 500** — a content-policy refusal, a malformed prompt image, a bad prompt parameter are all properties of material the caller submitted. Everything else keeps the status it already had; only the report became truthful about why.--The category a class declares is its default, and a raise site that knows better passes its own through the `error_category` argument. `ImgGenParameterError` is `CONTENT`, because an aspect ratio or a size the model's grid refuses is a property of the caller's request. A model spec its worker cannot use is not: no `rules`, a rule value this release does not know, a missing `model_choice` or `endpoint_path`, or, where a worker reads the Gemini geometry, a missing `aspect_ratio` taxonomy or one of another family. Those sites raise it with `error_category=InferenceErrorCategory.CONFIGURATION`, so the failure answers 500 and lands in server-error alerting like any other configuration fault, rather than a 422 telling the caller to change what they sent.+No class declares a domain: a class whose raise sites need two readings declares two codes, and the raise site chooses.#### Classified where it is raised-Most classes state whose fault they are in their body: an `error_domain`, and `_authors_caller_facing_message = True` when their message is copy written for the caller, which STRICT disclosure then keeps instead of replacing it with `An internal error occurred.`. Every instance of such a class is the same kind of fault. A few classes are raised both for faults in the caller's own method or inputs and for faults that are not the caller's, so they cannot state it. For those, the site that raises the error and knows calls `as_caller_fault()` on it: the report then carries the `input` domain, so an HTTP surface answers 422, a caller-facing message, and the next step the raise site passes, if any.+The code says who must act. Whether the error's *message* may be shown to the caller is a separate fact: `_authors_caller_facing_message = True` on a class whose message is copy written for the caller, which STRICT disclosure then keeps instead of replacing it with `An internal error occurred.`. A few classes are raised both with messages that describe only the caller's own method or inputs and with messages that do not, so they cannot state it. For those, the site that raises the error and knows calls `as_caller_fault()` on it, which marks this one message caller-facing and may pass a next step; the domain stays the code's, which the raise site chooses with `with_error_code()` when the class declares a set.```python-raise PipeRunInputsError(message=msg, run_mode=run_mode, pipe_code=pipe_code).as_caller_fault(- user_action=UserAction(kind=UserActionKind.CHANGE_INPUT, detail="Provide the missing required inputs of 'flow': topic."),+raise (+ PipeRunInputsError(message=msg, run_mode=run_mode, pipe_code=pipe_code)+ .with_error_code(CoreCode.INPUT_MISSING)+ .as_caller_fault(+ user_action=UserAction(kind=UserActionKind.CHANGE_INPUT, detail="Provide the missing required inputs of 'flow': topic."),+ ))```-The raise site vouches for the message: it names only the caller's own method and data (pipe codes, concept codes, variable names, the values the caller sent), never a path on the host, a secret or the text of a foreign exception. As with the class-level flag, a plain wrapper raised from the error inherits its domain but not its caller-facing flag, since the wrapper's message is its own; the located wrappers of a run failure report their root fault, so they carry both.+The raise site vouches for the message: it names only the caller's own method and data (pipe codes, concept codes, variable names, the values the caller sent), never a path on the host, a secret or the text of a foreign exception. A plain wrapper raised from the error takes its code when it declares none of its own, but never its caller-facing flag, since the wrapper's message is its own; the located wrappers of a run failure report their root fault, so they carry both.-| Raise site | Error | Why it is the caller's fault |+| Raise site | Error | Why its message is the caller's ||------------|-------|------------------------------|| A `PipeParallel` combining its branch results into its output | `StuffFactoryError` | The method sets which branch feeds which field, what each branch produces and whether it produces a list. A branch whose multiplicity differs from its field's is restated by a second `StuffFactoryError` raised from the combine's, whose next step names the multiplicity to change, and which the run reports as its root fault || A pipe checking that its required inputs are present | `PipeRunInputsError` | The request, or an earlier step of the method, left the input out || A `PipeCondition` whose expression renders nothing, whose outcome is `fail`, whose chosen pipe misses inputs, or, in a dry run, whose expression does not parse, whose outcomes name no pipe or whose every outcome is `fail` | `PipeRunError` | The method writes the expression and the outcomes, and the run's data it renders is the caller's; the messages name only the pipes and the input names, never the expression's text or the value it rendered, either of which may be a host library's || A model lookup for a reference the deck neither defines nor names in any of its own entries | `ModelNotFoundError` | Only an inline model setting of the method can have named it, so the next step is a `CHANGE_MODEL` action naming the reference as the method wrote it and the type of model the lookup needs; a reference the deck names but cannot serve stays `config` and redacted, with no next step of its own |-Some failures stay unclassified on purpose, each with a sentence at its raise site saying why: a model output that does not fit its structure, which depends on what the model produced; a `PipeFunc` crash, whose exception text can carry anything the process holds; an input resource the pipe cannot use, whose message names the path as resolved on the host; a template that fails to render, where the same failure can come from the template or from the data; and a working-memory miss, since a step naming a variable nothing produces is refused when the bundle loads.+Some failures carry their code with a message that stays redacted under STRICT on purpose, each with a sentence at its raise site saying why: a model output that does not fit its structure, which depends on what the model produced; a `PipeFunc` crash, whose exception text can carry anything the process holds; an input resource the pipe cannot use, whose message names the path as resolved on the host; a template that fails to render, where the same failure can come from the template or from the data; and a working-memory miss, since a step naming a variable nothing produces is refused when the bundle loads.---@@ -322,11 +315,11 @@ One refusal outside any service's own namespace is classified by the runtime its- **It is not a model-not-found.** The model exists and an integration serves it, only not for this caller, so `ClassificationResult.is_model_not_allowed` is set and `is_model_not_found` is not: the error stays on the family's generic failure class and carries the distinction in its advice. The ladder's generic 4xx arm would have given it the right category and advice sending the caller to edit their inputs.- **Its advice names the model.** The refusal's message names only the backend's wire id (`us.anthropic.claude-sonnet-4-5-20250929-v1:0`), which the method's author never wrote, so the advice names the model handle the deck resolved the pipe's model to. Both of its hints are conditional, because the Render step cannot tell the cases apart: leaving the pipe's model unset helps only when the pipe named the refused model rather than falling back to it as the default, and a model deck that lists a model the allow-list refuses is the operator's to settle on a hosted gateway and the user's own on a Portkey workspace of theirs.-- **It answers 500 on an HTTP surface.** `InferenceErrorCategory.CONFIGURATION` implies `ErrorDomain.CONFIG`, which `error_domain_to_http_status` renders as 500: it lands in server-error alerting, and 500 is a status outer clients retry, though an outer retry earns an identical refusal.+- **It answers 500 on an HTTP surface.** It carries `model.unavailable`, a code in the operator's domain, which reads `ErrorDomain.CONFIG` and which `error_domain_to_http_status` renders as 500: it lands in server-error alerting, and its verdict tells a client not to retry, since an outer retry earns an identical refusal.### The `instructor` Unwrap-On structured-generation paths, `instructor` raises an `InstructorRetryException` from the exception that ended its retry loop. The loop re-asks only a response that fails the schema, so that exception is either the raw SDK exception of a call that failed in transport, or, once the re-ask budget is spent, the last parse failure. `extract_underlying_sdk_exception()` recovers it from the wrapper's cause, not from `failed_attempts`, which lists only parse failures and would name an earlier one when a re-ask then fails in transport. The recovered exception routes through the same per-provider categorization as the plain-text path. Once the re-ask budget is spent, the recovered exception is the last `pydantic.ValidationError`, which `_STATUSLESS_BY_TYPE_NAME` classifies as `CONTENT` / `CHANGE_INPUT`, so it answers 422. A recovered exception the classifier does not recognize lands in `UNKNOWN`.+On structured-generation paths, `instructor` raises an `InstructorRetryException` from the exception that ended its retry loop. The loop re-asks only a response that fails the schema, so that exception is either the raw SDK exception of a call that failed in transport, or, once the re-ask budget is spent, the last parse failure. `extract_underlying_sdk_exception()` recovers it from the wrapper's cause, not from `failed_attempts`, which lists only parse failures and would name an earlier one when a re-ask then fails in transport. The recovered exception routes through the same per-provider categorization as the plain-text path. Once the re-ask budget is spent, the recovered exception is the last `pydantic.ValidationError`, which `_STATUSLESS_BY_TYPE_NAME` classifies as `CONTENT` / `CHANGE_INPUT` with `model.output_schema_mismatch`, so it answers 422. A recovered exception the classifier does not recognize lands in `UNKNOWN`.### Model and Provider Attribution@@ -341,7 +334,7 @@ def fill_model_and_provider(self, model_handle: str | None, *, backend_name: str## Cause-Chain Enrichment-A wrapper exception — `PipeRunError` → `PipeRouterError` → `PipelineExecutionError` — carries no `error_category` of its own. `to_error_report()` enriches the report from the `__cause__` chain, so the inference classification survives every wrapping layer.+A wrapper exception — `PipeRunError` → `PipeRouterError` → `PipelineExecutionError` — carries no `error_category` of its own. Its code comes from `resolve_error_code()`, which already walked the `__cause__` chain (see [Every error declares its code](#every-error-declares-its-code)); `to_error_report()` then enriches the report's diagnostic fields from the chain, so the inference classification survives every wrapping layer.```pythondef _enrich_error_report_from_cause(self, report: ErrorReport) -> ErrorReport:@@ -349,16 +342,16 @@ def _enrich_error_report_from_cause(self, report: ErrorReport) -> ErrorReport:if not isinstance(cause, PipelexError):return reportcause_report = cause.to_error_report()- return ErrorReport(- error_type=report.error_type, # keep own identity- message=report.message,- error_category=report.error_category or cause_report.error_category,- error_domain=report.error_domain or cause_report.error_domain,- # ... retryable, user_action, model, provider, provider_metadata ...+ return report.model_copy(+ update={+ "error_category": report.error_category or cause_report.error_category,+ "user_action": report.user_action or cause_report.user_action,+ # ... model, provider, provider_metadata ...+ })```-A wrapper keeps its own `error_type` and `message` but inherits every classification field it does not set itself. The two wrappers of a run failure go further, and report their root fault instead of themselves: see [Run Failures: the Root Fault, Located](#run-failures-the-root-fault-located).+A wrapper keeps its own `error_type` and `message`, and its code with everything the code decides, but inherits every diagnostic field it does not set itself. The two wrappers of a run failure go further, and report their root fault instead of themselves: see [Run Failures: the Root Fault, Located](#run-failures-the-root-fault-located).!!! warning "Overrides must call the enrichment helper"A `to_error_report()` override on a subclass **must** end with `self._enrich_error_report_from_cause(report)`. Otherwise that subclass becomes a black hole that drops the cause's classification. A cyclic-`__cause__` guard ensures a malformed chain can never turn error reporting into a `RecursionError`.@@ -367,7 +360,7 @@ A wrapper keeps its own `error_type` and `message` but inherits every classifica## Run Failures: the Root Fault, Located-When a pipe fails during a run, the error a surface receives sits under several wrappers: the pipe router's `PipeRouterError`, maybe a runtime bridge's `PipelexBridgeDispatchError`, and the runner's `PipelineExecutionError`. None of them is what went wrong, and a report reading `PipelineExecutionError` with a bridge's sentence for a message tells the reader nothing. So the two located wrappers, `PipeRouterError` and `PipelineExecutionError`, report the **root fault**, the innermost `PipelexError` on the cause chain, and only add where it happened (`pipelex/pipe_run/located_failure.py`). The walk stops at the first exception that is not a `PipelexError`, whose stand-in is then the fault, and an error raised from one of its own class (a remedy or an item index added to the same fault) counts as the outer one.+When a pipe fails during a run, the error a surface receives sits under several wrappers: the pipe router's `PipeRouterError`, maybe a runtime bridge's `PipelexBridgeDispatchError`, and the runner's `PipelineExecutionError`. None of them is what went wrong, and a report reading `PipelineExecutionError` with a bridge's sentence for a message tells the reader nothing. So the two located wrappers, `PipeRouterError` and `PipelineExecutionError`, which take their cause's code, report the **root fault** and only add where it happened (`pipelex/pipe_run/located_failure.py`). The root fault is the error whose code the failure resolves to: the first `PipelexError` down the cause chain that declares a code of its own, the walk `resolve_error_code()` makes, so a wrapper that adds the fact deciding the code (a PipeFunc's `pipe.function_raised` over a coded error its function raised) is the root fault over its cause, and the innermost `PipelexError` when none declares one. The walk stops at the first exception that is not a `PipelexError`, whose stand-in is then the fault.**Locating.** `PipeRouterProtocol.run()` catches every failure of the pipe it runs and re-raises it as a `PipeRouterError` chained to it, with the pipe's code and a snapshot of its stack taken where it failed. A failure that already carries a `PipeRouterError` rises untouched through the routers of the controllers above, so the innermost location is the one reported. An exception that is not a `PipelexError` first becomes a `PipelexUnexpectedError` whose message names its class (`KeyError: 'boom'`); it is never caller-facing, and a dry run that sorts its own failures from programming bugs (the bundle validator's sweep, the validate surfaces' graph step) finds the foreign exception behind it with `find_foreign_fault()` and lets it propagate rather than report it as the bundle's failure. A host router whose transport raises its own failures overrides the `_as_pipelex_failure()` hook, and returns `None` for a control-flow exception such as a cancellation, which then propagates as it is. For a transport failure carrying a recovered report, the far side packs the root fault's own report, never a located one: when it packs that report alone, the hook returns a `PipelexError` carrying it and the router locates it at the pipe it ran; when it packs the location it found as well, the hook returns a `PipeRouterError` rebuilt over that report with `make_located()`, which the router raises untouched, so the report reads exactly as the local run's. The runner wraps any failure of the run into a `PipelineExecutionError` with `make_for_run_failure()`, which takes the location from the innermost `PipeRouterError` on the chain (`find_failure_location()`), never from the live stack, which has unwound by then.@@ -375,11 +368,10 @@ When a pipe fails during a run, the error a surface receives sits under several| Field | Taken from ||-------|------------|-| `error_type`, `title`, `type_uri` | The root fault |+| `code`, `error_type`, and what the code decides: `title`, `type_uri`, `error_domain`, `retryable` | The root fault || `message` | The root fault's own message, prefixed with the failing pipe and its path || `caller_facing_message`, `validation_errors`, `migration` | The root fault |-| `error_category`, `retryable`, `model`, `provider`, `provider_metadata` | The cause-chain enrichment |-| `error_domain` | The cause-chain enrichment, with a `runtime` floor |+| `error_category`, `model`, `provider`, `provider_metadata` | The cause-chain enrichment || `user_action` | The cause-chain enrichment or, when nothing on the chain advises an action, a fallback naming the failing pipe |The message reads `Pipe 'summarize' failed (two_steps → summarize): Model handle 'x' was not found in the model deck.` for a nested pipe, and `Pipe 'flow' failed: …` for the entry pipe. Pipe codes are the caller's own names, so the located message is caller-facing exactly when the root fault's message is, and STRICT disclosure keeps it exactly then. `ErrorReport` has no location field, so the location rides the message; `PipeRouterError` and `PipelineExecutionError` carry it structurally as `pipe_code` and `pipe_stack`.@@ -396,13 +388,13 @@ The error model is built to survive serialization. Because `ErrorReport` round-tThe runtime itself stays transport-agnostic: the machinery that carries an error across a worker boundary ships in the **host-runtime plugin** for each distributed backend, not in core. A backend plugin is responsible for three things.-**Packing.** Convert a `PipelexError` into the transport's failure type and stash `to_error_report().to_dict()` in its details payload, so worker and submitter code keep the full classification rather than a bare message. The same step derives the transport's retry decision from `InferenceErrorCategory.is_retryable`.+**Packing.** Convert a `PipelexError` into the transport's failure type and stash `to_error_report().to_dict()` in its details payload, so worker and submitter code keep the code and the full classification rather than a bare message. The same step derives the transport's retry decision from `InferenceErrorCategory.is_retryable`, which tells a provider call that may be repeated within the run from one whose outcome is unknown.**Recovering.** On the submitter side, walk the returned failure, pull the packed dict, and rebuild the `ErrorReport`. Recovery is **total**: when no report dict is found — a non-Pipelex exception, a worker crash, a timeout — the plugin synthesizes a fallback report so the recovery path always has structured classification to surface.**A fail-safe floor.** Ensure a domain error that escapes the conversion path fails the unit of work *terminally* rather than hanging. In a durable-execution system the default for an unconverted exception might be to retry forever, so "convert all the errors we know about" is not enough — the floor must hold for the errors, and the code paths, that nobody enumerated.-**Net effect:** a pipe failing on a remote worker reaches the CLI and HTTP adapters with the *same* `error_category` / `retryable` / `model` / `provider` / `user_action` as the identical failure run locally — and a failure that escapes conversion fails loud and bounded instead of hanging.+**Net effect:** a pipe failing on a remote worker reaches the CLI and HTTP adapters with the *same* `code` / `error_category` / `retryable` / `model` / `provider` / `user_action` as the identical failure run locally — and a failure that escapes conversion fails loud and bounded instead of hanging.See [Runtime Bridge & Transport](./runtime-bridge-and-transport.md) for the boundary these converters span; the per-backend converters themselves live in the host-runtime plugins.@@ -487,44 +479,37 @@ flowchart TB### Class Hierarchy-`PipelexError` is the single root. `CogtError` is the inference branch — it overrides `to_error_report()` to add `error_category`, `retryable`, `user_action`, `provider_metadata`, and reads `model_handle` / `backend_name` from the instance. It is also where `error_domain` is *derived* rather than declared: the whole subtree gets its domain from its category.+`PipelexError` is the single root, and every subclass declares its code (see [Every error declares its code](#every-error-declares-its-code)). `CogtError` is the inference branch: an abstract base whose subclasses declare the codes the classification picks from, and which overrides `to_error_report()` to add `error_category`, `provider_metadata`, and the `model_handle` / `backend_name` it reads from the instance.```Exception-└── PipelexError base_exceptions.py — error_domain, user_action, to_error_report()- ├── PipelexConfigError → error_domain = CONFIG- ├── PipelexSetupError → error_domain = CONFIG- ├── SecurityError base_exceptions.py — the policy refusals never absorbed into a domain answer- │ ├── UriReadRefusedError / SsrfBlockedError → error_domain = INPUT, caller-facing message- │ ├── UnsafeSchemaError- │ └── Jinja2TemplateSecurityError ← the template sandbox's refusal at render time- ├── CogtError cogt/exceptions.py — error_category, provider_metadata- │ │ → error_domain derived from error_category (no per-class declaration)- │ ├── LLMCompletionError ← per-instance category from the worker → per-instance domain- │ ├── ImgGenGenerationError ← per-instance category- │ ├── LLMPromptSpecError ← class-level CONTENT → INPUT → HTTP 422- │ ├── LLMConfigError ← class-level CONFIGURATION → CONFIG- │ ├── ModelNotFoundError ← sibling family raised on provider HTTP 404- │ │ ├── LLMModelNotFoundError / ImgGenModelNotFoundError- │ │ └── ExtractModelNotFoundError / SearchModelNotFoundError+└── PipelexError base_exceptions.py — error_code, with_error_code(), resolve_error_code(), to_error_report()+ ├── PipelexUnexpectedError → runtime.unexpected+ ├── PipelexConfigError → one of pipelex.config.invalid, .syntax, .file_missing+ ├── PipelexSetupError → inherits its cause's code, else runtime.misconfigured+ ├── SecurityError base_exceptions.py — abstract; the policy refusals never absorbed into a domain answer+ │ ├── UriReadRefusedError / SsrfBlockedError ← security.input_url_refused, or the code the site that knows the URL's author chooses+ │ ├── UnsafeSchemaError → security.schema_refused+ │ └── Jinja2TemplateSecurityError ← the template sandbox's refusal at render time, security.template_refused+ ├── CogtError cogt/exceptions.py — abstract; error_category, provider_metadata+ │ ├── LLMCompletionError ← a set the worker's classification picks from+ │ ├── ImgGenGenerationError ← a set the worker's classification picks from│ └── ... (see worker classification) ...- ├── PipelineExecutionError pipeline/exceptions.py — reports its located root fault, RUNTIME only as a floor+ ├── PipelineExecutionError pipeline/exceptions.py — reports its located root fault and its code└── ... (one exceptions.py per package) ...```-`SecurityError` is the base class of the policy refusals that are never absorbed into a domain answer: `UriReadRefusedError` (a read outside the run's scope), `SsrfBlockedError` (an outbound request the SSRF guard blocks), `UnsafeSchemaError` (a schema carrying Python code-generation extensions) and `Jinja2TemplateSecurityError` (a template the sandbox refuses at render time). The handlers that turn a refusal of the caller's input into a verdict, the bundle-validation cascade and the library load, let a `SecurityError` through as it is, and a host that treats this family alike, a durable-execution plugin marking it non-retryable for instance, names that base class. Not every refusal belongs to it: the template sandbox's render-budget refusal, `Jinja2TemplateBudgetError`, is a `ToolError` in the `input` domain, and `TemplateUrlRefusedError` derives from `PipelexError` directly, also in the `input` domain, so each is handled by its domain like any other refusal of the caller's input.--`PipelineExecutionError`'s `RUNTIME` is deliberately a *floor*, applied only when the cause chain surfaced no domain — so a `CONTENT`-categorized inference failure now reaches the HTTP boundary as `INPUT` / 422 through every wrapping layer instead of being flattened to the wrapper's generic 500. Its identity and message are its root fault's (see [Run Failures: the Root Fault, Located](#run-failures-the-root-fault-located)).+`SecurityError` is the abstract base class of the policy refusals that are never absorbed into a domain answer: `UriReadRefusedError` (a read outside the run's scope), `SsrfBlockedError` (an outbound request the SSRF guard blocks), `UnsafeSchemaError` (a schema carrying Python code-generation extensions) and `Jinja2TemplateSecurityError` (a template the sandbox refuses at render time). The handlers that turn a refusal of the caller's input into a verdict, the bundle-validation cascade and the library load, let a `SecurityError` through as it is, and a host that treats this family alike, a durable-execution plugin marking it non-retryable for instance, names that base class. Not every refusal belongs to it: the template sandbox's render-budget refusal, `Jinja2TemplateBudgetError`, is a `ToolError` coded `pipe.template_budget_exceeded`, and `TemplateUrlRefusedError`, coded `security.method_path_refused`, derives from `PipelexError` directly, so each is handled by its code like any other refusal.### Factory-time vs Runtime| When | What carries metadata | How ||------|----------------------|-----|-| **Class definition** | `error_domain`, `error_category` defaults, `user_action` defaults | Class-level attributes — one source of truth per exception type |-| **Raise time** | Per-instance `error_category`, `user_action`, `provider_metadata` | Constructor args — set by the worker that classified the failure |-| **Report time** | `model`, `provider`, cause-chain fields; `error_domain` on the `CogtError` family | `fill_model_and_provider()` at the worker chokepoint; `InferenceErrorCategory.error_domain` derivation and `_enrich_error_report_from_cause()` on `to_error_report()` |+| **Class definition** | `error_code` (a code, a set, its cause's, or abstract), `error_category` defaults, `user_action` defaults | Class-level attributes — one source of truth per exception type |+| **Raise time** | The code chosen from the class's set, per-instance `error_category`, `user_action`, `provider_metadata` | `with_error_code()` and constructor args — set by the raise site or the worker that classified the failure |+| **Report time** | The resolved code and everything it decides; `model`, `provider`, cause-chain fields | `resolve_error_code()` and `ErrorReport.make_for_code()`; `fill_model_and_provider()` at the worker chokepoint; `_enrich_error_report_from_cause()` on `to_error_report()` |-The "outcome" exceptions (`LLMCompletionError`, `ImgGenGenerationError`, `ExtractJobFailureError`, `SearchJobFailureError`) intentionally carry **no** class-level `error_category` — their category is genuinely per-instance, decided by the worker.+The "outcome" exceptions (`LLMCompletionError`, `ImgGenGenerationError`, `ExtractJobFailureError`, `SearchJobFailureError`) intentionally carry **no** class-level `error_category` — their category and their code are genuinely per-instance, decided by the worker.---@@ -537,10 +522,16 @@ The "outcome" exceptions (`LLMCompletionError`, `ImgGenGenerationError`, `Extracreport = exc.to_error_report() # enriched from the __cause__ chainpayload = report.to_dict() # None-free dict for serialization-# Classify one error as the caller's own fault, where it is raised-raise SomeError(msg).as_caller_fault(user_action=user_action) # input domain, caller-facing++# Declare a class's code, and choose one of its set where it is raised+class SomeError(PipelexError):+ error_code = ErrorCodeSet(default=CoreCode.INPUT_INVALID, others=(CoreCode.INPUT_MISSING,))+++raise SomeError(msg).with_error_code(CoreCode.INPUT_MISSING).as_caller_fault(user_action=user_action) # caller-facing# Consume a report+report.code # "input.missing" — the code decides everything belowreport.http_status # 422 / 429 / 500report.user_action_detail() # free-form advice text, or Nonereport.error_category # "transient" / "capacity" / ...@@ -557,6 +548,10 @@ InferenceErrorCategory.TRANSIENT.is_retryable # True — only TRANSIENT| File | Purpose ||------|---------|| `pipelex/base_exceptions.py` | `PipelexError`, `ErrorReport`, `ErrorDomain`, `ValidationErrorItem`, `error_domain_to_http_status()` |+| `pipelex/errors/error_code_declaration.py` | What a class declares: a code, `ErrorCodeSet`, `InheritsCause`, `ABSTRACT_ERROR` |+| `pipelex/errors/error_codes.py` | `ErrorCode`, `error_code_spec()`: what the registries declare about each code, as generated tables |+| `pipelex/errors/foreign_raises.py` | The scan behind the foreign-raise check |+| `pipelex/errors/retired_error_pages.py` | The static redirects of the retired per-class error pages || `pipelex/errors/registry/pipelex-error-registry.yaml` | The Pipelex error registry, the single source of the `pipelex.` codes; its snapshot, its typed codes (`pipelex_codes.py`) and its pages are generated from it || `pipelex/errors/registry/registry_document.py` | The typed model of an MTHDS error registry, and `load_pipelex_error_registry()` || `pipelex/pipeline/validation_errors.py` | `build_validation_error_items()` — shared CLI/API structured bundle-validation builder |@@ -575,30 +570,34 @@ InferenceErrorCategory.TRANSIENT.is_retryable # True — only TRANSIENT| Scenario | Behavior ||----------|----------|-| Rate limit hit | `TRANSIENT` → retryable; `error_domain = RUNTIME`; transport retry honors `Retry-After` (a provider 429 answers 429 regardless of domain) |-| Quota / billing exhausted | `CAPACITY` → non-retryable; `UserAction(CHECK_BILLING)`; `error_domain = RUNTIME` → HTTP 500 |-| Bad API key | `CONFIGURATION` → non-retryable; `error_domain = CONFIG` → HTTP 500 |-| Model or deployment not found (provider HTTP 404) | Raises a dedicated `*ModelNotFoundError` sibling (`LLMModelNotFoundError`, `ImgGenModelNotFoundError`, `ExtractModelNotFoundError`, `SearchModelNotFoundError`); operator re-raises `PipeOperatorModelAvailabilityError` |-| Model reference unknown to the deck (a method naming `gpt-5.1`, a mistyped `@alias` or `$preset`) | `ModelChoiceNotFoundError` → `CONFIGURATION` category, but `error_domain = INPUT` → **HTTP 422**, and caller-facing under STRICT: the message names the reference and its "Did you mean" suggestions, which are all a caller needs to fix the method |-| Content-policy violation | `CONTENT` → non-retryable; `UserAction(CHANGE_INPUT)`; `error_domain = INPUT` → **HTTP 422** |-| Malformed prompt image / bad prompt parameter | `CONTENT` class-level (`PromptImageFormatError`, `LLMPromptParameterError`, …) → `error_domain = INPUT` → **HTTP 422** |-| Any other provider **HTTP 400** | `CONTENT` → `error_domain = INPUT` → **HTTP 422**. This is the widest reach of the derivation: a 400 covers a context-length overflow and a parameter the model rejects alike, and an engine-side request-construction fault lands here too — reported as the caller's to fix, and absent from the 5xx rate |-| Local file extractor raises a builtin (docling, pypdfium2) | `ValueError` / `RuntimeError` / `FileNotFoundError` → `CONTENT` → `error_domain = INPUT` → **HTTP 422**; `OSError` → `TRANSIENT` (see `_LOCAL_EXTRACT_BY_TYPE_NAME`) |-| A text completion stops at its output limit or context window (`length`, `max_tokens`, `MAX_TOKENS`, an `incomplete` Responses answer at `max_output_tokens`, `model_context_window_exceeded`, `model_length`), with partial or empty text | Every LLM worker reads the stop before returning text and raises `LLMCompletionTruncatedError` → `CONTENT` / `CHANGE_INPUT`, non-retryable; `error_domain = INPUT` → **HTTP 422**, caller-facing under STRICT. The message names the model, the pipe, the stop value, the output tokens used and the `max_tokens` sent, never the partial text. The error's `truncation_limit` tells the output limit from the context window (`model_context_window_exceeded`, `model_length`), and so does its next step: a higher `max_tokens` or a shorter input for the first, a shorter input, a lower reasoning effort or a larger model for the second, never a higher `max_tokens`. A gateway in non-strict mode passing each provider's own value through the completions shape is read the same way, since the classifier reads the union of the provider vocabularies |-| A text completion refused or stopped by a safety filter (`content_filter`, `refusal`, `content_filtered`, `guardrail_intervened`, Gemini's `SAFETY` and its kin), or a Gemini prompt blocked before any candidate (its `prompt_feedback.block_reason`, whatever its value) | `LLMCompletionRefusedError` → `CONTENT` / `CHANGE_INPUT`, non-retryable; `error_domain = INPUT` → **HTTP 422**, caller-facing under STRICT |+| Rate limit hit | `TRANSIENT` → repeated within the run; `provider.rate_limited`, retryable; transport retry honors `Retry-After` (a provider 429 answers 429 whatever the domain) |+| Quota / billing exhausted | `CAPACITY` → not repeated; `UserAction(CHECK_BILLING)`; `provider.quota_exhausted` → HTTP 500 |+| Bad API key | `CONFIGURATION` → not repeated; `provider.credential_refused`, the operator's → HTTP 500 |+| Model or deployment not found (provider HTTP 404) | Raises a dedicated `*ModelNotFoundError` sibling (`LLMModelNotFoundError`, `ImgGenModelNotFoundError`, `ExtractModelNotFoundError`, `SearchModelNotFoundError`) carrying `model.unavailable`, since a method cannot name a provider's raw model id; operator re-raises `PipeOperatorModelAvailabilityError` |+| Model reference unknown to the deck (a method naming `gpt-5.1`, a mistyped `@alias` or `$preset`) | `ModelChoiceNotFoundError` → `CONFIGURATION` category, but the code `model.unknown`, the method's → **HTTP 422**, and caller-facing under STRICT: the message names the reference and its "Did you mean" suggestions, which are all a caller needs to fix the method. A handle the deck serves only as another type of model is `model.capability_unsupported` |+| The deck's own default or override names a model it does not define | `ModelDeckChoiceUnresolvedError`, naming the deck setting: `pipelex.config.invalid`, the deployment's → HTTP 500, redacted, never the caller's `model.unknown`; a bad override is refused when the deck is built |+| Content-policy violation | `CONTENT` → not repeated; `UserAction(CHANGE_INPUT)`; `model.content_refused` → **HTTP 422** |+| Malformed prompt image / bad prompt parameter | `CONTENT` class-level (`PromptImageFormatError`, `LLMPromptParameterError`, …), each with its own code (`input.file_type_unsupported`, `pipe.prompt_empty`, …) |+| Any other provider **HTTP 400** | `CONTENT` / `CHANGE_INPUT`, but `runtime.unexpected` → HTTP 500: a 400 nothing recognises is most likely a request of ours the provider could not take, and only a content-policy signal makes it the caller's `model.content_refused` |+| Local file extractor raises a builtin (docling, pypdfium2) | `FileNotFoundError` → `input.reference_not_found`, `ValueError` / `RuntimeError` → `input.file_unreadable`, both `CONTENT` → **HTTP 422**; `OSError` → `UNKNOWN`, `runtime.unexpected` (see `_LOCAL_EXTRACT_BY_TYPE_NAME`) |+| A text completion stops at its output limit or context window (`length`, `max_tokens`, `MAX_TOKENS`, an `incomplete` Responses answer at `max_output_tokens`, `model_context_window_exceeded`, `model_length`), with partial or empty text | Every LLM worker reads the stop before returning text and raises `LLMCompletionTruncatedError` → `CONTENT` / `CHANGE_INPUT`, not repeated: `model.output_truncated` at the output limit, which the method's `max_tokens` sets, and `model.context_exceeded` at the context window, both the method's → **HTTP 422**, caller-facing under STRICT. The message names the model, the pipe, the stop value, the output tokens used and the `max_tokens` sent, never the partial text. The error's `truncation_limit` tells the output limit from the context window (`model_context_window_exceeded`, `model_length`), and so does its next step: a higher `max_tokens` or a shorter input for the first, a shorter input, a lower reasoning effort or a larger model for the second, never a higher `max_tokens`. A gateway in non-strict mode passing each provider's own value through the completions shape is read the same way, since the classifier reads the union of the provider vocabularies |+| A text completion refused or stopped by a safety filter (`content_filter`, `refusal`, `content_filtered`, `guardrail_intervened`, Gemini's `SAFETY` and its kin), or a Gemini prompt blocked before any candidate (its `prompt_feedback.block_reason`, whatever its value) | `LLMCompletionRefusedError` → `CONTENT` / `CHANGE_INPUT`, not repeated; `model.content_refused` → **HTTP 422**, caller-facing under STRICT || A stop value no provider vocabulary lists | Logged at warning level with the model and the value, and taken as normal: the text is returned. An `incomplete` Responses answer whose reason is missing or unknown is the exception: logged at warning level and taken as a truncation, since the status alone says the text is unfinished || An Anthropic structured generation whose `max_tokens` its structured-output timeout lowers | Sent with the lowered limit; logged at warning level when the pipe set the limit, at debug level when it is the model's default; an error the lowered limit can explain, a structured output that failed validation or came back incomplete once the re-asks are spent, or a timeout, keeps its class and category and ends with a sentence saying the limit was lowered and to what; a rate limit, an authentication failure, an overload, a server error or a lost connection carries no such sentence |-| LLM returns schema-mismatched JSON | `instructor` re-asks; if exhausted → the last `pydantic.ValidationError` → `CONTENT` / `CHANGE_INPUT` → `error_domain = INPUT` → **HTTP 422** |-| The gateway does not allow the model for this account (`model_not_allowed_error`, HTTP 412) | `CONFIGURATION` / `CHANGE_MODEL`, never retried; the advice names the model handle; `error_domain = CONFIG` → HTTP 500 |-| Connection dropped mid-request | `AMBIGUOUS` → non-retryable (outcome unknown); `error_domain = RUNTIME` |-| A step names, in an inline model setting, a model the deck neither defines nor names | `ModelNotFoundError`, classified by the lookup as the caller's: `error_domain = INPUT` → **HTTP 422**, caller-facing under STRICT, with a `CHANGE_MODEL` next step naming the model as the method wrote it and the type of model the step needs. A model the deck itself names but does not serve (a preset or alias on a backend that is not enabled) keeps `CONFIG` → HTTP 500, redacted |-| A `PipeParallel` cannot combine its branch results, or a pipe starts without a required input | The caller's own method or request: `error_domain = INPUT` → **HTTP 422**, caller-facing under STRICT, with a `CHANGE_INPUT` next step |-| Unknown or ambiguous entry `pipe_code` (a CLI argument, a run request's field, the `--pipe` / `pipe_ref` slice selector of bundle validation) | `EntryPipeNotFoundError` / `EntryPipeAmbiguousError` → `UserAction(CHANGE_INPUT)`; `error_domain = INPUT` → **HTTP 422**, and caller-facing under STRICT. The in-body lookups (`get_optional_pipe` / `get_required_pipe`) keep raising the undomained `PipeNotFoundError` / `PipeLibraryError`: a ref written inside a bundle is not the caller's input |-| Wrapper exception (no own category) | Inherits cause's classification via enrichment — including the domain the cause derived |-| A pipe fails during a run | `PipeRouterError` → `PipelineExecutionError`, both reporting the root fault's `error_type` and its own message prefixed with `Pipe '<code>' failed (<path>): `; the classification comes from the chain |+| LLM returns schema-mismatched JSON | `instructor` re-asks; if exhausted → the last `pydantic.ValidationError` → `CONTENT` / `CHANGE_INPUT`, `model.output_schema_mismatch` → **HTTP 422** |+| The gateway does not allow the model for this account (`model_not_allowed_error`, HTTP 412) | `CONFIGURATION` / `CHANGE_MODEL`, never repeated; the advice names the model handle; `model.unavailable` → HTTP 500 |+| Connection dropped mid-request | `AMBIGUOUS` → not repeated (outcome unknown); `provider.outcome_unknown`, whose next step says to check the account, since the lost call may have been billed |+| A step names, in an inline model setting, a model the deck neither defines nor names | `ModelNotFoundError`, which the lookup raises with `model.unknown` as the caller's: **HTTP 422**, caller-facing under STRICT, with a `CHANGE_MODEL` next step naming the model as the method wrote it and the type of model the step needs. A model the deck itself names but does not serve (a preset or alias on a backend that is not enabled) keeps the class's `model.unavailable` → HTTP 500, redacted |+| A `PipeParallel` cannot combine its branch results, or a pipe starts without a required input | The caller's own method or request: `pipe.output_multiplicity`, or `input.missing` at the entry pipe and `pipe.input_unresolved` below it → **HTTP 422**, caller-facing under STRICT, with a `CHANGE_INPUT` next step |+| Unknown or ambiguous entry `pipe_code` (a CLI argument, a run request's field, the `--pipe` / `pipe_ref` slice selector of bundle validation) | `EntryPipeNotFoundError` / `EntryPipeAmbiguousError` → `UserAction(CHANGE_INPUT)`; `request.pipe_not_found`, `request.pipe_unspecified` or `request.pipe_ambiguous` → **HTTP 422**, and caller-facing under STRICT. The in-body lookups (`get_optional_pipe` / `get_required_pipe`) keep raising `PipeNotFoundError` / `PipeLibraryError`, whose codes are the method's: a ref written inside a bundle is not the caller's input |+| A template naming a filter or a test that does not exist, found only when it renders | `Jinja2TemplateInvalidError` at the pipe, naming the filter or test and none of the template: `method.template_invalid` → **HTTP 422**, caller-facing under STRICT, for a method's `PipeCondition` expression, `PipeLLM` prompt or `PipeDocGen` template, and `runtime.unexpected` for one of Pipelex's own templates |+| A URL or a storage key refused by the SSRF guard or the run's read scope | A `security.*` code saying whose the URL was: `security.input_url_refused` for one of the run's inputs, the default when the guard cannot tell, `security.method_url_refused` for one the method names and for a read refused inside a step, whose inputs were authorized when they were normalized, both → **HTTP 422**, and `security.provider_url_refused` for one in a model's generated answer, the runtime's → HTTP 500; a traversal in a storage key the caller supplied is `security.input_path_refused`, which `PipelineInputContentError` takes from its cause |+| A method of the host's own library directories refuses to load | `HostLibraryLoadRefusalError`, `pipelex.config.invalid` → HTTP 500, its message withheld under STRICT; the same refusal in the caller's own content stays the caller's verdict |+| Wrapper exception (no own category) | Takes its cause's code, and its classification via enrichment |+| A pipe fails during a run | `PipeRouterError` → `PipelineExecutionError`, both reporting the root fault's `code` and `error_type` and its own message prefixed with `Pipe '<code>' failed (<path>): `; the classification comes from the chain || A pipe raises a non-Pipelex exception | Located as a `PipelexUnexpectedError` whose message names the original class; redacted under STRICT || Failure on a distributed worker | `ErrorReport` recovered from the transport's serialized details — same classification as local |-| Worker exception with no `ErrorReport` | Synthesized fallback report — `error_domain = RUNTIME` |+| Worker exception with no `ErrorReport` | Synthesized fallback report — `runtime.unexpected` |---diff --git a/docs/under-the-hood/inference-backend-plugins.md b/docs/under-the-hood/inference-backend-plugins.mdindex cff76ce0c..ba7574263 100644--- a/docs/under-the-hood/inference-backend-plugins.md+++ b/docs/under-the-hood/inference-backend-plugins.md@@ -224,6 +224,25 @@ Use `pipelex plugins list` to see every discovered plugin, the entry-point group---+## Declaring the error codes a plugin raises++Every error a plugin raises reports a public registry code, a closed plugin's included: a caller reads the code, its page and its next step whatever plugin raised it. A plugin's error class declares its code as its `error_code`, one code, an `ErrorCodeSet` whose raise sites choose one with `.with_error_code(...)`, or an `InheritsCause` that takes its cause's code, and every code comes from the MTHDS core (`CoreCode`) or from Pipelex's registry (`PipelexErrorCode`). A plugin defines no code of its own. A failure a worker builds by hand with an `InferenceErrorCategory` and no code reports the category's own code (`InferenceErrorCategory.default_error_code`) when no cause carries one, so that a transient failure, which the run repeats, never reports a failure no retry clears.++The plugin also declares, in its `register`, every code its errors can carry:++```python+from mthds.protocol.problem.registry import CoreCode++from pipelex.errors.registry.pipelex_codes import PipelexErrorCode+++def register(self, registrar: PluginRegistrar) -> None:+ registrar.declare_error_codes(codes=(CoreCode.PROVIDER_FAILED, PipelexErrorCode.DOCGEN_PRINT_TIMEOUT, "pipelex.docgen.template_invalid"))+ # ...and the plugin's backends+```++A code is given as its constant or as its string. Each one is parsed at boot, and a code neither registry defines refuses the boot with `PluginErrorCodeNotRegisteredError` (`pipelex.plugin.broken`), naming the plugin and the code, before any of the plugin's codes is bound. A release of the plugin built against codes this Pipelex does not define therefore fails where its operator sees it, never on a caller's run. Several plugins may declare the same code, since a public code means one thing whoever raises it. The registrar keeps the bound codes per plugin in `declared_error_codes`, and the seam belongs to no layer, so a `pipelex.plugins.kernel` plugin declares its codes as an interpreter plugin does.+## The Inference SPIWhat an out-of-tree backend plugin imports *is* the contract. The published surface is listed below, one module per row, grouped by what a plugin does with it. The plugin contract and the worker contracts are what every backend plugin needs; the rest is what a plugin reaching an OpenAI- or Anthropic-compatible service, or a gateway with error codes of its own, builds on.@@ -316,10 +335,13 @@ A worker implements the provider half of a call, `_gen_text` or `_extract_pages`| `parse_retry_after_seconds`, `error_code_from_body_code_first` | `pipelex.cogt.inference.error_classification` | the parsers a distiller of a plain-HTTP failure shares || `extract_gateway_metadata` | `pipelex.cogt.inference.error_classification` | the distiller of a Portkey-substrate failure || `ProviderName` | `pipelex.cogt.inference.provider_name` | which provider a distilled failure reports |-| `classify_inference_error` | `pipelex.cogt.inference.error_classify` | the shared Classify step |-| `InferenceErrorFamily`, `render_inference_error` | `pipelex.cogt.inference.error_render` | the shared Render step |-| `ServiceErrorCode` | `pipelex.cogt.inference.service_error_vocabulary` | one error code a plugin's service emits, contributed through `PluginRegistrar.add_service_error_codes` ([Service Error Codes](service-error-codes.md)) |-| `URLs` | `pipelex.urls` | the public error docs base a plugin error's declared type URI points under |+| `classify_inference_error`, `InferenceErrorFamily`, `ClassificationResult` | `pipelex.cogt.inference.error_classify` | the shared Classify step, called with the family of the failed call (`classify_inference_error(metadata, family=InferenceErrorFamily.LLM)`), which picks the category and the registry code together |+| `render_inference_error` | `pipelex.cogt.inference.error_render` | the shared Render step, which constructs the family's error with the code the Classify step picked |+| `ServiceErrorCode` | `pipelex.cogt.inference.service_error_vocabulary` | one error code a plugin's service emits, with the registry code it reports, contributed through `PluginRegistrar.add_service_error_codes` ([Service Error Codes](service-error-codes.md)) |+| `INFERENCE_FAILURE_CODES` | `pipelex.cogt.exceptions` | the registry codes every family's failure class declares, which a classification and a service error code pick from |+| `CoreCode` | `mthds.protocol.problem.registry` | the MTHDS core's public error codes |+| `PipelexErrorCode` | `pipelex.errors.registry.pipelex_codes` | Pipelex's own public error codes |+| `ErrorCodeSet`, `InheritsCause`, `ABSTRACT_ERROR` | `pipelex.errors.error_code_declaration` | how a plugin's error class declares its code: a set its raise sites choose from, its cause's code, or none for a base never raised |**The runtime a worker runs in**@@ -345,6 +367,7 @@ The SPI is a documented, versioned **module/symbol list** gated by `PLUGIN_API_V| duplicate `sdk` model lister | `DuplicateModelListerError` (names both plugins) || a service error code two plugins contribute | `DuplicateServiceErrorCodeError` (names both plugins) || a service error code the runtime classifies itself | `ReservedServiceErrorCodeError` |+| a declared error code neither the MTHDS core nor Pipelex's registry defines | `PluginErrorCodeNotRegisteredError` (names the plugin and the code) || `name` in `runtime.plugins.disabled` but core-unconditional | `CoreUnconditionalPluginDisabledError` || entry point raises while loading/registering | `BrokenPluginError` || lookup for an unregistered `(family, sdk)` | `InferenceBackendNotFoundError` ("… Is its plugin installed and enabled?") |diff --git a/docs/under-the-hood/pipe-func-requirements.md b/docs/under-the-hood/pipe-func-requirements.mdindex a9481e26d..b469811d3 100644--- a/docs/under-the-hood/pipe-func-requirements.md+++ b/docs/under-the-hood/pipe-func-requirements.md@@ -42,7 +42,7 @@ The file is always named by its path in the method's tree, `requirements.txt`, o## A host's own library directories-A server loads its own library directories (`PIPELEXPATH`, the instance defaults, installed libraries) beside a caller's bundles. A method of those directories whose requirements are not met is the deployment's fault, not the caller's: around such a load, `reporting_host_library_tree_faults` turns the refusal into a `HostLibraryRequirementsError`, a `config`-domain error answered with a `500` whose message, naming paths on the host, never reaches the caller under STRICT disclosure, as it turns a tree it cannot list into a `HostLibraryTreeError`.+A server loads its own library directories (`PIPELEXPATH`, the instance defaults, installed libraries) beside a caller's bundles. A method of those directories whose requirements are not met is the deployment's fault, not the caller's: around such a load, `reporting_host_library_tree_faults` turns the refusal into a `HostLibraryRequirementsError`, carrying `pipelex.config.invalid` and answered with a `500` whose message, naming paths on the host, never reaches the caller under STRICT disclosure, as it turns a tree it cannot list into a `HostLibraryTreeError`. Any other refusal of such a method while it loads becomes a `HostLibraryLoadRefusalError`, carrying `pipelex.config.invalid` too (see [Library Configuration](../configuration/config-technical/library-config.md)).## Where the check runs on a sandbox-hosted deployment@@ -50,7 +50,7 @@ A server loads its own library directories (`PIPELEXPATH`, the instance defaults- **A run** (`/execute`, `/start`) with a `files` or `bundle_b64` bundle, or by `method_ref`, is refused there as a `422` naming each requirement, before the method's files load and before any dispatch.- **A validation by `method_ref`** (`/validate`) is dispatched whole to a validator that never reads the method's Python, a Temporal worker for instance, so `ApiRunner.validate_verdict` returns a refusal as the invalid verdict, one item per line, before the validator is reached. Inline `mthds_contents` carry no Python and are not checked.-- **A directory of the request that cannot be listed** stays the host's fault, a `500` `HostLibraryTreeError`, as the load reports it.+- **A directory of the request that cannot be listed** stays the host's fault, a `500` `HostLibraryTreeError` carrying `pipelex.config.invalid`, as the load reports it.- **The worker** loads the library crate the runner built, which carries the method's Python sources but not its `requirements.txt`, so it never checks anything, and needs to know nothing of the sandbox's packages.## The seam: stating the sandbox's packages@@ -89,10 +89,10 @@ A mode with one fixed package set ignores the requirements and answers its packa- **The request**, `PipeFuncPackageOfferRequest` (`pipelex/plugins/pipe_func_package_offer_registry.py`), carries the `PipeFuncConfig` and `requirements`, every requirement the method's `requirements.txt` declares, in the file's order, each a `RequirementLine` (`pipelex/core/method_trees/requirements_file.py`: its line number, its text as written and the parsed PEP 508 requirement). A plugin judging them against a package set of its own uses Pipelex's judgment, `unmet_requirements` with an `OfferedPackageEnvironment`, so it sets aside exactly what the check would find met.- **The markers are the factory's to evaluate.** The requirements arrive with their markers unevaluated, since Pipelex cannot evaluate a marker before it knows the environment the mode would run the method in. A requirement whose marker is false in that environment is not needed there, and the check skips it, so the factory evaluates the markers against the marker environment of the place it would offer, builds nothing for a requirement the place does not need, and never refuses for one: a refusal rests only on requirements whose markers hold there. `requirements_needed_in` (`pipelex/libraries/method_requirements.py`) picks them out as the check would, keeping a requirement whose marker reads a variable the marker environment does not state, or cannot be evaluated, which the check refuses rather than skips.- **`PipeFuncPackageOffer`** is closed, frozen plain data: `environment`, the place as a refusal names it to the method's author; `distributions`, each distribution's name with its exact installed version, the names compared normalized; and `marker_environment`, the PEP 508 marker values of the sandbox's interpreter. A variable left out of `marker_environment`, such as `python_full_version` when the image pins only its minor version, makes every requirement whose marker reads it refused. Pipelex judges every requirement against the offer, one built for them included, so an offer that does not meet them refuses the method as a fixed package set would, naming each requirement.-- **`PipeFuncPackageRefusal`** is the answer when no environment of the mode can hold the requirements the place needs, such as a version conflicting with a package the sandbox's base pins, or a package with no wheel for the sandbox: `environment`, the place as the refusal names it, and `reason`, the plugin's own words, such as its resolver's explanation. The method is refused with `MethodRequirementsNotMetError`, an `input` fault of the method's whose message, "The method needs Python packages that the Example sandbox cannot offer, as its requirements.txt declares: …", carries the reason, with one item on the file and no line, since the reason is about the requirements together. The reason reaches the method's author, a server's caller included, so it names no path on the host.+- **`PipeFuncPackageRefusal`** is the answer when no environment of the mode can hold the requirements the place needs, such as a version conflicting with a package the sandbox's base pins, or a package with no wheel for the sandbox: `environment`, the place as the refusal names it, and `reason`, the plugin's own words, such as its resolver's explanation. The method is refused with `MethodRequirementsNotMetError`, a fault of the method's carrying `method.dependency_missing`, whose message, "The method needs Python packages that the Example sandbox cannot offer, as its requirements.txt declares: …", carries the reason, with one item on the file and no line, since the reason is about the requirements together. The reason reaches the method's author, a server's caller included, so it names no path on the host.- **The factory is synchronous, and caching by the requirements is the plugin's job.** The check runs inside the library load, which is synchronous and runs on whatever thread its caller runs it on: a worker thread for the API server's check of a served method, and the thread of a running event loop for a load inside an asynchronous run or validation. An asynchronous factory could not be awaited there without blocking that same thread, so it would buy nothing short of making every load asynchronous. Pipelex calls the factory for each tree declaring requirements each time a check judges it, never at registration, and keeps none of its answers, so a load that judges a tree at more than one of its steps asks again. A factory whose answer takes time, such as one resolving the requirements with `uv`, which takes seconds the first time, bounds the work with a timeout of its own and caches its answers by the requirements' texts, so only a process's first check of a requirement set pays for it: on the API server, the check of a served method runs first, off the event loop, and the load after it reads the cache. A factory may be called on a thread running an event loop, so it never calls `asyncio.run`.- **A fault of the plugin's own is not a refusal.** A resolver the plugin cannot reach, or one outlasting its timeout, says nothing about the method: the factory raises it as an error of the plugin's, which Pipelex lets through, rather than answering a `PipeFuncPackageRefusal`, which would blame the method's author.-- **It fails closed.** A mode with no registered offer, or whose factory answers `None`, meets no requirement: a method declaring one is refused with `PipeFuncPackageSetUnstatedError`, a `config`-domain fault of the deployment whose message is not caller-facing, rather than loading and failing inside the sandbox at its first import. Its message says which of the two happened: no plugin registers an offer for the mode, or the registered one could not state the packages, whose remedy is in the plugin's configuration. A method declaring none still loads.+- **It fails closed.** A mode with no registered offer, or whose factory answers `None`, meets no requirement: a method declaring one is refused with `PipeFuncPackageSetUnstatedError`, a fault of the deployment carrying `runtime.misconfigured`, whose message is not caller-facing, rather than loading and failing inside the sandbox at its first import. Its message says which of the two happened: no plugin registers an offer for the mode, or the registered one could not state the packages, whose remedy is in the plugin's configuration. A method declaring none still loads.- **It is interpreter-layer**, like `add_pipe_func_executor`: a plugin published under `pipelex.plugins.kernel` that calls it is refused with `PluginLayerViolationError`. A second plugin stating the same mode is refused with `DuplicatePipeFuncPackageOfferError`, naming both.`Pipelex.setup` builds the `PipeFuncPackageOfferRegistry` from the registrar beside the `PipeFuncExecutorRegistry` and puts it on the `InterpreterHub` (`get_pipe_func_package_offer_registry`).@@ -103,11 +103,11 @@ For the hosted API, the Daytona sandbox plugin states the package set of the Day## Errors-| Error | Domain | When |+| Error | Code | When || --- | --- | --- |-| `MethodRequirementsFileError` | `input` | The file holds a line the standard refuses, naming each, or is not UTF-8 text. |-| `MethodRequirementsNotMetError` | `input` | The environment does not meet a requirement, naming each and why, or the deployment refuses the requirements with its own reason, no environment it can build holding them. |-| `HostLibraryRequirementsError` | `config` | A method of a host's own library directories, loaded beside a caller's bundles, is refused for its requirements. |-| `PipeFuncPackageSetUnstatedError` | `config` | A sandbox-hosted deployment states no package set for its execution mode. |+| `MethodRequirementsFileError` | `method.package_invalid` | The file holds a line the standard refuses, naming each, or is not UTF-8 text. |+| `MethodRequirementsNotMetError` | `method.dependency_missing` | The environment does not meet a requirement, naming each and why, or the deployment refuses the requirements with its own reason, no environment it can build holding them. |+| `HostLibraryRequirementsError` | `pipelex.config.invalid` | A method of a host's own library directories, loaded beside a caller's bundles, is refused for its requirements. |+| `PipeFuncPackageSetUnstatedError` | `runtime.misconfigured` | A sandbox-hosted deployment states no package set for its execution mode. |The first two are `LibraryLoadingError`s carrying one blueprint validation item per line, whose `source` is the file's path in the tree and whose `line` is the line's number, so a validation reports them as an invalid verdict located on the line. They are deliberately not `MethodTreeLoadError`s, which a server reports as its own fault around the library directories it loads.diff --git a/docs/under-the-hood/pipelex-kernel.md b/docs/under-the-hood/pipelex-kernel.mdindex fe2bfc353..3cec653f0 100644--- a/docs/under-the-hood/pipelex-kernel.md+++ b/docs/under-the-hood/pipelex-kernel.md@@ -32,7 +32,7 @@ That boot stands up the model deck, the content generator, the class registry, t**`user_id` and `storage_scope` are both required, with no default.** `user_id` is who the run is attributed to; `storage_scope` is the opaque prefix every byte the run writes lands under, composed by *you* from whatever your tenancy model is (`"<org>/<run>"`, `"<customer>/<job>"`, or a flat name for a single-tenant service). The kernel composes its own leaves onto it and never parses it, so it never learns what a tenant is: `assets/` for what you supplied, `generated/` for what the run produced, `results/` for the delivered envelope, and `payloads/` for transport spill. It is validated at construction — one to three path-safe segments — because the value becomes a storage key prefix and a `..` in it would escape the namespace. Neither field defaults, deliberately: a missing identity used to fall back to the tracing placeholder `"anonymous"`, which then became the key prefix, pointing every unauthenticated run at one shared namespace.-**`read_scope` is required too, and `None` is a value you pass, not a default.** It bounds what the run may read: every `pipelex-storage://` key a step reads must lie under it, compared segment by segment, and no step reads a bare path or a `file://` URI from the local disk. `https://` and `data:` URLs are untouched. A value can carry any URL its method or its model chose, so the check runs where values are read, in every content-generation leaf before the dry-run branch, and `shape_inputs` applies it to a table given as a CSV input, which is always a local file. The storage scope must lie under the read scope, since a run reads its own outputs back, and a mismatch is refused at construction. A multi-tenant host passes its tenant's prefix (the hosted platform passes the organization id); `None` is the explicit statement that the run is unscoped, which is the truth for a single-tenant service or a laptop. It has no default for the storage scope's reason: a host that forgot it would run unscoped, and an unscoped run reads every key the process's credentials reach. A refused read raises `UriReadRefusedError`, a caller-facing input error that names where the URL sat and never quotes it.+**`read_scope` is required too, and `None` is a value you pass, not a default.** It bounds what the run may read: every `pipelex-storage://` key a step reads must lie under it, compared segment by segment, and no step reads a bare path or a `file://` URI from the local disk. `https://` and `data:` URLs are untouched. A value can carry any URL its method or its model chose, so the check runs where values are read, in every content-generation leaf before the dry-run branch, and `shape_inputs` applies it to a table given as a CSV input, which is always a local file. The storage scope must lie under the read scope, since a run reads its own outputs back, and a mismatch is refused at construction. A multi-tenant host passes its tenant's prefix (the hosted platform passes the organization id); `None` is the explicit statement that the run is unscoped, which is the truth for a single-tenant service or a laptop. It has no default for the storage scope's reason: a host that forgot it would run unscoped, and an unscoped run reads every key the process's credentials reach. A refused read raises `UriReadRefusedError`, a caller-facing error with the code `security.input_url_refused` that names where the URL sat and never quotes it.`needs_inference=False` boots keyless (every enabled backend and model loaded, no credential resolved, no model-deck validation) and sets the forced-DRY flag: every run the process initiates is coerced to `run_mode=DRY`, so the leaves mock instead of calling a provider. `PipelexKernel.make` applies that rule through the same `runtime_hub.resolve_effective_run_mode` the pipe tier uses, which refuses `is_mock_usage` on a live request before it coerces — a second copy of the rule at a second factory is how the two would drift apart.@@ -88,9 +88,11 @@ Both façade calls take the concept and the output class the caller wants, defauThe two operator-specific `assemble_*` functions are there because `run_llm_text` and `run_img_gen` both take a *ready* prompt. A caller that could not build one would be holding an operator it cannot reach, which is what image generation was until `assemble_img_gen_prompt` existed: its only builder was an interpreter-layer blueprint. Both are thin over `pipelex.kernel.prompt_assembly`, the user-prompt assembly PipeLLM, PipeImgGen and PipeJudge share. It owns the part a caller must not re-derive: resolving `ImageReference` and `DocumentReference` out of working memory, numbering the files they name, substituting the `[Image N]` and `[Document N]` tokens for direct, list and dotted references, and handing the files over in the order their tokens number them, since a mismatch mislabels which file the prompt is describing and nothing downstream can detect it. `assemble_user_prompt` assembles one template into an `AssembledUserPrompt`, its text with its ordered images and documents; `PromptFiles` is the same numbering shared by several templates of one prompt, a PipeLLM's system and user prompts or a PipeImgGen's positive and negative ones, whose references are all registered before the first renders so their tokens number one sequence. A reference whose root input is declared optional and was not given is skipped before numbering, taking no number and handing over no file, so the template's guard renders it out, while an absent required input is refused; the reference carries `is_optional`, which the factories set through the one analysis they share, `analyze_template_file_references` in `pipelex.pipe_operators.shared`, and the context answers presence through `ContextProviderAbstract.is_variable_present`. The caller's `extra_params` are copied, never written to.+The `resolve_*_setting` functions, and `judgment_setting_of_choice`, walk the deck chain: the step's own choice, then the deck's override where the family has one, then the deck's default. Whose fault a miss is follows the rung that missed. A choice the step names that the deck does not resolve is the method's, `ModelChoiceNotFoundError` with `model.unknown`, caller-facing; a bare handle the deck serves only as another model type is `model.capability_unsupported`. An override or a default the deck names that it does not resolve is the deployment's, which a caller cannot fix by changing their input: `ModelDeckChoiceUnresolvedError`, naming the deck setting, such as `extract.choice_default`, with `model.unavailable` for a bare handle no backend serves and `pipelex.config.invalid` for a preset, an alias or a waterfall the deck does not define. The deck refuses an override that does not resolve when it loads, and a default when a step first runs on it, or, for a `PipeJudge` naming no model, when its method loads, where the operator lets the error through rather than locating it on the pipe as the method's unknown model.+`served_llm_model` gives the spec of the LLM a handle resolves to on this boot, an alias to its target and a waterfall to its first served member as a run resolves them, or `None` when no backend serves one. `check_llm_setting_with_served_model` refuses an LLM setting the model it resolves to refuses, before anything is spent: it runs the request check the model's backend registered beside its worker factory, which is the check the worker itself runs before every call, against the job params the setting gives once the model's constraints apply, for a text or a structured output. For a built-in backend it raises an `LLMSettingRefusedError`, an `LLMCapabilityError` carrying the worker's reason with the model named by its deck handle rather than by the SDK, backend and provider model id the worker's own refusal names, so its message is shown to a caller even under strict error disclosure. An external plugin's refusal is raised as the plugin wrote it, and its message reaches a caller only when the plugin raised it as caller-facing copy. A backend that registered no check is held to the rule every worker shares, that a model whose spec declares `thinking_mode = "none"` takes no reasoning setting, and a model no backend serves, or whose backend's SDK is not installed, is left to the run. The interpreter's `PipeLLM` and `PipeStructure` call it when a method loads; a programmatic caller calls it before `run_llm_text` or `run_llm_object` to get the same refusal without a call.-`run_judgment` asks one question about the evidence of a prompt. It takes the step's evidence template as a `UserPromptContent`, the same carrier a PipeLLM's user prompt travels in, and assembles it through `assemble_user_prompt`, so the evidence is rendered, and its images and documents numbered into `[Image N]` and `[Document N]` tokens, exactly as a PipeLLM's prompt is; the text and the ordered files become the `JudgmentPrompt` the worker receives. The question arrives as the cogt question with its instructions still a template, rendered against memory as a `BASIC` template, and is sent as the job's only question, under one fixed key. An optional input that holds no value renders as the template's guard says, through `@?name` or a Jinja2 test, and the shared assembly skips its files, as it does for every operator. A refusal is a worker outcome like an answer, and `run_judgment`'s policy for it is to fail: one question has nowhere to leave its verdict absent, so it raises `JudgmentRefusedError`, a content error naming the step and the model. The `JudgmentResult` carries the prompt sent and the rendered question beside the verdict, which is what the operator records as its execution data. `run_multi_judgment` asks several questions about one evidence, in one request, and fills a structure with their verdicts. The evidence is assembled and each question rendered as `run_judgment` does, and the questions travel as `AskedQuestion`s, each a cogt question beside the threshold its yes/no verdict reads its probability against, keyed by name in one job. A question's name is also the name of the field holding its verdict in `output_class`, the output's content class, which the caller resolves and hands down, as `run_llm_object` takes its output class, since the kernel does not read the concept library; a class whose fields are not exactly the questions' names is refused with `JudgmentOutputFieldsError`, a `ValueError` raised before the judging model is called. Each answer becomes its verdict native under `make_verdict_content`'s rules, and the verdicts are handed to the class as plain data keyed by field name, whatever alias a field carries, so a field typed by a concept refining the native is built as that concept's class. A refusal stores nothing in its question's field when that field may hold nothing, by `class_field_may_hold_nothing` (`pipelex.core.stuffs.non_null_any`), the rule the load's concept walk reads a class field by too: its type admits `None`, whether it is required or has a default, or it is neither required nor given a default. A field whose type admits `None` is given it outright, so a required one validates and a defaulted one does not fill in its default. The refusal is logged as a warning naming the question and recorded in the result; behind any other field it raises `JudgmentRefusedError`, which then names the question too, since leaving a defaulted field out would fill in its default, a verdict nobody gave. The `MultiJudgmentResult` carries the prompt sent and, per question, a `QuestionJudgment`: the rendered question, the raw outcome, a refusal included, and whether a threshold decided the verdict. A dry run answers every question and never refuses. `make_verdict_content` turns the answer into the verdict native: a yes/no answer's probability decides the verdict against the step's threshold, inclusive, or against 0.5 when none is declared; an answer with no probability keeps the model's own verdict, and when a threshold was declared a live run logs a warning and its `JudgmentResult` reports `threshold_applied` as false. A rating takes the label of the level the answer names off the scale the question declared, since no backend reports one, a dry run included, and its distribution is keyed by the level index written as text. `judgment_setting_of_choice` gives the setting of the step's model, else of the deck's default, and raises `JudgmentModelMissingError` when neither names one, since the deck serves none by default. `served_judgment_model` gives the spec of the model a handle resolves to on this boot, or `None` when no backend serves one, a waterfall none of whose models is served included. `resolve_judgment_setting` then pins the setting to the handle the model resolves to; on a dry run, a model no backend serves on this boot keeps the deck's handle, since no judging worker is called.+`run_judgment` asks one question about the evidence of a prompt. It takes the step's evidence template as a `UserPromptContent`, the same carrier a PipeLLM's user prompt travels in, and assembles it through `assemble_user_prompt`, so the evidence is rendered, and its images and documents numbered into `[Image N]` and `[Document N]` tokens, exactly as a PipeLLM's prompt is; the text and the ordered files become the `JudgmentPrompt` the worker receives. The question arrives as the cogt question with its instructions still a template, rendered against memory as a `BASIC` template, and is sent as the job's only question, under one fixed key. An optional input that holds no value renders as the template's guard says, through `@?name` or a Jinja2 test, and the shared assembly skips its files, as it does for every operator. A refusal is a worker outcome like an answer, and `run_judgment`'s policy for it is to fail: one question has nowhere to leave its verdict absent, so it raises `JudgmentRefusedError`, a content error naming the step and the model. The `JudgmentResult` carries the prompt sent and the rendered question beside the verdict, which is what the operator records as its execution data. `run_multi_judgment` asks several questions about one evidence, in one request, and fills a structure with their verdicts. The evidence is assembled and each question rendered as `run_judgment` does, and the questions travel as `AskedQuestion`s, each a cogt question beside the threshold its yes/no verdict reads its probability against, keyed by name in one job. A question's name is also the name of the field holding its verdict in `output_class`, the output's content class, which the caller resolves and hands down, as `run_llm_object` takes its output class, since the kernel does not read the concept library; a class whose fields are not exactly the questions' names is refused with `JudgmentOutputFieldsError`, raised before the judging model is called with `runtime.unexpected`, since a method's judge has its output checked when it loads and only a programmatic caller can break this contract. Each answer becomes its verdict native under `make_verdict_content`'s rules, and the verdicts are handed to the class as plain data keyed by field name, whatever alias a field carries, so a field typed by a concept refining the native is built as that concept's class. A refusal stores nothing in its question's field when that field may hold nothing, by `class_field_may_hold_nothing` (`pipelex.core.stuffs.non_null_any`), the rule the load's concept walk reads a class field by too: its type admits `None`, whether it is required or has a default, or it is neither required nor given a default. A field whose type admits `None` is given it outright, so a required one validates and a defaulted one does not fill in its default. The refusal is logged as a warning naming the question and recorded in the result; behind any other field it raises `JudgmentRefusedError`, which then names the question too, since leaving a defaulted field out would fill in its default, a verdict nobody gave. The `MultiJudgmentResult` carries the prompt sent and, per question, a `QuestionJudgment`: the rendered question, the raw outcome, a refusal included, and whether a threshold decided the verdict. A dry run answers every question and never refuses. `make_verdict_content` turns the answer into the verdict native: a yes/no answer's probability decides the verdict against the step's threshold, inclusive, or against 0.5 when none is declared; an answer with no probability keeps the model's own verdict, and when a threshold was declared a live run logs a warning and its `JudgmentResult` reports `threshold_applied` as false. A rating takes the label of the level the answer names off the scale the question declared, since no backend reports one, a dry run included, and its distribution is keyed by the level index written as text. `judgment_setting_of_choice` gives the setting of the step's model, else of the deck's default, and raises `JudgmentModelMissingError` when neither names one, since the deck serves none by default. `served_judgment_model` gives the spec of the model a handle resolves to on this boot, or `None` when no backend serves one, a waterfall none of whose models is served included. `resolve_judgment_setting` then pins the setting to the handle the model resolves to; on a dry run, a model no backend serves on this boot keeps the deck's handle, since no judging worker is called.A PipeJudge records these results as its execution data, kept per question. A step asking one question records its rendered question, its kind as text, its threshold, whether the threshold decided the verdict and the model's raw answer at the top level, beside the rendered prompt and the resolved model. A step asking several records the rendered prompt and the model there too, and nests the rest under `questions`, keyed by each question's name, as `rendered_question`, `judgment_kind`, `threshold`, `threshold_applied` and `outcome`, the outcome being the raw answer or the refusal, since a field holding nothing shows nothing of what the model said.@@ -175,7 +177,7 @@ A caller can scope the event log instead of registering it: under `with scoped_eThe trace context also states the chain of execution attempts its events belong to, required as the mode is, since every usage event takes its execution, its attempt and its lineage from it (see [Executions and Their Attempts](execution-graph-tracing.md#executions-and-their-attempts)). A host running the kernel in its own process states `make_direct_chain()`, the direct mode's one execution in its first attempt. A host running it inside a durable workflow states that workflow's own chain, its lineage followed by its id and the attempt its engine runs, so that the usage of a new attempt supersedes the earlier one's, where both would otherwise be written as `direct@1`.-The trace context states the mode the run takes, which `resolve_effective_run_mode` gives: every usage event a step writes states the context's `run_mode`, so a context saying live for a run whose steps run dry would stamp the whole run live. `PipelexKernel.make` refuses a context stating another mode with `TraceContextRunModeError` (`pipelex/kernel/exceptions.py`), a `ValueError` raised before any step runs. It refuses rather than correct its own copy because the trace is the caller's, possibly shared with writers the kernel never sees, which a corrected copy would leave disagreeing with the kernel's events.+The trace context states the mode the run takes, which `resolve_effective_run_mode` gives: every usage event a step writes states the context's `run_mode`, so a context saying live for a run whose steps run dry would stamp the whole run live. `PipelexKernel.make` refuses a context stating another mode with `TraceContextRunModeError` (`pipelex/kernel/exceptions.py`), raised before any step runs with `runtime.unexpected`, since the caller handing it the context is the host integration. It refuses rather than correct its own copy because the trace is the caller's, possibly shared with writers the kernel never sees, which a corrected copy would leave disagreeing with the kernel's events.Passing a `trace_context` adopts its `graph_id` as the run's `pipeline_run_id`, and passing a `pipeline_run_id` that differs from it raises `ValueError` rather than letting either win. The two are one identity: letting them diverge would scatter a single run's usage events across two ids, because the registered-context emit path stamps the event log's id while the scoped event log and the runner fallback stamp the metadata's — and a read-back keyed on either would silently miss the other's.@@ -205,6 +207,6 @@ with kernel.log_context():Two arms of the interpreter stayed interpreter-side, both because moving them would cost more than the caller gains:- **`PipeCompose`'s construct mode.** Its semantics are `StructuredContentComposer` over a `ConstructBlueprint`, and a blueprint is an MTHDS language artifact with a language-side consumer. A programmatic caller holds real Python and builds its structured object directly rather than describing the construction declaratively. The template path *is* fully extracted, and the one thing both paths share — the three-layer context ordering — is single-sourced in `build_compose_context`.-- **`PipeFunc`'s pluggable executor seam.** The protocol and its DTOs are typed on interpreter models (`PipeRunParams`, `LibraryCrate`), so the kernel cannot name them. What running a function *means* — async-vs-sync dispatch and content coercion — is single-sourced in `call_function`, which both the in-process executor and the kernel's `run_func` ride. Finding the function is not the kernel's: a `PipeFunc` step imports it by its import path from its method tree, which is a library's business, so `run_func` takes the function itself, as every other op takes resolved values. What stays outside is *where* the function runs, which is configured deployment machinery rather than operator semantics. So a kernel `run_func` always runs in this process.+- **`PipeFunc`'s pluggable executor seam.** The protocol and its DTOs are typed on interpreter models (`PipeRunParams`, `LibraryCrate`), so the kernel cannot name them. What running a function *means* — async-vs-sync dispatch and content coercion — is single-sourced in `call_function`, the composition of `invoke_function` and `coerce_function_output`, which the kernel's `run_func` rides; the in-process executor calls the two apart, so that only the call itself is the function's failure. A function that returns something other than a stuff content, a list of them or a string fails the step with `FuncOutputTypeError`, `pipe.output_invalid`, a list holding anything else included: the function is the method's, so its output is what failed. Finding the function is not the kernel's: a `PipeFunc` step imports it by its import path from its method tree, which is a library's business, so `run_func` takes the function itself, as every other op takes resolved values. What stays outside is *where* the function runs, which is configured deployment machinery rather than operator semantics. So a kernel `run_func` always runs in this process.Beyond those: controllers are out of scope entirely (`pipelex/pipe_controllers/` is the interpreter's), the kernel is not separately installable from PyPI, and "activity-shaped" is a design constraint on the call signatures rather than a distributed-execution deliverable.diff --git a/docs/under-the-hood/service-error-codes.md b/docs/under-the-hood/service-error-codes.mdindex 00f07ad24..2f924b192 100644--- a/docs/under-the-hood/service-error-codes.md+++ b/docs/under-the-hood/service-error-codes.md@@ -14,6 +14,8 @@ The plugin that speaks to such a service knows its codes, so the plugin contribuA plugin declares each code its service emits as a `ServiceErrorCode` (`pipelex.cogt.inference.service_error_vocabulary`) and hands them to the registrar in its `register`:```python+from mthds.protocol.problem.registry import CoreCode+from pipelex.cogt.exceptions import InferenceErrorCategoryfrom pipelex.cogt.inference.error_classification import UserActionKindfrom pipelex.cogt.inference.service_error_vocabulary import ServiceErrorCode@@ -24,12 +26,14 @@ ACME_ERROR_CODES = (ServiceErrorCode(code="acme_body_too_large",category=InferenceErrorCategory.CONTENT,+ error_code=CoreCode.INPUT_TOO_LARGE,user_action_kind=UserActionKind.CHANGE_INPUT,detail="The request was too large for the Acme gateway — send less in one call, or use smaller inputs.",),ServiceErrorCode(code="acme_unknown_model",category=InferenceErrorCategory.CONFIGURATION,+ error_code=CoreCode.MODEL_UNAVAILABLE,user_action_kind=UserActionKind.CHANGE_MODEL,detail="The Acme gateway does not serve that model — pick a model this deployment serves.",is_model_not_found=True,@@ -46,19 +50,20 @@ class AcmePlugin:# ...and the plugin's inference backends```-Each entry says four things about one code:+Each entry says, about one code:| Field | Meaning ||-------|---------|| `code` | the code as the service puts it on the wire, which the worker's Extract step recovers into `ProviderErrorMetadata.provider_error_code` |-| `category` | the `InferenceErrorCategory`, which decides whether the error is retried and the HTTP status it answers on a server |+| `category` | the `InferenceErrorCategory`, which decides whether the call is repeated within the run |+| `error_code` | the public registry code the rendered error reports, which decides its domain, the HTTP status it answers on a server and whether its report invites a retry. It is one of the codes every family's failure class declares (`INFERENCE_FAILURE_CODES` in `pipelex.cogt.exceptions`) || `user_action_kind` | the kind of advice the caller gets || `detail` | the advice itself, rendered beside the service's own message: what the caller, or whoever operates the service, should do. The service's message already names the specifics, so the advice need not repeat them |-| `is_model_not_found` | set for a code that means the service does not know the model at all: it selects the family's `*ModelNotFoundError` class, which the pipe layer re-raises as a model-availability error carrying the model handle |+| `is_model_not_found` | set for a code that means the service does not know the model at all: it selects the family's `*ModelNotFoundError` class, which the pipe layer re-raises as a model-availability error carrying the model handle, and its `error_code` is then `model.unavailable` |## How the runtime reads them-At boot, every plugin's contributions are frozen into one `ServiceErrorVocabulary` on the runtime hub. `classify_inference_error` consults it first, ahead of the quota rules and the status ladder, for any failure that reached an HTTP status: a code the vocabulary knows decides the category, the action and the model-not-found flag, and `render_inference_error` renders the entry's advice. A code nobody contributed, and every failure in a process that registered none, classifies on the status ladder as before.+At boot, every plugin's contributions are frozen into one `ServiceErrorVocabulary` on the runtime hub. `classify_inference_error` consults it first, ahead of the quota rules and the status ladder, for any failure that reached an HTTP status: a code the vocabulary knows decides the category, the registry code, the action and the model-not-found flag, and `render_inference_error` constructs the family's error with that registry code and renders the entry's advice. A code nobody contributed, and every failure in a process that registered none, classifies on the status ladder as before.**Codes are matched on the code alone, with no check on the provider.** A request reaches a service through whichever SDK its protocol calls for, so the provider a failure reports does not identify the service; the code does. A plugin that contributes a code vouches that no vendor emits it, which in practice means the codes live in a namespace of the service's own.@@ -68,6 +73,7 @@ At boot, every plugin's contributions are frozen into one `ServiceErrorVocabular| Condition | Error ||-----------|-------|+| an entry whose `error_code` no family's failure class declares, a model-not-found entry whose `error_code` is not `model.unavailable`, or a `TRANSIENT` entry whose `error_code` does not invite a retry | a validation error when the plugin builds the entry, at import || two plugins contribute the same code | `DuplicateServiceErrorCodeError`, naming both plugins || a plugin contributes a code the runtime classifies itself (`model_not_allowed_error`, see the [Error Model](error-model.md#a-model-the-integration-does-not-allow)) | `ReservedServiceErrorCodeError` |diff --git a/docs/under-the-hood/template-sandbox.md b/docs/under-the-hood/template-sandbox.mdindex b22e90bd3..a09804a62 100644--- a/docs/under-the-hood/template-sandbox.md+++ b/docs/under-the-hood/template-sandbox.md@@ -42,11 +42,15 @@ A method template renders without a template loader, so `{% include %}`, `{% extMany refusals are visible in the template itself, and validation reports them before anything runs: a template that reads an undeclared underscore name with a dot fails with the `template_private_name` validation error, which names the pipe and the template (`prompt`, `system_prompt`, `template`, `expression`, or `construct field '<path>'`).-What validation cannot see, because it depends on the values at run time (a method call, a name computed while rendering, or a bracketed key, which is legitimate on a plain dict), is refused where it happens: the render raises `Jinja2TemplateSecurityError`, whose message names the refused attribute or callable and the type it was reached on. A refusal never renders as an empty string, so a prompt is never sent with a hole in it.+What validation cannot see, because it depends on the values at run time (a method call, a name computed while rendering, or a bracketed key, which is legitimate on a plain dict), is refused where it happens: the render raises `Jinja2TemplateSecurityError`, with the code `security.template_refused`, whose message names the refused attribute or callable and the type it was reached on. A refusal never renders as an empty string, so a prompt is never sent with a hole in it.-`Jinja2TemplateSecurityError` is a `SecurityError`, like `UriReadRefusedError`, `SsrfBlockedError` and `UnsafeSchemaError`, the other policy refusals that are never absorbed into a domain answer. A host that treats that family alike, never retrying any of it, catches that base class, and an `except ToolError` around a render does not catch this refusal. The sandbox's budget refusal is a separate error, `Jinja2TemplateBudgetError`, which is a `ToolError` in the input domain (see below). `Jinja2TemplateSecurityError` stays a type of its own, apart from `Jinja2TemplateRenderError`, which a template that fails for any other reason raises.+`Jinja2TemplateSecurityError` is a `SecurityError`, like `UriReadRefusedError`, `SsrfBlockedError` and `UnsafeSchemaError`, the other policy refusals that are never absorbed into a domain answer. A host that treats that family alike, never retrying any of it, catches that base class, and an `except ToolError` around a render does not catch this refusal. The sandbox's budget refusal is a separate error, `Jinja2TemplateBudgetError`, which is a `ToolError` (see below). `Jinja2TemplateSecurityError` stays a type of its own, apart from `Jinja2TemplateRenderError`, which a template that fails for any other reason raises.-A render that would overdraw its budget raises `Jinja2TemplateBudgetError`, in the input domain, whose message names the operation that was refused and what it would have spent, never the template or a value: for example, *the operator '\*' needs about 1,000,000,000, and 134,217,062 are left*. A template whose macros or includes nest deeper than Python allows raises the same error.+A render that would overdraw its budget raises `Jinja2TemplateBudgetError`, with the code `pipe.template_budget_exceeded`, whose message names the operation that was refused and what it would have spent, never the template or a value: for example, *the operator '\*' needs about 1,000,000,000, and 134,217,062 are left*. A template whose macros or includes nest deeper than Python allows raises the same error.++A template that names a filter or a test Jinja2 does not know inside a conditional branch compiles, and only the render of that branch finds the name. The render raises `Jinja2TemplateInvalidError`, with the code `method.template_invalid`, whose message names the unknown name and never quotes the template. A `PipeCondition` expression and a `PipeLLM` prompt answer it as a fault of the method, located on the pipe and the field, with a next step that survives STRICT disclosure.++These codes describe a template of the method, which is the caller's to fix and which an API answers with HTTP 422. A template Pipelex itself renders, such as one of its own prompts, is no fault of the caller's: the same refusals take `runtime.unexpected` there, and a budget overdrawn on the caller's data takes `input.too_large`.## How it is built@@ -101,3 +105,4 @@ A method also writes dotted paths that are not templates: a PipeCompose construc- [StuffArtefact & Image Rendering](stuffartefact-and-image-rendering.md): how inputs reach templates, and how images are extracted from them.- `Jinja2TemplateSecurityError`: the error a refusal raises at render time.- `Jinja2TemplateBudgetError`: the error a render raises when it would overdraw its budget.+- `Jinja2TemplateInvalidError`: the error a render raises when a template names a filter or a test that does not exist, or cannot otherwise render as written.diff --git a/mkdocs.yml b/mkdocs.ymlindex c32b7bb44..a2f76051c 100644--- a/mkdocs.yml+++ b/mkdocs.yml@@ -201,6 +201,395 @@ plugins:'home/9-tools/cli/validate.md': 'tools/cli/validate.md''home/9-tools/logging.md': 'tools/logging.md''home/9-tools/plxt.md': 'tools/plxt.md'+ # BEGIN retired error class pages+ # The retired per-class error pages, each sent to the page of its class's code: the default of a set, the+ # fallback of a class that takes its cause's code, or the error codes' index for a class abstract or gone.+ # The keys are the closed set of retired pages; the targets are generated by `make generate-error-identity`.+ 'errors/ambiguous-inputs-files-error.md': 'https://mthds.ai/errors/request.invalid'+ 'errors/anthropic-factory-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/anthropic-model-listing-error.md': 'https://mthds.ai/errors/provider.response_invalid'+ 'errors/anthropic-sdk-unsupported-error.md': 'https://mthds.ai/errors/runtime.unsupported'+ 'errors/anthropic-worker-configuration-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/argument-type-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/async-execution-not-enabled-error.md': 'https://mthds.ai/errors/runtime.unsupported'+ 'errors/authoring-and-language.md': 'errors/index.md'+ 'errors/auto-detected-inputs-file-error.md': 'https://mthds.ai/errors/request.invalid'+ 'errors/aws-credentials-error.md': 'errors/pipelex/config/credential_missing.md'+ 'errors/azure-credentials-error.md': 'errors/pipelex/config/credential_missing.md'+ 'errors/batch-params-error.md': 'errors/index.md'+ 'errors/bedrock-factory-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/bedrock-worker-configuration-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/binding-path-unresolved-error.md': 'https://mthds.ai/errors/method.field_path_unresolved'+ 'errors/binding-step-run-error.md': 'https://mthds.ai/errors/pipe.binding_failed'+ 'errors/broken-plugin-error.md': 'errors/pipelex/plugin/broken.md'+ 'errors/bundle-elaborator-error.md': 'https://mthds.ai/errors/method.schema_violation'+ 'errors/bundle-resource-not-named-error.md': 'https://mthds.ai/errors/request.invalid'+ 'errors/bundle-resource-path-error.md': 'https://mthds.ai/errors/security.input_path_refused'+ 'errors/codegen-error.md': 'errors/pipelex/codegen/output_conflict.md'+ 'errors/codegen-lock-error.md': 'errors/pipelex/codegen/lock_invalid.md'+ 'errors/codegen-stamp-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/cogt-error.md': 'errors/index.md'+ 'errors/concept-code-error.md': 'https://mthds.ai/errors/method.schema_violation'+ 'errors/concept-error.md': 'errors/index.md'+ 'errors/concept-factory-error.md': 'https://mthds.ai/errors/method.concept_invalid'+ 'errors/concept-library-concept-not-found-error.md': 'https://mthds.ai/errors/input.wrong_concept'+ 'errors/concept-library-error.md': 'https://mthds.ai/errors/method.concept_unresolved'+ 'errors/concept-loading-error.md': 'errors/index.md'+ 'errors/concept-ref-ambiguous-error.md': 'https://mthds.ai/errors/method.ref_ambiguous'+ 'errors/concept-refine-error.md': 'errors/index.md'+ 'errors/concept-spec-error.md': 'errors/index.md'+ 'errors/concept-string-error.md': 'https://mthds.ai/errors/method.schema_violation'+ 'errors/concept-structure-generator-error.md': 'https://mthds.ai/errors/method.concept_invalid'+ 'errors/concept-structure-validation-error.md': 'https://mthds.ai/errors/method.concept_invalid'+ 'errors/config-validation-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/construct-field-blueprint-type-error.md': 'https://mthds.ai/errors/method.schema_violation'+ 'errors/construct-field-blueprint-value-error.md': 'https://mthds.ai/errors/method.schema_violation'+ 'errors/context-provider-error.md': 'errors/index.md'+ 'errors/core-unconditional-plugin-disabled-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/cost-registry-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/crate-normalization-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/credentials-error.md': 'errors/index.md'+ 'errors/csv-coercion-error.md': 'https://mthds.ai/errors/input.invalid'+ 'errors/csv-column-error.md': 'https://mthds.ai/errors/input.invalid'+ 'errors/csv-error.md': 'https://mthds.ai/errors/input.invalid'+ 'errors/csv-flatness-error.md': 'https://mthds.ai/errors/input.invalid'+ 'errors/csv-read-error.md': 'https://mthds.ai/errors/input.file_unreadable'+ 'errors/date-content-error.md': 'https://mthds.ai/errors/pipe.function_raised'+ 'errors/delivery-error.md': 'errors/index.md'+ 'errors/doc-gen-engine-missing-error.md': 'errors/pipelex/docgen/engine_unavailable.md'+ 'errors/doc-gen-handle-not-found-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/doc-gen-model-capability-error.md': 'https://mthds.ai/errors/model.capability_unsupported'+ 'errors/doc-gen-render-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/domain-code-error.md': 'https://mthds.ai/errors/method.schema_violation'+ 'errors/domain-factory-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/domain-library-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/domain-loading-error.md': 'errors/index.md'+ 'errors/drift-ack-error.md': 'https://mthds.ai/errors/request.invalid'+ 'errors/drift-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/drift-git-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/drift-manifest-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/dry-run-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/dry-run-graph-not-produced-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/dry-run-mock-build-error.md': 'https://mthds.ai/errors/method.mock_unsatisfiable'+ 'errors/dry-run-object-fidelity-error.md': 'https://mthds.ai/errors/method.mock_unsatisfiable'+ 'errors/duplicate-bundle-validator-error.md': 'errors/pipelex/plugin/conflict.md'+ 'errors/duplicate-doc-gen-default-error.md': 'errors/pipelex/plugin/conflict.md'+ 'errors/duplicate-http-error-mapper-error.md': 'errors/pipelex/plugin/conflict.md'+ 'errors/duplicate-inference-backend-error.md': 'errors/pipelex/plugin/conflict.md'+ 'errors/duplicate-internal-model-error.md': 'errors/pipelex/plugin/conflict.md'+ 'errors/duplicate-log-sink-error.md': 'errors/pipelex/plugin/conflict.md'+ 'errors/duplicate-model-lister-error.md': 'errors/pipelex/plugin/conflict.md'+ 'errors/duplicate-orchestrator-error.md': 'errors/pipelex/plugin/conflict.md'+ 'errors/duplicate-pipe-func-executor-error.md': 'errors/pipelex/plugin/conflict.md'+ 'errors/duplicate-pipe-func-package-offer-error.md': 'errors/pipelex/plugin/conflict.md'+ 'errors/duplicate-secrets-provider-error.md': 'errors/pipelex/plugin/conflict.md'+ 'errors/duplicate-service-error-code-error.md': 'errors/pipelex/plugin/conflict.md'+ 'errors/duplicate-storage-provider-error.md': 'errors/pipelex/plugin/conflict.md'+ 'errors/empty-method-tree-error.md': 'https://mthds.ai/errors/method.invalid'+ 'errors/entry-pipe-ambiguous-error.md': 'https://mthds.ai/errors/request.pipe_ambiguous'+ 'errors/entry-pipe-not-found-error.md': 'https://mthds.ai/errors/request.pipe_not_found'+ 'errors/env-var-not-found-error.md': 'errors/pipelex/config/variable_missing.md'+ 'errors/event-log-error.md': 'errors/index.md'+ 'errors/event-log-read-error.md': 'https://mthds.ai/errors/runtime.unavailable'+ 'errors/event-log-schema-mismatch-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/event-log-setup-error.md': 'https://mthds.ai/errors/runtime.misconfigured'+ 'errors/execution-and-runtime.md': 'errors/index.md'+ 'errors/explicit-concept-incompatible-error.md': 'https://mthds.ai/errors/input.wrong_concept'+ 'errors/extract-capability-error.md': 'https://mthds.ai/errors/model.capability_unsupported'+ 'errors/extract-handle-not-found-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/extract-input-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/extract-input-format-error.md': 'https://mthds.ai/errors/input.file_type_unsupported'+ 'errors/extract-job-failure-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/extract-model-not-found-error.md': 'https://mthds.ai/errors/model.unavailable'+ 'errors/extract-output-error.md': 'errors/index.md'+ 'errors/fal-credentials-error.md': 'errors/index.md'+ 'errors/fatal-error.md': 'errors/index.md'+ 'errors/file-type-error.md': 'https://mthds.ai/errors/input.file_type_unsupported'+ 'errors/fix-transaction-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/fix-write-conflict-error.md': 'https://mthds.ai/errors/method.changed_concurrently'+ 'errors/former-release-config-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/function-names-migration-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/gcp-log-sink-credentials-error.md': 'errors/pipelex/config/file_missing.md'+ 'errors/generated-image-error.md': 'https://mthds.ai/errors/provider.response_invalid'+ 'errors/google-img-gen-worker-error.md': 'errors/index.md'+ 'errors/google-llm-worker-error.md': 'https://mthds.ai/errors/model.output_schema_mismatch'+ 'errors/graph-spec-error.md': 'errors/index.md'+ 'errors/graph-spec-validation-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/host-library-requirements-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/host-library-tree-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/hosted-base-url-error.md': 'https://mthds.ai/errors/client.not_configured'+ 'errors/hosted-local-file-upload-unavailable-error.md': 'https://mthds.ai/errors/request.unsupported'+ 'errors/hosted-method-invalid-error.md': 'https://mthds.ai/errors/method.invalid'+ 'errors/hosted-run-error.md': 'errors/index.md'+ 'errors/hosted-run-interrupted-error.md': 'https://mthds.ai/errors/client.outcome_unknown'+ 'errors/hosted-run-outcome-unknown-error.md': 'https://mthds.ai/errors/client.outcome_unknown'+ 'errors/hosted-run-polling-error.md': 'https://mthds.ai/errors/client.follow_failed'+ 'errors/hosted-run-source-error.md': 'https://mthds.ai/errors/client.argument_invalid'+ 'errors/hub-slot-already-claimed-error.md': 'errors/pipelex/plugin/conflict.md'+ 'errors/image-content-error.md': 'errors/index.md'+ 'errors/img-gen-generated-type-error.md': 'errors/index.md'+ 'errors/img-gen-generation-error.md': 'https://mthds.ai/errors/provider.outcome_unknown'+ 'errors/img-gen-handle-not-found-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/img-gen-model-not-found-error.md': 'https://mthds.ai/errors/model.unavailable'+ 'errors/img-gen-parameter-error.md': 'https://mthds.ai/errors/model.capability_unsupported'+ 'errors/img-gen-prompt-error.md': 'https://mthds.ai/errors/pipe.prompt_empty'+ 'errors/img-gen-settings-validation-error.md': 'errors/index.md'+ 'errors/inference-and-providers.md': 'errors/index.md'+ 'errors/inference-backend-credentials-error.md': 'errors/pipelex/config/credential_missing.md'+ 'errors/inference-backend-library-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/inference-backend-library-not-found-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/inference-backend-library-validation-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/inference-backend-not-found-error.md': 'https://mthds.ai/errors/model.unavailable'+ 'errors/inference-model-spec-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/input-shaping-error.md': 'errors/index.md'+ 'errors/input-stuff-spec-not-found-error.md': 'https://mthds.ai/errors/method.wiring_invalid'+ 'errors/input-stuff-specs-error.md': 'errors/index.md'+ 'errors/input-stuff-specs-factory-error.md': 'https://mthds.ai/errors/method.schema_violation'+ 'errors/invocation-path-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/jinja2-context-error.md': 'https://mthds.ai/errors/pipe.template_render_failed'+ 'errors/jinja2-detect-variables-error.md': 'https://mthds.ai/errors/method.syntax'+ 'errors/jinja2-stuff-error.md': 'https://mthds.ai/errors/method.name_conflict'+ 'errors/jinja2-template-budget-error.md': 'https://mthds.ai/errors/pipe.template_budget_exceeded'+ 'errors/jinja2-template-render-error.md': 'https://mthds.ai/errors/pipe.template_render_failed'+ 'errors/jinja2-template-security-error.md': 'https://mthds.ai/errors/security.template_refused'+ 'errors/jinja2-template-syntax-error.md': 'https://mthds.ai/errors/method.syntax'+ 'errors/job-metadata-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/json-type-error.md': 'https://mthds.ai/errors/request.invalid'+ 'errors/judgment-answer-mismatch-error.md': 'https://mthds.ai/errors/model.output_schema_mismatch'+ 'errors/judgment-capability-error.md': 'https://mthds.ai/errors/model.capability_unsupported'+ 'errors/judgment-handle-not-found-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/judgment-job-failure-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/judgment-model-missing-error.md': 'https://mthds.ai/errors/model.unspecified'+ 'errors/judgment-model-not-found-error.md': 'https://mthds.ai/errors/model.unavailable'+ 'errors/judgment-refused-error.md': 'https://mthds.ai/errors/model.content_refused'+ 'errors/kit-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/kit-index-loading-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/langfuse-credentials-error.md': 'errors/pipelex/config/variable_missing.md'+ 'errors/library-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/library-loading-error.md': 'https://mthds.ai/errors/method.invalid'+ 'errors/linkup-error.md': 'errors/pipelex/config/credential_missing.md'+ 'errors/linkup-search-empty-result-error.md': 'https://mthds.ai/errors/model.no_result'+ 'errors/linkup-search-response-error.md': 'https://mthds.ai/errors/provider.response_invalid'+ 'errors/list-where-singular-error.md': 'https://mthds.ai/errors/input.wrong_multiplicity'+ 'errors/llm-assignment-error.md': 'errors/index.md'+ 'errors/llm-capability-error.md': 'https://mthds.ai/errors/model.capability_unsupported'+ 'errors/llm-completion-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/llm-completion-refused-error.md': 'https://mthds.ai/errors/model.content_refused'+ 'errors/llm-completion-truncated-error.md': 'https://mthds.ai/errors/model.output_truncated'+ 'errors/llm-config-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/llm-handle-not-found-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/llm-model-not-found-error.md': 'https://mthds.ai/errors/model.unavailable'+ 'errors/llm-prompt-parameter-error.md': 'https://mthds.ai/errors/pipe.prompt_empty'+ 'errors/llm-prompt-spec-error.md': 'errors/index.md'+ 'errors/llm-setting-refused-error.md': 'https://mthds.ai/errors/model.capability_unsupported'+ 'errors/llm-settings-validation-error.md': 'errors/index.md'+ 'errors/log-sink-header-value-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/log-sink-variable-error.md': 'errors/pipelex/config/variable_missing.md'+ 'errors/markdown-formatting-budget-error.md': 'https://mthds.ai/errors/input.too_large'+ 'errors/method-dependency-fetch-error.md': 'https://mthds.ai/errors/method.dependency_missing'+ 'errors/method-dependency-not-shipped-error.md': 'https://mthds.ai/errors/method.dependency_missing'+ 'errors/method-entry-error.md': 'https://mthds.ai/errors/request.pipe_unspecified'+ 'errors/method-fetch-disabled-error.md': 'https://mthds.ai/errors/method.dependency_missing'+ 'errors/method-fetch-error.md': 'https://mthds.ai/errors/method.fetch_failed'+ 'errors/method-file-unavailable-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/method-install-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/method-package-ambiguity-error.md': 'https://mthds.ai/errors/method.ambiguous'+ 'errors/method-package-not-found-error.md': 'https://mthds.ai/errors/method.not_found'+ 'errors/method-package-symlink-error.md': 'https://mthds.ai/errors/method.package_invalid'+ 'errors/method-package-too-large-error.md': 'https://mthds.ai/errors/method.package_invalid'+ 'errors/method-ref-error.md': 'errors/index.md'+ 'errors/method-ref-parse-error.md': 'https://mthds.ai/errors/request.invalid'+ 'errors/method-requirements-error.md': 'errors/index.md'+ 'errors/method-requirements-file-error.md': 'https://mthds.ai/errors/method.package_invalid'+ 'errors/method-requirements-not-met-error.md': 'https://mthds.ai/errors/method.dependency_missing'+ 'errors/method-structures-refused-error.md': 'errors/pipelex/deployment/python_structures_refused.md'+ 'errors/method-tree-load-error.md': 'https://mthds.ai/errors/method.package_invalid'+ 'errors/migration-error.md': 'errors/index.md'+ 'errors/migration-golden-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/migration-ledger-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/migration-registry-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/migration-snapshot-refused-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/missing-bundle-validator-error.md': 'errors/pipelex/plugin/not_found.md'+ 'errors/missing-dependency-error.md': 'errors/pipelex/config/dependency_missing.md'+ 'errors/missing-orchestrator-error.md': 'errors/pipelex/plugin/not_found.md'+ 'errors/mistral-extract-response-error.md': 'https://mthds.ai/errors/provider.response_invalid'+ 'errors/mistral-model-listing-error.md': 'https://mthds.ai/errors/provider.response_invalid'+ 'errors/mistral-plugin-error.md': 'errors/index.md'+ 'errors/mistral-worker-configuration-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/model-choice-not-found-error.md': 'https://mthds.ai/errors/model.unknown'+ 'errors/model-deck-not-found-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/model-deck-preset-validaton-error.md': 'errors/index.md'+ 'errors/model-deck-validation-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/model-deck-validaton-error.md': 'errors/index.md'+ 'errors/model-listing-unsupported-error.md': 'https://mthds.ai/errors/runtime.unsupported'+ 'errors/model-manager-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/model-not-found-error.md': 'https://mthds.ai/errors/model.unavailable'+ 'errors/model-reference-parse-error.md': 'https://mthds.ai/errors/method.model_setting_invalid'+ 'errors/model-waterfall-error.md': 'https://mthds.ai/errors/model.unavailable'+ 'errors/module-file-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/mthds-parser-error.md': 'https://mthds.ai/errors/method.invalid'+ 'errors/multiplicity-count-mismatch-error.md': 'https://mthds.ai/errors/input.wrong_multiplicity'+ 'errors/native-concept-definition-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/neither-url-nor-data-error.md': 'https://mthds.ai/errors/provider.response_invalid'+ 'errors/nested-key-conflict-error.md': 'https://mthds.ai/errors/pipe.template_render_failed'+ 'errors/null-input-error.md': 'https://mthds.ai/errors/input.invalid'+ 'errors/open-ai-client-factory-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/optional-value-absent-error.md': 'https://mthds.ai/errors/pipe.forced_input_absent'+ 'errors/output-structure-schema-error.md': 'https://mthds.ai/errors/method.concept_invalid'+ 'errors/pipe-batch-factory-error.md': 'errors/index.md'+ 'errors/pipe-compose-error.md': 'https://mthds.ai/errors/pipe.output_invalid'+ 'errors/pipe-compose-factory-error.md': 'https://mthds.ai/errors/method.template_invalid'+ 'errors/pipe-condition-factory-error.md': 'https://mthds.ai/errors/method.schema_violation'+ 'errors/pipe-controller-error.md': 'errors/index.md'+ 'errors/pipe-controller-output-concept-mismatch-error.md': 'errors/index.md'+ 'errors/pipe-doc-gen-factory-error.md': 'https://mthds.ai/errors/method.template_invalid'+ 'errors/pipe-doc-gen-run-error.md': 'https://mthds.ai/errors/pipe.template_render_failed'+ 'errors/pipe-doc-gen-template-check-error.md': 'errors/pipelex/docgen/template_invalid.md'+ 'errors/pipe-doc-gen-template-file-unchecked-error.md': 'https://mthds.ai/errors/runtime.unsupported'+ 'errors/pipe-doc-gen-undefined-value-error.md': 'https://mthds.ai/errors/pipe.template_render_failed'+ 'errors/pipe-execution-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/pipe-extract-factory-error.md': 'https://mthds.ai/errors/method.schema_violation'+ 'errors/pipe-factory-error.md': 'https://mthds.ai/errors/method.schema_violation'+ 'errors/pipe-func-execution-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/pipe-func-function-error.md': 'https://mthds.ai/errors/method.function_invalid'+ 'errors/pipe-func-package-set-unstated-error.md': 'https://mthds.ai/errors/runtime.misconfigured'+ 'errors/pipe-func-transport-error.md': 'https://mthds.ai/errors/runtime.misconfigured'+ 'errors/pipe-img-gen-factory-error.md': 'https://mthds.ai/errors/model.context_exceeded'+ 'errors/pipe-img-gen-run-error.md': 'https://mthds.ai/errors/pipe.input_unresolved'+ 'errors/pipe-input-error.md': 'errors/index.md'+ 'errors/pipe-inputs-factory-error.md': 'errors/index.md'+ 'errors/pipe-io-contract-error.md': 'https://mthds.ai/errors/method.concept_invalid'+ 'errors/pipe-job-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/pipe-judge-error.md': 'errors/index.md'+ 'errors/pipe-judge-input-capability-error.md': 'https://mthds.ai/errors/model.capability_unsupported'+ 'errors/pipe-library-error.md': 'https://mthds.ai/errors/method.name_conflict'+ 'errors/pipe-llm-factory-error.md': 'https://mthds.ai/errors/method.template_invalid'+ 'errors/pipe-load-refusal-error.md': 'https://mthds.ai/errors/method.schema_violation'+ 'errors/pipe-loading-error.md': 'errors/index.md'+ 'errors/pipe-not-found-error.md': 'https://mthds.ai/errors/method.pipe_unresolved'+ 'errors/pipe-operator-model-availability-error.md': 'https://mthds.ai/errors/model.unavailable'+ 'errors/pipe-operator-model-choice-error.md': 'https://mthds.ai/errors/model.unknown'+ 'errors/pipe-parallel-factory-error.md': 'https://mthds.ai/errors/method.schema_violation'+ 'errors/pipe-router-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/pipe-run-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/pipe-run-inputs-error.md': 'https://mthds.ai/errors/pipe.input_unresolved'+ 'errors/pipe-run-params-error.md': 'https://mthds.ai/errors/method.schema_violation'+ 'errors/pipe-search-error.md': 'errors/index.md'+ 'errors/pipe-search-factory-error.md': 'errors/index.md'+ 'errors/pipe-sequence-factory-error.md': 'errors/index.md'+ 'errors/pipe-signature-not-executable-error.md': 'https://mthds.ai/errors/method.not_runnable'+ 'errors/pipe-spec-error.md': 'errors/index.md'+ 'errors/pipe-stack-overflow-error.md': 'https://mthds.ai/errors/pipe.stack_overflow'+ 'errors/pipelex-bridge-dispatch-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/pipelex-cli-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/pipelex-config-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/pipelex-error.md': 'errors/index.md'+ 'errors/pipelex-runtime-bridge-error.md': 'errors/index.md'+ 'errors/pipelex-setup-error.md': 'https://mthds.ai/errors/runtime.misconfigured'+ 'errors/pipelex-unexpected-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/pipeline-execution-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/pipeline-input-content-error.md': 'errors/pipelex/storage/uri_invalid.md'+ 'errors/pipeline-input-format-error.md': 'errors/index.md'+ 'errors/pipeline-input-format-unsupported-error.md': 'https://mthds.ai/errors/input.file_type_unsupported'+ 'errors/pipeline-input-not-an-image-error.md': 'https://mthds.ai/errors/input.file_type_unsupported'+ 'errors/pipeline-input-url-invalid-error.md': 'https://mthds.ai/errors/input.invalid'+ 'errors/pipeline-input-url-missing-error.md': 'https://mthds.ai/errors/input.invalid'+ 'errors/pipeline-manager-already-exists-error.md': 'errors/pipelex/run/already_exists.md'+ 'errors/pipeline-manager-not-found-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/platform-and-tooling.md': 'errors/index.md'+ 'errors/plugin-api-version-mismatch-error.md': 'errors/pipelex/plugin/api_mismatch.md'+ 'errors/plugin-declared-in-multiple-groups-error.md': 'errors/pipelex/plugin/broken.md'+ 'errors/plugin-error.md': 'errors/index.md'+ 'errors/plugin-layer-violation-error.md': 'errors/pipelex/plugin/broken.md'+ 'errors/plugin-model-declaration-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/portkey-credentials-error.md': 'errors/pipelex/config/credential_missing.md'+ 'errors/portkey-error.md': 'errors/index.md'+ 'errors/portkey-factory-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/prompt-document-factory-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/prompt-document-format-error.md': 'https://mthds.ai/errors/input.file_type_unsupported'+ 'errors/prompt-image-factory-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/prompt-image-format-error.md': 'https://mthds.ai/errors/input.file_type_unsupported'+ 'errors/py-pdfium2-renderer-error.md': 'errors/index.md'+ 'errors/readiness-check-error.md': 'https://mthds.ai/errors/runtime.misconfigured'+ 'errors/remote-file-fetch-error.md': 'https://mthds.ai/errors/input.file_unreadable'+ 'errors/reporting-manager-error.md': 'errors/index.md'+ 'errors/reserved-service-error-code-error.md': 'errors/pipelex/plugin/broken.md'+ 'errors/retired-plugin-entry-point-group-error.md': 'errors/pipelex/plugin/broken.md'+ 'errors/routing-profile-blueprint-value-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/routing-profile-disabled-backend-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/routing-profile-library-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/routing-profile-library-not-found-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/sdk-type-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/search-handle-not-found-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/search-job-failure-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/search-model-not-found-error.md': 'https://mthds.ai/errors/model.unavailable'+ 'errors/secret-not-found-error.md': 'errors/pipelex/config/variable_missing.md'+ 'errors/security-error.md': 'errors/index.md'+ 'errors/ssrf-blocked-error.md': 'https://mthds.ai/errors/security.input_url_refused'+ 'errors/storage-checksum-mismatch-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/storage-config-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/storage-delivery-error.md': 'errors/pipelex/storage/unavailable.md'+ 'errors/storage-error.md': 'errors/index.md'+ 'errors/storage-file-not-found-error.md': 'errors/pipelex/storage/not_found.md'+ 'errors/storage-gcp-credentials-error.md': 'errors/pipelex/config/file_missing.md'+ 'errors/storage-gcp-error.md': 'errors/pipelex/storage/unavailable.md'+ 'errors/storage-invalid-key-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/storage-invalid-uri-error.md': 'https://mthds.ai/errors/security.input_path_refused'+ 'errors/storage-local-error.md': 'https://mthds.ai/errors/runtime.misconfigured'+ 'errors/storage-s3-error.md': 'errors/pipelex/storage/unavailable.md'+ 'errors/structure-class-error.md': 'errors/index.md'+ 'errors/structure-validation-error.md': 'https://mthds.ai/errors/input.invalid'+ 'errors/structured-content-composer-type-error.md': 'https://mthds.ai/errors/pipe.output_invalid'+ 'errors/structured-content-composer-validation-error.md': 'https://mthds.ai/errors/pipe.output_invalid'+ 'errors/structured-content-composer-value-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/stuff-artefact-error.md': 'errors/index.md'+ 'errors/stuff-artefact-reserved-field-error.md': 'errors/index.md'+ 'errors/stuff-content-factory-error.md': 'https://mthds.ai/errors/input.invalid'+ 'errors/stuff-content-type-error.md': 'https://mthds.ai/errors/method.wiring_invalid'+ 'errors/stuff-content-validation-error.md': 'https://mthds.ai/errors/method.wiring_invalid'+ 'errors/stuff-error.md': 'errors/index.md'+ 'errors/stuff-factory-error.md': 'https://mthds.ai/errors/input.invalid'+ 'errors/stuff-spec-error.md': 'errors/index.md'+ 'errors/stuff-spec-factory-error.md': 'https://mthds.ai/errors/method.schema_violation'+ 'errors/telemetry-config-error.md': 'errors/index.md'+ 'errors/telemetry-config-validation-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/template-sigil-syntax-error.md': 'https://mthds.ai/errors/method.syntax'+ 'errors/template-url-refused-error.md': 'https://mthds.ai/errors/security.method_path_refused'+ 'errors/toml-error.md': 'errors/pipelex/config/syntax.md'+ 'errors/tool-error.md': 'errors/index.md'+ 'errors/trace-event-mode-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/traceback-message-error.md': 'errors/index.md'+ 'errors/tree-module-shadowing-error.md': 'https://mthds.ai/errors/method.name_conflict'+ 'errors/tree-python-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/tree-python-held-error.md': 'https://mthds.ai/errors/runtime.unavailable'+ 'errors/typesafe-error.md': 'errors/pipelex/config/credential_missing.md'+ 'errors/typesafe-judgment-response-error.md': 'https://mthds.ai/errors/provider.response_invalid'+ 'errors/typesafe-question-unsupported-error.md': 'https://mthds.ai/errors/model.capability_unsupported'+ 'errors/unknown-boot-orchestrator-error.md': 'errors/pipelex/plugin/not_found.md'+ 'errors/unknown-input-name-error.md': 'https://mthds.ai/errors/input.unexpected'+ 'errors/unknown-log-sink-error.md': 'errors/pipelex/plugin/not_found.md'+ 'errors/unknown-pipe-func-execution-mode-error.md': 'errors/pipelex/plugin/not_found.md'+ 'errors/unknown-secrets-method-error.md': 'errors/pipelex/plugin/not_found.md'+ 'errors/unknown-storage-method-error.md': 'errors/pipelex/plugin/not_found.md'+ 'errors/unknown-var-prefix-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/unsafe-schema-error.md': 'https://mthds.ai/errors/security.schema_refused'+ 'errors/uri-read-refused-error.md': 'https://mthds.ai/errors/security.input_url_refused'+ 'errors/validate-bundle-error.md': 'https://mthds.ai/errors/method.invalid'+ 'errors/var-fallback-pattern-error.md': 'errors/pipelex/config/variable_missing.md'+ 'errors/var-not-found-error.md': 'errors/pipelex/config/variable_missing.md'+ 'errors/vertex-ai-config-error.md': 'errors/pipelex/config/invalid.md'+ 'errors/vertex-ai-credentials-error.md': 'errors/pipelex/config/credential_missing.md'+ 'errors/webhook-delivery-error.md': 'errors/pipelex/webhook/delivery_failed.md'+ 'errors/with-images-filter-error.md': 'https://mthds.ai/errors/method.template_invalid'+ 'errors/working-memory-consistency-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/working-memory-error.md': 'errors/index.md'+ 'errors/working-memory-factory-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/working-memory-stuff-attribute-not-found-error.md': 'https://mthds.ai/errors/method.wiring_invalid'+ 'errors/working-memory-stuff-not-found-error.md': 'https://mthds.ai/errors/runtime.unexpected'+ 'errors/working-memory-type-error.md': 'https://mthds.ai/errors/method.wiring_invalid'+ 'errors/working-memory-variable-error.md': 'errors/index.md'+ 'errors/wrong-scalar-kind-error.md': 'https://mthds.ai/errors/input.invalid'+ # END retired error class pages- meta-manager- glightbox:touchNavigation: truediff --git a/pipelex/base_exceptions.py b/pipelex/base_exceptions.pyindex 1572c6883..c7548aa55 100644--- a/pipelex/base_exceptions.py+++ b/pipelex/base_exceptions.py@@ -2,14 +2,24 @@ from collections.abc import Iteratorfrom enum import StrEnumfrom typing import Any, ClassVar, Self+from mthds.protocol.problem.registry import CoreCode, ProblemDomainfrom pydantic import BaseModel, ConfigDict, Fieldfrom typing_extensions import overridefrom pipelex.cogt.inference.error_classification import ProviderErrorMetadata, UserAction+from pipelex.errors.error_code_declaration import (+ ABSTRACT_ERROR,+ AbstractError,+ ErrorCodeDeclaration,+ ErrorCodeSet,+ InheritsCause,+ declared_error_codes,+ describe_error_code_declaration,+)+from pipelex.errors.error_codes import ErrorCode, error_code_spec+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.migration.plan import MigrationPlanfrom pipelex.suggested_fix import SuggestedFix-from pipelex.tools.misc.string_utils import pascal_case_to_kebab, pascal_case_to_sentence-from pipelex.urls import URLsfrom pipelex.validation_error_types import ValidationErrorType@@ -80,7 +90,7 @@ INTERNAL_ERROR_PLACEHOLDER = "An internal error occurred."# deployment's settings — never anything the caller submitted. It is diagnostics# for whoever runs the process, which on a hosted surface is not the caller._STRICT_KEPT_FIELDS: frozenset[str] = frozenset(- {"error_type", "title", "type_uri", "error_domain", "error_category", "retryable", "validation_errors"}+ {"code", "error_type", "title", "type_uri", "error_domain", "error_category", "retryable", "validation_errors"})# The curated subset of ``ProviderErrorMetadata`` that survives STRICT@@ -187,12 +197,32 @@ class ErrorDomain(StrEnum):- INPUT: the caller can fix it (bad .mthds, wrong args, malformed JSON).- CONFIG: an environment or configuration change is needed.- RUNTIME: a failure that occurred during execution.++ A report's domain is no longer declared by an error class: it is read from the domain the registry+ gives the error's code, through :meth:`from_problem_domain`, until the problem document carries that+ domain itself."""INPUT = "input"CONFIG = "config"RUNTIME = "runtime"+ @classmethod+ def from_problem_domain(cls, problem_domain: ProblemDomain) -> "ErrorDomain":+ """The report domain of a code's registry domain.++ The caller's input and the method the caller sent are both the caller's to change, so both read+ ``INPUT``; the account's owner and whoever runs the runtime act outside the request, so both read+ ``CONFIG``; and ``runtime`` stays ``RUNTIME``.+ """+ match problem_domain:+ case ProblemDomain.INPUT | ProblemDomain.METHOD:+ return cls.INPUT+ case ProblemDomain.ACCOUNT | ProblemDomain.OPERATOR:+ return cls.CONFIG+ case ProblemDomain.RUNTIME:+ return cls.RUNTIME+@propertydef is_input(self) -> bool:"""True for the caller-fixable input domain — read state through the enum rather than ``== ErrorDomain.INPUT``.@@ -415,10 +445,11 @@ class ErrorReport(BaseModel):Used by CLI JSON output, agent output, and Temporal error details.- ``title`` and ``type_uri`` are the stable identity pair surfaced to consumers- (CLI, API, docs). Every ``PipelexError`` populates them automatically via- :meth:`PipelexError.title` / :meth:`PipelexError.type_uri`; consumers never- humanize or kebab-case a class name themselves.+ ``code`` is the registry code the error resolved to (:meth:`PipelexError.resolve_error_code`): a core code+ of the MTHDS standard or a Pipelex code. ``title`` and ``type_uri`` are the code's title and the code's+ documentation page, and ``error_domain`` and ``retryable`` are read from the domain and the retry verdict+ the registry gives the code, so that no raise site sets them independently: two cases that need different+ verdicts are two codes. Consumers never humanize or kebab-case a class name themselves.Frozen: wrappers must rebuild via :meth:`model_copy` rather than mutate, soa cause-enrichment pass cannot accidentally overwrite an outer wrapper's@@ -427,6 +458,7 @@ class ErrorReport(BaseModel):model_config = ConfigDict(frozen=True, extra="forbid", arbitrary_types_allowed=True)+ code: strerror_type: strmessage: strtitle: str@@ -576,6 +608,47 @@ class ErrorReport(BaseModel):"""return cls.model_validate(data)+ @classmethod+ def make_for_code(+ cls,+ *,+ code: ErrorCode,+ error_type: str,+ message: str,+ user_action: UserAction | None = None,+ caller_facing_message: bool = False,+ validation_errors: list[ValidationErrorItem] | None = None,+ ) -> "ErrorReport":+ """Build the report of an error that carries ``code``, reading from the registry what the code decides.++ The title, the documentation page, the domain and the retry verdict are the code's, so a report built here+ can never disagree with its code. ``PipelexError.to_error_report`` builds every error's report this way.++ Args:+ code: The registry code the error resolved to.+ error_type: The error's class name.+ message: The error's message.+ user_action: The next step its raise site named, when it named one.+ caller_facing_message: Whether the message is caller-facing copy, which STRICT disclosure keeps.+ validation_errors: The structured items of a bundle-validation refusal.++ Returns:+ The report.+ """+ spec = error_code_spec(code)+ return cls(+ code=code,+ error_type=error_type,+ message=message,+ title=spec.title,+ type_uri=spec.type_uri,+ error_domain=ErrorDomain.from_problem_domain(spec.domain),+ retryable=spec.invites_retry,+ user_action=user_action,+ caller_facing_message=caller_facing_message,+ validation_errors=validation_errors,+ )+def user_action_detail(self) -> str | None:"""Return the free-form advice text on ``user_action``, or ``None`` when absent."""return self.user_action.detail if self.user_action is not None else None@@ -596,109 +669,137 @@ class ErrorReport(BaseModel):return error_domain_to_http_status(self.error_domain)-def _humanize_class_name(class_name: str) -> str:- """Derive a human-readable title from a ``PipelexError`` subclass name.-- Strips a trailing ``Error`` (if present) and runs the remainder through- :func:`pipelex.tools.misc.string_utils.pascal_case_to_sentence`. Single-token- leaves (``CogtError`` -> ``Cogt``) read awkwardly and warrant a curated- :attr:`PipelexError._declared_title` override.- """- stem = class_name.removesuffix("Error") if class_name.endswith("Error") and class_name != "Error" else class_name- return pascal_case_to_sentence(stem)+_FALLBACK_ERROR_CODE: ErrorCode = CoreCode.RUNTIME_UNEXPECTED+"""The code of an error whose cause chain names none: the catch-all, ``runtime.unexpected``, step ``report``."""class PipelexError(Exception):- error_domain: ErrorDomain | None = None+ """The root of every error Pipelex raises, each carrying a registry code.++ Every subclass declares ``error_code`` in its own class body, as :mod:`pipelex.errors.error_code_declaration`+ describes: the code it raises, the set its raise sites choose from, that it takes its cause's code, or that it+ is an abstract base. The code decides the report's title, documentation page, domain and retry verdict, so a+ class declares none of them; ``tests/unit/pipelex/errors/test_error_code_gate.py`` fails the build on a+ subclass that declares no code, and ``docs/under-the-hood/error-model.md`` explains the model.+ """++ error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERRORuser_action: UserAction | None = None- # Whether running the same request again could succeed, declared by a class whose every instance answers the- # same: ``False`` on a deterministic refusal of what the caller sent. ``None`` says nothing, and the report then- # takes the answer from the ``__cause__`` chain, or carries none. The ``CogtError`` family derives it from its- # ``error_category`` instead.- retryable: bool | None = None- # When declared *directly in a subclass body*, ``title()`` returns this- # verbatim instead of auto-deriving from the class name. Use to fix awkward- # auto-derives (e.g. ``CogtError`` -> ``Cogt``) or to publish a curated- # user-facing label. ``title()`` consults ``cls.__dict__`` so inheritance- # is bypassed — each class either declares its own title or auto-derives- # from its own name. That is why the curated ``"Pipelex error"`` value is- # set on ``PipelexError`` *itself* without leaking to bare subclasses.- _declared_title: ClassVar[str | None] = "Pipelex error"- # When declared *directly in a subclass body*, ``type_uri()`` returns this- # verbatim instead of appending the kebab-cased class name to the- # ``URLs.error_docs_base`` constant. Same inheritance-bypass semantics- # as ``_declared_title``.- _declared_type_uri: ClassVar[str | None] = None# When True, ``ErrorReport``s built from this class keep their ``message``# verbatim under STRICT disclosure (see :class:`DisclosureMode`). Set it on# classes whose ``message`` is genuinely caller-facing copy — text describing# the *caller's own* input (a ``.mthds`` syntax error, a failed bundle# validation). It is consulted by plain attribute access, so it inherits# normally — a subclass of a caller-facing error stays caller-facing.- # (Contrast ``_declared_title`` / ``_declared_type_uri``, which ``title()`` /- # ``type_uri()`` deliberately read via ``cls.__dict__`` to bypass inheritance.)_authors_caller_facing_message: ClassVar[bool] = False# The per-instance counterpart of ``_authors_caller_facing_message``, set only by# :meth:`as_caller_fault`, for a class whose instances are not all the caller's fault._raised_as_caller_fault: bool = False+ # The code the raise site chose with :meth:`with_error_code`, from the codes the class declares.+ _chosen_error_code: ErrorCode | None = None++ def __init_subclass__(cls, **kwargs: Any) -> None:+ super().__init_subclass__(**kwargs)+ declaration = cls.__dict__.get("error_code")+ if declaration is not None and not isinstance(declaration, (CoreCode, PipelexErrorCode, ErrorCodeSet, InheritsCause, AbstractError)):+ msg = (+ f"{cls.__qualname__}.error_code must be a CoreCode, a PipelexErrorCode, an ErrorCodeSet, an InheritsCause "+ f"or ABSTRACT_ERROR, not {declaration!r}."+ )+ raise TypeError(msg)- @classmethod- def title(cls) -> str:- """Return the human-readable title for this error class.-- Used as the RFC 7807 ``title`` field on every ``ErrorReport``. Auto-derived- from the class name unless a subclass sets :attr:`_declared_title` directly- in its own body. Inheritance is bypassed so a parent's curated title does- not silently capture every subclass — each class either declares its own- title or auto-derives.+ def __init__(self, message: str):+ super().__init__(message)+ self.message = message++ def with_error_code(self, error_code: ErrorCode) -> Self:+ """Choose, where this error is raised, which of its class's codes it carries.++ A class whose raise sites need different codes declares them as an :class:`ErrorCodeSet`, or as the+ codes an :class:`InheritsCause` class's raise site may choose, and the raise site that knows which+ applies chooses it here: ``raise SomeError(msg).with_error_code(CoreCode.MODEL_UNAVAILABLE)``. A chosen+ code stops the cause walk at this error, as a declared code does.++ Args:+ error_code: One of the codes the class declares.++ Returns:+ This error, so that the raise site reads ``raise SomeError(msg).with_error_code(code)``.++ Raises:+ ValueError: When the class does not declare the code, which is a fault of the raise site; the gate+ test checks every raise site that chooses a code on the class it constructs."""- declared = cls.__dict__.get("_declared_title")- if isinstance(declared, str):- return declared- return _humanize_class_name(cls.__name__)+ declared_codes = declared_error_codes(type(self).error_code)+ if error_code not in declared_codes:+ declared = describe_error_code_declaration(type(self).error_code)+ msg = f"{type(self).__name__} does not declare the code '{error_code}': its declaration is {declared}."+ raise ValueError(msg)+ self._chosen_error_code = error_code+ return self- @classmethod- def type_uri(cls) -> str:- """Return the class-derived URI for this error class.-- Used as the RFC 7807 ``type`` field on every ``ErrorReport``. Auto-derived- as ``<URLs.error_docs_base>/<kebab-class-name>/`` unless a subclass sets- :attr:`_declared_type_uri` directly in its own body. The per-class pages- this URI named are retired: an error's documentation is now the page of- its code in the MTHDS core registry or the Pipelex error registry- (``pipelex/errors/registry/``), and the docs site's ``404.html`` sends a- retired class URI to the error codes' index.-- Pure function: the base URI is the :data:`pipelex.urls.URLs.error_docs_base`- constant, so this is safe to call before Pipelex bootstrap and inside- Temporal workflow code without any determinism hazard.-- Footgun: ``pascal_case_to_kebab`` is case-folding — acronym-casing- variants of an existing class name collide (``LLMError`` and ``LlmError``- both kebab to ``llm-error``). ``test_pipelex_error_type_uri_uniqueness``- catches this at CI time. Pick one casing per acronym in the codebase.+ @property+ def own_error_code(self) -> ErrorCode | None:+ """The code this error carries by itself, ``None`` when it takes its cause's.++ The code its raise site chose; else its class's code, or the default of its class's set; else ``None``+ for a class that takes its cause's code or an abstract base."""- declared = cls.__dict__.get("_declared_type_uri")- if isinstance(declared, str):- return declared- return f"{URLs.error_docs_base}/{pascal_case_to_kebab(cls.__name__)}/"+ if self._chosen_error_code is not None:+ return self._chosen_error_code+ declaration = type(self).error_code+ if isinstance(declaration, ErrorCodeSet):+ return declaration.default+ if isinstance(declaration, (InheritsCause, AbstractError)):+ return None+ return declaration- def __init__(self, message: str):- super().__init__(message)- self.message = message+ @property+ def implied_error_code(self) -> ErrorCode | None:+ """The code this error implies without carrying it, ``None`` for an error that implies none.++ An inference error built by hand with a category and no code implies its category's code+ (``CogtError``). :meth:`resolve_error_code` reads it in the same walk as the codes the chain carries: a code+ any error along the chain carries by itself wins over it, and the deepest implied code wins over a wrapper's+ fallback.+ """+ return None++ def resolve_error_code(self) -> ErrorCode:+ """The registry code this error reports, resolved along its ``__cause__`` chain.++ The walk starts at this error and stops at the first error that carries a code by itself+ (:attr:`own_error_code`). It descends through every error that takes its cause's code, and through an+ abstract base raised by mistake, and stops at a cause that is not a Pipelex error. When no error along+ the way carries a code, the error reports the code the deepest error implies (:attr:`implied_error_code`),+ else the fallback of the deepest error that takes its cause's code, and ``runtime.unexpected`` when none+ names one. The walk is the one cycle-guarded ``iter_cause_chain``, which no error's code walks again.+ """+ implied_code: ErrorCode | None = None+ fallback: ErrorCode | None = None+ for node in iter_cause_chain(self):+ if not isinstance(node, PipelexError):+ break+ own_code = node.own_error_code+ if own_code is not None:+ return own_code+ implied_code = node.implied_error_code or implied_code+ declaration = type(node).error_code+ if isinstance(declaration, InheritsCause):+ fallback = declaration.fallback+ return implied_code or fallback or _FALLBACK_ERROR_CODEdef as_caller_fault(self, *, user_action: UserAction | None = None) -> Self:- """Classify this error, where it is raised, as a fault in the caller's own method or inputs.+ """Say, where this error is raised, that its message describes only the caller's own method or inputs.- Its report then carries the ``INPUT`` domain, so an HTTP surface answers 422, and a- caller-facing ``message``, which STRICT disclosure keeps (see :class:`DisclosureMode`): the- two facts a class declares with ``error_domain = ErrorDomain.INPUT`` and- ``_authors_caller_facing_message = True``. It serves a class raised both for the caller's- faults and for faults that are not the caller's, which therefore cannot declare them: the- raise site that knows says so there, for this one error. A plain wrapper raised from this- error inherits the ``INPUT`` domain through the cause chain, but never the caller-facing- flag, since its own message is not this one.+ Its report then carries a caller-facing ``message``, which STRICT disclosure keeps (see+ :class:`DisclosureMode`): the fact a class declares with ``_authors_caller_facing_message = True``. It+ serves a class raised both for the caller's faults and for faults that are not the caller's, which+ therefore cannot declare it: the raise site that knows says so there, for this one error. Who must act+ is the code's domain, which the raise site chooses with :meth:`with_error_code` when the class declares+ a set. A plain wrapper raised from this error never inherits the caller-facing flag, since its own+ message is not this one.The raise site vouches for the message: it names only the caller's own method and data(pipe codes, concept codes, variable names, the values the caller sent), never a server@@ -710,7 +811,6 @@ class PipelexError(Exception):Returns:This error, so that the raise site reads ``raise SomeError(msg).as_caller_fault()``."""- self.error_domain = ErrorDomain.INPUTself._raised_as_caller_fault = Trueif user_action is not None:self.user_action = user_action@@ -719,45 +819,35 @@ class PipelexError(Exception):def to_error_report(self) -> ErrorReport:"""Return a structured error report, enriched from the ``__cause__`` chain.- Wrapper exceptions (``PipeRunError`` -> ``PipeRouterError`` ->- ``PipelineExecutionError``) carry no ``error_category`` / ``retryable`` /- ``model`` / ``provider`` of their own. This surfaces those classification- fields from the underlying exception (typically a ``CogtError``) so they- survive every wrapping layer up to the CLI / HTTP boundary.-- ``title`` / ``type_uri`` are *wrapper-wins*: enrichment never overwrites- them with the cause's identity — the outermost wrapper's class is what- the consumer sees.+ The report's ``code`` is :meth:`resolve_error_code`, and its title, documentation page, domain and+ retry verdict are the code's. Wrapper exceptions (``PipeRunError`` -> ``PipeRouterError`` ->+ ``PipelineExecutionError``) carry no ``error_category`` / ``model`` / ``provider`` of their own: this+ surfaces those fields from the underlying exception (typically a ``CogtError``) so they survive every+ wrapping layer up to the CLI / HTTP boundary.Subclasses override to include additional fields (error_category, model,etc.); an override must end with ``self._enrich_error_report_from_cause(report)``so the cause-chain enrichment stays uniform across the hierarchy."""- report = ErrorReport(+ report = ErrorReport.make_for_code(+ code=self.resolve_error_code(),error_type=type(self).__name__,message=self.message,- title=type(self).title(),- type_uri=type(self).type_uri(),- error_domain=self.error_domain,- retryable=self.retryable,user_action=self.user_action,caller_facing_message=self._authors_caller_facing_message or self._raised_as_caller_fault,)return self._enrich_error_report_from_cause(report)def _enrich_error_report_from_cause(self, report: ErrorReport) -> ErrorReport:- """Fill the ``None`` classification fields of ``report`` from the ``__cause__`` chain.-- A wrapper keeps its own ``error_type``, ``message``, ``title``,- ``type_uri`` and ``caller_facing_message`` but inherits every- classification field it does not set itself — ``error_category``,- ``error_domain``, ``retryable``, ``user_action``, ``model``, ``provider``,- ``provider_metadata`` — from the underlying ``PipelexError`` that knows- them. ``caller_facing_message`` is pointedly NOT inherited: it records- the provenance of ``report.message``, which is always the wrapper's own- message, so a domain-less wrapper raised ``from`` an ``INPUT`` cause does- not pick up caller-facing status. ``to_error_report()`` overrides call- this so enrichment stays uniform.+ """Fill the ``None`` diagnostic fields of ``report`` from the ``__cause__`` chain.++ A wrapper keeps its own ``code`` and everything the code decides, ``error_type``, ``message`` and+ ``caller_facing_message``, but inherits every field it does not set itself — ``error_category``,+ ``user_action``, ``model``, ``provider``, ``provider_metadata`` — from the underlying ``PipelexError``+ that knows them. The code needs no inheriting here: :meth:`resolve_error_code` already walked the chain.+ ``caller_facing_message`` is pointedly NOT inherited: it records the provenance of ``report.message``,+ which is always the wrapper's own message. ``to_error_report()`` overrides call this so enrichment stays+ uniform."""cause = self.__cause__if not isinstance(cause, PipelexError):@@ -768,10 +858,10 @@ class PipelexError(Exception):if any(node is self for node in iter_cause_chain(cause)):return reportcause_report = cause.to_error_report()- # Only the cause-merged classification fields are updated; the wrapper-wins- # fields (error_type, message, title, type_uri, caller_facing_message)- # stay untouched, so a future wrapper-wins field added to ErrorReport- # does not need to be re-listed here.+ # Only the cause-merged diagnostic fields are updated; the wrapper-wins+ # fields (code, error_type, message, title, type_uri, error_domain, retryable,+ # caller_facing_message) stay untouched, so a future wrapper-wins field added+ # to ErrorReport does not need to be re-listed here.# Footgun: ``provider_metadata`` uses whole-object OR, and a Pydantic# model instance is always truthy — a wrapper that attached# attribution-only metadata (no ``status_code`` / ``retry_after_seconds``)@@ -780,8 +870,6 @@ class PipelexError(Exception):return report.model_copy(update={"error_category": report.error_category or cause_report.error_category,- "error_domain": report.error_domain or cause_report.error_domain,- "retryable": report.retryable if report.retryable is not None else cause_report.retryable,"user_action": report.user_action or cause_report.user_action,"model": report.model or cause_report.model,"provider": report.provider or cause_report.provider,@@ -791,18 +879,18 @@ class PipelexError(Exception):class PipelexUnexpectedError(PipelexError):- _declared_title = "Unexpected internal error"+ """A fault of ours: an invariant that did not hold, or a host wired wrongly."""+ error_code: ClassVar[ErrorCodeDeclaration] = CoreCode.RUNTIME_UNEXPECTED-class PipelexConfigError(PipelexError):- """A configuration this process cannot use, optionally with the migration that explains it.- ``error_domain`` stays :attr:`ErrorDomain.CONFIG` whether or not a migration is attached —- that value is a closed cross-repo enum and the agent-hook spec routes anything else to BLOCK,- so staleness is reported *inside* the CONFIG domain rather than as a domain of its own.- """+class PipelexConfigError(PipelexError):+ """A configuration this process cannot use, optionally with the migration that explains it."""- error_domain = ErrorDomain.CONFIG+ error_code: ClassVar[ErrorCodeDeclaration] = ErrorCodeSet(+ default=PipelexErrorCode.CONFIG_INVALID,+ others=(PipelexErrorCode.CONFIG_SYNTAX, PipelexErrorCode.CONFIG_FILE_MISSING),+ )def __init__(self, message: str, *, migration: MigrationErrorBlock | None = None):super().__init__(message)@@ -817,7 +905,17 @@ class PipelexConfigError(PipelexError):class PipelexSetupError(PipelexError):- error_domain = ErrorDomain.CONFIG+ """A boot that cannot complete: an embedding host calling it wrongly, or a configuration it wraps."""++ error_code: ClassVar[ErrorCodeDeclaration] = InheritsCause(+ fallback=CoreCode.RUNTIME_MISCONFIGURED,+ others=(+ CoreCode.RUNTIME_UNEXPECTED,+ PipelexErrorCode.CONFIG_FILE_MISSING,+ PipelexErrorCode.CONFIG_INVALID,+ PipelexErrorCode.CONFIG_SYNTAX,+ ),+ )class SecurityError(PipelexError):@@ -827,4 +925,4 @@ class SecurityError(PipelexError):swallowed by domain-level `except` handlers (e.g. `except PipelexError`)."""- _declared_title = "Security policy violation"+ error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERRORdiff --git a/pipelex/cli/agent_cli/CLAUDE.md b/pipelex/cli/agent_cli/CLAUDE.mdindex 5ec7a1406..d94b02c57 100644--- a/pipelex/cli/agent_cli/CLAUDE.md+++ b/pipelex/cli/agent_cli/CLAUDE.md@@ -99,7 +99,7 @@ commands/## Key Patterns- **Output contract**: Commands with `--format` emit success via `agent_success_formatted(result, markdown_renderer, output_format)` — JSON or a markdown renderer per the explicit `output_format` argument. `agent_error(message, error_type, cause)` dispatches JSON or markdown by reading the `_agent_cli_error_format` ContextVar, which each `--format`-aware command sets via `set_agent_cli_error_format(error_format or output_format)` at function entry. Exceptions that print directly to stdout: `fmt`/`lint` (plxt passthrough) and `inputs --format toml` (the raw TOML template). Markdown renderers: `format_run_markdown` (`run/_output_helpers.py`), `format_validate_markdown` (lifted to the non-CLI `pipelex/pipeline/validation_render.py` so `pipelex-api` can import it without CLI/Typer deps), `format_fix_markdown` (non-CLI `pipelex/pipeline/fixes/fix_render.py`), `_format_init_markdown` (`init_cmd.py`).-- **Error classification**: Each error carries a domain (`input`, `config`, `runtime`), a hint string, and a `retryable` flag. `agent_error()` reads them **report-first**: a `PipelexError` cause's `to_error_report()` wins, and the `AGENT_ERROR_HINTS` / `AGENT_ERROR_DOMAINS` dicts in `agent_output.py` are the fallback for error types that cannot self-describe (builtins, third-party classes, synthetic `error_type` labels). Two ways a class self-describes, and both bar it from the dicts: a class-level `error_domain` / `user_action`, **or** — for the `CogtError` family — an `error_category`, from which `InferenceErrorCategory.error_domain` derives the domain (so `CONTENT` inference failures report `input`, and a dict entry for such a class would be unreachable). `tests/unit/pipelex/cli/test_agent_output_drift.py` enforces both. Because the read is report-first, the `error_type` an arm passes must name the class that actually failed — `type(exc).__name__`, not the base class the `except` caught. A hardcoded label detaches the reported class from the domain and hint riding the same envelope from the cause's report, so a consumer reading `error_type` is told one class produced a classification only another declares; the `validate pipe` / `validate bundle` not-found arms did exactly that until the entry-shaped lookups gained their own INPUT-domain classes. A synthetic label is still legitimate where there is no exception class to name, and that is what the dicts key on. The run arms are the one deliberate exception: they pass `PipelineExecutionError`, the one class a run failure arrives as, and `run_failure_fields()` adds `pipe_code` / `pipe_stack` (the failing pipe and its path) and `cause_type` / `cause_message` (the root fault's, found with `find_root_fault()`, never the router wrapper right under the run error); the classification and the located message come from the run error's report, which is its root fault's. When a derived domain is wrong for a class, declare an explicit `error_domain` on the class — `ModelChoiceNotFoundError` does, because a mistyped model reference is the caller's to fix even though the category is `CONFIGURATION`. The `error_domain` also drives the HTTP-status mapping for downstream APIs — see `error_domain_to_http_status()` in `pipelex/base_exceptions.py` and [Error Model](../../../docs/under-the-hood/error-model.md).+- **Error classification**: Each error carries a domain (`input`, `config`, `runtime`), a hint string, and a `retryable` flag. `agent_error()` reads them **report-first**: a `PipelexError` cause's `to_error_report()` wins, and every `PipelexError` carries a registry code, which decides the report's domain and its `retryable` verdict, so the report always holds both. The envelope names that code as `error_code`, the member a hosted refusal carries too; a cause that is not a `PipelexError` has no code and the envelope names none. The `AGENT_ERROR_DOMAINS` dict in `agent_output.py` is the fallback for the error types that carry no code alone (builtins, third-party classes, synthetic `error_type` labels), and no `PipelexError` subclass may sit in it, since its entry could never be read; `AGENT_ERROR_HINTS` may still name one, being read only when the report gives no next step, but not one that declares a class-level `user_action`. There is no retryable lookup: only a code's verdict, or a `retryable` passed in `extra`, sets it. `tests/unit/pipelex/cli/test_agent_output_drift.py` enforces these. Because the read is report-first, the `error_type` an arm passes must name the class that actually failed — `type(exc).__name__`, not the base class the `except` caught. A hardcoded label detaches the reported class from the domain and hint riding the same envelope from the cause's report, so a consumer reading `error_type` is told one class produced a classification only another declares; the `validate pipe` / `validate bundle` not-found arms did exactly that until the entry-shaped lookups gained their own INPUT-domain classes. A synthetic label is still legitimate where there is no exception class to name, and that is what the dicts key on. The run arms are the one deliberate exception: they pass `PipelineExecutionError`, the one class a run failure arrives as, and `run_failure_fields()` adds `pipe_code` / `pipe_stack` (the failing pipe and its path) and `cause_type` / `cause_message` (the root fault's, found with `find_root_fault()`, never the router wrapper right under the run error); the classification and the located message come from the run error's report, which is its root fault's. When the domain a class reports is wrong, the class needs another code, never a dict entry. The `error_domain` also drives the HTTP-status mapping for downstream APIs — see `error_domain_to_http_status()` in `pipelex/base_exceptions.py` and [Error Model](../../../docs/under-the-hood/error-model.md).- **The `migration` field on a configuration error**: A `PipelexConfigError` carries one when a scan of this machine's configuration directories found something — and only then, so its presence is the test for whether the migration history has anything to say. Whether a command *repairs* it is the separate `would_write` field: true means the configuration is *old*, and the loop is `pipelex-agent migrate --dry-run --format json`, show the user, then `--yes`; false means the block is a diagnosis its `plans` carry and the command would rewrite nothing, so branching on presence alone sends an agent to a run with nothing to do. Its `plans` are the same shape that command emits under its own `plans` key. `error_domain` stays `config`: a domain the hook specification does not know routes to BLOCK, which would stop an agent instead of telling it what to run. See `docs/migration-ledger.md` → "Reporting a stale configuration on a validation error".- **Init**: All commands that need Pipelex use `make_pipelex_for_agent_cli(library_dirs)`. It catches init errors and routes them through `agent_error()`.- **Async core**: Run and validate are async — commands use `asyncio.run()`.@@ -108,7 +108,7 @@ commands/- **Run refusals are verdicts too**: a run loads its bundle inside the same translation (`acquire_library`), so an invalid bundle leaves `run pipe` / `run bundle` / `run method` as a `ValidateBundleError` with exit 1, through the generic `agent_error` arm, and `_assemble_error_payload` copies the report's `validation_errors` into the envelope for any cause that carries them. `run_pipeline_core` sets `library_dirs_are_callers=True`, so a refusal in a `-L` directory (or the bundle's own directory) is the same verdict; `run bundle`'s own parse of a bundle without `--pipe` goes through the translation too, and so does its reading of the method tree: a folder resolves through `pipelex/cli/bundle_target_resolution.py` (`resolve_method_folder_run`, the protocol's entry rule in `pipelex/pipeline/method_entry.py`) and a lone file through `list_bundle_file_tree`, so a folder with no single `main_pipe`, a tree past its limits or a symbolic link in the tree is a `ValidateBundleError` too. So no `run` command keeps an arm of its own for a model-choice error either: an unknown model reaches it as the verdict's `unknown_model` item.- **Two readings of a folder, one resolution path**: `run bundle`, `validate bundle`, `fix bundle` and `inputs bundle` read a folder through `pipelex/cli/bundle_target_resolution.py` (`run` through `resolve_method_folder_run`, the others through `resolve_bundle_target_core`, validate and fix by way of `pipelex/cli/judged_target.py`, whose `JudgedBundleTarget.judged_path` is the path the verdict names and whose `fix_judged_target` is the one fix dispatch both CLIs call, and of `commands/bundle_path_resolver.py`), as its method tree, but with the `FolderReading` their job asks for. `validate` and `fix` take `WHOLE_TREE`, the MTHDS protocol's validation (`mthds/docs/spec/protocol.md`): every bundle of the tree is judged (`validate_bundle(method_dir=..., library_dirs_are_callers=True)`, `fix_method_folder`), with no pipe to start at, so a folder whose bundles declare several `main_pipe`s, or none, is validated like any other; mthds-js's local runner calls `pipelex validate bundle <dir>` to validate a whole method at install and relies on this. `--pipe` there only narrows the dry run, and `--graph` / `--view` draw from the pipe named, else from the entry (`locate_folder_pipe`), or, when the folder decides none, put `graph_unavailable` in the envelope and leave the verdict alone. `run` and `inputs` take `ENTRY_PIPE`, acting on one pipe: the one `--pipe` names, else the protocol's entry (`select_method_entry` in `pipelex/pipeline/method_entry.py`); no single `main_pipe` is a `ValidateBundleError` verdict on a run and the `MethodEntryError` with exit 1 on `inputs`, the message the same. A folder holding no bundle is `EmptyMethodTreeError` with exit 2 on `validate` and `fix`, and a `MethodEntryError` saying it has no pipe to start at on the others. A folder whose tree is refused at resolution (past its limits, a symbolic link) is the invalid verdict: `ValidateBundleError` on `validate`, and on `fix` the `FixBundleError` envelope of a fix that could not start (`unfixable_method_result`), exit 1 both. A fix of a folder writes anywhere in its method tree, from the root (`method_tree_root`) down, and the human `--diff` preview mirrors that root, so a fix landing in a bundle above the folder named is proposed and written alike. Only the tree's own pipes are judged: `validate_bundle(method_dir=...)` keeps the blueprints its tree lists (`_is_member_blueprint`), so a nested package, a dependency or a `-L` directory loads without being judged; `dirs_beside_method` is the one place the `-L` directories naming the folder itself are dropped, compared resolved. Reading the tree's limits loads the configuration before the boot, so each resolution site catches `PipelexConfigError` and reports it through `report_agent_init_failure` (`agent_cli_factory.py`), the envelope a failed boot gives.- **Hosted runs**: every `run` subcommand takes `--runner local|hosted`, `--hosted/--local` and `--base-url`; `resolve_agent_run_execution()` (`run/_run_hosted.py`) settles them through `pipelex.hosted.execution.resolve_run_execution` (the flag, then `[run] execution`, then local), refusing a `--runner` that contradicts the flag pair and a `--base-url` on a local run; a `PipelexConfigError` there carries `AGENT_INIT_FAILURE_HINT`, the hint a failed boot gives (`agent_cli_factory.py`). A hosted run boots nothing: it builds a `HostedRunRequest` from what `pipelex/cli/commands/run/_hosted_sources.py` resolves (the bundle and its library's `.mthds` files, a pipe's library, or a method's files; an address or a catalog id as `method_ref` / `method_id`, never fetched) and `run_hosted_for_agent()` runs it through `pipelex.hosted.hosted_run.run_hosted`, which reads the signature and uploads local input files (only when some input string names an existing local file, so a method with an address-based dependency runs with any other inputs), then drives the lifecycle `start_and_wait` drives step by step (the `/v1/version` handshake, `start`, `wait_for_result`, and the blocking `execute` on a server with no run store), so a failure while following an acknowledged run is a `HostedRunPollingError` naming the run, and a transport failure after the run request was sent is a `HostedRunOutcomeUnknownError` rather than an `ApiUnreachableError`. `run_hosted`'s `on_started` callback records the acknowledged run's id, so Ctrl-C (`KeyboardInterrupt`, or the `CancelledError` of a cancelled task) leaves as a `HostedRunInterruptedError` envelope carrying `pipeline_run_id`, with exit code 130. `run bundle` on a file with no `-L` sends `PIPELEXPATH`'s files (`hosted_library_dirs`), and an installed method named like a catalog id is that method. An exception no hosted arm names leaves through the command-boundary catch-all as the envelope. Its success envelope is `build_run_output()`'s, with the main output's content as `json`, an empty `markdown`, the working memory dump and `pipeline_run_id`; nothing is written to disk. `--dry-run` / `--mock-inputs` are refused on it, while `--graph` and `--costs` are accepted and ignored. There is no global `--runner` any more, and no `ctx.obj`.-- **Hosted refusals**: `agent_error_hosted()` routes pipelex-sdk's `ApiResponseError` (every `PipelexAPIClient` route raises it on a non-2xx answer) to `agent_error_api_response()`. `api_response_error_payload()` builds the envelope from the problem document alone: `error_type` is the runner's class (`ValidateBundleError` at load, as a local run reports it, or the root fault of a failed run, which a local run reports as `cause_type` under `PipelineExecutionError`; this path has no `cause_type`), `message` is the error's own `API POST /v1/start failed (<status>): <reason>` without the next step it appends, `hint` is `user_action.detail`, and `error_domain` / `error_category` / `retryable` / `validation_errors` / `pipe_code` / `pipe_stack` / `request_id` are the runner's, plus `error_code` (the problem's `code`), `retry_after_seconds` (the `Retry-After` header) and `http_status`. It deliberately bypasses `agent_error()`'s lookups: the dict hints keyed on a class name local commands (`doctor`, `check-model`) that cannot fix a remote refusal, and the domain is only the runner's to say, so one with no `error_domain` carries none. Both `error_domain` and `retryable` come from `pipelex.hosted.error_rendering.sent_verdict()`, the members the problem document carried, never from the verdict pipelex-sdk decides for every `ApiResponseError`, which fills an unsent member from its own status table and reads every 5xx, a 503 included, as retryable. A refusal with no `user_action` — the hosted plane's own answers in front of the runner: the gateway's 403 for a bad key, the rate limiter's 429, the unreachable runner's 503 — gets its status's next step from `pipelex.hosted.error_rendering` (`HOSTED_REFUSAL_NEXT_STEPS_BY_STATUS`, the table the human CLI reads too; 401 and 403 point at `PIPELEX_API_KEY` and `pipelex login`, 404 at the method and the origin), else `HOSTED_REFUSAL_CALLER_NEXT_STEP` for any other 4xx and `HOSTED_SERVER_FAULT_NEXT_STEP` for the rest. Only a 429 that did not say otherwise is inferred `retryable`: the platform can answer a 503 after the run completed, when it failed to record the result, so its hint warns that a retry can repeat a paid run. Every other failure, the SDK's and pipelex's own `HostedRunError` subclasses alike, goes through `agent_error()` with what `describe_hosted_error()` reads off it, the view the human CLI prints too: the class, message, next step, domain and `retryable`, the `pipeline_run_id` of any failure met once the run was acknowledged (`RunFailedError`, `RunTimeoutError`, `MissingMainStuffError`, `HostedRunPollingError`, `HostedRunInterruptedError`), a `retryable` passed whenever the hosted API gave a verdict, `false` included, so `RETRYABLE_ERROR_TYPES` keyed on the runner's class never overrides it, and the `validation_errors` of a failed run or of a `HostedMethodInvalidError` (pipe-io's verdict on a method that does not load, whose items name the faulty file in `source`); a `RunFailedError` adds `run_status` and its report's category, model and provider. The markdown renderer keeps a runner item this pipelex's `ValidationErrorItem` cannot type (a newer `error_type`, an unknown field) as JSON under Details instead of failing.+- **Hosted refusals**: `agent_error_hosted()` routes pipelex-sdk's `ApiResponseError` (every `PipelexAPIClient` route raises it on a non-2xx answer) to `agent_error_api_response()`. `api_response_error_payload()` builds the envelope from the problem document alone: `error_type` is the runner's class (`ValidateBundleError` at load, as a local run reports it, or the root fault of a failed run, which a local run reports as `cause_type` under `PipelineExecutionError`; this path has no `cause_type`), `message` is the error's own `API POST /v1/start failed (<status>): <reason>` without the next step it appends, `hint` is `user_action.detail`, and `error_domain` / `error_category` / `retryable` / `validation_errors` / `pipe_code` / `pipe_stack` / `request_id` are the runner's, plus `error_code` (the problem's `code`, the member a local envelope fills from its cause's registry code), `retry_after_seconds` (the `Retry-After` header) and `http_status`. It deliberately bypasses `agent_error()`'s lookups: the dict hints keyed on a class name local commands (`doctor`, `check-model`) that cannot fix a remote refusal, and the domain is only the runner's to say, so one with no `error_domain` carries none. Both `error_domain` and `retryable` come from `pipelex.hosted.error_rendering.sent_verdict()`, the members the problem document carried, never from the verdict pipelex-sdk decides for every `ApiResponseError`, which fills an unsent member from its own status table and reads every 5xx, a 503 included, as retryable. A refusal with no `user_action` — the hosted plane's own answers in front of the runner: the gateway's 403 for a bad key, the rate limiter's 429, the unreachable runner's 503 — gets its status's next step from `pipelex.hosted.error_rendering` (`HOSTED_REFUSAL_NEXT_STEPS_BY_STATUS`, the table the human CLI reads too; 401 and 403 point at `PIPELEX_API_KEY` and `pipelex login`, 404 at the method and the origin), else `HOSTED_REFUSAL_CALLER_NEXT_STEP` for any other 4xx and `HOSTED_SERVER_FAULT_NEXT_STEP` for the rest. Only a 429 that did not say otherwise is inferred `retryable`: the platform can answer a 503 after the run completed, when it failed to record the result, so its hint warns that a retry can repeat a paid run. Every other failure, the SDK's and pipelex's own `HostedRunError` subclasses alike, goes through `agent_error()` with what `describe_hosted_error()` reads off it, the view the human CLI prints too: the class, message, next step, domain and `retryable`, the `pipeline_run_id` of any failure met once the run was acknowledged (`RunFailedError`, `RunTimeoutError`, `MissingMainStuffError`, `HostedRunPollingError`, `HostedRunInterruptedError`), a `retryable` passed whenever the hosted API gave a verdict, `false` included, and the `validation_errors` of a failed run or of a `HostedMethodInvalidError` (pipe-io's verdict on a method that does not load, whose items name the faulty file in `source`); a `RunFailedError` adds `run_status` and its report's category, model and provider. The markdown renderer keeps a runner item this pipelex's `ValidationErrorItem` cannot type (a newer `error_type`, an unknown field) as JSON under Details instead of failing.- **Method-reference failures**: the `run`/`validate`/`inputs` method commands call `resolve_method_target(..., raise_ref_errors=True)` and shape the typed `MethodRefError` subclasses into `agent_error(...)` themselves (validate uses `exit_code=2`, its no-verdict convention) — the human CLI's red-text rendering stays in `resolve_method_target`'s default arm.- **Usage statistics**: the root callback runs every command through `run_with_usage_stats` (`pipelex/cli/usage_stats_cli.py`) with surface `pipelex-agent`, which reads the switches before the command does anything and sends one `command_completed` when it ends. Stderr is a machine contract when the invocation's errors are JSON (`--error-format json`, or `--format json` with no `--error-format`), so the anonymous-statistics notice is then neither printed nor recorded, though the events are still sent. `_assemble_error_payload` and `api_response_error_payload` note the envelope's `error_domain` as the command's, never the error itself. `fmt` and `lint` start `plxt` with `PIPELEX_USAGE_STATS=0`, since the command's statistics are this CLI's own. There is no `usage-stats` group here: `pipelex usage-stats` serves both CLIs. The contract is `conformance/specs/usage-statistics.md`; the user docs are `docs/setup/usage-statistics.md`.- **TOML handling**: Uses `tomlkit` (not `tomllib`) to preserve formatting and inline tables.diff --git a/pipelex/cli/agent_cli/commands/agent_cli_factory.py b/pipelex/cli/agent_cli/commands/agent_cli_factory.pyindex 512ca7ac6..1e816dea1 100644--- a/pipelex/cli/agent_cli/commands/agent_cli_factory.py+++ b/pipelex/cli/agent_cli/commands/agent_cli_factory.py@@ -8,7 +8,7 @@ from types import MappingProxyTypefrom typing import Any, NoReturnfrom pipelex.cli.agent_cli.commands.agent_output import agent_error-from pipelex.cogt.exceptions import ModelDeckPresetValidatonError+from pipelex.cogt.exceptions import ModelDeckPresetValidationErrorfrom pipelex.migration.exceptions import FormerReleaseConfigErrorfrom pipelex.pipelex import Pipelexfrom pipelex.runtime_hub import RuntimeHub@@ -176,10 +176,10 @@ def report_agent_init_failure(*, error: Exception) -> NoReturn:# Its own hint, the class's user_action, rather than the generic one, which offers a reset: the cleanup keeps# everything but what a former release left, and an agent can run it.agent_error(error.message, error_type="FormerReleaseConfigError", cause=error)- if isinstance(error, ModelDeckPresetValidatonError):+ if isinstance(error, ModelDeckPresetValidationError):agent_error(error.message,- error_type="ModelDeckPresetValidatonError",+ error_type="ModelDeckPresetValidationError",cause=error,preset_id=error.preset_id,model_type=str(error.model_type),diff --git a/pipelex/cli/agent_cli/commands/agent_output.py b/pipelex/cli/agent_cli/commands/agent_output.pyindex 10588465f..bdc4f04b6 100644--- a/pipelex/cli/agent_cli/commands/agent_output.py+++ b/pipelex/cli/agent_cli/commands/agent_output.py@@ -66,22 +66,16 @@ def get_agent_cli_error_format() -> CliOutputFormat:# Fallback error-classification lookups, keyed by error_type name.#-# agent_error() reads error_domain / user_action from a PipelexError cause's-# to_error_report() first; these dicts are the fallback for error types that-# cannot self-describe: builtin and third-party exceptions, synthetic error_type-# labels passed straight to agent_error(), and PipelexError subclasses not yet-# migrated to class-level metadata. A PipelexError subclass that declares-# class-level error_domain / user_action must NOT appear here — enforced by-# tests/unit/pipelex/cli/test_agent_output_drift.py.-#-# A CogtError subclass carrying an error_category self-describes too, without any-# class-level error_domain of its own: InferenceErrorCategory.error_domain derives-# one, and to_error_report() puts it on the report, so the report-first read at the-# bottom of agent_error() always wins and an AGENT_ERROR_DOMAINS entry for such a-# class can never be read. Those are barred from this dict as well, by the same-# drift test — a dead entry is exactly the rot it exists to prevent. When the-# derived domain is not the one this CLI wants, fix it on the class (declare an-# explicit error_domain, as ModelChoiceNotFoundError does), never here.+# agent_error() reads error_domain / retryable / user_action from a PipelexError+# cause's to_error_report() first, and every PipelexError carries a registry code,+# which decides its domain and its retry verdict: the report always holds both. So+# AGENT_ERROR_DOMAINS is the fallback for the error types that carry no code alone:+# builtin and third-party exceptions, and synthetic error_type labels passed straight+# to agent_error(). A PipelexError subclass must NOT appear in it, since its entry+# could never be read; when the domain the code projects is not the one this CLI+# wants, the class needs another code, never an entry here. AGENT_ERROR_HINTS may+# still name a PipelexError subclass: a hint is read only when the report gives no+# next step. Both are enforced by tests/unit/pipelex/cli/test_agent_output_drift.py.# An unknown model is the author's input fault, whether it is raised bare by the deck check or located# on its pipe: the next step is to correct the reference, not to diagnose the installation._UNKNOWN_MODEL_HINT = (@@ -99,7 +93,7 @@ AGENT_ERROR_HINTS: dict[str, str] = {"ModelChoiceNotFoundError": _UNKNOWN_MODEL_HINT,"PipeOperatorModelChoiceError": _UNKNOWN_MODEL_HINT,"PipeOperatorModelAvailabilityError": "Run 'pipelex-agent doctor' to check available models and verify API keys",- "ModelDeckPresetValidatonError": (+ "ModelDeckPresetValidationError": ("Run 'pipelex-agent doctor' to check model configuration. ""Update the preset model, configure it in an enabled backend, or enable a supporting backend"),@@ -133,8 +127,6 @@ AGENT_ERROR_HINTS: dict[str, str] = {"Without a 'migration' field, correct the telemetry.toml settings named in the message."),"BinaryNotFoundError": "Install pipelex-tools: uv tool install pipelex-tools",- # Graph errors- "GraphSpecParseError": "Validate graphspec.json structure; ensure it matches the expected GraphSpec schema",# Input/type errors"JsonTypeError": "Input file must be a JSON object {...}, not an array or scalar value","TomlError": "Fix the TOML syntax error (the message includes the line and column)",@@ -154,32 +146,20 @@ AGENT_ERROR_HINTS: dict[str, str] = {"UnknownCommandError": "Check 'valid_commands' in this error response for available commands",}-# retryable=True fallback for non-CogtError error types: their ErrorReport-# carries no `retryable`, unlike CogtError whose error_category drives it.-RETRYABLE_ERROR_TYPES: set[str] = {- "PipeOperatorModelAvailabilityError",-}-AGENT_ERROR_DOMAINS: dict[str, str] = {# input = agent can fix (bad .mthds, wrong args, bad JSON)- "PipeValidationError": "input","FixBundleError": "input","FileNotFoundError": "input","JSONDecodeError": "input","StdinEnvelopeShapeError": "input",- "JsonTypeError": "input",- "TomlError": "input","ArgumentError": "input","ValidationError": "input","ValueError": "input","BundleError": "input",- "GraphSpecParseError": "input","UnknownCommandError": "input","CodegenDriftError": "input","CodegenLockNotFoundError": "input",- "CodegenLockError": "input",# config = environment/config changes needed- "PipeOperatorModelAvailabilityError": "config","BinaryNotFoundError": "config","InitConfigError": "config",}@@ -219,7 +199,7 @@ def _build_error_source(exc: BaseException) -> list[str]:def _assemble_error_payload(message: str, *, error_type: str, cause: BaseException | None, extra: dict[str, Any]) -> dict[str, Any]:"""Build the structured error payload shared by the JSON and markdown renderers.- Sources ``hint`` / ``retryable`` / ``error_domain`` / ``error_category`` /+ Sources ``hint`` / ``retryable`` / ``error_domain`` / ``error_code`` / ``error_category`` /``model`` / ``provider`` from a ``PipelexError`` cause's ``to_error_report()``first, falling back to the lookup dicts for error types that cannotself-describe. ``extra`` is merged last and overrides everything.@@ -246,6 +226,7 @@ def _assemble_error_payload(message: str, *, error_type: str, cause: BaseExceptireport_retryable: bool | None = Nonereport_category: str | None = Nonereport_domain: str | None = None+ report_code: str | None = Nonereport_extras: dict[str, Any] = {}if isinstance(cause, PipelexError):@@ -254,6 +235,7 @@ def _assemble_error_payload(message: str, *, error_type: str, cause: BaseExceptireport_retryable = report.retryablereport_category = report.error_categoryreport_domain = report.error_domain+ report_code = report.codeif report.model:report_extras["model"] = report.modelif report.provider:@@ -268,20 +250,21 @@ def _assemble_error_payload(message: str, *, error_type: str, cause: BaseExceptiif hint:error_json["hint"] = hint- # retryable: report takes precedence, fallback to lookup set (only emit when True)- if report_retryable is not None:- if report_retryable:- error_json["retryable"] = True- elif error_type in RETRYABLE_ERROR_TYPES:+ # retryable: the report's verdict, which its code decides (only emit when True)+ if report_retryable:error_json["retryable"] = True- # error_domain: report-first (class-level metadata), lookup dict as fallback+ # error_domain: report-first (its code's projection), lookup dict as fallback for an error that carries no codedomain = report_domain or AGENT_ERROR_DOMAINS.get(error_type)if domain:error_json["error_domain"] = domain# The command's usage statistics carry the same classification, never the error itself.note_command_error_domain(error_domain=usage_stats_error_domain_of(domain=domain))+ # error_code: the cause's registry code, the member a hosted refusal carries as well; an uncoded cause names none+ if report_code:+ error_json["error_code"] = report_code+# error_category: from report when availableif report_category:error_json["error_category"] = report_category@@ -518,7 +501,7 @@ def api_response_error_payload(*, error: ApiResponseError) -> dict[str, Any]:- ``http_status`` and ``request_id`` are what to quote when the fault is the runner's.- ``error_source`` is the client-side trace, as on every JSON envelope."""- problem: dict[str, Any] = error.problem or {}+ problem: dict[str, Any] = error.problem_document or {}payload: dict[str, Any] = {"error": True,"error_type": error.error_type or type(error).__name__,diff --git a/pipelex/cli/agent_cli/commands/codegen/types_cmd.py b/pipelex/cli/agent_cli/commands/codegen/types_cmd.pyindex 5c78bd708..7ada455f0 100644--- a/pipelex/cli/agent_cli/commands/codegen/types_cmd.py+++ b/pipelex/cli/agent_cli/commands/codegen/types_cmd.py@@ -22,6 +22,7 @@ from pipelex.cli.agent_cli.commands.agent_output import (set_agent_cli_error_format,)from pipelex.cli.commands.crate_loading import load_normalized_crate+from pipelex.cli.exceptions import BundleClosureEmptyErrorfrom pipelex.codegen.emission import write_stamped_projectionfrom pipelex.codegen.emitters.target import CodegenKind, CodegenTargetfrom pipelex.codegen.emitters.types_emitter import emit_types@@ -89,6 +90,9 @@ def agent_codegen_types_cmd(except FileNotFoundError as exc:# No verdict: the closure could not even be assembled.agent_error(f"Cannot resolve — {exc}", error_type="FileNotFoundError", cause=exc, exit_code=2)+ except BundleClosureEmptyError as exc:+ # No verdict: the closure holds no bundle to read.+ agent_error(f"Cannot resolve — {exc}", error_type=type(exc).__name__, cause=exc, exit_code=2)generation_report.describe(crate=crate)emitted = emit_types(crate, target=target)diff --git a/pipelex/cli/agent_cli/commands/inputs/pipe_cmd.py b/pipelex/cli/agent_cli/commands/inputs/pipe_cmd.pyindex 5c9c233b0..73b79e57c 100644--- a/pipelex/cli/agent_cli/commands/inputs/pipe_cmd.py+++ b/pipelex/cli/agent_cli/commands/inputs/pipe_cmd.py@@ -11,6 +11,7 @@ import typerfrom pipelex.cli.agent_cli.commands.agent_cli_factory import make_pipelex_for_agent_clifrom pipelex.cli.agent_cli.commands.agent_output import agent_error, extract_validation_errorsfrom pipelex.cli.agent_cli.commands.inputs._inputs_core import emit_inputs_result, inputs_core+from pipelex.cli.exceptions import ExportedPipeAmbiguousErrorfrom pipelex.cli.method_resolver import resolve_pipe_from_exportsfrom pipelex.core.pipes.exceptions import PipeOperatorModelChoiceErrorfrom pipelex.mthds_parsing.helpers import MTHDS_EXTENSION, is_pipelex_file@@ -61,7 +62,7 @@ def inputs_pipe_cmd(# Check installed methods' exports for additional library dirstry:export_dirs = resolve_pipe_from_exports(pipe_code)- except ValueError as exc:+ except ExportedPipeAmbiguousError as exc:agent_error(f"Ambiguous pipe code '{pipe_code}': {exc}",error_type="ArgumentError",diff --git a/pipelex/cli/agent_cli/commands/run/pipe_cmd.py b/pipelex/cli/agent_cli/commands/run/pipe_cmd.pyindex f421c75ee..f6be2d8b0 100644--- a/pipelex/cli/agent_cli/commands/run/pipe_cmd.py+++ b/pipelex/cli/agent_cli/commands/run/pipe_cmd.py@@ -29,6 +29,7 @@ from pipelex.cli.agent_cli.commands.run._run_hosted import ()from pipelex.cli.agent_cli.commands.run.stdin_resolver import parse_cli_inputsfrom pipelex.cli.commands.run._hosted_sources import hosted_pipe_library_files+from pipelex.cli.exceptions import ExportedPipeAmbiguousErrorfrom pipelex.cli.method_resolver import resolve_pipe_from_exportsfrom pipelex.hosted.exceptions import HostedRunSourceErrorfrom pipelex.hosted.hosted_run import HostedRunRequest@@ -124,7 +125,7 @@ def run_pipe_cmd(# Check installed methods' exports for additional library dirstry:export_dirs = resolve_pipe_from_exports(pipe_code)- except ValueError as exc:+ except ExportedPipeAmbiguousError as exc:agent_error(f"Ambiguous pipe code '{pipe_code}': {exc}",error_type="ArgumentError",diff --git a/pipelex/cli/agent_cli/commands/run/stdin_resolver.py b/pipelex/cli/agent_cli/commands/run/stdin_resolver.pyindex 5349c102b..847552a86 100644--- a/pipelex/cli/agent_cli/commands/run/stdin_resolver.py+++ b/pipelex/cli/agent_cli/commands/run/stdin_resolver.py@@ -7,6 +7,8 @@ import sysfrom pathlib import Pathfrom typing import Any, NamedTuple, cast+from mthds.protocol.problem.registry import CoreCode+from pipelex.cli.agent_cli.commands.agent_output import agent_errorfrom pipelex.cli.commands.run._inputs_file_loader import load_inputs_dict_from_bytes, load_inputs_dict_from_path, read_default_inputs_filefrom pipelex.cli.commands.run._inputs_path_resolver import resolve_inputs_paths@@ -229,7 +231,8 @@ def _parse_inputs_file(*, inputs_path: Path, label: str, data: bytes | None) ->except JsonTypeError as exc:agent_error(f"Input file must be a valid JSON dictionary: {label}", error_type="JsonTypeError", cause=exc)except TomlError as exc:- agent_error(exc.message, error_type="TomlError", cause=exc)+ # The inputs file is the caller's request, not the runtime's configuration.+ agent_error(exc.message, error_type="TomlError", cause=exc.with_error_code(CoreCode.REQUEST_MALFORMED))def _read_stdin_inputs() -> dict[str, Any] | None:diff --git a/pipelex/cli/agent_cli/commands/validate/pipe_cmd.py b/pipelex/cli/agent_cli/commands/validate/pipe_cmd.pyindex 9a315ab32..c945950c8 100644--- a/pipelex/cli/agent_cli/commands/validate/pipe_cmd.py+++ b/pipelex/cli/agent_cli/commands/validate/pipe_cmd.py@@ -18,6 +18,7 @@ from pipelex.cli.agent_cli.commands.validate._validate_core import (validate_all_core,validate_pipe_core,)+from pipelex.cli.exceptions import ExportedPipeAmbiguousErrorfrom pipelex.cli.method_resolver import resolve_pipe_from_exportsfrom pipelex.libraries.pipe.exceptions import PipeNotFoundErrorfrom pipelex.mthds_parsing.helpers import MTHDS_EXTENSION, is_pipelex_file@@ -145,7 +146,7 @@ def validate_pipe_cmd(# Check installed methods' exports for additional library dirstry:export_dirs = resolve_pipe_from_exports(pipe_code)- except ValueError as exc:+ except ExportedPipeAmbiguousError as exc:agent_error(f"Ambiguous pipe code '{pipe_code}': {exc}",error_type="ArgumentError",diff --git a/pipelex/cli/bundle_target_resolution.py b/pipelex/cli/bundle_target_resolution.pyindex a712accba..0a8fb2b29 100644--- a/pipelex/cli/bundle_target_resolution.py+++ b/pipelex/cli/bundle_target_resolution.py@@ -24,6 +24,7 @@ from typing import NamedTuplefrom mthds.method_tree.discovery import BUNDLE_SUFFIXfrom mthds.method_tree.models import MethodTree+from mthds.protocol.problem.registry import CoreCodefrom pipelex.libraries.exceptions import EmptyMethodTreeError, MethodTreeLoadErrorfrom pipelex.libraries.method_trees import list_local_method_tree@@ -99,7 +100,7 @@ def resolve_method_folder(*, directory: Path, pipe_override: str | None) -> Methtree = list_method_folder(directory=directory)except EmptyMethodTreeError as exc:msg = f"The folder '{directory}' holds no .mthds bundle, so it has no pipe to start at."- raise MethodEntryError(msg) from exc+ raise MethodEntryError(msg).with_error_code(CoreCode.METHOD_INVALID) from excif pipe_override:return MethodFolderTarget(tree=tree, pipe_code=pipe_override, entry=None, entry_bundle_file=None)with translate_to_validate_bundle_error():diff --git a/pipelex/cli/cli_factory.py b/pipelex/cli/cli_factory.pyindex 310ad1a2d..9768ead84 100644--- a/pipelex/cli/cli_factory.py+++ b/pipelex/cli/cli_factory.py@@ -8,7 +8,7 @@ from pipelex.cli.error_handlers import (handle_model_deck_preset_error,handle_telemetry_config_validation_error,)-from pipelex.cogt.exceptions import ModelDeckPresetValidatonError+from pipelex.cogt.exceptions import ModelDeckPresetValidationErrorfrom pipelex.migration.exceptions import FormerReleaseConfigErrorfrom pipelex.pipelex import Pipelexfrom pipelex.system.runtime import IntegrationMode@@ -49,7 +49,7 @@ def make_pipelex_for_cli()except TelemetryConfigValidationError as exc:handle_telemetry_config_validation_error(exc)- except ModelDeckPresetValidatonError as exc:+ except ModelDeckPresetValidationError as exc:handle_model_deck_preset_error(exc, context=context)except FormerReleaseConfigError as exc:handle_former_release_config_error(exc=exc)diff --git a/pipelex/cli/commands/build/inputs/_inputs_core.py b/pipelex/cli/commands/build/inputs/_inputs_core.pyindex e5c2bd98e..30246cd2c 100644--- a/pipelex/cli/commands/build/inputs/_inputs_core.py+++ b/pipelex/cli/commands/build/inputs/_inputs_core.py@@ -13,7 +13,6 @@ from pipelex.cli.error_handlers import (handle_model_choice_error,)from pipelex.core.pipes.exceptions import PipeOperatorModelChoiceError-from pipelex.core.pipes.inputs.exceptions import PipeInputErrorfrom pipelex.interpreter_hub import get_library_manager, get_required_entry_pipe, resolve_library_dirs, set_current_libraryfrom pipelex.pipe_machinery.rendering.input_renderer import InputsTemplateFormat, NoInputsRequiredError, render_inputs, render_inputs_tomlfrom pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityError@@ -76,9 +75,6 @@ async def _generate_inputs_core(except ValidateBundleError as exc:typer.secho(f"Failed to load bundle '{bundle_path}': {exc}", fg=typer.colors.RED, err=True)raise typer.Exit(1) from exc- except PipeInputError as exc:- typer.secho(f"Failed to load bundle '{bundle_path}': {exc}", fg=typer.colors.RED, err=True)- raise typer.Exit(1) from excelse:# No bundle: the pipe named is found in the library directories, a method's folder among them.library_manager = get_library_manager()diff --git a/pipelex/cli/commands/build/output/_output_core.py b/pipelex/cli/commands/build/output/_output_core.pyindex 52549b365..e8a78b33c 100644--- a/pipelex/cli/commands/build/output/_output_core.py+++ b/pipelex/cli/commands/build/output/_output_core.py@@ -14,7 +14,6 @@ from pipelex.cli.error_handlers import ()from pipelex.core.concepts.concept_representation_generator import ConceptRepresentationFormatfrom pipelex.core.pipes.exceptions import PipeOperatorModelChoiceError-from pipelex.core.pipes.inputs.exceptions import PipeInputErrorfrom pipelex.interpreter_hub import get_library_manager, get_required_entry_pipe, resolve_library_dirs, set_current_libraryfrom pipelex.pipe_machinery.rendering.output_renderer import render_outputfrom pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityError@@ -75,9 +74,6 @@ async def _generate_output_core(except ValidateBundleError as exc:typer.secho(f"Failed to load bundle '{bundle_path}': {exc}", fg=typer.colors.RED, err=True)raise typer.Exit(1) from exc- except PipeInputError as exc:- typer.secho(f"Failed to load bundle '{bundle_path}': {exc}", fg=typer.colors.RED, err=True)- raise typer.Exit(1) from excelse:# No bundle: the pipe named is found in the library directories, a method's folder among them.library_manager = get_library_manager()diff --git a/pipelex/cli/commands/crate_loading.py b/pipelex/cli/commands/crate_loading.pyindex 3d7d65193..3e02d4074 100644--- a/pipelex/cli/commands/crate_loading.py+++ b/pipelex/cli/commands/crate_loading.py@@ -17,6 +17,7 @@ from pathlib import Pathimport typerfrom mthds.package.manifest.schema import MTHDS_STANDARD_VERSION+from pipelex.cli.exceptions import BundleClosureEmptyErrorfrom pipelex.interpreter_hub import get_library_managerfrom pipelex.libraries.crate_normalization import normalize_cratefrom pipelex.libraries.exceptions import LibraryLoadingError@@ -31,14 +32,15 @@ def load_normalized_crate(*, library_dirs: list[Path] | None) -> LibraryCrate:Raises:LibraryLoadingError: The library is structurally invalid (a negative verdict).PipeLibraryError: A pipe conflict across bundles (a negative verdict).- FileNotFoundError: The closure could not be assembled, or it holds no .mthds bundles (no verdict).+ FileNotFoundError: The closure could not be assembled (no verdict).+ BundleClosureEmptyError: The closure holds no .mthds bundles (no verdict)."""expanded_library_dirs = [library_dir.expanduser() for library_dir in library_dirs] if library_dirs is not None else Nonelibrary_id = load_libraries_and_activate(expanded_library_dirs)crate = get_library_manager().get_crate(library_id)if crate is None:msg = "no .mthds bundles found in the closure."- raise FileNotFoundError(msg)+ raise BundleClosureEmptyError(msg)# CrateNormalizationError (an internal invariant) is deliberately not caught — it must surface.return normalize_crate(crate, mthds_version=MTHDS_STANDARD_VERSION)@@ -56,7 +58,7 @@ def load_normalized_crate_or_exit(*, library_dirs: list[Path] | None) -> Library# Negative verdict: the library is structurally invalid, so no crate can be produced.typer.secho(f"Cannot resolve — the library is invalid:\n{exc}", fg=typer.colors.RED, err=True)raise typer.Exit(1) from exc- except FileNotFoundError as exc:+ except (FileNotFoundError, BundleClosureEmptyError) as exc:# No verdict: the closure could not even be assembled.typer.secho(f"Cannot resolve — {exc}", fg=typer.colors.RED, err=True)raise typer.Exit(2) from excdiff --git a/pipelex/cli/commands/graph_cmd.py b/pipelex/cli/commands/graph_cmd.pyindex d215ad2b6..6876a9987 100644--- a/pipelex/cli/commands/graph_cmd.py+++ b/pipelex/cli/commands/graph_cmd.py@@ -13,6 +13,7 @@ from pathlib import Pathfrom typing import Annotatedimport typer+from mthds.protocol.problem.registry import CoreCodefrom posthog import tagfrom pydantic import ValidationErrorfrom rich.markup import escape@@ -68,7 +69,7 @@ def _do_graph_render(f"one, whose specs carried fields that have since been retired. Run the pipeline again to get a spec in "f"the current shape. ({validation_error.error_count()} field(s) refused in {input_file})")- raise GraphSpecValidationError(msg) from validation_error+ raise GraphSpecValidationError(msg).with_error_code(CoreCode.REQUEST_INVALID) from validation_errortyper.secho(f"✅ Loaded graph with {len(graph_spec.nodes)} nodes", fg=typer.colors.GREEN, err=True)# Determine output directorydiff --git a/pipelex/cli/commands/init/setup_path.py b/pipelex/cli/commands/init/setup_path.pyindex 6485fae3e..44e664e7c 100644--- a/pipelex/cli/commands/init/setup_path.py+++ b/pipelex/cli/commands/init/setup_path.py@@ -18,6 +18,7 @@ from rich.markup import escapefrom pipelex.cli.commands.login.api_key_store import find_pipelex_api_keyfrom pipelex.cli.commands.login.command import LOGIN_PASTE_COMMAND, login_with_browser, warn_about_shadowing_env_filefrom pipelex.cli.exceptions import PipelexCLIError+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.hosted.api_key_check import PIPELEX_API_KEY_PREFIX, is_well_formed_pipelex_api_keyfrom pipelex.hosted.client_factory import PIPELEX_API_KEY_ENV_KEYfrom pipelex.hosted.run_config import RunExecution@@ -100,7 +101,7 @@ def write_run_execution(*, pipelex_toml_path: Path, execution: RunExecution) ->run_section = document[RUN_SECTION]if not isinstance(run_section, dict):msg = f"'{RUN_SECTION}' in {pipelex_toml_path} is not a table, so where runs execute cannot be written there"- raise PipelexCLIError(msg)+ raise PipelexCLIError(msg).with_error_code(PipelexErrorCode.CONFIG_INVALID)run_section[RUN_EXECUTION_KEY] = execution.valuesave_toml_to_path(document, path=pipelex_toml_path)diff --git a/pipelex/cli/commands/login/command.py b/pipelex/cli/commands/login/command.pyindex d277c28bf..94bba64de 100644--- a/pipelex/cli/commands/login/command.py+++ b/pipelex/cli/commands/login/command.py@@ -22,6 +22,7 @@ from pipelex.cli.commands.init.credentials import get_global_env_pathfrom pipelex.cli.commands.login.api_key_store import find_shadowing_env_file, save_pipelex_api_keyfrom pipelex.cli.commands.login.loopback import CallbackRefusal, LoopbackListenerfrom pipelex.cli.exceptions import PipelexCLIError+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.hosted.api_key_check import PIPELEX_API_KEY_PREFIX, ApiKeyVerdict, check_pipelex_api_key, is_well_formed_pipelex_api_keyfrom pipelex.hosted.client_factory import PIPELEX_API_KEY_ENV_KEY, PIPELEX_BASE_URL_ENV_KEY, redact_url_for_displayfrom pipelex.runtime_hub import get_console@@ -85,7 +86,7 @@ def resolve_app_origin() -> str:f"{PIPELEX_APP_URL_ENV_KEY} is not an origin: {redact_url_for_display(url=configured)!r}. "f"Give scheme://host[:port], with http or https and no path, such as {URLs.app}, or unset it.")- raise PipelexCLIError(msg)+ raise PipelexCLIError(msg).with_error_code(PipelexErrorCode.CONFIG_INVALID)return origindiff --git a/pipelex/cli/commands/run/_hosted_sources.py b/pipelex/cli/commands/run/_hosted_sources.pyindex d2e7efc8e..c38ae7b75 100644--- a/pipelex/cli/commands/run/_hosted_sources.py+++ b/pipelex/cli/commands/run/_hosted_sources.py@@ -23,7 +23,8 @@ from pipelex_sdk.crate_models import MthdsFileItemfrom pydantic import BaseModel, ConfigDictfrom pipelex.cli.commands.run._run_output_folder import run_output_label-from pipelex.cli.installed_methods import DuplicateMethodNameError, MethodNotFoundError, find_method_by_name+from pipelex.cli.exceptions import DuplicateMethodNameError, MethodNotFoundError+from pipelex.cli.installed_methods import find_method_by_namefrom pipelex.cli.method_resolver import method_output_base_dir, resolve_method_targetfrom pipelex.hosted.exceptions import HostedRunSourceErrorfrom pipelex.libraries.exceptions import MethodTreeLoadErrordiff --git a/pipelex/cli/commands/run/exceptions.py b/pipelex/cli/commands/run/exceptions.pyindex 84a90e632..badc192d5 100644--- a/pipelex/cli/commands/run/exceptions.py+++ b/pipelex/cli/commands/run/exceptions.py@@ -1,6 +1,8 @@"""Errors raised while loading pipeline-inputs files for the run CLI surfaces."""-from pipelex.base_exceptions import ErrorDomain, PipelexError+from mthds.protocol.problem.registry import CoreCode++from pipelex.base_exceptions import PipelexErrorfrom pipelex.cogt.inference.error_classification import UserAction, UserActionKind@@ -11,7 +13,7 @@ class AmbiguousInputsFilesError(PipelexError):exist there is no safe pick, so the caller must choose explicitly."""- error_domain = ErrorDomain.INPUT+ error_code = CoreCode.REQUEST_INVALIDuser_action = UserAction(kind=UserActionKind.CHANGE_INPUT,detail="Pass --inputs explicitly to choose which inputs file to use",@@ -28,8 +30,7 @@ class AutoDetectedInputsFileError(PipelexError):into a run; a directory or any other entry of either name is refused the same way."""- _declared_title = "Auto-detected inputs file is not a regular file"- error_domain = ErrorDomain.INPUT+ error_code = CoreCode.REQUEST_INVALIDuser_action = UserAction(kind=UserActionKind.CHANGE_INPUT,detail="Replace it with the file itself, or name the inputs file with --inputs <path>",diff --git a/pipelex/cli/commands/run/pipe_cmd.py b/pipelex/cli/commands/run/pipe_cmd.pyindex eafdc4bcf..c967729a0 100644--- a/pipelex/cli/commands/run/pipe_cmd.py+++ b/pipelex/cli/commands/run/pipe_cmd.py@@ -9,6 +9,7 @@ from pipelex.cli.commands.run._hosted_sources import hosted_pipe_library_filesfrom pipelex.cli.commands.run._run_core import COMMAND, execute_run, validate_run_flag_combinationfrom pipelex.cli.commands.run._run_hosted import execute_hosted_run, refuse_local_only_flags, resolve_cli_run_executionfrom pipelex.cli.commands.run._run_output_folder import run_output_label+from pipelex.cli.exceptions import ExportedPipeAmbiguousErrorfrom pipelex.cli.method_resolver import resolve_pipe_from_exportsfrom pipelex.hosted.exceptions import HostedRunSourceErrorfrom pipelex.mthds_parsing.helpers import MTHDS_EXTENSION, is_pipelex_file@@ -144,7 +145,7 @@ def run_pipe_cmd(# Check installed methods' exports for additional library dirstry:extra_dirs = resolve_pipe_from_exports(pipe_code)- except ValueError as exc:+ except ExportedPipeAmbiguousError as exc:typer.secho(f"Ambiguous pipe code '{pipe_code}': {exc}",fg=typer.colors.RED,diff --git a/pipelex/cli/commands/show_cmd.py b/pipelex/cli/commands/show_cmd.pyindex 4c87c7005..764665c78 100644--- a/pipelex/cli/commands/show_cmd.py+++ b/pipelex/cli/commands/show_cmd.py@@ -20,6 +20,7 @@ from pipelex.cli.exceptions import PipelexCLIErrorfrom pipelex.cogt.model_backends.backend_library import InferenceBackendLibraryfrom pipelex.cogt.model_backends.credential_resolution import CredentialResolutionfrom pipelex.cogt.model_backends.model_lists import ModelLister+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.interpreter_hub import get_library_manager, get_pipe_library, get_required_entry_pipe, resolve_library_dirs, set_current_libraryfrom pipelex.libraries.pipe.exceptions import PipeLibraryErrorfrom pipelex.pipelex import Pipelex@@ -44,9 +45,12 @@ def do_show_config() -> None:try:final_config = config_manager.load_config()pretty_print(final_config, title="Pipelex configuration")- except (OSError, TomlError) as exc:+ except TomlError as exc:msg = f"Error loading configuration: {exc}"- raise PipelexConfigError(msg) from exc+ raise PipelexConfigError(msg).with_error_code(PipelexErrorCode.CONFIG_SYNTAX) from exc+ except OSError as exc:+ msg = f"Error loading configuration: {exc}"+ raise PipelexConfigError(msg).with_error_code(PipelexErrorCode.CONFIG_FILE_MISSING) from excdef do_list_pipes() -> None:@@ -82,9 +86,12 @@ def do_show_backends(*, show_all: bool = False) -> None:backend_library = models_manager.inference_backend_libraryrouting_profile = models_manager.routing_profile- except (PipelexError, OSError, ValidationError) as exc:+ except PipelexError as exc:msg = f"Error accessing backend or routing configuration: {exc}"raise PipelexCLIError(msg) from exc+ except (OSError, ValidationError) as exc:+ msg = f"Error accessing backend or routing configuration: {exc}"+ raise PipelexCLIError(msg).with_error_code(PipelexErrorCode.CONFIG_INVALID) from excconsole = get_console()diff --git a/pipelex/cli/commands/validate/pipe_cmd.py b/pipelex/cli/commands/validate/pipe_cmd.pyindex 791b9a693..ab8cca9c5 100644--- a/pipelex/cli/commands/validate/pipe_cmd.py+++ b/pipelex/cli/commands/validate/pipe_cmd.py@@ -12,6 +12,7 @@ from pipelex.cli.commands.validate._validate_core import (execute_validate,)from pipelex.cli.error_handlers import ErrorContext+from pipelex.cli.exceptions import ExportedPipeAmbiguousErrorfrom pipelex.cli.method_resolver import resolve_pipe_from_exportsfrom pipelex.mthds_parsing.helpers import MTHDS_EXTENSION, is_pipelex_filefrom pipelex.pipelex import Pipelex@@ -105,7 +106,7 @@ def validate_pipe_cmd(# Check installed methods' exports for additional library dirstry:extra_dirs = resolve_pipe_from_exports(pipe_code)- except ValueError as exc:+ except ExportedPipeAmbiguousError as exc:typer.secho(f"Ambiguous pipe code '{pipe_code}': {exc}",fg=typer.colors.RED,diff --git a/pipelex/cli/dev_cli/_dev_cli.py b/pipelex/cli/dev_cli/_dev_cli.pyindex ce0782c99..e84c9ce5e 100644--- a/pipelex/cli/dev_cli/_dev_cli.py+++ b/pipelex/cli/dev_cli/_dev_cli.py@@ -213,7 +213,7 @@ def generate_corpus_vocabulary_command(sys.exit(1)[email protected](name="generate-error-identity", help="Regenerate the committed (error_type, title, type_uri) snapshot of every PipelexError subclass")[email protected](name="generate-error-identity", help="Regenerate the committed (error_type, code declaration) snapshot of every PipelexError subclass")def generate_error_identity_command(output: Annotated[str | None, typer.Option("--output", "-o", help="Custom output path for the snapshot file")] = None,quiet: Annotated[bool, typer.Option("--quiet", "-q", help="Output only a single status line")] = False,diff --git a/pipelex/cli/dev_cli/commands/drift/exceptions.py b/pipelex/cli/dev_cli/commands/drift/exceptions.pyindex d535f332f..c16c25120 100644--- a/pipelex/cli/dev_cli/commands/drift/exceptions.py+++ b/pipelex/cli/dev_cli/commands/drift/exceptions.py@@ -1,19 +1,37 @@-"""Exceptions for the drift-contracts dev CLI (`pipelex-dev drift`)."""+"""Exceptions for the drift-contracts dev CLI (`pipelex-dev drift`).++Developer tooling: `pipelex-dev drift` checks this repository's own contracts, so no caller of a method ever+reads these codes.+"""++from typing import ClassVar++from mthds.protocol.problem.registry import CoreCodefrom pipelex.cli.exceptions import PipelexCLIError+from pipelex.errors.error_code_declaration import ErrorCodeDeclaration+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodeclass DriftError(PipelexCLIError):- """Base error for the drift-contracts tooling."""+ """Base error for the drift-contracts tooling, also raised directly."""++ error_code: ClassVar[ErrorCodeDeclaration] = CoreCode.RUNTIME_UNEXPECTEDclass DriftManifestError(DriftError):"""Raised when drift.toml is missing, unparseable, or schema-invalid."""+ error_code = PipelexErrorCode.CONFIG_INVALID+class DriftAckError(DriftError):"""Raised when an ack file is invalid or an ack operation cannot proceed."""+ error_code = CoreCode.REQUEST_INVALID+class DriftGitError(DriftError):"""Raised when a git plumbing call needed by drift fails."""++ error_code = CoreCode.RUNTIME_UNEXPECTEDdiff --git a/pipelex/cli/dev_cli/commands/error_registry/codes_generator.py b/pipelex/cli/dev_cli/commands/error_registry/codes_generator.pyindex e82b9fe68..14639681d 100644--- a/pipelex/cli/dev_cli/commands/error_registry/codes_generator.py+++ b/pipelex/cli/dev_cli/commands/error_registry/codes_generator.py@@ -208,6 +208,58 @@ def _params_class(*, registry: ErrorRegistryDocument, entry: RegistryEntry, imporeturn lines+def _entries_lines(*, registry: ErrorRegistryDocument) -> list[str]:+ """The lines declaring ``PipelexErrorEntry`` and ``PIPELEX_ERROR_ENTRIES``, every code's title and verdict.++ The runtime reads a code's title, domain, retry verdict, status and step kinds from this table rather+ than from the snapshot, so that classifying an error never reads a file: an error is built anywhere,+ inside a Temporal workflow's sandbox included.+ """+ lines = [+ "",+ "",+ "class PipelexErrorEntry(NamedTuple):",+ ' """What the registry declares about a Pipelex code that classifying an error needs.',+ "",+ " Attributes:",+ " title: The code's short title, the same for every occurrence.",+ " domain: Who must act, from the MTHDS protocol's closed list of domains.",+ " retry: Whether repeating the operation can succeed: ``no``, ``yes`` or ``outcome_unknown``.",+ " status: The HTTP status of an answer the code is the body of, ``None`` for a code raised otherwise.",+ " actor_step: The kind of the step aimed at the domain's actor.",+ " other_step: The kind of the step aimed at any other reader.",+ ' """',+ "",+ " title: str",+ " domain: str",+ " retry: str",+ " status: int | None",+ " actor_step: str",+ " other_step: str",+ "",+ "",+ "PIPELEX_ERROR_ENTRIES: dict[PipelexErrorCode, PipelexErrorEntry] = {",+ ]+ for entry in registry.codes:+ member_name = code_member_name(registry=registry, code=entry.code)+ title = _docstring_text(text=entry.title, where=f"{entry.code}: title")+ lines.extend(+ [+ f" PipelexErrorCode.{member_name}: PipelexErrorEntry(",+ f" title={json.dumps(title)},",+ f" domain={json.dumps(str(entry.domain))},",+ f" retry={json.dumps(str(entry.retry))},",+ f" status={entry.status},",+ f" actor_step={json.dumps(str(entry.steps.actor.kind))},",+ f" other_step={json.dumps(str(entry.steps.other.kind))},",+ " ),",+ ]+ )+ lines.append("}")+ lines.append('"""The title and verdict of every Pipelex code."""')+ return lines++def render_pipelex_codes(*, registry: ErrorRegistryDocument) -> str:"""The text of ``pipelex_codes.py`` for a registry."""imports = _Imports()@@ -256,12 +308,14 @@ def render_pipelex_codes(*, registry: ErrorRegistryDocument) -> str:body.append(f" PipelexErrorCode.{member_name}: {params_class_name(registry=registry, code=entry.code)},")body.append("}")body.append('"""The parameters model of every Pipelex code."""')+ body.extend(_entries_lines(registry=registry))- typing_names = ["ClassVar"]+ typing_names = ["ClassVar", "NamedTuple"]if imports.uses_annotated:- typing_names.insert(0, "Annotated")+ typing_names.append("Annotated")if imports.uses_literal:typing_names.append("Literal")+ typing_names.sort()pydantic_names = ["BaseModel", "ConfigDict", "Field"] if imports.uses_field else ["BaseModel", "ConfigDict"]header = ['"""The Pipelex error codes and the typed parameters of each, generated from ``pipelex-error-registry.yaml``.',diff --git a/pipelex/cli/dev_cli/commands/error_registry/exceptions.py b/pipelex/cli/dev_cli/commands/error_registry/exceptions.pyindex b35ed25ce..8ac554fc8 100644--- a/pipelex/cli/dev_cli/commands/error_registry/exceptions.py+++ b/pipelex/cli/dev_cli/commands/error_registry/exceptions.py@@ -1,7 +1,14 @@"""Exceptions for the error registry tooling (`pipelex-dev generate-error-registry` and its checks)."""+from mthds.protocol.problem.registry import CoreCode+from pipelex.cli.exceptions import PipelexCLIErrorclass ErrorRegistryError(PipelexCLIError):- """Raised when the error registry's source, the standard's vendored files or a generated output cannot be used."""+ """Raised when the error registry's source, the standard's vendored files or a generated output cannot be used.++ Dev tooling that never reaches a run, so it takes ``runtime.unexpected``.+ """++ error_code = CoreCode.RUNTIME_UNEXPECTEDdiff --git a/pipelex/cli/dev_cli/commands/error_registry/pages_generator.py b/pipelex/cli/dev_cli/commands/error_registry/pages_generator.pyindex 7af0a831b..0c6e39164 100644--- a/pipelex/cli/dev_cli/commands/error_registry/pages_generator.py+++ b/pipelex/cli/dev_cli/commands/error_registry/pages_generator.py@@ -183,9 +183,9 @@ def render_index_page(*, registry: ErrorRegistryDocument) -> str:),"",(- "The registry declares the Pipelex codes, but Pipelex's errors do not carry them yet: an error still reports its "- "`error_type` and a type URI derived from its class, and giving every error its code is the next step of this "- f"work, as the [Error Model]({_link(page=page, target=ERROR_MODEL_SECTION)}) describes."+ "Every Pipelex error carries a code, one of these or a core code: its problem document names it as `code`, "+ "and its `type` is the code's page. The [Error Model]"+ f"({_link(page=page, target=ERROR_MODEL_SECTION)}) describes how an error class declares the code it raises."),"",]diff --git a/pipelex/cli/dev_cli/commands/generate_error_identity_cmd.py b/pipelex/cli/dev_cli/commands/generate_error_identity_cmd.pyindex d9d76cf10..c95819bfb 100644--- a/pipelex/cli/dev_cli/commands/generate_error_identity_cmd.py+++ b/pipelex/cli/dev_cli/commands/generate_error_identity_cmd.py@@ -1,4 +1,4 @@-"""Command to regenerate the committed ``PipelexError`` wire-identity snapshot."""+"""Command to regenerate the committed ``PipelexError`` wire-identity snapshot and the retired error page redirects."""from __future__ import annotations@@ -7,6 +7,7 @@ from pathlib import Pathfrom rich.panel import Panelfrom pipelex.errors.error_identity_snapshot import iter_error_identity_rows, render_error_identity_snapshot+from pipelex.errors.retired_error_pages import render_retired_error_page_redirectsfrom pipelex.runtime_hub import get_console# Repo-relative location of the committed snapshot. It lives under ``tests/data/``@@ -14,13 +15,20 @@ from pipelex.runtime_hub import get_console# and no Make gate to keep in sync.ERROR_IDENTITY_PATH = Path("tests/data/errors/error_identity.txt")+# Repo-relative location of the documentation's configuration, whose ``redirect_maps`` holds the static+# redirects of the retired per-class error pages, each to the page of its class's code.+MKDOCS_CONFIG_PATH = Path("mkdocs.yml")+def generate_error_identity_cmd(*, output: Path | None = None, quiet: bool = False) -> None:- """Regenerate the ``(error_type, title, type_uri)`` snapshot for every ``PipelexError`` subclass.+ """Regenerate the ``(error_type, code declaration)`` snapshot for every ``PipelexError`` subclass.++ It also rewrites the targets of ``mkdocs.yml``'s redirects of the retired per-class error pages, which follow+ each class's code (``pipelex/errors/retired_error_pages.py``), when ``output`` is not given.- Deliberately does NOT bootstrap Pipelex: ``title()`` / ``type_uri()`` read- class attributes and a module-level URL constant, and the discovery helper- imports error modules by filename, so the whole rendering is pure. That keeps+ Deliberately does NOT bootstrap Pipelex: a code declaration is a class+ attribute, and the discovery helper imports error modules by filename, so+ the whole rendering is pure. That keepsthis runnable in any environment, including one with no configured backend.Args:@@ -42,6 +50,12 @@ def generate_error_identity_cmd(*, output: Path | None = None, quiet: bool = Falif not already_current:output_path.parent.mkdir(parents=True, exist_ok=True)output_path.write_text(content, encoding="utf-8")+ if output is None:+ mkdocs_text = MKDOCS_CONFIG_PATH.read_text(encoding="utf-8")+ redirected_text = render_retired_error_page_redirects(mkdocs_text=mkdocs_text)+ if redirected_text != mkdocs_text:+ MKDOCS_CONFIG_PATH.write_text(redirected_text, encoding="utf-8")+ already_current = Falsestatus = "unchanged" if already_current else "written"diff --git a/pipelex/cli/error_handlers.py b/pipelex/cli/error_handlers.pyindex 346737863..bbe95242b 100644--- a/pipelex/cli/error_handlers.py+++ b/pipelex/cli/error_handlers.py@@ -10,7 +10,7 @@ from rich.markup import escapefrom rich.traceback import Tracebackfrom pipelex.base_exceptions import PipelexConfigError, ValidationErrorCategory, ValidationErrorItem, error_domain_is_input, iter_cause_chain-from pipelex.cogt.exceptions import ModelDeckPresetValidatonError+from pipelex.cogt.exceptions import ModelDeckPresetValidationErrorfrom pipelex.core.pipes.exceptions import PipeOperatorModelChoiceErrorfrom pipelex.migration.exceptions import FormerReleaseConfigErrorfrom pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityError@@ -232,8 +232,8 @@ def handle_dedicated_failure_panel(*, error: BaseException, context: ErrorContexhandle_model_choice_error(node, context=context)-def handle_model_deck_preset_error(exc: ModelDeckPresetValidatonError, *, context: ErrorContext) -> NoReturn:- """Handle and display ModelDeckPresetValidatonError with formatted output.+def handle_model_deck_preset_error(exc: ModelDeckPresetValidationError, *, context: ErrorContext) -> NoReturn:+ """Handle and display ModelDeckPresetValidationError with formatted output.Args:exc: The model deck preset validation error exceptiondiff --git a/pipelex/cli/exceptions.py b/pipelex/cli/exceptions.pyindex 1d51c3a53..5c66f20b0 100644--- a/pipelex/cli/exceptions.py+++ b/pipelex/cli/exceptions.py@@ -1,11 +1,67 @@+from typing import ClassVar+from click import ClickException+from mthds.protocol.problem.registry import CoreCodefrom pipelex.base_exceptions import PipelexError+from pipelex.errors.error_code_declaration import ErrorCodeDeclaration, InheritsCause+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodeclass PipelexCLIError(PipelexError, ClickException):- """Raised when there's an error in CLI usage or operation."""+ """Raised when there's an error in CLI usage or operation.++ Most raise sites wrap the error that decides the code, so the class takes its cause's code. A raise site+ that names a misconfiguration itself chooses ``pipelex.config.invalid``, and the model-listing wrappers+ choose the code of the fault their uncoded cause stands for.+ """++ error_code: ClassVar[ErrorCodeDeclaration] = InheritsCause(+ fallback=CoreCode.RUNTIME_UNEXPECTED,+ others=(+ PipelexErrorCode.CONFIG_INVALID,+ PipelexErrorCode.CONFIG_VARIABLE_MISSING,+ PipelexErrorCode.CONFIG_CREDENTIAL_MISSING,+ CoreCode.PROVIDER_CREDENTIAL_REFUSED,+ CoreCode.PROVIDER_FAILED,+ ),+ )class ReadinessCheckError(PipelexCLIError):- """Raised when readiness checks fail (missing dependencies or dev mode without venv)."""+ """Raised when readiness checks fail (missing dependencies or dev mode without venv).++ Developer tooling: it fires only on a development install of Pipelex without a virtual environment.+ """++ error_code = CoreCode.RUNTIME_MISCONFIGURED+++class MethodNotFoundError(PipelexError):+ """Raised when no installed method matches the given name."""++ error_code = CoreCode.METHOD_NOT_FOUND+++class DuplicateMethodNameError(PipelexError):+ """Raised when two installed methods share the same name."""++ error_code = CoreCode.METHOD_AMBIGUOUS+++class ExportedPipeNotFoundError(PipelexError):+ """Raised when no installed method exports the given pipe code."""++ error_code = CoreCode.REQUEST_PIPE_NOT_FOUND+++class ExportedPipeAmbiguousError(PipelexError):+ """Raised when several installed methods export the given pipe code."""++ error_code = CoreCode.REQUEST_PIPE_AMBIGUOUS+++class BundleClosureEmptyError(PipelexError):+ """Raised when the bundle closure a command assembled holds no .mthds bundle, so there is no method to read."""++ error_code = CoreCode.METHOD_NOT_FOUNDdiff --git a/pipelex/cli/installed_methods.py b/pipelex/cli/installed_methods.pyindex f7818b785..1de9b36e7 100644--- a/pipelex/cli/installed_methods.py+++ b/pipelex/cli/installed_methods.py@@ -13,8 +13,10 @@ from pathlib import Pathfrom mthds.package.discovery import MANIFEST_FILENAMEfrom mthds.package.manifest.parser import parse_methods_tomlfrom mthds.package.manifest.schema import MethodsManifest+from mthds.protocol.problem.registry import CoreCodefrom pydantic import BaseModel, ValidationError+from pipelex.cli.exceptions import DuplicateMethodNameError, MethodNotFoundErrorfrom pipelex.methods.exceptions import MethodInstallErrorfrom pipelex.methods.fetching import MethodProvenance@@ -28,22 +30,6 @@ PROVENANCE_FILENAME = ".provenance.json"_STAGING_SUFFIX = ".staging"-class MethodNotFoundError(Exception):- """Raised when no installed method matches the given name."""-- def __init__(self, message: str = "") -> None:- self.message = message- super().__init__(message)---class DuplicateMethodNameError(Exception):- """Raised when two installed methods share the same name."""-- def __init__(self, message: str = "") -> None:- self.message = message- super().__init__(message)--class InstalledMethod(BaseModel):"""An installed method discovered from the filesystem.@@ -368,7 +354,7 @@ def install_method_package(final_dir = (target_root / name).resolve()if final_dir == target_root or final_dir.parent != target_root or name.startswith("."):msg = f"Cannot install method '{name}': the name escapes the methods directory '{target_root}' or is not a valid method directory name."- raise MethodInstallError(msg)+ raise MethodInstallError(msg).with_error_code(CoreCode.METHOD_PACKAGE_INVALID)if final_dir.exists():return _resolve_occupied_install_target(final_dir=final_dir, name=name, full_address=full_address)@@ -394,5 +380,5 @@ def install_method_package(if installed is None:shutil.rmtree(final_dir, ignore_errors=True)msg = f"Installed method '{name}' at '{final_dir}' carries no {MANIFEST_FILENAME} — the source package was not a method package."- raise MethodInstallError(msg)+ raise MethodInstallError(msg).with_error_code(CoreCode.METHOD_PACKAGE_INVALID)return installeddiff --git a/pipelex/cli/method_resolver.py b/pipelex/cli/method_resolver.pyindex 34612bb21..54fe2e603 100644--- a/pipelex/cli/method_resolver.py+++ b/pipelex/cli/method_resolver.py@@ -7,10 +7,9 @@ from pathlib import Pathimport typer+from pipelex.cli.exceptions import DuplicateMethodNameError, ExportedPipeAmbiguousError, ExportedPipeNotFoundError, MethodNotFoundErrorfrom pipelex.cli.installed_methods import (- DuplicateMethodNameError,InstalledMethod,- MethodNotFoundError,discover_installed_methods,discover_method_at,find_method_by_name,@@ -48,8 +47,8 @@ def _find_method_by_exported_pipe(pipe_code: str) -> InstalledMethod:The installed method that exports the given pipe codeRaises:- LookupError: If the pipe code is not found in any method's exports- ValueError: If the pipe code is found in multiple methods+ ExportedPipeNotFoundError: If the pipe code is not found in any method's exports+ ExportedPipeAmbiguousError: If the pipe code is found in multiple methods"""methods = discover_installed_methods()@@ -60,11 +59,11 @@ def _find_method_by_exported_pipe(pipe_code: str) -> InstalledMethod:if len(matches) == 0:msg = f"Pipe code '{pipe_code}' not found in any installed method's exports."- raise LookupError(msg)+ raise ExportedPipeNotFoundError(msg)if len(matches) > 1:method_names = ", ".join(method.name for method in matches)msg = f"Pipe code '{pipe_code}' is exported by multiple methods: {method_names}"- raise ValueError(msg)+ raise ExportedPipeAmbiguousError(msg)return matches[0]@@ -285,10 +284,10 @@ def resolve_pipe_from_exports(Library dirs if the pipe code was found in an installed method, None otherwise.Raises:- ValueError: If the pipe code is found in multiple methods (ambiguous).+ ExportedPipeAmbiguousError: If the pipe code is found in multiple methods (ambiguous)."""try:method = _find_method_by_exported_pipe(pipe_code)return [str(method.path)]- except LookupError:+ except ExportedPipeNotFoundError:return Nonediff --git a/pipelex/codegen/exceptions.py b/pipelex/codegen/exceptions.pyindex 00c9b5de0..7162b9fd2 100644--- a/pipelex/codegen/exceptions.py+++ b/pipelex/codegen/exceptions.py@@ -1,19 +1,33 @@+from typing import ClassVar++from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import PipelexError+from pipelex.errors.error_code_declaration import ErrorCodeDeclaration, ErrorCodeSet+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodeclass CodegenError(PipelexError):- """Base error for the codegen projection engine (stamps, lock, check, emission)."""+ """Base error for the codegen projection engine (stamps, lock, check, emission).- _declared_title = "Codegen error"+ Raised directly when an output path conflicts with what is already there: a file codegen does not own, or+ an artifact path that escapes the root, is not a file, or passes through a symlink.+ """++ error_code: ClassVar[ErrorCodeDeclaration] = PipelexErrorCode.CODEGEN_OUTPUT_CONFLICTclass CodegenStampError(CodegenError):- """Raised when a generated file cannot be stamped (e.g. an unstampable file type)."""+ """Raised when a generated file cannot be stamped (e.g. an unstampable file type), a fault of the emitter."""- _declared_title = "Codegen stamp error"+ error_code = CoreCode.RUNTIME_UNEXPECTEDclass CodegenLockError(CodegenError):- """Raised when a `codegen.lock` cannot be read or parsed."""+ """Raised when a `codegen.lock` cannot be read or parsed.++ A malformed lock is ``pipelex.codegen.lock_invalid``; a lock of an unknown or newer format version, which+ a newer build reads, is ``pipelex.codegen.lock_unsupported``.+ """- _declared_title = "Codegen lock error"+ error_code = ErrorCodeSet(default=PipelexErrorCode.CODEGEN_LOCK_INVALID, others=(PipelexErrorCode.CODEGEN_LOCK_UNSUPPORTED,))diff --git a/pipelex/codegen/lock.py b/pipelex/codegen/lock.pyindex 1b7ef308b..d79915649 100644--- a/pipelex/codegen/lock.py+++ b/pipelex/codegen/lock.py@@ -42,6 +42,7 @@ from pydantic import BaseModel, ConfigDict, Fieldfrom pipelex.codegen.exceptions import CodegenError, CodegenLockErrorfrom pipelex.codegen.stamp import STAMPABLE_SUFFIXES+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.tools.misc.exceptions import TomlErrorfrom pipelex.tools.misc.file_utils import load_text_from_pathfrom pipelex.tools.misc.toml_utils import load_toml_from_content@@ -239,4 +240,4 @@ def _reject_unknown_lock_version(*, data: dict[str, Any], lock_path: Path) -> Noelse:reason = f"lock_version {raw_version!r} is not a known codegen lock format version"msg = f"Unsupported codegen lock version at '{lock_path}': this build reads lock_version {CODEGEN_LOCK_VERSION}, but {reason}."- raise CodegenLockError(msg)+ raise CodegenLockError(msg).with_error_code(PipelexErrorCode.CODEGEN_LOCK_UNSUPPORTED)diff --git a/pipelex/cogt/content_generation/cogt_run_params.py b/pipelex/cogt/content_generation/cogt_run_params.pyindex 4f8894bd8..cee408bfd 100644--- a/pipelex/cogt/content_generation/cogt_run_params.py+++ b/pipelex/cogt/content_generation/cogt_run_params.py@@ -23,20 +23,21 @@ from typing import Selffrom pydantic import BaseModel, ConfigDict, model_validator+from pipelex.cogt.content_generation.exceptions import MockUsageOnLiveRunErrorfrom pipelex.system.pipe_run_mode import PipeRunModedef check_mock_usage_requires_dry(*, run_mode: PipeRunMode, is_mock_usage: bool) -> None:"""Single home of the rule: ``is_mock_usage`` is a sub-flag of ``run_mode=DRY``.- Raises ``ValueError`` on the illegal LIVE combination — called by the model validators on+ Raises ``MockUsageOnLiveRunError``, a ``ValueError``, on the illegal LIVE combination — called by the model validators onboth ``CogtRunParams`` and ``PipeRunParams`` (each guards its own boundary) and by``PipeRunParamsFactory.make_run_params`` (which must reject the REQUESTED mode before thekeyless forced-DRY coercion can mask it)."""if is_mock_usage and run_mode.is_live:msg = "is_mock_usage is a sub-flag of run_mode=DRY: it cannot be set on a LIVE run"- raise ValueError(msg)+ raise MockUsageOnLiveRunError(msg)class CogtRunParams(BaseModel):diff --git a/pipelex/cogt/content_generation/content_generator.py b/pipelex/cogt/content_generation/content_generator.pyindex 84e69efcf..3fb6896c7 100644--- a/pipelex/cogt/content_generation/content_generator.py+++ b/pipelex/cogt/content_generation/content_generator.py@@ -1,5 +1,6 @@from typing import Any+from mthds.protocol.problem.registry import CoreCodefrom typing_extensions import overridefrom pipelex.cogt.content_generation.assignment_models import (@@ -27,6 +28,7 @@ from pipelex.cogt.content_generation.search_generate import search_gen_sourced_afrom pipelex.cogt.content_generation.templating_generate import templating_gen_textfrom pipelex.cogt.doc_gen.doc_gen_setting import DocGenSettingfrom pipelex.cogt.doc_gen.document_composition import DocumentComposition+from pipelex.cogt.exceptions import ExtractJobFailureErrorfrom pipelex.cogt.extract.extract_input import ExtractInputfrom pipelex.cogt.extract.extract_job_components import ExtractJobConfig, ExtractJobParamsfrom pipelex.cogt.img_gen.img_gen_job_components import ImgGenJobConfig, ImgGenJobParams@@ -294,7 +296,7 @@ class ContentGenerator(ContentGeneratorProtocol):page_view_contents = [ImageContent(url=extract_input.image_uri)]if len(page_view_contents) != len(page_contents):msg = f"Number of page view contents ({len(page_view_contents)}) does not match number of page contents ({len(page_contents)})"- raise ValueError(msg)+ raise ExtractJobFailureError(msg).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)for page_content in page_contents:page_content.page_view = page_view_contents.pop(0)diff --git a/pipelex/cogt/content_generation/doc_gen_generate.py b/pipelex/cogt/content_generation/doc_gen_generate.pyindex 598664a6b..fc8b65803 100644--- a/pipelex/cogt/content_generation/doc_gen_generate.py+++ b/pipelex/cogt/content_generation/doc_gen_generate.py@@ -40,7 +40,7 @@ from pipelex.base_exceptions import PipelexError, PipelexUnexpectedErrorfrom pipelex.cogt.content_generation.assignment_models import RenderDocumentAssignmentfrom pipelex.cogt.content_generation.dry_mock import dry_render_documentfrom pipelex.cogt.content_generation.generated_content_factory import GeneratedContentFactory-from pipelex.cogt.content_generation.read_authorization import authorize_assignment_reads+from pipelex.cogt.content_generation.read_authorization import authorize_assignment_reads, authorize_method_uri_readfrom 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 DocGenWorkerFactoryfrom pipelex.cogt.doc_gen.document_composition import DocumentComposition@@ -51,10 +51,10 @@ from pipelex.cogt.doc_gen.template_check import TemplateCheckRequestfrom pipelex.cogt.inference.inference_call_summary import InferenceCallSummary, InferenceOperationfrom pipelex.core.method_trees.method_files import TreeListing, read_listed_file, read_method_file, read_tree_listingfrom pipelex.core.stuffs.document_content import DocumentContent+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom 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_uri-from pipelex.tools.uri.uri_read_scope import authorize_uri_readif TYPE_CHECKING:from pipelex.cogt.model_backends.model_spec import InferenceModelSpec@@ -109,7 +109,7 @@ class RunRenderResources(RenderResources):f"template can name, and this document is {source_desc}.")raise TemplateUrlRefusedError(msg, refusal_code=None)- authorize_uri_read(uri=uri, read_scope=self._read_scope, position=position)+ authorize_method_uri_read(uri=uri, read_scope=self._read_scope, position=position)loaded = await load_bytes_and_mime_type_from_any_uri(uri, storage_provider=self._storage_provider)return LoadedResource(data=loaded.data, mime_type=loaded.mime_type)@@ -165,7 +165,7 @@ class RunRenderResources(RenderResources):# Stop the read too, which would otherwise go on running on the loop after the print has failed.future.cancel()msg = f"Reading {position} took longer than {_RESOURCE_LOAD_TIMEOUT_SECONDS} seconds."- raise DocGenRenderError(msg) from exc+ raise DocGenRenderError(msg).with_error_code(PipelexErrorCode.DOCGEN_PRINT_TIMEOUT) from excasync def render_document_and_store(@@ -229,7 +229,7 @@ async def read_template_file(*, render_assignment: RenderDocumentAssignment) ->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+ raise DocGenRenderError(msg).with_error_code(PipelexErrorCode.DOCGEN_TEMPLATE_INVALID) from exchtml = await get_template_file_stage().render_html_template_file(template_file=template_file, template_source=template_source)return TemplateFileForPrint(html=html, template=None)diff --git a/pipelex/cogt/content_generation/exceptions.py b/pipelex/cogt/content_generation/exceptions.pyindex 56d6adb84..3c8357656 100644--- a/pipelex/cogt/content_generation/exceptions.py+++ b/pipelex/cogt/content_generation/exceptions.py@@ -1,12 +1,34 @@-from pipelex.base_exceptions import ErrorDomain, PipelexError, SecurityError+from mthds.protocol.problem.registry import CoreCode++from pipelex.base_exceptions import PipelexError, SecurityErrorclass NeitherUrlNorDataError(PipelexError):- pass+ """A generated image a provider returned with neither a URL nor data."""++ error_code = CoreCode.PROVIDER_RESPONSE_INVALID+++class MockUsageOnLiveRunError(PipelexError, ValueError):+ """A run asking for synthetic usage, which only a dry run reports, on a live run.++ A ``ValueError`` too, because the model validators of ``CogtRunParams`` and ``PipeRunParams`` raise it and pydantic+ wraps only a ``ValueError`` into its validation error.+ """++ error_code = CoreCode.REQUEST_INVALID+ _authors_caller_facing_message = Trueclass UnsafeSchemaError(SecurityError):- pass+ """A JSON schema carrying the code generator's extensions, refused before any code is generated from it.++ The schema is the method's output concept, or a payload forged across a process boundary, so it is refused as a+ security policy rather than read as a malformed method. The same perimeter refuses, as this error, an import the+ generated code makes outside its allowlist.+ """++ error_code = CoreCode.SECURITY_SCHEMA_REFUSEDclass DryRunObjectFidelityError(PipelexError):@@ -23,10 +45,9 @@ class DryRunObjectFidelityError(PipelexError):``ValidationError`` behavior."""- # The caller's output concept enforces an invariant the schema round-trip drops; they can fix it by- # declaring `examples` / `mock_format` on the offending fields — caller-fixable input, not a- # server-side fault.- error_domain = ErrorDomain.INPUT+ # The method's output concept enforces an invariant the schema round-trip drops; its author fixes it by+ # declaring `examples` / `mock_format` on the offending fields, not a server-side fault.+ error_code = CoreCode.METHOD_MOCK_UNSATISFIABLE# The message is pure caller-facing guidance (names the caller's own output concept class and the# field-level remedy) with no internal paths or secrets, so it should survive STRICT disclosure intact._authors_caller_facing_message = True@@ -56,9 +77,9 @@ class OutputStructureSchemaError(PipelexError):the class."""- # The caller's output concept uses a type pydantic cannot describe as JSON Schema; they fix it by- # changing the field or teaching the type `__get_pydantic_json_schema__` — caller-fixable input.- error_domain = ErrorDomain.INPUT+ # The method's output concept uses a type pydantic cannot describe as JSON Schema; its author fixes it by+ # changing the field or teaching the type `__get_pydantic_json_schema__`.+ error_code = CoreCode.METHOD_CONCEPT_INVALID# The message names the caller's own output concept class and the remedy, with no internal paths or# secrets, so it should survive STRICT disclosure intact._authors_caller_facing_message = True@@ -88,9 +109,9 @@ class DryRunMockBuildError(PipelexError):``mock_format`` on fields whose constraints polyfactory cannot satisfy from the schema alone."""- # The caller's output concept has field constraints the mock factory cannot satisfy; fixable by- # declaring `examples` / `mock_format` on those fields — caller-fixable input, not a server fault.- error_domain = ErrorDomain.INPUT+ # The method's output concept has field constraints the mock factory cannot satisfy; its author fixes it+ # by declaring `examples` / `mock_format` on those fields, not a server fault.+ error_code = CoreCode.METHOD_MOCK_UNSATISFIABLE# The message is pure caller-facing guidance (names the caller's own output concept class and the# field-level remedy) with no internal paths or secrets, so it should survive STRICT disclosure intact._authors_caller_facing_message = Truediff --git a/pipelex/cogt/content_generation/generated_content_factory.py b/pipelex/cogt/content_generation/generated_content_factory.pyindex 22deb596e..2a0f5455a 100644--- a/pipelex/cogt/content_generation/generated_content_factory.py+++ b/pipelex/cogt/content_generation/generated_content_factory.py@@ -1,6 +1,8 @@import base64import hashlib+from mthds.protocol.problem.registry import CoreCode+from pipelex import logfrom pipelex.cogt.content_generation.exceptions import NeitherUrlNorDataErrorfrom pipelex.cogt.extract.extract_output import ExtractOutput@@ -18,6 +20,7 @@ from pipelex.tools.misc.exceptions import RemoteFileFetchErrorfrom pipelex.tools.misc.file_fetch_utils import fetch_file_and_content_type_from_url_httpxfrom pipelex.tools.misc.filetype_utils import UNKNOWN_FILE_TYPE, mime_type_to_extensionfrom pipelex.tools.misc.image_utils import ImageFormat+from pipelex.tools.network.exceptions import SsrfBlockedErrorfrom pipelex.tools.storage.storage_provider_abstract import StorageProviderAbstract@@ -108,8 +111,19 @@ class GeneratedContentFactory:What is dropped is everything that is not an image at all: the`application/octet-stream` of a store that never learned better, or the`text/html` of an error page a server dressed as a 200.++ The URL is one a provider's answer named, so a refusal or a failure to fetch it is the provider's:+ ``security.provider_url_refused`` for a destination the SSRF guard refuses, ``provider.response_invalid``+ for a file that could not be fetched."""- raw_bytes, media_type = await fetch_file_and_content_type_from_url_httpx(url)+ try:+ raw_bytes, media_type = await fetch_file_and_content_type_from_url_httpx(url)+ except SsrfBlockedError as exc:+ exc.with_error_code(CoreCode.SECURITY_PROVIDER_URL_REFUSED)+ raise+ except RemoteFileFetchError as exc:+ exc.with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)+ raiseif media_type and media_type.startswith("image/"):return raw_bytes, media_typereturn raw_bytes, Nonediff --git a/pipelex/cogt/content_generation/read_authorization.py b/pipelex/cogt/content_generation/read_authorization.pyindex 2caa2a300..bd5eecb28 100644--- a/pipelex/cogt/content_generation/read_authorization.py+++ b/pipelex/cogt/content_generation/read_authorization.py@@ -8,10 +8,18 @@ every hand-off to another reader share. Each leaf authorizes the URLs its assignmethod a live run would, and before any worker is built. The document print authorizes first in eachbranch instead, its live branch inside the summary event the print ends with, so a print the scoperefuses ends with that event too. See :mod:`pipelex.tools.uri.uri_read_scope` for the rule.++A refusal here is the method's, ``security.method_url_refused``. The run's inputs, the files nested in their lists+and structures included, were checked against the same read scope when the run took them, and refused there as the+caller's (``pipelex.pipeline.input_normalizer``), so a URL a leaf finds out of scope is one the method's own steps+produced: a construct that assembled it, a model's structured output, a function's result."""+from mthds.protocol.problem.registry import CoreCode+from pipelex.system.job_metadata import JobMetadata-from pipelex.tools.uri.uri_read_scope import UriReference, authorize_uri_reads+from pipelex.tools.uri.exceptions import UriReadRefusedError+from pipelex.tools.uri.uri_read_scope import UriReference, authorize_uri_read, authorize_uri_readsdef authorize_assignment_reads(*, job_metadata: JobMetadata, uri_references: list[UriReference]) -> None:@@ -20,11 +28,30 @@ def authorize_assignment_reads(*, job_metadata: JobMetadata, uri_references: lisThe pipe the assignment belongs to is added to each position, so a refusal names the step.Raises:- UriReadRefusedError: one of the URLs is a storage key outside the read scope, or a local path.+ UriReadRefusedError: one of the URLs is a storage key outside the read scope, or a local path, refused as the+ method's (``security.method_url_refused``)."""pipe_code = job_metadata.pipe_codeif pipe_code is not None:uri_references = [UriReference(uri=uri_reference.uri, position=f"{uri_reference.position} of pipe '{pipe_code}'") for uri_reference in uri_references]- authorize_uri_reads(uri_references=uri_references, read_scope=job_metadata.run_metadata.read_scope)+ try:+ authorize_uri_reads(uri_references=uri_references, read_scope=job_metadata.run_metadata.read_scope)+ except UriReadRefusedError as exc:+ exc.with_error_code(CoreCode.SECURITY_METHOD_URL_REFUSED)+ raise+++def authorize_method_uri_read(*, uri: str, read_scope: str | None, position: str) -> None:+ """Refuse the read of a URL a document print names that the run's read scope does not allow.++ Raises:+ UriReadRefusedError: the URL is a storage key outside the read scope, or a local path, refused as the method's+ (``security.method_url_refused``).+ """+ try:+ authorize_uri_read(uri=uri, read_scope=read_scope, position=position)+ except UriReadRefusedError as exc:+ exc.with_error_code(CoreCode.SECURITY_METHOD_URL_REFUSED)+ raisediff --git a/pipelex/cogt/content_generation/schema_to_model_factory.py b/pipelex/cogt/content_generation/schema_to_model_factory.pyindex aa669498f..ee5e5fee0 100644--- a/pipelex/cogt/content_generation/schema_to_model_factory.py+++ b/pipelex/cogt/content_generation/schema_to_model_factory.py@@ -229,11 +229,11 @@ class SchemaToModelFactory:"""if level != 0:msg = f"Relative imports are not allowed in generated code: {name!r}"- raise ImportError(msg)+ raise UnsafeSchemaError(msg)top_level = name.split(".", 1)[0]if top_level not in cls._ALLOWED_IMPORT_TOP_LEVELS:msg = f"Import of {name!r} is not allowed in generated code"- raise ImportError(msg)+ raise UnsafeSchemaError(msg)return builtins.__import__(name, import_globals, import_locals, fromlist or (), level)@classmethoddiff --git a/pipelex/cogt/doc_gen/doc_gen_engine.py b/pipelex/cogt/doc_gen/doc_gen_engine.pyindex 272be4b3c..6b8f63af4 100644--- a/pipelex/cogt/doc_gen/doc_gen_engine.py+++ b/pipelex/cogt/doc_gen/doc_gen_engine.py@@ -13,11 +13,14 @@ this installation does not declare is told to run `pipelex update` or to installmodel is unknown."""-from pipelex.cogt.doc_gen.doc_gen_format import DocGenFormat, DocGenSource+from functools import partial++from pipelex.cogt.doc_gen.doc_gen_format import DocGenFormat, DocGenSource, doc_gen_choice_keyfrom pipelex.cogt.doc_gen.doc_gen_setting import DocGenModelChoice, DocGenSettingfrom pipelex.cogt.doc_gen.exceptions import KNOWN_DOC_GEN_MODEL_NAMES, DocGenEngineGap, DocGenEngineMissingError, DocGenModelCapabilityErrorfrom pipelex.cogt.model_backends.model_spec import InferenceModelSpecfrom pipelex.cogt.model_backends.model_type import ModelType+from pipelex.cogt.models.model_deck import resolve_deck_choicefrom pipelex.cogt.models.model_reference import ModelReferenceKind, ensure_model_reference, write_model_handlefrom pipelex.plugins.inference_backend_registry import InferenceFamilyfrom pipelex.runtime_hub import get_inference_backend_registry, get_model_deck@@ -137,19 +140,28 @@ def resolve_doc_gen_setting(the built-in one or one of the plugin's and this installation does not declare it, or no installed pluginregisters the engine.ModelChoiceNotFoundError: the step names a reference the deck does not define.+ ModelDeckChoiceUnresolvedError: the step names no engine and the deck's default for the step names a reference+ the deck does not define.ModelNotFoundError: the reference resolves to no model served here.DocGenModelCapabilityError: the engine does not print the step's format from its source."""model_deck = get_model_deck()- resolved_choice = doc_gen_choice- if resolved_choice is None:- resolved_choice = model_deck.get_doc_gen_choice_default(doc_gen_format=doc_gen_format, source=source)- if resolved_choice is None:- raise DocGenEngineMissingError(- gap=DocGenEngineGap.NO_DEFAULT, doc_gen_format=doc_gen_format, source=source, model=None, sdk=None, pipe_code=pipe_code+ doc_gen_setting: DocGenSetting+ if doc_gen_choice is not None:+ require_doc_gen_engine_declared(doc_gen_choice=doc_gen_choice, doc_gen_format=doc_gen_format, source=source, pipe_code=pipe_code)+ doc_gen_setting = model_deck.get_doc_gen_setting(doc_gen_choice=doc_gen_choice)+ else:+ doc_gen_choice_default = model_deck.get_doc_gen_choice_default(doc_gen_format=doc_gen_format, source=source)+ if doc_gen_choice_default is None:+ raise DocGenEngineMissingError(+ gap=DocGenEngineGap.NO_DEFAULT, doc_gen_format=doc_gen_format, source=source, model=None, sdk=None, pipe_code=pipe_code+ )+ require_doc_gen_engine_declared(doc_gen_choice=doc_gen_choice_default, doc_gen_format=doc_gen_format, source=source, pipe_code=pipe_code)+ # The deck's own default, so a miss is the deployment's, not the method's.+ doc_gen_setting = resolve_deck_choice(+ deck_setting=f'doc_gen.choice_defaults["{doc_gen_choice_key(doc_gen_format=doc_gen_format, source=source)}"]',+ resolve=partial(model_deck.get_doc_gen_setting, doc_gen_choice=doc_gen_choice_default),)- require_doc_gen_engine_declared(doc_gen_choice=resolved_choice, doc_gen_format=doc_gen_format, source=source, pipe_code=pipe_code)- doc_gen_setting = model_deck.get_doc_gen_setting(doc_gen_choice=resolved_choice)inference_model = get_doc_gen_inference_model(model_handle=doc_gen_setting.model, doc_gen_format=doc_gen_format, source=source, pipe_code=pipe_code)diff --git a/pipelex/cogt/doc_gen/doc_gen_format.py b/pipelex/cogt/doc_gen/doc_gen_format.pyindex 44c540c9c..acde14bbe 100644--- a/pipelex/cogt/doc_gen/doc_gen_format.py+++ b/pipelex/cogt/doc_gen/doc_gen_format.py@@ -1,5 +1,7 @@from enum import StrEnum+from pipelex.cogt.doc_gen.doc_gen_format_exceptions import DocGenChoiceKeyError+class DocGenFormat(StrEnum):"""The file formats a `PipeDocGen` step can ask for.@@ -145,7 +147,7 @@ def parse_doc_gen_choice_key(key: str) -> tuple[DocGenFormat, DocGenSource]:"""The format and source a key of the model deck's doc-gen defaults names.Raises:- ValueError: the key is not '<format>.<source>', or no step composes that format from that source.+ DocGenChoiceKeyError: the key is not '<format>.<source>', or no step composes that format from that source."""format_token, separator, source_token = key.partition(".")try:@@ -153,8 +155,8 @@ def parse_doc_gen_choice_key(key: str) -> tuple[DocGenFormat, DocGenSource]:source = DocGenSource(source_token)except ValueError as exc:msg = f"'{key}' is not a '<format>.<source>' key, such as 'pdf.layout'."- raise ValueError(msg) from exc+ raise DocGenChoiceKeyError(msg) from excif not separator or source not in DocGenSource.possible_for(doc_gen_format=doc_gen_format):msg = f"'{key}' names no step: {doc_gen_format.with_article} is never composed {source.desc}."- raise ValueError(msg)+ raise DocGenChoiceKeyError(msg)return doc_gen_format, sourcediff --git a/pipelex/cogt/doc_gen/doc_gen_format_exceptions.py b/pipelex/cogt/doc_gen/doc_gen_format_exceptions.pynew file mode 100644index 000000000..350ff864f--- /dev/null+++ b/pipelex/cogt/doc_gen/doc_gen_format_exceptions.py@@ -0,0 +1,13 @@+from pipelex.base_exceptions import PipelexError+from pipelex.errors.registry.pipelex_codes import PipelexErrorCode+++class DocGenChoiceKeyError(PipelexError, ValueError):+ """A key of the model deck's doc-gen defaults that names no step: not '<format>.<source>', or a pair no step composes.++ The deck and the plugins declaring defaults are the deployment's, so the key is its configuration. A ``ValueError``+ too, because the deck's field validator raises it and pydantic wraps only a ``ValueError`` into its validation error.+ Its own module because ``doc_gen/exceptions.py`` imports ``doc_gen_format``, which raises it.+ """++ error_code = PipelexErrorCode.CONFIG_INVALIDdiff --git a/pipelex/cogt/doc_gen/exceptions.py b/pipelex/cogt/doc_gen/exceptions.pyindex b3b43f050..fcb930acf 100644--- a/pipelex/cogt/doc_gen/exceptions.py+++ b/pipelex/cogt/doc_gen/exceptions.py@@ -1,9 +1,12 @@from enum import StrEnumfrom mthds.method_tree.vocabulary import TreeRefusalCode+from mthds.protocol.problem.registry import CoreCode-from pipelex.base_exceptions import ErrorDomain, PipelexError+from pipelex.base_exceptions import PipelexErrorfrom pipelex.cogt.doc_gen.doc_gen_format import DocGenFormat, DocGenSource, doc_gen_choice_key+from pipelex.errors.error_code_declaration import ErrorCodeSet+from pipelex.errors.registry.pipelex_codes import PipelexErrorCode# The package whose engines print what open Pipelex does not: a PDF from a template, Excel, Word and PowerPoint.DOC_GEN_PLUGIN_PACKAGE = "pipelex-doc-gen"@@ -48,11 +51,12 @@ class DocGenEngineMissingError(PipelexError):engines when it loads. Or the model may be declared with no worker registered for it: open Pipelex registers`reportlab-pdf`'s, and the plugin registers the rest. Raised when the method loads, before a run spendsanything, and again by the print stage should the engine have gone since. A runtime that disables the built-in- plugin and installs no other refuses every `PipeDocGen` step this way. Its message names only the step, the- format, the source, the engine and the plugin, so it is kept verbatim for the caller.+ plugin and installs no other refuses every `PipeDocGen` step this way. Every remedy it names is the operator's,+ so it is ``pipelex.docgen.engine_unavailable``. Its message names only the step, the format, the source, the+ engine and the plugin, so it is kept verbatim for the caller."""- error_domain = ErrorDomain.INPUT+ error_code = PipelexErrorCode.DOCGEN_ENGINE_UNAVAILABLE_authors_caller_facing_message = Truedef __init__(@@ -106,7 +110,7 @@ class DocGenModelCapabilityError(PipelexError):that names one outside them is refused when the method loads."""- error_domain = ErrorDomain.INPUT+ error_code = CoreCode.MODEL_CAPABILITY_UNSUPPORTED_authors_caller_facing_message = Truedef __init__(self, *, doc_gen_format: DocGenFormat, source: DocGenSource, model: str, pipe_code: str | None = None):@@ -127,9 +131,26 @@ class DocGenRenderError(PipelexError):Engines raise it for what they cannot lay out, such as a table cell taller than a page, and the print stageraises it for an engine failure it did not expect. Engines outside Pipelex raise it too: it is part of therender contract (`render_job.py`).++ Its raise site chooses the code: ``pipelex.docgen.content_unprintable`` for the run's data an engine cannot lay+ out (an element taller than a page, an image that is not one), which is also the site that says+ ``as_caller_fault()``; ``pipelex.docgen.print_timeout`` for a print stopped at its deadline;+ ``pipelex.docgen.resource_refused`` or ``security.method_url_refused`` for a file the printed document may not+ name; ``pipelex.docgen.template_invalid`` for a method's template file the print cannot read; and+ ``runtime.unexpected``, the default, for an engine failure or a job an engine was never meant to get,+ since the step's engine was checked to print it before printing."""- error_domain = ErrorDomain.RUNTIME+ error_code = ErrorCodeSet(+ default=CoreCode.RUNTIME_UNEXPECTED,+ others=(+ PipelexErrorCode.DOCGEN_CONTENT_UNPRINTABLE,+ PipelexErrorCode.DOCGEN_PRINT_TIMEOUT,+ PipelexErrorCode.DOCGEN_RESOURCE_REFUSED,+ PipelexErrorCode.DOCGEN_TEMPLATE_INVALID,+ CoreCode.SECURITY_METHOD_URL_REFUSED,+ ),+ )class MarkdownFormattingBudgetError(PipelexError):@@ -143,9 +164,8 @@ class MarkdownFormattingBudgetError(PipelexError):goes."""- error_domain = ErrorDomain.INPUT+ error_code = CoreCode.INPUT_TOO_LARGE_authors_caller_facing_message = True- _declared_title = "Markdown formatting budget exceeded"class TemplateUrlRefusedError(PipelexError):@@ -163,14 +183,17 @@ class TemplateUrlRefusedError(PipelexError):these last three, which the standard does not name. A URL the template writes as it is is checked when the methodloads, so this is raised for one the run's input supplied.- `RenderResources.load` raises it, and an engine lets it pass, as it lets the read scope's refusal pass. The method's- author or the run's caller fixes it, so it is an input error, and its message names only the method's own files, by- their tree paths, and where the URL sat in the document, so it is kept for the caller.+ `RenderResources.load` raises it, and an engine lets it pass, as it lets the read scope's refusal pass. Every one of+ its refusals keeps a document inside its method tree's read perimeter, which a path that climbs out of the tree,+ names a file the tree keeps out or names the method's own code would cross, so it is ``security.method_path_refused``:+ a refused path into the method's tree, which its author bounds, rather than ``method.resource_missing``, a file the+ method itself refers to and lacks, which the load-time check already refuses for a URL the template writes. Its+ message names only the method's own files, by their tree paths, and where the URL sat in the document, so it is+ kept for the caller."""- error_domain = ErrorDomain.INPUT+ error_code = CoreCode.SECURITY_METHOD_PATH_REFUSED_authors_caller_facing_message = True- _declared_title = "Relative URL refused"def __init__(self, message: str, *, refusal_code: TreeRefusalCode | None):super().__init__(message)diff --git a/pipelex/cogt/exceptions.py b/pipelex/cogt/exceptions.pyindex fdffc0d47..582cce9be 100644--- a/pipelex/cogt/exceptions.py+++ b/pipelex/cogt/exceptions.py@@ -1,20 +1,30 @@from __future__ import annotationsfrom enum import StrEnum-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, ClassVar+from mthds.protocol.problem.registry import CoreCodefrom typing_extensions import override-from pipelex.base_exceptions import ErrorDomain, ErrorReport, PipelexError, iter_cause_chain+from pipelex.base_exceptions import ErrorReport, PipelexError, iter_cause_chainfrom pipelex.cogt.inference.error_classification import ProviderErrorMetadata, UserAction, UserActionKind+from pipelex.cogt.models.model_reference import ModelReferenceKind+from pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeDeclaration, ErrorCodeSet, InheritsCause, declared_error_codes+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodeif TYPE_CHECKING:from pipelex.cogt.model_backends.model_type import ModelType- from pipelex.cogt.models.model_reference import ModelReferenceKind+ from pipelex.errors.error_codes import ErrorCodeclass InferenceErrorCategory(StrEnum):- """Classifies inference errors for retry decisions and error reporting."""+ """The runtime's own classification of an inference failure, which picks its registry code.++ It stays inside the runtime: a report's domain and retry verdict are its code's, and the category is+ what the classification (``pipelex.cogt.inference.error_classify``) reads to pick that code, and what the+ Temporal activity reads to decide whether a provider call may be repeated within the run, since a call+ whose outcome is unknown must not be, though a new run may succeed (the census's question 6).+ """TRANSIENT = "transient"CONFIGURATION = "configuration"@@ -41,43 +51,97 @@ class InferenceErrorCategory(StrEnum):return False@property- def error_domain(self) -> ErrorDomain | None:- """The :class:`~pipelex.base_exceptions.ErrorDomain` this category implies — who can fix it.-- The category a worker assigns is already the authoritative statement of *whose fault*- an inference failure is, so :meth:`CogtError.to_error_report` derives the domain from it- rather than making every leaf class in the family declare the same fact twice.-- ``CONTENT`` is the one mapping that changes an HTTP answer: a content-policy refusal, a- malformed prompt image, a bad prompt parameter are all properties of material the caller- submitted, so they belong in ``INPUT`` and answer 422 rather than 500.-- ``UNKNOWN`` deliberately maps to ``None``. It means classification itself failed, and- ``RUNTIME`` would be a claim this code cannot support; an absent domain already renders- 500, so the honest answer costs nothing.+ def is_outcome_unknown(self) -> bool:+ """Whether the failed call may have taken effect, so it must not be repeated within the run."""+ match self:+ case InferenceErrorCategory.AMBIGUOUS:+ return True+ case (+ InferenceErrorCategory.TRANSIENT+ | InferenceErrorCategory.CONFIGURATION+ | InferenceErrorCategory.CONTENT+ | InferenceErrorCategory.CAPACITY+ | InferenceErrorCategory.UNKNOWN+ ):+ return False- ``CAPACITY -> RUNTIME`` does not disturb the provider-429 passthrough:- :attr:`~pipelex.base_exceptions.ErrorReport.http_status` checks- ``provider_metadata.status_code`` before it consults the domain.+ @property+ def default_error_code(self) -> ErrorCode | None:+ """The code an error naming this category and no code reports, ``None`` where the category alone names none.++ The classification picks a code with every category it reads. This serves an error a worker or a plugin builds+ by hand with a category alone, whose report must agree with what the category says: a transient failure invites+ a retry, which ``runtime.unexpected`` does not, and a configuration failure is the operator's to fix. A content+ failure may be the caller's input or a request the runtime built, so it names no code, and neither does an+ unknown one: such an error keeps its class's fallback."""match self:- case InferenceErrorCategory.CONTENT:- return ErrorDomain.INPUT+ case InferenceErrorCategory.TRANSIENT:+ return CoreCode.PROVIDER_UNAVAILABLEcase InferenceErrorCategory.CONFIGURATION:- return ErrorDomain.CONFIG- case InferenceErrorCategory.TRANSIENT | InferenceErrorCategory.CAPACITY | InferenceErrorCategory.AMBIGUOUS:- return ErrorDomain.RUNTIME- case InferenceErrorCategory.UNKNOWN:+ return CoreCode.RUNTIME_MISCONFIGURED+ case InferenceErrorCategory.CAPACITY:+ return CoreCode.PROVIDER_QUOTA_EXHAUSTED+ case InferenceErrorCategory.AMBIGUOUS:+ return CoreCode.PROVIDER_OUTCOME_UNKNOWN+ case InferenceErrorCategory.CONTENT | InferenceErrorCategory.UNKNOWN:return None+# Every code the inference classification picks for a failed provider call (``pipelex.cogt.inference.error_classify``),+# from the status ladder, the status-less type tables and the service error vocabulary a plugin contributes. Each+# family's failure class declares them all, so that the Render step constructs it with the code the classification+# chose, and the vocabulary refuses an entry naming a code outside them. ``model.unavailable`` is also the code of the+# families' not-found classes.+INFERENCE_FAILURE_CODES: tuple[ErrorCode, ...] = (+ CoreCode.RUNTIME_UNEXPECTED,+ CoreCode.RUNTIME_MISCONFIGURED,+ CoreCode.PROVIDER_RATE_LIMITED,+ CoreCode.PROVIDER_UNAVAILABLE,+ CoreCode.PROVIDER_TIMEOUT,+ CoreCode.PROVIDER_FAILED,+ CoreCode.PROVIDER_RESPONSE_INVALID,+ CoreCode.PROVIDER_CREDENTIAL_REFUSED,+ CoreCode.PROVIDER_QUOTA_EXHAUSTED,+ CoreCode.PROVIDER_OUTCOME_UNKNOWN,+ CoreCode.MODEL_UNAVAILABLE,+ CoreCode.MODEL_CAPABILITY_UNSUPPORTED,+ CoreCode.MODEL_CONTEXT_EXCEEDED,+ CoreCode.MODEL_CONTENT_REFUSED,+ CoreCode.MODEL_OUTPUT_SCHEMA_MISMATCH,+ CoreCode.MODEL_NO_RESULT,+ CoreCode.INPUT_TOO_LARGE,+ CoreCode.INPUT_FILE_TYPE_UNSUPPORTED,+ CoreCode.INPUT_FILE_UNREADABLE,+ CoreCode.INPUT_REFERENCE_NOT_FOUND,+ CoreCode.INPUT_URL_UNREACHABLE,+ CoreCode.SECURITY_INPUT_URL_REFUSED,+ CoreCode.SECURITY_METHOD_URL_REFUSED,+ PipelexErrorCode.CONFIG_INVALID,+ PipelexErrorCode.CONFIG_CREDENTIAL_MISSING,+ PipelexErrorCode.BILLING_CREDIT_EXHAUSTED,+)+++def _inference_failure_declaration(*, fallback: ErrorCode) -> InheritsCause:+ """The declaration of a family's failure class: its cause's code, else the fallback, or any classified code chosen."""+ return InheritsCause(fallback=fallback, others=tuple(code for code in INFERENCE_FAILURE_CODES if code is not fallback))++class CogtError(PipelexError):+ """The base of the inference layer's errors, which carry the provider facts a classification reads.++ Never raised directly: a subclass declares its code, or the set the classification picks from+ (``pipelex.cogt.inference.error_classify``), where ``error_category`` stays the runtime's own reading of+ the failure.+ """++ error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERRORerror_category: InferenceErrorCategory | None = Noneuser_action: UserAction | None = Noneprovider_metadata: ProviderErrorMetadata | None = Nonemodel_handle: str | None = Nonebackend_name: str | None = None- _declared_title = "AI inference failed"def __init__(self,@@ -97,6 +161,24 @@ class CogtError(PipelexError):if backend_name is not None:self.backend_name = backend_name+ @property+ @override+ def implied_error_code(self) -> ErrorCode | None:+ """The code its category names, when its class declares it, ``None`` otherwise.++ A failure class takes its cause's code, or its fallback with no coded cause. An error built by hand with a+ category and no code, by a worker or by a plugin, reports its category's code instead+ (``InferenceErrorCategory.default_error_code``), when its class declares it and no Pipelex error along its+ cause chain carries a code of its own, so that its report's retry verdict agrees with the category's. Which+ of the chain's codes wins is ``PipelexError.resolve_error_code``'s one walk, so a cyclic chain cannot recurse.+ """+ if self.error_category is None:+ return None+ category_code = self.error_category.default_error_code+ if category_code is None or category_code not in declared_error_codes(type(self).error_code):+ return None+ return category_code+def fill_model_and_provider(self, model_handle: str | None, *, backend_name: str | None) -> None:"""Fill ``model_handle`` / ``backend_name`` from the worker, only when still unset.@@ -119,31 +201,21 @@ class CogtError(PipelexError):@overridedef to_error_report(self) -> ErrorReport:# Start from the base report (which already runs cause-chain enrichment- # over the shared classification fields) and layer the CogtError-specific+ # over the shared diagnostic fields) and layer the CogtError-specific# fields on top with the same wrapper-wins-when-set semantics: a value# explicitly set on this CogtError overrides whatever the cause surfaced,# otherwise the cause-derived value carried by ``base_report`` stays.+ # The code, and the domain and retry verdict it decides, are already on+ # ``base_report``: the category picked the code, it decides nothing else.# Footgun: ``provider_metadata`` uses whole-object OR, and a Pydantic# model instance is always truthy — a wrapper that attached# attribution-only metadata (no ``status_code`` / ``retry_after_seconds``)# discards the cause's actionable hints. Pinned by# ``tests/unit/pipelex/cogt/test_cogt_provider_metadata_wrapper_wins.py``.base_report = super().to_error_report()- own_retryable = self.error_category.is_retryable if self.error_category is not None else None- # ``error_domain`` is derived from this error's own category rather than declared per leaf- # class, so the two fields can never contradict each other on the wire. Precedence mirrors- # every other field here — a class-level ``error_domain`` set explicitly on the leaf wins,- # then the derivation, then whatever ``base_report`` already inherited from the cause chain- # (which for a ``CogtError`` cause is that cause's own derivation). Deriving from- # ``self.error_category`` and not from ``base_report.error_category`` is deliberate: the- # report field is typed ``str``, and the same wrapper-wins precedence on both fields makes- # the two agree anyway — an inherited category rides in with the domain it derived.- own_domain = self.error_category.error_domain if self.error_category is not None else Nonereturn base_report.model_copy(update={"error_category": self.error_category or base_report.error_category,- "error_domain": self.error_domain or own_domain or base_report.error_domain,- "retryable": own_retryable if own_retryable is not None else base_report.retryable,"model": self.model_handle or base_report.model,"provider": self.backend_name or base_report.provider,"provider_metadata": self.provider_metadata or base_report.provider_metadata,@@ -174,22 +246,20 @@ def find_inference_error_category_in_chain(exc: BaseException) -> InferenceErrorclass LLMConfigError(CogtError):+ error_code = PipelexErrorCode.CONFIG_INVALIDerror_category = InferenceErrorCategory.CONFIGURATION-class ImageContentError(CogtError):- error_category = InferenceErrorCategory.CONTENT--class CostRegistryError(CogtError):- pass-+ """An accounting invariant of the cost registry that did not hold."""-class ReportingManagerError(CogtError):- pass+ error_code = CoreCode.RUNTIME_UNEXPECTEDclass SdkTypeError(CogtError):+ """A worker handed an SDK client of the wrong type: wiring code of ours, not a file an operator edits."""++ error_code = CoreCode.RUNTIME_UNEXPECTEDerror_category = InferenceErrorCategory.CONFIGURATION@@ -201,22 +271,19 @@ class ModelChoiceNotFoundError(CogtError):model is an invalid validation verdict (error type ``unknown_model``), never a failure of the validator.Includes available options and migration hints in error message.++ The reference is the method's, so the fault is its author's: ``model.unknown`` for a reference the deck does not+ define, and ``model.capability_unsupported`` for a bare handle the deck serves only as another model type, which+ the deck chooses where it raises it. A reference the deck itself names, as a default or an override, is the+ deployment's fault instead: the deck re-raises its miss as a ``ModelDeckChoiceUnresolvedError``."""+ error_code = ErrorCodeSet(default=CoreCode.MODEL_UNKNOWN, others=(CoreCode.MODEL_CAPABILITY_UNSUPPORTED,))error_category = InferenceErrorCategory.CONFIGURATION- # Declared explicitly, against the grain of the CONFIGURATION category's ``CONFIG`` derivation,- # because the two fields are answering different questions here. The *category* is right: from- # the provider call's point of view the setup is wrong and no retry will help. But this class- # exists to report a mistyped model reference in material the caller authored — its message- # carries "Did you mean:" suggestions and lists the available options — so the caller is who- # fixes it, on the hosted API (a submitted method naming an unknown model) as much as in a- # local ``.mthds`` file. An operator-side deck fault surfaces as- # ``ModelDeckPresetValidatonError`` instead, which keeps the derived ``CONFIG``.- error_domain = ErrorDomain.INPUT- # The message is caller-facing copy for the same reason: it names only the caller's own model- # reference and the deck's public handles (suggestions, sigil hints, available options). Without- # the flag, STRICT disclosure on the hosted API replaced it with the generic placeholder, so a- # method naming an unknown model failed its dry run with no hint of which model or what to use.+ # The message is caller-facing copy: it names only the caller's own model reference and the+ # deck's public handles (suggestions, sigil hints, available options). Without the flag, STRICT+ # disclosure on the hosted API replaced it with the generic placeholder, so a method naming an+ # unknown model failed its dry run with no hint of which model or what to use._authors_caller_facing_message = Truedef __init__(@@ -256,19 +323,62 @@ class ModelChoiceNotFoundError(CogtError):super().__init__(message=full_message)-class LLMSettingsValidationError(CogtError):- error_category = InferenceErrorCategory.CONFIGURATION+class ModelDeckChoiceUnresolvedError(ModelChoiceNotFoundError):+ """A model choice the model deck names itself, a default or an override, that the deck does not resolve.+ The deck is the deployment's configuration, so the fault is the host's, never the caller's input, though the+ reference reaches the deck's lookup as a method's own does: a step that names no model runs on the deck's default+ or override, and a miss there is raised by the same lookup, as a ``ModelChoiceNotFoundError``, which this wraps.+ A bare handle is ``model.unavailable``, a model this deployment serves no backend for as the type the step needs,+ whose other step lets the caller name a model the step can use; a preset, an alias or a waterfall the deck does+ not define is ``pipelex.config.invalid``. Its message names the deck's setting and the reference, for the+ operator, so it is not caller-facing.-class ImgGenSettingsValidationError(CogtError):+ It is still a model choice the deck does not resolve, so a handler that skips an unresolvable choice, such as the+ load-time checks that leave a model to the run, skips the deck's own as it skips a method's.+ """++ error_code = ErrorCodeSet(default=PipelexErrorCode.CONFIG_INVALID, others=(CoreCode.MODEL_UNAVAILABLE,))error_category = InferenceErrorCategory.CONFIGURATION+ _authors_caller_facing_message = False++ def __init__(self, *, deck_setting: str, unresolved: ModelChoiceNotFoundError):+ self.deck_setting = deck_setting+ message = (+ f"The model deck's {deck_setting} names the model '{unresolved.model_choice}', which the deck does not resolve: {unresolved.message}"+ )+ # The lookup's message already carries its suggestions and options, so they are copied rather than appended again.+ super().__init__(+ message=message,+ model_type=unresolved.model_type,+ model_choice=unresolved.model_choice,+ reference_kind=unresolved.reference_kind,+ )+ self.available_options = unresolved.available_options+ self.suggestions = unresolved.suggestions+ self.wrong_sigil_hints = unresolved.wrong_sigil_hints+ self.cross_collection_suggestions = unresolved.cross_collection_suggestions+ if unresolved.reference_kind is None:+ return+ match unresolved.reference_kind:+ case ModelReferenceKind.HANDLE:+ self.with_error_code(CoreCode.MODEL_UNAVAILABLE)+ case ModelReferenceKind.PRESET | ModelReferenceKind.ALIAS | ModelReferenceKind.WATERFALL:+ pass++class ModelDeckValidationError(CogtError):+ """The model deck as configured is invalid: its files do not validate, or a preset names a model it does not serve."""-class ModelDeckValidatonError(CogtError):+ error_code = PipelexErrorCode.CONFIG_INVALIDerror_category = InferenceErrorCategory.CONFIGURATION-class ModelDeckPresetValidatonError(ModelDeckValidatonError):+class ModelDeckPresetValidationError(ModelDeckValidationError):+ """A deck preset names a model this deployment does not serve, refused when the deck is validated at boot."""++ error_code = PipelexErrorCode.CONFIG_INVALID+def __init__(self,message: str,@@ -285,6 +395,15 @@ class ModelDeckPresetValidatonError(ModelDeckValidatonError):class ModelNotFoundError(CogtError):+ """A model reference that resolves to no model this deployment serves, when a run looks its model up.++ ``model.unavailable`` for a reference the deck itself names (a preset's model, an alias's target, a waterfall)+ on a backend that is not enabled, which is the operator's to fix; ``model.unknown`` for a reference only a+ method's inline model setting names, which the deck chooses where it raises it. The base of the render path's+ not-found classes too, which a provider's answer selects.+ """++ error_code: ClassVar[ErrorCodeDeclaration] = ErrorCodeSet(default=CoreCode.MODEL_UNAVAILABLE, others=(CoreCode.MODEL_UNKNOWN,))error_category = InferenceErrorCategory.CONFIGURATIONdef __init__(@@ -305,6 +424,10 @@ class ModelNotFoundError(CogtError):class ModelWaterfallError(ModelNotFoundError):+ """A waterfall none of whose models this deployment serves."""++ error_code = CoreCode.MODEL_UNAVAILABLE+def __init__(self, message: str, model_handle: str, fallback_list: list[str]):self.model_handle = model_handleself.fallback_list = fallback_list@@ -312,6 +435,7 @@ class ModelWaterfallError(ModelNotFoundError):class LLMHandleNotFoundError(CogtError):+ error_code = PipelexErrorCode.CONFIG_INVALIDerror_category = InferenceErrorCategory.CONFIGURATIONdef __init__(self, message: str, preset_id: str, model_handle: str, enabled_backends: set[str] | None = None):@@ -322,6 +446,7 @@ class LLMHandleNotFoundError(CogtError):class ImgGenHandleNotFoundError(CogtError):+ error_code = PipelexErrorCode.CONFIG_INVALIDerror_category = InferenceErrorCategory.CONFIGURATIONdef __init__(self, message: str, preset_id: str, model_handle: str):@@ -331,6 +456,7 @@ class ImgGenHandleNotFoundError(CogtError):class ExtractHandleNotFoundError(CogtError):+ error_code = PipelexErrorCode.CONFIG_INVALIDerror_category = InferenceErrorCategory.CONFIGURATIONdef __init__(self, message: str, preset_id: str, model_handle: str):@@ -340,6 +466,7 @@ class ExtractHandleNotFoundError(CogtError):class SearchHandleNotFoundError(CogtError):+ error_code = PipelexErrorCode.CONFIG_INVALIDerror_category = InferenceErrorCategory.CONFIGURATIONdef __init__(self, message: str, preset_id: str, model_handle: str):@@ -349,6 +476,7 @@ class SearchHandleNotFoundError(CogtError):class DocGenHandleNotFoundError(CogtError):+ error_code = PipelexErrorCode.CONFIG_INVALIDerror_category = InferenceErrorCategory.CONFIGURATIONdef __init__(self, message: str, preset_id: str, model_handle: str):@@ -358,6 +486,7 @@ class DocGenHandleNotFoundError(CogtError):class JudgmentHandleNotFoundError(CogtError):+ error_code = PipelexErrorCode.CONFIG_INVALIDerror_category = InferenceErrorCategory.CONFIGURATIONdef __init__(self, message: str, preset_id: str, model_handle: str):@@ -366,19 +495,28 @@ class JudgmentHandleNotFoundError(CogtError):super().__init__(message)-class ExtractOutputError(CogtError):- pass--class GeneratedImageError(CogtError):- pass+ """An image a provider returned that cannot be converted."""++ error_code = CoreCode.PROVIDER_RESPONSE_INVALIDclass LLMModelNotFoundError(ModelNotFoundError):- pass+ """A provider that does not know the model the deck resolved, as its answer said: the deployment's to fix."""++ error_code = CoreCode.MODEL_UNAVAILABLEclass LLMCapabilityError(CogtError):+ """A setting or a request the model refuses: the method's choice of model, or of a setting it cannot take.++ ``model.capability_unsupported``, or ``model.context_exceeded`` where the run's inputs carry more images than the+ model takes, which the raise site chooses.+ """++ error_code: ClassVar[ErrorCodeDeclaration] = ErrorCodeSet(+ default=CoreCode.MODEL_CAPABILITY_UNSUPPORTED, others=(CoreCode.MODEL_CONTEXT_EXCEEDED,)+ )error_category = InferenceErrorCategory.CONFIGURATION@@ -389,11 +527,19 @@ class LLMSettingRefusedError(LLMCapabilityError):worker's own refusal carries, so a validation verdict can show it under strict disclosure."""+ error_code = CoreCode.MODEL_CAPABILITY_UNSUPPORTED_authors_caller_facing_message = Trueclass LLMCompletionError(CogtError):- pass+ """A text completion that failed: a provider's failure the classification read, or an answer that cannot be used.++ The Render step constructs it with the code its classification picked, and a worker raising it directly chooses+ one: ``provider.response_invalid`` for an answer with no usable text, ``runtime.unexpected`` for a structured+ generation that failed with no cause to read. A worker wrapping a coded error in it takes that error's code.+ """++ error_code: ClassVar[ErrorCodeDeclaration] = _inference_failure_declaration(fallback=CoreCode.RUNTIME_UNEXPECTED)class CompletionTruncationLimit(StrEnum):@@ -410,8 +556,9 @@ class LLMCompletionTruncatedError(LLMCompletionError):A worker raises it when its provider's stop signal says the text was cut (see`pipelex.cogt.llm.completion_stop`), instead of handing back the partial or empty text as a result. It- is a content error, in the input domain, and not retryable: the same request stops at the same limit,- and the remedy is the author's or the caller's. Which remedy depends on the limit hit, carried as+ is not retryable: the same request stops at the same limit. Its code follows the limit hit:+ ``model.output_truncated`` at the output limit, the method's token cap, and ``model.context_exceeded`` at the+ context window, which the inputs filled. Which remedy applies depends on the limit hit, carried as`truncation_limit`: at the output limit, a higher `max_tokens` on the pipe or a shorter input, or, when therequest sent no `max_tokens` and the provider's default cut the text, a `max_tokens` set on the pipe up tothe model's limit, a lower reasoning effort or a shorter input; at the context window, which the input and@@ -420,6 +567,7 @@ class LLMCompletionTruncatedError(LLMCompletionError):token counts, never the partial text or the provider's body, so it is kept verbatim for the caller."""+ error_code = ErrorCodeSet(default=CoreCode.MODEL_OUTPUT_TRUNCATED, others=(CoreCode.MODEL_CONTEXT_EXCEEDED,))error_category = InferenceErrorCategory.CONTENT_authors_caller_facing_message = True@@ -465,6 +613,11 @@ class LLMCompletionTruncatedError(LLMCompletionError):f"The model '{model_handle}' {what_happened} before it finished {subject} ({', '.join(details)}), so the text is incomplete. {next_step}")super().__init__(message, user_action=UserAction(kind=UserActionKind.CHANGE_INPUT, detail=next_step))+ match truncation_limit:+ case CompletionTruncationLimit.MAX_TOKENS:+ self.with_error_code(CoreCode.MODEL_OUTPUT_TRUNCATED)+ case CompletionTruncationLimit.CONTEXT_WINDOW:+ self.with_error_code(CoreCode.MODEL_CONTEXT_EXCEEDED)self.model_handle = model_handleself.stop_reason = stop_reasonself.truncation_limit = truncation_limit@@ -478,12 +631,13 @@ class LLMCompletionRefusedError(LLMCompletionError):A worker raises it when its provider's stop signal says the model refused or a filter cut the text (see`pipelex.cogt.llm.completion_stop`), instead of handing back the partial or empty text as a result. It- is a content error, in the input domain, and not retryable: what a model declines or a filter blocks is+ is ``model.content_refused``, and not retryable: what a model declines or a filter blocks isthe prompt and the input it was given, so the remedy is to revise them. The message names only the pipe,the model's deck handle and the provider's stop value, never the partial text or the provider's body, soit is kept verbatim for the caller."""+ error_code = CoreCode.MODEL_CONTENT_REFUSEDerror_category = InferenceErrorCategory.CONTENT_authors_caller_facing_message = True@@ -500,113 +654,172 @@ class LLMCompletionRefusedError(LLMCompletionError):self.pipe_code = pipe_code-class LLMAssignmentError(CogtError):- pass-+class LLMPromptParameterError(CogtError):+ """A rendered prompt that holds no text, usually because an input it renders was empty."""-class LLMPromptSpecError(CogtError):+ error_code = CoreCode.PIPE_PROMPT_EMPTYerror_category = InferenceErrorCategory.CONTENT-class LLMPromptParameterError(CogtError):- error_category = InferenceErrorCategory.CONTENT+class LLMSettingValueError(PipelexError, ValueError):+ """An LLM setting whose values contradict each other, refused by its validator.++ A ``ValueError`` as well, so that pydantic wraps it into the validation error of the model being built: the+ method's bundle, or the model deck, whose boundary then reads the fault as its own.+ """++ error_code = CoreCode.METHOD_MODEL_SETTING_INVALIDclass PromptImageFactoryError(CogtError):+ """A prompt image with none of a URI, base64 data or bytes: an invariant of ours."""++ error_code = CoreCode.RUNTIME_UNEXPECTEDerror_category = InferenceErrorCategory.CONTENTclass PromptImageFormatError(CogtError):+ """A prompt image of a known format the model does not read."""++ error_code = CoreCode.INPUT_FILE_TYPE_UNSUPPORTEDerror_category = InferenceErrorCategory.CONTENTclass PromptDocumentFactoryError(CogtError):+ """A prompt document with none of a URI, base64 data or bytes: an invariant of ours."""++ error_code = CoreCode.RUNTIME_UNEXPECTEDerror_category = InferenceErrorCategory.CONTENTclass PromptDocumentFormatError(CogtError):"""A prompt document's known format is one the LLM does not read.- A content error, and so in the input domain: the model is fixed by the method and reads the+ The input's fault, ``input.file_type_unsupported``: the model is fixed by the method and reads theformats it declares, while the file changes from run to run. A model that reads no documents atall is the author's choice of model, which stays an `LLMCapabilityError`."""+ error_code = CoreCode.INPUT_FILE_TYPE_UNSUPPORTEDerror_category = InferenceErrorCategory.CONTENTclass ImgGenModelNotFoundError(ModelNotFoundError):- pass+ """An image provider that does not know the model the deck resolved, as its answer said."""++ error_code = CoreCode.MODEL_UNAVAILABLEclass ImgGenPromptError(CogtError):+ """An image generation prompt that holds no text."""++ error_code = CoreCode.PIPE_PROMPT_EMPTYerror_category = InferenceErrorCategory.CONTENTclass ImgGenParameterError(CogtError):+ """An image generation setting that cannot reach the model.++ ``model.capability_unsupported`` for a setting the method asks of a model that does not take it (an aspect ratio,+ a size, a background, a format); ``pipelex.config.invalid`` for a model spec with no image rules, or rules the+ worker cannot apply; ``runtime.unexpected`` for a prepared file of a type the worker never receives. The raise+ site chooses.+ """++ error_code = ErrorCodeSet(+ default=CoreCode.MODEL_CAPABILITY_UNSUPPORTED,+ others=(PipelexErrorCode.CONFIG_INVALID, CoreCode.RUNTIME_UNEXPECTED),+ )error_category = InferenceErrorCategory.CONTENTclass ImgGenGenerationError(CogtError):- pass+ """An image generation that failed: a provider's failure the classification read, or an answer that cannot be used.+ The Render step constructs it with the code its classification picked, and a worker raising it directly chooses+ one: ``provider.response_invalid`` for an answer with no usable image, ``provider.outcome_unknown`` for a call+ that failed after it was sent, which may have generated, and billed, the image. With no code chosen and no coded+ cause, it is ``provider.outcome_unknown``, since an image generation is a call no one may blindly repeat.+ """-class ImgGenGeneratedTypeError(ImgGenGenerationError):- pass+ error_code = _inference_failure_declaration(fallback=CoreCode.PROVIDER_OUTCOME_UNKNOWN)class ExtractCapabilityError(CogtError):+ """An extraction the model cannot perform, such as captioning images it does not read."""++ error_code = CoreCode.MODEL_CAPABILITY_UNSUPPORTEDerror_category = InferenceErrorCategory.CONFIGURATIONclass ExtractInputFormatError(CogtError):"""The file given to an extraction has a known format that the extract model does not read.- A content error, and so in the input domain: the model is fixed by the method and reads the+ The input's fault, ``input.file_type_unsupported``: the model is fixed by the method and reads theformats it declares, while the file changes from run to run, and the person who can act is theone supplying it."""+ error_code = CoreCode.INPUT_FILE_TYPE_UNSUPPORTEDerror_category = InferenceErrorCategory.CONTENTclass ExtractJobFailureError(CogtError):- pass+ """An extraction that failed at its provider, raised by the Render step with the code its classification picked."""++ error_code = _inference_failure_declaration(fallback=CoreCode.RUNTIME_UNEXPECTED)class ExtractModelNotFoundError(ModelNotFoundError):- pass+ """An extract provider that does not know the model the deck resolved, as its answer said."""++ error_code = CoreCode.MODEL_UNAVAILABLEclass SearchJobFailureError(CogtError):- pass+ """A search that failed at its provider, raised by the Render step with the code its classification picked."""++ error_code = _inference_failure_declaration(fallback=CoreCode.RUNTIME_UNEXPECTED)class SearchModelNotFoundError(ModelNotFoundError):- pass+ """A search provider that does not know the model the deck resolved, as its answer said."""++ error_code = CoreCode.MODEL_UNAVAILABLEclass JudgmentJobFailureError(CogtError):- pass+ """A judgment that failed at its provider, raised by the Render step with the code its classification picked."""++ error_code = _inference_failure_declaration(fallback=CoreCode.RUNTIME_UNEXPECTED)class JudgmentAnswerMismatchError(CogtError):- """A judgment worker answered questions nobody asked, or answered one in the wrong shape."""+ """A judgment worker answered questions nobody asked, or answered one in the wrong shape: its output does not match its schema."""++ error_code = CoreCode.MODEL_OUTPUT_SCHEMA_MISMATCHclass JudgmentCapabilityError(CogtError):"""A judgment job carries files its model does not read: images to a model without vision, documents to one that reads none.- The author's choice of model, and so a configuration error, as `LLMCapabilityError` is for an LLM.- A document of a format the model does not read is the caller's file, which stays a- `PromptDocumentFormatError`.+ The author's choice of model, ``model.capability_unsupported``, as `LLMCapabilityError` is for an LLM; more+ images than the model takes is ``model.context_exceeded``; a model spec claiming files its backend cannot take+ is ``pipelex.config.invalid``. The raise site chooses. A document of a format the model does not read is the+ caller's file, which stays a `PromptDocumentFormatError`."""+ error_code = ErrorCodeSet(+ default=CoreCode.MODEL_CAPABILITY_UNSUPPORTED,+ others=(CoreCode.MODEL_CONTEXT_EXCEEDED, PipelexErrorCode.CONFIG_INVALID),+ )error_category = InferenceErrorCategory.CONFIGURATIONclass JudgmentModelNotFoundError(ModelNotFoundError):- pass+ """A judgment provider that does not know the model the deck resolved, as its answer said."""++ error_code = CoreCode.MODEL_UNAVAILABLEclass JudgmentRefusedError(CogtError):@@ -622,6 +835,7 @@ class JudgmentRefusedError(CogtError):caller."""+ error_code = CoreCode.MODEL_CONTENT_REFUSEDerror_category = InferenceErrorCategory.CONTENT_authors_caller_facing_message = True@@ -663,7 +877,7 @@ class JudgmentModelMissingError(PipelexError):remedies, so it is kept verbatim for the caller."""- error_domain = ErrorDomain.INPUT+ error_code = CoreCode.MODEL_UNSPECIFIED_authors_caller_facing_message = Truedef __init__(self, *, pipe_code: str | None = None):@@ -677,27 +891,29 @@ class JudgmentModelMissingError(PipelexError):class RoutingProfileLibraryNotFoundError(CogtError):- pass+ error_code = PipelexErrorCode.CONFIG_INVALIDclass RoutingProfileBlueprintValueError(CogtError, ValueError):- pass+ """A routing profile's value its validator refuses; a ``ValueError`` as well, so that pydantic wraps it."""++ error_code = PipelexErrorCode.CONFIG_INVALIDclass RoutingProfileLibraryError(CogtError):- pass+ error_code = PipelexErrorCode.CONFIG_INVALIDclass InferenceModelSpecError(CogtError):- pass+ error_code = PipelexErrorCode.CONFIG_INVALIDclass InferenceBackendLibraryNotFoundError(CogtError):- pass+ error_code = PipelexErrorCode.CONFIG_INVALIDclass InferenceBackendLibraryValidationError(CogtError):- pass+ error_code = PipelexErrorCode.CONFIG_INVALIDclass InferenceBackendCredentialsErrorType(StrEnum):@@ -710,6 +926,18 @@ class InferenceBackendCredentialsErrorType(StrEnum):class InferenceBackendCredentialsError(CogtError):+ """A credential a backend needs that this process cannot resolve, coded by why.++ ``pipelex.config.credential_missing`` for a variable or secret this process does not hold, or a fallback pattern+ none of whose candidates resolves; ``pipelex.config.invalid`` for a placeholder whose prefix no secrets provider+ reads, a malformed file rather than a missing key; ``runtime.misconfigured`` for a process booted without+ inference that was asked to call a backend, which is the deployment's wiring.+ """++ error_code = ErrorCodeSet(+ default=PipelexErrorCode.CONFIG_CREDENTIAL_MISSING,+ others=(PipelexErrorCode.CONFIG_INVALID, CoreCode.RUNTIME_MISCONFIGURED),+ )error_category = InferenceErrorCategory.CONFIGURATIONuser_action = UserAction(kind=UserActionKind.CHECK_CREDENTIALS,@@ -739,6 +967,13 @@ class InferenceBackendCredentialsError(CogtError):if user_action is not None:self.user_action = user_actionsuper().__init__(message)+ match credentials_error_type:+ case InferenceBackendCredentialsErrorType.VAR_NOT_FOUND | InferenceBackendCredentialsErrorType.VAR_FALLBACK_PATTERN:+ self.with_error_code(PipelexErrorCode.CONFIG_CREDENTIAL_MISSING)+ case InferenceBackendCredentialsErrorType.UNKNOWN_VAR_PREFIX:+ self.with_error_code(PipelexErrorCode.CONFIG_INVALID)+ case InferenceBackendCredentialsErrorType.NOT_RESOLVED_ON_KEYLESS_BOOT:+ self.with_error_code(CoreCode.RUNTIME_MISCONFIGURED)class InferenceBackendLibraryError(CogtError):@@ -748,15 +983,19 @@ class InferenceBackendLibraryError(CogtError):the failure to that backend rather than to one whose name merely appears in the message's prose."""+ error_code = PipelexErrorCode.CONFIG_INVALIDerror_category = InferenceErrorCategory.CONFIGURATIONclass RoutingProfileDisabledBackendError(CogtError):+ error_code = PipelexErrorCode.CONFIG_INVALIDerror_category = InferenceErrorCategory.CONFIGURATIONclass ModelManagerError(CogtError):- pass+ """A route to a backend that is not loaded, or an exact route to a backend that declares no such model."""++ error_code = PipelexErrorCode.CONFIG_INVALIDclass PluginModelDeclarationError(CogtError):@@ -768,6 +1007,7 @@ class PluginModelDeclarationError(CogtError):file when one is involved."""+ error_code = PipelexErrorCode.CONFIG_INVALIDerror_category = InferenceErrorCategory.CONFIGURATIONdef __init__(self, message: str, *, plugin: str):@@ -786,14 +1026,12 @@ class ModelListingUnsupportedError(CogtError):"unsupported" exception so core names no integration."""+ error_code = CoreCode.RUNTIME_UNSUPPORTED+def __init__(self, *, sdk: str) -> None:self.sdk = sdksuper().__init__(f"The '{sdk}' SDK client does not support remote model listing.")class ModelDeckNotFoundError(CogtError):- pass---class ModelDeckValidationError(CogtError):- pass+ error_code = PipelexErrorCode.CONFIG_INVALIDdiff --git a/pipelex/cogt/extract/exceptions.py b/pipelex/cogt/extract/exceptions.pyindex 401a5776e..1cb827d1c 100644--- a/pipelex/cogt/extract/exceptions.py+++ b/pipelex/cogt/extract/exceptions.py@@ -1,5 +1,14 @@+from mthds.protocol.problem.registry import CoreCode+from pipelex.cogt.exceptions import CogtError+from pipelex.errors.error_code_declaration import ErrorCodeSetclass ExtractInputError(CogtError):- pass+ """An extraction handed an input it cannot take.++ ``runtime.unexpected`` for an input with neither or both of an image and a document, which our own code builds,+ and ``model.capability_unsupported`` for an input of a kind the model does not read, which its raise site chooses.+ """++ error_code = ErrorCodeSet(default=CoreCode.RUNTIME_UNEXPECTED, others=(CoreCode.MODEL_CAPABILITY_UNSUPPORTED,))diff --git a/pipelex/cogt/img_gen/exceptions.py b/pipelex/cogt/img_gen/exceptions.pyindex 48a6714b8..15cd5f5ca 100644--- a/pipelex/cogt/img_gen/exceptions.py+++ b/pipelex/cogt/img_gen/exceptions.py@@ -1,5 +1,13 @@-from pipelex.system.exceptions import CredentialsError+from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import PipelexError-class FalCredentialsError(CredentialsError):- pass++class ImgGenSettingValueError(PipelexError, ValueError):+ """An image generation setting whose values contradict each other, refused by its validator.++ A ``ValueError`` as well, so that pydantic wraps it into the validation error of the model being built: the+ method's bundle, or the model deck, whose boundary then reads the fault as its own.+ """++ error_code = CoreCode.METHOD_MODEL_SETTING_INVALIDdiff --git a/pipelex/cogt/img_gen/img_gen_args_factory.py b/pipelex/cogt/img_gen/img_gen_args_factory.pyindex 5399c9591..703c72a0d 100644--- a/pipelex/cogt/img_gen/img_gen_args_factory.py+++ b/pipelex/cogt/img_gen/img_gen_args_factory.py@@ -11,6 +11,8 @@ import base64from enum import StrEnumfrom typing import Any, TypeAlias, TypeVar+from mthds.protocol.problem.registry import CoreCode+from pipelex import logfrom pipelex.cogt.exceptions import ImgGenParameterError, InferenceErrorCategoryfrom pipelex.cogt.image.image_size import ImageSize@@ -37,6 +39,7 @@ from pipelex.cogt.img_gen.img_gen_model_rules import (SpecificTaxonomy,)from pipelex.config import get_config+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.tools.log.log_fields import USER_ACTION_FIELDfrom pipelex.tools.misc.image_utils import ImageFormatfrom pipelex.tools.uri.prepared_file import PreparedFileBase64, PreparedFileHttpUrl@@ -73,7 +76,9 @@ class ImgGenArgsFactory:return taxonomy_class(taxonomy_value)except ValueError as exc:msg = f"Image model '{model_name}' has an unknown {topic} taxonomy '{taxonomy_value}'"- raise ImgGenParameterError(msg, error_category=InferenceErrorCategory.CONFIGURATION) from exc+ raise ImgGenParameterError(msg, error_category=InferenceErrorCategory.CONFIGURATION).with_error_code(+ PipelexErrorCode.CONFIG_INVALID+ ) from exc@classmethodasync def make_args_for_model(@@ -670,10 +675,10 @@ class ImgGenArgsFactory:elif isinstance(prepped, PreparedFileHttpUrl):# GPT Image API requires the image bytes as a file part, not an HTTP URLmsg = "GPT Image API requires image file data, but got HTTP URL"- raise ImgGenParameterError(msg)+ raise ImgGenParameterError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)else:msg = f"Unexpected PreparedFile type for GPT Image API: {type(prepped).__name__}"- raise ImgGenParameterError(msg)+ raise ImgGenParameterError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)return {"image": image_files}case InputImagesTaxonomy.BFL_FLUX_2:@@ -690,7 +695,7 @@ class ImgGenArgsFactory:args[key] = prepped.urlelse:msg = f"Unexpected PreparedFile type for Flux 2 API: {type(prepped).__name__}"- raise ImgGenParameterError(msg)+ raise ImgGenParameterError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)return args@classmethoddiff --git a/pipelex/cogt/img_gen/img_gen_gemini_mapping.py b/pipelex/cogt/img_gen/img_gen_gemini_mapping.pyindex 836f7921d..106301773 100644--- a/pipelex/cogt/img_gen/img_gen_gemini_mapping.py+++ b/pipelex/cogt/img_gen/img_gen_gemini_mapping.py@@ -19,6 +19,7 @@ from pipelex.cogt.image.image_size import ImageSizefrom pipelex.cogt.img_gen.img_gen_job_components import AspectRatio, SizeTierfrom pipelex.cogt.img_gen.img_gen_model_rules import AspectRatioTaxonomy, ImgGenArgTopicfrom pipelex.cogt.model_backends.model_spec import InferenceModelSpec+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodeGeminiAspectRatioType = Literal["1:1", "1:4", "1:8", "2:3", "3:2", "3:4", "4:1", "4:3", "4:5", "5:4", "8:1", "9:16", "16:9", "21:9"]@@ -142,12 +143,14 @@ class ImgGenGeminiMapping:f"Google image model '{inference_model.name}' has no 'aspect_ratio' rules configured; "f"set rules.aspect_ratio to a Gemini taxonomy (e.g. 'gemini_3_flash')")- raise ImgGenParameterError(msg, error_category=InferenceErrorCategory.CONFIGURATION)+ raise ImgGenParameterError(msg, error_category=InferenceErrorCategory.CONFIGURATION).with_error_code(PipelexErrorCode.CONFIG_INVALID)try:return AspectRatioTaxonomy(taxonomy_value)except ValueError as exc:msg = f"Google image model '{inference_model.name}' has an unknown aspect_ratio taxonomy '{taxonomy_value}'"- raise ImgGenParameterError(msg, error_category=InferenceErrorCategory.CONFIGURATION) from exc+ raise ImgGenParameterError(msg, error_category=InferenceErrorCategory.CONFIGURATION).with_error_code(+ PipelexErrorCode.CONFIG_INVALID+ ) from exc@classmethoddef optional_img_gen_taxonomy(cls, inference_model: InferenceModelSpec) -> AspectRatioTaxonomy | None:@@ -182,7 +185,7 @@ class ImgGenGeminiMapping:taxonomy_value = rules.get(ImgGenArgTopic.ASPECT_RATIO)if taxonomy_value is None:msg = f"Image model '{inference_model.name}' declares no aspect_ratio rule, so whether it takes Google's image_config cannot be decided"- raise ImgGenParameterError(msg, error_category=InferenceErrorCategory.CONFIGURATION)+ raise ImgGenParameterError(msg, error_category=InferenceErrorCategory.CONFIGURATION).with_error_code(PipelexErrorCode.CONFIG_INVALID)try:taxonomy = AspectRatioTaxonomy(taxonomy_value)except ValueError as exc:@@ -190,7 +193,9 @@ class ImgGenGeminiMapping:f"Image model '{inference_model.name}' has an unknown aspect_ratio taxonomy '{taxonomy_value}', ""so whether it takes Google's image_config cannot be decided")- raise ImgGenParameterError(msg, error_category=InferenceErrorCategory.CONFIGURATION) from exc+ raise ImgGenParameterError(msg, error_category=InferenceErrorCategory.CONFIGURATION).with_error_code(+ PipelexErrorCode.CONFIG_INVALID+ ) from excif not taxonomy.is_gemini:return Nonereturn taxonomy@@ -300,7 +305,7 @@ class ImgGenGeminiMapping:| AspectRatioTaxonomy.QWEN_IMAGE):msg = f"Taxonomy '{taxonomy}' configured for model '{model_name}' is not a Google Gemini image generation taxonomy"- raise ImgGenParameterError(msg, error_category=InferenceErrorCategory.CONFIGURATION)+ raise ImgGenParameterError(msg, error_category=InferenceErrorCategory.CONFIGURATION).with_error_code(PipelexErrorCode.CONFIG_INVALID)@classmethoddef dimensions_for_aspect_ratio_and_size(diff --git a/pipelex/cogt/img_gen/img_gen_setting.py b/pipelex/cogt/img_gen/img_gen_setting.pyindex bf2f7a879..66aedafeb 100644--- a/pipelex/cogt/img_gen/img_gen_setting.py+++ b/pipelex/cogt/img_gen/img_gen_setting.py@@ -2,15 +2,12 @@ from typing import Annotated, Self, Unionfrom pydantic import BeforeValidator, Field, model_validator+from pipelex.cogt.img_gen.exceptions import ImgGenSettingValueErrorfrom pipelex.cogt.img_gen.img_gen_job_components import Qualityfrom pipelex.cogt.models.model_reference import ModelReference, parse_model_referencefrom pipelex.system.configuration.config_model import ConfigModel-class ImgGenSettingValueError(ValueError):- pass--class ImgGenSetting(ConfigModel):model: strquality: Quality | None = Field(default=None, strict=False)diff --git a/pipelex/cogt/inference/error_classify.py b/pipelex/cogt/inference/error_classify.pyindex 36d7b60ed..7bf8f80de 100644--- a/pipelex/cogt/inference/error_classify.py+++ b/pipelex/cogt/inference/error_classify.py@@ -11,16 +11,54 @@ by the Extract step (e.g. Google's ``code`` becomes ``status_code``;quota-vs-rate-limit is decided by the ``is_quota_exhaustion`` property). TheHTTP status code drives classification; status-less errors dispatch on theSDK exception type name.++The verdict carries the registry code the rendered error reports, beside the+category the runtime keeps for itself (retries, the Temporal activity's+``non_retryable``). The code depends on the family as well as the metadata in one+respect: a call that may have taken effect on the provider's side cannot be+repeated blind when it is not idempotent, so an image generation's 5xx, timeout+or dropped connection reads ``provider.outcome_unknown`` where a text call's+reads as an outage or a timeout."""-from pydantic import BaseModel+from enum import StrEnum+from typing import NamedTuple, Self++from mthds.protocol.problem.registry import CoreCode+from pydantic import BaseModel, model_validator-from pipelex.cogt.exceptions import InferenceErrorCategory+from pipelex.cogt.exceptions import INFERENCE_FAILURE_CODES, InferenceErrorCategoryfrom pipelex.cogt.inference.error_classification import SDKErrorEnvelope, UserActionKindfrom pipelex.cogt.inference.service_error_vocabulary import ServiceErrorCode+from pipelex.errors.error_codes import ErrorCode, error_code_spec+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.runtime_hub import get_optional_service_error_vocabulary+class InferenceErrorFamily(StrEnum):+ """The worker family raising an inference error: selects the exception class, and whether a call may be repeated."""++ LLM = "llm"+ IMG_GEN = "img_gen"+ EXTRACT = "extract"+ SEARCH = "search"+ JUDGMENT = "judgment"++ @property+ def is_idempotent(self) -> bool:+ """Whether repeating a call that may have taken effect is harmless.++ An image generation is billed per image produced and its result is not kept by the provider for a+ repeat to find, so a call that may have run cannot be sent again blind. A text, extraction, search+ or judgment call answers the same question again.+ """+ match self:+ case InferenceErrorFamily.LLM | InferenceErrorFamily.EXTRACT | InferenceErrorFamily.SEARCH | InferenceErrorFamily.JUDGMENT:+ return True+ case InferenceErrorFamily.IMG_GEN:+ return False++class ClassificationResult(BaseModel):"""Outcome of classifying an inference SDK error.@@ -31,6 +69,10 @@ class ClassificationResult(BaseModel):category: InferenceErrorCategoryuser_action_kind: UserActionKind+ # The registry code the rendered error reports: one of the codes every family's failure class declares+ # (``INFERENCE_FAILURE_CODES``), and ``model.unavailable`` whenever ``is_model_not_found`` selects the+ # family's not-found class.+ error_code: ErrorCodeis_model_not_found: bool = False# The service error code this refusal carried, when the service the request reached refused it# itself under a code its plugin contributed (see ``service_error_vocabulary``). Like@@ -43,27 +85,57 @@ class ClassificationResult(BaseModel):# names the model handle the deck resolved to, which the refusal's own message does not.is_model_not_allowed: bool = False+ @model_validator(mode="after")+ def validate_error_code(self) -> Self:+ if self.error_code not in INFERENCE_FAILURE_CODES:+ msg = f"The classification's code '{self.error_code}' is not one an inference failure class declares"+ raise ValueError(msg)+ if self.is_model_not_found and self.error_code is not CoreCode.MODEL_UNAVAILABLE:+ msg = f"A model-not-found classification reports 'model.unavailable', not '{self.error_code}'"+ raise ValueError(msg)+ # The category decides whether the call is repeated within the run, the code whether the report invites a+ # retry: a call worth repeating cannot report a failure no retry clears.+ if self.category.is_retryable and not error_code_spec(self.error_code).invites_retry:+ msg = f"A {self.category} classification reports a code that invites a retry, not '{self.error_code}'"+ raise ValueError(msg)+ return self+++class _StatuslessVerdict(NamedTuple):+ category: InferenceErrorCategory+ user_action_kind: UserActionKind+ error_code: ErrorCode+# Status-less SDK exception type names recognizable regardless of provider:# the pydantic / instructor schema-validation failure and the uniquely-named# Linkup typed exceptions (which carry no HTTP status). Network/transport# failures are handled earlier via the metadata's ``is_network_error`` property.-_STATUSLESS_BY_TYPE_NAME: dict[str, tuple[InferenceErrorCategory, UserActionKind]] = {- # pydantic / instructor schema-validation failure- "ValidationError": (InferenceErrorCategory.CONTENT, UserActionKind.CHANGE_INPUT),+_STATUSLESS_BY_TYPE_NAME: dict[str, _StatuslessVerdict] = {+ # pydantic / instructor schema-validation failure: the model's answer still did not fit the schema+ # after instructor's re-asks.+ "ValidationError": _StatuslessVerdict(InferenceErrorCategory.CONTENT, UserActionKind.CHANGE_INPUT, CoreCode.MODEL_OUTPUT_SCHEMA_MISMATCH),# Linkup typed SDK exceptions. ``LinkupTimeoutError`` and any# connection-shaped variants flow through ``is_network_error`` (the# ``_NETWORK_ERROR_TOKENS`` check matches "timeout"/"connect"), so they are# intentionally absent from this map.- "LinkupAuthenticationError": (InferenceErrorCategory.CONFIGURATION, UserActionKind.CHECK_CREDENTIALS),- "LinkupInsufficientCreditError": (InferenceErrorCategory.CAPACITY, UserActionKind.CHECK_BILLING),- "LinkupTooManyRequestsError": (InferenceErrorCategory.TRANSIENT, UserActionKind.WAIT_AND_RETRY),- "LinkupInvalidRequestError": (InferenceErrorCategory.CONTENT, UserActionKind.CHANGE_INPUT),- "LinkupNoResultError": (InferenceErrorCategory.CONTENT, UserActionKind.CHANGE_INPUT),- "LinkupFetchResponseTooLargeError": (InferenceErrorCategory.CONTENT, UserActionKind.CHANGE_INPUT),- "LinkupFetchUrlIsFileError": (InferenceErrorCategory.CONTENT, UserActionKind.CHANGE_INPUT),- "LinkupFailedFetchError": (InferenceErrorCategory.TRANSIENT, UserActionKind.WAIT_AND_RETRY),- "LinkupUnknownError": (InferenceErrorCategory.TRANSIENT, UserActionKind.WAIT_AND_RETRY),+ "LinkupAuthenticationError": _StatuslessVerdict(+ InferenceErrorCategory.CONFIGURATION, UserActionKind.CHECK_CREDENTIALS, CoreCode.PROVIDER_CREDENTIAL_REFUSED+ ),+ "LinkupInsufficientCreditError": _StatuslessVerdict(+ InferenceErrorCategory.CAPACITY, UserActionKind.CHECK_BILLING, CoreCode.PROVIDER_QUOTA_EXHAUSTED+ ),+ "LinkupTooManyRequestsError": _StatuslessVerdict(InferenceErrorCategory.TRANSIENT, UserActionKind.WAIT_AND_RETRY, CoreCode.PROVIDER_RATE_LIMITED),+ # A request Linkup could not take is one we built, so it is ours to fix rather than the caller's.+ "LinkupInvalidRequestError": _StatuslessVerdict(InferenceErrorCategory.CONTENT, UserActionKind.CHANGE_INPUT, CoreCode.RUNTIME_UNEXPECTED),+ "LinkupNoResultError": _StatuslessVerdict(InferenceErrorCategory.CONTENT, UserActionKind.CHANGE_INPUT, CoreCode.MODEL_NO_RESULT),+ "LinkupFetchResponseTooLargeError": _StatuslessVerdict(InferenceErrorCategory.CONTENT, UserActionKind.CHANGE_INPUT, CoreCode.INPUT_TOO_LARGE),+ "LinkupFetchUrlIsFileError": _StatuslessVerdict(+ InferenceErrorCategory.CONTENT, UserActionKind.CHANGE_INPUT, CoreCode.INPUT_FILE_TYPE_UNSUPPORTED+ ),+ # The page the caller named could not be fetched, which a later attempt may change.+ "LinkupFailedFetchError": _StatuslessVerdict(InferenceErrorCategory.TRANSIENT, UserActionKind.WAIT_AND_RETRY, CoreCode.INPUT_URL_UNREACHABLE),+ "LinkupUnknownError": _StatuslessVerdict(InferenceErrorCategory.TRANSIENT, UserActionKind.WAIT_AND_RETRY, CoreCode.PROVIDER_FAILED),# TypeSafe's client-side refusal: the SDK validates a request it will not send (an empty# questions map, a rating with no levels) and raises the bare base class, with no status, no# body and no request id. Every one of those is a shape our own blueprint validation is@@ -71,32 +143,70 @@ _STATUSLESS_BY_TYPE_NAME: dict[str, tuple[InferenceErrorCategory, UserActionKind# CONFIGURATION says nothing the caller wrote caused it and CONTACT_SUPPORT says who can fix# it. Its HTTP-reaching siblings (``TypeSafeAPITimeoutError``, ``TypeSafeAPIConnectionError``)# never arrive here: ``is_network_error`` matches their names first.- "TypeSafeError": (InferenceErrorCategory.CONFIGURATION, UserActionKind.CONTACT_SUPPORT),+ "TypeSafeError": _StatuslessVerdict(InferenceErrorCategory.CONFIGURATION, UserActionKind.CONTACT_SUPPORT, CoreCode.RUNTIME_UNEXPECTED),# FAL's typed credential failure — raised before any HTTP call when the API key is unset- "MissingCredentialsError": (InferenceErrorCategory.CONFIGURATION, UserActionKind.CHECK_CREDENTIALS),+ "MissingCredentialsError": _StatuslessVerdict(+ InferenceErrorCategory.CONFIGURATION, UserActionKind.CHECK_CREDENTIALS, PipelexErrorCode.CONFIG_CREDENTIAL_MISSING+ ),# FAL's generic SDK error (base class) — caught last in the worker; HTTP/timeout variants- # are peeled off earlier, so this branch represents the residual SDK failure.- "FalClientError": (InferenceErrorCategory.TRANSIENT, UserActionKind.WAIT_AND_RETRY),+ # are peeled off earlier, so this branch represents the residual SDK failure. FAL serves image+ # generation alone, where ``_classify_statusless`` reads a failure that may have run as an+ # outcome nobody knows.+ "FalClientError": _StatuslessVerdict(InferenceErrorCategory.TRANSIENT, UserActionKind.WAIT_AND_RETRY, CoreCode.PROVIDER_FAILED),}# Builtin exception type names raised by the local file-based extractors# (docling, pypdfium2). Interpreted only when the provider is a local file# extractor — the same builtin type means something else from an SDK provider.-_LOCAL_EXTRACT_BY_TYPE_NAME: dict[str, tuple[InferenceErrorCategory, UserActionKind]] = {- "FileNotFoundError": (InferenceErrorCategory.CONTENT, UserActionKind.CHANGE_INPUT),- "ValueError": (InferenceErrorCategory.CONTENT, UserActionKind.CHANGE_INPUT),- "RuntimeError": (InferenceErrorCategory.CONTENT, UserActionKind.CHANGE_INPUT),- "OSError": (InferenceErrorCategory.TRANSIENT, UserActionKind.WAIT_AND_RETRY),+_LOCAL_EXTRACT_BY_TYPE_NAME: dict[str, _StatuslessVerdict] = {+ "FileNotFoundError": _StatuslessVerdict(InferenceErrorCategory.CONTENT, UserActionKind.CHANGE_INPUT, CoreCode.INPUT_REFERENCE_NOT_FOUND),+ # The file was there and did not parse.+ "ValueError": _StatuslessVerdict(InferenceErrorCategory.CONTENT, UserActionKind.CHANGE_INPUT, CoreCode.INPUT_FILE_UNREADABLE),+ "RuntimeError": _StatuslessVerdict(InferenceErrorCategory.CONTENT, UserActionKind.CHANGE_INPUT, CoreCode.INPUT_FILE_UNREADABLE),+ # A local disk or descriptor failure is this machine's, not the input's and not a provider's, and not one a retry+ # is known to clear.+ "OSError": _StatuslessVerdict(InferenceErrorCategory.UNKNOWN, UserActionKind.CONTACT_SUPPORT, CoreCode.RUNTIME_UNEXPECTED),}+# The httpx transport failures that fire before a request leaves this process: the connection was never+# opened, or never taken from the pool. Nothing reached the provider, so even a call that is not+# idempotent may be sent again. Every other network failure may have fired after the provider took the+# request, an SDK's own ``APIConnectionError`` included, since it wraps a read as well as a connect.+_PRE_REQUEST_TRANSPORT_TYPE_NAMES: frozenset[str] = frozenset({"ConnectError", "ConnectTimeout", "PoolTimeout"})-def _classify_statusless(metadata: SDKErrorEnvelope) -> ClassificationResult:- """Classify an error that never reached an HTTP status (transport failure or local error)."""- if metadata.is_network_error:++def _outcome_unknown() -> ClassificationResult:+ """A call that is not idempotent and may have taken effect: not repeated by the runtime, the reader checks first."""+ return ClassificationResult(+ category=InferenceErrorCategory.AMBIGUOUS,+ user_action_kind=UserActionKind.WAIT_AND_RETRY,+ error_code=CoreCode.PROVIDER_OUTCOME_UNKNOWN,+ )+++def _classify_network_error(*, metadata: SDKErrorEnvelope, family: InferenceErrorFamily) -> ClassificationResult:+ """Classify a failure that never reached an HTTP status: never sent, timed out, or dropped mid-request."""+ type_name = metadata.sdk_exception_type+ if type_name in _PRE_REQUEST_TRANSPORT_TYPE_NAMES:return ClassificationResult(category=InferenceErrorCategory.TRANSIENT,user_action_kind=UserActionKind.WAIT_AND_RETRY,+ error_code=CoreCode.PROVIDER_UNAVAILABLE,)+ if not family.is_idempotent:+ return _outcome_unknown()+ error_code: ErrorCode = CoreCode.PROVIDER_TIMEOUT if "timeout" in type_name.lower() else CoreCode.PROVIDER_UNAVAILABLE+ return ClassificationResult(+ category=InferenceErrorCategory.TRANSIENT,+ user_action_kind=UserActionKind.WAIT_AND_RETRY,+ error_code=error_code,+ )+++def _classify_statusless(metadata: SDKErrorEnvelope, *, family: InferenceErrorFamily) -> ClassificationResult:+ """Classify an error that never reached an HTTP status (transport failure or local error)."""+ if metadata.is_network_error:+ return _classify_network_error(metadata=metadata, family=family)# The provider-agnostic map (pydantic / Linkup) takes precedence; the local# file-extractor map is a fallback applied only for docling / pypdfium2,# where builtins like ``ValueError`` carry an extraction-specific meaning.@@ -105,30 +215,55 @@ def _classify_statusless(metadata: SDKErrorEnvelope) -> ClassificationResult:mapped = _STATUSLESS_BY_TYPE_NAME.get(type_name)if mapped is None and metadata.provider.is_local_file_extractor:mapped = _LOCAL_EXTRACT_BY_TYPE_NAME.get(type_name)- if mapped is not None:- category, user_action_kind = mapped- return ClassificationResult(category=category, user_action_kind=user_action_kind)+ if mapped is None:+ return ClassificationResult(+ category=InferenceErrorCategory.UNKNOWN,+ user_action_kind=UserActionKind.CONTACT_SUPPORT,+ error_code=CoreCode.RUNTIME_UNEXPECTED,+ )+ if mapped.category.is_retryable and not family.is_idempotent:+ # A residual SDK failure on a call that is not idempotent (FAL's ``FalClientError``) may have run.+ return _outcome_unknown()+ return ClassificationResult(category=mapped.category, user_action_kind=mapped.user_action_kind, error_code=mapped.error_code)+++def _classify_server_error(*, status_code: int, family: InferenceErrorFamily) -> ClassificationResult:+ """Classify a provider 5xx: an outage, a timeout or a failure, unless the call may have run and cannot be repeated."""+ if not family.is_idempotent:+ return _outcome_unknown()+ error_code: ErrorCode+ match status_code:+ case 503 | 529:+ # 529 is Anthropic's "overloaded".+ error_code = CoreCode.PROVIDER_UNAVAILABLE+ case 504:+ error_code = CoreCode.PROVIDER_TIMEOUT+ case _:+ error_code = CoreCode.PROVIDER_FAILEDreturn ClassificationResult(- category=InferenceErrorCategory.UNKNOWN,- user_action_kind=UserActionKind.CONTACT_SUPPORT,+ category=InferenceErrorCategory.TRANSIENT,+ user_action_kind=UserActionKind.WAIT_AND_RETRY,+ error_code=error_code,)-def classify_inference_error(metadata: SDKErrorEnvelope) -> ClassificationResult:+def classify_inference_error(metadata: SDKErrorEnvelope, *, family: InferenceErrorFamily) -> ClassificationResult:"""Classify an inference SDK error from its structured metadata.Args:metadata: The structured envelope produced by a provider's``extract_*_metadata`` function.+ family: The worker family that made the call, which says whether a call that may+ have run can be repeated.Returns:A ``ClassificationResult`` carrying the error category, the user-action- kind, and the model-not-found flag.+ kind, the registry code, and the model-not-found flag."""status_code = metadata.status_codeif status_code is None:- return _classify_statusless(metadata)+ return _classify_statusless(metadata, family=family)# A code the service contributed comes first: an explicit code from the service itself is a# more specific verdict than any status bucket, and the statuses such refusals arrive on (413,@@ -142,6 +277,7 @@ def classify_inference_error(metadata: SDKErrorEnvelope) -> ClassificationResultreturn ClassificationResult(category=service_error_code.category,user_action_kind=service_error_code.user_action_kind,+ error_code=service_error_code.error_code,is_model_not_found=service_error_code.is_model_not_found,service_error_code=service_error_code,)@@ -154,6 +290,7 @@ def classify_inference_error(metadata: SDKErrorEnvelope) -> ClassificationResultreturn ClassificationResult(category=InferenceErrorCategory.CONFIGURATION,user_action_kind=UserActionKind.CHANGE_MODEL,+ error_code=CoreCode.MODEL_UNAVAILABLE,is_model_not_allowed=True,)@@ -164,44 +301,61 @@ def classify_inference_error(metadata: SDKErrorEnvelope) -> ClassificationResultreturn ClassificationResult(category=InferenceErrorCategory.CAPACITY,user_action_kind=UserActionKind.CHECK_BILLING,+ error_code=CoreCode.PROVIDER_QUOTA_EXHAUSTED,)if status_code == 429:return ClassificationResult(category=InferenceErrorCategory.TRANSIENT,user_action_kind=UserActionKind.WAIT_AND_RETRY,+ error_code=CoreCode.PROVIDER_RATE_LIMITED,+ )++ if status_code == 408:+ # The provider answered that it gave up waiting. Nothing in the caller's input or the deployment caused it,+ # and the provider said so itself, which is not the lost answer `provider.outcome_unknown` covers: the call+ # is repeated, a billed image call included.+ return ClassificationResult(+ category=InferenceErrorCategory.TRANSIENT,+ user_action_kind=UserActionKind.WAIT_AND_RETRY,+ error_code=CoreCode.PROVIDER_TIMEOUT,)if status_code == 402:return ClassificationResult(category=InferenceErrorCategory.CAPACITY,user_action_kind=UserActionKind.CHECK_BILLING,+ error_code=CoreCode.PROVIDER_QUOTA_EXHAUSTED,)if status_code in {401, 403}:return ClassificationResult(category=InferenceErrorCategory.CONFIGURATION,user_action_kind=UserActionKind.CHECK_CREDENTIALS,+ error_code=CoreCode.PROVIDER_CREDENTIAL_REFUSED,)if status_code == 404:+ # The deck names a provider model id the provider no longer serves: a method cannot name a raw+ # provider id, so this is never the method's `model.unknown`.return ClassificationResult(category=InferenceErrorCategory.CONFIGURATION,user_action_kind=UserActionKind.CHANGE_MODEL,+ error_code=CoreCode.MODEL_UNAVAILABLE,is_model_not_found=True,)if status_code == 400:+ # A 400 nothing recognises is most likely a request of ours the provider could not take; only a+ # content-policy signal says the caller's material was refused.return ClassificationResult(category=InferenceErrorCategory.CONTENT,user_action_kind=UserActionKind.CHANGE_INPUT,+ error_code=CoreCode.MODEL_CONTENT_REFUSED if metadata.is_content_policy_violation else CoreCode.RUNTIME_UNEXPECTED,)if status_code >= 500:- return ClassificationResult(- category=InferenceErrorCategory.TRANSIENT,- user_action_kind=UserActionKind.WAIT_AND_RETRY,- )+ return _classify_server_error(status_code=status_code, family=family)if status_code >= 400:# Unrecognized 4xx (e.g. 405, 409, 422) — 5xx is handled above. A safety/content@@ -213,14 +367,24 @@ def classify_inference_error(metadata: SDKErrorEnvelope) -> ClassificationResultreturn ClassificationResult(category=InferenceErrorCategory.CONTENT,user_action_kind=UserActionKind.CHANGE_INPUT,+ error_code=CoreCode.MODEL_CONTENT_REFUSED,)+ error_code: ErrorCode+ match status_code:+ case 413:+ # Anthropic's ``request_too_large``: the request the caller's material made is over the provider's limit.+ error_code = CoreCode.INPUT_TOO_LARGE+ case _:+ error_code = CoreCode.RUNTIME_UNEXPECTEDreturn ClassificationResult(category=InferenceErrorCategory.CONFIGURATION,user_action_kind=UserActionKind.CHANGE_INPUT,+ error_code=error_code,)- # A non-error status (< 400) on an error envelope: nothing we can classify.+ # A non-error status (< 400) on an error envelope: the provider's answer could not be used.return ClassificationResult(category=InferenceErrorCategory.UNKNOWN,user_action_kind=UserActionKind.CONTACT_SUPPORT,+ error_code=CoreCode.PROVIDER_RESPONSE_INVALID,)diff --git a/pipelex/cogt/inference/error_render.py b/pipelex/cogt/inference/error_render.pyindex 3545e9bd9..12cd8b560 100644--- a/pipelex/cogt/inference/error_render.py+++ b/pipelex/cogt/inference/error_render.py@@ -8,7 +8,6 @@ worker's error family, with a human-readable message and a structured"""import math-from enum import StrEnumfrom pipelex.cogt.exceptions import (CogtError,@@ -25,18 +24,7 @@ from pipelex.cogt.exceptions import (SearchModelNotFoundError,)from pipelex.cogt.inference.error_classification import SDKErrorEnvelope, UserAction, UserActionKind-from pipelex.cogt.inference.error_classify import ClassificationResult---class InferenceErrorFamily(StrEnum):- """The worker family raising an inference error — selects the exception class."""-- LLM = "llm"- IMG_GEN = "img_gen"- EXTRACT = "extract"- SEARCH = "search"- JUDGMENT = "judgment"-+from pipelex.cogt.inference.error_classify import ClassificationResult, InferenceErrorFamily# Generic failure error class per family — used when the error is not a missing model._FAILURE_CLASSES: dict[InferenceErrorFamily, type[CogtError]] = {@@ -93,6 +81,9 @@ def _render_detail(metadata: SDKErrorEnvelope, *, classification: Classification# Same reason: ``CHANGE_MODEL`` renders "the requested model was not found", which is false# for a model that exists and is served, only not for this caller.return _render_model_not_allowed_detail(model_handle=model_handle)+ if classification.category.is_outcome_unknown:+ # A call that is not idempotent may have run: the kind's "run it again" would duplicate a billed result.+ return "The provider failed after the request was sent, so it may have produced and billed a result — check for one before running it again."match classification.user_action_kind:case UserActionKind.WAIT_AND_RETRY:# The advice is read on a failed run's report, once every automatic retry is spent, so@@ -137,7 +128,7 @@ def render_inference_error(Returns:A ``CogtError`` subclass instance carrying the category, structured- ``UserAction``, and ``provider_metadata``.+ ``UserAction``, and ``provider_metadata``, with the classification's code chosen."""message = _format_message(metadata, model_desc=model_desc)user_action = UserAction(@@ -153,10 +144,13 @@ def render_inference_error(user_action=user_action,provider_metadata=metadata,)+ # The not-found classes report ``model.unavailable`` alone, which the classification guarantees. A failure+ # class declares every classified code, and its code is chosen here rather than inherited, since the+ # provider's exception it is raised from carries none.failure_class = _FAILURE_CLASSES[family]return failure_class(message,error_category=classification.category,user_action=user_action,provider_metadata=metadata,- )+ ).with_error_code(classification.error_code)diff --git a/pipelex/cogt/inference/service_error_vocabulary.py b/pipelex/cogt/inference/service_error_vocabulary.pyindex 7f1b362ca..6e2930b04 100644--- a/pipelex/cogt/inference/service_error_vocabulary.py+++ b/pipelex/cogt/inference/service_error_vocabulary.py@@ -18,11 +18,14 @@ code does, and a service that contributes codes vouches that no vendor emits int"""from collections.abc import Mapping+from typing import Self-from pydantic import BaseModel, ConfigDict, Field+from mthds.protocol.problem.registry import CoreCode+from pydantic import BaseModel, ConfigDict, Field, model_validator-from pipelex.cogt.exceptions import InferenceErrorCategory+from pipelex.cogt.exceptions import INFERENCE_FAILURE_CODES, InferenceErrorCategoryfrom pipelex.cogt.inference.error_classification import UserActionKind+from pipelex.errors.error_codes import ErrorCode, error_code_specclass ServiceErrorCode(BaseModel):@@ -30,8 +33,10 @@ class ServiceErrorCode(BaseModel):`detail` is the advice rendered beside the service's own message. It names what the caller, orwhoever operates the service, should do; the service's message already names the specifics.- `is_model_not_found` selects the family's `*ModelNotFoundError` class, for a code that means the- service does not know the model at all.+ `error_code` is the registry code the rendered error reports, which says who acts and whether a+ retry can succeed: one of the codes an inference failure class declares, and `model.unavailable`+ for an entry flagged `is_model_not_found`, which selects the family's `*ModelNotFoundError` class,+ for a code that means the service does not know the model at all."""model_config = ConfigDict(frozen=True, extra="forbid")@@ -39,9 +44,23 @@ class ServiceErrorCode(BaseModel):code: strcategory: InferenceErrorCategory = Field(strict=False)user_action_kind: UserActionKind = Field(strict=False)+ error_code: ErrorCodedetail: stris_model_not_found: bool = False+ @model_validator(mode="after")+ def validate_error_code(self) -> Self:+ if self.error_code not in INFERENCE_FAILURE_CODES:+ msg = f"Service error code '{self.code}' reports '{self.error_code}', which no inference failure class declares"+ raise ValueError(msg)+ if self.is_model_not_found and self.error_code is not CoreCode.MODEL_UNAVAILABLE:+ msg = f"Service error code '{self.code}' means the model is not found, so it reports 'model.unavailable', not '{self.error_code}'"+ raise ValueError(msg)+ if self.category.is_retryable and not error_code_spec(self.error_code).invites_retry:+ msg = f"Service error code '{self.code}' is {self.category}, so it reports a code that invites a retry, not '{self.error_code}'"+ raise ValueError(msg)+ return self+class ServiceErrorVocabulary:"""Every service error code the booted plugins contributed, keyed by code.diff --git a/pipelex/cogt/judgment/judgment_worker_abstract.py b/pipelex/cogt/judgment/judgment_worker_abstract.pyindex 4b6543996..25f6ed4ae 100644--- a/pipelex/cogt/judgment/judgment_worker_abstract.py+++ b/pipelex/cogt/judgment/judgment_worker_abstract.py@@ -2,6 +2,7 @@ import mathfrom abc import abstractmethodfrom collections.abc import Mapping+from mthds.protocol.problem.registry import CoreCodefrom typing_extensions import overridefrom pipelex.cogt.exceptions import CogtError, JudgmentAnswerMismatchError, JudgmentCapabilityError@@ -103,7 +104,7 @@ class JudgmentWorkerAbstract(InferenceWorkerAbstract):f"Judgment model '{self.inference_model.name}' reads at most {max_prompt_images} images, "f"and the judgment was given {len(prompt_images)}.")- raise JudgmentCapabilityError(msg)+ raise JudgmentCapabilityError(msg).with_error_code(CoreCode.MODEL_CONTEXT_EXCEEDED)check_prompt_images_are_images(model_name=self.inference_model.name, prompt_images=prompt_images)prompt_documents = judgment_job.prompt.documentsdiff --git a/pipelex/cogt/llm/llm_setting.py b/pipelex/cogt/llm/llm_setting.pyindex c77b7ced6..510a0db32 100644--- a/pipelex/cogt/llm/llm_setting.py+++ b/pipelex/cogt/llm/llm_setting.py@@ -2,16 +2,13 @@ from typing import Annotated, Any, Self, Unionfrom pydantic import BeforeValidator, Field, WithJsonSchema, field_validator, model_validator+from pipelex.cogt.exceptions import LLMSettingValueErrorfrom pipelex.cogt.image.prompt_image import PromptImageDetailfrom pipelex.cogt.llm.llm_job_components import LLMJobParams, ReasoningEffortfrom pipelex.cogt.models.model_reference import ModelReference, parse_model_referencefrom pipelex.system.configuration.config_model import ConfigModel-class LLMSettingValueError(ValueError):- pass--class LLMSetting(ConfigModel):model: strtemperature: float = Field(..., ge=0, le=1)@@ -84,9 +81,6 @@ class LLMSettingChoices(ConfigModel):for_text: LLMModelChoice | Nonefor_object: LLMModelChoice | None- def list_choice_references(self) -> set[ModelReference]:- return {item for item in (self.for_text, self.for_object) if isinstance(item, ModelReference)}-@classmethoddef make_completed_with_defaults(cls, *, for_text: LLMModelChoice | None = None, for_object: LLMModelChoice | None = None) -> Self:return cls(diff --git a/pipelex/cogt/llm/llm_worker_abstract.py b/pipelex/cogt/llm/llm_worker_abstract.pyindex b24b96804..1365205a1 100644--- a/pipelex/cogt/llm/llm_worker_abstract.py+++ b/pipelex/cogt/llm/llm_worker_abstract.py@@ -4,6 +4,7 @@ import sysfrom abc import ABC, abstractmethodfrom typing import TYPE_CHECKING, Any+from mthds.protocol.problem.registry import CoreCodefrom opentelemetry import tracefrom opentelemetry.trace import NonRecordingSpan, Span, SpanContext, SpanKind, Status, StatusCode, TraceFlagsfrom typing_extensions import override@@ -525,7 +526,7 @@ class LLMWorkerAbstract(InferenceWorkerAbstract, ABC):max_prompt_images = self.inference_model.max_prompt_images or 5000if nb_images > max_prompt_images:msg = f"LLM Engine '{self.inference_model.tag}' does not accept that many images: {nb_images}."- raise LLMCapabilityError(msg)+ raise LLMCapabilityError(msg).with_error_code(CoreCode.MODEL_CONTEXT_EXCEEDED)check_prompt_images_are_images(model_name=self.inference_model.name, prompt_images=llm_job.llm_prompt.user_images)diff --git a/pipelex/cogt/models/exceptions.py b/pipelex/cogt/models/exceptions.pyindex 5c3c51d79..75d192387 100644--- a/pipelex/cogt/models/exceptions.py+++ b/pipelex/cogt/models/exceptions.py@@ -1,12 +1,20 @@+from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import PipelexError+from pipelex.errors.error_code_declaration import ErrorCodeSet+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodeclass ModelReferenceParseError(PipelexError):"""Error raised when a model reference string cannot be parsed.- Includes helpful syntax guide in error message.+ Includes helpful syntax guide in error message. ``method.model_setting_invalid`` for a reference a method+ writes, and ``pipelex.config.invalid`` for one the model deck writes, which a site that knows the reference is+ the deck's chooses; the parser itself cannot tell."""+ error_code = ErrorCodeSet(default=CoreCode.METHOD_MODEL_SETTING_INVALID, others=(PipelexErrorCode.CONFIG_INVALID,))+def __init__(self, message: str, raw_value: str):self.raw_value = raw_valuesyntax_help = (diff --git a/pipelex/cogt/models/model_deck.py b/pipelex/cogt/models/model_deck.pyindex 8cc32aa77..4ef993f0e 100644--- a/pipelex/cogt/models/model_deck.py+++ b/pipelex/cogt/models/model_deck.py@@ -1,6 +1,8 @@-from collections.abc import Container, Mapping-from typing import NoReturn, Self+from collections.abc import Callable, Container, Mapping+from functools import partial+from typing import NoReturn, Self, TypeVar+from mthds.protocol.problem.registry import CoreCodefrom pydantic import Field, PrivateAttr, field_validator, model_validatorfrom pipelex import log@@ -15,7 +17,8 @@ from pipelex.cogt.exceptions import (JudgmentHandleNotFoundError,LLMHandleNotFoundError,ModelChoiceNotFoundError,- ModelDeckPresetValidatonError,+ ModelDeckChoiceUnresolvedError,+ ModelDeckPresetValidationError,ModelNotFoundError,ModelWaterfallError,SearchHandleNotFoundError,@@ -55,6 +58,29 @@ from pipelex.urls import URLsLLM_PRESET_DISABLED = "disabled"+DeckSettingT = TypeVar("DeckSettingT")+++def resolve_deck_choice(*, deck_setting: str, resolve: Callable[[], DeckSettingT]) -> DeckSettingT:+ """Resolve a model choice the deck names itself, a default or an override, so that a miss is the deck's fault.++ The deck's lookups refuse a reference they do not resolve as ``ModelChoiceNotFoundError``, which reads as the+ method's: ``model.unknown`` and caller-facing. A step that names no model reaches the same lookups with the deck's+ own choice, and the caller can change nothing about that, so the miss is raised again as a+ ``ModelDeckChoiceUnresolvedError`` naming the deck's setting.++ Args:+ deck_setting: Where the deck names the choice, as its file spells it, such as ``extract.choice_default``.+ resolve: The lookup of the deck's choice.++ Returns:+ What the lookup returns.+ """+ try:+ return resolve()+ except ModelChoiceNotFoundError as exc:+ raise ModelDeckChoiceUnresolvedError(deck_setting=deck_setting, unresolved=exc) from exc+def _warn_if_ambiguous_bare_handle(*,@@ -298,14 +324,22 @@ class ModelDeck(ConfigModel):case ModelReferenceKind.HANDLE:return self.is_bare_handle_resolvable(name=reference.name, model_type=model_type)+ def is_served_only_as_other_types(self, *, name: str, model_type: ModelType) -> bool:+ """Whether the deck serves a model of this name, but never as this model type.++ A bare handle refused for that reason names a model that exists and is served, so its refusal is the+ model lacking the capability the step needs (``model.capability_unsupported``), not an unknown model.+ """+ served_types = self.inference_models.types_serving(handle=name)+ return bool(served_types) and model_type not in served_types+def unresolved_handle_sentence(self, *, name: str, model_type: ModelType) -> str:"""The sentence refusing a bare handle that does not resolve for this model type.It names the handle and the type the field needs. When the deck serves a model of that nameonly as other types, it says so rather than calling the handle missing, without naming them."""- served_types = self.inference_models.types_serving(handle=name)- if served_types and model_type not in served_types:+ if self.is_served_only_as_other_types(name=name, model_type=model_type):return f"Model handle '{name}' is served by the model deck, but not as {model_type.indefinite_description}"return f"Model handle '{name}' was not found in the model deck"@@ -425,13 +459,16 @@ class ModelDeck(ConfigModel):if hints:msg += "\n\nMigration hints:\n" + "\n".join(f" - {hint}" for hint in hints)- raise ModelChoiceNotFoundError(+ not_found = ModelChoiceNotFoundError(message=msg,model_type=model_type,model_choice=ref.raw,reference_kind=ModelReferenceKind.HANDLE,available_options=self.inference_models.handles_of_type(model_type=model_type),)+ if self.is_served_only_as_other_types(name=ref.name, model_type=model_type):+ raise not_found.with_error_code(CoreCode.MODEL_CAPABILITY_UNSUPPORTED)+ raise not_founddef check_llm_choice(self,@@ -484,13 +521,16 @@ class ModelDeck(ConfigModel):if self.is_bare_handle_resolvable(name=ref.name, model_type=ModelType.LLM):returnmsg = self.unresolved_handle_sentence(name=ref.name, model_type=ModelType.LLM)- raise ModelChoiceNotFoundError(+ not_found = ModelChoiceNotFoundError(message=msg,model_type=ModelType.LLM,model_choice=ref.raw,reference_kind=ModelReferenceKind.HANDLE,available_options=self.inference_models.handles_of_type(model_type=ModelType.LLM),)+ if self.is_served_only_as_other_types(name=ref.name, model_type=ModelType.LLM):+ raise not_found.with_error_code(CoreCode.MODEL_CAPABILITY_UNSUPPORTED)+ raise not_founddef get_llm_setting(self, llm_choice: LLMModelChoice) -> LLMSetting:if isinstance(llm_choice, LLMSetting):@@ -821,8 +861,13 @@ class ModelDeck(ConfigModel):@model_validator(mode="after")def validate_llm_choice_overrides(self) -> Self:- for llm_choice_ref in self.llm_choice_overrides.list_choice_references():- self.check_llm_choice(llm_choice=llm_choice_ref)+ # An override is the deck's own choice, so a miss is the deck's fault, refused before any caller is involved.+ for field_name, llm_choice in (("for_text", self.llm_choice_overrides.for_text), ("for_object", self.llm_choice_overrides.for_object)):+ if isinstance(llm_choice, ModelReference):+ resolve_deck_choice(+ deck_setting=f"llm.choice_overrides.{field_name}",+ resolve=partial(self.check_llm_choice, llm_choice=llm_choice),+ )return selfdef validate_llm_presets(self) -> Self:@@ -913,7 +958,7 @@ class ModelDeck(ConfigModel):match self.model_deck_config.missing_presets_reaction:case ProblemReaction.RAISE:msg = f"Failed to validate all LLM presets: {exc}"- raise ModelDeckPresetValidatonError(+ raise ModelDeckPresetValidationError(message=msg,model_type=ModelType.LLM,preset_id=exc.preset_id,@@ -930,7 +975,7 @@ class ModelDeck(ConfigModel):match self.model_deck_config.missing_presets_reaction:case ProblemReaction.RAISE:msg = f"Failed to validate all ImgGen presets: {exc}"- raise ModelDeckPresetValidatonError(+ raise ModelDeckPresetValidationError(message=msg,model_type=ModelType.IMG_GEN,preset_id=exc.preset_id,@@ -946,7 +991,7 @@ class ModelDeck(ConfigModel):match self.model_deck_config.missing_presets_reaction:case ProblemReaction.RAISE:msg = f"Failed to validate all Extract presets: {exc}"- raise ModelDeckPresetValidatonError(+ raise ModelDeckPresetValidationError(message=msg,model_type=ModelType.TEXT_EXTRACTOR,preset_id=exc.preset_id,@@ -962,7 +1007,7 @@ class ModelDeck(ConfigModel):match self.model_deck_config.missing_presets_reaction:case ProblemReaction.RAISE:msg = f"Failed to validate all Search presets: {exc}"- raise ModelDeckPresetValidatonError(+ raise ModelDeckPresetValidationError(message=msg,model_type=ModelType.SEARCH,preset_id=exc.preset_id,@@ -978,7 +1023,7 @@ class ModelDeck(ConfigModel):match self.model_deck_config.missing_presets_reaction:case ProblemReaction.RAISE:msg = f"Failed to validate all DocGen presets: {exc}"- raise ModelDeckPresetValidatonError(+ raise ModelDeckPresetValidationError(message=msg,model_type=ModelType.DOC_GEN,preset_id=exc.preset_id,@@ -994,7 +1039,7 @@ class ModelDeck(ConfigModel):match self.model_deck_config.missing_presets_reaction:case ProblemReaction.RAISE:msg = f"Failed to validate all Judgment presets: {exc}"- raise ModelDeckPresetValidatonError(+ raise ModelDeckPresetValidationError(message=msg,model_type=ModelType.JUDGMENT,preset_id=exc.preset_id,@@ -1328,7 +1373,6 @@ class ModelDeck(ConfigModel):# reaches, a hosted run's stored error included, whose reader has no local deck. The# remedy for a stale local deck is the local CLI's to give, in its model panel.msg = f"Model handle '{model_handle}' was not found in the model deck."- model_not_found_error = ModelNotFoundError(message=msg, model_handle=model_handle)if not self._is_deck_model_reference(model_handle=model_handle, model_type=model_type):# The deck neither defines this reference for this type nor names it anywhere, so the# method being run named it. The load-time check refuses every reference it sees that@@ -1338,15 +1382,19 @@ class ModelDeck(ConfigModel):# The message and the next step name nothing but the caller's own reference, as the# method wrote it, and the type its pipe asked for, never the type the deck serves it# as. A reference the deck itself names but cannot serve (a preset or an alias target on- # a backend that is not enabled) stays the deployment's fault, and stays redacted, with- # no next step.- model_not_found_error.as_caller_fault(- user_action=UserAction(- kind=UserActionKind.CHANGE_MODEL,- detail=f"Change the model '{model_handle}' to {model_type.indefinite_description} the model deck serves.",+ # a backend that is not enabled) stays the deployment's fault, `model.unavailable`, and stays+ # redacted, with no next step.+ raise (+ ModelNotFoundError(message=msg, model_handle=model_handle)+ .with_error_code(CoreCode.MODEL_UNKNOWN)+ .as_caller_fault(+ user_action=UserAction(+ kind=UserActionKind.CHANGE_MODEL,+ detail=f"Change the model '{model_handle}' to {model_type.indefinite_description} the model deck serves.",+ )))- raise model_not_found_error+ raise ModelNotFoundError(message=msg, model_handle=model_handle)if self.inference_models.get(model_type=model_type, handle=model_handle) is None:log.verbose(f"Model reference '{model_handle}' resolves to model '{inference_model.name}'")return inference_modeldiff --git a/pipelex/cogt/models/model_deck_check.py b/pipelex/cogt/models/model_deck_check.pyindex 94abaf8d7..5a085a4d3 100644--- a/pipelex/cogt/models/model_deck_check.py+++ b/pipelex/cogt/models/model_deck_check.py@@ -2,6 +2,8 @@from typing import NoReturn+from mthds.protocol.problem.registry import CoreCode+from pipelex.cogt.doc_gen.doc_gen_setting import DocGenModelChoice, DocGenSettingfrom pipelex.cogt.exceptions import ModelChoiceNotFoundErrorfrom pipelex.cogt.extract.extract_setting import ExtractModelChoice, ExtractSetting@@ -26,11 +28,15 @@ def _raise_model_choice_not_found(reference_kind: ModelReferenceKind,available_options: list[str],) -> NoReturn:- """Compute fuzzy suggestions and raise ModelChoiceNotFoundError."""+ """Compute fuzzy suggestions and raise ModelChoiceNotFoundError.++ A bare handle the deck serves only as other types names a model that exists, so its refusal is the capability+ that model lacks, `model.capability_unsupported`, rather than an unknown model.+ """suggestions, wrong_sigil_hints, cross_suggestions = suggest_model_alternatives(model_deck=model_deck, model_type=model_type, name=name, kind=reference_kind)- raise ModelChoiceNotFoundError(+ not_found = ModelChoiceNotFoundError(message=msg,model_type=model_type,model_choice=raw_choice,@@ -40,6 +46,13 @@ def _raise_model_choice_not_found(wrong_sigil_hints=wrong_sigil_hints,cross_collection_suggestions=cross_suggestions,)+ match reference_kind:+ case ModelReferenceKind.HANDLE:+ if model_deck.is_served_only_as_other_types(name=name, model_type=model_type):+ raise not_found.with_error_code(CoreCode.MODEL_CAPABILITY_UNSUPPORTED)+ raise not_found+ case ModelReferenceKind.PRESET | ModelReferenceKind.ALIAS | ModelReferenceKind.WATERFALL:+ raise not_founddef check_llm_choice_with_deck(llm_choice: LLMModelChoice) -> None:diff --git a/pipelex/cogt/templating/exceptions.py b/pipelex/cogt/templating/exceptions.pyindex 2a32980db..efeffdebd 100644--- a/pipelex/cogt/templating/exceptions.py+++ b/pipelex/cogt/templating/exceptions.py@@ -1,3 +1,5 @@+from mthds.protocol.problem.registry import CoreCode+from pipelex.system.exceptions import ToolError@@ -6,5 +8,8 @@ class TemplateSigilSyntaxError(ToolError):line-bounded `@` rule.The error message includes the 1-based line number, the offending sigil span, and a- migration hint pointing the author at `$var` (inline) or `@@` (literal `@`).+ migration hint pointing the author at `$var` (inline) or `@@` (literal `@`). The sigil is misplaced in the+ method's own template, so it is the method's syntax error."""++ error_code = CoreCode.METHOD_SYNTAXdiff --git a/pipelex/cogt/templating/template_rendering.py b/pipelex/cogt/templating/template_rendering.pyindex 8dd25c049..9391a188c 100644--- a/pipelex/cogt/templating/template_rendering.py+++ b/pipelex/cogt/templating/template_rendering.py@@ -4,6 +4,7 @@ from typing import Anyfrom pipelex.cogt.templating.template_preprocessor import rewrite_template_sigilsfrom pipelex.tools.jinja2.jinja2_rendering import render_jinja2_asyncfrom pipelex.tools.jinja2.template_category import TemplateCategory+from pipelex.tools.jinja2.template_owner import TemplateOwnerfrom pipelex.tools.templating.templating_style import TemplatingStyle@@ -15,7 +16,9 @@ async def render_template(templating_style: TemplatingStyle | None = None,finalize: Callable[[Any], Any] | None = None,is_undefined_strict: bool = False,+ template_owner: TemplateOwner = TemplateOwner.METHOD,) -> str:+ """Render a template written with sigils, a method's unless `template_owner` says it is Pipelex's own."""template_source = rewrite_template_sigils(template)return await render_jinja2_async(@@ -25,4 +28,5 @@ async def render_template(templating_style=templating_style,finalize=finalize,is_undefined_strict=is_undefined_strict,+ template_owner=template_owner,)diff --git a/pipelex/core/bundle_resources/bundle_resource.py b/pipelex/core/bundle_resources/bundle_resource.pyindex 186eab9a3..bc2426a89 100644--- a/pipelex/core/bundle_resources/bundle_resource.py+++ b/pipelex/core/bundle_resources/bundle_resource.py@@ -10,6 +10,8 @@ it would in a folder, and the run's crate names that tree by its digest like anyfrom collections.abc import Mappingfrom pathlib import PurePosixPath+from mthds.protocol.problem.registry import CoreCode+from pipelex.core.bundle_resources.exceptions import BundleResourcePathError@@ -76,6 +78,6 @@ def canonical_submitted_files(*, files: Mapping[str, bytes]) -> dict[str, bytes]canonical_path = canonical_resource_path(path=path)if canonical_path in canonical_files:msg = f"Two files submitted with the bundle name the same file '{canonical_path}'."- raise BundleResourcePathError(msg)+ raise BundleResourcePathError(msg).with_error_code(CoreCode.REQUEST_INVALID)canonical_files[canonical_path] = contentreturn canonical_filesdiff --git a/pipelex/core/bundle_resources/exceptions.py b/pipelex/core/bundle_resources/exceptions.pyindex 3895aa245..c03c63e6c 100644--- a/pipelex/core/bundle_resources/exceptions.py+++ b/pipelex/core/bundle_resources/exceptions.py@@ -1,4 +1,7 @@-from pipelex.base_exceptions import ErrorDomain, PipelexError+from mthds.protocol.problem.registry import CoreCode++from pipelex.base_exceptions import PipelexError+from pipelex.errors.error_code_declaration import ErrorCodeSetclass BundleResourcePathError(PipelexError):@@ -8,11 +11,12 @@ class BundleResourcePathError(PipelexError):absolute path, a `..` segment, a backslash, a drive colon and an empty path are refused, and so are two keys namingthe same file, or a key the tree of the submitted files cannot hold, such as one colliding with another oncecase-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.+ The path is the caller's own, so the message is theirs to read, and the same request is refused again. A path that+ cannot name a file inside the bundle is ``security.input_path_refused``; paths that each could but that cannot+ make one tree together choose ``request.invalid``."""- error_domain = ErrorDomain.INPUT- retryable = False+ error_code = ErrorCodeSet(default=CoreCode.SECURITY_INPUT_PATH_REFUSED, others=(CoreCode.REQUEST_INVALID,))_authors_caller_facing_message = True@@ -24,6 +28,5 @@ class BundleResourceNotNamedError(PipelexError):the same request is refused again."""- error_domain = ErrorDomain.INPUT- retryable = False+ error_code = CoreCode.REQUEST_INVALID_authors_caller_facing_message = Truediff --git a/pipelex/core/concepts/concept.py b/pipelex/core/concepts/concept.pyindex 9aabf1dec..c51eccd86 100644--- a/pipelex/core/concepts/concept.py+++ b/pipelex/core/concepts/concept.py@@ -1,6 +1,7 @@from typing import Any, Callablefrom mthds.protocol.concept import ConceptAbstract+from mthds.protocol.problem.registry import CoreCodefrom pydantic import Field, field_validatorfrom pipelex.core.concepts.concept_representation_generator import (@@ -272,7 +273,7 @@ class Concept(ConceptAbstract):return {"concept": self.concept_ref, "content": json_content}, set()case ConceptRepresentationFormat.PYTHON:msg = f"Concept '{self.concept_ref}' declares no structure class, so it has no Python representation"- raise ConceptValueError(msg)+ raise ConceptValueError(msg).with_error_code(CoreCode.REQUEST_UNSUPPORTED)def _render_schema_representation(self,diff --git a/pipelex/core/concepts/concept_factory.py b/pipelex/core/concepts/concept_factory.pyindex a67efa89f..91ff83be2 100644--- a/pipelex/core/concepts/concept_factory.py+++ b/pipelex/core/concepts/concept_factory.py@@ -1,6 +1,7 @@from enum import StrEnumfrom typing import NamedTuple, cast+from mthds.protocol.problem.registry import CoreCodefrom pydantic import BaseModelfrom pipelex import log@@ -8,7 +9,6 @@ from pipelex.core.concepts.concept import Conceptfrom pipelex.core.concepts.concept_blueprint import ConceptBlueprintfrom pipelex.core.concepts.exceptions import (ConceptFactoryError,- ConceptRefineError,ConceptStringError,)from pipelex.core.concepts.helpers import make_qualified_structure_class_name, normalize_structure_blueprint@@ -256,17 +256,17 @@ class ConceptFactory:ref = QualifiedRef.parse_concept_ref(remainder)if ref.domain_path is None:msg = f"Cross-package concept ref '{concept_ref_or_code}' must include a domain"- raise ConceptFactoryError(msg)+ raise ConceptFactoryError(msg).with_error_code(CoreCode.METHOD_SCHEMA_VIOLATION)return DomainAndConceptCode(domain_code=f"{alias}->{ref.domain_path}", concept_code=ref.local_code)if "." not in concept_ref_or_code and not domain_code:msg = f"Not enough information to make a domain and concept code from '{concept_ref_or_code}'"- raise ConceptFactoryError(msg)+ raise ConceptFactoryError(msg).with_error_code(CoreCode.METHOD_SCHEMA_VIOLATION)try:validate_concept_ref_or_code(concept_ref_or_code=concept_ref_or_code)except ConceptStringError as exc:msg = f"Concept string or code '{concept_ref_or_code}' is not a valid concept string or code"- raise ConceptFactoryError(msg) from exc+ raise ConceptFactoryError(msg).with_error_code(CoreCode.METHOD_SCHEMA_VIOLATION) from excif NativeConceptCode.is_native_concept_ref_or_code(concept_ref_or_code=concept_ref_or_code):native_concept_ref = NativeConceptCode.get_validated_native_concept_ref(concept_ref_or_code=concept_ref_or_code)@@ -281,7 +281,7 @@ class ConceptFactory:return DomainAndConceptCode(domain_code=domain_code, concept_code=concept_ref_or_code)else:msg = f"Not enough information to make a domain and concept code from '{concept_ref_or_code}'"- raise ConceptFactoryError(msg)+ raise ConceptFactoryError(msg).with_error_code(CoreCode.METHOD_SCHEMA_VIOLATION)@classmethoddef make_concept_ref_with_domain(cls, *, domain_code: str, concept_code: str) -> str:@@ -348,7 +348,7 @@ class ConceptFactory:structure_class_name = blueprint.structureif not isinstance(structure_class_name, str):msg = f"Expected structure to be a string, got {type(structure_class_name)}"- raise ConceptFactoryError(msg)+ raise ConceptFactoryError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)if not _is_valid_structure_class(structure_class_name=structure_class_name):msg = (f"Structure class '{structure_class_name}' set for concept '{concept_code}' in domain '{domain_code}' "@@ -380,7 +380,7 @@ class ConceptFactory:"""if not isinstance(blueprint.structure, dict):msg = f"Expected structure to be a dict, got {type(blueprint.structure)}"- raise ConceptFactoryError(msg)+ raise ConceptFactoryError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)# Normalize the structure blueprint to ensure all values are ConceptStructureBlueprint objectsnormalized_structure = normalize_structure_blueprint(blueprint.structure)@@ -459,13 +459,9 @@ class ConceptFactory:"""if blueprint.refines is None:msg = "Expected refines to be set"- raise ConceptFactoryError(msg)+ raise ConceptFactoryError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)- try:- current_refine = cls.make_refine(refine=blueprint.refines, domain_code=domain_code)- except ConceptRefineError as exc:- msg = f"Could not validate refine '{blueprint.refines}' for concept '{concept_code}' in domain '{domain_code}': {exc}"- raise ConceptFactoryError(msg) from exc+ current_refine = cls.make_refine(refine=blueprint.refines, domain_code=domain_code)qualified_class_name = make_qualified_structure_class_name(domain_code=domain_code, concept_code=concept_code)@@ -600,7 +596,7 @@ class ConceptFactory:blueprint = cast("ConceptBlueprint", blueprint_or_string_description)if not isinstance(blueprint.structure, dict):msg = f"Expected structure to be a dict, got {type(blueprint.structure)}"- raise ConceptFactoryError(msg)+ raise ConceptFactoryError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)return Concept(domain_code=domain_and_concept_code.domain_code,code=domain_and_concept_code.concept_code,diff --git a/pipelex/core/concepts/exceptions.py b/pipelex/core/concepts/exceptions.pyindex 99e82c0dd..59abb9191 100644--- a/pipelex/core/concepts/exceptions.py+++ b/pipelex/core/concepts/exceptions.py@@ -1,12 +1,23 @@+from typing import ClassVar++from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import PipelexError+from pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeDeclaration, ErrorCodeSetclass ConceptError(PipelexError):- _declared_title = "Concept error"+ error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERROR-class ConceptValueError(ValueError):- pass+class ConceptValueError(PipelexError, ValueError):+ """A concept that breaks a rule of the language, or that cannot be rendered as the caller asked.++ A ``ValueError`` too, since the concept's pydantic validators raise it and pydantic wraps nothing else. The+ rendering of a concept that has no Python representation chooses ``request.unsupported``.+ """++ error_code: ClassVar[ErrorCodeDeclaration] = ErrorCodeSet(default=CoreCode.METHOD_SCHEMA_VIOLATION, others=(CoreCode.REQUEST_UNSUPPORTED,))class ConceptStructureClassNotFoundError(ConceptValueError):@@ -17,25 +28,34 @@ class ConceptStructureClassNotFoundError(ConceptValueError):already convert that error at their own boundary keep working unchanged."""+ error_code = CoreCode.METHOD_CONCEPT_INVALID+class ConceptFactoryError(PipelexError):- pass+ """A concept that cannot be built from its blueprint.+ The default ``method.concept_invalid`` is a structure that cannot be generated or refined; a malformed concept+ ref chooses ``method.schema_violation``, and a type invariant the blueprint guarantees ``runtime.unexpected``.+ """-class ConceptCodeError(ConceptError):- pass+ error_code = ErrorCodeSet(+ default=CoreCode.METHOD_CONCEPT_INVALID,+ others=(CoreCode.METHOD_SCHEMA_VIOLATION, CoreCode.RUNTIME_UNEXPECTED),+ )-class ConceptStringError(ConceptError):- pass+class ConceptCodeError(ConceptError):+ error_code = CoreCode.METHOD_SCHEMA_VIOLATION-class ConceptRefineError(ConceptError):- pass+class ConceptStringError(ConceptError):+ error_code = CoreCode.METHOD_SCHEMA_VIOLATIONclass ConceptLibraryConceptNotFoundError(PipelexError):- pass+ """A concept the library does not hold, named by an input; ``runtime.unexpected`` for a native concept it lacks."""++ error_code = ErrorCodeSet(default=CoreCode.INPUT_WRONG_CONCEPT, others=(CoreCode.RUNTIME_UNEXPECTED,))class ConceptRefAmbiguousError(ConceptError):@@ -47,3 +67,5 @@ class ConceptRefAmbiguousError(ConceptError):definition to the other's data without a word, so the ambiguity is raised instead, namingevery key that matched."""++ error_code = CoreCode.METHOD_REF_AMBIGUOUSdiff --git a/pipelex/core/concepts/helpers.py b/pipelex/core/concepts/helpers.pyindex 0e306c2fc..e8e7254da 100644--- a/pipelex/core/concepts/helpers.py+++ b/pipelex/core/concepts/helpers.py@@ -3,6 +3,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKINGfrom pipelex.core.concepts.concept_structure_blueprint import ConceptStructureBlueprint, ConceptStructureBlueprintFieldType+from pipelex.core.concepts.exceptions import ConceptStringErrorfrom pipelex.core.concepts.validation import is_concept_ref_or_code_validfrom pipelex.core.qualified_ref import QualifiedRef@@ -30,11 +31,11 @@ def get_structure_class_name_from_blueprint(The structure class name to useRaises:- ValueError: If concept_ref_or_code is not a valid concept reference or code+ ConceptStringError: If concept_ref_or_code is not a valid concept reference or code"""if not is_concept_ref_or_code_valid(concept_ref_or_code):msg = f"Invalid concept_ref_or_code: '{concept_ref_or_code}'"- raise ValueError(msg)+ raise ConceptStringError(msg)# Extract concept_code from concept_ref_or_coderef = QualifiedRef.parse_stripping_cross_package(concept_ref_or_code)@@ -120,10 +121,13 @@ def extract_concept_code_from_concept_ref_or_code(concept_ref_or_code: str) -> sReturns:The concept code++ Raises:+ ConceptStringError: If concept_ref_or_code is not a valid concept reference or code"""if not is_concept_ref_or_code_valid(concept_ref_or_code):msg = f"Invalid concept_ref_or_code: '{concept_ref_or_code}' for extracting concept code"- raise ValueError(msg)+ raise ConceptStringError(msg)ref = QualifiedRef.parse_stripping_cross_package(concept_ref_or_code)return ref.local_codediff --git a/pipelex/core/concepts/native/exceptions.py b/pipelex/core/concepts/native/exceptions.pyindex 4d7fe146f..622e19bf9 100644--- a/pipelex/core/concepts/native/exceptions.py+++ b/pipelex/core/concepts/native/exceptions.py@@ -1,5 +1,9 @@+from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import PipelexErrorclass NativeConceptDefinitionError(PipelexError):- pass+ """A native concept asked for a definition it lacks: every caller checks nativeness first, so it is an invariant."""++ error_code = CoreCode.RUNTIME_UNEXPECTEDdiff --git a/pipelex/core/concepts/structure_generation/exceptions.py b/pipelex/core/concepts/structure_generation/exceptions.pyindex 57d9b16e5..67d698e5c 100644--- a/pipelex/core/concepts/structure_generation/exceptions.py+++ b/pipelex/core/concepts/structure_generation/exceptions.py@@ -1,7 +1,8 @@+from mthds.protocol.problem.registry import CoreCodefrom pydantic import BaseModelfrom pipelex.base_exceptions import PipelexError-from pipelex.core.concepts.exceptions import ConceptFactoryError+from pipelex.errors.error_code_declaration import ErrorCodeSetclass SyntaxErrorData(BaseModel):@@ -24,11 +25,11 @@ class SyntaxErrorData(BaseModel):)-class StructureClassError(ConceptFactoryError):- pass+class ConceptStructureGeneratorError(PipelexError):+ """A concept structure whose Python class cannot be generated; ``runtime.unexpected`` for an invariant of the generator."""+ error_code = ErrorCodeSet(default=CoreCode.METHOD_CONCEPT_INVALID, others=(CoreCode.RUNTIME_UNEXPECTED,))-class ConceptStructureGeneratorError(PipelexError):def __init__(self, message: str, structure_class_python_code: str | None = None, syntax_error_data: SyntaxErrorData | None = None):self.structure_class_python_code = structure_class_python_codeself.syntax_error_data = syntax_error_data@@ -36,4 +37,6 @@ class ConceptStructureGeneratorError(PipelexError):class ConceptStructureValidationError(PipelexError):- pass+ """A generated structure class that does not hold, such as one naming a base class that is not registered."""++ error_code = CoreCode.METHOD_CONCEPT_INVALIDdiff --git a/pipelex/core/concepts/structure_generation/generator.py b/pipelex/core/concepts/structure_generation/generator.pyindex edcca4ccf..fb791e6b9 100644--- a/pipelex/core/concepts/structure_generation/generator.py+++ b/pipelex/core/concepts/structure_generation/generator.py@@ -4,6 +4,7 @@ from datetime import date, datetime, timefrom enum import Enumfrom typing import Any, Literal, cast+from mthds.protocol.problem.registry import CoreCodefrom pydantic import Fieldfrom pipelex.core.concepts.concept_structure_blueprint import ConceptStructureBlueprint@@ -106,7 +107,8 @@ class StructureGenerator:raise ConceptStructureGeneratorError(msg, structure_class_python_code=generated_code, syntax_error_data=syntax_error_data) from syntax_error- except (ConceptStructureValidationError, ValueError, ImportError, Exception) as exc:+ except Exception as exc:+ # Unbounded code (case 2): the generated module is executed, so its exception surface cannot be enumerated.msg = f"Error validating generated code: {exc}\nGenerated code:\n```python\n{generated_code}\n```"raise ConceptStructureGeneratorError(msg, structure_class_python_code=generated_code) from exc@@ -270,7 +272,7 @@ class StructureGenerator:cls = NativeConceptCode.get_native_structure_class(base_class)if not cls:msg = f"Native structure class '{base_class}' not found"- raise ConceptStructureGeneratorError(msg)+ raise ConceptStructureGeneratorError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)self.imports.add(f"from {cls.__module__} import {cls.__name__}")elif base_class != "StructuredContent":# Cross-package refines: base class lives in another already-installed package — recover its module via the class registry.@@ -329,7 +331,7 @@ class StructureGenerator:f"Field '{resolved_field.name}' is required AND carries default_value {default_value!r} — "f"the blueprint validator rejects this pair, so reaching the generator with it is a bug.")- raise ConceptStructureGeneratorError(msg)+ raise ConceptStructureGeneratorError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)field_params.insert(0, "...")elif default_value is not None:field_params.insert(0, f"default={self._format_default_value(default_value)}")diff --git a/pipelex/core/concepts/validation.py b/pipelex/core/concepts/validation.pyindex 7301eca71..61e56be06 100644--- a/pipelex/core/concepts/validation.py+++ b/pipelex/core/concepts/validation.py@@ -1,5 +1,6 @@from pipelex.core.concepts.exceptions import ConceptCodeError, ConceptStringError-from pipelex.core.qualified_ref import QualifiedRef, QualifiedRefError+from pipelex.core.qualified_ref import QualifiedRef+from pipelex.core.qualified_ref_exceptions import QualifiedRefErrorfrom pipelex.tools.misc.string_utils import is_pascal_casediff --git a/pipelex/core/domains/exceptions.py b/pipelex/core/domains/exceptions.pyindex b6daaf5c1..3fc57d41b 100644--- a/pipelex/core/domains/exceptions.py+++ b/pipelex/core/domains/exceptions.py@@ -1,9 +1,13 @@+from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import PipelexErrorclass DomainCodeError(PipelexError):- pass+ error_code = CoreCode.METHOD_SCHEMA_VIOLATIONclass DomainFactoryError(PipelexError):- pass+ """A domain the factory refuses after its blueprint passed the same validation, so an invariant."""++ error_code = CoreCode.RUNTIME_UNEXPECTEDdiff --git a/pipelex/core/memory/exceptions.py b/pipelex/core/memory/exceptions.pyindex 7f3da87ed..a27d6fea6 100644--- a/pipelex/core/memory/exceptions.py+++ b/pipelex/core/memory/exceptions.py@@ -1,36 +1,47 @@-from pipelex.base_exceptions import ErrorDomain, PipelexError+from typing import ClassVar++from mthds.protocol.problem.registry import CoreCode++from pipelex.base_exceptions import PipelexErrorfrom pipelex.cogt.inference.error_classification import UserAction, UserActionKind+from pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeDeclaration, ErrorCodeSetfrom pipelex.tools.misc.exceptions import ContextProviderErrorclass WorkingMemoryFactoryError(PipelexError):- pass+ error_code = CoreCode.RUNTIME_UNEXPECTEDclass WorkingMemoryError(PipelexError):- pass+ error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERRORclass WorkingMemoryConsistencyError(WorkingMemoryError):- pass+ error_code = CoreCode.RUNTIME_UNEXPECTEDclass WorkingMemoryVariableError(WorkingMemoryError, ContextProviderError):- pass+ error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERRORclass WorkingMemoryTypeError(WorkingMemoryVariableError):- pass+ """The method reads a variable as a type it does not hold; ``input.invalid`` for an empty list where an item is read."""++ error_code = ErrorCodeSet(default=CoreCode.METHOD_WIRING_INVALID, others=(CoreCode.INPUT_INVALID,))class WorkingMemoryStuffAttributeNotFoundError(WorkingMemoryVariableError):- pass+ """The method reads an attribute a variable does not have; ``method.template_private_name`` for a private one."""++ error_code = ErrorCodeSet(default=CoreCode.METHOD_WIRING_INVALID, others=(CoreCode.METHOD_TEMPLATE_PRIVATE_NAME,))class WorkingMemoryStuffNotFoundError(WorkingMemoryVariableError):# Not classified as the caller's fault: a step that names a variable nothing produces, a batch# over one included, is refused when the bundle loads, so a miss at run time is the runtime's own# bookkeeping going wrong, not a mistake in the caller's method.+ error_code = CoreCode.RUNTIME_UNEXPECTED+def __init__(self, message: str, variable_name: str, pipe_code: str | None = None, concept_code: str | None = None):super().__init__(message, variable_name)self.pipe_code = pipe_code@@ -42,14 +53,14 @@ class InputShapingError(PipelexError):Every subclass describes a fault in the *caller's own* provided inputs — the input name,the declared concept, what was provided, and the expected shape rendered from the pipe's- signature. ``error_domain = INPUT`` (the caller can fix it) and ``_authors_caller_facing_message``+ signature. Each subclass carries an ``input.`` code (the caller can fix it), and ``_authors_caller_facing_message``(the copy names only the caller's inputs and method, so it survives STRICT disclosure).Each subclass sets a per-instance ``user_action`` (advice tailored to the specific failure)rather than a class-level one, because the actionable fix differs per failure mode."""- error_domain = ErrorDomain.INPUT+ error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERROR_authors_caller_facing_message = Truedef __init__(self, message: str, *, variable_name: str, user_action: UserAction | None = None):@@ -66,6 +77,8 @@ class WrongScalarKindError(InputShapingError):is attempted — JSON already distinguishes scalars — so the mismatch is a hard error."""+ error_code = CoreCode.INPUT_INVALID+@classmethoddef make(cls,@@ -87,6 +100,8 @@ class WrongScalarKindError(InputShapingError):class ListWhereSingularError(InputShapingError):"""A list was provided where the signature declares a single value (D2)."""+ error_code = CoreCode.INPUT_WRONG_MULTIPLICITY+@classmethoddef make(cls,@@ -110,6 +125,8 @@ class ListWhereSingularError(InputShapingError):class MultiplicityCountMismatchError(InputShapingError):"""A fixed-count list input received the wrong number of items (D2)."""+ error_code = CoreCode.INPUT_WRONG_MULTIPLICITY+@classmethoddef make(cls,@@ -145,6 +162,8 @@ class StructureValidationError(InputShapingError):The last three are fixed in the value, sent in the expected shape."""+ error_code = ErrorCodeSet(default=CoreCode.INPUT_INVALID, others=(CoreCode.INPUT_WRONG_CONCEPT,))+@classmethoddef make(cls,@@ -273,7 +292,7 @@ class StructureValidationError(InputShapingError):kind=UserActionKind.CHANGE_INPUT,detail=f"Send input '{variable_name}' in the expected shape, which names its concept and spells out its content.",)- return cls(message, variable_name=variable_name, user_action=user_action)+ return cls(message, variable_name=variable_name, user_action=user_action).with_error_code(CoreCode.INPUT_WRONG_CONCEPT)class ExplicitConceptIncompatibleError(InputShapingError):@@ -283,6 +302,8 @@ class ExplicitConceptIncompatibleError(InputShapingError):is now checked: ``C`` must be compatible with — refine or equal — the declared concept."""+ error_code = CoreCode.INPUT_WRONG_CONCEPT+@classmethoddef make(cls,@@ -310,6 +331,8 @@ class UnknownInputNameError(InputShapingError):the declared names, instead of silently carrying an input that is never read."""+ error_code = CoreCode.INPUT_UNEXPECTED+@classmethoddef make(cls, *, variable_name: str, declared_names: list[str]) -> "UnknownInputNameError":declared_display = ", ".join(f"'{name}'" for name in declared_names) if declared_names else "(none)"@@ -328,6 +351,8 @@ class NullInputError(InputShapingError):null is a hard error rather than a silently-dropped or mis-shaped input."""+ error_code = CoreCode.INPUT_INVALID+@classmethoddef make(cls, *, variable_name: str, declared_concept_ref: str, expected_shape: str) -> "NullInputError":message = (diff --git a/pipelex/core/memory/working_memory.py b/pipelex/core/memory/working_memory.pyindex f7b86a4c1..9649b34c7 100644--- a/pipelex/core/memory/working_memory.py+++ b/pipelex/core/memory/working_memory.py@@ -1,6 +1,7 @@from operator import attrgetterfrom typing import Any, Self, cast+from mthds.protocol.problem.registry import CoreCodefrom mthds.protocol.working_memory import WorkingMemoryAbstractfrom pydantic import Field, model_validatorfrom typing_extensions import override@@ -345,7 +346,7 @@ class WorkingMemory(WorkingMemoryAbstract[Stuff], ContextProviderAbstract):raise WorkingMemoryStuffAttributeNotFoundError(variable_name=name,message=f"Attribute path '{name}' reads '{private_segment}', which starts with an underscore: a path reads public fields only",- )+ ).with_error_code(CoreCode.METHOD_TEMPLATE_PRIVATE_NAME)parts = name.split(".", 1) # Split only at the first dotbase_name = parts[0]attr_path_str = parts[1] # Keep the rest as a dot-separated string@@ -426,7 +427,7 @@ class WorkingMemory(WorkingMemoryAbstract[Stuff], ContextProviderAbstract):raise WorkingMemoryTypeError(variable_name=name,message=f"Content of '{name}' is ListContent, but it is empty",- )+ ).with_error_code(CoreCode.INPUT_INVALID)return top_level_content_itemsif wanted_type is not None and not isinstance(top_level_content, wanted_type):diff --git a/pipelex/core/method_trees/exceptions.py b/pipelex/core/method_trees/exceptions.pyindex c70c11e09..a47e8a9f1 100644--- a/pipelex/core/method_trees/exceptions.py+++ b/pipelex/core/method_trees/exceptions.py@@ -1,8 +1,23 @@-from pipelex.base_exceptions import ErrorDomain, PipelexError+from typing import ClassVar++from mthds.protocol.problem.registry import CoreCode++from pipelex.base_exceptions import PipelexError+from pipelex.errors.error_code_declaration import ErrorCodeDeclaration, ErrorCodeSetclass TreePythonError(PipelexError):- """A method tree's Python cannot be imported in this process."""+ """A method tree's Python cannot be imported in this process.++ The default ``runtime.unexpected`` is an invariant of the import hold; a raise site chooses ``request.unsupported``+ for a tree handed over in a form that holds no directory of Python, and ``method.name_conflict`` for a module of the+ tree that a module of the same name imported earlier hides.+ """++ error_code: ClassVar[ErrorCodeDeclaration] = ErrorCodeSet(+ default=CoreCode.RUNTIME_UNEXPECTED,+ others=(CoreCode.REQUEST_UNSUPPORTED, CoreCode.METHOD_NAME_CONFLICT),+ )class TreePythonHeldError(TreePythonError):@@ -10,9 +25,12 @@ class TreePythonHeldError(TreePythonError):A process imports one tree's Python at a time: the tree root goes first on `sys.path` and its modules keep theirreal names, so two trees defining the same module could not share the process, and evicting the earlier tree's- modules would pull them from under its run. The message names both trees.+ modules would pull them from under its run. The message names both trees, and the same run succeeds once the run+ in flight ends."""+ error_code = CoreCode.RUNTIME_UNAVAILABLE+class TreeModuleShadowingError(TreePythonError):"""A top-level module of a method tree shares its name with a standard-library module or a module importable outside the tree.@@ -22,8 +40,7 @@ class TreeModuleShadowingError(TreePythonError):would shadow; it describes the caller's own method, so it is kept under STRICT disclosure."""- error_domain = ErrorDomain.INPUT- retryable = False+ error_code = CoreCode.METHOD_NAME_CONFLICT_authors_caller_facing_message = True@@ -45,5 +62,8 @@ class MethodFileUnavailableError(PipelexError):The store does not hold it, such as a tree the process that assembled the run never handed over, or the bytes itholds 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.+ message names the tree by its digest and the file by its tree path, never by a path of this host. A tree that names+ no file at the path a method refers to chooses ``method.resource_missing``; the rest is the store failing this run."""++ error_code = ErrorCodeSet(default=CoreCode.RUNTIME_UNEXPECTED, others=(CoreCode.METHOD_RESOURCE_MISSING,))diff --git a/pipelex/core/method_trees/method_files.py b/pipelex/core/method_trees/method_files.pyindex 98639bb50..14ae9e521 100644--- a/pipelex/core/method_trees/method_files.py+++ b/pipelex/core/method_trees/method_files.py@@ -11,6 +11,7 @@ from collections.abc import Callable, Iterablefrom mthds.method_tree.digest import DIGEST_PREFIX, is_sha256_hex, sha256_hexfrom mthds.method_tree.tree_path import tree_path_violation+from mthds.protocol.problem.registry import CoreCodefrom pydantic import BaseModel, ConfigDictfrom pipelex.core.method_trees.exceptions import MethodFileUnavailableError@@ -84,7 +85,7 @@ async def read_listed_file(*, listing: TreeListing, tree_path: str, read_scope: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)+ raise MethodFileUnavailableError(msg).with_error_code(CoreCode.METHOD_RESOURCE_MISSING)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."diff --git a/pipelex/core/method_trees/tree_python.py b/pipelex/core/method_trees/tree_python.pyindex f1e4a60e8..63d7c11ab 100644--- a/pipelex/core/method_trees/tree_python.py+++ b/pipelex/core/method_trees/tree_python.py@@ -42,6 +42,7 @@ from typing import NamedTuple, castfrom mthds.method_tree.models import MethodTreefrom mthds.method_tree.tree_path import nfc+from mthds.protocol.problem.registry import CoreCodefrom typing_extensions import Buffer, overridefrom pipelex import log@@ -94,13 +95,13 @@ def tree_python_identity(*, tree: MethodTree, label: str) -> TreePythonIdentity:"""if tree.directory is None:msg = "The method tree was read from a map of file entries and has no directory on this host, so its Python cannot be imported here."- raise TreePythonError(msg)+ raise TreePythonError(msg).with_error_code(CoreCode.REQUEST_UNSUPPORTED)if tree.is_one_file:msg = (f"The bundle {tree.entry or ''} was read alone, as a one-file tree, which holds no Python: hand over the method's folder, ""whose tree holds the bundle and its Python.")- raise TreePythonError(msg)+ raise TreePythonError(msg).with_error_code(CoreCode.REQUEST_UNSUPPORTED)return TreePythonIdentity(root=tree.directory.resolve(), digest=tree.digest, label=label)@@ -577,5 +578,5 @@ def import_held_tree_module(*, identity: TreePythonIdentity, module_name: str) -f"The module '{module_name}' resolved outside {identity.describe()}: a module of that name was imported in this ""process before the tree's Python loaded.")- raise TreePythonError(msg)+ raise TreePythonError(msg).with_error_code(CoreCode.METHOD_NAME_CONFLICT)return modulediff --git a/pipelex/core/pipes/exceptions.py b/pipelex/core/pipes/exceptions.pyindex ddb1e0db3..624f0591b 100644--- a/pipelex/core/pipes/exceptions.py+++ b/pipelex/core/pipes/exceptions.py@@ -1,6 +1,12 @@-from pipelex.base_exceptions import ErrorDomain, PipelexError+from typing import ClassVar++from mthds.protocol.problem.registry import CoreCode++from pipelex.base_exceptions import PipelexErrorfrom pipelex.cogt.exceptions import ModelChoiceNotFoundErrorfrom pipelex.cogt.model_backends.model_type import ModelType+from pipelex.errors.error_code_declaration import ErrorCodeDeclaration, ErrorCodeSet, InheritsCause+from pipelex.errors.error_codes import ErrorCodefrom pipelex.system.pipe_run_mode import PipeRunModefrom pipelex.validation_error_types import PipeFactoryErrorType, PipeValidationErrorType@@ -17,8 +23,17 @@ class PipeFactoryError(PipelexError):domain: The domain of the pipemissing_concept_code: The concept code that is missing (for MISSING_OUTPUT_CONCEPT errors)declared_concepts: List of concepts declared in the domain++ An unknown concept carries ``method.concept_unresolved``; any other factory refusal carries the residual+ ``method.schema_violation`` unless its raise site chooses a code, such as ``runtime.unexpected`` for a pipe+ type whose factory pipelex failed to register."""+ error_code = ErrorCodeSet(+ default=CoreCode.METHOD_SCHEMA_VIOLATION,+ others=(CoreCode.METHOD_CONCEPT_UNRESOLVED, CoreCode.RUNTIME_UNEXPECTED),+ )+def __init__(self,message: str,@@ -34,10 +49,20 @@ class PipeFactoryError(PipelexError):self.missing_concept_code = missing_concept_codeself.declared_concepts = declared_concepts or []super().__init__(message)+ match error_type:+ case PipeFactoryErrorType.UNKNOWN_CONCEPT:+ self.with_error_code(CoreCode.METHOD_CONCEPT_UNRESOLVED)+ case PipeFactoryErrorType.UNKNOWN_FACTORY_ERROR:+ pass-class PipeVariableMultiplicityError(ValueError):- pass+class PipeVariableMultiplicityError(PipelexError, ValueError):+ """A concept spec whose multiplicity or presence marker does not parse.++ A ``ValueError`` too, since pydantic validators raise it and pydantic wraps nothing else.+ """++ error_code = CoreCode.METHOD_SCHEMA_VIOLATIONclass PipeRunError(PipelexError):@@ -47,8 +72,28 @@ class PipeRunError(PipelexError):the kernel layer subclasses it: `PipeRunInputsError` and `OptionalValueAbsentError` in`core.pipes.inputs.exceptions` derive from it, so filing the base with the machinery put amodule of `pipe_run` — and its whole import chain — inside every kernel import closure.++ A wrapper of an inference or a sub-pipe failure takes its cause's code; a raise site that finds the fault+ itself chooses it among the codes below."""+ error_code: ClassVar[ErrorCodeDeclaration] = InheritsCause(+ fallback=CoreCode.RUNTIME_UNEXPECTED,+ others=(+ CoreCode.MODEL_OUTPUT_SCHEMA_MISMATCH,+ CoreCode.PIPE_CONDITION_UNMATCHED,+ CoreCode.PIPE_CONDITION_REFUSED,+ CoreCode.PIPE_INPUT_UNRESOLVED,+ CoreCode.METHOD_FUNCTION_INVALID,+ CoreCode.METHOD_TEMPLATE_INVALID,+ CoreCode.METHOD_PIPE_UNRESOLVED,+ CoreCode.METHOD_SCHEMA_VIOLATION,+ CoreCode.METHOD_WIRING_INVALID,+ CoreCode.METHOD_NAME_CONFLICT,+ CoreCode.METHOD_OPTIONAL_UNHANDLED,+ ),+ )+def __init__(self, message: str, run_mode: PipeRunMode, pipe_code: str):self.run_mode = run_modeself.pipe_code = pipe_code@@ -70,9 +115,13 @@ class PipeOperatorModelChoiceError(PipelexError):The message names the pipe and the field, then keeps the deck check's sentence and its suggestions,so it is caller-facing copy: it names only the caller's own model reference and the deck's publichandles, and it must reach a hosted caller under STRICT disclosure.++ It takes the code of the deck check's refusal it locates: ``model.unknown`` for a reference the deck+ does not define, ``model.capability_unsupported`` for a bare handle the deck serves only as another+ model type, and ``model.unknown`` when it has no such cause."""- error_domain = ErrorDomain.INPUT+ error_code = InheritsCause(fallback=CoreCode.MODEL_UNKNOWN)_authors_caller_facing_message = Truedef __init__(@@ -138,10 +187,10 @@ class PipeLoadRefusalError(PipelexError):Its message is built only from caller-facing material, the caller's own pipe code and either therefusal's message, when that message is caller-facing, or the refusal's title, so it is kept under- STRICT disclosure.+ STRICT disclosure. It takes the code of the refusal it wraps."""- error_domain = ErrorDomain.INPUT+ error_code = InheritsCause(fallback=CoreCode.METHOD_SCHEMA_VIOLATION)_authors_caller_facing_message = Truedef __init__(self, message: str, *, pipe_code: str, domain_code: str, source: str | None):@@ -170,7 +219,100 @@ def caller_facing_refusal_text(*, refusal: PipelexError) -> str:return report.title-class PipeValidationError(ValueError):+def pipe_validation_error_code(*, error_type: PipeValidationErrorType | None) -> ErrorCode:+ """The code of a pipe validation refusal of a type, ``method.schema_violation`` for one with no type."""+ match error_type:+ case PipeValidationErrorType.MISSING_INPUT_VARIABLE:+ return CoreCode.METHOD_INPUT_UNDECLARED+ case PipeValidationErrorType.EXTRANEOUS_INPUT_VARIABLE:+ return CoreCode.METHOD_INPUT_UNUSED+ case PipeValidationErrorType.INPUT_STUFF_SPEC_MISMATCH:+ return CoreCode.METHOD_INPUT_CONCEPT_MISMATCH+ case PipeValidationErrorType.INADEQUATE_OUTPUT_CONCEPT | PipeValidationErrorType.LLM_OUTPUT_CANNOT_BE_IMAGE:+ return CoreCode.METHOD_OUTPUT_CONCEPT_MISMATCH+ case PipeValidationErrorType.INADEQUATE_OUTPUT_MULTIPLICITY:+ return CoreCode.METHOD_OUTPUT_MULTIPLICITY_MISMATCH+ case PipeValidationErrorType.LLM_SETTING_REFUSED_BY_MODEL:+ return CoreCode.MODEL_CAPABILITY_UNSUPPORTED+ case PipeValidationErrorType.INVALID_PIPE_CODE_SYNTAX | PipeValidationErrorType.INVALID_INPUT_NAME:+ return CoreCode.METHOD_IDENTIFIER_INVALID+ case PipeValidationErrorType.UNKNOWN_PIPE_TYPE | PipeValidationErrorType.MISSING_PIPE_TYPE:+ return CoreCode.METHOD_PIPE_TYPE_INVALID+ case PipeValidationErrorType.BATCH_ITEM_NAME_COLLISION | PipeValidationErrorType.NATIVE_CONCEPT_REDECLARATION:+ return CoreCode.METHOD_NAME_CONFLICT+ case PipeValidationErrorType.BINDING_STEP_INVALID:+ return CoreCode.METHOD_BINDING_STEP_INVALID+ case PipeValidationErrorType.BINDING_PATH_UNRESOLVED:+ return CoreCode.METHOD_FIELD_PATH_UNRESOLVED+ case PipeValidationErrorType.OPTIONAL_MARKER_INVALID:+ return CoreCode.METHOD_OPTIONAL_MARKER_INVALID+ case (+ PipeValidationErrorType.OPTIONAL_NOT_HANDLED+ | PipeValidationErrorType.OPTIONAL_OUTPUT_REQUIRED+ | PipeValidationErrorType.OPTIONAL_INPUT_UNGUARDED+ | PipeValidationErrorType.OPTIONAL_BRANCH_REQUIRED_FIELD+ ):+ return CoreCode.METHOD_OPTIONAL_UNHANDLED+ case PipeValidationErrorType.TEMPLATE_PRIVATE_NAME:+ return CoreCode.METHOD_TEMPLATE_PRIVATE_NAME+ case PipeValidationErrorType.OPTIONAL_FORCE_REDUNDANT:+ return CoreCode.METHOD_OPTIONAL_FORCE_REDUNDANT+ case PipeValidationErrorType.INPUT_PRESENCE_VACUOUS:+ return CoreCode.METHOD_INPUT_PRESENCE_VACUOUS+ case PipeValidationErrorType.UNRESOLVED_CONCEPT:+ return CoreCode.METHOD_CONCEPT_UNRESOLVED+ case PipeValidationErrorType.UNRESOLVED_PIPE_DEPENDENCY:+ return CoreCode.METHOD_PIPE_UNRESOLVED+ case PipeValidationErrorType.UNRESOLVED_PACKAGE_DEPENDENCY:+ return CoreCode.METHOD_DEPENDENCY_MISSING+ case PipeValidationErrorType.UNEXPORTED_PIPE_DEPENDENCY:+ return CoreCode.METHOD_PIPE_NOT_EXPORTED+ case PipeValidationErrorType.UNKNOWN_MODEL:+ return CoreCode.MODEL_UNKNOWN+ case PipeValidationErrorType.PIPE_FUNC_FUNCTION_REFUSED:+ return CoreCode.METHOD_FUNCTION_INVALID+ case PipeValidationErrorType.UNKNOWN_VALIDATION_ERROR | None:+ return CoreCode.METHOD_SCHEMA_VIOLATION+++class PipeValidationError(PipelexError, ValueError):+ """A pipe that breaks a rule of the language or of its pipe type, found when the bundle is validated.++ Its code follows its ``error_type`` (:func:`pipe_validation_error_code`), and a raise site whose refusal the+ type does not name chooses one of the codes the class declares. A ``ValueError`` too, since the blueprint+ validators raise it and pydantic wraps nothing else.+ """++ error_code = ErrorCodeSet(+ default=CoreCode.METHOD_SCHEMA_VIOLATION,+ others=(+ CoreCode.METHOD_INPUT_UNDECLARED,+ CoreCode.METHOD_INPUT_UNUSED,+ CoreCode.METHOD_INPUT_CONCEPT_MISMATCH,+ CoreCode.METHOD_OUTPUT_CONCEPT_MISMATCH,+ CoreCode.METHOD_OUTPUT_MULTIPLICITY_MISMATCH,+ CoreCode.METHOD_IDENTIFIER_INVALID,+ CoreCode.METHOD_PIPE_TYPE_INVALID,+ CoreCode.METHOD_NAME_CONFLICT,+ CoreCode.METHOD_BINDING_STEP_INVALID,+ CoreCode.METHOD_FIELD_PATH_UNRESOLVED,+ CoreCode.METHOD_OPTIONAL_MARKER_INVALID,+ CoreCode.METHOD_OPTIONAL_UNHANDLED,+ CoreCode.METHOD_TEMPLATE_PRIVATE_NAME,+ CoreCode.METHOD_OPTIONAL_FORCE_REDUNDANT,+ CoreCode.METHOD_INPUT_PRESENCE_VACUOUS,+ CoreCode.METHOD_CONCEPT_UNRESOLVED,+ CoreCode.METHOD_PIPE_UNRESOLVED,+ CoreCode.METHOD_DEPENDENCY_MISSING,+ CoreCode.METHOD_PIPE_NOT_EXPORTED,+ CoreCode.METHOD_FUNCTION_INVALID,+ CoreCode.METHOD_WIRING_INVALID,+ CoreCode.MODEL_UNKNOWN,+ CoreCode.MODEL_CAPABILITY_UNSUPPORTED,+ CoreCode.RUNTIME_UNEXPECTED,+ ),+ )+def __init__(self,message: str,@@ -228,6 +370,7 @@ class PipeValidationError(ValueError):self.file_path = file_pathself.explanation = explanationsuper().__init__(message)+ self.with_error_code(pipe_validation_error_code(error_type=error_type))def desc(self) -> str:msg = f"{self.error_type} • domain_code='{self.domain_code}'"diff --git a/pipelex/core/pipes/inputs/exceptions.py b/pipelex/core/pipes/inputs/exceptions.pyindex 17c5ca44f..babee76d4 100644--- a/pipelex/core/pipes/inputs/exceptions.py+++ b/pipelex/core/pipes/inputs/exceptions.py@@ -1,37 +1,44 @@-from pipelex.base_exceptions import ErrorDomain, PipelexError+from typing import ClassVar++from mthds.protocol.problem.registry import CoreCode++from pipelex.base_exceptions import PipelexErrorfrom pipelex.cogt.inference.error_classification import UserAction, UserActionKindfrom pipelex.core.memory.absence import AbsenceRecordfrom pipelex.core.pipes.exceptions import PipeRunError+from pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeDeclaration, ErrorCodeSetfrom pipelex.system.pipe_run_mode import PipeRunModeclass InputStuffSpecsError(PipelexError):- pass+ error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERRORclass InputStuffSpecsFactoryError(InputStuffSpecsError):- pass+ """An input's concept spec that does not parse, which the blueprint validators refuse first in practice."""+ error_code = CoreCode.METHOD_SCHEMA_VIOLATION-class InputStuffSpecNotFoundError(InputStuffSpecsError):- pass+class InputStuffSpecNotFoundError(InputStuffSpecsError):+ """A pipe's inputs lack a variable its wiring names."""-class PipeInputError(PipelexError):- def __init__(- self,- message: str,- pipe_code: str,- variable_name: str | None = None,- concept_code: str | None = None,- ):- self.pipe_code = pipe_code- self.variable_name = variable_name- self.concept_code = concept_code- super().__init__(message)+ error_code = CoreCode.METHOD_WIRING_INVALIDclass PipeRunInputsError(PipeRunError):+ """A pipe's input cannot be found when it runs.++ Its raise site chooses the code: ``input.missing`` for an input the run's caller did not send,+ ``input.reference_not_found`` for an input whose resource does not resolve, ``method.wiring_invalid`` for a+ wiring that names no input, and the default ``pipe.input_unresolved`` for a value no earlier step produced.+ """++ error_code = ErrorCodeSet(+ default=CoreCode.PIPE_INPUT_UNRESOLVED,+ others=(CoreCode.INPUT_MISSING, CoreCode.INPUT_REFERENCE_NOT_FOUND, CoreCode.METHOD_WIRING_INVALID),+ )+def __init__(self,message: str,@@ -54,7 +61,7 @@ class OptionalValueAbsentError(PipeRunError):variable name, the consuming pipe, and the full provenance chain from the absence ledger,so the report can say where the absence entered the flow and why.- ``error_domain = RUNTIME``: the failure is data-dependent — the method's assumption failed+ ``pipe.forced_input_absent``: the failure is data-dependent — the method's assumption failedon this input data, not on the caller's request shape.``_authors_caller_facing_message``: the message and user action describe the caller's own@@ -62,7 +69,7 @@ class OptionalValueAbsentError(PipeRunError):caller is the only one who can act on them; they must survive STRICT disclosure."""- error_domain = ErrorDomain.RUNTIME+ error_code = CoreCode.PIPE_FORCED_INPUT_ABSENT_authors_caller_facing_message = Truedef __init__(@@ -117,5 +124,11 @@ class OptionalValueAbsentError(PipeRunError):)-class NoInputsRequiredError(Exception):- """Raised when a pipe has no inputs."""+class NoInputsRequiredError(PipelexError):+ """Raised when a pipe has no inputs.++ A signal rather than an error: every caller answers it with an empty template or a notice. It carries+ ``request.unsupported`` until it becomes a return value.+ """++ error_code = CoreCode.REQUEST_UNSUPPORTEDdiff --git a/pipelex/core/pipes/stuff_spec/exceptions.py b/pipelex/core/pipes/stuff_spec/exceptions.pyindex 46bc632d8..ff7c04daa 100644--- a/pipelex/core/pipes/stuff_spec/exceptions.py+++ b/pipelex/core/pipes/stuff_spec/exceptions.py@@ -1,16 +1,9 @@-from pipelex.base_exceptions import PipelexError---class StuffSpecError(PipelexError):- def __init__(self, message: str, pipe_code: str, missing_inputs: dict[str, str]):- self.pipe_code = pipe_code- self.missing_inputs = missing_inputs- super().__init__(message)+from mthds.protocol.problem.registry import CoreCode--class PipeInputsFactoryError(PipelexError):- pass+from pipelex.base_exceptions import PipelexErrorclass StuffSpecFactoryError(PipelexError):- pass+ """An output concept spec that does not parse, or names a concept that does not resolve."""++ error_code = CoreCode.METHOD_SCHEMA_VIOLATIONdiff --git a/pipelex/core/qualified_ref.py b/pipelex/core/qualified_ref.pyindex 729f7a08c..603587485 100644--- a/pipelex/core/qualified_ref.py+++ b/pipelex/core/qualified_ref.py@@ -2,13 +2,10 @@ from typing import NamedTuplefrom pydantic import BaseModel, ConfigDict+from pipelex.core.qualified_ref_exceptions import QualifiedRefErrorfrom pipelex.tools.misc.string_utils import is_pascal_case, is_snake_case-class QualifiedRefError(ValueError):- """Raised when a qualified reference string is invalid."""--class CrossPackageRef(NamedTuple):alias: strremainder: strdiff --git a/pipelex/core/qualified_ref_exceptions.py b/pipelex/core/qualified_ref_exceptions.pynew file mode 100644index 000000000..4f901bbdf--- /dev/null+++ b/pipelex/core/qualified_ref_exceptions.py@@ -0,0 +1,12 @@+from mthds.protocol.problem.registry import CoreCode++from pipelex.base_exceptions import PipelexError+++class QualifiedRefError(PipelexError, ValueError):+ """Raised when a qualified reference string is invalid.++ A ``ValueError`` too, since the guards that parse a reference inside pydantic validators catch it as one.+ """++ error_code = CoreCode.METHOD_SCHEMA_VIOLATIONdiff --git a/pipelex/core/stuffs/exceptions.py b/pipelex/core/stuffs/exceptions.pyindex 41a4a7132..00b8a5986 100644--- a/pipelex/core/stuffs/exceptions.py+++ b/pipelex/core/stuffs/exceptions.py@@ -1,27 +1,40 @@+from typing import ClassVar++from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import PipelexError+from pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeDeclaration, ErrorCodeSetclass StuffError(PipelexError):- _declared_title = "Stuff error"+ error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERRORclass StuffFactoryError(StuffError):- pass-+ """A stuff that cannot be built from what it is given.-class StuffContentFactoryError(StuffError):- pass+ The default ``input.invalid`` is an input of a malformed shape; a raise site chooses ``input.wrong_concept`` for+ an input whose concept is not the one declared, and ``pipe.output_invalid`` or ``pipe.output_multiplicity`` for+ a pipe's output that does not hold what it combines.+ """+ error_code = ErrorCodeSet(+ default=CoreCode.INPUT_INVALID,+ others=(CoreCode.INPUT_WRONG_CONCEPT, CoreCode.PIPE_OUTPUT_INVALID, CoreCode.PIPE_OUTPUT_MULTIPLICITY),+ )-class StuffArtefactError(StuffError):- pass+class StuffContentFactoryError(StuffError):+ """A content that cannot be built from a value, such as a date that is not ISO; ``runtime.unexpected`` for a class that is no content."""-class StuffArtefactReservedFieldError(StuffArtefactError):- pass+ error_code = ErrorCodeSet(default=CoreCode.INPUT_INVALID, others=(CoreCode.RUNTIME_UNEXPECTED,))class StuffContentTypeError(StuffError):+ """A typed accessor read a content of another type than the one the method expects."""++ error_code = CoreCode.METHOD_WIRING_INVALID+def __init__(self, message: str, expected_type: str, actual_type: str):self.expected_type = expected_typeself.actual_type = actual_type@@ -32,9 +45,11 @@ class DateContentError(StuffError):"""Raised when a DateContent operation needs a time of day the value does not carry.The only such operation today is ``to_datetime()`` on a date-only value: converting it- would invent a time, which the Date concept refuses to do (no silent midnight).+ would invent a time, which the Date concept refuses to do (no silent midnight). It is reached only from a+ PipeFunc's own code, so its reader sees the function's failure."""+ error_code = CoreCode.PIPE_FUNCTION_RAISED# The message describes the caller's own data (a date-only Date has no time to convert) and carries# no server internals, so it must survive STRICT disclosure — like OptionalValueAbsentError._authors_caller_facing_message = True@@ -43,6 +58,8 @@ class DateContentError(StuffError):class StuffContentValidationError(StuffError):"""Raised when content validation fails during type conversion."""+ error_code = CoreCode.METHOD_WIRING_INVALID+def __init__(self, original_type: str, target_type: str, validation_error: str):self.original_type = original_typeself.target_type = target_typediff --git a/pipelex/core/stuffs/stuff_artefact.py b/pipelex/core/stuffs/stuff_artefact.pyindex 431efd648..16c9feeb6 100644--- a/pipelex/core/stuffs/stuff_artefact.py+++ b/pipelex/core/stuffs/stuff_artefact.py@@ -31,6 +31,7 @@ from typing import TYPE_CHECKING, Any, Callable, Iteratorfrom typing_extensions import overridefrom pipelex.core.stuffs.list_content import ListContent+from pipelex.tools.jinja2.exceptions import Jinja2ContextErrorfrom pipelex.tools.jinja2.html_renderable import HtmlRenderablefrom pipelex.tools.jinja2.image_renderable import ImageRenderablefrom pipelex.tools.jinja2.renderable_dispatch import type_implements@@ -450,7 +451,8 @@ class StuffArtefact:String with [Image N] tokens where images appear.Raises:- TypeError: If content type does not implement ImageRenderable.+ Jinja2ContextError: If content type does not implement ImageRenderable, which the render reports as the+ template's failure, as it does the filter's own refusal of such a value."""content = self._stuff.contentif not isinstance(content, ImageRenderable):@@ -459,7 +461,7 @@ class StuffArtefact:f"The | with_images filter can only be used with content types that may contain images: "f"ImageContent, TextAndImagesContent, ListContent, StructuredContent (and subclasses like PageContent).")- raise TypeError(msg)+ raise Jinja2ContextError(msg)return content.render_with_images(registry=registry, text_format=text_format)@overridediff --git a/pipelex/core/stuffs/stuff_content_factory.py b/pipelex/core/stuffs/stuff_content_factory.pyindex 70de01fba..aadb07314 100644--- a/pipelex/core/stuffs/stuff_content_factory.py+++ b/pipelex/core/stuffs/stuff_content_factory.py@@ -2,6 +2,8 @@ import datetimeimport refrom typing import Any+from mthds.protocol.problem.registry import CoreCode+from pipelex.core.concepts.concept import Conceptfrom pipelex.core.stuffs.date_content import DateContentfrom pipelex.core.stuffs.exceptions import StuffContentFactoryError@@ -102,6 +104,6 @@ class StuffContentFactory:if not issubclass(the_structure_class, StuffContent):msg = f"Concept '{concept.code}', subclass '{the_structure_class}' is not a subclass of StuffContent"- raise StuffContentFactoryError(msg)+ raise StuffContentFactoryError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)return cls.make_content_from_value(stuff_content_subclass=the_structure_class, value=value)diff --git a/pipelex/core/stuffs/stuff_factory.py b/pipelex/core/stuffs/stuff_factory.pyindex 94a15bacd..9c1afaee9 100644--- a/pipelex/core/stuffs/stuff_factory.py+++ b/pipelex/core/stuffs/stuff_factory.py@@ -5,6 +5,7 @@ from urllib.parse import urlsplit, urlunsplitimport shortuuidfrom mthds.protocol.pipeline_inputs import StuffContentOrData+from mthds.protocol.problem.registry import CoreCodefrom pydantic import BaseModel, ValidationError, field_validatorfrom pipelex.core.concepts.concept import Concept@@ -141,7 +142,7 @@ class StuffFactory:the_stuff_content = the_subclass.model_validate(obj=stuff_contents)except ValidationError as exc:msg = f"Error combining stuffs for concept {concept.code}, stuff named `{name}`: {format_pydantic_validation_error(exc=exc)}"- raise StuffFactoryError(msg) from exc+ raise StuffFactoryError(msg).with_error_code(CoreCode.PIPE_OUTPUT_INVALID) from excreturn cls.make_stuff(concept=concept,content=the_stuff_content,@@ -287,7 +288,7 @@ class StuffFactory:return concept_provider.get_required_entry_concept(concept_ref_or_code=concept_ref_or_code, search_scope=search_scope)except ConceptLibraryConceptNotFoundError as exc:msg = f"{context_msg} the concept of name '{concept_ref_or_code}' could not be resolved: {exc}"- raise StuffFactoryError(msg) from exc+ raise StuffFactoryError(msg).with_error_code(CoreCode.INPUT_WRONG_CONCEPT) from exc@classmethoddef make_stuff_from_stuff_content_or_data(@@ -537,7 +538,7 @@ class StuffFactory:f"Trying to create a Stuff '{name}' in the inputs of your pipe, from a dict that should represent a StuffContentOrData "f"but the concept of name '{concept_ref}' is not compatible with native concept 'native.YesNo' (the content is a boolean)")- raise StuffFactoryError(msg)+ raise StuffFactoryError(msg).with_error_code(CoreCode.INPUT_WRONG_CONCEPT)# Case 2.1: content is a stringif isinstance(content, str):@@ -573,7 +574,7 @@ class StuffFactory:f"Trying to create a Stuff '{name}' in the inputs of your pipe, from a dict that should represent a StuffContentOrData "f"but the concept of name '{concept_ref}' is not compatible with native concept 'native.Text', 'native.Date', or 'native.Time'")- raise StuffFactoryError(msg)+ raise StuffFactoryError(msg).with_error_code(CoreCode.INPUT_WRONG_CONCEPT)# Case 2.1e: content is a bare date/datetime object (a TOML temporal literal used as envelope content)# → DateContent for a Date-compatible concept. isinstance(date) covers datetime (its subclass).@@ -590,7 +591,7 @@ class StuffFactory:f"Trying to create a Stuff '{name}' in the inputs of your pipe, from a dict that should represent a StuffContentOrData "f"but the concept of name '{concept_ref}' is not compatible with native concept 'native.Date' (the content is a date/datetime)")- raise StuffFactoryError(msg)+ raise StuffFactoryError(msg).with_error_code(CoreCode.INPUT_WRONG_CONCEPT)# Case 2.1g: content is a bare time object (a TOML time literal used as envelope content).if isinstance(content, datetime.time):@@ -606,7 +607,7 @@ class StuffFactory:f"Trying to create a Stuff '{name}' in the inputs of your pipe, from a dict that should represent a StuffContentOrData "f"but the concept of name '{concept_ref}' is not compatible with native concept 'native.Time' (the content is a time)")- raise StuffFactoryError(msg)+ raise StuffFactoryError(msg).with_error_code(CoreCode.INPUT_WRONG_CONCEPT)# Case 2.3: content is a StuffContent object (includes both native and StructuredContent)if isinstance(content, StuffContent):@@ -615,7 +616,7 @@ class StuffFactory:f"Trying to create a Stuff '{name}' in the inputs of your pipe, from a dict that should represent a StuffContentOrData "f"but the concept of name '{concept_ref}' is not compatible with the content of type {content.__class__.__name__}")- raise StuffFactoryError(msg)+ raise StuffFactoryError(msg).with_error_code(CoreCode.INPUT_WRONG_CONCEPT)return cls.make_stuff(concept=concept,@@ -640,7 +641,7 @@ class StuffFactory:f"Trying to create a Stuff '{name}' in the inputs of your pipe, from a dict that should represent a StuffContentOrData "f"but the concept of name '{concept_ref}' is not compatible with a dict content")- raise StuffFactoryError(msg)+ raise StuffFactoryError(msg).with_error_code(CoreCode.INPUT_WRONG_CONCEPT)return cls.make_stuff(name=name,@@ -691,7 +692,7 @@ class StuffFactory:)msg = f"Concept '{concept_ref}' is not compatible with list of text content"- raise StuffFactoryError(msg)+ raise StuffFactoryError(msg).with_error_code(CoreCode.INPUT_WRONG_CONCEPT)# Case 2.4: list[StuffContent] (includes both native and StructuredContent)if isinstance(first_item, StuffContent):diff --git a/pipelex/errors/error_code_declaration.py b/pipelex/errors/error_code_declaration.pynew file mode 100644index 000000000..cc8cccbde--- /dev/null+++ b/pipelex/errors/error_code_declaration.py@@ -0,0 +1,132 @@+"""How a ``PipelexError`` subclass declares the code it raises.++Every subclass of :class:`~pipelex.base_exceptions.PipelexError` sets ``error_code`` in its own class body,+and a test fails the build on one that does not (``tests/unit/pipelex/errors/test_error_code_gate.py``).+The declaration is one of four:++- **A code**, a :class:`~mthds.protocol.problem.registry.CoreCode` or a+ :class:`~pipelex.errors.registry.pipelex_codes.PipelexErrorCode`: every instance raises that code.+- **A set**, :class:`ErrorCodeSet`: the raise site chooses one of its codes with+ :meth:`~pipelex.base_exceptions.PipelexError.with_error_code`, and an instance whose raise site chose none+ carries the set's default. A class whose raise sites need different verdicts declares a set rather than+ letting a raise site set a domain or a verdict of its own, since a verdict belongs to a code.+- **Its cause's code**, :class:`InheritsCause`: a wrapper that adds no fact deciding the code takes the code+ of its cause, and carries its fallback when the cause is not a coded error. A raise site that knows the+ code itself may still choose its fallback or one of its ``others`` with ``with_error_code``, and the walk+ then stops there.+- **An abstract base**, :data:`ABSTRACT_ERROR`: a base class that is never raised directly. The gate also+ refuses a ``raise`` of such a class anywhere in the package.++The code of a raised error is resolved by walking its ``__cause__`` chain: the walk descends through every+error that takes its cause's code and stops at the first that declares one, so that a wrapper which adds+the fact that decides the code keeps its own over a coded cause.+"""++from __future__ import annotations++from typing import Self, TypeAlias++from pydantic import ConfigDict, model_validator+from pydantic.dataclasses import dataclass++from pipelex.errors.error_codes import ErrorCode+++@dataclass(frozen=True, config=ConfigDict(arbitrary_types_allowed=True))+class ErrorCodeSet:+ """The codes a class's raise sites choose from, the first being the default.++ Attributes:+ default: The code an instance carries when its raise site chose none.+ others: The other codes a raise site may choose.+ """++ default: ErrorCode+ others: tuple[ErrorCode, ...]++ @model_validator(mode="after")+ def _validate_codes(self) -> Self:+ if not self.others:+ msg = "A set of codes holds more than one code; a class raising one code declares that code."+ raise ValueError(msg)+ if len(set(self.codes)) != len(self.codes):+ msg = f"A set of codes names a code twice: {', '.join(self.codes)}."+ raise ValueError(msg)+ return self++ @property+ def codes(self) -> tuple[ErrorCode, ...]:+ """Every code of the set, the default first."""+ return (self.default, *self.others)+++@dataclass(frozen=True, config=ConfigDict(arbitrary_types_allowed=True))+class InheritsCause:+ """The class takes the code of its cause, or its fallback when the cause carries none.++ Attributes:+ fallback: The code an instance carries when no error along its ``__cause__`` chain declares one.+ others: The codes a raise site that knows the code itself may choose, besides the fallback.+ """++ fallback: ErrorCode+ others: tuple[ErrorCode, ...] = ()++ @model_validator(mode="after")+ def _validate_codes(self) -> Self:+ if len(set(self.codes)) != len(self.codes):+ msg = f"A cause's fallback and the codes a raise site may choose name a code twice: {', '.join(self.codes)}."+ raise ValueError(msg)+ return self++ @property+ def codes(self) -> tuple[ErrorCode, ...]:+ """The fallback, then the codes a raise site may choose."""+ return (self.fallback, *self.others)+++@dataclass(frozen=True)+class AbstractError:+ """The declaration of a base class that is never raised directly."""+++ABSTRACT_ERROR = AbstractError()+"""The declaration of a base class that is never raised directly."""++ErrorCodeDeclaration: TypeAlias = ErrorCode | ErrorCodeSet | InheritsCause | AbstractError+"""What a ``PipelexError`` subclass declares about the code it raises."""+++def describe_error_code_declaration(declaration: ErrorCodeDeclaration) -> str:+ """A one-line reading of a declaration, as the error identity snapshot records it.++ Args:+ declaration: A class's declaration.++ Returns:+ The code; ``one of`` the codes of a set, the default first; ``inherits cause, else`` the fallback;+ or ``abstract``.+ """+ if isinstance(declaration, ErrorCodeSet):+ return "one of " + ", ".join(declaration.codes)+ if isinstance(declaration, InheritsCause):+ described = f"inherits cause, else {declaration.fallback}"+ if declaration.others:+ described += "; or chosen: " + ", ".join(declaration.others)+ return described+ if isinstance(declaration, AbstractError):+ return "abstract"+ return str(declaration)+++def declared_error_codes(declaration: ErrorCodeDeclaration) -> tuple[ErrorCode, ...]:+ """Every code a declaration names, which are the codes a raise site may choose.++ A code alone; a set's codes; a cause's fallback and the codes a raise site may choose besides it; or none+ for an abstract base.+ """+ if isinstance(declaration, (ErrorCodeSet, InheritsCause)):+ return declaration.codes+ if isinstance(declaration, AbstractError):+ return ()+ return (declaration,)diff --git a/pipelex/errors/error_code_sites.py b/pipelex/errors/error_code_sites.pynew file mode 100644index 000000000..f186558bd--- /dev/null+++ b/pipelex/errors/error_code_sites.py@@ -0,0 +1,93 @@+"""Where the package raises its errors and chooses their codes, read from the source without importing it.++The error-code gate (``tests/unit/pipelex/errors/test_error_code_gate.py``) needs two facts no import can give:+which class each ``raise`` statement constructs, so that an abstract base is never raised directly, and which+code each raise site chooses with ``with_error_code``, so that it is one its class declares. Both are read here+from the syntax tree of every module, which is pure and needs no Pipelex bootstrap.+"""++from __future__ import annotations++import ast+from typing import TYPE_CHECKING, NamedTuple++if TYPE_CHECKING:+ from pathlib import Path++_CODE_ENUM_NAMES = frozenset({"CoreCode", "PipelexErrorCode"})+++class RaisedClassSite(NamedTuple):+ """A ``raise`` statement that constructs a class by its name."""++ path: Path+ line: int+ class_name: str+++class ChosenCodeSite(NamedTuple):+ """A ``with_error_code`` call on a class constructed in place, choosing a code by its enum member."""++ path: Path+ line: int+ class_name: str+ enum_name: str+ member_name: str+++def constructed_class_name(node: ast.expr) -> str | None:+ """The name of the class an expression constructs, through any chain of methods called on the new instance.++ ``SomeError(msg)``, ``module.SomeError(msg)`` and ``SomeError(msg).with_error_code(code).as_caller_fault()``+ all construct ``SomeError``; a bare name, such as a re-raised variable, constructs nothing.+ """+ current: ast.expr = node+ while isinstance(current, ast.Call):+ func = current.func+ if isinstance(func, ast.Attribute) and isinstance(func.value, ast.Call):+ current = func.value+ continue+ if isinstance(func, ast.Name):+ return func.id+ if isinstance(func, ast.Attribute):+ return func.attr+ return None+ return None+++def _chosen_code(call: ast.Call) -> tuple[str, str] | None:+ if len(call.args) != 1 or call.keywords:+ return None+ argument = call.args[0]+ if isinstance(argument, ast.Attribute) and isinstance(argument.value, ast.Name) and argument.value.id in _CODE_ENUM_NAMES:+ return argument.value.id, argument.attr+ return None+++def iter_raised_class_sites(*, path: Path, source: str) -> list[RaisedClassSite]:+ """Every ``raise`` in a module that constructs a class, with the class's name."""+ sites: list[RaisedClassSite] = []+ for node in ast.walk(ast.parse(source, filename=str(path))):+ if isinstance(node, ast.Raise) and node.exc is not None:+ class_name = constructed_class_name(node.exc)+ if class_name is not None:+ sites.append(RaisedClassSite(path=path, line=node.lineno, class_name=class_name))+ return sites+++def iter_chosen_code_sites(*, path: Path, source: str) -> list[ChosenCodeSite]:+ """Every ``with_error_code(Enum.MEMBER)`` call on a class constructed in place, anywhere in a module."""+ sites: list[ChosenCodeSite] = []+ for node in ast.walk(ast.parse(source, filename=str(path))):+ if not isinstance(node, ast.Call):+ continue+ func = node.func+ if not (isinstance(func, ast.Attribute) and func.attr == "with_error_code" and isinstance(func.value, ast.Call)):+ continue+ class_name = constructed_class_name(func.value)+ chosen = _chosen_code(node)+ if class_name is None or chosen is None:+ continue+ enum_name, member_name = chosen+ sites.append(ChosenCodeSite(path=path, line=node.lineno, class_name=class_name, enum_name=enum_name, member_name=member_name))+ return sitesdiff --git a/pipelex/errors/error_codes.py b/pipelex/errors/error_codes.pynew file mode 100644index 000000000..aae54744d--- /dev/null+++ b/pipelex/errors/error_codes.py@@ -0,0 +1,129 @@+"""Every error code a Pipelex error may carry, and what the registries declare about each.++A code is either a core code of the MTHDS standard, generated into the ``mthds`` package as+:class:`~mthds.protocol.problem.registry.CoreCode` from the core registry, or a Pipelex code, generated into+:class:`~pipelex.errors.registry.pipelex_codes.PipelexErrorCode` from Pipelex's own registry. A code+decides everything a reader branches on: its title, the domain whose actor must act, its retry verdict,+its HTTP status and its two steps. :func:`error_code_spec` reads them from the generated tables, never+from a file, so classifying an error is a pure lookup that is safe anywhere, inside a Temporal workflow's+sandbox included.++Each ``PipelexError`` subclass declares the code it raises, the set its raise sites choose from, that it+takes its cause's code, or that it is an abstract base, as :mod:`pipelex.errors.error_code_declaration`+describes. ``docs/under-the-hood/error-model.md`` explains the whole model.+"""++from __future__ import annotations++from typing import TypeAlias++from mthds.protocol.problem.registry import CORE_BASE_URL, CORE_CODE_SPECS, EXTENSION_PREFIXES, CoreCode, ProblemDomain, RetryVerdict, StepKind+from pydantic import BaseModel, ConfigDict++from pipelex.errors.registry.pipelex_codes import PIPELEX_ERROR_ENTRIES, PipelexErrorCode++ErrorCode: TypeAlias = CoreCode | PipelexErrorCode+"""A registered code: a core code of the MTHDS standard, or a Pipelex code."""++PIPELEX_ERROR_BASE_URL: str = EXTENSION_PREFIXES["pipelex"]+"""The base URL the core registry registers for the ``pipelex`` prefix: a Pipelex code's type URI is this URL, a slash, then the code."""+++class ErrorCodeSpec(BaseModel):+ """What the registry declares about a code that classifying and reporting an error needs.++ Attributes:+ code: The code.+ title: The code's short title, the same for every occurrence.+ domain: Who must act.+ retry: Whether repeating the operation that produced the error can succeed.+ status: The HTTP status of an answer the code is the body of, ``None`` for a code a client+ raises itself or one that only rides a warning.+ actor_step: The kind of the next step for the domain's actor.+ other_step: The kind of the next step for any other reader.+ type_uri: The code's documentation page: its registry's base URL, a slash, then the code.+ """++ model_config = ConfigDict(frozen=True, extra="forbid")++ code: str+ title: str+ domain: ProblemDomain+ retry: RetryVerdict+ status: int | None+ actor_step: StepKind+ other_step: StepKind+ type_uri: str++ @property+ def invites_retry(self) -> bool:+ """Whether the verdict invites a repeat of the operation: only ``yes``, never ``no`` nor ``outcome_unknown``."""+ match self.retry:+ case RetryVerdict.YES:+ return True+ case RetryVerdict.NO | RetryVerdict.OUTCOME_UNKNOWN:+ return False+++def _build_specs() -> dict[str, ErrorCodeSpec]:+ specs: dict[str, ErrorCodeSpec] = {}+ for core_code in CoreCode:+ core_spec = CORE_CODE_SPECS[core_code]+ specs[core_code] = ErrorCodeSpec(+ code=core_code,+ title=core_spec.title,+ domain=core_spec.domain,+ retry=core_spec.retry,+ status=core_spec.status,+ actor_step=core_spec.actor_step.kind,+ other_step=core_spec.other_step.kind,+ type_uri=f"{CORE_BASE_URL}/{core_code}",+ )+ for pipelex_code in PipelexErrorCode:+ entry = PIPELEX_ERROR_ENTRIES[pipelex_code]+ specs[pipelex_code] = ErrorCodeSpec(+ code=pipelex_code,+ title=entry.title,+ domain=ProblemDomain(entry.domain),+ retry=RetryVerdict(entry.retry),+ status=entry.status,+ actor_step=StepKind(entry.actor_step),+ other_step=StepKind(entry.other_step),+ type_uri=f"{PIPELEX_ERROR_BASE_URL}/{pipelex_code}",+ )+ return specs+++_ERROR_CODE_SPECS: dict[str, ErrorCodeSpec] = _build_specs()+++def error_code_spec(code: ErrorCode) -> ErrorCodeSpec:+ """What the registry declares about a registered code.++ Args:+ code: A core code or a Pipelex code.++ Returns:+ The code's title, domain, retry verdict, status, step kinds and type URI.+ """+ return _ERROR_CODE_SPECS[code]+++def parse_error_code(value: str) -> ErrorCode | None:+ """The registered code a string names, ``None`` when it names no code of either registry.++ Args:+ value: A code as a reader received it, such as ``"model.unknown"`` or ``"pipelex.config.invalid"``.++ Returns:+ The code's constant, or ``None`` for a string that is no registered code.+ """+ # A lookup by value rather than `value in CoreCode`, which raises on a string before Python 3.12.+ try:+ return CoreCode(value)+ except ValueError:+ pass+ try:+ return PipelexErrorCode(value)+ except ValueError:+ return Nonediff --git a/pipelex/errors/error_identity_snapshot.py b/pipelex/errors/error_identity_snapshot.pyindex ee0bcf578..e7c96ec3a 100644--- a/pipelex/errors/error_identity_snapshot.py+++ b/pipelex/errors/error_identity_snapshot.py@@ -1,24 +1,18 @@-"""Snapshot of the wire-visible identity of every ``PipelexError`` subclass.+"""Snapshot of the wire-visible identity of every ``PipelexError`` subclass: its name and its code.-Every ``ErrorReport`` carries three identity fields — ``error_type``, ``title``-and ``type_uri`` (see :meth:`pipelex.base_exceptions.PipelexError.to_error_report`).-``error_type`` is the Python class name verbatim, with no indirection, and-external consumers branch on that string. Renaming an error class therefore-breaks them *silently*: their build stays green and the branch simply stops+Every ``ErrorReport`` carries the registry ``code`` its error resolved to, and still carries ``error_type``,+the Python class name verbatim, with no indirection, which external consumers branch on until the problem+document moves the class name to the operator's diagnostics. Renaming an error class therefore breaks them+*silently*, and so does changing the code a class raises: their build stays green and the branch simply stopsmatching, falling through to a generic error path.-``title`` and ``type_uri`` each have a declaration hatch (``_declared_title`` /-``_declared_type_uri``) precisely because they are presentation. ``error_type``,-the one field that is a machine contract, has none — so nothing in this repo-flagged a rename. This module closes that gap the cheap way: it renders the full-``(error_type, title, type_uri)`` set as a flat sorted table whose rendering is-committed to the repo, so a rename lands as a reviewable one-line-pair diff on a-single file at the moment it is made, instead of surfacing much later as a-fallthrough in a different repo.--Pure: :meth:`PipelexError.title` and :meth:`PipelexError.type_uri` read class-attributes and a module-level URL constant, so rendering needs no Pipelex-bootstrap.+This module closes that gap the cheap way: it renders every class's name and code declaration (the code, the+set its raise sites choose from, the cause it takes its code from, or that it is abstract, as+:func:`~pipelex.errors.error_code_declaration.describe_error_code_declaration` reads it) as a flat sorted table+whose rendering is committed to the repo, so a rename or a change of code lands as a reviewable diff on a single+file at the moment it is made, instead of surfacing much later as a fallthrough in a different repo.++Pure: a declaration is a class attribute, so rendering needs no Pipelex bootstrap."""from __future__ import annotations@@ -26,20 +20,24 @@ from __future__ import annotationsfrom typing import NamedTuplefrom pipelex.errors.error_class_discovery import iter_pipelex_error_subclasses+from pipelex.errors.error_code_declaration import describe_error_code_declaration# Column separator. Space-padded so the fields stay legible in a raw diff, and-# absent from every class name / type URI so a naive split round-trips.+# absent from every class name and declaration so a naive split round-trips.SNAPSHOT_SEPARATOR = " | "# Preamble written above the table. Explains what a diff here means to whoever# is reviewing one, and names the command that regenerates the file._HEADER_LINES: tuple[str, ...] = (- "# Wire identity of every PipelexError subclass: error_type | title | type_uri",+ "# Wire identity of every PipelexError subclass: error_type | code declaration","#","# `error_type` is the Python class name, verbatim — base_exceptions.py builds it as","# `type(self).__name__`. Consumers outside this repo switch on that string, so renaming","# an error class is a wire break that no build anywhere catches: they stay green and",- "# silently fall through to a generic branch. A diff in this file IS that wire break.",+ "# silently fall through to a generic branch. The declaration is the registry code the",+ "# class raises, the set its raise sites choose from, the cause it takes its code from,",+ "# or `abstract`; a change to it changes what every reader of the code is told to do.",+ "# A diff in this file IS that wire change.","#","# Generated — do not hand-edit. Regenerate with `make generate-error-identity` (alias `make gei`).","# Verified by tests/unit/pipelex/errors/test_error_identity_snapshot.py.",@@ -47,31 +45,31 @@ _HEADER_LINES: tuple[str, ...] = (class ErrorIdentityRow(NamedTuple):- """One error class's wire-visible identity triple."""+ """One error class's wire-visible identity: its name and its code declaration."""error_type: str- title: str- type_uri: str+ code_declaration: strdef iter_error_identity_rows() -> list[ErrorIdentityRow]:- """Return the identity triple of every discoverable ``PipelexError`` subclass, sorted.+ """Return the identity of every discoverable ``PipelexError`` subclass, sorted.Population comes from :func:`iter_pipelex_error_subclasses`, whichforce-loads the deferred-import error modules and filters synthetic /- fixture subclasses — the same set the generated docs pages and the- ``type_uri`` uniqueness check agree on. Do not hand-roll a- ``__subclasses__()`` walk here; see+ fixture subclasses. Do not hand-roll a ``__subclasses__()`` walk here; see``tests/unit/pipelex/errors/test_error_class_location_convention.py`` for whya naked walk is green for the wrong reason.- Sorted by the triple itself so the rendering is stable across runs and- independent of import order. Duplicate triples are not collapsed — two- classes sharing a name would show as two identical lines rather than being- silently merged (``test_pipelex_error_type_uri_uniqueness`` is what actually+ Sorted by the row itself so the rendering is stable across runs and+ independent of import order. Duplicate rows are not collapsed — two+ classes sharing a name would show as two lines rather than being+ silently merged (``test_pipelex_error_class_name_uniqueness`` is what actuallyforbids that case)."""- rows = [ErrorIdentityRow(error_type=cls.__name__, title=cls.title(), type_uri=cls.type_uri()) for cls in iter_pipelex_error_subclasses()]+ rows = [+ ErrorIdentityRow(error_type=cls.__name__, code_declaration=describe_error_code_declaration(cls.error_code))+ for cls in iter_pipelex_error_subclasses()+ ]return sorted(rows)diff --git a/pipelex/errors/foreign_raises.py b/pipelex/errors/foreign_raises.pynew file mode 100644index 000000000..1194e9567--- /dev/null+++ b/pipelex/errors/foreign_raises.py@@ -0,0 +1,254 @@+"""The raises, in our own code, of exception classes outside the ``PipelexError`` root.++An error raised outside the root carries no registry code: whatever reader it reaches gets the catch-all+``runtime.unexpected``, or worse a raw library message. So a raise a reader can see constructs a coded class,+and the check this module feeds (``tests/unit/pipelex/errors/test_foreign_raises.py``) catches a new foreign+raise where one is practical, as ``wip/error-handling/census.md`` ("Raises outside the root") describes.++Some foreign raises are right, and the scan allows them by their shape:++- a builtin raised inside a pydantic validator or serializer, which pydantic wraps into its own error and which+ takes the code of the boundary that catches it;+- ``NotImplementedError`` inside an abstract method or a ``Protocol``;+- any raise inside a data-model dunder (``__getitem__``, ``__getattr__``, ``__iter__`` and the like), which is+ how Python and Jinja learn that a key, an attribute or an item is missing;+- the framework carriers a library expects by type (:data:`FRAMEWORK_CARRIER_NAMES`);+- developer, release and test code (:data:`EXEMPT_DIRECTORY_NAMES`).++The rest are listed with their disposition in ``tests/data/errors/foreign_raises.txt``: an invariant raised+only on a bug of ours, which a boundary reports as ``runtime.unexpected``; a builtin raised in a helper only+validators call; a private class caught in the module that defines it; a carrier the scan cannot recognise+by its name; developer tooling outside the exempt directories; or a builtin of a module that must import nothing+of Pipelex, which its every caller catches. The check fails on a foreign raise that file does not list, and on a+listed one that is gone. A class whose name starts with an underscore is read as a variable re-raised, so a+private sentinel is never listed.++Pure: the scan reads the syntax tree of every module and imports nothing.+"""++from __future__ import annotations++import ast+from typing import TYPE_CHECKING, NamedTuple++from typing_extensions import override++if TYPE_CHECKING:+ from collections.abc import Iterable+ from pathlib import Path++ROOT_ERROR_CLASS_NAME = "PipelexError"+"""The root every coded error joins."""++VALIDATOR_DECORATOR_NAMES: frozenset[str] = frozenset(+ {"field_validator", "model_validator", "validator", "root_validator", "field_serializer", "model_serializer"}+)+"""Pydantic's decorators, inside which a builtin raise is wrapped by pydantic into its own error."""++VALIDATOR_EXCEPTION_NAMES: frozenset[str] = frozenset({"ValueError", "TypeError", "AssertionError", "PydanticCustomError"})+"""The exceptions pydantic turns into a validation error when a validator raises them."""++DATA_MODEL_DUNDER_NAMES: frozenset[str] = frozenset(+ {+ "__getitem__",+ "__getattr__",+ "__getattribute__",+ "__setattr__",+ "__delattr__",+ "__iter__",+ "__next__",+ "__anext__",+ "__len__",+ "__contains__",+ "__missing__",+ "__html__",+ "__reduce__",+ }+)+"""The dunders whose raises are how Python's data model, and Jinja's, learn that something is missing."""++FRAMEWORK_CARRIER_NAMES: frozenset[str] = frozenset(+ {+ # The CLI framework's own exits and refusals, which it renders itself.+ "Exit",+ "Abort",+ "BadParameter",+ "UsageError",+ "SystemExit",+ "KeyboardInterrupt",+ # The iteration and generator protocols.+ "StopIteration",+ "StopAsyncIteration",+ "GeneratorExit",+ # Temporal's failure carrier, Jinja's template refusals inside the render budget and the sandbox,+ # httpcore's refused connection inside the SSRF guard's transport, google-auth's refresh refusal,+ # kajson's decoder refusal inside the payload decoder, and the print protocol's end of stream.+ "ApplicationError",+ "TemplateError",+ "JinjaSecurityError",+ "ConnectError",+ "RefreshError",+ "KajsonDecoderError",+ "EOFError",+ }+)+"""The carriers a library expects by type, kept as they are wherever they are raised."""++EXEMPT_DIRECTORY_NAMES: frozenset[str] = frozenset({"dev_cli", "test_extras", "test_helpers", "scripts", "migrations"})+"""Developer, release, migration and test code, which the check does not read."""+++class ForeignRaiseSite(NamedTuple):+ """A raise of a class outside the root, by the module, the function and the class it raises."""++ path: str+ function: str+ exception: str+ line: int++ @property+ def key(self) -> tuple[str, str, str]:+ """The site without its line, which moves with every edit above it."""+ return (self.path, self.function, self.exception)+++def collect_root_error_class_names(*, sources: Iterable[tuple[Path, str]]) -> frozenset[str]:+ """The names of every class, across the given sources, that derives from the root by its bases' names.++ Read from the syntax tree alone, so that the runner's classes, which the package cannot import, count too.++ Args:+ sources: Each module's path and source.++ Returns:+ The root's name and the name of every class whose bases reach it.+ """+ bases_by_name: dict[str, set[str]] = {}+ for path, source in sources:+ for node in ast.walk(ast.parse(source, filename=str(path))):+ if isinstance(node, ast.ClassDef):+ expression_names = {_expression_name(base) for base in node.bases}+ bases_by_name.setdefault(node.name, set()).update(name for name in expression_names if name is not None)+ rooted: set[str] = {ROOT_ERROR_CLASS_NAME}+ grew = True+ while grew:+ grew = False+ for name, base_names in bases_by_name.items():+ if name not in rooted and base_names & rooted:+ rooted.add(name)+ grew = True+ return frozenset(rooted)+++def _expression_name(node: ast.expr) -> str | None:+ if isinstance(node, ast.Name):+ return node.id+ if isinstance(node, ast.Attribute):+ return node.attr+ if isinstance(node, ast.Subscript):+ return _expression_name(node.value)+ return None+++def _raised_class_name(node: ast.expr) -> str | None:+ """The class a raise constructs, through any chain of methods called on the new instance, or names bare."""+ current: ast.expr = node+ while isinstance(current, ast.Call):+ func = current.func+ if isinstance(func, ast.Attribute) and isinstance(func.value, ast.Call):+ current = func.value+ continue+ current = func+ break+ name = _expression_name(current)+ if name is None or not name[:1].isupper():+ # A lowercase name is a variable holding an exception being re-raised, not a class.+ return None+ return name+++def _decorator_names(function: ast.FunctionDef | ast.AsyncFunctionDef) -> set[str]:+ names: set[str] = set()+ for decorator in function.decorator_list:+ target = decorator.func if isinstance(decorator, ast.Call) else decorator+ name = _expression_name(target)+ if name is not None:+ names.add(name)+ return names+++class _ForeignRaiseVisitor(ast.NodeVisitor):+ def __init__(self, *, path: str, root_names: frozenset[str]) -> None:+ self.path = path+ self.root_names = root_names+ self.sites: list[ForeignRaiseSite] = []+ self._scopes: list[ast.ClassDef | ast.FunctionDef | ast.AsyncFunctionDef] = []++ @override+ def visit_ClassDef(self, node: ast.ClassDef) -> None:+ self._scopes.append(node)+ self.generic_visit(node)+ self._scopes.pop()++ @override+ def visit_FunctionDef(self, node: ast.FunctionDef) -> None:+ self._scopes.append(node)+ self.generic_visit(node)+ self._scopes.pop()++ @override+ def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:+ self._scopes.append(node)+ self.generic_visit(node)+ self._scopes.pop()++ @override+ def visit_Raise(self, node: ast.Raise) -> None:+ if node.exc is None:+ return+ class_name = _raised_class_name(node.exc)+ if class_name is None or class_name in self.root_names or self._is_allowed(class_name=class_name):+ return+ function = ".".join(scope.name for scope in self._scopes) or "<module>"+ self.sites.append(ForeignRaiseSite(path=self.path, function=function, exception=class_name, line=node.lineno))++ def _is_allowed(self, *, class_name: str) -> bool:+ if class_name in FRAMEWORK_CARRIER_NAMES:+ return True+ functions = [scope for scope in self._scopes if isinstance(scope, (ast.FunctionDef, ast.AsyncFunctionDef))]+ if not functions:+ return False+ innermost = functions[-1]+ if innermost.name in DATA_MODEL_DUNDER_NAMES:+ return True+ decorators = _decorator_names(innermost)+ if decorators & VALIDATOR_DECORATOR_NAMES and class_name in VALIDATOR_EXCEPTION_NAMES:+ return True+ if class_name == "NotImplementedError":+ if "abstractmethod" in decorators:+ return True+ enclosing_classes = [scope for scope in self._scopes if isinstance(scope, ast.ClassDef)]+ if enclosing_classes and "Protocol" in {_expression_name(base) for base in enclosing_classes[-1].bases}:+ return True+ return False+++def iter_foreign_raise_sites(*, path: str, source: str, root_names: frozenset[str]) -> list[ForeignRaiseSite]:+ """Every raise in a module of a class outside the root that no allowance covers.++ Args:+ path: The module's path, as the baseline names it.+ source: The module's source.+ root_names: The names of the root and of every class deriving from it.++ Returns:+ The sites, in the module's order.+ """+ visitor = _ForeignRaiseVisitor(path=path, root_names=root_names)+ visitor.visit(ast.parse(source, filename=path))+ return visitor.sites+++def is_exempt_path(*, relative_parts: tuple[str, ...]) -> bool:+ """Whether a module lies in developer, release, migration or test code, which the check does not read."""+ return not EXEMPT_DIRECTORY_NAMES.isdisjoint(relative_parts)diff --git a/pipelex/errors/registry/pipelex_codes.py b/pipelex/errors/registry/pipelex_codes.pyindex 93d061739..ab52bf25e 100644--- a/pipelex/errors/registry/pipelex_codes.py+++ b/pipelex/errors/registry/pipelex_codes.py@@ -8,7 +8,7 @@ the generator writes from it.from __future__ import annotationsfrom enum import StrEnum-from typing import ClassVar, Literal+from typing import ClassVar, Literal, NamedTuplefrom pydantic import BaseModel, ConfigDict, Field@@ -1014,3 +1014,492 @@ PIPELEX_ERROR_PARAMS: dict[PipelexErrorCode, type[PipelexErrorParams]] = {PipelexErrorCode.WEBHOOK_DELIVERY_FAILED: WebhookDeliveryFailedParams,}"""The parameters model of every Pipelex code."""+++class PipelexErrorEntry(NamedTuple):+ """What the registry declares about a Pipelex code that classifying an error needs.++ Attributes:+ title: The code's short title, the same for every occurrence.+ domain: Who must act, from the MTHDS protocol's closed list of domains.+ retry: Whether repeating the operation can succeed: ``no``, ``yes`` or ``outcome_unknown``.+ status: The HTTP status of an answer the code is the body of, ``None`` for a code raised otherwise.+ actor_step: The kind of the step aimed at the domain's actor.+ other_step: The kind of the step aimed at any other reader.+ """++ title: str+ domain: str+ retry: str+ status: int | None+ actor_step: str+ other_step: str+++PIPELEX_ERROR_ENTRIES: dict[PipelexErrorCode, PipelexErrorEntry] = {+ PipelexErrorCode.BILLING_PLAN_LIMIT: PipelexErrorEntry(+ title="The account's plan does not allow this",+ domain="account",+ retry="no",+ status=409,+ actor_step="check_account",+ other_step="contact_owner",+ ),+ PipelexErrorCode.BILLING_CREDIT_EXHAUSTED: PipelexErrorEntry(+ title="The organization is out of credit",+ domain="account",+ retry="no",+ status=402,+ actor_step="check_account",+ other_step="contact_owner",+ ),+ PipelexErrorCode.BILLING_SUBSCRIPTION_CONFLICT: PipelexErrorEntry(+ title="The subscription's state does not allow this",+ domain="account",+ retry="no",+ status=409,+ actor_step="check_account",+ other_step="contact_owner",+ ),+ PipelexErrorCode.BILLING_PLAN_REFUSED: PipelexErrorEntry(+ title="The plan's rules refuse this change",+ domain="input",+ retry="no",+ status=409,+ actor_step="change_input",+ other_step="change_input",+ ),+ PipelexErrorCode.ORG_REQUIRED: PipelexErrorEntry(+ title="An organization is required",+ domain="account",+ retry="no",+ status=403,+ actor_step="check_account",+ other_step="contact_owner",+ ),+ PipelexErrorCode.ORG_MISMATCH: PipelexErrorEntry(+ title="The reference belongs to another organization",+ domain="input",+ retry="no",+ status=403,+ actor_step="change_input",+ other_step="change_input",+ ),+ PipelexErrorCode.ORG_NOT_FOUND: PipelexErrorEntry(+ title="The organization's resource does not exist",+ domain="input",+ retry="no",+ status=404,+ actor_step="change_input",+ other_step="change_input",+ ),+ PipelexErrorCode.ORG_NOT_MANAGEABLE: PipelexErrorEntry(+ title="The resource cannot be changed this way in its state",+ domain="input",+ retry="no",+ status=409,+ actor_step="change_input",+ other_step="change_input",+ ),+ PipelexErrorCode.ORG_ALREADY_EXISTS: PipelexErrorEntry(+ title="The organization's resource already exists",+ domain="input",+ retry="no",+ status=409,+ actor_step="change_input",+ other_step="change_input",+ ),+ PipelexErrorCode.ORG_PROMO_INVALID: PipelexErrorEntry(+ title="The promo code cannot be redeemed",+ domain="input",+ retry="no",+ status=422,+ actor_step="change_input",+ other_step="change_input",+ ),+ PipelexErrorCode.ORG_PROMO_CREDIT_PENDING: PipelexErrorEntry(+ title="The promo credit is pending",+ domain="runtime",+ retry="no",+ status=502,+ actor_step="wait",+ other_step="wait",+ ),+ PipelexErrorCode.CATALOG_NOT_FOUND: PipelexErrorEntry(+ title="The saved method does not exist",+ domain="input",+ retry="no",+ status=404,+ actor_step="change_input",+ other_step="change_input",+ ),+ PipelexErrorCode.CATALOG_NOT_PUBLISHED: PipelexErrorEntry(+ title="The saved method has no published version",+ domain="input",+ retry="no",+ status=409,+ actor_step="change_input",+ other_step="change_input",+ ),+ PipelexErrorCode.CATALOG_BEING_DELETED: PipelexErrorEntry(+ title="The saved method is being deleted",+ domain="input",+ retry="no",+ status=409,+ actor_step="change_input",+ other_step="change_input",+ ),+ PipelexErrorCode.CATALOG_DELETION_FAILED: PipelexErrorEntry(+ title="The saved method's deletion failed",+ domain="runtime",+ retry="yes",+ status=503,+ actor_step="retry",+ other_step="retry",+ ),+ PipelexErrorCode.CATALOG_UPDATE_CONFLICT: PipelexErrorEntry(+ title="The saved method changed since it was read",+ domain="input",+ retry="no",+ status=409,+ actor_step="refresh",+ other_step="refresh",+ ),+ PipelexErrorCode.CATALOG_SELECTOR_INVALID: PipelexErrorEntry(+ title="The catalog selector is malformed",+ domain="input",+ retry="no",+ status=422,+ actor_step="change_input",+ other_step="change_input",+ ),+ PipelexErrorCode.CATALOG_LINK_CONFLICT: PipelexErrorEntry(+ title="The directory is linked to another method",+ domain="input",+ retry="no",+ status=None,+ actor_step="change_input",+ other_step="change_input",+ ),+ PipelexErrorCode.RUN_ALREADY_EXISTS: PipelexErrorEntry(+ title="A run with this id already exists",+ domain="input",+ retry="no",+ status=409,+ actor_step="change_input",+ other_step="change_input",+ ),+ PipelexErrorCode.STORAGE_URI_INVALID: PipelexErrorEntry(+ title="The storage address is malformed",+ domain="input",+ retry="no",+ status=422,+ actor_step="change_input",+ other_step="change_input",+ ),+ PipelexErrorCode.STORAGE_NOT_FOUND: PipelexErrorEntry(+ title="A stored file is gone",+ domain="runtime",+ retry="no",+ status=500,+ actor_step="report",+ other_step="report",+ ),+ PipelexErrorCode.STORAGE_UNAVAILABLE: PipelexErrorEntry(+ title="Storage is unavailable",+ domain="runtime",+ retry="yes",+ status=503,+ actor_step="retry",+ other_step="wait",+ ),+ PipelexErrorCode.STORAGE_NOT_CONFIGURED: PipelexErrorEntry(+ title="This deployment serves no storage for that address",+ domain="operator",+ retry="no",+ status=500,+ actor_step="fix_configuration",+ other_step="report",+ ),+ PipelexErrorCode.STORAGE_GRANT_UNUSABLE: PipelexErrorEntry(+ title="The upload grant is spent or expired",+ domain="runtime",+ retry="yes",+ status=403,+ actor_step="retry",+ other_step="retry",+ ),+ PipelexErrorCode.STORAGE_GRANT_MISMATCH: PipelexErrorEntry(+ title="The upload differs from its grant",+ domain="runtime",+ retry="no",+ status=403,+ actor_step="report",+ other_step="report",+ ),+ PipelexErrorCode.STORAGE_UPLOAD_REFUSED: PipelexErrorEntry(+ title="Storage refused the upload",+ domain="runtime",+ retry="no",+ status=403,+ actor_step="report",+ other_step="report",+ ),+ PipelexErrorCode.SECURITY_RESERVED_KEY: PipelexErrorEntry(+ title="The request carries a reserved key",+ domain="input",+ retry="no",+ status=422,+ actor_step="change_input",+ other_step="change_input",+ ),+ PipelexErrorCode.SECURITY_RESULT_OUTSIDE_SCOPE: PipelexErrorEntry(+ title="A result location lies outside the run",+ domain="runtime",+ retry="no",+ status=500,+ actor_step="report",+ other_step="report",+ ),+ PipelexErrorCode.CONFIG_INVALID: PipelexErrorEntry(+ title="The runtime's configuration is invalid",+ domain="operator",+ retry="no",+ status=500,+ actor_step="fix_configuration",+ other_step="report",+ ),+ PipelexErrorCode.CONFIG_SYNTAX: PipelexErrorEntry(+ title="A configuration file does not parse",+ domain="operator",+ retry="no",+ status=500,+ actor_step="fix_configuration",+ other_step="report",+ ),+ PipelexErrorCode.CONFIG_FILE_MISSING: PipelexErrorEntry(+ title="A configuration file is missing",+ domain="operator",+ retry="no",+ status=500,+ actor_step="fix_configuration",+ other_step="report",+ ),+ PipelexErrorCode.CONFIG_VARIABLE_MISSING: PipelexErrorEntry(+ title="A configuration variable is not set",+ domain="operator",+ retry="no",+ status=500,+ actor_step="fix_configuration",+ other_step="report",+ ),+ PipelexErrorCode.CONFIG_CREDENTIAL_MISSING: PipelexErrorEntry(+ title="An inference backend has no credential",+ domain="operator",+ retry="no",+ status=500,+ actor_step="check_credentials",+ other_step="report",+ ),+ PipelexErrorCode.CONFIG_CREDENTIAL_REFUSED: PipelexErrorEntry(+ title="A service refused the configured credential",+ domain="operator",+ retry="no",+ status=500,+ actor_step="check_credentials",+ other_step="report",+ ),+ PipelexErrorCode.CONFIG_DEPENDENCY_MISSING: PipelexErrorEntry(+ title="An optional dependency is not installed",+ domain="operator",+ retry="no",+ status=500,+ actor_step="fix_configuration",+ other_step="report",+ ),+ PipelexErrorCode.PLUGIN_NOT_FOUND: PipelexErrorEntry(+ title="No plugin provides the configured choice",+ domain="operator",+ retry="no",+ status=500,+ actor_step="fix_configuration",+ other_step="report",+ ),+ PipelexErrorCode.PLUGIN_BROKEN: PipelexErrorEntry(+ title="A plugin failed to load",+ domain="operator",+ retry="no",+ status=500,+ actor_step="fix_configuration",+ other_step="report",+ ),+ PipelexErrorCode.PLUGIN_CONFLICT: PipelexErrorEntry(+ title="Two plugins claim the same slot",+ domain="operator",+ retry="no",+ status=500,+ actor_step="fix_configuration",+ other_step="report",+ ),+ PipelexErrorCode.PLUGIN_API_MISMATCH: PipelexErrorEntry(+ title="A plugin targets another plugin API",+ domain="operator",+ retry="no",+ status=500,+ actor_step="upgrade",+ other_step="report",+ ),+ PipelexErrorCode.DEPLOYMENT_ORCHESTRATION_OVERRIDE_FORBIDDEN: PipelexErrorEntry(+ title="This deployment does not allow choosing the orchestration mode",+ domain="input",+ retry="no",+ status=422,+ actor_step="change_input",+ other_step="change_input",+ ),+ PipelexErrorCode.DEPLOYMENT_CUSTOM_CODE_REQUIRES_SANDBOX: PipelexErrorEntry(+ title="Custom code needs a sandbox-hosted deployment",+ domain="operator",+ retry="no",+ status=501,+ actor_step="fix_configuration",+ other_step="report",+ ),+ PipelexErrorCode.DEPLOYMENT_PYTHON_STRUCTURES_REFUSED: PipelexErrorEntry(+ title="Python structure classes are not allowed here",+ domain="method",+ retry="no",+ status=422,+ actor_step="change_method",+ other_step="contact_owner",+ ),+ PipelexErrorCode.DEPLOYMENT_TOKEN_CLAIMS_INVALID: PipelexErrorEntry(+ title="The token's claims cannot be used",+ domain="operator",+ retry="no",+ status=500,+ actor_step="fix_configuration",+ other_step="report",+ ),+ PipelexErrorCode.DOCGEN_ENGINE_UNAVAILABLE: PipelexErrorEntry(+ title="No document engine prints this here",+ domain="operator",+ retry="no",+ status=501,+ actor_step="fix_configuration",+ other_step="report",+ ),+ PipelexErrorCode.DOCGEN_TEMPLATE_INVALID: PipelexErrorEntry(+ title="The document template cannot be used",+ domain="method",+ retry="no",+ status=422,+ actor_step="change_method",+ other_step="contact_owner",+ ),+ PipelexErrorCode.DOCGEN_RESOURCE_REFUSED: PipelexErrorEntry(+ title="The document names a file it may not read",+ domain="method",+ retry="no",+ status=422,+ actor_step="change_method",+ other_step="contact_owner",+ ),+ PipelexErrorCode.DOCGEN_CONTENT_UNPRINTABLE: PipelexErrorEntry(+ title="The document's content cannot be printed",+ domain="input",+ retry="no",+ status=422,+ actor_step="change_input",+ other_step="change_input",+ ),+ PipelexErrorCode.DOCGEN_PRINT_TIMEOUT: PipelexErrorEntry(+ title="Printing the document took too long",+ domain="runtime",+ retry="yes",+ status=504,+ actor_step="retry",+ other_step="retry",+ ),+ PipelexErrorCode.DOCGEN_TEMPLATE_WARNING: PipelexErrorEntry(+ title="The document template may be faulty",+ domain="method",+ retry="no",+ status=None,+ actor_step="change_method",+ other_step="contact_owner",+ ),+ PipelexErrorCode.SANDBOX_UNAVAILABLE: PipelexErrorEntry(+ title="The Daytona sandbox could not be started",+ domain="runtime",+ retry="yes",+ status=503,+ actor_step="retry",+ other_step="retry",+ ),+ PipelexErrorCode.CODEGEN_OUTPUT_CONFLICT: PipelexErrorEntry(+ title="Codegen will not write there",+ domain="input",+ retry="no",+ status=409,+ actor_step="change_input",+ other_step="change_input",+ ),+ PipelexErrorCode.CODEGEN_LOCK_INVALID: PipelexErrorEntry(+ title="The codegen lock is unreadable",+ domain="input",+ retry="no",+ status=422,+ actor_step="change_input",+ other_step="change_input",+ ),+ PipelexErrorCode.CODEGEN_LOCK_UNSUPPORTED: PipelexErrorEntry(+ title="The codegen lock needs a newer Pipelex",+ domain="operator",+ retry="no",+ status=500,+ actor_step="upgrade",+ other_step="report",+ ),+ PipelexErrorCode.CODEGEN_LOCK_NOT_FOUND: PipelexErrorEntry(+ title="No codegen lock in this directory",+ domain="input",+ retry="no",+ status=404,+ actor_step="change_input",+ other_step="change_input",+ ),+ PipelexErrorCode.CODEGEN_DRIFTED: PipelexErrorEntry(+ title="The generated code has drifted from its method",+ domain="input",+ retry="no",+ status=409,+ actor_step="change_input",+ other_step="change_input",+ ),+ PipelexErrorCode.CONNECTOR_TOOL_NOT_IN_TOOLSET: PipelexErrorEntry(+ title="The tool is not in the connector's toolset",+ domain="method",+ retry="no",+ status=422,+ actor_step="change_method",+ other_step="contact_owner",+ ),+ PipelexErrorCode.ERASURE_INCOMPLETE: PipelexErrorEntry(+ title="The erasure left data behind",+ domain="runtime",+ retry="yes",+ status=503,+ actor_step="retry",+ other_step="report",+ ),+ PipelexErrorCode.WEBHOOK_DELIVERY_FAILED: PipelexErrorEntry(+ title="A webhook was not delivered",+ domain="input",+ retry="yes",+ status=502,+ actor_step="change_input",+ other_step="change_input",+ ),+}+"""The title and verdict of every Pipelex code."""diff --git a/pipelex/errors/retired_error_pages.py b/pipelex/errors/retired_error_pages.pynew file mode 100644index 000000000..382ed09e9--- /dev/null+++ b/pipelex/errors/retired_error_pages.py@@ -0,0 +1,130 @@+"""Static redirects from the retired per-class error pages to the page of each class's code.++Before every error carried a registry code, each ``PipelexError`` class had a generated page at+``errors/<kebab-class-name>/``, which its class-derived type URI named+(``https://docs.pipelex.com/latest/errors/<kebab-class-name>/``). Those pages are retired, and a type URI is now+its code's page. A client that kept an old type URI, or follows one from a stored report, still deserves an+answer rather than a 404, and a non-browser client never runs the site's ``404.html`` script, so the+documentation build holds a static redirect for every retired page: ``mkdocs.yml``'s ``redirect_maps`` sends each+to the page of its class's code, the default of a set or the fallback of a class that takes its cause's code, and+sends a page whose class is gone or abstract to the error codes' index.++The retired pages are a closed historical set, so the keys of the block in ``mkdocs.yml`` are its record; the+targets are derived from the classes, and ``make generate-error-identity`` rewrites them when a class's code+changes. ``tests/unit/pipelex/errors/test_retired_error_page_redirects.py`` fails when they drift.+"""++from __future__ import annotations++import re+from typing import TYPE_CHECKING++from mthds.protocol.problem.registry import CoreCode++from pipelex.errors.error_class_discovery import iter_pipelex_error_subclasses+from pipelex.errors.error_code_declaration import AbstractError, ErrorCodeSet, InheritsCause+from pipelex.tools.misc.string_utils import pascal_case_to_kebab++if TYPE_CHECKING:+ from pipelex.base_exceptions import PipelexError+ from pipelex.errors.error_codes import ErrorCode++BLOCK_BEGIN = " # BEGIN retired error class pages"+BLOCK_END = " # END retired error class pages"+ERROR_CODES_INDEX_PAGE = "errors/index.md"+_ENTRY_PATTERN = re.compile(r"^\s+'errors/(?P<kebab>[a-z0-9]+(?:-[a-z0-9]+)*)\.md': '(?P<target>[^']+)'$")+_BLOCK_PREAMBLE: tuple[str, ...] = (+ " # The retired per-class error pages, each sent to the page of its class's code: the default of a set, the",+ " # fallback of a class that takes its cause's code, or the error codes' index for a class abstract or gone.",+ " # The keys are the closed set of retired pages; the targets are generated by `make generate-error-identity`.",+)+++class RetiredErrorPagesError(ValueError):+ """``mkdocs.yml`` holds no well-formed block of retired error page redirects."""+++def _representative_code(cls: type[PipelexError]) -> ErrorCode | None:+ declaration = cls.error_code+ if isinstance(declaration, ErrorCodeSet):+ return declaration.default+ if isinstance(declaration, InheritsCause):+ return declaration.fallback+ if isinstance(declaration, AbstractError):+ return None+ return declaration+++def _code_page_target(code: ErrorCode) -> str:+ if isinstance(code, CoreCode):+ # A core code's page is published with the standard; its type URI is that page.+ return f"https://mthds.ai/errors/{code}"+ return f"errors/{code.replace('.', '/')}.md"+++def retired_page_target(*, kebab_name: str, classes_by_kebab: dict[str, type[PipelexError]]) -> str:+ """Where the retired page of the class kebab-cased ``kebab_name`` now redirects.++ Args:+ kebab_name: The retired page's name, the class name kebab-cased.+ classes_by_kebab: The current error classes by their kebab-cased name.++ Returns:+ The page of the class's code (a documentation path for a Pipelex code, the standard's URL for a core+ code), or the error codes' index for a class that is abstract or no longer exists.+ """+ cls = classes_by_kebab.get(kebab_name)+ if cls is None:+ return ERROR_CODES_INDEX_PAGE+ code = _representative_code(cls)+ if code is None:+ return ERROR_CODES_INDEX_PAGE+ return _code_page_target(code)+++def _split_block(*, mkdocs_text: str) -> tuple[list[str], list[str], list[str]]:+ lines = mkdocs_text.split("\n")+ try:+ begin = lines.index(BLOCK_BEGIN)+ end = lines.index(BLOCK_END)+ except ValueError as exc:+ msg = f"mkdocs.yml holds no '{BLOCK_BEGIN.strip()}' ... '{BLOCK_END.strip()}' block under redirect_maps."+ raise RetiredErrorPagesError(msg) from exc+ if end < begin:+ msg = "mkdocs.yml's block of retired error page redirects ends before it begins."+ raise RetiredErrorPagesError(msg)+ return lines[: begin + 1], lines[begin + 1 : end], lines[end:]+++def retired_page_names(*, mkdocs_text: str) -> list[str]:+ """The retired pages' names, as the block in ``mkdocs.yml`` records them."""+ _head, body, _tail = _split_block(mkdocs_text=mkdocs_text)+ names: list[str] = []+ for line in body:+ if not line.strip() or line.strip().startswith("#"):+ continue+ matched = _ENTRY_PATTERN.match(line)+ if matched is None:+ msg = f"A line of mkdocs.yml's block of retired error page redirects is not a redirect: {line!r}"+ raise RetiredErrorPagesError(msg)+ names.append(matched.group("kebab"))+ return names+++def render_retired_error_page_redirects(*, mkdocs_text: str) -> str:+ """``mkdocs.yml`` with the targets of its retired error page redirects derived from the current classes.++ Args:+ mkdocs_text: The current ``mkdocs.yml``.++ Returns:+ The same text, the block between its markers rewritten: the preamble, then one redirect per retired page,+ sorted by name.+ """+ head, _body, tail = _split_block(mkdocs_text=mkdocs_text)+ classes_by_kebab = {pascal_case_to_kebab(cls.__name__): cls for cls in iter_pipelex_error_subclasses()}+ body = list(_BLOCK_PREAMBLE)+ for kebab_name in sorted(set(retired_page_names(mkdocs_text=mkdocs_text))):+ target = retired_page_target(kebab_name=kebab_name, classes_by_kebab=classes_by_kebab)+ body.append(f" 'errors/{kebab_name}.md': '{target}'")+ return "\n".join([*head, *body, *tail])diff --git a/pipelex/exceptions.py b/pipelex/exceptions.pyindex 77876940a..0f6f728f5 100644--- a/pipelex/exceptions.py+++ b/pipelex/exceptions.py@@ -3,10 +3,9 @@ from pipelex.core.concepts.exceptions import (ConceptError,ConceptFactoryError,ConceptLibraryConceptNotFoundError,- ConceptRefineError,ConceptStringError,)-from pipelex.core.concepts.structure_generation.exceptions import ConceptStructureGeneratorError, ConceptStructureValidationError, StructureClassError+from pipelex.core.concepts.structure_generation.exceptions import ConceptStructureGeneratorError, ConceptStructureValidationErrorfrom pipelex.core.domains.exceptions import DomainCodeErrorfrom pipelex.core.memory.exceptions import (WorkingMemoryConsistencyError,@@ -24,23 +23,18 @@ from pipelex.core.pipes.exceptions import ()from pipelex.core.pipes.inputs.exceptions import InputStuffSpecNotFoundErrorfrom pipelex.core.stuffs.exceptions import (- StuffArtefactError,- StuffArtefactReservedFieldError,StuffContentTypeError,StuffContentValidationError,StuffError,)from pipelex.libraries.exceptions import (- ConceptLoadingError,- DomainLoadingError,LibraryError,LibraryLoadingError,- PipeLoadingError,)from pipelex.libraries.pipe.exceptions import PipeNotFoundError-from pipelex.pipe_controllers.exceptions import PipeControllerError, PipeControllerOutputConceptMismatchError+from pipelex.pipe_controllers.exceptions import PipeControllerErrorfrom pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityError-from pipelex.pipe_run.exceptions import BatchParamsError, PipeRouterError, PipeRunParamsError+from pipelex.pipe_run.exceptions import PipeRouterError, PipeRunParamsErrorfrom pipelex.pipeline.exceptions import (PipeExecutionError,PipelineExecutionError,@@ -63,28 +57,21 @@ __all__ = ["ConceptError","ConceptStructureValidationError","ConceptFactoryError",- "StructureClassError","ConceptCodeError","ConceptStringError",- "ConceptRefineError","ConceptLibraryConceptNotFoundError","ConceptStructureGeneratorError",# from pipelex.libraries.exceptions"LibraryError","LibraryLoadingError",- "ConceptLoadingError",- "DomainLoadingError",- "PipeLoadingError",# from pipelex.libraries.pipe.exceptions"PipeNotFoundError",# from pipelex.pipe_controllers.exceptions"PipeControllerError",- "PipeControllerOutputConceptMismatchError",# from pipelex.pipe_operators.exceptions"PipeOperatorModelAvailabilityError",# from pipelex.pipe_run.exceptions"PipeRunParamsError",- "BatchParamsError","PipeRouterError",# from pipelex.core.pipes.exceptions"PipeRunError",@@ -92,8 +79,6 @@ __all__ = ["PipeFactoryError","PipeOperatorModelChoiceError",# from pipelex.core.stuffs.exceptions- "StuffArtefactError",- "StuffArtefactReservedFieldError","StuffError","StuffContentTypeError","StuffContentValidationError",diff --git a/pipelex/fix_ops/exceptions.py b/pipelex/fix_ops/exceptions.pyindex c3106db99..0bbc7dd09 100644--- a/pipelex/fix_ops/exceptions.py+++ b/pipelex/fix_ops/exceptions.py@@ -1,9 +1,15 @@+from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import PipelexError, PipelexUnexpectedErrorclass FixWriteConflictError(PipelexError):"""A file changed after a fix or a migration read it but before the atomic commit."""+ error_code = CoreCode.METHOD_CHANGED_CONCURRENTLY+class FixTransactionError(PipelexUnexpectedError):"""A multi-file commit failed and could not be fully rolled back."""++ error_code = CoreCode.RUNTIME_UNEXPECTEDdiff --git a/pipelex/graph/exceptions.py b/pipelex/graph/exceptions.pyindex ba31fbd55..a9d81899f 100644--- a/pipelex/graph/exceptions.py+++ b/pipelex/graph/exceptions.py@@ -1,11 +1,18 @@"""GraphSpec-specific exceptions."""+from typing import ClassVar++from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import PipelexError+from pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeDeclaration, ErrorCodeSetclass GraphSpecError(PipelexError):"""Base exception for GraphSpec-related errors."""+ error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERROR+class GraphSpecValidationError(GraphSpecError):"""Exception raised when GraphSpec validation fails.@@ -15,4 +22,10 @@ class GraphSpecValidationError(GraphSpecError):- Duplicate node IDs- Duplicate edge IDs- Failed status without error specification++ Those are invariants of the graph we assemble, so a violation is ours (`runtime.unexpected`, the+ default); a graph spec file a caller hands back in a shape this version no longer accepts is+ `request.invalid`, which the raise site chooses."""++ error_code = ErrorCodeSet(default=CoreCode.RUNTIME_UNEXPECTED, others=(CoreCode.REQUEST_INVALID,))diff --git a/pipelex/hosted/error_rendering.py b/pipelex/hosted/error_rendering.pyindex b9bf625a0..22c5331c4 100644--- a/pipelex/hosted/error_rendering.py+++ b/pipelex/hosted/error_rendering.py@@ -93,11 +93,12 @@ def sent_verdict(*, error: ApiResponseError) -> SentVerdict:pipelex-sdk gives every `ApiResponseError` a decided `error_domain` and `retryable`, filling a member the serverdid not send from its own table by status, which reads every unlabelled 5xx, a 503 included, as retryable. A 503does not say whether the run happened (see `_UNAVAILABLE_NEXT_STEP`), and who has to act is only the runner's to- say, so both CLIs report what the server sent and nothing the SDK inferred. `problem` keeps the server's members.+ say, so both CLIs report what the server sent and nothing the SDK inferred. `problem_document` keeps the server's+ members as it sent them; `problem` is the standard's reading of the answer, which may be inferred from the status."""- problem = error.problem or {}- sent_domain = problem.get("error_domain")- sent_retryable = problem.get("retryable")+ problem_document = error.problem_document or {}+ sent_domain = problem_document.get("error_domain")+ sent_retryable = problem_document.get("retryable")return SentVerdict(error_domain=sent_domain if isinstance(sent_domain, str) and sent_domain else None,retryable=sent_retryable if isinstance(sent_retryable, bool) else None,@@ -166,7 +167,10 @@ def describe_hosted_error(*, error: PipelineRequestError | HostedRunError) -> Hocase HostedRunError():message = error.messagenext_step = error.user_action.detail if error.user_action is not None else "Check the run request: the method, the pipe and the inputs"- error_domain = error.error_domain+ # Who acts and whether a retry can succeed are the error's code's, read off its report.+ hosted_report = error.to_error_report()+ error_domain = hosted_report.error_domain+ retryable = hosted_report.retryableif isinstance(error, (HostedRunPollingError, HostedRunInterruptedError)):pipeline_run_id = error.pipeline_run_idif isinstance(error, HostedMethodInvalidError):diff --git a/pipelex/hosted/exceptions.py b/pipelex/hosted/exceptions.pyindex 8aef77401..9f9f3d111 100644--- a/pipelex/hosted/exceptions.py+++ b/pipelex/hosted/exceptions.py@@ -1,9 +1,11 @@from typing import ClassVar+from mthds.protocol.problem.registry import CoreCodefrom pipelex_sdk.validation_models import ValidationErrorItem-from pipelex.base_exceptions import ErrorDomain, PipelexError+from pipelex.base_exceptions import PipelexErrorfrom pipelex.cogt.inference.error_classification import UserAction, UserActionKind+from pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeDeclaration, ErrorCodeSetclass HostedRunError(PipelexError):@@ -12,10 +14,11 @@ class HostedRunError(PipelexError):An error the hosted API answers, or one the pipelex-sdk client raises on the way, keeps the SDK's own class(`ApiResponseError`, `ApiUnreachableError`, `RunFailedError`, …); these are the ones pipelex detects itself: beforeit sends anything, from the verdict of the method's signature, from a connection lost after the run request was- sent, while following a run it started, or when the run is interrupted on this machine.+ sent, while following a run it started, or when the run is interrupted on this machine. Most are the client's own+ findings, so they carry the `client.` codes, which no response is the body of."""- _declared_title = "Hosted run error"+ error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERRORclass HostedBaseUrlError(HostedRunError):@@ -24,7 +27,7 @@ class HostedBaseUrlError(HostedRunError):The message names where the value came from, `--base-url` or `PIPELEX_BASE_URL`, and what an origin looks like."""- error_domain = ErrorDomain.INPUT+ error_code = CoreCode.CLIENT_NOT_CONFIGUREDuser_action = UserAction(kind=UserActionKind.CHANGE_INPUT,detail="Give the hosted API's origin as scheme://host[:port], such as https://api.pipelex.com, in --base-url or PIPELEX_BASE_URL",@@ -40,7 +43,7 @@ class HostedRunSourceError(HostedRunError):directories, or one that cannot be read."""- error_domain = ErrorDomain.INPUT+ error_code = CoreCode.CLIENT_ARGUMENT_INVALID_authors_caller_facing_message: ClassVar[bool] = True@@ -52,7 +55,7 @@ class HostedMethodInvalidError(HostedRunError):could not do: it takes the method's files as bare contents."""- error_domain = ErrorDomain.INPUT+ error_code = CoreCode.METHOD_INVALIDuser_action = UserAction(kind=UserActionKind.CHANGE_INPUT, detail="Fix the method as each validation error says, then run it again")_authors_caller_facing_message: ClassVar[bool] = True@@ -68,7 +71,7 @@ class HostedRunPollingError(HostedRunError):the command again would start another one. The cause is the failure met while following it."""- error_domain = ErrorDomain.RUNTIME+ error_code = CoreCode.CLIENT_FOLLOW_FAILEDdef __init__(self, message: str, *, pipeline_run_id: str):super().__init__(message)@@ -92,7 +95,7 @@ class HostedRunOutcomeUnknownError(HostedRunError):failure or a body that could not be decoded, met after the request left this machine."""- error_domain = ErrorDomain.RUNTIME+ error_code = CoreCode.CLIENT_OUTCOME_UNKNOWNuser_action = UserAction(kind=UserActionKind.UNKNOWN,detail=(@@ -107,10 +110,12 @@ class HostedRunInterruptedError(HostedRunError):Interrupting stops the wait, not the run: a run the hosted API acknowledged keeps going and is paid for, and`pipeline_run_id` finds it again. Interrupted before the acknowledgement, `pipeline_run_id` is `None`, and the- start request may still have reached the hosted API.+ start request may still have reached the hosted API. The code follows: following a started run stopped+ (`client.follow_failed`) once a run id arrived, a call that may have created a run (`client.outcome_unknown`)+ before one did."""- error_domain = ErrorDomain.RUNTIME+ error_code = ErrorCodeSet(default=CoreCode.CLIENT_OUTCOME_UNKNOWN, others=(CoreCode.CLIENT_FOLLOW_FAILED,))_authors_caller_facing_message: ClassVar[bool] = Truedef __init__(self, *, pipeline_run_id: str | None):@@ -130,6 +135,8 @@ class HostedRunInterruptedError(HostedRunError):super().__init__(message)self.pipeline_run_id = pipeline_run_idself.user_action = UserAction(kind=UserActionKind.UNKNOWN, detail=detail)+ if pipeline_run_id is not None:+ self.with_error_code(CoreCode.CLIENT_FOLLOW_FAILED)class HostedLocalFileUploadUnavailableError(HostedRunError):@@ -140,7 +147,7 @@ class HostedLocalFileUploadUnavailableError(HostedRunError):run goes through when the file is given as an https URL, which needs no upload."""- error_domain = ErrorDomain.INPUT+ error_code = CoreCode.REQUEST_UNSUPPORTEDuser_action = UserAction(kind=UserActionKind.CHANGE_INPUT,detail="Pass each local file as an https URL the hosted API can fetch, instead of a path on this machine, then run again",diff --git a/pipelex/kernel/exceptions.py b/pipelex/kernel/exceptions.pyindex ec784b58d..9d6d9a91e 100644--- a/pipelex/kernel/exceptions.py+++ b/pipelex/kernel/exceptions.py@@ -1,30 +1,50 @@-class PromptContentError(ValueError):+from mthds.protocol.problem.registry import CoreCode++from pipelex.base_exceptions import PipelexError+from pipelex.errors.error_code_declaration import ErrorCodeSet+++class PromptContentError(PipelexError):"""A prompt's image or document reference could not be resolved out of working memory.- A `ValueError` rather than a `PipelexError` subclass, matching what the prompt-assembly code- raised before it moved into the kernel: callers that already handle it as a value error keep- working, and nothing in the error taxonomy changes.+ ``runtime.unexpected`` when the reference names nothing the context holds, which load-time validation and the+ entry checks guarantee against, and ``method.wiring_invalid``, chosen by its raise site, when the wired value is+ not the content type the prompt reads."""+ error_code = ErrorCodeSet(default=CoreCode.RUNTIME_UNEXPECTED, others=(CoreCode.METHOD_WIRING_INVALID,))-class JudgmentOutputFieldsError(ValueError):++class JudgmentOutputFieldsError(PipelexError):"""A judgment asking several questions was handed an output class whose fields are not exactly its questions' names.Each question's verdict fills the field of its name, so a question with no field would be answered fornothing and a field no question answers could never be filled. A `PipeJudge` has its output checkedagainst its questions when its method loads, so this is a programmatic caller's contract broken, and- it is raised before the judging model is called. A `ValueError`, as `PromptContentError` is: the- caller handed the kernel a value it cannot work with.+ it is raised before the judging model is called."""+ error_code = CoreCode.RUNTIME_UNEXPECTED+-class TraceContextRunModeError(ValueError):+class TraceContextRunModeError(PipelexError):"""A kernel run was handed a trace context stating a run mode other than the one the run takes.Every trace event of a run states the mode its steps run in, and the usage events of a kernel run state the modeof the trace context its caller supplied. The caller opened that trace, and may share it with writers the kernelnever sees, so the kernel cannot correct it: it refuses the context before any step runs, rather than let the runwrite events that say live while its steps run dry, as a keyless boot forces them to. The mode a run takes is the- one `resolve_effective_run_mode` returns, which is what the caller states on the context. A `ValueError`, as the- other refusals of `PipelexKernel.make` are: the caller handed the kernel a value it cannot work with.+ one `resolve_effective_run_mode` returns, which is what the caller states on the context. Our own host+ integration is that caller, so the refusal is an invariant of ours."""++ error_code = CoreCode.RUNTIME_UNEXPECTED+++class FuncOutputTypeError(PipelexError):+ """A registered function returned a value that is neither a stuff content, a list nor a string.++ The function is the method's, so the step's output is what failed, not the runtime.+ """++ error_code = CoreCode.PIPE_OUTPUT_INVALIDdiff --git a/pipelex/kernel/extract_ops.py b/pipelex/kernel/extract_ops.pyindex 19d556f02..85a020968 100644--- a/pipelex/kernel/extract_ops.py+++ b/pipelex/kernel/extract_ops.py@@ -9,12 +9,14 @@ an image or a document URI is a question about the memory's stuffs and the conceis the caller's business; the kernel takes the `ExtractInput` already built."""+from functools import partialfrom typing import TYPE_CHECKINGfrom pipelex.cogt.content_generation.cogt_run_params import CogtRunParamsfrom pipelex.cogt.extract.extract_input import ExtractInputfrom pipelex.cogt.extract.extract_job_components import ExtractJobConfig, ExtractJobParamsfrom pipelex.cogt.extract.extract_setting import ExtractModelChoice, ExtractSetting+from pipelex.cogt.models.model_deck import resolve_deck_choicefrom pipelex.core.concepts.concept import Conceptfrom pipelex.core.memory.working_memory import WorkingMemoryfrom pipelex.core.stuffs.list_content import ListContent@@ -28,10 +30,17 @@ if TYPE_CHECKING:def resolve_extract_setting(*, extract_choice: ExtractModelChoice | None = None) -> ExtractSetting:- """The deck chain for an extraction: the step's own choice, then the deck's default."""+ """The deck chain for an extraction: the step's own choice, then the deck's default.++ The step's choice that the deck does not resolve is the method's, `model.unknown`; the deck's default is the+ deployment's, `ModelDeckChoiceUnresolvedError`.+ """model_deck = get_model_deck()- resolved_choice = extract_choice or model_deck.extract_choice_default- return model_deck.get_extract_setting(extract_choice=resolved_choice)+ if extract_choice:+ return model_deck.get_extract_setting(extract_choice=extract_choice)+ return resolve_deck_choice(+ deck_setting="extract.choice_default", resolve=partial(model_deck.get_extract_setting, extract_choice=model_deck.extract_choice_default)+ )def build_extract_job_params(diff --git a/pipelex/kernel/func_ops.py b/pipelex/kernel/func_ops.pyindex 4a1f8cf0d..7bac824ea 100644--- a/pipelex/kernel/func_ops.py+++ b/pipelex/kernel/func_ops.py@@ -7,9 +7,11 @@ handed in already resolved. Where a `PipeFunc`'s function comes from, an importits method tree, is the interpreter's business (`pipelex.pipe_operators.func.pipe_func_python`); thekernel is handed the callable, as every other op is handed resolved values.-`call_function` is where the semantics actually live — async-vs-sync dispatch and the-return coercion that lets a function return a bare `str` or a `list` and still produce one-`StuffContent` shape downstream. It is deliberately separate from `run_func`, because the+`call_function` is where the semantics actually live — async-vs-sync dispatch (`invoke_function`) and+the return coercion (`coerce_function_output`) that lets a function return a bare `str` or a `list` and+still produce one `StuffContent` shape downstream. The two are apart so that a caller can tell the+function's own failure from the coercion refusing what it returned, which is the step's output failing.+It is deliberately separate from `run_func`, because theinterpreter's out-of-process executors (a sandbox, a Temporal activity) replace *the call* and keepthe write-back; `run_func` is the in-process composition of the two, and the entry point aprogrammatic caller wants.@@ -28,44 +30,58 @@ from pipelex.core.memory.working_memory import WorkingMemoryfrom pipelex.core.stuffs.list_content import ListContentfrom pipelex.core.stuffs.stuff_content import StuffContentfrom pipelex.core.stuffs.text_content import TextContent+from pipelex.kernel.exceptions import FuncOutputTypeErrorfrom pipelex.kernel.func_results import FuncCallResult, FuncResultfrom pipelex.kernel.memory_ops import store_result-async def call_function(*, function: Callable[..., Any], memory: WorkingMemory, function_name: str | None = None) -> FuncCallResult:- """Run a function against the memory, and coerce what it returns.+async def invoke_function(*, function: Callable[..., Any], memory: WorkingMemory) -> Any:+ """Run a function against the memory, and return what it returned, as it returned it.- The function is arbitrary user code and its failure surface is not enumerable, so nothing is- caught here: a caller that can add context to a failure (the interpreter's operator decorates it- with the step's inputs and declared output) wraps this call instead.-- A sync function runs on a worker thread so it cannot block the event loop. The coercion accepts- the three shapes the language allows an author to return — a `StuffContent`, a list of them, or a- bare `str` — and normalizes them so every caller downstream sees one shape.+ The call alone, apart from the coercion of its result (`coerce_function_output`), so that a caller wrapping the+ function's own failures wraps nothing else. The function is arbitrary user code and its failure surface is not+ enumerable, so nothing is caught here. A sync function runs on a worker thread so it cannot block the event loop.Args:function: The function, called with the memory as its `working_memory` keyword.memory: The working memory the function reads.+ """+ if inspect.iscoroutinefunction(function):+ return await function(working_memory=memory)+ return await asyncio.to_thread(function, working_memory=memory)+++def coerce_function_output(*, function: Callable[..., Any], function_output: Any, function_name: str | None = None) -> FuncCallResult:+ """Coerce what a function returned into one `StuffContent` shape, refusing any other shape as the step's output.++ The coercion accepts the three shapes the language allows an author to return — a `StuffContent`, a list of them,+ or a bare `str` — and normalizes them so every caller downstream sees one shape.++ Args:+ function: The function that returned it, whose module and qualified name ride on the result.+ function_output: What the function returned.function_name: The name the step calls the function by, for messages; its qualified name when not given.++ Raises:+ FuncOutputTypeError: The function returned another shape, or a list holding anything but stuff contents."""label = function_name or getattr(function, "__qualname__", repr(function))- if inspect.iscoroutinefunction(function):- func_output_object = await function(working_memory=memory)- else:- func_output_object = await asyncio.to_thread(function, working_memory=memory)-content: StuffContent- if isinstance(func_output_object, StuffContent):- content = func_output_object- elif isinstance(func_output_object, list):- func_result_list = cast("list[StuffContent]", func_output_object)- content = ListContent(items=func_result_list)- elif isinstance(func_output_object, str):- content = TextContent(text=func_output_object)+ if isinstance(function_output, StuffContent):+ content = function_output+ elif isinstance(function_output, list):+ output_items = cast("list[Any]", function_output)+ for index_item, output_item in enumerate(output_items):+ if not isinstance(output_item, StuffContent):+ msg = f"Function '{label}' must return a list of StuffContent, got {type(output_item)} at index {index_item}"+ raise FuncOutputTypeError(msg)+ content = ListContent(items=cast("list[StuffContent]", output_items))+ elif isinstance(function_output, str):+ content = TextContent(text=function_output)else:- msg = f"Function '{label}' must return a StuffContent or a list, got {type(func_output_object)}"- raise TypeError(msg)+ msg = f"Function '{label}' must return a StuffContent, a list or a string, got {type(function_output)}"+ raise FuncOutputTypeError(msg)return FuncCallResult(content=content,@@ -74,6 +90,25 @@ async def call_function(*, function: Callable[..., Any], memory: WorkingMemory,)+async def call_function(*, function: Callable[..., Any], memory: WorkingMemory, function_name: str | None = None) -> FuncCallResult:+ """Run a function against the memory, and coerce what it returns.++ The composition of `invoke_function` and `coerce_function_output`. Nothing is caught here: a caller that can add+ context to a failure (the interpreter's operator decorates it with the step's inputs and declared output) wraps+ the call instead, and a caller that must tell the function's own failure from the coercion's calls the two apart.++ Args:+ function: The function, called with the memory as its `working_memory` keyword.+ memory: The working memory the function reads.+ function_name: The name the step calls the function by, for messages; its qualified name when not given.++ Raises:+ FuncOutputTypeError: The function returned a shape the coercion refuses.+ """+ function_output = await invoke_function(function=function, memory=memory)+ return coerce_function_output(function=function, function_output=function_output, function_name=function_name)++async def run_func(*,memory: WorkingMemory,diff --git a/pipelex/kernel/img_gen_ops.py b/pipelex/kernel/img_gen_ops.pyindex b85360f6c..42858061e 100644--- a/pipelex/kernel/img_gen_ops.py+++ b/pipelex/kernel/img_gen_ops.py@@ -15,6 +15,7 @@ dispatch — answering them needs something the kernel does not have:when it takes an already-mapped `LlmPromptContent`."""+from functools import partialfrom typing import TYPE_CHECKING, Literalfrom pipelex.cogt.content_generation.cogt_run_params import CogtRunParams@@ -22,6 +23,7 @@ from pipelex.cogt.image.image_size import ImageSizefrom pipelex.cogt.img_gen.img_gen_job_components import AspectRatio, Background, ImgGenJobParams, ImgGenSizefrom pipelex.cogt.img_gen.img_gen_prompt import ImgGenPromptfrom pipelex.cogt.img_gen.img_gen_setting import ImgGenModelChoice, ImgGenSetting+from pipelex.cogt.models.model_deck import resolve_deck_choicefrom pipelex.config import get_configfrom pipelex.core.concepts.concept import Conceptfrom pipelex.core.memory.working_memory import WorkingMemory@@ -38,11 +40,17 @@ if TYPE_CHECKING:def resolve_img_gen_setting(*, img_gen_choice: ImgGenModelChoice | None = None) -> ImgGenSetting:- """The deck chain for an image generation: the step's own choice, then the deck's default."""+ """The deck chain for an image generation: the step's own choice, then the deck's default.++ The step's choice that the deck does not resolve is the method's, `model.unknown`; the deck's default is the+ deployment's, `ModelDeckChoiceUnresolvedError`.+ """model_deck = get_model_deck()if img_gen_choice is not None:return model_deck.get_img_gen_setting(img_gen_choice)- return model_deck.get_img_gen_setting(model_deck.img_gen_choice_default)+ return resolve_deck_choice(+ deck_setting="img_gen.choice_default", resolve=partial(model_deck.get_img_gen_setting, model_deck.img_gen_choice_default)+ )def resolve_default_size(*, explicit_aspect_ratio: AspectRatio | None, default_size: ImgGenSize | None) -> ImgGenSize | None:diff --git a/pipelex/kernel/judgment_ops.py b/pipelex/kernel/judgment_ops.pyindex 68316783e..6bf523ecd 100644--- a/pipelex/kernel/judgment_ops.py+++ b/pipelex/kernel/judgment_ops.py@@ -16,6 +16,7 @@ A step asks one question, `run_judgment`, whose verdict native is the result, orjudging model, every question answered independently over the same evidence."""+from functools import partialfrom typing import NamedTuplefrom pydantic import BaseModel, ConfigDict@@ -38,6 +39,7 @@ from pipelex.cogt.judgment.judgment_models import (from pipelex.cogt.judgment.judgment_setting import JudgmentModelChoice, JudgmentSettingfrom pipelex.cogt.model_backends.model_spec import InferenceModelSpecfrom pipelex.cogt.model_backends.model_type import ModelType+from pipelex.cogt.models.model_deck import resolve_deck_choicefrom pipelex.cogt.models.model_reference import write_model_handlefrom pipelex.cogt.templating.template_rendering import render_templatefrom pipelex.core.concepts.concept import Concept@@ -95,10 +97,14 @@ def judgment_setting_of_choice(*, judgment_choice: JudgmentModelChoice | None =which no backend may serve on this boot."""model_deck = get_model_deck()- resolved_choice = judgment_choice or model_deck.judgment_choice_default- if resolved_choice is None:+ if judgment_choice:+ return model_deck.get_judgment_setting(judgment_choice=judgment_choice)+ if (judgment_choice_default := model_deck.judgment_choice_default) is None:raise JudgmentModelMissingError(pipe_code=pipe_code)- return model_deck.get_judgment_setting(judgment_choice=resolved_choice)+ # The deck's own default, so a miss is the deployment's, not the method's.+ return resolve_deck_choice(+ deck_setting="judgment.choice_default", resolve=partial(model_deck.get_judgment_setting, judgment_choice=judgment_choice_default)+ )def served_judgment_model(*, model_handle: str) -> InferenceModelSpec | None:diff --git a/pipelex/kernel/llm_ops.py b/pipelex/kernel/llm_ops.pyindex d37a9c371..ce23b49ee 100644--- a/pipelex/kernel/llm_ops.py+++ b/pipelex/kernel/llm_ops.py@@ -16,6 +16,7 @@ Two seams are deliberately *not* here, because they are the caller's job by consalways has; the kernel has no pipe to name."""+from functools import partialfrom typing import Anyfrom pipelex import log@@ -26,6 +27,7 @@ from pipelex.cogt.llm.llm_setting import LLMModelChoice, LLMSettingfrom pipelex.cogt.llm.llm_worker_abstract import LLMWorkerAbstractfrom pipelex.cogt.model_backends.model_spec import InferenceModelSpecfrom pipelex.cogt.model_backends.model_type import ModelType+from pipelex.cogt.models.model_deck import resolve_deck_choicefrom pipelex.cogt.models.model_reference import ModelReferenceKind, ensure_model_referencefrom pipelex.cogt.templating.template_rendering import render_templatefrom pipelex.config import get_config@@ -41,15 +43,26 @@ from pipelex.system.exceptions import MissingDependencyErrorfrom pipelex.system.job_metadata import JobMetadatafrom pipelex.system.telemetry.otel_constants import GenAISpanAttrfrom pipelex.tools.jinja2.template_category import TemplateCategory+from pipelex.tools.jinja2.template_owner import TemplateOwnerfrom pipelex.tools.templating.templating_style import TemplatingStylefrom pipelex.tools.typing.structure_printer import StructurePrinterdef resolve_llm_setting_for_text(*, llm_choice: LLMModelChoice | None = None) -> LLMSetting:- """The deck chain for a text output: the step's own choice, then the deck's override, then its default."""+ """The deck chain for a text output: the step's own choice, then the deck's override, then its default.++ A choice the step names that the deck does not resolve is the method's, `model.unknown`; the deck's own override+ or default is the deployment's, `ModelDeckChoiceUnresolvedError`.+ """model_deck = get_model_deck()- resolved_choice = llm_choice or model_deck.llm_choice_overrides.for_text or model_deck.llm_choice_defaults.for_text- return model_deck.get_llm_setting(llm_choice=resolved_choice)+ if llm_choice:+ return model_deck.get_llm_setting(llm_choice=llm_choice)+ if override := model_deck.llm_choice_overrides.for_text:+ return resolve_deck_choice(deck_setting="llm.choice_overrides.for_text", resolve=partial(model_deck.get_llm_setting, llm_choice=override))+ return resolve_deck_choice(+ deck_setting="llm.choice_defaults.for_text",+ resolve=partial(model_deck.get_llm_setting, llm_choice=model_deck.llm_choice_defaults.for_text),+ )def resolve_llm_setting_for_object(*, llm_choice: LLMModelChoice | None = None, llm_choice_for_text: LLMModelChoice | None = None) -> LLMSetting:@@ -59,10 +72,19 @@ def resolve_llm_setting_for_object(*, llm_choice: LLMModelChoice | None = None,for text only still generates its objects with that model, so `llm_choice_for_text` is consultedbefore the deck's own object override. A caller with no text choice (a step that only everproduces objects) leaves it unset and gets the plain override-then-default chain.++ Either choice of the step's that the deck does not resolve is the method's, `model.unknown`; the deck's own+ override or default is the deployment's, `ModelDeckChoiceUnresolvedError`."""model_deck = get_model_deck()- resolved_choice = llm_choice or llm_choice_for_text or model_deck.llm_choice_overrides.for_object or model_deck.llm_choice_defaults.for_object- return model_deck.get_llm_setting(llm_choice=resolved_choice)+ if step_choice := llm_choice or llm_choice_for_text:+ return model_deck.get_llm_setting(llm_choice=step_choice)+ if override := model_deck.llm_choice_overrides.for_object:+ return resolve_deck_choice(deck_setting="llm.choice_overrides.for_object", resolve=partial(model_deck.get_llm_setting, llm_choice=override))+ return resolve_deck_choice(+ deck_setting="llm.choice_defaults.for_object",+ resolve=partial(model_deck.get_llm_setting, llm_choice=model_deck.llm_choice_defaults.for_object),+ )def served_llm_model(*, model_handle: str) -> InferenceModelSpec | None:@@ -194,7 +216,8 @@ async def derive_structure_prompt(*, output_class: type[StuffContent], templatinIt renders under a style like every other prompt fragment: the shipped template uses no taggingfilter, but the template is config-editable, and one that reached this render style-less could- not use one at all.+ not use one at all. The template is Pipelex's own, not the method's, so a failure to render it is+ ours, ``runtime.unexpected``, never the method's ``method.template_invalid``."""llm_config = get_config().inference.llmif not llm_config.is_structure_prompt_enabled:@@ -207,6 +230,7 @@ async def derive_structure_prompt(*, output_class: type[StuffContent], templatincategory=TemplateCategory.LLM_PROMPT,context={"class_structure_str": "\n".join(class_structure)},templating_style=templating_style,+ template_owner=TemplateOwner.PIPELEX,)diff --git a/pipelex/kernel/prompt_assembly.py b/pipelex/kernel/prompt_assembly.pyindex 7559725bc..47ed52929 100644--- a/pipelex/kernel/prompt_assembly.py+++ b/pipelex/kernel/prompt_assembly.py@@ -29,6 +29,7 @@ substituted as a parameter, a dotted path included.from collections.abc import Sequencefrom typing import Any, Self, cast+from mthds.protocol.problem.registry import CoreCodefrom pydantic import BaseModel, ConfigDictfrom pipelex.cogt.document.prompt_document import PromptDocument@@ -244,10 +245,10 @@ class PromptFiles:)except ContextProviderError as exc:msg = f"Could not find image '{image_reference.variable_path}' in context: {exc}"- raise PromptContentError(msg) from exc+ raise PromptContentError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED) from excif not isinstance(image_content, ImageContent):msg = f"Image reference '{image_reference.variable_path}' is of type '{type(image_content).__name__}', expected ImageContent"- raise PromptContentError(msg)+ raise PromptContentError(msg).with_error_code(CoreCode.METHOD_WIRING_INVALID)self._image_registry_indices[image_reference.variable_path] = self._image_registry.register_image(image_content)def _register_direct_list_images(self, *, image_reference: ImageReference, context_provider: ContextProviderAbstract) -> None:@@ -259,17 +260,17 @@ class PromptFiles:)except ContextProviderError as exc:msg = f"Could not find image list '{image_reference.variable_path}' in context: {exc}"- raise PromptContentError(msg) from exc+ raise PromptContentError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED) from excif not isinstance(image_items, (list, tuple)):msg = (f"Image list reference '{image_reference.variable_path}' is of type '{type(image_items).__name__}', ""expected list or tuple of ImageContent")- raise PromptContentError(msg)+ raise PromptContentError(msg).with_error_code(CoreCode.METHOD_WIRING_INVALID)for list_position, image_item in enumerate(cast("list[Any] | tuple[Any, ...]", image_items), start=1):if not isinstance(image_item, ImageContent):msg = f"Item of '{image_reference.variable_path}' is of type '{type(image_item).__name__}', expected ImageContent"- raise PromptContentError(msg)+ raise PromptContentError(msg).with_error_code(CoreCode.METHOD_WIRING_INVALID)# Keyed by the 1-based list position, numbered by the registry index.self._image_registry_indices[f"{image_reference.variable_path}[{list_position}]"] = self._image_registry.register_image(image_item)@@ -282,10 +283,10 @@ class PromptFiles:)except ContextProviderError as exc:msg = f"Could not find document '{document_reference.variable_path}' in context: {exc}"- raise PromptContentError(msg) from exc+ raise PromptContentError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED) from excif not isinstance(document_content, DocumentContent):msg = f"Document reference '{document_reference.variable_path}' is of type '{type(document_content).__name__}', expected DocumentContent"- raise PromptContentError(msg)+ raise PromptContentError(msg).with_error_code(CoreCode.METHOD_WIRING_INVALID)self._documents[document_reference.variable_path] = PromptDocumentFactory.make_prompt_document(uri=document_content.url,mime_type=document_content.mime_type,@@ -300,17 +301,17 @@ class PromptFiles:)except ContextProviderError as exc:msg = f"Could not find document list '{document_reference.variable_path}' in context: {exc}"- raise PromptContentError(msg) from exc+ raise PromptContentError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED) from excif not isinstance(document_items, (list, tuple)):msg = (f"Document list reference '{document_reference.variable_path}' is of type '{type(document_items).__name__}', ""expected list or tuple of DocumentContent")- raise PromptContentError(msg)+ raise PromptContentError(msg).with_error_code(CoreCode.METHOD_WIRING_INVALID)for list_position, document_item in enumerate(cast("list[Any] | tuple[Any, ...]", document_items), start=1):if not isinstance(document_item, DocumentContent):msg = f"Item of '{document_reference.variable_path}' is of type '{type(document_item).__name__}', expected DocumentContent"- raise PromptContentError(msg)+ raise PromptContentError(msg).with_error_code(CoreCode.METHOD_WIRING_INVALID)self._documents[f"{document_reference.variable_path}[{list_position}]"] = PromptDocumentFactory.make_prompt_document(uri=document_item.url,mime_type=document_item.mime_type,diff --git a/pipelex/kernel/search_ops.py b/pipelex/kernel/search_ops.pyindex b7de7ff62..30d2af78f 100644--- a/pipelex/kernel/search_ops.py+++ b/pipelex/kernel/search_ops.py@@ -10,9 +10,12 @@ it, leave it out and it comes back as a sourced answer. Resolving a concept to tlibrary's business, so the kernel never asks for one."""+from functools import partial+from pipelex.cogt.content_generation.assignment_models import SearchAssignmentfrom pipelex.cogt.content_generation.cogt_run_params import CogtRunParamsfrom pipelex.cogt.model_backends.model_type import ModelType+from pipelex.cogt.models.model_deck import resolve_deck_choicefrom pipelex.cogt.models.model_reference import write_model_handlefrom pipelex.cogt.search.search_setting import SearchModelChoice, SearchSettingfrom pipelex.cogt.templating.template_rendering import render_template@@ -38,10 +41,18 @@ def resolve_search_setting(The middle step is the one worth naming: the deck's setting may name a waterfall or an alias, andthe returned setting is pinned to the *resolved* handle so it doubles as a distributed run'srouting key. A caller that skipped it would route on a name no worker recognises.++ The step's choice that the deck does not resolve is the method's, `model.unknown`; the deck's default is the+ deployment's, `ModelDeckChoiceUnresolvedError`."""model_deck = get_model_deck()- resolved_choice = search_choice or model_deck.search_choice_default- search_setting = model_deck.get_search_setting(search_choice=resolved_choice)+ search_setting: SearchSetting+ if search_choice:+ search_setting = model_deck.get_search_setting(search_choice=search_choice)+ else:+ search_setting = resolve_deck_choice(+ deck_setting="search.choice_default", resolve=partial(model_deck.get_search_setting, search_choice=model_deck.search_choice_default)+ )inference_model = model_deck.get_required_inference_model(model_handle=search_setting.model, model_type=ModelType.SEARCH)# Pinned as a reference that parses back to the resolved handle, whatever its spelling, since every lookup reads it again.diff --git a/pipelex/kit/exceptions.py b/pipelex/kit/exceptions.pyindex ead7484a8..8b3ed2af7 100644--- a/pipelex/kit/exceptions.py+++ b/pipelex/kit/exceptions.py@@ -1,9 +1,21 @@+from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import PipelexErrorclass KitError(PipelexError):- pass+ """Raised when the kit's agent rules cannot be assembled.++ Developer tooling: reached only from `pipelex-dev kit`.+ """++ error_code = CoreCode.RUNTIME_UNEXPECTEDclass KitIndexLoadingError(PipelexError):- pass+ """Raised when the kit's index of agent rules cannot be loaded.++ Developer tooling: reached only from `pipelex-dev kit` and the rules sync check.+ """++ error_code = CoreCode.RUNTIME_UNEXPECTEDdiff --git a/pipelex/libraries/concept/concept_library.py b/pipelex/libraries/concept/concept_library.pyindex 44c1a6176..28dfbdeec 100644--- a/pipelex/libraries/concept/concept_library.py+++ b/pipelex/libraries/concept/concept_library.py@@ -1,6 +1,7 @@from typing import Any, Callable, Self, castfrom kajson.exceptions import ClassRegistryInheritanceError, ClassRegistryNotFoundError+from mthds.protocol.problem.registry import CoreCodefrom pydantic import Field, RootModel, model_validatorfrom typing_extensions import override@@ -106,7 +107,7 @@ class ConceptLibrary(RootModel[ConceptLibraryRoot], ConceptLibraryAbstract):def add_new_concept(self, concept: Concept):if concept.concept_ref in self.root:msg = f"Concept '{concept.concept_ref}' already exists in the library"- raise ConceptLibraryError(msg)+ raise ConceptLibraryError(msg).with_error_code(CoreCode.METHOD_NAME_CONFLICT)self.root[concept.concept_ref] = conceptself._mark_changed()@@ -223,7 +224,7 @@ class ConceptLibrary(RootModel[ConceptLibraryRoot], ConceptLibraryAbstract):the_native_concept = self.get_optional_concept(f"{SpecialDomain.NATIVE}.{native_concept}")if not the_native_concept:msg = f"Native concept '{native_concept}' not found in the library"- raise ConceptLibraryConceptNotFoundError(msg)+ raise ConceptLibraryConceptNotFoundError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)return the_native_conceptdef get_native_concepts(self) -> list[Concept]:@@ -366,7 +367,7 @@ class ConceptLibrary(RootModel[ConceptLibraryRoot], ConceptLibraryAbstract):key = f"{alias}->{concept.concept_ref}"if key in self.root:msg = f"Dependency concept '{key}' already exists in the library"- raise ConceptLibraryError(msg)+ raise ConceptLibraryError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)self.root[key] = conceptself._mark_changed()diff --git a/pipelex/libraries/concept/exceptions.py b/pipelex/libraries/concept/exceptions.pyindex f779a0b7c..124ae74d7 100644--- a/pipelex/libraries/concept/exceptions.py+++ b/pipelex/libraries/concept/exceptions.py@@ -1,3 +1,6 @@+from mthds.protocol.problem.registry import CoreCode++from pipelex.errors.error_code_declaration import ErrorCodeSetfrom pipelex.libraries.exceptions import LibraryLoadingError@@ -11,4 +14,13 @@ class ConceptLibraryError(LibraryLoadingError):pipe/field and the missing concept) rather than a bare message-only residual.Call sites that only pass a message keep working: the structured lists defaultto empty, so those raises behave exactly as before (one fallback residual).++ The default ``method.concept_unresolved`` is a reference to a concept nothing declares; a raise site chooses+ ``method.name_conflict`` for two declarations of one concept, and ``runtime.unexpected`` for an invariant of the+ crate."""++ error_code = ErrorCodeSet(+ default=CoreCode.METHOD_CONCEPT_UNRESOLVED,+ others=(CoreCode.METHOD_NAME_CONFLICT, CoreCode.RUNTIME_UNEXPECTED),+ )diff --git a/pipelex/libraries/crate_normalization.py b/pipelex/libraries/crate_normalization.pyindex 100aeeada..900993909 100644--- a/pipelex/libraries/crate_normalization.py+++ b/pipelex/libraries/crate_normalization.py@@ -35,6 +35,8 @@ are not yet applied here, mirroring the spec's own "Specification Status" calloufrom typing import NamedTuple+from mthds.protocol.problem.registry import CoreCode+from pipelex.codegen.native_expansion import collect_native_refs_from_structure, materialize_native_conceptfrom pipelex.core.concepts.concept_blueprint import ConceptBlueprintfrom pipelex.core.concepts.concept_structure_blueprint import ConceptStructureBlueprint@@ -172,7 +174,7 @@ def _resolve_refinement(first_index = cycle.index(first_ref)ordered_cycle = cycle[first_index:] + cycle[:first_index] + [first_ref]msg = f"Refinement cycle detected: {' -> '.join(ordered_cycle)}"- raise CrateNormalizationError(msg)+ raise CrateNormalizationError(msg).with_error_code(CoreCode.METHOD_CYCLE)path_index_by_ref[current_ref] = len(path)path.append(current_ref)diff --git a/pipelex/libraries/domain/exceptions.py b/pipelex/libraries/domain/exceptions.pyindex ee2dfb1a7..005c30fa7 100644--- a/pipelex/libraries/domain/exceptions.py+++ b/pipelex/libraries/domain/exceptions.py@@ -1,5 +1,9 @@+from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import PipelexErrorclass DomainLibraryError(PipelexError):- pass+ """A domain the library is asked for or asked to remove that it does not hold, which no caller reaches but by a bug."""++ error_code = CoreCode.RUNTIME_UNEXPECTEDdiff --git a/pipelex/libraries/exceptions.py b/pipelex/libraries/exceptions.pyindex cd026b6c2..30ccb6b5c 100644--- a/pipelex/libraries/exceptions.py+++ b/pipelex/libraries/exceptions.py@@ -1,15 +1,34 @@-from pipelex.base_exceptions import ErrorDomain, PipelexError+from typing import ClassVar++from mthds.protocol.problem.registry import CoreCode++from pipelex.base_exceptions import PipelexErrorfrom pipelex.core.exceptions import PipelexBundleBlueprintValidationErrorData, PipesAndConceptValidationErrorData+from pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeDeclaration, ErrorCodeSet+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodeclass LibraryError(PipelexError):- _declared_title = "Library error"+ """A library that cannot hold what it is asked to hold.++ The default ``runtime.unexpected`` is an invariant of the library manager, such as a library id that does not+ exist; a raise site that finds a fault of the request, of the method or of the library directories chooses+ ``request.invalid``, ``method.concept_unresolved`` or ``pipelex.config.invalid``.+ """++ error_code: ClassVar[ErrorCodeDeclaration] = ErrorCodeSet(+ default=CoreCode.RUNTIME_UNEXPECTED,+ others=(CoreCode.REQUEST_INVALID, CoreCode.METHOD_CONCEPT_UNRESOLVED, PipelexErrorCode.CONFIG_INVALID),+ )class CrateNormalizationError(LibraryError):- """Raised when a library crate cannot be normalized (e.g. a non-domain-qualified key, or a pipe ref matching no crate pipe, or several)."""+ """Raised when a library crate cannot be normalized (e.g. a non-domain-qualified key, or a pipe ref matching no crate pipe, or several).++ A key the crate builder failed to qualify is an invariant; a refinement cycle chooses ``method.cycle``.+ """- _declared_title = "Crate normalization error"+ error_code = ErrorCodeSet(default=CoreCode.RUNTIME_UNEXPECTED, others=(CoreCode.METHOD_CYCLE,))class LibraryLoadingError(LibraryError):@@ -27,8 +46,23 @@ class LibraryLoadingError(LibraryError):Also handles:- Factory errors (Domain, Concept, Pipe)- Interpreter errors (blueprint parsing)++ The default ``method.invalid`` is the umbrella whose items carry their own codes; a raise site that finds one+ fault chooses its code."""+ error_code: ClassVar[ErrorCodeDeclaration] = ErrorCodeSet(+ default=CoreCode.METHOD_INVALID,+ others=(+ CoreCode.METHOD_CYCLE,+ CoreCode.METHOD_NAME_CONFLICT,+ CoreCode.METHOD_PIPE_NOT_EXPORTED,+ CoreCode.METHOD_DEPENDENCY_MISSING,+ CoreCode.METHOD_CONCEPT_INVALID,+ CoreCode.METHOD_NOT_FOUND,+ ),+ )+def __init__(self,message: str,@@ -47,46 +81,6 @@ class LibraryLoadingError(LibraryError):super().__init__(message)-class DomainLoadingError(LibraryLoadingError):- def __init__(self, message: str, domain_code: str, description: str, source: str | None = None):- self.domain_code = domain_code- self.description = description- self.source = source- super().__init__(message)---class ConceptLoadingError(LibraryLoadingError):- def __init__(- self,- message: str,- concept_code: str,- description: str,- source: str | None = None,- original_error: Exception | None = None,- ):- self.concept_code = concept_code- self.description = description- self.source = source- self.original_error = original_error- super().__init__(message)---class PipeLoadingError(LibraryLoadingError):- def __init__(- self,- message: str,- pipe_code: str,- description: str,- source: str | None = None,- original_error: Exception | None = None,- ):- self.pipe_code = pipe_code- self.description = description- self.source = source- self.original_error = original_error- super().__init__(message)--class MethodTreeLoadError(LibraryLoadingError):"""Raised when a method tree a load reads from this host's disk cannot be listed.@@ -97,8 +91,7 @@ class MethodTreeLoadError(LibraryLoadingError):is theirs to read, and the same load is refused again until the tree changes."""- error_domain = ErrorDomain.INPUT- retryable = False+ error_code = CoreCode.METHOD_PACKAGE_INVALID_authors_caller_facing_message = True@@ -107,9 +100,12 @@ class EmptyMethodTreeError(MethodTreeLoadError):The membership rule keeps every file of the folder out of its method tree, which holds at least one, or none of thefiles it keeps is a bundle. A command handed the folder finds nothing to judge and no pipe to start at: it reports- the folder as holding no bundle rather than as a method refused.+ the folder as holding no bundle rather than as a method refused. It carries ``method.invalid``, as a method entry+ holding no bundle does."""+ error_code = CoreCode.METHOD_INVALID+class HostLibraryTreeError(PipelexError):"""Raised when a library directory of this host, one a load reads beside a caller's bundles, cannot be read as a method tree.@@ -120,8 +116,7 @@ class HostLibraryTreeError(PipelexError):caller-facing. It is deliberately no `LibraryError`, which a validation would report as the caller's invalid bundle."""- error_domain = ErrorDomain.CONFIG- retryable = False+ error_code = PipelexErrorCode.CONFIG_INVALIDclass MethodRequirementsError(LibraryLoadingError):@@ -133,8 +128,7 @@ class MethodRequirementsError(LibraryLoadingError):(`reporting_host_library_tree_faults`)."""- error_domain = ErrorDomain.INPUT- retryable = False+ error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERROR_authors_caller_facing_message = Truedef __init__(self, message: str, *, items: list[PipelexBundleBlueprintValidationErrorData]):@@ -148,6 +142,8 @@ class MethodRequirementsFileError(MethodRequirementsError):`-r`, `-e` or `--index-url`, a comment after a requirement and a line continued with a backslash are refused."""+ error_code = CoreCode.METHOD_PACKAGE_INVALID+class MethodRequirementsNotMetError(MethodRequirementsError):"""Raised when the Python environment a method's PipeFunc steps run in does not satisfy its `requirements.txt`.@@ -158,6 +154,8 @@ class MethodRequirementsNotMetError(MethodRequirementsError):refuses the requirements because no environment it can build holds them, carries the deployment's own reason."""+ error_code = CoreCode.METHOD_DEPENDENCY_MISSING+class HostLibraryRequirementsError(PipelexError):"""Raised when a method of this host's own library directories, loaded beside a caller's bundles, is refused for its requirements.@@ -168,8 +166,7 @@ class HostLibraryRequirementsError(PipelexError):the host, is not caller-facing. Like `HostLibraryTreeError`, it is deliberately no `LibraryError`."""- error_domain = ErrorDomain.CONFIG- retryable = False+ error_code = PipelexErrorCode.CONFIG_INVALIDclass PipeFuncPackageSetUnstatedError(PipelexError):@@ -182,8 +179,7 @@ class PipeFuncPackageSetUnstatedError(PipelexError):the caller's invalid bundle, and its message is not caller-facing."""- error_domain = ErrorDomain.CONFIG- retryable = False+ error_code = CoreCode.RUNTIME_MISCONFIGUREDdef __init__(self, *, execution_mode: str, offer_registered: bool):self.execution_mode = execution_modediff --git a/pipelex/libraries/library.py b/pipelex/libraries/library.pyindex 56b8abc40..f05d335e1 100644--- a/pipelex/libraries/library.py+++ b/pipelex/libraries/library.py@@ -3,12 +3,14 @@ from pathlib import Pathfrom typing import TYPE_CHECKINGfrom kajson.class_registry import ClassRegistry+from mthds.protocol.problem.registry import CoreCodefrom pydantic import BaseModel, Field, PrivateAttrfrom pipelex import logfrom pipelex.base_exceptions import PipelexUnexpectedErrorfrom pipelex.core.exceptions import PipesAndConceptValidationErrorData-from pipelex.core.qualified_ref import QualifiedRef, QualifiedRefError+from pipelex.core.qualified_ref import QualifiedRef+from pipelex.core.qualified_ref_exceptions import QualifiedRefErrorfrom pipelex.libraries.concept.concept_library import ConceptLibraryfrom pipelex.libraries.concept.exceptions import ConceptLibraryErrorfrom pipelex.libraries.domain.domain_library import DomainLibrary@@ -362,7 +364,7 @@ class Library(BaseModel):f"Concept '{concept.concept_ref}' refines cross-package concept '{concept.refines}' "f"but '{remainder}' was not found in dependency '{alias}'")- raise LibraryError(msg)+ raise LibraryError(msg).with_error_code(CoreCode.METHOD_CONCEPT_UNRESOLVED)log.verbose(f"The validation of concept '{concept.concept_ref}' was skipped: it refines cross-package concept "f"'{concept.refines}' from unloaded dependency '{alias}'"diff --git a/pipelex/libraries/library_crate_factory.py b/pipelex/libraries/library_crate_factory.pyindex ba497db35..3c8ab18df 100644--- a/pipelex/libraries/library_crate_factory.py+++ b/pipelex/libraries/library_crate_factory.py@@ -1,5 +1,7 @@from typing import TYPE_CHECKING, NamedTuple+from mthds.protocol.problem.registry import CoreCode+from pipelex.core.concepts.concept_factory import ConceptFactoryfrom pipelex.core.domains.domain_blueprint import DomainBlueprintfrom pipelex.libraries.collision_messages import duplicate_ref_msg@@ -119,7 +121,7 @@ class LibraryCrateFactory:existing_source=source_map.get(concept_ref),incoming_source=source,)- )+ ).with_error_code(CoreCode.METHOD_NAME_CONFLICT)concepts[concept_ref] = valueif source:source_map[concept_ref] = source@@ -221,7 +223,9 @@ class LibraryCrateFactory:# At least one is a signature: the declarations' contracts must match (normalized identity).if not contracts_match(existing=existing.blueprint, incoming=incoming.blueprint, domain_code=domain_code):- raise PipeLibraryError(cls._contract_mismatch_msg(pipe_ref=pipe_ref, existing=existing, incoming=incoming))+ raise PipeLibraryError(cls._contract_mismatch_msg(pipe_ref=pipe_ref, existing=existing, incoming=incoming)).with_error_code(+ CoreCode.METHOD_SIGNATURE_MISMATCH+ )# A concrete definition beats a forward declaration.if existing_is_signature and not incoming_is_signature:diff --git a/pipelex/libraries/library_manager.py b/pipelex/libraries/library_manager.pyindex 7cfbfded2..67884e950 100644--- a/pipelex/libraries/library_manager.py+++ b/pipelex/libraries/library_manager.py@@ -13,6 +13,7 @@ from mthds.package.dependency_resolver import ResolvedDependency, determine_expofrom mthds.package.discovery import find_package_manifestfrom mthds.package.exceptions import DependencyResolveError, ManifestErrorfrom mthds.package.manifest.schema import MTHDS_STANDARD_VERSION, MethodsManifest+from mthds.protocol.problem.registry import CoreCodefrom pydantic import BaseModel, PydanticUserError, ValidationErrorfrom typing_extensions import override@@ -88,7 +89,8 @@ from pipelex.runtime_hub import get_class_registryfrom pipelex.system.registries.class_registry_utils import ClassRegistryUtilsfrom pipelex.tools.log.error_fields import error_fieldsfrom pipelex.tools.log.log_fields import USER_ACTION_FIELD-from pipelex.tools.misc.semver import SemVerError, parse_constraint, parse_version, version_satisfies+from pipelex.tools.misc.exceptions import SemVerError+from pipelex.tools.misc.semver import parse_constraint, parse_version, version_satisfiesfrom pipelex.validation_error_types import PipeValidationErrorTypeif TYPE_CHECKING:@@ -161,7 +163,9 @@ def _parse_dependency_bundle(*, mthds_path: Path, bundle_source: str, package_admthds_content = mthds_path.read_text(encoding="utf-8")except UnicodeDecodeError as exc:msg = f"Bundle '{bundle_source}' of method package '{package_address}' is not valid UTF-8."- raise MthdsParserError(msg, validation_errors=[PipelexBundleBlueprintValidationErrorData(source=bundle_source, message=msg)]) from exc+ raise MthdsParserError(msg, validation_errors=[PipelexBundleBlueprintValidationErrorData(source=bundle_source, message=msg)]).with_error_code(+ CoreCode.METHOD_DEPENDENCY_INVALID+ ) from exctry:return MthdsParser.make_pipelex_bundle_blueprint(mthds_content=mthds_content, mthds_source=bundle_source)except MthdsParserError as exc:@@ -172,7 +176,7 @@ def _parse_dependency_bundle(*, mthds_path: Path, bundle_source: str, package_admsg = f"{context}: {exc.message}"raise MthdsParserError(msg, validation_errors=items or [PipelexBundleBlueprintValidationErrorData(source=bundle_source, message=msg)]- ) from exc+ ).with_error_code(CoreCode.METHOD_DEPENDENCY_INVALID) from excdef _public_dependency_pipe_refs(*, resolved_dep: ResolvedDependency, blueprints: list[PipelexBundleBlueprint]) -> set[str] | None:@@ -302,8 +306,8 @@ def _locating_pipe_build_refusals(as a ``PipeLoadRefusalError`` naming the pipe and the file, ``from`` the original.- Everything else leaves untouched: a configuration or runtime fault keeps its identity and stays ano-verdict fault, a security refusal is never absorbed into a verdict, a library error keeps the- structured items its own arm forwards, and pydantic's ``ValidationError`` and the- ``PipeValidationError`` family (not ``PipelexError``s) keep their categorizers.+ structured items its own arm forwards, and pydantic's ``ValidationError`` and a+ ``PipeValidationError``, whose own arm locates it, keep their categorizers.A synthetic helper the bundle elaborator generated (the ``<code>__draft_text`` and ``<code>__structure``pipes of a ``preliminary_text`` PipeLLM) is not in the author's file, so its refusal is located on@@ -320,7 +324,7 @@ def _locating_pipe_build_refusals(if relocated is model_choice_error:raiseraise relocated from model_choice_error- except (SecurityError, LibraryError):+ except (SecurityError, LibraryError, PipeValidationError):raiseexcept PipelexError as refusal:if not error_domain_is_input(refusal.to_error_report().error_domain):@@ -638,13 +642,13 @@ class LibraryManager(LibraryManagerAbstract):"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)+ raise BundleResourcePathError(msg).with_error_code(CoreCode.REQUEST_INVALID)joined[path] = held_filecollisions = 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)+ raise BundleResourcePathError(msg).with_error_code(CoreCode.REQUEST_INVALID)return joineddef _submitted_tree(self, *, library_id: str) -> MethodTree | None:@@ -970,7 +974,7 @@ class LibraryManager(LibraryManagerAbstract):parsed = QualifiedRef.parse_pipe_ref(raw=pipe_ref)if parsed.domain_path is None:msg = f"Crate pipe_ref '{pipe_ref}' must be domain-qualified"- raise PipeLibraryError(msg)+ raise PipeLibraryError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)domain_code = parsed.domain_pathpipe_code = parsed.local_code@@ -1156,7 +1160,7 @@ class LibraryManager(LibraryManagerAbstract):existing_source=str(existing_source) if existing_source else None,incoming_source=str(new_source) if new_source else None,)- )+ ).with_error_code(CoreCode.METHOD_NAME_CONFLICT)concept_source_in_this_load[concept_ref] = new_sourceref_to_entry[concept_ref] = (blueprint.domain,@@ -1194,7 +1198,7 @@ class LibraryManager(LibraryManagerAbstract):parsed = QualifiedRef.parse_concept_ref(raw=concept_ref)if parsed.domain_path is None:msg = f"Crate concept_ref '{concept_ref}' must be domain-qualified"- raise ConceptLibraryError(msg)+ raise ConceptLibraryError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)ref_to_entry[concept_ref] = (parsed.domain_path,parsed.local_code,@@ -1249,7 +1253,7 @@ class LibraryManager(LibraryManagerAbstract):sorted_refs = list(sorter.static_order())except CycleError as exc:msg = f"Cycle detected in concept refines dependencies: {exc.args[1]}"- raise LibraryLoadingError(msg) from exc+ raise LibraryLoadingError(msg).with_error_code(CoreCode.METHOD_CYCLE) from excall_concepts: list[Concept] = []for concept_ref in sorted_refs:@@ -1328,7 +1332,7 @@ class LibraryManager(LibraryManagerAbstract):blueprint.place_in_tree(tree_bundle=bundle_file.tree_bundle)except FileNotFoundError as file_not_found_error:msg = f"Could not find MTHDS bundle at '{bundle_source}'"- raise LibraryLoadingError(msg) from file_not_found_error+ raise LibraryLoadingError(msg).with_error_code(CoreCode.METHOD_NOT_FOUND) from file_not_found_errorexcept MthdsParserError as parser_error:# Forward BLUEPRINT validation errors from interpretermsg = f"Could not load MTHDS bundle from '{bundle_source}' because of: {parser_error.message}"@@ -1399,13 +1403,20 @@ class LibraryManager(LibraryManagerAbstract):# items that make an unresolved concept a categorized `unresolved_concept` rather than a# bare residual. Reconstructing it message-only silently dropped them.msg = f"Could not load blueprints from {bundle_sources} because of: {ref_error}"+ # The new error keeps the code its raise site chose, which a fresh instance of the class would not carry.+ rewrapped_error: ConceptLibraryError | PipeLibraryErrorif isinstance(ref_error, LibraryLoadingError):- raise type(ref_error)(+ rewrapped_error = type(ref_error)(msg,blueprint_validation_errors=ref_error.blueprint_validation_errors,pipe_concept_validation_errors=ref_error.pipe_concept_validation_errors,- ) from ref_error- raise type(ref_error)(msg) from ref_error+ )+ else:+ rewrapped_error = type(ref_error)(msg)+ chosen_code = ref_error.own_error_code+ if chosen_code is not None:+ rewrapped_error.with_error_code(chosen_code)+ raise rewrapped_error from ref_errordef _warn_if_mthds_version_unsatisfied(self,@@ -1468,7 +1479,7 @@ class LibraryManager(LibraryManagerAbstract):error_messages = [err.message for err in reserved_errors]joined_errors = "\n - ".join(error_messages)msg = f"Reserved domain violations found:\n - {joined_errors}"- raise LibraryLoadingError(msg) from exc+ raise LibraryLoadingError(msg).with_error_code(CoreCode.METHOD_NAME_CONFLICT) from excreturn Noneif manifest is None:@@ -1479,7 +1490,7 @@ class LibraryManager(LibraryManagerAbstract):error_messages = [err.message for err in reserved_errors]joined_errors = "\n - ".join(error_messages)msg = f"Reserved domain violations found:\n - {joined_errors}"- raise LibraryLoadingError(msg)+ raise LibraryLoadingError(msg).with_error_code(CoreCode.METHOD_NAME_CONFLICT)return Nonevisibility_errors = check_visibility_for_blueprints(manifest=manifest, blueprints=blueprints)@@ -1487,7 +1498,7 @@ class LibraryManager(LibraryManagerAbstract):error_messages = [err.message for err in visibility_errors]joined_errors = "\n - ".join(error_messages)msg = f"Package visibility violations found:\n - {joined_errors}"- raise LibraryLoadingError(msg)+ raise LibraryLoadingError(msg).with_error_code(CoreCode.METHOD_PIPE_NOT_EXPORTED)return manifest@@ -1542,7 +1553,7 @@ class LibraryManager(LibraryManagerAbstract):resolved_deps = resolve_all_dependencies(manifest=manifest, package_root=package_root)except DependencyResolveError as exc:msg = f"Failed to resolve dependencies: {exc}"- raise LibraryLoadingError(msg) from exc+ raise LibraryLoadingError(msg).with_error_code(CoreCode.METHOD_DEPENDENCY_MISSING) from exclibrary = self.get_library(library_id=library_id)@@ -1711,7 +1722,7 @@ class LibraryManager(LibraryManagerAbstract):parsed_pipe = QualifiedRef.parse_pipe_ref(raw=pipe_ref)if parsed_pipe.domain_path is None:msg = f"Crate pipe_ref '{pipe_ref}' must be domain-qualified"- raise PipeLibraryError(msg)+ raise PipeLibraryError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)domain_code = parsed_pipe.domain_pathpipe_code = parsed_pipe.local_code# A private pipe nothing public reaches is never built, so a broken one cannot refuse the consumer's load.@@ -2090,7 +2101,7 @@ class LibraryManager(LibraryManagerAbstract):"A structure field may name a concept declared by a bundle already loaded, or by a method package that ""one of the bundle's pipes references (`address->domain.Concept`).")- raise LibraryLoadingError(" ".join(refusals))+ raise LibraryLoadingError(" ".join(refusals)).with_error_code(CoreCode.METHOD_CONCEPT_INVALID)def _detect_concept_cycles(self, concepts: list["Concept"], *, concept_sources: "Mapping[str, str]") -> None:"""Detect cycles in concept references and raise an error if found.@@ -2169,7 +2180,7 @@ class LibraryManager(LibraryManagerAbstract):source = concept_sources.get(concept_ref)where = f" (declared in '{source}')" if source else ""msg = f"Cycle detected in concept references: {cycle_str}{where}"- raise LibraryLoadingError(msg)+ raise LibraryLoadingError(msg).with_error_code(CoreCode.METHOD_CYCLE)# Find the concept by refconcept = next((c for c in concepts if c.concept_ref == concept_ref), None)diff --git a/pipelex/libraries/pipe/exceptions.py b/pipelex/libraries/pipe/exceptions.pyindex 14db261ff..6818e96f5 100644--- a/pipelex/libraries/pipe/exceptions.py+++ b/pipelex/libraries/pipe/exceptions.py@@ -1,14 +1,31 @@-from pipelex.base_exceptions import ErrorDomain+from typing import ClassVar++from mthds.protocol.problem.registry import CoreCode+from pipelex.cogt.inference.error_classification import UserAction, UserActionKind+from pipelex.errors.error_code_declaration import ErrorCodeDeclaration, ErrorCodeSetfrom pipelex.libraries.exceptions import LibraryErrorclass PipeLibraryError(LibraryError):- pass+ """A pipe library that cannot hold the pipes it is given.++ The default ``method.name_conflict`` is two declarations of one pipe; a raise site chooses+ ``method.ref_ambiguous`` for a bare code matching several packages, ``method.signature_mismatch`` for a concrete+ pipe whose contract differs from its signature, ``request.unsupported`` for a form of request the resolve does not+ take, and ``runtime.unexpected`` for an invariant of the crate.+ """++ error_code: ClassVar[ErrorCodeDeclaration] = ErrorCodeSet(+ default=CoreCode.METHOD_NAME_CONFLICT,+ others=(CoreCode.METHOD_REF_AMBIGUOUS, CoreCode.METHOD_SIGNATURE_MISMATCH, CoreCode.REQUEST_UNSUPPORTED, CoreCode.RUNTIME_UNEXPECTED),+ )class PipeNotFoundError(PipeLibraryError):- pass+ """A pipe ref written inside a bundle that names no pipe the library holds."""++ error_code: ClassVar[ErrorCodeDeclaration] = CoreCode.METHOD_PIPE_UNRESOLVEDclass EntryPipeNotFoundError(PipeNotFoundError):@@ -17,15 +34,19 @@ class EntryPipeNotFoundError(PipeNotFoundError):The in-body sibling `PipeNotFoundError` reports a ref written inside a bundle, which is a faultof the loaded methods and stays unclassified. This one reports a code the caller supplied at anentry point (a CLI argument, the `pipe_code` field of a run request, the `--pipe` / `pipe_ref`- slice selector of bundle validation), so it is the caller's own typo: INPUT domain, which every- presentation derives from at once — 422 rather than a 500 that reads as retryable to every SDK.+ slice selector of bundle validation), so it is the caller's own typo: ``request.pipe_not_found``, or+ ``request.pipe_unspecified`` where the caller named no pipe and the method declares no entry pipe. An entry pipe+ the method itself declares that names no pipe of the method chooses ``method.pipe_unresolved``.Caller-facing copy: the message names only the caller's own `pipe_code`, so STRICT disclosurekeeps it verbatim. The flag spans every raise site of the class, so each one owes that invariant:a message here may name what the caller typed and nothing from the loaded library."""- error_domain = ErrorDomain.INPUT+ error_code = ErrorCodeSet(+ default=CoreCode.REQUEST_PIPE_NOT_FOUND,+ others=(CoreCode.REQUEST_PIPE_UNSPECIFIED, CoreCode.METHOD_PIPE_UNRESOLVED),+ )user_action = UserAction(kind=UserActionKind.CHANGE_INPUT,# Scope-neutral on purpose, because a class-level detail cannot name the scope its raise@@ -37,7 +58,6 @@ class EntryPipeNotFoundError(PipeNotFoundError):# stop asserting a scope it cannot know.detail="Check the pipe code for typos and make sure the bundle in scope for this operation declares it.",)- _declared_title = "Entry pipe not found"_authors_caller_facing_message = True@@ -46,7 +66,8 @@ class EntryPipeAmbiguousError(PipeLibraryError):Raised only by the entry lookup, which searches a bare code across domains precisely because ahuman typed it. Refusing to guess is the right answer, but it is the caller who picks the winner- — INPUT domain, same reasoning as :class:`EntryPipeNotFoundError`.+ — ``request.pipe_ambiguous``, same reasoning as :class:`EntryPipeNotFoundError`; several entry pipes the method+ itself declares choose ``method.pipe_unresolved``.Caller-facing copy: the message names the caller's own `pipe_code` and the qualified `pipe_ref`sof bundles they loaded themselves, so it survives STRICT disclosure intact — and it has to, since@@ -57,7 +78,7 @@ class EntryPipeAmbiguousError(PipeLibraryError):library would put host `pipe_ref`s in this message."""- error_domain = ErrorDomain.INPUT+ error_code = ErrorCodeSet(default=CoreCode.REQUEST_PIPE_AMBIGUOUS, others=(CoreCode.METHOD_PIPE_UNRESOLVED,))user_action = UserAction(kind=UserActionKind.CHANGE_INPUT,# Both spellings, because both raise sites reach this one detail: the bare-code arm is fixed by@@ -65,5 +86,4 @@ class EntryPipeAmbiguousError(PipeLibraryError):# the alias too — a bare 'domain.pipe_code' does not reach a dependency pipe at all.detail="Name one candidate explicitly: 'domain.pipe_code', or 'alias->domain.pipe_code' for a cross-package code.",)- _declared_title = "Entry pipe ambiguous"_authors_caller_facing_message = Truediff --git a/pipelex/libraries/pipe/pipe_library.py b/pipelex/libraries/pipe/pipe_library.pyindex 2280bd317..599dfa648 100644--- a/pipelex/libraries/pipe/pipe_library.py+++ b/pipelex/libraries/pipe/pipe_library.py@@ -1,6 +1,7 @@from itertools import groupbyfrom typing import Self+from mthds.protocol.problem.registry import CoreCodefrom pydantic import PrivateAttr, RootModelfrom typing_extensions import override@@ -120,7 +121,7 @@ class PipeLibrary(RootModel[PipeLibraryRoot], PipeLibraryAbstract):if len(matches) > 1:domains = [match.domain_code for match in matches]msg = f"Ambiguous cross-package pipe code '{pipe_code}' found in domains: {domains}. Use domain-qualified ref."- raise PipeLibraryError(msg)+ raise PipeLibraryError(msg).with_error_code(CoreCode.METHOD_REF_AMBIGUOUS)return Nonereturn None@@ -198,7 +199,7 @@ class PipeLibrary(RootModel[PipeLibraryRoot], PipeLibraryAbstract):key = f"{alias}->{pipe.pipe_ref}"if key in self.root:msg = f"Dependency pipe '{key}' already exists in the library"- raise PipeLibraryError(msg)+ raise PipeLibraryError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)self.root[key] = pipeif not is_exported:self._private_dependency_keys.add(key)diff --git a/pipelex/methods/exceptions.py b/pipelex/methods/exceptions.pyindex ced3362ad..5853bf536 100644--- a/pipelex/methods/exceptions.py+++ b/pipelex/methods/exceptions.py@@ -1,6 +1,10 @@from typing import ClassVar+from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import PipelexError+from pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeDeclaration, ErrorCodeSet+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodeclass MethodRefError(PipelexError):@@ -10,33 +14,54 @@ class MethodRefError(PipelexError):so the messages are caller-facing by design."""- _declared_title = "Method reference error"+ error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERROR_authors_caller_facing_message: ClassVar[bool] = Trueclass MethodRefParseError(MethodRefError):- """The method reference does not match the `<address>[@<tag>]` grammar."""+ """The method reference does not match the `<address>[@<tag>]` grammar, or names an address this runtime does not fetch."""++ error_code = ErrorCodeSet(default=CoreCode.REQUEST_INVALID, others=(CoreCode.REQUEST_UNSUPPORTED,))class MethodFetchError(MethodRefError):- """Fetching the repository behind a method reference failed (clone, tag verification, or commit resolution)."""+ """Fetching the repository behind a method reference failed (clone, tag verification, or commit resolution).++ The default ``method.fetch_failed`` is a clone, a resolution or a timeout that failed; a raise site chooses+ ``pipelex.config.dependency_missing`` when git is not installed on this host, ``method.not_found`` when the+ repository holds no such tag or no commit, and ``method.package_invalid`` for a fetched package that breaks a+ package rule.+ """++ error_code = ErrorCodeSet(+ default=CoreCode.METHOD_FETCH_FAILED,+ others=(PipelexErrorCode.CONFIG_DEPENDENCY_MISSING, CoreCode.METHOD_NOT_FOUND, CoreCode.METHOD_PACKAGE_INVALID),+ )class MethodPackageNotFoundError(MethodRefError):"""No package inside the fetched repository matches the requested address by manifest identity."""+ error_code = CoreCode.METHOD_NOT_FOUND+class MethodPackageAmbiguityError(MethodRefError):"""More than one package inside the fetched repository matches the requested address."""+ error_code = CoreCode.METHOD_AMBIGUOUS+class MethodPackageTooLargeError(MethodRefError):"""Fetched content exceeds a ceiling: the selected package's file count or total bytes, or the repository's manifest scan."""+ error_code = CoreCode.METHOD_PACKAGE_INVALID+class MethodPackageSymlinkError(MethodRefError):"""The fetched package contains a symlink, which fetched packages must not carry (it would bypass the content scans)."""+ error_code = CoreCode.METHOD_PACKAGE_INVALID+class MethodStructuresRefusedError(MethodRefError):"""The method declares Python structure classes, which hosted execution refuses to import into its own process.@@ -45,18 +70,32 @@ class MethodStructuresRefusedError(MethodRefError):whatever the content's origin: an inline bundle, a stored method or a host directory."""+ error_code = PipelexErrorCode.DEPLOYMENT_PYTHON_STRUCTURES_REFUSED+class MethodInstallError(MethodRefError):- """Installing a fetched method package into the installed-methods directory failed (occupied target, path escape, or copy failure)."""+ """Installing a fetched method package into the installed-methods directory failed (occupied target, path escape, or copy failure).++ The default ``pipelex.config.invalid`` is an installed-methods directory that cannot take the package; a package+ whose name escapes the directory or that carries no manifest chooses ``method.package_invalid``.+ """++ error_code = ErrorCodeSet(default=PipelexErrorCode.CONFIG_INVALID, others=(CoreCode.METHOD_PACKAGE_INVALID,))class MethodFetchDisabledError(MethodRefError):"""An address-referenced method is not installed and fetch-on-miss is disabled, so it cannot be fetched."""+ error_code = CoreCode.METHOD_DEPENDENCY_MISSING+class MethodDependencyFetchError(MethodRefError):"""An address-referenced method is not installed and fetching it failed (or its address is not fetchable)."""+ error_code = CoreCode.METHOD_DEPENDENCY_MISSING+class MethodDependencyNotShippedError(MethodRefError):"""An address-referenced method the caller did not ship, under a resolution that reads nothing installed and fetches nothing."""++ error_code = CoreCode.METHOD_DEPENDENCY_MISSINGdiff --git a/pipelex/methods/fetching.py b/pipelex/methods/fetching.pyindex 4564ac5c4..f8685f83e 100644--- a/pipelex/methods/fetching.py+++ b/pipelex/methods/fetching.py@@ -12,8 +12,10 @@ from pathlib import Pathfrom mthds.package.exceptions import VCSFetchErrorfrom mthds.package.manifest.schema import MethodsManifestfrom mthds.package.vcs_resolver import clone_at_version, clone_default_branch+from mthds.protocol.problem.registry import CoreCodefrom pydantic import BaseModel, ConfigDict, Field+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.methods.exceptions import MethodFetchError, MethodPackageSymlinkError, MethodPackageTooLargeErrorfrom pipelex.methods.fetch_limits import MAX_FETCHED_PACKAGE_FILES, MAX_FETCHED_PACKAGE_TOTAL_BYTESfrom pipelex.methods.method_ref import MethodRef@@ -102,7 +104,7 @@ def resolve_head_commit_sha(*, clone_dir: Path) -> str:)except FileNotFoundError as exc:msg = "git is not installed or not found on PATH"- raise MethodFetchError(msg) from exc+ raise MethodFetchError(msg).with_error_code(PipelexErrorCode.CONFIG_DEPENDENCY_MISSING) from excexcept subprocess.CalledProcessError as exc:msg = f"Failed to resolve the fetched commit: {_without_host_directory(text=exc.stderr.strip(), directory=clone_dir)}"raise MethodFetchError(msg) from exc@@ -136,7 +138,7 @@ def ensure_cloned_at_tag(*, clone_dir: Path, ref: MethodRef) -> None:)except FileNotFoundError as exc:msg = "git is not installed or not found on PATH"- raise MethodFetchError(msg) from exc+ raise MethodFetchError(msg).with_error_code(PipelexErrorCode.CONFIG_DEPENDENCY_MISSING) from excexcept subprocess.TimeoutExpired as exc:msg = f"Timed out verifying tag '{ref.tag}' of method reference '{ref.ref_str}'"raise MethodFetchError(msg) from exc@@ -145,7 +147,7 @@ def ensure_cloned_at_tag(*, clone_dir: Path, ref: MethodRef) -> None:f"'{ref.tag}' in method reference '{ref.ref_str}' does not name a git tag on the repository — "f"`@<tag>` pins a git tag (recommended form vX.Y.Z); branch names are not accepted.")- raise MethodFetchError(msg)+ raise MethodFetchError(msg).with_error_code(CoreCode.METHOD_NOT_FOUND)def ensure_package_within_bounds(*, package_dir: Path, package_address: str) -> None:diff --git a/pipelex/methods/method_ref.py b/pipelex/methods/method_ref.pyindex 7bfa1dd36..503d317f4 100644--- a/pipelex/methods/method_ref.py+++ b/pipelex/methods/method_ref.py@@ -13,6 +13,7 @@ This module is the single place the CLI, the API, and the tests parse that grammimport refrom mthds.package.vcs_resolver import address_to_clone_url+from mthds.protocol.problem.registry import CoreCodefrom pydantic import BaseModel, ConfigDictfrom pipelex.methods.exceptions import MethodRefParseError@@ -117,7 +118,7 @@ def parse_method_ref(ref: str) -> MethodRef:if not body.startswith(f"{GITHUB_HOST}/"):msg = f"Unsupported method address '{raw}': only '{GITHUB_HOST}/...' addresses are supported."- raise MethodRefParseError(msg)+ raise MethodRefParseError(msg).with_error_code(CoreCode.REQUEST_UNSUPPORTED)parts = body.split("/")diff --git a/pipelex/migration/exceptions.py b/pipelex/migration/exceptions.pyindex 175fb989a..86488cdb3 100644--- a/pipelex/migration/exceptions.py+++ b/pipelex/migration/exceptions.py@@ -1,30 +1,38 @@-from pipelex.base_exceptions import ErrorDomain, PipelexError, PipelexSetupError+from typing import ClassVar++from mthds.protocol.problem.registry import CoreCode++from pipelex.base_exceptions import PipelexError, PipelexSetupErrorfrom pipelex.cogt.inference.error_classification import UserAction, UserActionKind+from pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeDeclaration, InheritsCause+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodeclass MigrationError(PipelexError):"""Base for every failure raised by the configuration-migration engine."""- error_domain = ErrorDomain.CONFIG- _declared_title = "Migration error"+ error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERRORclass MigrationRegistryError(MigrationError):- """The surface registry is inconsistent, or names a surface that does not exist."""+ """The surface registry is inconsistent, or names a surface that does not exist: our packaged code is wrong."""- _declared_title = "Migration registry error"+ error_code = CoreCode.RUNTIME_UNEXPECTEDclass MigrationLedgerError(MigrationError):- """A ledger file is missing, unparseable, or internally inconsistent."""+ """A ledger file is missing, unparseable, or internally inconsistent: our packaged ledger is wrong."""- _declared_title = "Migration ledger error"+ error_code = CoreCode.RUNTIME_UNEXPECTEDclass MigrationGoldenError(MigrationError):- """A checked-in golden is missing or unreadable, so no verdict can be produced."""+ """A checked-in golden is missing or unreadable, so no verdict can be produced.++ Developer tooling: only `pipelex-dev check-ledger` and the schema update reach it.+ """- _declared_title = "Migration golden error"+ error_code = CoreCode.RUNTIME_UNEXPECTEDclass MigrationSnapshotRefusedError(MigrationError):@@ -32,9 +40,11 @@ class MigrationSnapshotRefusedError(MigrationError):Raised so that a habitual regeneration cannot quietly erase the very removal the coverage gateexists to catch. The refusal names both readings of the situation and the flag that resolves it.++ Developer tooling: only `pipelex-dev update-migration-schemas` reaches it."""- _declared_title = "Migration snapshot refused"+ error_code = CoreCode.RUNTIME_UNEXPECTEDclass FunctionNamesMigrationError(PipelexError):@@ -43,11 +53,12 @@ class FunctionNamesMigrationError(PipelexError):Raised by `pipelex fix function-names` when the path it is handed is not a method's folder, its method tree cannotbe listed, or a file cannot be read or written. The flat names it cannot resolve are not an error: the migrationreports them for the author to decide.++ A path that is not a folder is ``request.invalid``, chosen where it is raised; a tree that cannot be listed+ takes the code of the error that refused it; a file that cannot be read or written is ``runtime.unexpected``."""- error_domain = ErrorDomain.INPUT- retryable = False- _declared_title = "Function names migration error"+ error_code = InheritsCause(fallback=CoreCode.RUNTIME_UNEXPECTED, others=(CoreCode.REQUEST_INVALID,))class FormerReleaseConfigError(PipelexSetupError):@@ -60,7 +71,7 @@ class FormerReleaseConfigError(PipelexSetupError):again, on the hosted Pipelex API or on this machine."""- _declared_title = "Configuration left by a former release"+ error_code = PipelexErrorCode.CONFIG_INVALID# One next step for a person and an agent alike, since both read it: the human command first, then the loop an# agent runs, which shows the user what the cleanup would remove before it writes anything.user_action = UserAction(diff --git a/pipelex/migration/function_names.py b/pipelex/migration/function_names.pyindex f4dfc1fac..5eb000629 100644--- a/pipelex/migration/function_names.py+++ b/pipelex/migration/function_names.py@@ -29,6 +29,7 @@ import tomlkitfrom mthds.method_tree.exceptions import MethodTreeRefusedError, TreeLimitError, TreeSourceErrorfrom mthds.method_tree.lister import list_method_treefrom mthds.method_tree.python_modules import is_valid_function_segment+from mthds.protocol.problem.registry import CoreCodefrom pydantic import BaseModel, ConfigDict, Fieldfrom tomlkit.exceptions import TOMLKitErrorfrom tomlkit.items import String@@ -227,7 +228,7 @@ def migrate_function_names_in_directory(*, directory: Path, is_dry_run: bool) ->"""if not directory.is_dir():msg = f"'{directory}' is not a directory: hand over the folder of the method, whose tree holds its bundles and its Python."- raise FunctionNamesMigrationError(msg)+ raise FunctionNamesMigrationError(msg).with_error_code(CoreCode.REQUEST_INVALID)try:tree = list_method_tree(directory)except (MethodTreeRefusedError, TreeLimitError, TreeSourceError) as exc:diff --git a/pipelex/mthds_parsing/exceptions.py b/pipelex/mthds_parsing/exceptions.pyindex ba4e3adb1..a46af6035 100644--- a/pipelex/mthds_parsing/exceptions.py+++ b/pipelex/mthds_parsing/exceptions.py@@ -1,8 +1,13 @@-from pipelex.base_exceptions import ErrorDomain, PipelexError+from typing import ClassVar++from mthds.protocol.problem.registry import CoreCode++from pipelex.base_exceptions import PipelexErrorfrom pipelex.core.exceptions import PipelexBundleBlueprintValidationErrorData+from pipelex.errors.error_code_declaration import ErrorCodeDeclaration, ErrorCodeSet-class NativeConceptRedeclarationError(ValueError):+class NativeConceptRedeclarationError(PipelexError, ValueError):"""A bundle declares a concept whose code collides with a native Pipelex concept.Subclasses ``ValueError`` so a ``mode="before"`` pydantic field validator can raise it and@@ -11,12 +16,14 @@ class NativeConceptRedeclarationError(ValueError):Carrying the offending code is what lets the fix planner emit a targeted delete."""+ error_code = CoreCode.METHOD_NAME_CONFLICT+def __init__(self, message: str, concept_code: str):self.concept_code = concept_codesuper().__init__(message)-class InvalidPipeCodeSyntaxError(ValueError):+class InvalidPipeCodeSyntaxError(PipelexError, ValueError):"""A same-domain over-qualified pipe code the fix planner can strip back to its bare form.Raised (in place of a bare ``ValueError``) only at the two snake_case-enforcing raise sites —@@ -30,6 +37,8 @@ class InvalidPipeCodeSyntaxError(ValueError):refs stay bare ``ValueError``s → uncategorized-as-fixable, so they are never stripped."""+ error_code = CoreCode.METHOD_IDENTIFIER_INVALID+def __init__(self, message: str, offending_code: str, stripped_code: str):self.offending_code = offending_codeself.stripped_code = stripped_code@@ -43,14 +52,25 @@ class MthdsParserError(PipelexError):does not parse, and TOML that parses but fails blueprint validation. Themessage is always caller-facing copy describing a fault in the caller's owninput.++ The default ``method.invalid`` is the umbrella refusal whose items carry their own codes. A raise site that+ finds one fault chooses its code: ``method.syntax`` for a source that does not parse, ``method.schema_violation``+ for one that parses into no valid bundle, ``method.dependency_invalid`` for a dependency's bundle,+ ``request.invalid`` or ``request.pipe_unspecified`` for a request naming no usable pipe, and+ ``runtime.unexpected`` for a caller of the parser that passed it nothing to parse."""- error_domain = ErrorDomain.INPUT- # Declared rather than auto-derived: `_humanize_class_name` would render the- # class name as "Mthds parser", and MTHDS is the open standard's brand, always- # uppercase. This string is the RFC 7807 `title` on every ErrorReport, so the- # mis-casing would be wire-visible, not merely a docs-heading concern.- _declared_title = "MTHDS parser"+ error_code: ClassVar[ErrorCodeDeclaration] = ErrorCodeSet(+ default=CoreCode.METHOD_INVALID,+ others=(+ CoreCode.METHOD_SYNTAX,+ CoreCode.METHOD_SCHEMA_VIOLATION,+ CoreCode.METHOD_DEPENDENCY_INVALID,+ CoreCode.REQUEST_INVALID,+ CoreCode.REQUEST_PIPE_UNSPECIFIED,+ CoreCode.RUNTIME_UNEXPECTED,+ ),+ )# The parser's messages describe faults in the caller's own .mthds# source — caller-facing copy, kept verbatim under STRICT disclosure._authors_caller_facing_message = True@@ -66,3 +86,5 @@ class MthdsParserError(PipelexError):class BundleElaboratorError(MthdsParserError):"""Raised when bundle elaboration fails (e.g. synthetic-name collision, invalid output for preliminary_text)."""++ error_code = CoreCode.METHOD_SCHEMA_VIOLATIONdiff --git a/pipelex/mthds_parsing/parser.py b/pipelex/mthds_parsing/parser.pyindex fc99e3944..1537d9863 100644--- a/pipelex/mthds_parsing/parser.py+++ b/pipelex/mthds_parsing/parser.py@@ -1,6 +1,7 @@from pathlib import Pathfrom typing import Any+from mthds.protocol.problem.registry import CoreCodefrom pydantic import BaseModel, ValidationErrorfrom pipelex.core.exceptions import PipelexBundleBlueprintValidationErrorData@@ -75,7 +76,7 @@ class MthdsParser(BaseModel):blueprint_dict[PIPELEX_BUNDLE_BLUEPRINT_SOURCE_FIELD] = mthds_sourceelse:msg = "Either 'bundle_path' or 'mthds_content' must be provided for the MthdsParser to make a PipelexBundleBlueprint"- raise MthdsParserError(msg)+ raise MthdsParserError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)except TomlError as exc:toml_message = exc.messageif bundle_path is not None and mthds_source is not None:@@ -94,7 +95,7 @@ class MthdsParser(BaseModel):column=exc.colno,)],- ) from exc+ ).with_error_code(CoreCode.METHOD_SYNTAX) from excexcept UnicodeDecodeError as exc:# tomli reads a file as bytes and decodes them as UTF-8, so a file of a tree that is not text fails here.source = mthds_source if mthds_source is not None else str(bundle_path)@@ -103,11 +104,11 @@ class MthdsParser(BaseModel):raise MthdsParserError(msg,validation_errors=[PipelexBundleBlueprintValidationErrorData(source=source, message=msg, line=line, column=column)],- ) from exc+ ).with_error_code(CoreCode.METHOD_SYNTAX) from excif not blueprint_dict:msg = "Could not make 'PipelexBundleBlueprint': no blueprint found in the MTHDS file"- raise MthdsParserError(msg)+ raise MthdsParserError(msg).with_error_code(CoreCode.METHOD_SCHEMA_VIOLATION)try:# ``source`` is already populated from the seeded ``blueprint_dict`` above@@ -133,7 +134,7 @@ class MthdsParser(BaseModel):try:elaborated_blueprint = BundleElaborator.elaborate(bundle=pipelex_bundle_blueprint)except BundleElaboratorError as exc:- raise MthdsParserError(message=str(exc)) from exc+ raise MthdsParserError(message=str(exc)).with_error_code(CoreCode.METHOD_SCHEMA_VIOLATION) from exc# Only a bundle read from a file here may read beside it: a content string's `mthds_source` is a label.if bundle_path is not None:elaborated_blueprint.mark_read_from_host_file(bundle_file=Path(bundle_path))diff --git a/pipelex/pipe_controllers/batch/exceptions.py b/pipelex/pipe_controllers/batch/exceptions.pydeleted file mode 100644index b6f63b547..000000000--- a/pipelex/pipe_controllers/batch/exceptions.py+++ /dev/null@@ -1,5 +0,0 @@-from pipelex.base_exceptions import PipelexError---class PipeBatchFactoryError(PipelexError):- passdiff --git a/pipelex/pipe_controllers/batch/pipe_batch.py b/pipelex/pipe_controllers/batch/pipe_batch.pyindex e8130dcc0..0c51e0174 100644--- a/pipelex/pipe_controllers/batch/pipe_batch.py+++ b/pipelex/pipe_controllers/batch/pipe_batch.py@@ -1,12 +1,13 @@import functoolsfrom typing import TYPE_CHECKING, Any, Literal, cast+from mthds.protocol.problem.registry import CoreCodefrom typing_extensions import overridefrom pipelex import logfrom pipelex.core.memory.absence import AbsenceRecordfrom pipelex.core.memory.working_memory import WorkingMemory-from pipelex.core.pipes.exceptions import PipeRunError+from pipelex.core.pipes.exceptions import PipeRunError, PipeValidationErrorfrom pipelex.core.pipes.inputs.input_stuff_specs import InputStuffSpecsfrom pipelex.core.pipes.pipe_output import PipeOutputfrom pipelex.core.stuffs.list_content import ListContent@@ -65,7 +66,7 @@ class PipeBatch(PipeController):# 2. Check that the input_list_stuff_name is in the inputs of the pipeif self.batch_params.input_item_stuff_name not in required_variables:msg = f"Input item name '{self.batch_params.input_item_stuff_name}' not found in inputs of branch pipe '{self.branch_pipe_code}'"- raise ValueError(msg)+ raise PipeValidationError(message=msg, domain_code=self.domain_code, pipe_code=self.code).with_error_code(CoreCode.METHOD_WIRING_INVALID)required_variables.remove(self.batch_params.input_item_stuff_name)required_variables.add(self.batch_params.input_list_stuff_name)return required_variables@@ -88,7 +89,7 @@ class PipeBatch(PipeController):branch_pipe = get_required_pipe(pipe_code=self.branch_pipe_code)if self.batch_params.input_item_stuff_name not in branch_pipe.inputs.variables:msg = f"Input item name '{self.batch_params.input_item_stuff_name}' not found in inputs of branch pipe '{self.branch_pipe_code}'"- raise ValueError(msg)+ raise PipeValidationError(message=msg, domain_code=self.domain_code, pipe_code=self.code).with_error_code(CoreCode.METHOD_WIRING_INVALID)@overridedef validate_output_static(self):@@ -109,7 +110,7 @@ class PipeBatch(PipeController):if not self.inputs.is_variable_existing(variable_name=input_list_stuff_name):input_names = ", ".join(f"'{input_name}'" for input_name in self.inputs.variables) or "none"msg = f"The list '{list_label}' that PipeBatch '{self.code}' batches over is not among its inputs: {input_names}."- raise PipeRunError(message=msg, run_mode=pipe_run_params.run_mode, pipe_code=self.code)+ raise PipeRunError(message=msg, run_mode=pipe_run_params.run_mode, pipe_code=self.code).with_error_code(CoreCode.METHOD_WIRING_INVALID)if not working_memory.is_stuff_exists(input_list_stuff_name):msg = f"The list '{list_label}' that PipeBatch '{self.code}' batches over is not in working memory."@@ -121,7 +122,7 @@ class PipeBatch(PipeController):f"The value '{list_label}' that PipeBatch '{self.code}' batches over is not a list: it holds a "f"'{input_stuff.concept.concept_ref}', and a batch runs its pipe once per item of a list.")- raise PipeRunError(message=msg, run_mode=pipe_run_params.run_mode, pipe_code=self.code)+ raise PipeRunError(message=msg, run_mode=pipe_run_params.run_mode, pipe_code=self.code).with_error_code(CoreCode.METHOD_WIRING_INVALID)@overrideasync def _live_run_controller_pipe(diff --git a/pipelex/pipe_controllers/binding/binding_value.py b/pipelex/pipe_controllers/binding/binding_value.pyindex 5951658a7..d00fd2e99 100644--- a/pipelex/pipe_controllers/binding/binding_value.py+++ b/pipelex/pipe_controllers/binding/binding_value.py@@ -19,6 +19,8 @@ import datetimeimport mathfrom typing import Any, NamedTuple, cast+from mthds.protocol.problem.registry import CoreCode+from pipelex.core.stuffs.date_content import DateContentfrom pipelex.core.stuffs.json_content import JSONContentfrom pipelex.core.stuffs.list_content import ListContent@@ -110,14 +112,14 @@ def _refuse_shape_mismatch(*, root_content: StuffContent, derivation: BindingDerf"{item_count} items, and a binding never chooses one item of a list. The root was typed before the run as a single value, ""so whatever stored it stored a list instead, such as a step whose caller asked for several outputs.")- raise BindingStepRunError(msg)+ raise BindingStepRunError(msg).with_error_code(CoreCode.PIPE_OUTPUT_MULTIPLICITY)if derivation.is_bare_name and derivation.is_plural:msg = (f"Binding '{derivation.path}' was derived as a list, but its root '{derivation.root_name}' holds a single value, ""and a bare name binds its root's value as it is. The root was typed before the run as a list, so whatever stored it ""stored a single value instead.")- raise BindingStepRunError(msg)+ raise BindingStepRunError(msg).with_error_code(CoreCode.PIPE_OUTPUT_MULTIPLICITY)def _list_items(*, value: Any, reached_path: str, path: str) -> list[Any]:diff --git a/pipelex/pipe_controllers/binding/exceptions.py b/pipelex/pipe_controllers/binding/exceptions.pyindex 2d396b892..be2b77d17 100644--- a/pipelex/pipe_controllers/binding/exceptions.py+++ b/pipelex/pipe_controllers/binding/exceptions.py@@ -1,4 +1,7 @@+from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import PipelexError+from pipelex.errors.error_code_declaration import ErrorCodeSetclass BindingPathUnresolvedError(PipelexError):@@ -12,6 +15,8 @@ class BindingPathUnresolvedError(PipelexError):concepts, is refused the same way, the message naming each outcome and the concept it stores."""+ error_code = CoreCode.METHOD_FIELD_PATH_UNRESOLVED+def __init__(self, message: str, *, path: str, failed_segment: str, available_fields: list[str]):self.path = pathself.failed_segment = failed_segment@@ -27,4 +32,9 @@ class BindingStepRunError(PipelexError):multiplicity, such as a list held by a root derived as a single value. A binding whose root a pipe thatdid not resolve at validation stored is derived when it runs, and a result that contradicts the sequence'soutput, or the input of the step reading it, is reported this way too.++ Its code is ``pipe.binding_failed``; a raise site finding a root that holds a list where a single value was+ derived, or the reverse, chooses ``pipe.output_multiplicity``."""++ error_code = ErrorCodeSet(default=CoreCode.PIPE_BINDING_FAILED, others=(CoreCode.PIPE_OUTPUT_MULTIPLICITY,))diff --git a/pipelex/pipe_controllers/condition/exceptions.py b/pipelex/pipe_controllers/condition/exceptions.pyindex d1358166f..15b9031a1 100644--- a/pipelex/pipe_controllers/condition/exceptions.py+++ b/pipelex/pipe_controllers/condition/exceptions.py@@ -1,13 +1,16 @@-from pipelex.base_exceptions import ErrorDomain, PipelexError+from mthds.protocol.problem.registry import CoreCode++from pipelex.base_exceptions import PipelexErrorclass PipeConditionFactoryError(PipelexError):"""Raised when a ``PipeCondition`` declares neither ``expression_template`` nor ``expression``.- Raised only while the pipe is built from its blueprint, about that blueprint, so it is the author's to fix- (``input``) and bundle validation reports it as an item located on the pipe. Its messages name only the- author's own pipe, concepts and template text, so they are caller-facing copy kept under STRICT disclosure.+ Raised only while the pipe is built from its blueprint, about that blueprint, so it is the method's to fix+ (``method.schema_violation``) and bundle validation reports it as an item located on the pipe. Its messages+ name only the author's own pipe, concepts and template text, so they are caller-facing copy kept under STRICT+ disclosure."""- error_domain = ErrorDomain.INPUT+ error_code = CoreCode.METHOD_SCHEMA_VIOLATION_authors_caller_facing_message = Truediff --git a/pipelex/pipe_controllers/condition/pipe_condition.py b/pipelex/pipe_controllers/condition/pipe_condition.pyindex 7821ac15d..ec3ace7f2 100644--- a/pipelex/pipe_controllers/condition/pipe_condition.py+++ b/pipelex/pipe_controllers/condition/pipe_condition.py@@ -1,5 +1,6 @@from typing import TYPE_CHECKING, Any, Literal+from mthds.protocol.problem.registry import CoreCodefrom pydantic import BaseModel, ConfigDictfrom typing_extensions import override@@ -35,7 +36,7 @@ from pipelex.pipe_run.pipe_job_factory import PipeJobFactoryfrom pipelex.pipe_run.pipe_run_params import PipeRunParams, output_multiplicity_to_applyfrom pipelex.system.invocation_path import DEFAULT_OUTCOME_SEGMENT, outcome_segmentfrom pipelex.system.job_metadata import JobMetadata-from pipelex.tools.jinja2.exceptions import Jinja2DetectVariablesError+from pipelex.tools.jinja2.exceptions import Jinja2DetectVariablesError, Jinja2TemplateInvalidErrorfrom 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_path@@ -404,26 +405,26 @@ class PipeCondition(PipeController):async def _validate_before_run(self, *, job_metadata: JobMetadata, working_memory: WorkingMemory, pipe_run_params: PipeRunParams, output_name: str | None = None):- evaluated_expression = await render_template(- template=self.expression,- category=TemplateCategory.EXPRESSION,- context=working_memory.generate_context(),- )+ evaluated_expression = await self._render_expression(working_memory=working_memory, pipe_run_params=pipe_run_params)if not evaluated_expression or evaluated_expression == "None":# The expression is the caller's own method, rendered over their run's data: when it renders# nothing, no outcome can be chosen, and the method is theirs to fix. The message names only the pipe.error_msg = f"PipeCondition '{self.code}': Conditional expression returned no result"- raise PipeRunError(- pipe_code=self.code,- message=error_msg,- run_mode=pipe_run_params.run_mode,- ).as_caller_fault(- user_action=UserAction(- kind=UserActionKind.CHANGE_INPUT,- detail=(- f"Change the expression of PipeCondition '{self.code}' so that it always renders a value: "- "the name of one of its outcomes, or any other value, which takes the default outcome."- ),+ raise (+ PipeRunError(+ pipe_code=self.code,+ message=error_msg,+ run_mode=pipe_run_params.run_mode,+ )+ .with_error_code(CoreCode.PIPE_CONDITION_UNMATCHED)+ .as_caller_fault(+ user_action=UserAction(+ kind=UserActionKind.CHANGE_INPUT,+ detail=(+ f"Change the expression of PipeCondition '{self.code}' so that it always renders a value: "+ "the name of one of its outcomes, or any other value, which takes the default outcome."+ ),+ )))@@ -433,24 +434,53 @@ class PipeCondition(PipeController):):pass+ async def _render_expression(self, *, working_memory: WorkingMemory, pipe_run_params: PipeRunParams) -> str:+ """Render the conditional expression over the run's data.++ Raises:+ PipeRunError: `method.template_invalid` when the expression cannot render as written, such as a filter or+ a test inside a branch that the expression environment does not define, which only rendering that+ branch finds. The message names the pipe, its expression and what Jinja2 refused, never the+ expression's text.+ """+ try:+ return await render_template(+ template=self.expression,+ category=TemplateCategory.EXPRESSION,+ context=working_memory.generate_context(),+ )+ except Jinja2TemplateInvalidError as exc:+ if not exc.template_owner.is_method:+ # One of Pipelex's own templates, reached from the expression's render: ours, kept as it is.+ raise+ msg = f"PipeCondition '{self.code}': its expression cannot render: {exc.fault}"+ raise (+ PipeRunError(message=msg, run_mode=pipe_run_params.run_mode, pipe_code=self.code)+ .with_error_code(CoreCode.METHOD_TEMPLATE_INVALID)+ .as_caller_fault(+ user_action=UserAction(+ kind=UserActionKind.CHANGE_INPUT,+ detail=f"Fix the expression of PipeCondition '{self.code}': {exc.fault}",+ )+ )+ ) from exc+async def _evaluate_expression(self,*,working_memory: WorkingMemory,+ pipe_run_params: PipeRunParams,) -> str:"""Evaluate the conditional expression and select the appropriate pipe.Args:working_memory: The working memory context for evaluation+ pipe_run_params: The run's parameters, whose mode a refusal of the expression reportsReturns:The evaluated expression"""- evaluated_expression = await render_template(- template=self.expression,- category=TemplateCategory.EXPRESSION,- context=working_memory.generate_context(),- )+ evaluated_expression = await self._render_expression(working_memory=working_memory, pipe_run_params=pipe_run_params)if self.add_alias_from_expression_to:working_memory.add_alias(@@ -470,7 +500,7 @@ class PipeCondition(PipeController):output_name: str | None = None,library_crate: "LibraryCrate | None" = None,) -> PipeOutput:- evaluated_expression = await self._evaluate_expression(working_memory=working_memory)+ evaluated_expression = await self._evaluate_expression(working_memory=working_memory, pipe_run_params=pipe_run_params)# Select the outcome based on the evaluated expressionoutcome = self.outcome_map.get(evaluated_expression, self.default_outcome)@@ -499,13 +529,17 @@ class PipeCondition(PipeController):# message names only the pipe: the value the expression rendered can be literal text of the expression,# or an outcome key, of a condition a host library declared. The execution data above keeps that value.msg = f"PipeCondition '{self.code}' failed with outcome: {outcome}."- raise PipeRunError(message=msg, run_mode=pipe_run_params.run_mode, pipe_code=self.code).as_caller_fault(- user_action=UserAction(- kind=UserActionKind.CHANGE_INPUT,- detail=(- f"PipeCondition '{self.code}' refuses this run on purpose: change the inputs so that its expression "- "selects another outcome, or map that outcome to a pipe or to 'continue'."- ),+ raise (+ PipeRunError(message=msg, run_mode=pipe_run_params.run_mode, pipe_code=self.code)+ .with_error_code(CoreCode.PIPE_CONDITION_REFUSED)+ .as_caller_fault(+ user_action=UserAction(+ kind=UserActionKind.CHANGE_INPUT,+ detail=(+ f"PipeCondition '{self.code}' refuses this run on purpose: change the inputs so that its expression "+ "selects another outcome, or map that outcome to a pipe or to 'continue'."+ ),+ )))@@ -531,10 +565,14 @@ class PipeCondition(PipeController):# message names only the pipes and the input names.missing_names_str = ", ".join(missing_names)msg = f"PipeCondition '{self.code}' chose pipe '{outcome}', whose required inputs are missing: {missing_names_str}."- raise PipeRunError(message=msg, run_mode=pipe_run_params.run_mode, pipe_code=self.code).as_caller_fault(- user_action=UserAction(- kind=UserActionKind.CHANGE_INPUT,- detail=f"Provide the missing required inputs of '{outcome}', which PipeCondition '{self.code}' chose: {missing_names_str}.",+ raise (+ PipeRunError(message=msg, run_mode=pipe_run_params.run_mode, pipe_code=self.code)+ .with_error_code(CoreCode.PIPE_INPUT_UNRESOLVED)+ .as_caller_fault(+ user_action=UserAction(+ kind=UserActionKind.CHANGE_INPUT,+ detail=f"Provide the missing required inputs of '{outcome}', which PipeCondition '{self.code}' chose: {missing_names_str}.",+ )))@@ -644,10 +682,14 @@ class PipeCondition(PipeController):# past the `Jinja2DetectVariablesError` that quotes the expression: a run failure reports the innermost# Pipelex error on its chain (`find_root_fault`), which must be this refusal.msg = f"Dry run failed for pipe '{self.code}' (PipeCondition): its expression {describe_expression_parse_failure(error=exc)}."- raise PipeRunError(message=msg, run_mode=pipe_run_params.run_mode, pipe_code=self.code).as_caller_fault(- user_action=UserAction(- kind=UserActionKind.CHANGE_INPUT,- detail=f"Fix the expression of PipeCondition '{self.code}' so that it parses as a Jinja2 expression.",+ raise (+ PipeRunError(message=msg, run_mode=pipe_run_params.run_mode, pipe_code=self.code)+ .with_error_code(CoreCode.METHOD_TEMPLATE_INVALID)+ .as_caller_fault(+ user_action=UserAction(+ kind=UserActionKind.CHANGE_INPUT,+ detail=f"Fix the expression of PipeCondition '{self.code}' so that it parses as a Jinja2 expression.",+ ))) from exc.__cause__@@ -663,10 +705,16 @@ class PipeCondition(PipeController):# The caller's method names these pipes in its outcomes. The message names only the pipe codes.missing_pipes_str = ", ".join(missing_pipes)msg = f"Dry run failed for PipeCondition '{self.code}': its outcomes name pipes that do not exist: {missing_pipes_str}."- raise PipeRunError(message=msg, run_mode=pipe_run_params.run_mode, pipe_code=self.code).as_caller_fault(- user_action=UserAction(- kind=UserActionKind.CHANGE_INPUT,- detail=f"Declare the pipes {missing_pipes_str}, or change the outcomes of PipeCondition '{self.code}' to name existing pipes.",+ raise (+ PipeRunError(message=msg, run_mode=pipe_run_params.run_mode, pipe_code=self.code)+ .with_error_code(CoreCode.METHOD_PIPE_UNRESOLVED)+ .as_caller_fault(+ user_action=UserAction(+ kind=UserActionKind.CHANGE_INPUT,+ detail=(+ f"Declare the pipes {missing_pipes_str}, or change the outcomes of PipeCondition '{self.code}' to name existing pipes."+ ),+ )))@@ -721,10 +769,14 @@ class PipeCondition(PipeController):f"PipeCondition '{self.code}' maps every outcome (and the default) to 'fail': "f"every live run of this pipe raises. Map at least one outcome to a pipe or to 'continue'.")- raise PipeRunError(message=msg, run_mode=pipe_run_params.run_mode, pipe_code=self.code).as_caller_fault(- user_action=UserAction(- kind=UserActionKind.CHANGE_INPUT,- detail=f"Map at least one outcome of PipeCondition '{self.code}' to a pipe or to 'continue'.",+ raise (+ PipeRunError(message=msg, run_mode=pipe_run_params.run_mode, pipe_code=self.code)+ .with_error_code(CoreCode.METHOD_SCHEMA_VIOLATION)+ .as_caller_fault(+ user_action=UserAction(+ kind=UserActionKind.CHANGE_INPUT,+ detail=f"Map at least one outcome of PipeCondition '{self.code}' to a pipe or to 'continue'.",+ )))self._record_declared_absent_output(diff --git a/pipelex/pipe_controllers/exceptions.py b/pipelex/pipe_controllers/exceptions.pyindex af29b7448..4a1557107 100644--- a/pipelex/pipe_controllers/exceptions.py+++ b/pipelex/pipe_controllers/exceptions.py@@ -1,12 +1,8 @@from pipelex.base_exceptions import PipelexError+from pipelex.errors.error_code_declaration import ABSTRACT_ERRORclass PipeControllerError(PipelexError):- pass+ """Base of the errors of the pipe controllers."""--class PipeControllerOutputConceptMismatchError(PipeControllerError):- def __init__(self, message: str, tested_concept: str, wanted_concept: str):- self.tested_concept = tested_concept- self.wanted_concept = wanted_concept- super().__init__(message)+ error_code = ABSTRACT_ERRORdiff --git a/pipelex/pipe_controllers/parallel/exceptions.py b/pipelex/pipe_controllers/parallel/exceptions.pyindex 8aea0e2b8..b9dd581bd 100644--- a/pipelex/pipe_controllers/parallel/exceptions.py+++ b/pipelex/pipe_controllers/parallel/exceptions.py@@ -1,13 +1,16 @@-from pipelex.base_exceptions import ErrorDomain, PipelexError+from mthds.protocol.problem.registry import CoreCode++from pipelex.base_exceptions import PipelexErrorclass PipeParallelFactoryError(PipelexError):"""Raised when a ``PipeParallel`` branch names no ``result``.- Raised only while the pipe is built from its blueprint, about that blueprint, so it is the author's to fix- (``input``) and bundle validation reports it as an item located on the pipe. Its messages name only the- author's own pipe, concepts and template text, so they are caller-facing copy kept under STRICT disclosure.+ Raised only while the pipe is built from its blueprint, about that blueprint, so it is the method's to fix+ (``method.schema_violation``) and bundle validation reports it as an item located on the pipe. Its messages+ name only the author's own pipe, concepts and template text, so they are caller-facing copy kept under STRICT+ disclosure."""- error_domain = ErrorDomain.INPUT+ error_code = CoreCode.METHOD_SCHEMA_VIOLATION_authors_caller_facing_message = Truediff --git a/pipelex/pipe_controllers/parallel/pipe_parallel.py b/pipelex/pipe_controllers/parallel/pipe_parallel.pyindex 54edf8a1b..9e824ca20 100644--- a/pipelex/pipe_controllers/parallel/pipe_parallel.py+++ b/pipelex/pipe_controllers/parallel/pipe_parallel.py@@ -2,6 +2,7 @@ import asyncioimport builtinsfrom typing import TYPE_CHECKING, Any, Literal, get_origin+from mthds.protocol.problem.registry import CoreCodefrom pydantic import ValidationError, field_validatorfrom typing_extensions import override@@ -129,7 +130,7 @@ class PipeParallel(PipeController):f"Batch input item named '{sub_pipe.batch_params.input_item_stuff_name}' is not "f"in this Parallel Pipe '{self.code}' input requirements: {pipe_needed_inputs}")- raise PipeValidationError(message=msg) from exc+ raise PipeValidationError(message=msg).with_error_code(CoreCode.METHOD_WIRING_INVALID) from exc# A branch batches over a plain name only: a dotted `batch_over` is refused on a branch, since it binds.needed_inputs.add_stuff_spec(variable_name=sub_pipe.batch_params.input_list_stuff_name,@@ -508,7 +509,7 @@ class PipeParallel(PipeController):# TODO: check that at the blueprint / factory levelsub_pipe_code = self.parallel_sub_pipes[output_index].pipe_codemsg = f"PipeParallel '{self.code}': sub-pipe '{sub_pipe_code}' duplicate output name '{sub_pipe_output_name}'"- raise PipeRunError(message=msg, run_mode=pipe_run_params.run_mode, pipe_code=self.code)+ raise PipeRunError(message=msg, run_mode=pipe_run_params.run_mode, pipe_code=self.code).with_error_code(CoreCode.METHOD_NAME_CONFLICT)seen_output_names.add(sub_pipe_output_name)branch_resolved = pipe_output.working_memory.resolve_main_stuff()if isinstance(branch_resolved, AbsenceRecord):@@ -526,7 +527,9 @@ class PipeParallel(PipeController):f"'{self.output.concept.concept_ref}' is required. Make the field optional "f"(required = false) or sink the absence upstream (a `?` input on the branch path).")- raise PipeRunError(message=msg, run_mode=pipe_run_params.run_mode, pipe_code=self.code)+ raise PipeRunError(message=msg, run_mode=pipe_run_params.run_mode, pipe_code=self.code).with_error_code(+ CoreCode.METHOD_OPTIONAL_UNHANDLED+ )if self.add_each_output:# Branch results are parent slots only under add_each_output — same gate as the# present arm below and as lifted_companion_slots(). Writing the record without@@ -570,10 +573,12 @@ class PipeParallel(PipeController):"and so that every required field is fed by a branch.")# When the refusal is a branch whose multiplicity differs from its field's, say which one to change;- # any other refusal leaves as it came, flagged as the caller's fault.+ # any other refusal leaves as it came, flagged as the caller's fault: an output that does not fit its concept.next_steps = self._multiplicity_next_steps(structure_class=structure_class, output_stuffs=output_stuffs)if not next_steps:- exc.as_caller_fault(user_action=UserAction(kind=UserActionKind.CHANGE_INPUT, detail=method_next_step))+ exc.with_error_code(CoreCode.PIPE_OUTPUT_INVALID).as_caller_fault(+ user_action=UserAction(kind=UserActionKind.CHANGE_INPUT, detail=method_next_step)+ )raiselead = f"PipeParallel '{self.code}' cannot combine its branch results into its output '{output_concept_ref}'."message_parts = [lead, *next_steps.values()]@@ -588,8 +593,10 @@ class PipeParallel(PipeController):# of two faults of the same class on the chain the outer one, which restates the inner with a remedy,# is that root (see `pipe_run.located_failure.find_root_fault`), so every surface reports this one.# It is the caller's fault like the refusal it restates, with the multiplicity change as its next step.- raise StuffFactoryError(" ".join(message_parts)).as_caller_fault(- user_action=UserAction(kind=UserActionKind.CHANGE_INPUT, detail=" ".join(next_step_parts))+ raise (+ StuffFactoryError(" ".join(message_parts))+ .with_error_code(CoreCode.PIPE_OUTPUT_MULTIPLICITY)+ .as_caller_fault(user_action=UserAction(kind=UserActionKind.CHANGE_INPUT, detail=" ".join(next_step_parts)))) from excworking_memory.set_new_main_stuff(stuff=combined_output_stuff,diff --git a/pipelex/pipe_controllers/sequence/exceptions.py b/pipelex/pipe_controllers/sequence/exceptions.pyindex 12d1c8f57..8bfa793f5 100644--- a/pipelex/pipe_controllers/sequence/exceptions.py+++ b/pipelex/pipe_controllers/sequence/exceptions.py@@ -1,9 +1,12 @@+from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import PipelexError-class PipeSequenceValueError(ValueError):- pass+class PipeSequenceValueError(PipelexError, ValueError):+ """A ``PipeSequence`` step batches over an item its batched pipe does not take as an input: the method's wiring.+ It stays a ``ValueError`` as well, for a pydantic validator that reaches it while it reads the sequence's inputs.+ """-class PipeSequenceFactoryError(PipelexError):- pass+ error_code = CoreCode.METHOD_WIRING_INVALIDdiff --git a/pipelex/pipe_controllers/sub_pipe.py b/pipelex/pipe_controllers/sub_pipe.pyindex 15c5e2bd5..7aad696a5 100644--- a/pipelex/pipe_controllers/sub_pipe.py+++ b/pipelex/pipe_controllers/sub_pipe.py@@ -1,5 +1,6 @@from typing import TYPE_CHECKING+from mthds.protocol.problem.registry import CoreCodefrom pydantic import BaseModel, field_validatorfrom pipelex.core.memory.exceptions import WorkingMemoryStuffNotFoundError, WorkingMemoryTypeError@@ -117,7 +118,7 @@ class SubPipe(BaseModel):pipe_code=self.pipe_code,variable_name=list_label,concept_code=None,- ) from exc+ ).with_error_code(CoreCode.METHOD_WIRING_INVALID) from exctry:item_stuff_spec = sub_pipe.inputs.get_required_stuff_spec(variable_name=batch_params.input_item_stuff_name)@@ -132,7 +133,7 @@ class SubPipe(BaseModel):pipe_code=self.pipe_code,variable_name=batch_params.input_item_stuff_name,concept_code=None,- ) from exc+ ).with_error_code(CoreCode.METHOD_WIRING_INVALID) from exc# The batch is built as the runtime pipe, not from a blueprint: its list is a name of the calling sequence's memory,# a private one for a dotted `batch_over` the sequence rewrote, or any name a step stores under, never an input# name an author declares, so the input-name grammar a blueprint enforces does not apply to it.diff --git a/pipelex/pipe_machinery/pipe_abstract.py b/pipelex/pipe_machinery/pipe_abstract.pyindex 25d0186e5..676ca3451 100644--- a/pipelex/pipe_machinery/pipe_abstract.py+++ b/pipelex/pipe_machinery/pipe_abstract.py@@ -4,6 +4,7 @@ from datetime import UTC, datetimefrom typing import TYPE_CHECKING, Any, NamedTuple, Self, finalimport shortuuid+from mthds.protocol.problem.registry import CoreCodefrom opentelemetry import tracefrom opentelemetry.trace import NonRecordingSpan, Span, SpanContext, SpanKind, Status, StatusCode, TraceFlagsfrom pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator@@ -598,19 +599,28 @@ class PipeAbstract(ABC, BaseModel):]if optional_input_names:msg += f" These optional inputs may be omitted: {', '.join(optional_input_names)}."- # Whether the caller left the inputs out of the request or an earlier step of their- # method did not produce them, the fault is in the caller's own request or method, and- # the message names only the pipe and its input names.- raise PipeRunInputsError(- message=msg,- run_mode=pipe_run_params.run_mode,- pipe_code=self.code,- missing_inputs=presence_scan.missing_names,- ).as_caller_fault(- user_action=UserAction(- kind=UserActionKind.CHANGE_INPUT,- detail=f"Provide the missing required inputs of '{self.code}': {', '.join(presence_scan.missing_names)}.",+ # The run's entry pipe reads what the caller sent, so a name missing there is an input the caller left+ # out of the request; a nested pipe reads what earlier steps of the method produced, so a name missing+ # there is the method's wiring. The pipe stack tells them apart: it holds this pipe alone at the entry.+ # Either way the message names only the pipe and its input names.+ missing_inputs_str = ", ".join(presence_scan.missing_names)+ missing_inputs_code: CoreCode+ missing_inputs_detail: str+ if len(pipe_run_params.pipe_stack) <= 1:+ missing_inputs_code = CoreCode.INPUT_MISSING+ missing_inputs_detail = f"Provide the missing required inputs of '{self.code}': {missing_inputs_str}."+ else:+ missing_inputs_code = CoreCode.PIPE_INPUT_UNRESOLVED+ missing_inputs_detail = f"Change the method so that an earlier step produces the inputs '{self.code}' reads: {missing_inputs_str}."+ raise (+ PipeRunInputsError(+ message=msg,+ run_mode=pipe_run_params.run_mode,+ pipe_code=self.code,+ missing_inputs=presence_scan.missing_names,)+ .with_error_code(missing_inputs_code)+ .as_caller_fault(user_action=UserAction(kind=UserActionKind.CHANGE_INPUT, detail=missing_inputs_detail)))# The pipe is about to be lifted (skipped): per-pipe validation and resource checks are@@ -641,7 +651,7 @@ class PipeAbstract(ABC, BaseModel):run_mode=pipe_run_params.run_mode,pipe_code=self.code,variable_name=variable_name,- ) from exc+ ).with_error_code(CoreCode.INPUT_REFERENCE_NOT_FOUND) from exc# Specific pipe validation functionawait self._validate_before_run(diff --git a/pipelex/pipe_machinery/pipe_factory.py b/pipelex/pipe_machinery/pipe_factory.pyindex acd815ac8..95a2c8744 100644--- a/pipelex/pipe_machinery/pipe_factory.py+++ b/pipelex/pipe_machinery/pipe_factory.py@@ -1,6 +1,7 @@from typing import TYPE_CHECKING, Any, Generic, Protocol, TypeVarfrom kajson.exceptions import ClassRegistryInheritanceError, ClassRegistryNotFoundError+from mthds.protocol.problem.registry import CoreCodefrom typing_extensions import runtime_checkablefrom pipelex.core.concepts.helpers import strip_markers_from_concept_ref_or_code@@ -73,7 +74,7 @@ class PipeFactory(Generic[PipeAbstractType]):f"The concept must be either native, declared in domain '{domain_code}', or fully qualified with a domain prefix. "f"Declared concepts are: '{concept_codes_from_the_same_domain}'")- raise PipeFactoryError(msg)+ raise PipeFactoryError(msg).with_error_code(CoreCode.METHOD_CONCEPT_UNRESOLVED)if "." not in blueprint.output:stripped_output_concept_ref_or_code = strip_markers_from_concept_ref_or_code(concept_ref_or_code=blueprint.output)@@ -93,7 +94,7 @@ class PipeFactory(Generic[PipeAbstractType]):domain_code=domain_code,missing_concept_code=stripped_output_concept_ref_or_code,declared_concepts=concept_codes_from_the_same_domain,- )+ ).with_error_code(CoreCode.METHOD_CONCEPT_UNRESOLVED)# Parse common attributestry:@@ -129,10 +130,10 @@ class PipeFactory(Generic[PipeAbstractType]):)except ClassRegistryNotFoundError as factory_not_found_error:msg = f"Pipe '{pipe_code}' couldn't be created: factory '{factory_class_name}' not found: {factory_not_found_error}"- raise PipeFactoryError(msg) from factory_not_found_error+ raise PipeFactoryError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED) from factory_not_found_errorexcept ClassRegistryInheritanceError as factory_inheritance_error:msg = f"Pipe '{pipe_code}' couldn't be created: factory '{factory_class_name}' is not a subclass of {type(PipeFactoryProtocol)}."- raise PipeFactoryError(msg) from factory_inheritance_error+ raise PipeFactoryError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED) from factory_inheritance_errorpipe: PipeAbstractType = pipe_factory.make(pipe_category=pipe_category,diff --git a/pipelex/pipe_machinery/rendering/exceptions.py b/pipelex/pipe_machinery/rendering/exceptions.pynew file mode 100644index 000000000..4c3f3d487--- /dev/null+++ b/pipelex/pipe_machinery/rendering/exceptions.py@@ -0,0 +1,14 @@+from mthds.protocol.problem.registry import CoreCode++from pipelex.base_exceptions import PipelexError+++class OutputShapeUnavailableError(PipelexError, ValueError):+ """A pipe's output has no shape to render: it is ``Anything``, and no output it could produce can be determined.++ The request to render it asks for a form this pipe cannot give. It stays a ``ValueError`` for the callers that+ report it as a notice rather than a failure. The message names only the native concept.+ """++ error_code = CoreCode.REQUEST_UNSUPPORTED+ _authors_caller_facing_message = Truediff --git a/pipelex/pipe_machinery/rendering/output_renderer.py b/pipelex/pipe_machinery/rendering/output_renderer.pyindex 647378418..61dd72d94 100644--- a/pipelex/pipe_machinery/rendering/output_renderer.py+++ b/pipelex/pipe_machinery/rendering/output_renderer.py@@ -8,6 +8,7 @@ from pipelex.interpreter_hub import get_concept_library, get_required_pipefrom pipelex.pipe_controllers.binding.binding_step import BindingStepfrom pipelex.pipe_machinery.pipe_abstract import PipeAbstractfrom pipelex.pipe_machinery.pipe_blueprint import PipeType+from pipelex.pipe_machinery.rendering.exceptions import OutputShapeUnavailableErrorif TYPE_CHECKING:from pipelex.pipe_controllers.condition.pipe_condition import PipeCondition@@ -197,7 +198,7 @@ def _render_json_output(the_pipe: PipeAbstract, *, indent: int = 2) -> str:if not possible_outputs:msg = f"Output is '{NativeConceptCode.ANYTHING.concept_ref}' which has no specific shape and no possible outputs could be determined."- raise ValueError(msg)+ raise OutputShapeUnavailableError(msg)# Build dict with "output_option_1", "output_option_2", etc.# Each option includes "concept" and "content" fields@@ -233,7 +234,7 @@ def _render_python_output(the_pipe: PipeAbstract) -> str:if not possible_outputs:msg = f"Output is '{NativeConceptCode.ANYTHING.concept_ref}' which has no specific shape and no possible outputs could be determined."- raise ValueError(msg)+ raise OutputShapeUnavailableError(msg)# Generate Python code for multiple possible outputslines: list[str] = [@@ -283,7 +284,7 @@ def _render_schema_output(the_pipe: PipeAbstract, *, indent: int = 2) -> str:if not possible_outputs:msg = f"Output is '{NativeConceptCode.ANYTHING.concept_ref}' which has no specific shape and no possible outputs could be determined."- raise ValueError(msg)+ raise OutputShapeUnavailableError(msg)# Build dict with schema optionsresult: dict[str, Any] = {}diff --git a/pipelex/pipe_operators/compose/construct_blueprint.py b/pipelex/pipe_operators/compose/construct_blueprint.pyindex 57e023d94..2d166d34e 100644--- a/pipelex/pipe_operators/compose/construct_blueprint.py+++ b/pipelex/pipe_operators/compose/construct_blueprint.py@@ -14,7 +14,7 @@ from typing import Any, Self, castfrom pydantic import BaseModel, ConfigDict, SerializationInfo, SerializerFunctionWrapHandler, field_validator, model_serializer, model_validatorfrom pipelex.cogt.templating.template_preprocessor import preprocess_template-from pipelex.pipe_operators.compose.exceptions import ConstructFieldBlueprintTypeError, ConstructFieldBlueprintValueError+from pipelex.pipe_operators.compose.exceptions import ConstructFieldBlueprintTypeError, ConstructFieldBlueprintValueError, PipeComposeTemplateErrorfrom pipelex.tools.jinja2.exceptions import Jinja2DetectVariablesErrorfrom pipelex.tools.jinja2.jinja2_required_variables import detect_jinja2_required_variablesfrom pipelex.tools.jinja2.template_category import TemplateCategory@@ -296,7 +296,7 @@ class ConstructBlueprint(BaseModel):)except Jinja2DetectVariablesError as exc:msg = f"Error detecting required variables in construct template: {exc}"- raise ValueError(msg) from exc+ raise PipeComposeTemplateError(msg) from exc# Filter out internal and special variables by their root (same approach as template mode)for var in template_vars:root_var = get_root_from_dotted_path(var)diff --git a/pipelex/pipe_operators/compose/exceptions.py b/pipelex/pipe_operators/compose/exceptions.pyindex 02184c07d..2a05cb028 100644--- a/pipelex/pipe_operators/compose/exceptions.py+++ b/pipelex/pipe_operators/compose/exceptions.py@@ -1,37 +1,69 @@-from pipelex.base_exceptions import ErrorDomain, PipelexError+from typing import ClassVar++from mthds.protocol.problem.registry import CoreCode++from pipelex.base_exceptions import PipelexError+from pipelex.errors.error_code_declaration import ErrorCodeDeclaration, ErrorCodeSet, InheritsCauseclass PipeComposeError(PipelexError):- pass+ """A ``PipeCompose`` failed to compose its output; raised directly, it takes its cause's code."""++ error_code: ClassVar[ErrorCodeDeclaration] = InheritsCause(fallback=CoreCode.PIPE_OUTPUT_INVALID)class PipeComposeFactoryError(PipeComposeError):"""Raised when a ``PipeCompose`` has no template in template mode, or its template does not parse.- Raised only while the pipe is built from its blueprint, about that blueprint, so it is the author's to fix- (``input``) and bundle validation reports it as an item located on the pipe. Its messages name only the- author's own pipe, concepts and template text, so they are caller-facing copy kept under STRICT disclosure.+ Raised only while the pipe is built from its blueprint, about that blueprint, so it is the method's to fix and+ bundle validation reports it as an item located on the pipe: a template that does not parse is+ ``method.template_invalid``, its code over the parser's own, and a template mode with no template+ ``method.schema_violation``. Its messages name only the author's own pipe, concepts and template text, so they+ are caller-facing copy kept under STRICT disclosure."""- error_domain = ErrorDomain.INPUT+ error_code = ErrorCodeSet(default=CoreCode.METHOD_TEMPLATE_INVALID, others=(CoreCode.METHOD_SCHEMA_VIOLATION,))_authors_caller_facing_message = Trueclass ConstructFieldBlueprintTypeError(PipeComposeError, TypeError):- pass+ """A ``construct`` field of the method has a shape the blueprint does not accept."""++ error_code = CoreCode.METHOD_SCHEMA_VIOLATIONclass ConstructFieldBlueprintValueError(PipeComposeError, ValueError):- pass+ """A ``construct`` field of the method breaks a rule of the blueprint."""++ error_code = CoreCode.METHOD_SCHEMA_VIOLATION+++class PipeComposeTemplateError(PipeComposeError, ValueError):+ """A template of a ``PipeCompose``, its own or a ``construct`` field's, does not parse when its variables are read.++ Its message carries the parser's diagnosis, which can quote the template, so it is not caller-facing: the+ template may be a host library's. It stays a ``ValueError`` for the pydantic validators that read a pipe's+ required variables.+ """++ error_code = CoreCode.METHOD_TEMPLATE_INVALIDclass StructuredContentComposerTypeError(PipeComposeError, TypeError):- pass+ """The value a ``construct`` composed does not fit the output concept."""++ error_code = CoreCode.PIPE_OUTPUT_INVALIDclass StructuredContentComposerValueError(PipeComposeError, ValueError):- pass+ """A ``construct`` cannot compose a field: a blueprint invariant the load guarantees broke (``runtime.unexpected``),+ or a ``from`` path or key attribute names a field the value lacks (``method.field_path_unresolved``).+ """++ error_code = ErrorCodeSet(default=CoreCode.RUNTIME_UNEXPECTED, others=(CoreCode.METHOD_FIELD_PATH_UNRESOLVED,))class StructuredContentComposerValidationError(PipeComposeError):- pass+ """The composed value does not validate against the output concept's structure."""++ error_code = CoreCode.PIPE_OUTPUT_INVALIDdiff --git a/pipelex/pipe_operators/compose/pipe_compose.py b/pipelex/pipe_operators/compose/pipe_compose.pyindex 2d2d13212..3cc0747d3 100644--- a/pipelex/pipe_operators/compose/pipe_compose.py+++ b/pipelex/pipe_operators/compose/pipe_compose.py@@ -3,6 +3,7 @@ from typing import Any, Literalfrom pydantic import Fieldfrom typing_extensions import override+from pipelex.base_exceptions import PipelexUnexpectedErrorfrom pipelex.cogt.content_generation.dry_run_factory import DryRunFactoryfrom pipelex.cogt.templating.template_preprocessor import rewrite_template_sigilsfrom pipelex.config import get_config@@ -19,7 +20,7 @@ from pipelex.kernel.compose_ops import run_compose_templatefrom pipelex.kernel.templating_style_ops import resolve_templating_stylefrom pipelex.pipe_machinery.template_guard_lint import lint_authored_template, lint_template_private_namesfrom pipelex.pipe_operators.compose.construct_blueprint import ConstructBlueprint-from pipelex.pipe_operators.compose.exceptions import PipeComposeError, StructuredContentComposerValueError+from pipelex.pipe_operators.compose.exceptions import PipeComposeError, PipeComposeTemplateError, StructuredContentComposerValueErrorfrom pipelex.pipe_operators.compose.structured_content_composer import StructuredContentComposerfrom pipelex.pipe_operators.pipe_operator import PipeOperatorfrom pipelex.pipe_run.pipe_run_params import PipeRunParams@@ -82,7 +83,7 @@ class PipeCompose(PipeOperator[PipeComposeOutput]):)except Jinja2DetectVariablesError as exc:msg = f"Error detecting required variables for PipeCompose: {exc}"- raise ValueError(msg) from exc+ raise PipeComposeTemplateError(msg) from excroots: set[str] = set()for path in full_paths:root = get_root_from_dotted_path(path)@@ -199,8 +200,9 @@ class PipeCompose(PipeOperator[PipeComposeOutput]):) -> PipeComposeOutput:"""Run PipeCompose in template mode (produces Text or Html output)."""if self.template is None:+ # The factory refuses a template mode with no template, so this is a bug of ours.msg = "Template is required for template mode"- raise ValueError(msg)+ raise PipelexUnexpectedError(msg)# Resolved here rather than inside the kernel: turning a concept into a class is a library's# business, and handing the class over is what spares the kernel a registry read.@@ -243,8 +245,9 @@ class PipeCompose(PipeOperator[PipeComposeOutput]):) -> PipeComposeOutput:"""Run PipeCompose in construct mode (produces StructuredContent output)."""if self.construct_blueprint is None:+ # The factory refuses a construct mode with no construct, so this is a bug of ours.msg = "Construct blueprint is required for construct mode"- raise ValueError(msg)+ raise PipelexUnexpectedError(msg)# Get the output class from the registryoutput_class = get_class_registry().get_required_subclass(diff --git a/pipelex/pipe_operators/compose/pipe_compose_factory.py b/pipelex/pipe_operators/compose/pipe_compose_factory.pyindex 7eba77cb3..c5c829de4 100644--- a/pipelex/pipe_operators/compose/pipe_compose_factory.py+++ b/pipelex/pipe_operators/compose/pipe_compose_factory.py@@ -1,5 +1,6 @@from typing import Any+from mthds.protocol.problem.registry import CoreCodefrom typing_extensions import overridefrom pipelex.cogt.templating.exceptions import TemplateSigilSyntaxError@@ -63,7 +64,7 @@ class PipeComposeFactory(PipeFactoryProtocol[PipeComposeBlueprint, PipeCompose])template_source = blueprint.template_sourceif template_source is None:msg = "Template source is required for template mode"- raise PipeComposeFactoryError(msg)+ raise PipeComposeFactoryError(msg).with_error_code(CoreCode.METHOD_SCHEMA_VIOLATION)# Preprocess here only to validate at load time (sigil syntax + Jinja2 parseability).# The PipeCompose stores the *authored* source, like every other pipe (PipeLLM,diff --git a/pipelex/pipe_operators/compose/structured_content_composer.py b/pipelex/pipe_operators/compose/structured_content_composer.pyindex dcba6f85b..a9cb72df2 100644--- a/pipelex/pipe_operators/compose/structured_content_composer.py+++ b/pipelex/pipe_operators/compose/structured_content_composer.py@@ -2,6 +2,7 @@ import datetimeimport inspectfrom typing import Any, NamedTuple, TypeAlias, cast, get_args, get_origin+from mthds.protocol.problem.registry import CoreCodefrom pydantic import BaseModel, ValidationErrorfrom pipelex.cogt.templating.template_rendering import render_template@@ -255,7 +256,7 @@ class StructuredContentComposer:if find_private_path_segment(path=key_attr):msg = f"list_to_dict_keyed_by names '{key_attr}', which starts with an underscore: it names a public field only"- raise StructuredContentComposerValueError(msg)+ raise StructuredContentComposerValueError(msg).with_error_code(CoreCode.METHOD_FIELD_PATH_UNRESOLVED)result: dict[str, Any] = {}for idx, item in enumerate(items):@@ -266,7 +267,7 @@ class StructuredContentComposer:key = item[key_attr] # pyright: ignore[reportUnknownVariableType]else:msg = f"Item at index {idx} does not have attribute '{key_attr}'"- raise StructuredContentComposerValueError(msg)+ raise StructuredContentComposerValueError(msg).with_error_code(CoreCode.METHOD_FIELD_PATH_UNRESOLVED)if not isinstance(key, str):msg = f"Key attribute '{key_attr}' at index {idx} must be a string, got {type(key).__name__}" # pyright: ignore[reportUnknownArgumentType]@@ -299,7 +300,7 @@ class StructuredContentComposer:# The blueprint refuses these at load; the walk below is raw `getattr`, so it refuses them again.if private_segment := find_private_path_segment(path=path):msg = f"Cannot resolve path '{path}': '{private_segment}' starts with an underscore, and a path reads public fields only"- raise StructuredContentComposerValueError(msg)+ raise StructuredContentComposerValueError(msg).with_error_code(CoreCode.METHOD_FIELD_PATH_UNRESOLVED)parts = path.split(".", 1)base_name = parts[0]attr_path = parts[1]@@ -316,7 +317,7 @@ class StructuredContentComposer:current_value = current_value[attr] # pyright: ignore[reportUnknownVariableType]else:msg = f"Cannot resolve path '{path}': attribute '{attr}' not found"- raise StructuredContentComposerValueError(msg)+ raise StructuredContentComposerValueError(msg).with_error_code(CoreCode.METHOD_FIELD_PATH_UNRESOLVED)# Apply type conversion if the resolved value is a StuffContentif isinstance(current_value, StuffContent):diff --git a/pipelex/pipe_operators/doc_gen/doc_gen_rendering.py b/pipelex/pipe_operators/doc_gen/doc_gen_rendering.pyindex 85f041505..faccb5dd7 100644--- a/pipelex/pipe_operators/doc_gen/doc_gen_rendering.py+++ b/pipelex/pipe_operators/doc_gen/doc_gen_rendering.py@@ -9,10 +9,11 @@ Both raise the same errors, worded the same way.from typing import Anyfrom jinja2.exceptions import UndefinedError+from mthds.protocol.problem.registry import CoreCodefrom pipelex.cogt.templating.template_rendering import render_templatefrom pipelex.pipe_operators.doc_gen.exceptions import PipeDocGenRunError, PipeDocGenUndefinedValueError-from pipelex.tools.jinja2.exceptions import Jinja2TemplateRenderError+from pipelex.tools.jinja2.exceptions import Jinja2TemplateInvalidError, Jinja2TemplateRenderErrorfrom pipelex.tools.jinja2.template_category import TemplateCategoryfrom pipelex.tools.templating.templating_style import TemplatingStyle@@ -40,6 +41,13 @@ async def render_doc_gen_template(templating_style=templating_style,is_undefined_strict=True,)+ except Jinja2TemplateInvalidError as exc:+ if not exc.template_owner.is_method:+ # One of Pipelex's own templates, reached from the method's render: ours, kept as it is.+ raise+ # The template is the method author's own: the message names the step, the template and what Jinja2 refused.+ msg = f"PipeDocGen '{pipe_code}' could not render its {label}: {exc.fault}"+ raise PipeDocGenRunError(msg).with_error_code(CoreCode.METHOD_TEMPLATE_INVALID).as_caller_fault() from excexcept Jinja2TemplateRenderError as exc:undefined_error = exc.__cause__if isinstance(undefined_error, UndefinedError):diff --git a/pipelex/pipe_operators/doc_gen/exceptions.py b/pipelex/pipe_operators/doc_gen/exceptions.pyindex d9dce6136..37f0a169d 100644--- a/pipelex/pipe_operators/doc_gen/exceptions.py+++ b/pipelex/pipe_operators/doc_gen/exceptions.py@@ -1,4 +1,8 @@-from pipelex.base_exceptions import ErrorDomain, PipelexError+from mthds.protocol.problem.registry import CoreCode++from pipelex.base_exceptions import PipelexError+from pipelex.errors.error_code_declaration import ErrorCodeSet, InheritsCause+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodeclass PipeDocGenFactoryError(PipelexError):@@ -7,15 +11,32 @@ class PipeDocGenFactoryError(PipelexError):The output concept is not a Document, a template does not parse or reads a field its input does not have,or the template file is missing or cannot be resolved. It is raised only while the pipe is built, about theauthor's own blueprint, so it is the author's to fix and its messages name only the author's pipe, concepts,- fields, template and file path.+ fields, template and file path. Its code defaults to a template that does not parse; the raise site chooses+ the code of what else it found."""- error_domain = ErrorDomain.INPUT+ error_code = ErrorCodeSet(+ default=CoreCode.METHOD_TEMPLATE_INVALID,+ others=(+ CoreCode.METHOD_OUTPUT_CONCEPT_MISMATCH,+ CoreCode.METHOD_RESOURCE_MISSING,+ CoreCode.SECURITY_METHOD_PATH_REFUSED,+ CoreCode.METHOD_INPUT_UNDECLARED,+ CoreCode.METHOD_FIELD_PATH_UNRESOLVED,+ ),+ )_authors_caller_facing_message = Trueclass PipeDocGenRunError(PipelexError):- """Raised when a ``PipeDocGen`` step fails while it composes its document: a template or the filename does not render."""+ """Raised when a ``PipeDocGen`` step fails while it composes its document: a template or the filename does not render.++ It takes the code of the render failure it wraps, else a template that failed to render; a raise site finding an+ invariant the load and the crate guarantee broken chooses ``runtime.unexpected``, and one naming a template that+ cannot render as written, with its field and what Jinja2 refused, chooses ``method.template_invalid``.+ """++ error_code = InheritsCause(fallback=CoreCode.PIPE_TEMPLATE_RENDER_FAILED, others=(CoreCode.RUNTIME_UNEXPECTED, CoreCode.METHOD_TEMPLATE_INVALID))class PipeDocGenUndefinedValueError(PipelexError):@@ -28,7 +49,7 @@ class PipeDocGenUndefinedValueError(PipelexError):the template or the filename, and the missing name, and it never quotes the template's source."""- error_domain = ErrorDomain.INPUT+ error_code = CoreCode.PIPE_TEMPLATE_RENDER_FAILED_authors_caller_facing_message = True@@ -37,10 +58,10 @@ class PipeDocGenTemplateCheckError(PipelexError):The dry run is what ``pipelex validate`` runs, so a template naming a field the inputs do not have fails there,before anything is spent. Its message lists the checker's findings, which name only the author's template,- names and fields.+ names and fields. PipeDocGen is not in the MTHDS standard, hence a Pipelex code."""- error_domain = ErrorDomain.INPUT+ error_code = PipelexErrorCode.DOCGEN_TEMPLATE_INVALID_authors_caller_facing_message = True@@ -52,8 +73,8 @@ class PipeDocGenTemplateFileUncheckedError(PipelexError):by digest and carries none of its files, so a validation of the crate reads the file from a tree a library of thisprocess holds, and reaches the verdict the load where the crate was assembled reached. Where no library holds thetree, 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.+ was validated, not in the method, and the message names only the step and the template file's tree path: this+ runtime cannot serve the validation, which a runtime holding the method's files can."""- error_domain = ErrorDomain.RUNTIME- retryable = False+ error_code = CoreCode.RUNTIME_UNSUPPORTEDdiff --git a/pipelex/pipe_operators/doc_gen/pipe_doc_gen.py b/pipelex/pipe_operators/doc_gen/pipe_doc_gen.pyindex 2e065d513..bacdee192 100644--- a/pipelex/pipe_operators/doc_gen/pipe_doc_gen.py+++ b/pipelex/pipe_operators/doc_gen/pipe_doc_gen.py@@ -1,5 +1,6 @@from typing import TYPE_CHECKING, Any, Literal+from mthds.protocol.problem.registry import CoreCodefrom pydantic import Field, PrivateAttrfrom typing_extensions import override@@ -341,7 +342,7 @@ class PipeDocGen(PipeOperator[PipeDocGenOutput]):"""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)+ raise PipeDocGenRunError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)return ComposedTemplateFile(file=self.template_file_ref,name=self.template_file,@@ -363,7 +364,7 @@ class PipeDocGen(PipeOperator[PipeDocGenOutput]):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)+ raise PipeDocGenRunError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)input_stuffs: dict[str, Stuff] = {}for input_name in self.inputs.variables:stuff = working_memory.get_optional_stuff(input_name)diff --git a/pipelex/pipe_operators/doc_gen/pipe_doc_gen_factory.py b/pipelex/pipe_operators/doc_gen/pipe_doc_gen_factory.pyindex 9a18bcd00..36004949e 100644--- a/pipelex/pipe_operators/doc_gen/pipe_doc_gen_factory.py+++ b/pipelex/pipe_operators/doc_gen/pipe_doc_gen_factory.py@@ -2,7 +2,8 @@ from typing import Anyfrom mthds.method_tree.exceptions import MethodTreeRefusedErrorfrom mthds.method_tree.references import is_file_reference-from mthds.method_tree.vocabulary import ReferenceContext+from mthds.method_tree.vocabulary import ReferenceContext, TreeRefusalCode+from mthds.protocol.problem.registry import CoreCodefrom typing_extensions import overridefrom pipelex.core.concepts.native.concept_native import NativeConceptCode@@ -42,7 +43,7 @@ class PipeDocGenFactory(PipeFactoryProtocol[PipeDocGenBlueprint, PipeDocGen]):f"The output of PipeDocGen '{pipe_code}' is '{output.concept.concept_ref}', which is not a Document. "f"Declare the output as {document_concept.concept_ref}, or as a concept that refines it.")- raise PipeDocGenFactoryError(msg)+ raise PipeDocGenFactoryError(msg).with_error_code(CoreCode.METHOD_OUTPUT_CONCEPT_MISMATCH)template_file_ref: MethodFileRef | None = Nonetemplate_bundle_ref: TreeBundleRef | None = None@@ -84,10 +85,11 @@ class PipeDocGenFactory(PipeFactoryProtocol[PipeDocGenBlueprint, PipeDocGen]):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+ raise PipeDocGenFactoryError(msg).with_error_code(_template_file_refusal_code(refusal_error=exc)) from exctemplate_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))+ msg = cls._unsubmitted_template_file_message(pipe_code=pipe_code, template_file=template_file)+ raise PipeDocGenFactoryError(msg).with_error_code(CoreCode.METHOD_RESOURCE_MISSING)pipe_doc_gen = PipeDocGen(domain_code=domain_code,@@ -140,7 +142,7 @@ class PipeDocGenFactory(PipeFactoryProtocol[PipeDocGenBlueprint, PipeDocGen]):"loaded from a string with no file sent beside it, so it belongs to no method tree and a relative URL ""names no file. Load the method from its folder, or name the file by an https:// or a data: URL.")- raise PipeDocGenFactoryError(msg)+ raise PipeDocGenFactoryError(msg).with_error_code(CoreCode.METHOD_RESOURCE_MISSING)return None, False@classmethod@@ -160,7 +162,7 @@ class PipeDocGenFactory(PipeFactoryProtocol[PipeDocGenBlueprint, PipeDocGen]):if refusal is None:returnmsg = f"PipeDocGen '{pipe_code}' names '{refusal.reference}' in {refusal.holder_label}, which its method cannot give it. {refusal.reason}"- raise PipeDocGenFactoryError(msg)+ raise PipeDocGenFactoryError(msg).with_error_code(CoreCode.METHOD_RESOURCE_MISSING)@classmethoddef _resolve_template_file(cls, *, pipe_code: str, template_file: str, tree_bundle: TreeBundle) -> str:@@ -178,10 +180,10 @@ class PipeDocGenFactory(PipeFactoryProtocol[PipeDocGenBlueprint, PipeDocGen]):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 exc+ raise PipeDocGenFactoryError(msg).with_error_code(CoreCode.METHOD_RESOURCE_MISSING) 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+ raise PipeDocGenFactoryError(msg).with_error_code(_template_file_refusal_code(refusal_error=exc)) from exc@staticmethoddef _unsubmitted_template_file_message(*, pipe_code: str, template_file: str) -> str:@@ -210,7 +212,7 @@ class PipeDocGenFactory(PipeFactoryProtocol[PipeDocGenBlueprint, PipeDocGen]):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)+ raise PipeDocGenFactoryError(msg).with_error_code(CoreCode.METHOD_RESOURCE_MISSING)try:return data.decode("utf-8")except UnicodeError as exc:@@ -233,4 +235,34 @@ class PipeDocGenFactory(PipeFactoryProtocol[PipeDocGenBlueprint, PipeDocGen]):raise PipeDocGenFactoryError(msg) from excfor root in sorted(roots - declared_inputs):msg = f"Variable '{root}' in the template file '{template_file}' of PipeDocGen '{pipe_code}' is not in the inputs of the pipe."- raise PipeDocGenFactoryError(msg)+ raise PipeDocGenFactoryError(msg).with_error_code(CoreCode.METHOD_INPUT_UNDECLARED)+++def _template_file_refusal_code(*, refusal_error: MethodTreeRefusedError) -> CoreCode:+ """The code of a template file reference its method tree refused: a path that leaves the tree, or names a link or a+ special file, is refused as a security matter; any other refusal leaves the method without the file it names.+ """+ match refusal_error.refusal.code:+ case TreeRefusalCode.REFERENCE_LEAVES_TREE | TreeRefusalCode.SYMBOLIC_LINK | TreeRefusalCode.SPECIAL_FILE:+ return CoreCode.SECURITY_METHOD_PATH_REFUSED+ case (+ TreeRefusalCode.INVALID_TREE_PATH+ | TreeRefusalCode.NORMALIZATION_COLLISION+ | TreeRefusalCode.PATH_COLLISION+ | TreeRefusalCode.EMPTY_TREE+ | TreeRefusalCode.LONE_FILE_EXCLUDED+ | TreeRefusalCode.GITIGNORE_NOT_UTF8+ | TreeRefusalCode.DUPLICATE_KEY+ | TreeRefusalCode.EXCLUDED_NAME+ | TreeRefusalCode.MALFORMED_ENTRY+ | TreeRefusalCode.MISSING_BLOB+ | TreeRefusalCode.REFERENCE_INVALID+ | TreeRefusalCode.REFERENCE_NOT_A_TREE_PATH+ | TreeRefusalCode.REFERENCE_NOT_IN_TREE+ | TreeRefusalCode.REFERENCE_IN_ONE_FILE_TREE+ | TreeRefusalCode.FUNCTION_NAME_WITHOUT_MODULE+ | TreeRefusalCode.FUNCTION_NAME_INVALID_SEGMENT+ | TreeRefusalCode.MODULE_NOT_IN_TREE+ | TreeRefusalCode.MODULE_AMBIGUOUS+ ):+ return CoreCode.METHOD_RESOURCE_MISSINGdiff --git a/pipelex/pipe_operators/doc_gen/template_field_check.py b/pipelex/pipe_operators/doc_gen/template_field_check.pyindex a527bb9ab..dce5cb46b 100644--- a/pipelex/pipe_operators/doc_gen/template_field_check.py+++ b/pipelex/pipe_operators/doc_gen/template_field_check.py@@ -13,6 +13,7 @@ import typingfrom collections.abc import Sequencefrom typing import Any, Union+from mthds.protocol.problem.registry import CoreCodefrom pydantic import BaseModelfrom pipelex.cogt.templating.template_preprocessor import rewrite_template_sigils@@ -121,7 +122,7 @@ def _check_path(*, path: TemplateFieldPath, inputs: InputStuffSpecs, pipe_code:f"PipeDocGen '{pipe_code}': the {label} reads '{path.written}'{reached}, but {holder} has no field '{missing_field}'. "f"Its fields are: {_describe_fields(model_class)}.")- raise PipeDocGenFactoryError(msg)+ raise PipeDocGenFactoryError(msg).with_error_code(CoreCode.METHOD_FIELD_PATH_UNRESOLVED)def check_template_field_paths(diff --git a/pipelex/pipe_operators/doc_gen/template_file_stage.py b/pipelex/pipe_operators/doc_gen/template_file_stage.pyindex feabc51bb..429fc5c64 100644--- a/pipelex/pipe_operators/doc_gen/template_file_stage.py+++ b/pipelex/pipe_operators/doc_gen/template_file_stage.py@@ -19,6 +19,7 @@ from collections.abc import Generatorfrom contextlib import contextmanagerfrom typing import NamedTuple+from mthds.protocol.problem.registry import CoreCodefrom typing_extensions import overridefrom pipelex import log@@ -159,7 +160,7 @@ class DocGenTemplateFileStage(TemplateFileStageProtocol):render_context = template_file.render_contextif 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)+ raise PipeDocGenRunError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)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)diff --git a/pipelex/pipe_operators/exceptions.py b/pipelex/pipe_operators/exceptions.pyindex a96b98ae8..5ac2ae2e2 100644--- a/pipelex/pipe_operators/exceptions.py+++ b/pipelex/pipe_operators/exceptions.py@@ -1,8 +1,19 @@+from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import PipelexError+from pipelex.errors.error_code_declaration import InheritsCausefrom pipelex.system.pipe_run_mode import PipeRunModeclass PipeOperatorModelAvailabilityError(PipelexError):+ """An operator found no model to run: the model it names is unknown, or no backend serves it.++ It takes its cause's code, the model lookup's own (``model.unknown`` for the method's reference,+ ``model.unavailable`` for this deployment's backends), and falls back to the deployment serving no backend.+ """++ error_code = InheritsCause(fallback=CoreCode.MODEL_UNAVAILABLE)+def __init__(self,message: str,diff --git a/pipelex/pipe_operators/extract/exceptions.py b/pipelex/pipe_operators/extract/exceptions.pyindex 6820db284..d94ae1359 100644--- a/pipelex/pipe_operators/extract/exceptions.py+++ b/pipelex/pipe_operators/extract/exceptions.py@@ -1,13 +1,16 @@-from pipelex.base_exceptions import ErrorDomain, PipelexError+from mthds.protocol.problem.registry import CoreCode++from pipelex.base_exceptions import PipelexErrorclass PipeExtractFactoryError(PipelexError):"""Raised when a ``PipeExtract``'s input is neither an image nor a document.- Raised only while the pipe is built from its blueprint, about that blueprint, so it is the author's to fix- (``input``) and bundle validation reports it as an item located on the pipe. Its messages name only the- author's own pipe, concepts and template text, so they are caller-facing copy kept under STRICT disclosure.+ Raised only while the pipe is built from its blueprint, about that blueprint, so it is the method's to fix+ (``method.schema_violation``) and bundle validation reports it as an item located on the pipe. Its messages+ name only the author's own pipe, concepts and template text, so they are caller-facing copy kept under STRICT+ disclosure."""- error_domain = ErrorDomain.INPUT+ error_code = CoreCode.METHOD_SCHEMA_VIOLATION_authors_caller_facing_message = Truediff --git a/pipelex/pipe_operators/extract/pipe_extract.py b/pipelex/pipe_operators/extract/pipe_extract.pyindex bc07b4b8c..527c484ba 100644--- a/pipelex/pipe_operators/extract/pipe_extract.py+++ b/pipelex/pipe_operators/extract/pipe_extract.py@@ -67,22 +67,22 @@ class PipeExtract(PipeOperator[PipeExtractOutput]):# it's an image, we can't accept documnt-related fieldsif self.should_caption_images:msg = "PipeExtract with image input cannot have should_caption_images set to True"- raise ValueError(msg)+ raise PipeValidationError(message=msg, domain_code=self.domain_code, pipe_code=self.code)if self.should_include_page_views:msg = "PipeExtract with image input cannot have should_include_page_views set to True"- raise ValueError(msg)+ raise PipeValidationError(message=msg, domain_code=self.domain_code, pipe_code=self.code)if self.page_views_dpi is not None:msg = "PipeExtract with image input cannot have page_views_dpi set"- raise ValueError(msg)+ raise PipeValidationError(message=msg, domain_code=self.domain_code, pipe_code=self.code)if self.max_page_images is not None:msg = "PipeExtract with image input cannot have max_page_images set"- raise ValueError(msg)+ raise PipeValidationError(message=msg, domain_code=self.domain_code, pipe_code=self.code)elif not concept_library.is_compatible(tested_concept=the_single_input.concept, wanted_concept=document_concept, strict=True):msg = ("The input to PipeExtract must be an image or a document (or a concept that refines one of them), "f"but is {the_single_input.concept.concept_ref}")- raise TypeError(msg)+ raise PipeValidationError(message=msg, domain_code=self.domain_code, pipe_code=self.code)@overridedef validate_output_static(self):diff --git a/pipelex/pipe_operators/func/direct_pipe_func_executor.py b/pipelex/pipe_operators/func/direct_pipe_func_executor.pyindex e43ba053f..bbaa464d2 100644--- a/pipelex/pipe_operators/func/direct_pipe_func_executor.py+++ b/pipelex/pipe_operators/func/direct_pipe_func_executor.py@@ -6,6 +6,7 @@ from pathlib import Pathfrom mthds.method_tree.exceptions import MethodTreeRefusedError, TreeSourceErrorfrom mthds.method_tree.models import MethodTreefrom mthds.method_tree.written_tree import read_written_tree+from mthds.protocol.problem.registry import CoreCodefrom typing_extensions import overridefrom pipelex import log@@ -17,10 +18,10 @@ from pipelex.core.method_trees.tree_files import write_call_filesfrom pipelex.core.method_trees.tree_python import TREE_PYTHON_HOLDfrom pipelex.core.stuffs.stuff_factory import StuffFactoryfrom pipelex.interpreter_hub import get_library_manager, get_required_pipe-from pipelex.kernel.func_ops import call_function+from pipelex.kernel.func_ops import coerce_function_output, invoke_functionfrom pipelex.libraries.library_crate import LibraryCratefrom pipelex.libraries.pipe_func_call_files import read_pipe_func_call_files-from pipelex.pipe_operators.func.exceptions import PipeFuncExecutionError+from pipelex.pipe_operators.func.exceptions import PipeFuncExecutionError, PipeFuncRaisedErrorfrom pipelex.pipe_operators.func.pipe_func import PipeFuncfrom pipelex.pipe_operators.func.pipe_func_call_context import function_of_call_in_flightfrom pipelex.pipe_operators.func.pipe_func_execution_dtos import PipeFuncExecutionRequest, PipeFuncExecutionResponse@@ -58,8 +59,8 @@ class DirectPipeFuncExecutor(PipeFuncExecutorProtocol):The function is the step's own: the `PipeFunc` imports it by its import path, under the process'shold on its method tree's Python, and checks it (`PipeFunc.bind_function`). What running it *means*— async-vs-sync dispatch and the str/list -> StuffContent coercion — is the kernel's- ``call_function``, so this executor is what is left once that is factored out: the in-process- wiring of the live arm, and the whole transported arm below.+ (``invoke_function``, then ``coerce_function_output``), so this executor is what is left once+ that is factored out: the in-process wiring of the live arm, and the whole transported arm below."""@override@@ -76,11 +77,20 @@ class DirectPipeFuncExecutor(PipeFuncExecutorProtocol):# The step imported and checked its function before the run (its `_validate_before_run`), and names it for its# call in flight; a call that names none, the transported run's, finds the step in the current library, which# binds it once. The call itself — async/sync dispatch, return coercion — is the kernel's, so an out-of-process- # executor and this one share one definition of what running a function means. Nothing is caught here: the- # function is arbitrary user code whose failure surface is not enumerable, and the operator wraps this call to- # decorate the failure with the pipe's inputs/output for a diagnostic PipeRunError.+ # executor and this one share one definition of what running a function means. What the function raised is+ # marked as its own, `PipeFuncRaisedError`, so the operator, which decorates the failure with the pipe's inputs+ # and output, tells it from a failure of this seam, which keeps its own code.function = function_of_call_in_flight(pipe_ref=pipe_code) or resolve_pipe_func(pipe_code=pipe_code).bind_function()- call_result = await call_function(function=function, function_name=function_name, memory=working_memory)+ try:+ function_output = await invoke_function(function=function, memory=working_memory)+ except Exception as exc:+ # Case (2), unbounded code: the function is arbitrary user code whose exception surface cannot be+ # enumerated. Whatever it raised is its failure, a coded Pipelex error a helper raised inside it included.+ msg = f"{type(exc).__name__}: {exc}"+ raise PipeFuncRaisedError(msg) from exc+ # Outside the function's failure: the kernel's coercion refusing what the function returned is the step's+ # output failing, `FuncOutputTypeError` with `pipe.output_invalid`, whatever shape it refused.+ call_result = coerce_function_output(function=function, function_output=function_output, function_name=function_name)return PipeFuncExecutionResult(content=call_result.content,function_module=call_result.function_module,@@ -208,7 +218,7 @@ class DirectPipeFuncExecutor(PipeFuncExecutorProtocol):)except TimeoutError as exc:msg = f"PipeFunc '{request.function_name}' exceeded its {request.timeout_seconds}s timeout"- raise PipeFuncExecutionError(msg) from exc+ raise PipeFuncExecutionError(msg).with_error_code(CoreCode.PIPE_FUNCTION_TIMED_OUT) 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)diff --git a/pipelex/pipe_operators/func/exceptions.py b/pipelex/pipe_operators/func/exceptions.pyindex 08bf5b450..32de965d0 100644--- a/pipelex/pipe_operators/func/exceptions.py+++ b/pipelex/pipe_operators/func/exceptions.py@@ -1,22 +1,43 @@-from pipelex.base_exceptions import ErrorDomain, PipelexError+from mthds.protocol.problem.registry import CoreCode++from pipelex.base_exceptions import PipelexError+from pipelex.errors.error_code_declaration import InheritsCauseclass PipeFuncTransportError(PipelexError):"""A PipeFunc could not be packaged for, or rebound from, out-of-process execution.Raised while building the transport request (e.g. no crate is available for the current library,- so the customer sources cannot travel) or while rehydrating the transported response.+ so the customer sources cannot travel) or while rehydrating the transported response: the library was not+ loaded the way out-of-process execution needs, which is the deployment's to fix."""+ error_code = CoreCode.RUNTIME_MISCONFIGURED+class PipeFuncExecutionError(PipelexError):"""A transported PipeFunc failed to run to a usable result out-of-process.Raised by the ``direct`` executor's transported run (the code a sandbox box runs internally) whenrehydration yields no working memory or the function exceeds its (plan-dependent) timeout — as- opposed to the customer function itself raising, which propagates untouched.+ opposed to the customer function itself raising, which propagates untouched. It takes its cause's code,+ else ``runtime.unexpected``; the timeout's raise site chooses ``pipe.function_timed_out``.+ """++ error_code = InheritsCause(fallback=CoreCode.RUNTIME_UNEXPECTED, others=(CoreCode.PIPE_FUNCTION_TIMED_OUT,))+++class PipeFuncRaisedError(PipelexError):+ """The function a PipeFunc step calls raised.++ Raised by the in-process executor from whatever the function's own code raised, so that the step tells a failure+ of its function from a failure of the seam that runs it: it is ``pipe.function_raised`` whatever the function+ raised, a coded Pipelex error included, which rides as its cause. Its message gives the type and the text of the+ function's exception, which can carry whatever the process holds, so it is not caller-facing."""+ error_code = CoreCode.PIPE_FUNCTION_RAISED+class PipeFuncFunctionError(PipelexError):"""A `PipeFunc`'s `function_name` names no function the step may call.@@ -27,6 +48,5 @@ class PipeFuncFunctionError(PipelexError):caller's own method, so it is kept under STRICT disclosure."""- error_domain = ErrorDomain.INPUT- retryable = False+ error_code = CoreCode.METHOD_FUNCTION_INVALID_authors_caller_facing_message = Truediff --git a/pipelex/pipe_operators/func/pipe_func.py b/pipelex/pipe_operators/func/pipe_func.pyindex c3a56bd9e..97099b9fb 100644--- a/pipelex/pipe_operators/func/pipe_func.py+++ b/pipelex/pipe_operators/func/pipe_func.py@@ -5,13 +5,13 @@ from typing import Any, Literal, cast, get_args, get_origin, get_type_hintsfrom mthds.method_tree.models import MethodTreefrom mthds.method_tree.tree_path import nfc+from mthds.protocol.problem.registry import CoreCodefrom pydantic import PrivateAttr, field_validatorfrom typing_extensions import overridefrom pipelex import logfrom pipelex.config import is_pipe_func_sandbox_hostedfrom pipelex.core.concepts.concept_factory import ConceptFactory-from pipelex.core.memory.exceptions import WorkingMemoryStuffNotFoundErrorfrom pipelex.core.memory.working_memory import WorkingMemoryfrom pipelex.core.memory.working_memory_factory import WorkingMemoryFactoryfrom pipelex.core.method_trees.building_bundle import BuildingBundle@@ -27,7 +27,7 @@ from pipelex.core.stuffs.stuff_content import StuffContentfrom pipelex.core.stuffs.stuff_factory import StuffFactoryfrom pipelex.interpreter_hub import get_current_library_id_or_none, get_pipe_func_executorfrom pipelex.kernel.memory_ops import store_result-from pipelex.pipe_operators.func.exceptions import PipeFuncFunctionError+from pipelex.pipe_operators.func.exceptions import PipeFuncFunctionError, PipeFuncRaisedErrorfrom pipelex.pipe_operators.func.function_name import function_name_form_violationfrom pipelex.pipe_operators.func.pipe_func_call_context import pipe_func_call_in_flightfrom pipelex.pipe_operators.func.pipe_func_python import (@@ -353,26 +353,22 @@ class PipeFunc(PipeOperator[PipeFuncOutput]):# PipeFunc runs arbitrary user code — in-process, or (in hosted mode) inside a sandbox# reached through a Temporal activity — whose failure surface is not enumerable; any# failure is wrapped into a diagnostic PipeRunError below. Re-raises, never swallows.- # Build informative error message with actual input values from working memory- inputs_lines: list[str] = []- for input_name in self.inputs.root:- try:- stuff = working_memory.get_stuff(name=input_name)- inputs_lines.append(f" {input_name} = {stuff.content!r}")- except WorkingMemoryStuffNotFoundError:- inputs_lines.append(f" {input_name} = <not found in working memory>")-- inputs_desc = "\n".join(inputs_lines) if inputs_lines else " none"+ # The message names the step's inputs, never their values: those are this run's content.+ inputs_desc = ", ".join(self.inputs.root) or "none"output_desc = self.output.to_bundle_representation()+ # The function's own exception, which the in-process executor marks as raised by the function.+ error_desc = exc.message if isinstance(exc, PipeFuncRaisedError) else f"{type(exc).__name__}: {exc}"msg = (- f"PipeFunc '{self.code}' failed during execution.\n"- f" Expected output: {output_desc}\n"- f" Inputs:\n{inputs_desc}\n\n"- f" Error: {type(exc).__name__}: {exc}"+ f"PipeFunc '{self.code}' failed during execution.\n Expected output: {output_desc}\n Inputs: {inputs_desc}\n\n Error: {error_desc}")# Not classified as the caller's fault: the function's own exception text can carry# whatever the process holds (a path, a setting, a secret), so it stays redacted under- # STRICT disclosure.+ # STRICT disclosure. The wrapper takes its cause's code. What the function raised reads+ # `pipe.function_raised` only because an executor marked it so: the in-process executor+ # raises it as `PipeFuncRaisedError`, and an out-of-process one must report a coded Pipelex+ # error the same way. A failure of the seam (a timeout, a sandbox that cannot run the call)+ # keeps its own code, and an exception that is not a Pipelex error proves nothing about the+ # function, such as a transport error, so it reads `runtime.unexpected`.raise PipeRunError(message=msg, run_mode=pipe_run_params.run_mode, pipe_code=self.code) from excthe_content = execution_result.content@@ -428,7 +424,9 @@ class PipeFunc(PipeOperator[PipeFuncOutput]):hinted_return_type = get_type_hints(function).get("return")if hinted_return_type is None:msg = f"Dry run of {self.type} '{self.code}' failed: function return type is None; it must be a subclass of StuffContent."- raise PipeRunError(message=msg, run_mode=pipe_run_params.run_mode, pipe_code=self.code)+ raise PipeRunError(message=msg, run_mode=pipe_run_params.run_mode, pipe_code=self.code).with_error_code(+ CoreCode.METHOD_FUNCTION_INVALID+ )return_type = hinted_return_type# Without an annotation (hosted mode), `return_type` is the ITEM structure class, so the@@ -498,7 +496,9 @@ class PipeFunc(PipeOperator[PipeFuncOutput]):# enumerable: an ImportError, the guard's refusal of a file the tree excludes included, or anything the# code raises. Wrapped on the step, as a failure of the function itself is, and never swallowed.msg = f"PipeFunc '{self.code}' cannot import the module of its function '{self.function_name}': {type(exc).__name__}: {exc}"- raise PipeRunError(message=msg, run_mode=pipe_run_params.run_mode, pipe_code=self.code) from exc+ raise PipeRunError(message=msg, run_mode=pipe_run_params.run_mode, pipe_code=self.code).with_error_code(+ CoreCode.METHOD_FUNCTION_INVALID+ ) from exc@overrideasync def _validate_after_run(diff --git a/pipelex/pipe_operators/img_gen/exceptions.py b/pipelex/pipe_operators/img_gen/exceptions.pyindex fc067a944..473cdf821 100644--- a/pipelex/pipe_operators/img_gen/exceptions.py+++ b/pipelex/pipe_operators/img_gen/exceptions.py@@ -1,9 +1,16 @@+from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import PipelexError+from pipelex.errors.error_code_declaration import InheritsCauseclass PipeImgGenRunError(PipelexError):- pass+ """A ``PipeImgGen`` could not gather what its prompt reads; it takes its cause's code, else a value it could not read."""++ error_code = InheritsCause(fallback=CoreCode.PIPE_INPUT_UNRESOLVED)class PipeImgGenFactoryError(PipelexError):- pass+ """The images a ``PipeImgGen`` prompt presents exceed what its model reads, found while the prompt is built at run time."""++ error_code = CoreCode.MODEL_CONTEXT_EXCEEDEDdiff --git a/pipelex/pipe_operators/img_gen/pipe_img_gen.py b/pipelex/pipe_operators/img_gen/pipe_img_gen.pyindex 4bf889f50..6e7b52bdc 100644--- a/pipelex/pipe_operators/img_gen/pipe_img_gen.py+++ b/pipelex/pipe_operators/img_gen/pipe_img_gen.py@@ -1,11 +1,13 @@from typing import Any, Literal+from mthds.protocol.problem.registry import CoreCodefrom pydantic import Fieldfrom typing_extensions import override+from pipelex.cogt.img_gen.exceptions import ImgGenSettingValueErrorfrom pipelex.cogt.img_gen.img_gen_job_components import AspectRatio, Background, ImgGenSizefrom pipelex.cogt.img_gen.img_gen_param_support import ImgGenParamSupport-from pipelex.cogt.img_gen.img_gen_setting import ImgGenModelChoice, ImgGenSetting, ImgGenSettingValueError+from pipelex.cogt.img_gen.img_gen_setting import ImgGenModelChoice, ImgGenSettingfrom pipelex.cogt.model_backends.model_type import ModelTypefrom pipelex.cogt.models.model_deck_check import check_img_gen_choice_with_deckfrom pipelex.core.concepts.native.concept_native import NativeConceptCode@@ -121,7 +123,7 @@ class PipeImgGen(PipeOperator[PipeImgGenOutput]):error_type=PipeValidationErrorType.UNKNOWN_VALIDATION_ERROR,domain_code=self.domain_code,pipe_code=self.code,- )+ ).with_error_code(CoreCode.MODEL_CAPABILITY_UNSUPPORTED)@overridedef validate_inputs_with_library(self):diff --git a/pipelex/pipe_operators/judge/exceptions.py b/pipelex/pipe_operators/judge/exceptions.pyindex 6b1f7d227..d2c0ea48a 100644--- a/pipelex/pipe_operators/judge/exceptions.py+++ b/pipelex/pipe_operators/judge/exceptions.py@@ -1,8 +1,15 @@-from pipelex.base_exceptions import ErrorDomain, PipelexError+from typing import ClassVar++from mthds.protocol.problem.registry import CoreCode++from pipelex.base_exceptions import PipelexError+from pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeDeclarationclass PipeJudgeError(PipelexError):- pass+ """Base of the refusals of a ``PipeJudge``."""++ error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERRORclass PipeJudgeInputCapabilityError(PipeJudgeError):@@ -14,7 +21,7 @@ class PipeJudgeInputCapabilityError(PipeJudgeError):the model and its declared inputs, so it is kept verbatim for the caller."""- error_domain = ErrorDomain.INPUT+ error_code = CoreCode.MODEL_CAPABILITY_UNSUPPORTED_authors_caller_facing_message = Truedef __init__(self, *, pipe_code: str, variable_path: str, file_kind: str, model_name: str, model_inputs: list[str]):diff --git a/pipelex/pipe_operators/judge/pipe_judge.py b/pipelex/pipe_operators/judge/pipe_judge.pyindex 804fe61ed..6a768ed8f 100644--- a/pipelex/pipe_operators/judge/pipe_judge.py+++ b/pipelex/pipe_operators/judge/pipe_judge.py@@ -1,5 +1,6 @@from typing import Any, Literal, Self+from mthds.protocol.problem.registry import CoreCodefrom pydantic import BaseModel, ConfigDict, model_validatorfrom typing_extensions import override@@ -469,7 +470,7 @@ class PipeJudge(PipeOperator[PipeJudgeOutput]):result_memory = judgment_result.memoryelse:msg = f"PipeJudge '{self.code}' asks no question, which its construction refuses."- raise PipeValidationError(message=msg, domain_code=self.domain_code, pipe_code=self.code)+ raise PipeValidationError(message=msg, domain_code=self.domain_code, pipe_code=self.code).with_error_code(CoreCode.RUNTIME_UNEXPECTED)# Capture execution data for the graph tracer.self._register_execution_data(job_metadata=job_metadata, execution_data=execution_data_dict)diff --git a/pipelex/pipe_operators/llm/exceptions.py b/pipelex/pipe_operators/llm/exceptions.pyindex 28bd6b179..1bd64a1ca 100644--- a/pipelex/pipe_operators/llm/exceptions.py+++ b/pipelex/pipe_operators/llm/exceptions.py@@ -1,13 +1,16 @@-from pipelex.base_exceptions import ErrorDomain, PipelexError+from mthds.protocol.problem.registry import CoreCode++from pipelex.base_exceptions import PipelexErrorclass PipeLLMFactoryError(PipelexError):"""Raised when a ``PipeLLM``'s prompt template, or the system prompt it declares or inherits from its domain, does not parse.- Raised only while the pipe is built from its blueprint, about that blueprint, so it is the author's to fix- (``input``) and bundle validation reports it as an item located on the pipe. Its messages name only the- author's own pipe, concepts and template text, so they are caller-facing copy kept under STRICT disclosure.+ Raised only while the pipe is built from its blueprint, about that blueprint, so it is the method's to fix+ (``method.template_invalid``) and bundle validation reports it as an item located on the pipe. Its messages+ name only the author's own pipe, concepts and template text, so they are caller-facing copy kept under STRICT+ disclosure."""- error_domain = ErrorDomain.INPUT+ error_code = CoreCode.METHOD_TEMPLATE_INVALID_authors_caller_facing_message = Truediff --git a/pipelex/pipe_operators/llm/pipe_llm.py b/pipelex/pipe_operators/llm/pipe_llm.pyindex 21ab95d92..74e98cf7d 100644--- a/pipelex/pipe_operators/llm/pipe_llm.py+++ b/pipelex/pipe_operators/llm/pipe_llm.py@@ -1,13 +1,16 @@from typing import TYPE_CHECKING, Any, Literal+from mthds.protocol.problem.registry import CoreCodefrom pydantic import ValidationErrorfrom typing_extensions import overridefrom pipelex.base_exceptions import iter_cause_chainfrom pipelex.cogt.exceptions import LLMCompletionError, ModelChoiceNotFoundError+from pipelex.cogt.inference.error_classification import UserAction, UserActionKindfrom pipelex.cogt.llm.llm_setting import LLMModelChoice, LLMSetting, LLMSettingChoicesfrom pipelex.cogt.models.model_deck_check import check_llm_choice_with_deckfrom pipelex.cogt.models.model_reference import ModelReference+from pipelex.cogt.templating.template_preprocessor import rewrite_template_sigilsfrom pipelex.core.concepts.concept_factory import ConceptFactoryfrom pipelex.core.concepts.native.concept_native import NativeConceptCodefrom pipelex.core.domains.domain import SpecialDomain@@ -40,6 +43,8 @@ from pipelex.pipe_run.pipe_run_params import (from pipelex.runtime_hub import get_class_registryfrom pipelex.system.job_metadata import JobMetadatafrom pipelex.system.pipe_run_param_key import PipeRunParamKey+from pipelex.tools.jinja2.exceptions import Jinja2TemplateInvalidError+from pipelex.tools.jinja2.jinja2_unknown_names import find_unknown_filters_and_testsfrom pipelex.tools.misc.string_utils import get_root_from_dotted_pathfrom pipelex.tools.templating.templating_style import TemplatingStylefrom pipelex.tools.typing.pydantic_utils import format_pydantic_validation_error@@ -328,6 +333,12 @@ class PipeLLM(PipeOperator[PipeLLMOutput]):result_name=output_name,result_code=pipe_run_params.final_stuff_code,)+ except Jinja2TemplateInvalidError as exc:+ if not exc.template_owner.is_method:+ # One of Pipelex's own templates failed within the step, such as the deployment's structure prompt:+ # ours, `runtime.unexpected`, which must not reach the caller as a fault of the method's prompt.+ raise+ raise self._make_invalid_prompt_error(invalid_template_error=exc, pipe_run_params=pipe_run_params) from excexcept LLMCompletionError as exc:location = self._format_error_location(pipe_run_params=pipe_run_params)error_details = self._format_llm_error(exc=exc, settings=[llm_setting_main])@@ -340,7 +351,9 @@ class PipeLLM(PipeOperator[PipeLLMOutput]):location = self._format_error_location(pipe_run_params=pipe_run_params)error_details = format_pydantic_validation_error(exc)msg = f"Error generating text content in PipeLLM {location}: {error_details}"- raise PipeRunError(message=msg, run_mode=pipe_run_params.run_mode, pipe_code=self.code) from exc+ raise PipeRunError(message=msg, run_mode=pipe_run_params.run_mode, pipe_code=self.code).with_error_code(+ CoreCode.MODEL_OUTPUT_SCHEMA_MISMATCH+ ) from excworking_memory = text_result.memoryrendered_llm_prompt = text_result.rendered_promptstructuring_path = text_result.structuring_path@@ -361,6 +374,12 @@ class PipeLLM(PipeOperator[PipeLLMOutput]):result_name=output_name,result_code=pipe_run_params.final_stuff_code,)+ except Jinja2TemplateInvalidError as exc:+ if not exc.template_owner.is_method:+ # One of Pipelex's own templates failed within the step, such as the deployment's structure prompt:+ # ours, `runtime.unexpected`, which must not reach the caller as a fault of the method's prompt.+ raise+ raise self._make_invalid_prompt_error(invalid_template_error=exc, pipe_run_params=pipe_run_params) from excexcept LLMCompletionError as exc:location = self._format_error_location(pipe_run_params=pipe_run_params)error_details = self._format_llm_error(exc=exc, settings=[llm_setting_for_object])@@ -391,6 +410,41 @@ class PipeLLM(PipeOperator[PipeLLMOutput]):pipeline_run_id=job_metadata.run_metadata.pipeline_run_id,)+ def _make_invalid_prompt_error(self, *, invalid_template_error: Jinja2TemplateInvalidError, pipe_run_params: PipeRunParams) -> PipeRunError:+ """The refusal of a method's prompt that cannot render as written, naming the pipe, the prompt field and what Jinja2 refused.++ Such a prompt names a filter or a test its environment does not define inside a branch, which only rendering that+ branch finds, since a prompt is parsed at load and not compiled. The render reports what Jinja2 refused, not+ which prompt it was, so the prompt fields are named by which of them names an unknown filter or test. The+ message never quotes a prompt's text.+ """+ field_names: list[str] = []+ for template_blueprint, template_label in [+ (self.llm_prompt_spec.system_prompt_blueprint, "system_prompt"),+ (self.llm_prompt_spec.prompt_blueprint, "prompt"),+ ]:+ if template_blueprint is None:+ continue+ unknown_names = find_unknown_filters_and_tests(+ template_source=rewrite_template_sigils(template_blueprint.template),+ template_category=template_blueprint.category,+ )+ if unknown_names:+ field_names.append(template_label)+ where = " and its ".join(field_names) if field_names else "prompt"+ fault = invalid_template_error.fault+ msg = f"PipeLLM '{self.code}': its {where} cannot render: {fault}"+ return (+ PipeRunError(message=msg, run_mode=pipe_run_params.run_mode, pipe_code=self.code)+ .with_error_code(CoreCode.METHOD_TEMPLATE_INVALID)+ .as_caller_fault(+ user_action=UserAction(+ kind=UserActionKind.CHANGE_INPUT,+ detail=f"Fix the {where} of PipeLLM '{self.code}': {fault}",+ )+ )+ )+def _format_error_location(self, pipe_run_params: PipeRunParams) -> str:return f"in pipe '{pipe_run_params.pipe_stack_str}'"diff --git a/pipelex/pipe_operators/pipe_operator.py b/pipelex/pipe_operators/pipe_operator.pyindex 7174d0910..43529413e 100644--- a/pipelex/pipe_operators/pipe_operator.py+++ b/pipelex/pipe_operators/pipe_operator.py@@ -5,7 +5,7 @@ from typing import TYPE_CHECKING, Generic, Literal, TypeVar, finalfrom typing_extensions import override-from pipelex.cogt.exceptions import ModelChoiceNotFoundError, ModelNotFoundError, ModelWaterfallError+from pipelex.cogt.exceptions import ModelChoiceNotFoundError, ModelDeckChoiceUnresolvedError, ModelNotFoundError, ModelWaterfallErrorfrom pipelex.core.memory.working_memory import WorkingMemoryfrom pipelex.core.pipes.exceptions import PipeOperatorModelChoiceErrorfrom pipelex.core.pipes.pipe_output import PipeOutput@@ -39,9 +39,15 @@ class PipeOperator(PipeAbstract, Generic[PipeOperatorOutputType]):pipe type — which bundle validation turns into one ``unknown_model`` item. ``field_name`` is theblueprint field the reference was written in (``model``, or ``model_to_structure`` on a``PipeLLM``), the key a fix rewrites.++ A miss of a choice the deck names itself, the default a step naming no model runs on, is the deployment's+ fault and leaves unchanged as its ``ModelDeckChoiceUnresolvedError``: located on the pipe, it would read+ as the caller's unknown model, and its message, which names the deck's setting, would reach the caller."""try:yield+ except ModelDeckChoiceUnresolvedError:+ raiseexcept ModelChoiceNotFoundError as model_choice_error:raise PipeOperatorModelChoiceError.make_from_model_choice_not_found(model_choice_error=model_choice_error,diff --git a/pipelex/pipe_operators/search/exceptions.py b/pipelex/pipe_operators/search/exceptions.pydeleted file mode 100644index bfe184a67..000000000--- a/pipelex/pipe_operators/search/exceptions.py+++ /dev/null@@ -1,9 +0,0 @@-from pipelex.base_exceptions import PipelexError---class PipeSearchFactoryError(PipelexError):- pass---class PipeSearchError(PipelexError):- passdiff --git a/pipelex/pipe_operators/shared/exceptions.py b/pipelex/pipe_operators/shared/exceptions.pyindex 12e26314f..9c05f44d0 100644--- a/pipelex/pipe_operators/shared/exceptions.py+++ b/pipelex/pipe_operators/shared/exceptions.py@@ -1,5 +1,9 @@+from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import PipelexErrorclass WithImagesFilterError(PipelexError):- """Raised when | with_images is used on a type without nested images."""+ """Raised when | with_images is used on a type without nested images: a template of the method that cannot work."""++ error_code = CoreCode.METHOD_TEMPLATE_INVALIDdiff --git a/pipelex/pipe_run/delivery_executor.py b/pipelex/pipe_run/delivery_executor.pyindex e6d9faa31..ea08d3369 100644--- a/pipelex/pipe_run/delivery_executor.py+++ b/pipelex/pipe_run/delivery_executor.py@@ -18,7 +18,8 @@ from pipelex.core.memory.absence import AbsenceRecordfrom pipelex.core.memory.absence_render import build_absence_html, build_absence_json, build_absence_markdownfrom pipelex.core.memory.working_memory import MAIN_STUFF_NAMEfrom pipelex.core.pipes.pipe_io_artifacts import INPUT_FORM_FILE_NAME, OUTPUT_FORM_FILE_NAME, PIPE_IO_CONTRACTS_FILE_NAME-from pipelex.core.qualified_ref import QualifiedRef, QualifiedRefError+from pipelex.core.qualified_ref import QualifiedRef+from pipelex.core.qualified_ref_exceptions import QualifiedRefErrorfrom pipelex.core.stuffs.stuff import Stufffrom pipelex.core.stuffs.stuff_content import StuffContentfrom pipelex.core.stuffs.stuff_viewer import render_stuff_viewerdiff --git a/pipelex/pipe_run/exceptions.py b/pipelex/pipe_run/exceptions.pyindex 4e1f803da..e3e418a88 100644--- a/pipelex/pipe_run/exceptions.py+++ b/pipelex/pipe_run/exceptions.py@@ -1,9 +1,12 @@-from typing import Self+from typing import ClassVar, Self+from mthds.protocol.problem.registry import CoreCodefrom typing_extensions import override-from pipelex.base_exceptions import ErrorDomain, ErrorReport, PipelexError, iter_cause_chain+from pipelex.base_exceptions import ErrorReport, PipelexError, iter_cause_chainfrom pipelex.core.exceptions import DryRunFailureErrorData+from pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeDeclaration, InheritsCause+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.pipe_run.located_failure import build_located_failure_report, locate_failure_messagefrom pipelex.system.pipe_run_mode import PipeRunMode@@ -15,19 +18,16 @@ class AsyncExecutionNotEnabledError(PipelexError):Backend-neutral on purpose, because it is the shared contract between therunner API — which maps it to an HTTP status (501) — and any async-executionbackend plugin that raises it: the Temporal plugin today, other async backends- (e.g. Mistral Workflows) as support lands. Nothing in this repo raises it. The- class name, title, and detail therefore talk about *async execution* as a+ (e.g. Mistral Workflows) as support lands. In this repo, the local runtime's+ ``PipelexMTHDSProtocol.start`` raises it, since it runs nothing asynchronously.+ The class name, title, and detail therefore talk about *async execution* as acapability of the deployment, not about any specific backend brand.- ``error_domain = CONFIG`` because the caller's request is well-formed; what- is missing is server-side configuration. The pipelex-api layer maps this- class to HTTP 501 (Not Implemented), which is more precise than the- ``CONFIG`` -> 500 default and tells clients the failure is permanent under- the current deployment rather than a transient runtime fault.+ Its code is ``runtime.unsupported``: the caller's request is well-formed, and what is missing is a+ capability of this deployment, permanent under it, so the caller's useful step is the synchronous route."""- error_domain = ErrorDomain.CONFIG- _declared_title = "Async execution not enabled"+ error_code = CoreCode.RUNTIME_UNSUPPORTEDDEFAULT_MESSAGE = ("Asynchronous pipeline execution is not enabled on this deployment. "@@ -48,27 +48,37 @@ class AsyncExecutionNotEnabledError(PipelexError):class PipeRunParamsError(PipelexError):- pass+ """A pipe's declaration and the run's params cannot settle a value the pipe needs, such as an image count."""--class BatchParamsError(PipelexError):- pass+ error_code = CoreCode.METHOD_SCHEMA_VIOLATIONclass PipeJobError(PipelexError):- pass+ """Our own serialized run state could not be rebuilt, or a completed run broke an invariant of ours.++ It declares its own code rather than taking its cause's: a concept-library error raised while rehydrating+ a run's memory is a fault of the transport, not of the method's concepts.+ """++ error_code = CoreCode.RUNTIME_UNEXPECTEDclass DeliveryError(PipelexError):- pass+ """Base of the failures to deliver a finished run's results."""++ error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERRORclass WebhookDeliveryError(DeliveryError):- pass+ """A webhook announcing a run's outcome could not be delivered."""++ error_code = PipelexErrorCode.WEBHOOK_DELIVERY_FAILEDclass StorageDeliveryError(DeliveryError):- pass+ """A finished run's results could not be stored; it takes its cause's code, else storage being unavailable."""++ error_code = InheritsCause(fallback=PipelexErrorCode.STORAGE_UNAVAILABLE)class DryRunError(PipelexError):@@ -79,9 +89,12 @@ class DryRunError(PipelexError):keeps the failure's own text only when that text is caller-facing and otherwise names the failure'stitle.- Raised elsewhere it may carry no failures, and validation then reports it as one item.+ Raised elsewhere it may carry no failures, and validation then reports it as one item. It takes the code of+ its cause, the failure it reports."""+ error_code: ClassVar[ErrorCodeDeclaration] = InheritsCause(fallback=CoreCode.RUNTIME_UNEXPECTED)+def __init__(self, message: str, *, failures: list[DryRunFailureErrorData] | None = None):self.failures = failures or []super().__init__(message)@@ -94,9 +107,12 @@ class DryRunGraphNotProducedError(DryRunError):graph, so a run that finishes without one is a contract violation on their side — not avalidation failure of the bundle. Distinct from the bare ``PipelexError`` it replaces so thathosts logging only the exception type (e.g. pipelex-api's best-effort ``/validate`` graph step)- get an unambiguous signal.+ get an unambiguous signal. Bundle validation lets it through rather than turning it into a ``dry_run``+ item, since the bundle is not at fault."""+ error_code = CoreCode.RUNTIME_UNEXPECTED+class PipeRouterError(PipelexError):"""A pipe failed while running: the failure, located at the pipe where it happened.@@ -106,9 +122,12 @@ class PipeRouterError(PipelexError):carries one keeps it as it rises through the routers of the controllers above, so the innermostlocation is the one reported. Its report is its root fault's, located (see`pipelex.pipe_run.located_failure`): a run whose pipe raised `StuffFactoryError` reports- `StuffFactoryError`, with a message naming the pipe and its path, never `PipeRouterError`.+ `StuffFactoryError`, with a message naming the pipe and its path, never `PipeRouterError`, and its code+ is the root fault's."""+ error_code = InheritsCause(fallback=CoreCode.RUNTIME_UNEXPECTED)+def __init__(self,message: str,diff --git a/pipelex/pipe_run/located_failure.py b/pipelex/pipe_run/located_failure.pyindex c7248b944..0542a1338 100644--- a/pipelex/pipe_run/located_failure.py+++ b/pipelex/pipe_run/located_failure.py@@ -3,18 +3,21 @@When a pipe fails during a run, the error that reaches a surface sits under several wrappers: thepipe router's `PipeRouterError`, which knows the failing pipe and its stack, maybe a runtime bridge's`PipelexBridgeDispatchError`, and the runner's `PipelineExecutionError`. None of them is what went-wrong. The report of such a failure is therefore built from its **root fault**, the innermost-`PipelexError` of the cause chain, and only located by the wrappers:--- the root fault stops at a foreign exception, whose stand-in is the fault, and an error raised from- one of its own class counts as the outer, more contextual one (see `find_root_fault`);-- the identity (`error_type`, `title`, `type_uri`) is the root fault's, and so are its caller-facing- flag, its `validation_errors` and its `migration`;+wrong, and each takes its cause's code. The report of such a failure is therefore built from its+**root fault**, the error whose code the failure resolves to, and only located by the wrappers:++- the root fault is the first `PipelexError` down the cause chain that carries a code of its own, the+ same walk `PipelexError.resolve_error_code` makes, so a wrapper that adds the fact deciding the code+ is the root fault over a coded cause; when none carries one, it is the innermost `PipelexError`. The+ walk stops at a foreign exception, whose stand-in is the fault (see `find_root_fault`);+- the identity (`code`, `error_type`, `title`, `type_uri`, and the domain and retry verdict the code+ decides) is the root fault's, and so are its caller-facing flag, its `validation_errors` and its+ `migration`;- the message names the failing pipe and its path from the entry pipe, then gives the root fault'sown message unaltered. Pipe codes are the caller's own names, so the message is caller-facingexactly when the root fault's is;-- the classification is the cause-chain enrichment's, floored at `runtime`, and when nothing on the- chain carries a user action, the fallback names the failing pipe.+- the diagnostics are the cause-chain enrichment's, and when nothing on the chain carries a user+ action, the fallback names the failing pipe.`ErrorReport` has no location field, so the location rides the message until the error contractgives it one. A root fault whose report was recovered across a transport boundary (a report@@ -26,7 +29,7 @@ the root fault's own report with its location rather than a located report (seefrom pydantic import ValidationError-from pipelex.base_exceptions import ErrorDomain, ErrorReport, PipelexError, PipelexUnexpectedError, iter_cause_chain+from pipelex.base_exceptions import ErrorReport, PipelexError, PipelexUnexpectedError, iter_cause_chainfrom pipelex.cogt.inference.error_classification import UserAction, UserActionKindfrom pipelex.tools.typing.pydantic_utils import format_pydantic_validation_error@@ -35,24 +38,32 @@ PIPE_PATH_SEPARATOR = " → "def find_root_fault(*, error: BaseException) -> PipelexError | None:- """Return the innermost `PipelexError` on `error`'s cause chain, `error` itself included.-- That is the error that knows what went wrong: every `PipelexError` above it on the chain is a- wrapper that located it or carried it across a boundary. Two exceptions to "innermost": the walk- stops at the first exception that is not a `PipelexError`, since what caused a foreign exception- is that code's own affair and the `PipelexUnexpectedError` standing in for it is the fault; and- a `PipelexError` raised from one of its own class restates that fault with more context (an- item index, a remedy), so the outer one is kept. `None` when the chain starts with no- `PipelexError`.+ """Return the `PipelexError` on `error`'s cause chain whose code the failure reports, `error` itself included.++ That is the first `PipelexError` down the chain that carries a code of its own+ (`PipelexError.own_error_code`), the error `resolve_error_code` stops at: every `PipelexError`+ above it takes its cause's code, being a wrapper that located it or carried it across a boundary.+ When no error on the chain carries a code of its own, it is the deepest error implying one+ (`PipelexError.implied_error_code`), whose code the failure reports, and else the innermost+ `PipelexError`, whose fallback the failure reports. The walk stops at the first exception that is not a `PipelexError`,+ since what caused a foreign exception is that code's own affair and the `PipelexUnexpectedError`+ standing in for it is the fault; and among wrappers that carry no code, one raised from its own+ class restates that fault with more context, so the outer one is kept. `None` when the chain+ starts with no `PipelexError`."""root_fault: PipelexError | None = None+ implying_fault: PipelexError | None = Nonefor node in iter_cause_chain(error):if not isinstance(node, PipelexError):break+ if node.own_error_code is not None:+ return node+ if node.implied_error_code is not None:+ implying_fault = nodeif root_fault is not None and type(node) is type(root_fault):continueroot_fault = node- return root_fault+ return implying_fault or root_faultdef find_foreign_fault(*, error: BaseException) -> BaseException | None:@@ -138,22 +149,22 @@ def build_located_failure_report(wrapper: The located wrapper whose report this is (a `PipeRouterError` or a`PipelineExecutionError`).own_report: The wrapper's own report, as `PipelexError.to_error_report` builds it: its own- identity, and the classification enriched from its cause chain.+ identity, and the diagnostics enriched from its cause chain.pipe_code: The pipe that failed.pipe_stack: That pipe's path from the entry pipe, ending with it. Empty when the location isunknown, in which case the message is the root fault's, unlocated.Returns:- The root fault's report, with the located message and the chain's classification.+ The root fault's report, carrying its code and what the code decides, with the located message and+ the chain's diagnostics."""- root_fault = _find_root_fault_below(wrapper=wrapper)+ # A wrapper whose raise site chose its code is the root fault itself, as `resolve_error_code` reads it.+ root_fault = None if wrapper.own_error_code is not None else _find_root_fault_below(wrapper=wrapper)identity_report = root_fault.to_error_report() if root_fault is not None else own_reportreturn identity_report.model_copy(update={"message": compose_located_message(pipe_code=pipe_code, pipe_stack=pipe_stack, message=identity_report.message),"error_category": own_report.error_category,- "error_domain": own_report.error_domain or ErrorDomain.RUNTIME,- "retryable": own_report.retryable,"user_action": own_report.user_action or _fallback_user_action(pipe_code=pipe_code, pipe_stack=pipe_stack),"model": own_report.model,"provider": own_report.provider,diff --git a/pipelex/pipe_signature/exceptions.py b/pipelex/pipe_signature/exceptions.pyindex 2edf7a90e..b1cafe5e4 100644--- a/pipelex/pipe_signature/exceptions.py+++ b/pipelex/pipe_signature/exceptions.py@@ -1,3 +1,5 @@+from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import PipelexError@@ -13,6 +15,8 @@ class PipeSignatureNotExecutableError(PipelexError):+ `is_runnable`), not a validation error (D-B). Running a stub, by contrast, must fail."""+ error_code = CoreCode.METHOD_NOT_RUNNABLE+def __init__(self, pipe_ref: str) -> None:self.pipe_ref = pipe_refmessage = (diff --git a/pipelex/pipelex.py b/pipelex/pipelex.pyindex dc36a538a..5ff8dbd65 100644--- a/pipelex/pipelex.py+++ b/pipelex/pipelex.py@@ -18,6 +18,7 @@ from pathlib import Pathfrom typing import Any, Selffrom kajson.class_registry_abstract import ClassRegistryAbstract+from mthds.protocol.problem.registry import CoreCodefrom typing_extensions import overridefrom pipelex import log@@ -105,7 +106,7 @@ class Pipelex(RuntimeBoot):) -> None:if kwargs:msg = f"The Pipelex setup method does not support any additional arguments: {kwargs}"- raise PipelexSetupError(msg)+ raise PipelexSetupError(msg).with_error_code(CoreCode.RUNTIME_MISCONFIGURED)# The kernel layer first, with the *composed* plugin manifests: this process will run methods,# so it needs the interpreter-touching built-ins (the `direct` orchestrator, the built-in@@ -139,7 +140,7 @@ class Pipelex(RuntimeBoot):plugin_registrar = self._plugin_registrarif plugin_registrar is None:msg = "The plugin registrar must be built by the runtime setup before the interpreter setup runs"- raise PipelexSetupError(msg)+ raise PipelexSetupError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)pipe_func_executor_registry = PipeFuncExecutorRegistry(plugin_registrar.pipe_func_executors)self.interpreter_hub.set_pipe_func_executor_registry(pipe_func_executor_registry)@@ -195,7 +196,7 @@ class Pipelex(RuntimeBoot):# halves carries no meaning beyond that.if self.class_registry is None:msg = "The class registry must be created by the runtime setup before the interpreter setup runs"- raise PipelexSetupError(msg)+ raise PipelexSetupError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)self.class_registry.register_classes(PipeRegistryModels.get_all_models())# --- Pipe Router -----------------------------------------------------------------------diff --git a/pipelex/pipeline/blueprint_selection.py b/pipelex/pipeline/blueprint_selection.pyindex 4ad15eaff..a06e4da96 100644--- a/pipelex/pipeline/blueprint_selection.py+++ b/pipelex/pipeline/blueprint_selection.py@@ -11,6 +11,8 @@ without an import cycle through ``bundle_validator``.from typing import NamedTuple, Sequence+from mthds.protocol.problem.registry import CoreCode+from pipelex.mthds_parsing.pipelex_bundle_blueprint import PipelexBundleBlueprintfrom pipelex.pipe_machinery.pipe_factory import PipeFactoryfrom pipelex.pipeline.exceptions import ValidateBundleError@@ -45,7 +47,7 @@ def select_primary_blueprint(blueprints: Sequence[PipelexBundleBlueprint]) -> Pr"""if not blueprints:msg = "Cannot select a primary blueprint from an empty batch: no MTHDS contents were provided."- raise ValidateBundleError(message=msg)+ raise ValidateBundleError(message=msg).with_error_code(CoreCode.REQUEST_INVALID)for blueprint in blueprints:if blueprint.main_pipe:main_pipe_ref = PipeFactory.make_pipe_ref_with_domain(domain_code=blueprint.domain, pipe_code=blueprint.main_pipe)diff --git a/pipelex/pipeline/dry_run_pipeline.py b/pipelex/pipeline/dry_run_pipeline.pyindex 2dabd9013..bb9aa8877 100644--- a/pipelex/pipeline/dry_run_pipeline.py+++ b/pipelex/pipeline/dry_run_pipeline.py@@ -11,6 +11,9 @@ against an already-open library without dispatching. The twin's callers (the procycle, which is why the two entrypoints are separate modules at separate altitudes."""+from mthds.protocol.problem.registry import CoreCode++from pipelex.base_exceptions import PipelexUnexpectedErrorfrom pipelex.config import get_configfrom pipelex.graph.graphspec import GraphSpecfrom pipelex.mthds_parsing.exceptions import MthdsParserError@@ -55,8 +58,9 @@ async def dry_run_pipeline(PipelineExecutionError: If dry-run execution fails."""if not mthds_contents:+ # Every caller passes the contents it validated, so none is a bug of ours.msg = "mthds_contents must be provided"- raise ValueError(msg)+ raise PipelexUnexpectedError(msg)# Pre-parse contents to extract the default main pipe's domain-qualified ref via the one# shared selection rule. Note: pipeline_run_setup will re-parse these contents. The@@ -65,12 +69,12 @@ async def dry_run_pipeline(blueprints = [MthdsParser.make_pipelex_bundle_blueprint(mthds_content=content) for content in mthds_contents]if pipe_code is not None and not pipe_code.strip():msg = "pipe_code must not be blank when provided"- raise MthdsParserError(msg)+ raise MthdsParserError(msg).with_error_code(CoreCode.REQUEST_INVALID)pipe_ref = pipe_code if pipe_code is not None else select_primary_blueprint(blueprints).main_pipe_refif not pipe_ref:msg = "Bundle does not declare a main_pipe, cannot generate graph"- raise MthdsParserError(msg)+ raise MthdsParserError(msg).with_error_code(CoreCode.REQUEST_PIPE_UNSPECIFIED)execution_config = get_config().interpreter.pipeline_execution.with_execution_overrides(generate_graph=True,diff --git a/pipelex/pipeline/exceptions.py b/pipelex/pipeline/exceptions.pyindex f80d19936..497488002 100644--- a/pipelex/pipeline/exceptions.py+++ b/pipelex/pipeline/exceptions.py@@ -1,10 +1,11 @@import refrom collections.abc import Collection-from typing import NamedTuple, Self, TypeVar+from typing import ClassVar, NamedTuple, Self, TypeVar+from mthds.protocol.problem.registry import CoreCodefrom typing_extensions import override-from pipelex.base_exceptions import ErrorDomain, ErrorReport, PipelexError, ValidationErrorItem+from pipelex.base_exceptions import ErrorReport, PipelexError, ValidationErrorItemfrom pipelex.cogt.inference.error_classification import UserAction, UserActionKindfrom pipelex.core.exceptions import (DryRunFailureErrorData,@@ -12,6 +13,8 @@ from pipelex.core.exceptions import (PipelexBundleBlueprintValidationErrorData,PipesAndConceptValidationErrorData,)+from pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeDeclaration, ErrorCodeSet, InheritsCause+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.pipe_run.exceptions import find_failure_locationfrom pipelex.pipe_run.located_failure import build_located_failure_report, locate_failure_messagefrom pipelex.pipeline.validation_errors import build_validation_error_items@@ -19,7 +22,9 @@ from pipelex.system.pipe_run_mode import PipeRunModeclass PipeExecutionError(PipelexError):- error_domain = ErrorDomain.RUNTIME+ """A run the runner cannot set up: no pipe to start at, or inputs that do not fit the run's models."""++ error_code = ErrorCodeSet(default=CoreCode.RUNTIME_UNEXPECTED, others=(CoreCode.REQUEST_PIPE_UNSPECIFIED, CoreCode.INPUT_INVALID))class PipelineExecutionError(PipelexError):@@ -32,15 +37,18 @@ class PipelineExecutionError(PipelexError):(it happened outside any routed pipe run, or it crossed a transport boundary as a report thatalready names its pipe), ``pipe_code`` is the entry pipe and ``pipe_stack`` is empty.- Its report is not its own. ``to_error_report()`` takes the identity (``error_type``, ``title``,- ``type_uri``), the message and the caller-facing flag of the root fault, the innermost- ``PipelexError`` on the cause chain, or the report such an error recovered across a transport- boundary; the message is prefixed with the failing pipe and its path. The classification is+ Its report is not its own. It takes its cause's code, and ``to_error_report()`` takes the identity+ (``code``, ``error_type``, ``title``, ``type_uri``, and the domain and retry verdict the code+ decides), the message and the caller-facing flag of the root fault, the first ``PipelexError`` on+ the cause chain that carries a code of its own, or the report such an error recovered across a+ transport boundary; the message is prefixed with the failing pipe and its path. The diagnostics areinherited from the cause chain (so a categorized ``CogtError`` keeps its ``WAIT_AND_RETRY`` /- ``CHECK_BILLING`` action), with a ``RUNTIME`` floor and, when nothing on the chain advises an- action, a fallback that names the failing pipe. See ``pipelex.pipe_run.located_failure``.+ ``CHECK_BILLING`` action) and, when nothing on the chain advises an action, a fallback names the+ failing pipe. See ``pipelex.pipe_run.located_failure``."""+ error_code = InheritsCause(fallback=CoreCode.RUNTIME_UNEXPECTED)+def __init__(self,message: str,@@ -97,6 +105,10 @@ class PipelineExecutionError(PipelexError):class PipeStackOverflowError(PipelexError):+ """A run nested pipes deeper than the configured limit, usually a method that recurses."""++ error_code = CoreCode.PIPE_STACK_OVERFLOW+def __init__(self, message: str, limit: int, pipe_stack: list[str]):self.limit = limitself.pipe_stack = list(pipe_stack) # snapshot: the live stack unwinds after this error is raised@@ -104,11 +116,15 @@ class PipeStackOverflowError(PipelexError):class PipelineManagerNotFoundError(PipelexError):- pass+ """The pipeline manager holds no run under an id it was asked for: an internal lookup of ours."""++ error_code = CoreCode.RUNTIME_UNEXPECTEDclass PipelineManagerAlreadyExistsError(PipelexError):- pass+ """A run id the caller supplied is still in flight; the next step is to pick another id."""++ error_code = PipelexErrorCode.RUN_ALREADY_EXISTSdef _summarize_bundle_validation_message(@@ -231,9 +247,12 @@ class ValidateBundleError(PipelexError):+ ``is_runnable``), not a validation failure — so this error no longer carries a signature channel.All errors are categorized and stored in their respective lists.++ Its code is ``method.invalid``, each item keeping its own; a request that names nothing to validate, such+ as an empty set of bundle contents, is ``request.invalid``, chosen at its raise site."""- error_domain = ErrorDomain.INPUT+ error_code = ErrorCodeSet(default=CoreCode.METHOD_INVALID, others=(CoreCode.REQUEST_INVALID,))user_action = UserAction(kind=UserActionKind.CHANGE_INPUT,# The next step points at the items' own: each item says what is wrong and where, and carries a@@ -359,6 +378,22 @@ class ValidateBundleError(PipelexError):return report.model_copy(update={"validation_errors": self.validation_error_items() or None})+class HostLibraryLoadRefusalError(PipelexError):+ """A method of this host's own library directories refused to load: the deployment's fault, never the caller's input.++ A server loads its library directories beside a request's bundles (`library_dirs_are_callers` False), and they are+ the deployment's, so a pipe there that its factory refuses, that names a model the deck does not define, or that+ refuses in any other way the caller's own content would be refused, is the deployment's configuration failing to+ validate: `pipelex.config.invalid`, the code the registry gives the libraries among the runtime's own+ configuration, and the one `HostLibraryTreeError` and `HostLibraryRequirementsError` carry for the same+ directories. Its message names the method's refusal for the operator and is not caller-facing, so STRICT+ disclosure answers with the placeholder and none of the host library's text. It is deliberately no+ `LibraryError`, which a validation would report as the caller's invalid bundle.+ """++ error_code = PipelexErrorCode.CONFIG_INVALID++class PipeIOContractError(PipelexError):"""Raised when projecting a validated pipe into its `pipe_io_contracts` IO contract fails.@@ -369,6 +404,8 @@ class PipeIOContractError(PipelexError):Temporal would pointlessly retry)."""+ error_code = CoreCode.METHOD_CONCEPT_INVALID+class PipelineInputContentError(PipelexError):"""A pipeline input's content reference (url) is unusable.@@ -387,9 +424,17 @@ class PipelineInputContentError(PipelexError):differently from ``FileNotFoundError`` on one that does not. Thecaller-facing half of this family is ``PipelineInputUrlMissingError``,whose message carries nothing but the accepted schemes.++ It takes its cause's code, so a storage key refused as a traversal reports the storage error's own code,+ and a key refused for another reason the fallback, a malformed storage address. A raise site that knows+ better chooses: a reference to nothing stored (``input.reference_not_found``), a data URL or a local+ file that cannot be read (``input.file_unreadable``)."""- error_domain = ErrorDomain.INPUT+ error_code: ClassVar[ErrorCodeDeclaration] = InheritsCause(+ fallback=PipelexErrorCode.STORAGE_URI_INVALID,+ others=(CoreCode.INPUT_REFERENCE_NOT_FOUND, CoreCode.INPUT_FILE_UNREADABLE),+ )user_action = UserAction(kind=UserActionKind.CHANGE_INPUT,detail=(@@ -407,6 +452,7 @@ class PipelineInputUrlInvalidError(PipelineInputContentError):that consumes the input fetches it and reports a real failure."""+ error_code = CoreCode.INPUT_INVALID_authors_caller_facing_message = Trueuser_action = UserAction(kind=UserActionKind.CHANGE_INPUT,@@ -424,6 +470,7 @@ class PipelineInputFormatError(PipelineInputContentError):model, the formats that model reads), never a url, a storage key or a server-side reason."""+ error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERROR_authors_caller_facing_message = Trueuser_action = UserAction(kind=UserActionKind.CHANGE_INPUT,@@ -439,6 +486,8 @@ class PipelineInputNotAnImageError(PipelineInputFormatError):identify, an SVG for one, is left to its consumer."""+ error_code = CoreCode.INPUT_FILE_TYPE_UNSUPPORTED+user_action = UserAction(kind=UserActionKind.CHANGE_INPUT,detail="Give an image file, such as PNG, JPEG or WebP, to every Image input.",@@ -455,6 +504,8 @@ class PipelineInputFormatUnsupportedError(PipelineInputFormatError):and the formats that model reads."""+ error_code = CoreCode.INPUT_FILE_TYPE_UNSUPPORTED+user_action = UserAction(kind=UserActionKind.CHANGE_INPUT,detail="Give each file input in a format the model of the pipe that consumes it reads.",@@ -471,6 +522,7 @@ class PipelineInputUrlMissingError(PipelineInputContentError):sets it is ``_authors_caller_facing_message``.)"""+ error_code = CoreCode.INPUT_INVALID_authors_caller_facing_message = True@@ -485,10 +537,26 @@ class MethodEntryError(PipelexError):defining it, when no single bundle of the method defines that pipe. A command judging the whole method, such as`validate`, needs no pipe to start at and is not refused. The method is the caller's own, so the message is theirsto read.++ Its code defaults to ``request.pipe_unspecified``, a run naming no pipe of a method that declares no+ ``main_pipe``; the raise site chooses ``request.pipe_ambiguous`` when several pipes qualify,+ ``request.pipe_not_found`` when no bundle of the method defines the pipe the caller named,+ ``method.pipe_unresolved`` when the manifest names a pipe no bundle defines, ``method.package_invalid``+ when the manifest cannot be read, ``method.syntax`` when a bundle is not text, and ``method.invalid`` when+ the method holds no bundle at all."""- error_domain = ErrorDomain.INPUT- retryable = False+ error_code = ErrorCodeSet(+ default=CoreCode.REQUEST_PIPE_UNSPECIFIED,+ others=(+ CoreCode.REQUEST_PIPE_AMBIGUOUS,+ CoreCode.REQUEST_PIPE_NOT_FOUND,+ CoreCode.METHOD_PIPE_UNRESOLVED,+ CoreCode.METHOD_PACKAGE_INVALID,+ CoreCode.METHOD_SYNTAX,+ CoreCode.METHOD_INVALID,+ ),+ )user_action = UserAction(kind=UserActionKind.CHANGE_INPUT,detail="Name the pipe, or declare the method's one main_pipe: in its METHODS.toml, or in one of its bundles",diff --git a/pipelex/pipeline/execution_seams.py b/pipelex/pipeline/execution_seams.pyindex 362a4b358..440c89dc6 100644--- a/pipelex/pipeline/execution_seams.py+++ b/pipelex/pipeline/execution_seams.py@@ -42,7 +42,6 @@ from pipelex.interpreter_hub import ()from pipelex.kernel.memory_ops import shape_inputsfrom pipelex.libraries.bundle_resources import check_submitted_files-from pipelex.libraries.method_trees import reporting_host_library_tree_faultsfrom pipelex.mthds_parsing.parser import MthdsParserfrom pipelex.pipe_machinery.pipe_abstract import PipeAbstractfrom pipelex.pipe_run.pipe_job import PipeJob@@ -52,7 +51,11 @@ from pipelex.pipe_run.pipe_run_params_factory import PipeRunParamsFactoryfrom pipelex.pipeline.blueprint_selection import select_primary_blueprintfrom pipelex.pipeline.file_input_consumers import check_file_inputs_against_consumersfrom pipelex.pipeline.input_normalizer import collect_file_inputs, prepare_file_inputs-from pipelex.pipeline.validate_bundle_translation import translate_to_validate_bundle_error, withholding_host_library_files+from pipelex.pipeline.validate_bundle_translation import (+ reporting_host_library_faults,+ translate_to_validate_bundle_error,+ withholding_host_library_files,+)from pipelex.system.configuration.configs import PipelineExecutionConfigfrom pipelex.system.job_metadata import JobMetadata, OtelContext, RunMetadatafrom pipelex.system.pipe_run_mode import PipeRunMode@@ -153,9 +156,10 @@ def acquire_library(if effective_dirs:effective_dirs_desc = ", ".join(str(dir_path) for dir_path in effective_dirs)log.verbose(f"Loading libraries from {len(effective_dirs)} directory(ies) ({source_label}): {effective_dirs_desc}")- # The caller's directories refuse as their invalid bundle; a host's report a tree it cannot list as its own fault.+ # The caller's directories refuse as their invalid bundle; a host's report a tree it cannot list, or a method+ # that refuses to load, as its own fault.library_dirs_translation: AbstractContextManager[None] = (- translate_to_validate_bundle_error() if library_dirs_are_callers else reporting_host_library_tree_faults()+ translate_to_validate_bundle_error() if library_dirs_are_callers else reporting_host_library_faults())with library_dirs_translation:library_manager.load_libraries(library_id=library_id, library_dirs=effective_dirs, methods_dirs=methods_dirs)diff --git a/pipelex/pipeline/input_normalizer.py b/pipelex/pipeline/input_normalizer.pyindex f07da3717..e1aa4a4d4 100644--- a/pipelex/pipeline/input_normalizer.py+++ b/pipelex/pipeline/input_normalizer.py@@ -29,6 +29,7 @@ from typing import Any, Final, NamedTuple, TypeAlias, TypeVar, castimport aiofilesimport shortuuid+from mthds.protocol.problem.registry import CoreCodefrom pydantic import BaseModel, ConfigDictfrom pipelex.config import get_config@@ -410,7 +411,7 @@ async def _prepare_storage_reference(head = await context.storage.load_head(uri=resolved_uri.storage_uri, nb_bytes=FILE_HEAD_NB_BYTES)except StorageFileNotFoundError as exc:msg = f"{type(content).__name__} input '{input_name}': the storage reference '{content.url}' names no stored file"- raise PipelineInputContentError(msg) from exc+ raise PipelineInputContentError(msg).with_error_code(CoreCode.INPUT_REFERENCE_NOT_FOUND) from excexcept StorageInvalidUriError as exc:msg = f"{type(content).__name__} input '{input_name}': the storage reference '{content.url}' cannot be read ({exc})"raise PipelineInputContentError(msg) from exc@@ -454,7 +455,7 @@ async def _prepare_data_url(raw_bytes = base64.b64decode(resolved_uri.base64_data)except binascii.Error as exc:msg = f"{type(content).__name__} input '{input_name}': the data URL does not hold valid base64 ({exc})"- raise PipelineInputContentError(msg) from exc+ raise PipelineInputContentError(msg).with_error_code(CoreCode.INPUT_FILE_UNREADABLE) from excmime_type = _identify_file_input(content=content,head=raw_bytes[:FILE_HEAD_NB_BYTES],@@ -519,7 +520,7 @@ async def _prepare_local_path(raw_bytes = await load_binary_async(local_path)except (OSError, ValueError) as exc:msg = f"Input file cannot be read: '{resolved_uri.path}' ({type(exc).__name__})"- raise PipelineInputContentError(msg) from exc+ raise PipelineInputContentError(msg).with_error_code(CoreCode.INPUT_FILE_UNREADABLE) from excmime_type = _identify_file_input(content=content,head=raw_bytes[:FILE_HEAD_NB_BYTES],diff --git a/pipelex/pipeline/inputs_template.py b/pipelex/pipeline/inputs_template.pyindex aef37e0c1..5d91ea452 100644--- a/pipelex/pipeline/inputs_template.py+++ b/pipelex/pipeline/inputs_template.py@@ -11,6 +11,7 @@ from pipelex.interpreter_hub import get_library_manager, get_required_entry_pipefrom pipelex.pipe_machinery.pipe_factory import PipeFactoryfrom pipelex.pipe_machinery.rendering.input_renderer import build_concept_comments, no_inputs_message, render_inputsfrom pipelex.pipeline.blueprint_selection import select_primary_blueprint+from pipelex.pipeline.exceptions import MethodEntryErrorfrom pipelex.pipeline.validate_bundle import validate_bundleif TYPE_CHECKING:@@ -44,7 +45,7 @@ async def build_inputs_for_pipe(Raises:ValidateBundleError: If bundle validation fails.- ValueError: If no pipe code can be determined.+ MethodEntryError: If no pipe code can be determined (``request.pipe_unspecified``)."""if mthds_contents:# validate_bundle opens a library, loads blueprints, and sets it as current.@@ -57,7 +58,7 @@ async def build_inputs_for_pipe(main_pipe_ref = select_primary_blueprint(blueprints).main_pipe_refif not main_pipe_ref:msg = "Bundle does not declare a main_pipe. Specify a pipe code."- raise ValueError(msg)+ raise MethodEntryError(msg)pipe_code = main_pipe_refelif bundle_path:# allow_signatures=True: see the mthds_contents branch — rendering inputs tolerates placeholders.@@ -67,7 +68,7 @@ async def build_inputs_for_pipe(main_pipe_code = bundle_blueprint.main_pipeif not main_pipe_code:msg = f"Bundle '{bundle_path}' does not declare a main_pipe. Specify a pipe code."- raise ValueError(msg)+ raise MethodEntryError(msg)pipe_code = PipeFactory.make_pipe_ref_with_domain(domain_code=bundle_blueprint.domain, pipe_code=main_pipe_code)else:# No bundle - initialize the library manually@@ -80,7 +81,7 @@ async def build_inputs_for_pipe(if not pipe_code:msg = "No pipe code specified"- raise ValueError(msg)+ raise MethodEntryError(msg)the_pipe = get_required_entry_pipe(pipe_code=pipe_code)# The envelope names the pipe that was resolved, always domain-qualified, never the selectordiff --git a/pipelex/pipeline/method_entry.py b/pipelex/pipeline/method_entry.pyindex 5dd200cd9..5454ce564 100644--- a/pipelex/pipeline/method_entry.py+++ b/pipelex/pipeline/method_entry.py@@ -24,6 +24,7 @@ from mthds.method_tree.models import MethodTreefrom mthds.package.discovery import read_package_manifest_atfrom mthds.package.exceptions import ManifestErrorfrom mthds.package.manifest.schema import MethodsManifest+from mthds.protocol.problem.registry import CoreCodefrom pipelex.base_exceptions import PipelexUnexpectedErrorfrom pipelex.core.qualified_ref import QualifiedRef, QualifiedRefError@@ -127,12 +128,14 @@ def read_method_candidates(*, tree: MethodTree) -> list[EntryCandidate]:"""The bundles of a method tree listed from this host's disk, in tree path order, by what each declares.Raises:- MethodEntryError: The tree has no directory on this host to read its bundles from.+ PipelexUnexpectedError: The tree has no directory on this host to read its bundles from, which is a host's+ wiring bug.MthdsParserError: A bundle's declarations cannot be read (see `read_entry_candidate`)."""if tree.directory is None:+ # A host handing an in-memory tree to the reader of trees on disk: a wiring bug of ours, never the caller's method.msg = "A method tree read from a map of file entries has no folder on this host to read its bundles from."- raise MethodEntryError(msg)+ raise PipelexUnexpectedError(msg)return [read_entry_candidate(tree_path=tree_path, bundle_file=tree.file_location(tree_path))for tree_path in tree.tree_paths@@ -144,22 +147,24 @@ def read_method_manifest(*, tree: MethodTree) -> MethodsManifest | None:"""The `METHODS.toml` at the root of a method tree listed from this host's disk, or None when it holds none there.Raises:- MethodEntryError: The tree has no directory on this host, or its manifest cannot be read.+ MethodEntryError: Its manifest cannot be read.+ PipelexUnexpectedError: The tree has no directory on this host, which is a host's wiring bug."""if MANIFEST_NAME not in tree.members:return Noneif tree.directory is None:+ # A host handing an in-memory tree to the reader of trees on disk: a wiring bug of ours, never the caller's method.msg = "A method tree read from a map of file entries has no folder on this host to read its manifest from."- raise MethodEntryError(msg)+ raise PipelexUnexpectedError(msg)method_label = tree_method_label(tree=tree)try:manifest = read_package_manifest_at(tree.directory)except ManifestError as exc:msg = f"The {MANIFEST_NAME} of the method {method_label} cannot be read: {exc}"- raise MethodEntryError(msg) from exc+ raise MethodEntryError(msg).with_error_code(CoreCode.METHOD_PACKAGE_INVALID) from excif manifest is None:msg = f"The method {method_label} lists a {MANIFEST_NAME} at its root that could not be read back."- raise MethodEntryError(msg)+ raise MethodEntryError(msg).with_error_code(CoreCode.METHOD_PACKAGE_INVALID)return manifest@@ -178,7 +183,7 @@ def select_entry(*, candidates: list[EntryCandidate], manifest: MethodsManifestbundle_paths = [candidate.tree_path for candidate in candidates]if not candidates:msg = f"The method {method_label} holds no .mthds bundle, so it has no pipe to start at."- raise MethodEntryError(msg)+ raise MethodEntryError(msg).with_error_code(CoreCode.METHOD_INVALID)if manifest is not None:return _manifest_entry(candidates=candidates, manifest=manifest, method_label=method_label, bundle_paths=bundle_paths)@@ -196,7 +201,7 @@ def select_entry(*, candidates: list[EntryCandidate], manifest: MethodsManifestf"A method starts at one pipe: keep one main_pipe, declare the method's main_pipe in a {MANIFEST_NAME} at its root, ""or name the pipe to run.")- raise MethodEntryError(msg)+ raise MethodEntryError(msg).with_error_code(CoreCode.REQUEST_PIPE_AMBIGUOUS)entry_candidate = declaring[0]main_pipe = entry_candidate.main_pipeif main_pipe is None:@@ -227,14 +232,14 @@ def _manifest_entry(*, candidates: list[EntryCandidate], manifest: MethodsManifef"The {MANIFEST_NAME} of the method {method_label} declares the main_pipe '{main_pipe}', exported by "f"{_listed(names=sorted(exporting_domains))}, which none of its bundles defines in that domain: {_listed(names=bundle_paths)}.")- raise MethodEntryError(msg)+ raise MethodEntryError(msg).with_error_code(CoreCode.METHOD_PIPE_UNRESOLVED)if len(defining) > 1:definitions = ", ".join(f"'{candidate.tree_path}' in domain '{candidate.domain}'" for candidate in defining)msg = (f"The {MANIFEST_NAME} of the method {method_label} declares the main_pipe '{main_pipe}', which several of its "f"bundles define: {definitions}. Name the pipe to run as domain.pipe_code.")- raise MethodEntryError(msg)+ raise MethodEntryError(msg).with_error_code(CoreCode.REQUEST_PIPE_AMBIGUOUS)return _entry_of(candidate=defining[0], pipe_code=main_pipe)@@ -245,8 +250,8 @@ def select_method_entry(*, tree: MethodTree) -> MethodEntry:is read.Raises:- MethodEntryError: The tree has no directory on this host, its manifest cannot be read, or `select_entry`- refuses it.+ MethodEntryError: Its manifest cannot be read, or `select_entry` refuses it.+ PipelexUnexpectedError: The tree has no directory on this host, which is a host's wiring bug.MthdsParserError: A bundle's declarations cannot be read (see `read_entry_candidate`)."""candidates = read_method_candidates(tree=tree)@@ -267,12 +272,12 @@ def select_named_pipe(*, candidates: list[EntryCandidate], pipe_ref: str, methodf"The pipe '{pipe_ref}' belongs to a package the method {method_label} depends on, and no bundle of the method ""defines it. Name a pipe of the method, or the bundle file that runs it.")- raise MethodEntryError(msg)+ raise MethodEntryError(msg).with_error_code(CoreCode.REQUEST_PIPE_NOT_FOUND)try:qualified_ref = QualifiedRef.parse(pipe_ref)except QualifiedRefError as exc:msg = f"'{pipe_ref}' does not name a pipe of the method {method_label}: {exc}"- raise MethodEntryError(msg) from exc+ raise MethodEntryError(msg).with_error_code(CoreCode.REQUEST_PIPE_NOT_FOUND) from excdefining = [candidatefor candidate in candidates@@ -280,9 +285,9 @@ def select_named_pipe(*, candidates: list[EntryCandidate], pipe_ref: str, method]if not defining:msg = f"No bundle of the method {method_label} defines the pipe '{pipe_ref}'. Its bundles: {_listed(names=bundle_paths)}."- raise MethodEntryError(msg)+ raise MethodEntryError(msg).with_error_code(CoreCode.REQUEST_PIPE_NOT_FOUND)if len(defining) > 1:definitions = ", ".join(f"'{candidate.tree_path}' in domain '{candidate.domain}'" for candidate in defining)msg = f"Several bundles of the method {method_label} define the pipe '{pipe_ref}': {definitions}. Name the pipe as domain.pipe_code."- raise MethodEntryError(msg)+ raise MethodEntryError(msg).with_error_code(CoreCode.REQUEST_PIPE_AMBIGUOUS)return _entry_of(candidate=defining[0], pipe_code=qualified_ref.local_code)diff --git a/pipelex/pipeline/pipeline_run_setup.py b/pipelex/pipeline/pipeline_run_setup.pyindex e90c57824..58704568b 100644--- a/pipelex/pipeline/pipeline_run_setup.py+++ b/pipelex/pipeline/pipeline_run_setup.py@@ -3,6 +3,7 @@ from pathlib import Pathfrom typing import TYPE_CHECKINGfrom mthds.protocol.pipeline_inputs import PipelineInputs+from mthds.protocol.problem.registry import CoreCodefrom pipelex import logfrom pipelex.config import get_config@@ -34,6 +35,7 @@ from pipelex.runtime_hub import ()from pipelex.system.configuration.configs import PipelineExecutionConfigfrom pipelex.system.environment import get_optional_env+from pipelex.system.exceptions import RunParameterErrorfrom pipelex.system.job_metadata import OtelContextfrom pipelex.system.pipe_run_mode import PipeRunModefrom pipelex.system.run_extras import validate_run_extras@@ -222,7 +224,7 @@ async def pipeline_run_setup(# production. The constant survives for telemetry only.if not mthds_contents and not pipe_code:msg = "Either pipe_code or mthds_contents must be provided to the pipeline API."- raise ValueError(msg)+ raise PipeExecutionError(message=msg).with_error_code(CoreCode.REQUEST_PIPE_UNSPECIFIED).as_caller_fault()# Validate the extras HERE, before this function causes anything observable.#@@ -264,7 +266,7 @@ async def pipeline_run_setup("A run with a read_scope must pass its own storage_scope: the local storage scope becomes the run id, ""which lies under no read_scope, and the run could not read what it writes.")- raise ValueError(msg)+ raise RunParameterError(msg)validate_storage_scope_within_read_scope(storage_scope=storage_scope, read_scope=read_scope)# TODO: rethink this, it's not forcing@@ -353,7 +355,7 @@ async def pipeline_run_setup(pipe = get_required_pipe(pipe_code=qualified_main_pipe)else:msg = "No pipe_code provided and no main_pipe found in any of the MTHDS contents."- raise PipeExecutionError(message=msg)+ raise PipeExecutionError(message=msg).with_error_code(CoreCode.REQUEST_PIPE_UNSPECIFIED).as_caller_fault()elif pipe_code:pipe = get_required_entry_pipe(pipe_code=pipe_code)else:diff --git a/pipelex/pipeline/request_exceptions.py b/pipelex/pipeline/request_exceptions.pynew file mode 100644index 000000000..f4beebfba--- /dev/null+++ b/pipelex/pipeline/request_exceptions.py@@ -0,0 +1,54 @@+"""The refusal of a request's argument, raised by the runtime as both the protocol's class and a coded Pipelex error."""++from __future__ import annotations++from mthds.protocol.exceptions import PipelineRequestError+from mthds.protocol.problem.client_problems import make_client_problem+from mthds.protocol.problem.registry import CoreCode++from pipelex.base_exceptions import PipelexError+from pipelex.errors.error_code_declaration import ErrorCodeSet++# The status a runner answers a refused request field with, the same for both codes of the class.+_REFUSED_REQUEST_STATUS = 422+++class PipelexRequestError(PipelineRequestError, PipelexError):+ """A request argument the runtime refuses before running anything: ``request.invalid`` or ``request.unsupported``.++ It is both the standard's :class:`~mthds.protocol.exceptions.PipelineRequestError`, which a client of the+ protocol catches whatever runner refused its request, and a :class:`~pipelex.base_exceptions.PipelexError`+ carrying the matching code, so the runtime's own boundaries report it like any other error (the census's+ question 13). Its ``problem`` is the standard's problem document for the same code, built from the registry.++ The code follows from the arguments: a field this runtime does not accept in the form it was sent, named+ with ``unsupported_reason``, is ``request.unsupported``; any other refused field is ``request.invalid``.+ """++ error_code = ErrorCodeSet(default=CoreCode.REQUEST_INVALID, others=(CoreCode.REQUEST_UNSUPPORTED,))+ # The message describes a field of the caller's own request and nothing of the server's.+ _authors_caller_facing_message = True++ def __init__(self, message: str, *, field: str, unsupported_reason: str | None = None) -> None:+ """Build the refusal of one request field.++ Args:+ message: What is wrong with the field, for a person; it names only what the caller sent.+ field: The refused field, by name, as the request spells it.+ unsupported_reason: Why this runtime does not accept the field's form, as an identifier such as+ ``extension_args_on_local_execute``; ``None`` for a field whose value is simply invalid.+ """+ code: CoreCode+ params: dict[str, str]+ if unsupported_reason is None:+ code = CoreCode.REQUEST_INVALID+ params = {"field": field}+ else:+ code = CoreCode.REQUEST_UNSUPPORTED+ params = {"field": field, "reason": unsupported_reason}+ super().__init__(message, problem=make_client_problem(code, params=params, status=_REFUSED_REQUEST_STATUS))+ # The protocol's class appends the problem's next step to the exception's text; the report's message+ # is the refusal alone, since the report states its next step on its own.+ self.message = message+ self.field = field+ self.with_error_code(code)diff --git a/pipelex/pipeline/resolve_bundle.py b/pipelex/pipeline/resolve_bundle.pyindex 64dacf22f..ba35e21ec 100644--- a/pipelex/pipeline/resolve_bundle.py+++ b/pipelex/pipeline/resolve_bundle.py@@ -28,6 +28,7 @@ from pathlib import Pathfrom typing import Sequencefrom mthds.package.manifest.schema import MTHDS_STANDARD_VERSION+from mthds.protocol.problem.registry import CoreCodefrom pipelex.base_exceptions import PipelexUnexpectedErrorfrom pipelex.core.method_trees.file_references import BundleFileOrigin@@ -191,4 +192,4 @@ def _reject_address_based_dependencies(*, blueprints: list[PipelexBundleBlueprinalias, _remainder = QualifiedRef.split_cross_package_ref(pipe_ref)if QualifiedRef.is_address_based_alias(alias):msg = unshipped_address_dependency_message(alias=alias)- raise PipeLibraryError(msg)+ raise PipeLibraryError(msg).with_error_code(CoreCode.REQUEST_UNSUPPORTED)diff --git a/pipelex/pipeline/runner.py b/pipelex/pipeline/runner.pyindex 2926a8513..80bcd6b4c 100644--- a/pipelex/pipeline/runner.py+++ b/pipelex/pipeline/runner.py@@ -5,11 +5,11 @@ from importlib import metadatafrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, cast-from mthds.protocol.exceptions import PipelineRequestErrorfrom mthds.protocol.models import ModelCategory as MthdsModelCategoryfrom mthds.protocol.models import ModelDeck as MthdsModelDeckfrom mthds.protocol.models import ModelInfo as MthdsModelInfofrom mthds.protocol.models import VersionInfo+from mthds.protocol.problem.registry import CoreCodefrom mthds.protocol.protocol import PROTOCOL_VERSION, MTHDSProtocolfrom pydantic import Field, ValidationErrorfrom typing_extensions import override@@ -26,9 +26,11 @@ from pipelex.interpreter_hub import (get_pipeline_manager,set_current_library,)+from pipelex.pipe_run.exceptions import AsyncExecutionNotEnabledErrorfrom pipelex.pipeline.exceptions import PipeExecutionError, PipelineExecutionErrorfrom pipelex.pipeline.pipeline_response import PipelexRunResultExecute, PipelexRunResultStart, RunStatefrom pipelex.pipeline.pipeline_run_setup import pipeline_run_setup+from pipelex.pipeline.request_exceptions import PipelexRequestErrorfrom pipelex.pipeline.validate_in_process import validate_bundles_in_processfrom pipelex.runtime_hub import get_report_delegate, get_telemetry_managerfrom pipelex.system.caller_identity import CallerIdentity@@ -149,14 +151,14 @@ def _extract_validate_graph_pipe_code(extra: dict[str, Any] | None) -> str | Nonunknown_keys = sorted(key for key in extra if key != _VALIDATE_EXTRA_GRAPH_PIPE_CODE)if unknown_keys:msg = f"The local runtime defines no extension args for: {unknown_keys}."- raise PipelineRequestError(msg)+ raise PipelexRequestError(msg, field="extra", unsupported_reason="unknown_validate_extension_args")graph_pipe_code = extra.get(_VALIDATE_EXTRA_GRAPH_PIPE_CODE)if graph_pipe_code is not None and not isinstance(graph_pipe_code, str):msg = f"validate extra '{_VALIDATE_EXTRA_GRAPH_PIPE_CODE}' must be a string when provided."- raise PipelineRequestError(msg)+ raise PipelexRequestError(msg, field=f"extra.{_VALIDATE_EXTRA_GRAPH_PIPE_CODE}")if graph_pipe_code is not None and not graph_pipe_code.strip():msg = f"validate extra '{_VALIDATE_EXTRA_GRAPH_PIPE_CODE}' must not be blank when provided."- raise PipelineRequestError(msg)+ raise PipelexRequestError(msg, field=f"extra.{_VALIDATE_EXTRA_GRAPH_PIPE_CODE}")return graph_pipe_code@@ -318,7 +320,7 @@ class PipelexMTHDSProtocol(MTHDSProtocol["PipeOutput"]):"""if extra:msg = f"The local runtime defines no extension args; got {sorted(extra)}."- raise PipelineRequestError(msg)+ raise PipelexRequestError(msg, field="extra", unsupported_reason="extension_args_on_local_execute")# Refused here, before the `try`: `RunMetadata` would refuse it inside the setup, where the# `ValidationError` arm below would report the host's bug as the caller's invalid input.if request_id is not None:@@ -397,7 +399,7 @@ class PipelexMTHDSProtocol(MTHDSProtocol["PipeOutput"]):formatted_error = format_pydantic_validation_error(exc)model_name = exc.titlemsg = f"Input validation failed for '{model_name}': {formatted_error}"- raise PipeExecutionError(message=msg) from exc+ raise PipeExecutionError(message=msg).with_error_code(CoreCode.INPUT_INVALID) from excfinally:# Close the tracer if it was opened (cleanup only — the PipeRun is responsible for capturing# the graph spec on pipe_output). The tracer is opened whenever graph OR cost reporting is on@@ -473,7 +475,8 @@ class PipelexMTHDSProtocol(MTHDSProtocol["PipeOutput"]):Asynchronous execution is owned by the API layer (pipelex-api overridesthis with Temporal dispatch) and the hosted platform; locally, use- `execute`.+ `execute`. It raises `AsyncExecutionNotEnabledError`, whose code is+ `runtime.unsupported`."""_ = (pipe_code,@@ -485,7 +488,7 @@ class PipelexMTHDSProtocol(MTHDSProtocol["PipeOutput"]):extra,)msg = "start is not implemented by the local runtime. Use execute, or run against an MTHDS API runner."- raise NotImplementedError(msg)+ raise AsyncExecutionNotEnabledError(msg)@overrideasync def validate(diff --git a/pipelex/pipeline/validate_bundle.py b/pipelex/pipeline/validate_bundle.pyindex 4b76dea80..3cc135c92 100644--- a/pipelex/pipeline/validate_bundle.py+++ b/pipelex/pipeline/validate_bundle.py@@ -6,6 +6,7 @@ from pathlib import Pathfrom typing import Sequencefrom mthds.method_tree.models import MethodTree+from mthds.protocol.problem.registry import CoreCodefrom pydantic import BaseModel# TypedDict from typing_extensions, not typing: pydantic rejects typing.TypedDict as a model@@ -26,14 +27,18 @@ from pipelex.interpreter_hub import ()from pipelex.libraries.bundle_resources import check_submitted_filesfrom pipelex.libraries.library_utils import get_pipelex_mthds_files_from_dirs-from pipelex.libraries.method_trees import list_local_method_tree, reporting_host_library_tree_faults+from pipelex.libraries.method_trees import list_local_method_treefrom pipelex.libraries.pipe.exceptions import EntryPipeNotFoundErrorfrom pipelex.mthds_parsing.parser import MthdsParserfrom pipelex.mthds_parsing.pipelex_bundle_blueprint import PipelexBundleBlueprintfrom pipelex.pipe_machinery.pipe_abstract import PipeAbstractfrom pipelex.pipeline.bundle_validator import BundleValidator, DryRunOutput, DryRunStatusfrom pipelex.pipeline.exceptions import ValidateBundleError-from pipelex.pipeline.validate_bundle_translation import translate_to_validate_bundle_error, withholding_host_library_files+from pipelex.pipeline.validate_bundle_translation import (+ reporting_host_library_faults,+ translate_to_validate_bundle_error,+ withholding_host_library_files,+)from pipelex.system.caller_identity import CallerIdentityPYTHON_SUFFIX = ".py"@@ -195,7 +200,7 @@ async def validate_bundle(# guard it would yield a blueprint-less result that downstream consumers (the canonical# report's primary-blueprint selection) cannot represent.msg = "mthds_contents must not be empty: provide at least one MTHDS content to validate"- raise ValidateBundleError(message=msg)+ raise ValidateBundleError(message=msg).with_error_code(CoreCode.REQUEST_INVALID)if mthds_sources is not None and (mthds_contents is None or len(mthds_sources) != len(mthds_contents)):# ``mthds_sources`` is a per-content source list (the host — e.g. an HTTP API —# threads each bundle's source onto the in-memory load path so its diagnostics carry a@@ -241,7 +246,8 @@ async def validate_bundle(# Beside submitted content, a host's library directories are withheld from the verdict: their files are paths# on the host. The caller's own directories, and every directory of a bundle file, keep their paths.host_library_withholding: AbstractContextManager[None]- # A host's library directories whose trees cannot be listed are the host's fault, never the caller's verdict.+ # A host's library directories whose trees cannot be listed, or whose methods refuse to load, are the host's+ # fault, never the caller's verdict.host_library_tree_faults: AbstractContextManager[None]if mthds_contents is not None and not library_dirs_are_callers:host_library_withholding = withholding_host_library_files(@@ -249,7 +255,7 @@ async def validate_bundle(caller_sources=[source for source in mthds_sources or [] if source is not None],caller_contents=mthds_contents,)- host_library_tree_faults = reporting_host_library_tree_faults()+ host_library_tree_faults = reporting_host_library_faults()else:host_library_withholding = nullcontext()host_library_tree_faults = nullcontext()diff --git a/pipelex/pipeline/validate_bundle_translation.py b/pipelex/pipeline/validate_bundle_translation.pyindex c90448b35..c0d57fee3 100644--- a/pipelex/pipeline/validate_bundle_translation.py+++ b/pipelex/pipeline/validate_bundle_translation.py@@ -33,7 +33,7 @@ from pipelex.core.validation import report_validation_errorfrom pipelex.interpreter_hub import get_library_managerfrom pipelex.libraries.exceptions import LibraryError, LibraryLoadingError, MethodTreeLoadErrorfrom pipelex.libraries.library_utils import get_pipelex_mthds_files_from_dirs-from pipelex.libraries.method_trees import bundle_files_under+from pipelex.libraries.method_trees import bundle_files_under, reporting_host_library_tree_faultsfrom pipelex.libraries.pipe.exceptions import PipeNotFoundErrorfrom pipelex.mthds_parsing.exceptions import MthdsParserErrorfrom pipelex.mthds_parsing.handle_pipe_errors import (@@ -42,8 +42,8 @@ from pipelex.mthds_parsing.handle_pipe_errors import (categorize_pipe_validation_error,categorize_pipe_validation_with_libraries_error,)-from pipelex.pipe_run.exceptions import DryRunError-from pipelex.pipeline.exceptions import ValidateBundleError+from pipelex.pipe_run.exceptions import DryRunError, DryRunGraphNotProducedError+from pipelex.pipeline.exceptions import HostLibraryLoadRefusalError, ValidateBundleErrorfrom pipelex.tools.misc.file_utils import find_files_in_dirfrom pipelex.tools.typing.module_inspector import convert_file_path_to_module_path@@ -150,6 +150,11 @@ def translate_to_validate_bundle_error() -> Generator[None, None, None]:# violations, factory failures). Surface them as a clean ValidateBundleError instead of a# raw traceback. LibraryLoadingError carries blueprint- and pipe/concept-validation errors;# forward them so the CLI renders the same structured detail it does for the other arms.+ # A library error that is not the caller's input, such as an invariant of the library manager+ # (`runtime.unexpected`) or library directories configured wrongly (`pipelex.config.invalid`), is a fault of+ # the runtime, never a verdict about the bundle, and propagates as it is.+ if not error_domain_is_input(library_error.to_error_report().error_domain):+ raiseif isinstance(library_error, LibraryLoadingError):blueprint_validation_errors = library_error.blueprint_validation_errorspipe_concept_validation_errors = library_error.pipe_concept_validation_errors@@ -174,6 +179,9 @@ def translate_to_validate_bundle_error() -> Generator[None, None, None]:)],) from pipe_run_error+ except DryRunGraphNotProducedError:+ # A graph-producing dry run that produced none is a fault of its entrypoint, not of the bundle.+ raiseexcept DryRunError as dry_run_error:# The sweep's failures, one per failing pipe, located at the innermost pipe that failed. A# DryRunError raised elsewhere carries none, and becomes one item under the disclosure rule.@@ -204,6 +212,37 @@ def translate_to_validate_bundle_error() -> Generator[None, None, None]:raise verdict from refusal+@contextmanager+def reporting_host_library_faults() -> Generator[None, None, None]:+ """Report a fault of loading this host's own library directories as the deployment's, never as the caller's input.++ Around a load of library directories that are not the caller's (`library_dirs_are_callers` False), such as the+ ones a server loads beside a request's bundles. A tree that cannot be listed, or whose requirements refuse it,+ leaves as `reporting_host_library_tree_faults` reports it. Any other refusal that would be the caller's input in+ the caller's own content (an `input`-domained `PipelexError`, such as a pipe factory's refusal or an unknown+ model, or a pydantic `ValidationError` of a blueprint) leaves as a `HostLibraryLoadRefusalError`, which the+ validation translation lets through as no verdict. A security refusal keeps its own class, as everywhere.++ Raises:+ HostLibraryLoadRefusalError: A method of the directories refused to load.+ HostLibraryTreeError: A tree of the directories could not be listed.+ HostLibraryRequirementsError: A method of the directories declares requirements its environment refuses.+ """+ try:+ with reporting_host_library_tree_faults():+ yield+ except SecurityError:+ raise+ except ValidationError as validation_error:+ msg = f"A method in a library directory of this host does not validate: {report_validation_error(validation_error=validation_error).message}"+ raise HostLibraryLoadRefusalError(msg) from validation_error+ except PipelexError as refusal:+ if not error_domain_is_input(refusal.to_error_report().error_domain):+ raise+ msg = f"A method in a library directory of this host refuses to load ({type(refusal).__name__}): {refusal.message}"+ raise HostLibraryLoadRefusalError(msg) from refusal++def _make_refusal_verdict(*, refusal: PipelexError) -> ValidateBundleError | None:"""The one-item verdict for a refusal of the caller's input that has no arm of its own, else ``None``.diff --git a/pipelex/pipeline/validation_report.py b/pipelex/pipeline/validation_report.pyindex 88b63a41e..72cce4792 100644--- a/pipelex/pipeline/validation_report.py+++ b/pipelex/pipeline/validation_report.py@@ -12,7 +12,7 @@ nowhere. Primary-blueprint selection (`bundle_blueprint`) goes through"""from collections.abc import Sequence-from typing import Literal+from typing import Any, Literalfrom mthds.protocol.models import ValidationReportfrom pydantic import Field@@ -29,7 +29,7 @@ from pipelex.pipeline.validate_bundle import ValidatedPipeEntry, build_validatedfrom pipelex.tools.typing.pydantic_utils import empty_list_factory_of-class PipelexValidationReport(ValidationReport):+class PipelexValidationReport(ValidationReport[Any]):"""Pipelex's validation artifacts — this implementation's extensions on theprotocol's `ValidationReport` (which declares no body fields).diff --git a/pipelex/plugins/bundle_validator_registry.py b/pipelex/plugins/bundle_validator_registry.pyindex fbbf783ed..23733427f 100644--- a/pipelex/plugins/bundle_validator_registry.py+++ b/pipelex/plugins/bundle_validator_registry.py@@ -24,7 +24,7 @@ canonical ``PipelexValidationReport`` (a ``ValidationReport`` subtype); the APIthat precise type at its edge."""-from typing import TYPE_CHECKING, Protocol, TypeAlias, runtime_checkable+from typing import TYPE_CHECKING, Any, Protocol, TypeAlias, runtime_checkablefrom mthds.protocol.models import ValidationReport@@ -41,7 +41,7 @@ if TYPE_CHECKING:# ErrorReport. Bound at runtime (not just under TYPE_CHECKING) so an external validator# plugin can import it to annotate its own validate_bundles. Both arms are leaf types w.r.t.# the hub, so this hub-reachable seam stays import-acyclic even with the runtime imports.-BundleValidationVerdict: TypeAlias = ValidationReport | ErrorReport+BundleValidationVerdict: TypeAlias = ValidationReport[Any] | ErrorReport@runtime_checkablediff --git a/pipelex/plugins/exceptions.py b/pipelex/plugins/exceptions.pyindex a4fec94bc..956a50d85 100644--- a/pipelex/plugins/exceptions.py+++ b/pipelex/plugins/exceptions.py@@ -1,16 +1,23 @@-from pipelex.base_exceptions import ErrorDomain, PipelexError+from typing import ClassVar++from mthds.protocol.problem.registry import CoreCode++from pipelex.base_exceptions import PipelexError+from pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeDeclaration+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodeclass PluginError(PipelexError):- """Base for plugin-discovery and plugin-registration failures."""+ """Base for plugin-discovery and plugin-registration failures, never raised directly."""- error_domain = ErrorDomain.CONFIG- _declared_title = "Plugin error"+ error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERRORclass PluginApiVersionMismatchError(PluginError):"""A discovered plugin targets a plugin-API version this Pipelex does not support."""+ error_code = PipelexErrorCode.PLUGIN_API_MISMATCH+def __init__(self, *, plugin_name: str, targets_api: object, supported_api: int):self.plugin_name = plugin_nameself.targets_api = targets_api@@ -32,6 +39,8 @@ class InferenceBackendNotFoundError(PluginError):release renamed, which the plugin that serves it no longer registers."""+ error_code = CoreCode.MODEL_UNAVAILABLE+def __init__(self, *, family: str, sdk: str):self.family = familyself.sdk = sdk@@ -46,6 +55,8 @@ class InferenceBackendNotFoundError(PluginError):class DuplicateInferenceBackendError(PluginError):"""Two plugins registered an inference backend for the same (family, sdk)."""+ error_code = PipelexErrorCode.PLUGIN_CONFLICT+def __init__(self, *, family: str, sdk: str, first_plugin: str, second_plugin: str):self.family = familyself.sdk = sdk@@ -61,6 +72,8 @@ class DuplicateInferenceBackendError(PluginError):class DuplicateModelListerError(PluginError):"""Two plugins registered a model lister for the same sdk."""+ error_code = PipelexErrorCode.PLUGIN_CONFLICT+def __init__(self, *, sdk: str, first_plugin: str, second_plugin: str):self.sdk = sdkself.first_plugin = first_plugin@@ -75,6 +88,8 @@ class DuplicateModelListerError(PluginError):class DuplicateServiceErrorCodeError(PluginError):"""Two plugins contributed the same service error code."""+ error_code = PipelexErrorCode.PLUGIN_CONFLICT+def __init__(self, *, code: str, first_plugin: str, second_plugin: str):self.code = codeself.first_plugin = first_plugin@@ -89,6 +104,8 @@ class DuplicateServiceErrorCodeError(PluginError):class ReservedServiceErrorCodeError(PluginError):"""A plugin contributed a service error code the runtime classifies itself."""+ error_code = PipelexErrorCode.PLUGIN_BROKEN+def __init__(self, *, code: str, plugin: str):self.code = codeself.plugin = plugin@@ -102,6 +119,8 @@ class ReservedServiceErrorCodeError(PluginError):class DuplicateOrchestratorError(PluginError):"""Two plugins registered an orchestrator for the same orchestration mode."""+ error_code = PipelexErrorCode.PLUGIN_CONFLICT+def __init__(self, *, mode: str, first_plugin: str, second_plugin: str):self.mode = modeself.first_plugin = first_plugin@@ -116,6 +135,8 @@ class DuplicateOrchestratorError(PluginError):class DuplicateBundleValidatorError(PluginError):"""Two plugins registered a bundle validator for the same orchestration mode."""+ error_code = PipelexErrorCode.PLUGIN_CONFLICT+def __init__(self, *, mode: str, first_plugin: str, second_plugin: str):self.mode = modeself.first_plugin = first_plugin@@ -130,6 +151,8 @@ class DuplicateBundleValidatorError(PluginError):class DuplicateStorageProviderError(PluginError):"""Two plugins registered a storage provider for the same method."""+ error_code = PipelexErrorCode.PLUGIN_CONFLICT+def __init__(self, *, method: str, first_plugin: str, second_plugin: str):self.method = methodself.first_plugin = first_plugin@@ -144,6 +167,8 @@ class DuplicateStorageProviderError(PluginError):class DuplicateSecretsProviderError(PluginError):"""Two plugins registered a secrets provider for the same method."""+ error_code = PipelexErrorCode.PLUGIN_CONFLICT+def __init__(self, *, method: str, first_plugin: str, second_plugin: str):self.method = methodself.first_plugin = first_plugin@@ -158,6 +183,8 @@ class DuplicateSecretsProviderError(PluginError):class DuplicateLogSinkError(PluginError):"""Two plugins registered a log sink for the same method."""+ error_code = PipelexErrorCode.PLUGIN_CONFLICT+def __init__(self, *, method: str, first_plugin: str, second_plugin: str):self.method = methodself.first_plugin = first_plugin@@ -172,6 +199,8 @@ class DuplicateLogSinkError(PluginError):class DuplicateInternalModelError(PluginError):"""Two plugins declared a model of the same name and model type in the internal backend."""+ error_code = PipelexErrorCode.PLUGIN_CONFLICT+def __init__(self, *, name: str, model_type: str, first_plugin: str, second_plugin: str):self.name = nameself.model_type = model_type@@ -187,6 +216,8 @@ class DuplicateInternalModelError(PluginError):class DuplicateDocGenDefaultError(PluginError):"""Two plugins declared the model deck's default document engine for the same format and source."""+ error_code = PipelexErrorCode.PLUGIN_CONFLICT+def __init__(self, *, choice_key: str, first_plugin: str, second_plugin: str):self.choice_key = choice_keyself.first_plugin = first_plugin@@ -201,6 +232,8 @@ class DuplicateDocGenDefaultError(PluginError):class DuplicatePipeFuncExecutorError(PluginError):"""Two plugins registered a PipeFunc executor for the same execution mode."""+ error_code = PipelexErrorCode.PLUGIN_CONFLICT+def __init__(self, *, mode: str, first_plugin: str, second_plugin: str):self.mode = modeself.first_plugin = first_plugin@@ -215,6 +248,8 @@ class DuplicatePipeFuncExecutorError(PluginError):class DuplicatePipeFuncPackageOfferError(PluginError):"""Two plugins stated the package offer of the same PipeFunc execution mode."""+ error_code = PipelexErrorCode.PLUGIN_CONFLICT+def __init__(self, *, mode: str, first_plugin: str, second_plugin: str):self.mode = modeself.first_plugin = first_plugin@@ -229,6 +264,8 @@ class DuplicatePipeFuncPackageOfferError(PluginError):class DuplicateHttpErrorMapperError(PluginError):"""Two plugins registered an HTTP-error mapper for the same exception type."""+ error_code = PipelexErrorCode.PLUGIN_CONFLICT+def __init__(self, *, exc_type: str, first_plugin: str, second_plugin: str):self.exc_type = exc_typeself.first_plugin = first_plugin@@ -243,6 +280,8 @@ class DuplicateHttpErrorMapperError(PluginError):class HubSlotAlreadyClaimedError(PluginError):"""Two plugins claimed the same hub slot."""+ error_code = PipelexErrorCode.PLUGIN_CONFLICT+def __init__(self, *, slot: str, first_plugin: str, second_plugin: str):self.slot = slotself.first_plugin = first_plugin@@ -257,6 +296,8 @@ class HubSlotAlreadyClaimedError(PluginError):class CoreUnconditionalPluginDisabledError(PluginError):"""A plugin that core requires unconditionally was named in ``runtime.plugins.disabled``."""+ error_code = PipelexErrorCode.CONFIG_INVALID+def __init__(self, *, plugin_name: str):self.plugin_name = plugin_namemessage = f"Plugin '{plugin_name}' is required by core and cannot be disabled via runtime.plugins.disabled. Remove it from the denylist."@@ -273,6 +314,8 @@ class PluginLayerViolationError(PluginError):before anything it contributed is wired."""+ error_code = PipelexErrorCode.PLUGIN_BROKEN+def __init__(self, *, plugin_name: str, capability: str, declared_group: str, interpreter_group: str):self.plugin_name = plugin_nameself.capability = capability@@ -297,6 +340,8 @@ class RetiredPluginEntryPointGroupError(PluginError):should move to."""+ error_code = PipelexErrorCode.PLUGIN_BROKEN+# The message names the caller's own installed distributions and the exact fix; it is fully# actionable, so keep it verbatim under STRICT disclosure._authors_caller_facing_message = True@@ -332,6 +377,8 @@ class PluginDeclaredInMultipleGroupsError(PluginError):tolerated — it is the declaration failing to say anything."""+ error_code = PipelexErrorCode.PLUGIN_BROKEN+# The message names the caller's own installed distribution and the exact fix._authors_caller_facing_message = True@@ -352,6 +399,8 @@ class PluginDeclaredInMultipleGroupsError(PluginError):class BrokenPluginError(PluginError):"""A discovered plugin failed while loading or registering itself."""+ error_code = PipelexErrorCode.PLUGIN_BROKEN+def __init__(self, *, plugin_name: str, reason: str):self.plugin_name = plugin_nameself.reason = reason@@ -372,6 +421,8 @@ class UnknownBootOrchestratorError(PluginError):decoupled from its plugins."""+ error_code = PipelexErrorCode.PLUGIN_NOT_FOUND+# The message describes the caller's own input (the requested orchestrator name) and is fully# actionable; keep it verbatim under STRICT disclosure._authors_caller_facing_message = True@@ -396,6 +447,8 @@ class UnknownStorageMethodError(PluginError):starting with no storage. The message lists the registered methods so the fix is obvious."""+ error_code = PipelexErrorCode.PLUGIN_NOT_FOUND+# The message describes the caller's own input (the configured storage method) and lists the# registered methods; it is fully actionable, so keep it verbatim under STRICT disclosure._authors_caller_facing_message = True@@ -422,6 +475,8 @@ class UnknownPipeFuncExecutionModeError(PluginError):registered modes so the fix is obvious."""+ error_code = PipelexErrorCode.PLUGIN_NOT_FOUND+# The message describes the caller's own input (the configured execution mode) and lists the# registered modes; it is fully actionable, so keep it verbatim under STRICT disclosure._authors_caller_facing_message = True@@ -447,6 +502,8 @@ class UnknownSecretsMethodError(PluginError):starting with no secrets provider. The message lists the registered methods so the fix is obvious."""+ error_code = PipelexErrorCode.PLUGIN_NOT_FOUND+# The message describes the caller's own input (the configured secrets method) and lists the# registered methods; it is fully actionable, so keep it verbatim under STRICT disclosure._authors_caller_facing_message = True@@ -472,6 +529,8 @@ class UnknownLogSinkError(PluginError):registered sinks so the fix is obvious."""+ error_code = PipelexErrorCode.PLUGIN_NOT_FOUND+# The message describes the caller's own input (the configured sink) and lists the registered# ones; it is fully actionable, so keep it verbatim under STRICT disclosure._authors_caller_facing_message = True@@ -485,3 +544,25 @@ class UnknownLogSinkError(PluginError):"Check runtime.log.sink, or install/enable the plugin that provides that sink.")super().__init__(message)+++class PluginErrorCodeNotRegisteredError(PluginError):+ """A plugin declared, at registration, a public error code that neither registry defines.++ Every code a plugin raises is one a caller reads, with its page and its next step, so it must be a code of the+ MTHDS core or of Pipelex's registry, whose names are public even where the plugin's implementation is closed.+ ``PluginRegistrar.declare_error_codes`` binds each declared code at boot, and this refuses the boot on the first+ code that does not parse, rather than letting it reach a caller as a code no page explains. The plugin is broken+ as packaged: a release of it targets codes this Pipelex does not define, so the fix is the plugin's.+ """++ error_code = PipelexErrorCode.PLUGIN_BROKEN++ def __init__(self, *, plugin_name: str, code: str):+ self.plugin_name = plugin_name+ self.code = code+ message = (+ f"Plugin '{plugin_name}' declares the error code '{code}', which is not a registered code of the MTHDS core or of "+ "Pipelex. Upgrade Pipelex or install a release of the plugin whose codes this Pipelex defines."+ )+ super().__init__(message)diff --git a/pipelex/plugins/registrar.py b/pipelex/plugins/registrar.pyindex be22e2761..b85890291 100644--- a/pipelex/plugins/registrar.py+++ b/pipelex/plugins/registrar.py@@ -9,6 +9,7 @@ from pipelex.base_exceptions import ErrorReportfrom pipelex.cogt.doc_gen.doc_gen_format import DocGenFormat, DocGenSource, doc_gen_choice_keyfrom pipelex.cogt.inference.error_classification import RUNTIME_CLASSIFIED_ERROR_CODESfrom pipelex.cogt.model_backends.model_type import DEFAULT_MODEL_TYPE+from pipelex.errors.error_codes import ErrorCode, parse_error_codefrom pipelex.plugins.bundle_validator_registry import BundleValidatorProtocolfrom pipelex.plugins.exceptions import (DuplicateBundleValidatorError,@@ -25,6 +26,7 @@ from pipelex.plugins.exceptions import (DuplicateServiceErrorCodeError,DuplicateStorageProviderError,HubSlotAlreadyClaimedError,+ PluginErrorCodeNotRegisteredError,PluginLayerViolationError,ReservedServiceErrorCodeError,)@@ -184,6 +186,8 @@ class PluginRegistrar:self.internal_models: dict[tuple[str, str], dict[str, Any]] = {}self.doc_gen_defaults: dict[tuple[DocGenFormat, DocGenSource], str] = {}self.service_error_codes: dict[str, ServiceErrorCode] = {}+ # The public codes each plugin declared it raises, bound to the registry and kept in the order declared.+ self.declared_error_codes: dict[str, tuple[ErrorCode, ...]] = {}# Ordered list (not a type-keyed dict) because the exception types are# resolved lazily — only ``get_http_error_mappers`` invokes the providers,# so duplicate-by-type detection is deferred to resolution time too.@@ -428,6 +432,32 @@ class PluginRegistrar:if contributed:self._active.contributions.append(f"service error codes {', '.join(contributed)}")+ def declare_error_codes(self, *, codes: "Iterable[str]") -> None:+ """Declare the public error codes this plugin raises, binding each to the registry that defines it.++ A plugin, a closed one included, raises errors whose codes are public: a caller reads the code, its page and its+ next step whatever plugin raised it, so each must be a code of the MTHDS core or of Pipelex's registry. Each+ declared code is parsed here (``parse_error_code``), at boot, and an unregistered one refuses the boot with+ ``PluginErrorCodeNotRegisteredError`` (``pipelex.plugin.broken``), naming the plugin and the code, before any of+ the plugin's codes is bound: a release of the plugin that targets a code this Pipelex does not define fails+ where its operator sees it, not on a caller's run. A code may be given as its string or as its constant, and+ declared by several plugins, since a public code means one thing whoever raises it. The bound codes are kept+ per plugin in ``declared_error_codes``, each once, in the order first declared.+ """+ bound: list[ErrorCode] = []+ for code in codes:+ error_code = parse_error_code(code)+ if error_code is None:+ raise PluginErrorCodeNotRegisteredError(plugin_name=self._active.name, code=code)+ bound.append(error_code)+ if not bound:+ return+ already_declared = self.declared_error_codes.get(self._active.name, ())+ newly_declared = tuple(dict.fromkeys(error_code for error_code in bound if error_code not in already_declared))+ self.declared_error_codes[self._active.name] = already_declared + newly_declared+ if newly_declared:+ self._active.contributions.append(f"error codes {', '.join(newly_declared)}")+def add_pipe_func_executor(self, *, mode: str, factory: PipeFuncExecutorFactoryFn) -> None:"""Contribute a factory for one PipeFunc execution mode, keyed by an open ``mode`` token.diff --git a/pipelex/providers/anthropic/anthropic_bedrock_sigv4.py b/pipelex/providers/anthropic/anthropic_bedrock_sigv4.pyindex fcd184f77..5f626b759 100644--- a/pipelex/providers/anthropic/anthropic_bedrock_sigv4.py+++ b/pipelex/providers/anthropic/anthropic_bedrock_sigv4.py@@ -4,6 +4,7 @@ from typing import Anyimport httpxfrom anthropic import DEFAULT_MAX_RETRIES, NOT_GIVEN, NotGivenfrom anthropic.lib.bedrock import AsyncAnthropicBedrock+from mthds.protocol.problem.registry import CoreCodefrom pipelex.providers.anthropic.anthropic_exceptions import AnthropicFactoryError@@ -47,7 +48,7 @@ class AsyncAnthropicBedrockSigV4(AsyncAnthropicBedrock):"AsyncAnthropicBedrockSigV4 signs with AWS access keys and takes no api_key: ""a Bedrock bearer token belongs to the 'bedrock_token' access variant")- raise AnthropicFactoryError(msg)+ raise AnthropicFactoryError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)super().__init__(aws_region=aws_region,base_url=base_url,diff --git a/pipelex/providers/anthropic/anthropic_exceptions.py b/pipelex/providers/anthropic/anthropic_exceptions.pyindex fca3b0c6f..d4a84f814 100644--- a/pipelex/providers/anthropic/anthropic_exceptions.py+++ b/pipelex/providers/anthropic/anthropic_exceptions.py@@ -1,17 +1,33 @@+from mthds.protocol.problem.registry import CoreCode+from pipelex.cogt.exceptions import CogtError+from pipelex.errors.error_code_declaration import ErrorCodeSet+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodeclass AnthropicModelListingError(CogtError):- pass+ """Anthropic's model listing answered with no models, which only the model listing command reads."""++ error_code = CoreCode.PROVIDER_RESPONSE_INVALIDclass AnthropicSDKUnsupportedError(CogtError):- pass+ """An Anthropic client variant that cannot list models, which the plugin turns into ``ModelListingUnsupportedError``."""++ error_code = CoreCode.RUNTIME_UNSUPPORTEDclass AnthropicWorkerConfigurationError(CogtError):- pass+ """A model spec missing a setting Anthropic requires, such as its ``max_tokens``."""++ error_code = PipelexErrorCode.CONFIG_INVALIDclass AnthropicFactoryError(CogtError):- pass+ """An Anthropic client the backend's settings cannot build.++ ``pipelex.config.invalid`` for an SDK handle or an authentication setting the backend gets wrong, and+ ``runtime.unexpected`` for an API key handed to the AWS request signer, which our own wiring does.+ """++ error_code = ErrorCodeSet(default=PipelexErrorCode.CONFIG_INVALID, others=(CoreCode.RUNTIME_UNEXPECTED,))diff --git a/pipelex/providers/anthropic/anthropic_list.py b/pipelex/providers/anthropic/anthropic_list.pyindex 7a0b1f706..c5c28d744 100644--- a/pipelex/providers/anthropic/anthropic_list.py+++ b/pipelex/providers/anthropic/anthropic_list.py@@ -3,6 +3,8 @@ from __future__ import annotationsimport importlib.utilfrom typing import TYPE_CHECKING+from mthds.protocol.problem.registry import CoreCode+from pipelex.cli.exceptions import PipelexCLIErrorfrom pipelex.plugins.model_handle import ModelHandlefrom pipelex.runtime_hub import get_console@@ -64,7 +66,7 @@ async def list_anthropic_models()except AuthenticationError as auth_exc:msg = f"Authentication error for SDK '{sdk}' in backend '{backend_name}': {auth_exc}"- raise PipelexCLIError(msg) from auth_exc+ raise PipelexCLIError(msg).with_error_code(CoreCode.PROVIDER_CREDENTIAL_REFUSED) from auth_excdef _display_anthropic_models_flat(diff --git a/pipelex/providers/anthropic/anthropic_llm_worker.py b/pipelex/providers/anthropic/anthropic_llm_worker.pyindex ec3c18789..bab5db069 100644--- a/pipelex/providers/anthropic/anthropic_llm_worker.py+++ b/pipelex/providers/anthropic/anthropic_llm_worker.py@@ -9,6 +9,7 @@ from anthropic import ()from anthropic.lib.bedrock import AsyncAnthropicBedrockfrom anthropic.types import OutputConfigParam, ThinkingConfigParam+from mthds.protocol.problem.registry import CoreCodefrom pydantic.dataclasses import dataclass as pydantic_dataclassfrom typing_extensions import override@@ -20,8 +21,8 @@ from pipelex.cogt.inference.error_classification import (extract_anthropic_metadata,extract_underlying_sdk_exception,)-from pipelex.cogt.inference.error_classify import classify_inference_error-from pipelex.cogt.inference.error_render import InferenceErrorFamily, render_inference_error+from pipelex.cogt.inference.error_classify import InferenceErrorFamily, classify_inference_error+from pipelex.cogt.inference.error_render import render_inference_errorfrom pipelex.cogt.llm.instructor_retry import make_instructor_schema_retryingfrom pipelex.cogt.llm.llm_job import LLMJobfrom pipelex.cogt.llm.llm_job_components import LLMJobParams, ReasoningEffort@@ -369,7 +370,7 @@ class AnthropicLLMWorker(LLMWorkerAbstract):final_message: Message = await stream.get_final_message()except (APIStatusError, APIConnectionError) as sdk_exc:metadata = extract_anthropic_metadata(sdk_exc)- classification = classify_inference_error(metadata)+ classification = classify_inference_error(metadata, family=InferenceErrorFamily.LLM)raise render_inference_error(metadata=metadata,classification=classification,@@ -412,7 +413,7 @@ class AnthropicLLMWorker(LLMWorkerAbstract):" — shorten the prompt, raise max_tokens, or disable thinking"),),- )+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)return "\n\n".join(text_parts)@@ -516,7 +517,7 @@ class AnthropicLLMWorker(LLMWorkerAbstract):underlying_exc = extract_underlying_sdk_exception(instructor_exc=instructor_exc)if underlying_exc is not None:metadata = extract_anthropic_metadata(underlying_exc)- classification = classify_inference_error(metadata)+ classification = classify_inference_error(metadata, family=InferenceErrorFamily.LLM)rendered_error = render_inference_error(metadata=metadata,classification=classification,@@ -536,11 +537,11 @@ class AnthropicLLMWorker(LLMWorkerAbstract):kind=UserActionKind.CONTACT_SUPPORT,detail="Structured generation failed for an unrecognized reason — retry, and report this if it persists",),- )+ ).with_error_code(CoreCode.RUNTIME_UNEXPECTED)raise self._with_note(error=fallback_error, note=lowered_max_tokens_note, failure=None) from instructor_excexcept (APIStatusError, APIConnectionError) as sdk_exc:metadata = extract_anthropic_metadata(sdk_exc)- classification = classify_inference_error(metadata)+ classification = classify_inference_error(metadata, family=InferenceErrorFamily.LLM)rendered_error = render_inference_error(metadata=metadata,classification=classification,diff --git a/pipelex/providers/azure_rest/azure_exceptions.py b/pipelex/providers/azure_rest/azure_exceptions.pyindex 7d8ac0777..f21da721e 100644--- a/pipelex/providers/azure_rest/azure_exceptions.py+++ b/pipelex/providers/azure_rest/azure_exceptions.py@@ -1,5 +1,15 @@+from pipelex.cogt.exceptions import CogtError+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.system.exceptions import CredentialsErrorclass AzureCredentialsError(CredentialsError):- pass+ """An Azure backend with no API key configured."""++ error_code = PipelexErrorCode.CONFIG_CREDENTIAL_MISSING+++class AzureWorkerConfigurationError(CogtError):+ """An Azure backend missing a setting its worker requires, such as its ``api_version``."""++ error_code = PipelexErrorCode.CONFIG_INVALIDdiff --git a/pipelex/providers/azure_rest/azure_img_gen_worker.py b/pipelex/providers/azure_rest/azure_img_gen_worker.pyindex c4c251459..f250d83af 100644--- a/pipelex/providers/azure_rest/azure_img_gen_worker.py+++ b/pipelex/providers/azure_rest/azure_img_gen_worker.py@@ -1,9 +1,10 @@import jsonimport httpx+from mthds.protocol.problem.registry import CoreCodefrom typing_extensions import override-from pipelex.cogt.exceptions import CogtError, ImgGenGenerationError, ImgGenParameterError, InferenceErrorCategory+from pipelex.cogt.exceptions import ImgGenGenerationError, ImgGenParameterError, InferenceErrorCategoryfrom pipelex.cogt.image.generated_image import GeneratedImageRawDetailsfrom pipelex.cogt.image.image_size import ImageSizefrom pipelex.cogt.img_gen.img_gen_args_factory import ImageFileTuple, ImgGenArgsFactory@@ -15,14 +16,15 @@ from pipelex.cogt.inference.error_classification import (extract_azure_metadata,extract_azure_metadata_from_response,)-from pipelex.cogt.inference.error_classify import classify_inference_error-from pipelex.cogt.inference.error_render import InferenceErrorFamily, render_inference_error+from pipelex.cogt.inference.error_classify import InferenceErrorFamily, classify_inference_error+from pipelex.cogt.inference.error_render import render_inference_errorfrom pipelex.cogt.inference.transport_retry import request_with_transport_retryfrom pipelex.cogt.model_backends.model_spec import InferenceModelSpecfrom pipelex.cogt.usage.token_category import NbTokensByCategoryDict, TokenCategoryfrom pipelex.config import get_config+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.plugins.model_handle import ModelHandle-from pipelex.providers.azure_rest.azure_exceptions import AzureCredentialsError+from pipelex.providers.azure_rest.azure_exceptions import AzureCredentialsError, AzureWorkerConfigurationErrorfrom pipelex.reporting.reporting_protocol import ReportingProtocolfrom pipelex.runtime_hub import get_models_manager@@ -46,7 +48,7 @@ class AzureImgGenWorker(ImgGenWorkerAbstract):self.api_version = backend.extra_config.get("api_version")if not self.api_version:msg = "Azure OpenAI API version is not configured"- raise CogtError(msg)+ raise AzureWorkerConfigurationError(msg)if not backend.api_key:msg = "Azure OpenAI API key (subscription_key) is not configured"raise AzureCredentialsError(msg)@@ -81,8 +83,8 @@ class AzureImgGenWorker(ImgGenWorkerAbstract):detail="Azure server error after submission — the outcome is unknown; retry manually after checking for a duplicate image",),provider_metadata=metadata,- ) from exc- classification = classify_inference_error(metadata)+ ).with_error_code(CoreCode.PROVIDER_OUTCOME_UNKNOWN) from exc+ classification = classify_inference_error(metadata, family=InferenceErrorFamily.IMG_GEN)raise render_inference_error(metadata=metadata,classification=classification,@@ -108,7 +110,7 @@ class AzureImgGenWorker(ImgGenWorkerAbstract):) -> list[GeneratedImageRawDetails]:if self.inference_model.rules is None:msg = f"Model '{self.inference_model.name}' does not have rules configured"- raise ImgGenParameterError(msg, error_category=InferenceErrorCategory.CONFIGURATION)+ raise ImgGenParameterError(msg, error_category=InferenceErrorCategory.CONFIGURATION).with_error_code(PipelexErrorCode.CONFIG_INVALID)args_dict = await ImgGenArgsFactory.make_args_for_model(model_rules=self.inference_model.rules,@@ -184,7 +186,7 @@ class AzureImgGenWorker(ImgGenWorkerAbstract):# Must precede the httpx.TimeoutException clause below (ConnectTimeout / PoolTimeout are# subclasses).metadata = extract_azure_metadata(exc)- classification = classify_inference_error(metadata)+ classification = classify_inference_error(metadata, family=InferenceErrorFamily.IMG_GEN)raise render_inference_error(metadata=metadata,classification=classification,@@ -208,7 +210,7 @@ class AzureImgGenWorker(ImgGenWorkerAbstract):detail="Azure timed out mid-request — the outcome is unknown; retry manually after checking for a duplicate image",),provider_metadata=metadata,- ) from exc+ ).with_error_code(CoreCode.PROVIDER_OUTCOME_UNKNOWN) from excexcept httpx.TransportError as exc:# Catch-all for the remaining httpx.TransportError family — ReadError / WriteError /# RemoteProtocolError and the like — which fire when the connection drops mid-request.@@ -227,7 +229,7 @@ class AzureImgGenWorker(ImgGenWorkerAbstract):detail="The connection to Azure failed mid-request — the outcome is unknown; retry manually after checking for a duplicate image",),provider_metadata=metadata,- ) from exc+ ).with_error_code(CoreCode.PROVIDER_OUTCOME_UNKNOWN) from exc# The HTTP status was successful, but Azure (or an intermediary gateway) can still# return a malformed or non-JSON body. json() raises a json.JSONDecodeError here, so@@ -236,7 +238,7 @@ class AzureImgGenWorker(ImgGenWorkerAbstract):response_dict = response.json()except json.JSONDecodeError as exc:metadata = extract_azure_metadata_from_response(response, sdk_exception_type=type(exc).__name__, message=str(exc))- classification = classify_inference_error(metadata)+ classification = classify_inference_error(metadata, family=InferenceErrorFamily.IMG_GEN)raise render_inference_error(metadata=metadata,classification=classification,@@ -271,7 +273,7 @@ class AzureImgGenWorker(ImgGenWorkerAbstract):detail="Azure returned an image without an output format — try a different model",),provider_metadata=None,- )+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)generated_images: list[GeneratedImageRawDetails] = []if images := response_dict.get("data"):size = response_dict.get("size")@@ -285,7 +287,7 @@ class AzureImgGenWorker(ImgGenWorkerAbstract):detail="Azure returned a malformed image size — try a different model",),provider_metadata=None,- )+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)size_split = size.split("x")if len(size_split) != 2:msg = f"Size from img gen response is not a valid size: '{size}'"@@ -297,7 +299,7 @@ class AzureImgGenWorker(ImgGenWorkerAbstract):detail="Azure returned a malformed image size — try a different model",),provider_metadata=None,- )+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)width_str, height_str = size_splittry:width = int(width_str)@@ -312,7 +314,7 @@ class AzureImgGenWorker(ImgGenWorkerAbstract):detail="Azure returned a malformed image size — try a different model",),provider_metadata=None,- ) from exc+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID) from excfor image in images:base64_str = image.get("b64_json")if not isinstance(base64_str, str):@@ -325,7 +327,7 @@ class AzureImgGenWorker(ImgGenWorkerAbstract):detail="Azure returned no image data — try rephrasing the prompt or using a different model",),provider_metadata=None,- )+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)generated_images.append(GeneratedImageRawDetails(base64_str=base64_str,@@ -343,6 +345,6 @@ class AzureImgGenWorker(ImgGenWorkerAbstract):detail="Azure returned an unexpected response shape — try a different model",),provider_metadata=None,- )+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)return generated_imagesdiff --git a/pipelex/providers/bedrock/bedrock_exceptions.py b/pipelex/providers/bedrock/bedrock_exceptions.pyindex 241d95a18..853ab3853 100644--- a/pipelex/providers/bedrock/bedrock_exceptions.py+++ b/pipelex/providers/bedrock/bedrock_exceptions.py@@ -1,9 +1,14 @@from pipelex.cogt.exceptions import CogtError+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodeclass BedrockFactoryError(CogtError):- pass+ """A Bedrock client the backend's settings cannot build, such as for an SDK handle it does not support."""++ error_code = PipelexErrorCode.CONFIG_INVALIDclass BedrockWorkerConfigurationError(CogtError):- pass+ """A model spec missing a setting Bedrock requires, such as its ``max_tokens``."""++ error_code = PipelexErrorCode.CONFIG_INVALIDdiff --git a/pipelex/providers/bedrock/bedrock_list.py b/pipelex/providers/bedrock/bedrock_list.pyindex 64018ee62..7f9731dfc 100644--- a/pipelex/providers/bedrock/bedrock_list.py+++ b/pipelex/providers/bedrock/bedrock_list.py@@ -3,6 +3,8 @@ from __future__ import annotationsimport importlib.utilfrom typing import TYPE_CHECKING, Any+from mthds.protocol.problem.registry import CoreCode+from pipelex.cli.exceptions import PipelexCLIErrorfrom pipelex.config import get_configfrom pipelex.plugins.model_handle import ModelHandle@@ -70,9 +72,13 @@ def list_bedrock_models(aws_region=aws_region,)- except (AwsCredentialsError, BotoCoreError, ClientError) as exc:+ except AwsCredentialsError as exc:msg = f"Error listing Bedrock models: {exc}"raise PipelexCLIError(msg) from exc+ except (BotoCoreError, ClientError) as exc:+ # The SDK's own failure carries no code: Bedrock answered the listing, or could not be reached, with a failure.+ msg = f"Error listing Bedrock models: {exc}"+ raise PipelexCLIError(msg).with_error_code(CoreCode.PROVIDER_FAILED) from excdef _display_bedrock_models_flat(diff --git a/pipelex/providers/bedrock/bedrock_llm_worker.py b/pipelex/providers/bedrock/bedrock_llm_worker.pyindex fb0cc3a6e..4ea7d76a4 100644--- a/pipelex/providers/bedrock/bedrock_llm_worker.py+++ b/pipelex/providers/bedrock/bedrock_llm_worker.py@@ -1,12 +1,13 @@from typing import Anyfrom botocore.exceptions import ClientError+from mthds.protocol.problem.registry import CoreCodefrom typing_extensions import overridefrom pipelex.cogt.exceptions import InferenceErrorCategory, LLMCapabilityError, LLMCompletionError, SdkTypeErrorfrom pipelex.cogt.inference.error_classification import UserAction, UserActionKind, extract_bedrock_metadata-from pipelex.cogt.inference.error_classify import classify_inference_error-from pipelex.cogt.inference.error_render import InferenceErrorFamily, render_inference_error+from pipelex.cogt.inference.error_classify import InferenceErrorFamily, classify_inference_error+from pipelex.cogt.inference.error_render import render_inference_errorfrom pipelex.cogt.llm.llm_job import LLMJobfrom pipelex.cogt.llm.llm_job_components import LLMJobParamsfrom pipelex.cogt.llm.llm_worker_abstract import LLMWorkerAbstract@@ -78,7 +79,7 @@ class BedrockLLMWorker(LLMWorkerAbstract):)except ClientError as exc:metadata = extract_bedrock_metadata(exc)- classification = classify_inference_error(metadata)+ classification = classify_inference_error(metadata, family=InferenceErrorFamily.LLM)raise render_inference_error(metadata=metadata,classification=classification,@@ -100,7 +101,7 @@ class BedrockLLMWorker(LLMWorkerAbstract):kind=UserActionKind.CHANGE_INPUT,detail="Bedrock returned an empty text response — try rephrasing the prompt or using a different model",),- )+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)return chat_result.text@overridediff --git a/pipelex/providers/docling/docling_extract_worker.py b/pipelex/providers/docling/docling_extract_worker.pyindex e5d85f475..817260301 100644--- a/pipelex/providers/docling/docling_extract_worker.py+++ b/pipelex/providers/docling/docling_extract_worker.py@@ -15,8 +15,8 @@ from pipelex.cogt.extract.extract_job import ExtractJobfrom pipelex.cogt.extract.extract_output import ExtractOutputfrom pipelex.cogt.extract.extract_worker_abstract import ExtractWorkerAbstractfrom pipelex.cogt.inference.error_classification import extract_local_extract_metadata-from pipelex.cogt.inference.error_classify import classify_inference_error-from pipelex.cogt.inference.error_render import InferenceErrorFamily, render_inference_error+from pipelex.cogt.inference.error_classify import InferenceErrorFamily, classify_inference_error+from pipelex.cogt.inference.error_render import render_inference_errorfrom pipelex.cogt.inference.provider_name import ProviderNamefrom pipelex.cogt.model_backends.model_spec import InferenceModelSpecfrom pipelex.providers.docling.docling_factory import DoclingFactory@@ -126,7 +126,7 @@ class DoclingExtractWorker(ExtractWorkerAbstract):# corrupt/unreadable documents, unsupported formats, or file system issues.except (FileNotFoundError, ValueError, RuntimeError, OSError) as sdk_exc:metadata = extract_local_extract_metadata(sdk_exc, provider=ProviderName.DOCLING)- classification = classify_inference_error(metadata)+ classification = classify_inference_error(metadata, family=InferenceErrorFamily.EXTRACT)raise render_inference_error(metadata=metadata,classification=classification,diff --git a/pipelex/providers/fal/fal_factory.py b/pipelex/providers/fal/fal_factory.pyindex a1ca13989..3c2753207 100644--- a/pipelex/providers/fal/fal_factory.py+++ b/pipelex/providers/fal/fal_factory.py@@ -1,5 +1,6 @@from typing import Any, cast+from mthds.protocol.problem.registry import CoreCodefrom pydantic import ValidationErrorfrom pipelex.cogt.exceptions import ImgGenGenerationError, InferenceErrorCategory@@ -22,7 +23,7 @@ class FalFactory:detail="FAL returned an unexpected number of images — try a different model",),provider_metadata=None,- )+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)return generated_image_list[0]@classmethod@@ -40,7 +41,7 @@ class FalFactory:detail="FAL returned an unexpected response shape — try a different model",),provider_metadata=None,- )+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)image_dicts = cast("list[dict[str, Any]]", image_dicts)for image_dict in image_dicts:generated_image = GeneratedImageRawDetails(@@ -59,6 +60,6 @@ class FalFactory:detail="FAL returned a malformed image response — try a different model",),provider_metadata=None,- ) from exc+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID) from excreturn generated_image_listdiff --git a/pipelex/providers/fal/fal_img_gen_worker.py b/pipelex/providers/fal/fal_img_gen_worker.pyindex d36d8778e..55fa05d25 100644--- a/pipelex/providers/fal/fal_img_gen_worker.py+++ b/pipelex/providers/fal/fal_img_gen_worker.py@@ -11,9 +11,10 @@ from pipelex.cogt.img_gen.img_gen_args_factory import ImgGenArgsFactoryfrom pipelex.cogt.img_gen.img_gen_job import ImgGenJobfrom pipelex.cogt.img_gen.img_gen_worker_abstract import ImgGenWorkerAbstractfrom pipelex.cogt.inference.error_classification import extract_fal_metadata-from pipelex.cogt.inference.error_classify import classify_inference_error-from pipelex.cogt.inference.error_render import InferenceErrorFamily, render_inference_error+from pipelex.cogt.inference.error_classify import InferenceErrorFamily, classify_inference_error+from pipelex.cogt.inference.error_render import render_inference_errorfrom pipelex.cogt.model_backends.model_spec import InferenceModelSpec+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.providers.fal.fal_factory import FalFactoryfrom pipelex.reporting.reporting_protocol import ReportingProtocol@@ -41,7 +42,7 @@ class FalImgGenWorker(ImgGenWorkerAbstract):) -> Any:if self.inference_model.rules is None:msg = f"Model '{self.inference_model.name}' does not have rules configured"- raise ImgGenParameterError(msg, error_category=InferenceErrorCategory.CONFIGURATION)+ raise ImgGenParameterError(msg, error_category=InferenceErrorCategory.CONFIGURATION).with_error_code(PipelexErrorCode.CONFIG_INVALID)args_dict = await ImgGenArgsFactory.make_args_for_model(model_rules=self.inference_model.rules,img_gen_job=img_gen_job,@@ -52,7 +53,7 @@ class FalImgGenWorker(ImgGenWorkerAbstract):fal_application = args_dict.pop("model", None)if fal_application is None:msg = f"Model '{self.inference_model.name}' rules must include a 'model_choice' entry"- raise ImgGenParameterError(msg, error_category=InferenceErrorCategory.CONFIGURATION)+ raise ImgGenParameterError(msg, error_category=InferenceErrorCategory.CONFIGURATION).with_error_code(PipelexErrorCode.CONFIG_INVALID)try:handler = await self.fal_async_client.submit(application=fal_application,@@ -61,7 +62,7 @@ class FalImgGenWorker(ImgGenWorkerAbstract):return await handler.get()except (MissingCredentialsError, FalClientHTTPError, FalClientTimeoutError, FalClientError) as exc:metadata = extract_fal_metadata(exc)- classification = classify_inference_error(metadata)+ classification = classify_inference_error(metadata, family=InferenceErrorFamily.IMG_GEN)raise render_inference_error(metadata=metadata,classification=classification,diff --git a/pipelex/providers/fal/fal_poller.py b/pipelex/providers/fal/fal_poller.pydeleted file mode 100644index 774a0463f..000000000--- a/pipelex/providers/fal/fal_poller.py+++ /dev/null@@ -1,82 +0,0 @@-from __future__ import annotations--from typing import Any, cast--import httpx-from tenacity import (- AsyncRetrying,- retry_if_exception,- retry_if_exception_type,- retry_if_result,- stop_after_delay,- wait_random_exponential,-)--from pipelex.tools.misc.tenacity_utils import log_retry---class FalPoller:- def _is_transient_http(self, exc: BaseException) -> bool:- if not isinstance(exc, httpx.HTTPStatusError):- return False- code = exc.response.status_code- return code == 429 or 500 <= code <= 599-- async def poll_queue_until_complete(self, response_dict: dict[str, Any]) -> dict[str, Any]:- """Poll Queue API until completion and return the final response JSON.-- Expects response_dict to include:- - status_url (str)- - response_url (str)-- Reads API key from env var FAL_KEY.- """- status_url = response_dict.get("status_url")- response_url = response_dict.get("response_url")- if not isinstance(status_url, str) or not isinstance(response_url, str):- msg = "response_dict must include 'status_url' and 'response_url' as strings"- raise TypeError(msg)-- async with httpx.AsyncClient(timeout=httpx.Timeout(20.0)) as client:-- async def _try_once() -> dict[str, Any] | None:- # 1) poll status- status = await client.get(status_url)- status.raise_for_status() # will be retried on 429/5xx via tenacity-- payload = status.json()- status = payload.get("status")-- if status in {"IN_QUEUE", "IN_PROGRESS"}:- return None # tells tenacity to retry-- if status == "COMPLETED":- # 2) fetch the actual response- res = await client.get(response_url)- res.raise_for_status()- return cast("dict[str, Any]", res.json())-- # Terminal / unexpected states: fail fast (no retry)- msg = f"fal request ended with status={status!r}: {payload}"- raise RuntimeError(msg)-- retrying = AsyncRetrying(- retry=(- retry_if_result(lambda r: r is None)- | retry_if_exception_type((httpx.TimeoutException, httpx.TransportError))- | retry_if_exception(self._is_transient_http)- ),- before_sleep=log_retry,- wait=wait_random_exponential(multiplier=0.5, max=8.0), # jittered backoff- stop=stop_after_delay(300.0), # total polling budget (seconds)- reraise=True,- )-- async for attempt in retrying:- with attempt:- result = await _try_once()- if result is not None:- return result-- msg = "Polling ended unexpectedly"- raise RuntimeError(msg)diff --git a/pipelex/providers/google/google_exceptions.py b/pipelex/providers/google/google_exceptions.pyindex b6fda43a8..f48716f8b 100644--- a/pipelex/providers/google/google_exceptions.py+++ b/pipelex/providers/google/google_exceptions.py@@ -1,9 +1,9 @@+from mthds.protocol.problem.registry import CoreCode+from pipelex.cogt.exceptions import CogtErrorclass GoogleLLMWorkerError(CogtError):- """Base exception for Google LLM Worker errors."""-+ """A Gemini structured answer whose parsed result is not of the schema's type."""-class GoogleImgGenWorkerError(CogtError):- """Base exception for Google Image Generation Worker errors."""+ error_code = CoreCode.MODEL_OUTPUT_SCHEMA_MISMATCHdiff --git a/pipelex/providers/google/google_factory.py b/pipelex/providers/google/google_factory.pyindex 65a46c957..cc1601afc 100644--- a/pipelex/providers/google/google_factory.py+++ b/pipelex/providers/google/google_factory.py@@ -5,6 +5,7 @@ from typing import Any, ClassVarfrom google.genai import types as genai_typesfrom google.genai.client import Client as GoogleGenAiClient+from mthds.protocol.problem.registry import CoreCodefrom pipelex import logfrom pipelex.cogt.document.prompt_document import PromptDocument@@ -129,7 +130,7 @@ class GoogleFactory:kind=UserActionKind.CHANGE_INPUT,detail="Google Gemini returned no candidates — try rephrasing the prompt or using a different model",),- )+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)candidate = response.candidates[0]if not candidate.content or not candidate.content.parts:@@ -142,7 +143,7 @@ class GoogleFactory:kind=UserActionKind.CHANGE_INPUT,detail="Google Gemini returned a candidate with no content parts — try rephrasing the prompt or using a different model",),- )+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)text_parts: list[str] = []for part in candidate.content.parts:@@ -163,7 +164,7 @@ class GoogleFactory:kind=UserActionKind.CHANGE_INPUT,detail="Google Gemini returned only thinking parts and no text — shorten the prompt, raise max_tokens, or disable thinking",),- )+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)return "\n\n".join(text_parts)diff --git a/pipelex/providers/google/google_img_gen_worker.py b/pipelex/providers/google/google_img_gen_worker.pyindex c92adbe55..5a26ae194 100644--- a/pipelex/providers/google/google_img_gen_worker.py+++ b/pipelex/providers/google/google_img_gen_worker.py@@ -5,6 +5,7 @@ import httpxfrom google.genai import errors as genai_errorsfrom google.genai import types as genai_typesfrom google.genai.client import Client as GoogleGenAiClient+from mthds.protocol.problem.registry import CoreCodefrom typing_extensions import overridefrom pipelex import log@@ -15,8 +16,8 @@ from pipelex.cogt.img_gen.img_gen_gemini_mapping import ImgGenGeminiMappingfrom pipelex.cogt.img_gen.img_gen_job import ImgGenJobfrom pipelex.cogt.img_gen.img_gen_worker_abstract import ImgGenWorkerAbstractfrom pipelex.cogt.inference.error_classification import UserAction, UserActionKind, extract_google_metadata-from pipelex.cogt.inference.error_classify import classify_inference_error-from pipelex.cogt.inference.error_render import InferenceErrorFamily, render_inference_error+from pipelex.cogt.inference.error_classify import InferenceErrorFamily, classify_inference_error+from pipelex.cogt.inference.error_render import render_inference_errorfrom pipelex.cogt.model_backends.model_spec import InferenceModelSpecfrom pipelex.providers.google.google_factory import GoogleFactoryfrom pipelex.reporting.reporting_protocol import ReportingProtocol@@ -121,7 +122,7 @@ class GoogleImgGenWorker(ImgGenWorkerAbstract):)except (genai_errors.ServerError, genai_errors.ClientError, httpx.TransportError) as exc:metadata = extract_google_metadata(exc)- classification = classify_inference_error(metadata)+ classification = classify_inference_error(metadata, family=InferenceErrorFamily.IMG_GEN)raise render_inference_error(metadata=metadata,classification=classification,@@ -152,7 +153,7 @@ class GoogleImgGenWorker(ImgGenWorkerAbstract):detail="Google returned no image candidates — try rephrasing the prompt or using a different model",),provider_metadata=None,- )+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)candidate = response.candidates[0]if not candidate.content or not candidate.content.parts:@@ -165,7 +166,7 @@ class GoogleImgGenWorker(ImgGenWorkerAbstract):detail="Google returned an empty response — try rephrasing the prompt or using a different model",),provider_metadata=None,- )+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)# Look for image data in response partsfor part in candidate.content.parts:@@ -184,7 +185,7 @@ class GoogleImgGenWorker(ImgGenWorkerAbstract):detail="Google returned image data without a mime type — try a different model",),provider_metadata=None,- )+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)return GeneratedImageRawDetails(actual_bytes=image_bytes,size=ImageSize(width=resolved.width, height=resolved.height),@@ -200,7 +201,7 @@ class GoogleImgGenWorker(ImgGenWorkerAbstract):detail="Google returned no image data — try rephrasing the prompt or using a different model",),provider_metadata=None,- )+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)@overrideasync def _gen_image_list(diff --git a/pipelex/providers/google/google_llm_worker.py b/pipelex/providers/google/google_llm_worker.pyindex 4cc42418e..7de05ad8b 100644--- a/pipelex/providers/google/google_llm_worker.py+++ b/pipelex/providers/google/google_llm_worker.py@@ -5,6 +5,7 @@ import httpxfrom google.genai import errors as genai_errorsfrom google.genai import types as genai_typesfrom google.genai.client import Client as GoogleGenAiClient+from mthds.protocol.problem.registry import CoreCodefrom typing_extensions import overridefrom pipelex import log@@ -15,8 +16,8 @@ from pipelex.cogt.inference.error_classification import (extract_google_metadata,extract_underlying_sdk_exception,)-from pipelex.cogt.inference.error_classify import classify_inference_error-from pipelex.cogt.inference.error_render import InferenceErrorFamily, render_inference_error+from pipelex.cogt.inference.error_classify import InferenceErrorFamily, classify_inference_error+from pipelex.cogt.inference.error_render import render_inference_errorfrom pipelex.cogt.llm.completion_stop import classify_prompt_block_reasonfrom pipelex.cogt.llm.instructor_retry import make_instructor_schema_retryingfrom pipelex.cogt.llm.llm_job import LLMJob@@ -252,7 +253,7 @@ class GoogleLLMWorker(LLMWorkerAbstract):)except (genai_errors.ServerError, genai_errors.ClientError, httpx.TransportError) as sdk_exc:metadata = extract_google_metadata(sdk_exc)- classification = classify_inference_error(metadata)+ classification = classify_inference_error(metadata, family=InferenceErrorFamily.LLM)raise render_inference_error(metadata=metadata,classification=classification,@@ -345,7 +346,7 @@ class GoogleLLMWorker(LLMWorkerAbstract):underlying_exc = extract_underlying_sdk_exception(instructor_exc=instructor_exc)if underlying_exc is not None:metadata = extract_google_metadata(underlying_exc)- classification = classify_inference_error(metadata)+ classification = classify_inference_error(metadata, family=InferenceErrorFamily.LLM)raise render_inference_error(metadata=metadata,classification=classification,@@ -361,10 +362,10 @@ class GoogleLLMWorker(LLMWorkerAbstract):kind=UserActionKind.CONTACT_SUPPORT,detail="Structured generation failed for an unrecognized reason — retry, and report this if it persists",),- ) from instructor_exc+ ).with_error_code(CoreCode.RUNTIME_UNEXPECTED) from instructor_excexcept (genai_errors.ServerError, genai_errors.ClientError, httpx.TransportError) as sdk_exc:metadata = extract_google_metadata(sdk_exc)- classification = classify_inference_error(metadata)+ classification = classify_inference_error(metadata, family=InferenceErrorFamily.LLM)raise render_inference_error(metadata=metadata,classification=classification,diff --git a/pipelex/providers/huggingface/huggingface_exceptions.py b/pipelex/providers/huggingface/huggingface_exceptions.pynew file mode 100644index 000000000..980312816--- /dev/null+++ b/pipelex/providers/huggingface/huggingface_exceptions.py@@ -0,0 +1,11 @@+from pipelex.cogt.exceptions import CogtError+from pipelex.errors.registry.pipelex_codes import PipelexErrorCode+++class HuggingFaceProviderUnknownError(CogtError):+ """A Hugging Face model handle whose variant names an inference provider the Hugging Face client does not know.++ The variant is the model spec's, so the deployment's configuration is what names it.+ """++ error_code = PipelexErrorCode.CONFIG_INVALIDdiff --git a/pipelex/providers/huggingface/huggingface_factory.py b/pipelex/providers/huggingface/huggingface_factory.pyindex a09405c47..88ed27e52 100644--- a/pipelex/providers/huggingface/huggingface_factory.py+++ b/pipelex/providers/huggingface/huggingface_factory.py@@ -1,5 +1,7 @@from huggingface_hub.inference._providers import PROVIDER_OR_POLICY_T+from pipelex.providers.huggingface.huggingface_exceptions import HuggingFaceProviderUnknownError+class HuggingFaceFactory:@classmethod@@ -48,5 +50,5 @@ class HuggingFaceFactory:case "auto":return "auto"case _:- msg = f"Unknown HuggingFace inference provider: {provider_str}"- raise ValueError(msg)+ msg = f"Unknown Hugging Face inference provider: {provider_str}"+ raise HuggingFaceProviderUnknownError(msg)diff --git a/pipelex/providers/huggingface/huggingface_img_gen_worker.py b/pipelex/providers/huggingface/huggingface_img_gen_worker.pyindex 91aacbea4..8194dae09 100644--- a/pipelex/providers/huggingface/huggingface_img_gen_worker.py+++ b/pipelex/providers/huggingface/huggingface_img_gen_worker.py@@ -11,9 +11,10 @@ from pipelex.cogt.img_gen.img_gen_args_factory import ImgGenArgsFactoryfrom pipelex.cogt.img_gen.img_gen_job import ImgGenJobfrom pipelex.cogt.img_gen.img_gen_worker_abstract import ImgGenWorkerAbstractfrom pipelex.cogt.inference.error_classification import extract_huggingface_metadata-from pipelex.cogt.inference.error_classify import classify_inference_error-from pipelex.cogt.inference.error_render import InferenceErrorFamily, render_inference_error+from pipelex.cogt.inference.error_classify import InferenceErrorFamily, classify_inference_error+from pipelex.cogt.inference.error_render import render_inference_errorfrom pipelex.cogt.model_backends.model_spec import InferenceModelSpec+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.reporting.reporting_protocol import ReportingProtocolfrom pipelex.tools.misc.image_utils import ImageFormat@@ -39,7 +40,7 @@ class HuggingFaceImgGenWorker(ImgGenWorkerAbstract):) -> Image.Image:if self.inference_model.rules is None:msg = f"Model '{self.inference_model.name}' does not have rules configured"- raise ImgGenParameterError(msg, error_category=InferenceErrorCategory.CONFIGURATION)+ raise ImgGenParameterError(msg, error_category=InferenceErrorCategory.CONFIGURATION).with_error_code(PipelexErrorCode.CONFIG_INVALID)args_dict = await ImgGenArgsFactory.make_args_for_model(model_rules=self.inference_model.rules,img_gen_job=img_gen_job,@@ -51,7 +52,7 @@ class HuggingFaceImgGenWorker(ImgGenWorkerAbstract):model_id = args_dict.pop("model", None)if model_id is None:msg = f"Model '{self.inference_model.name}' rules must include a 'model_choice' entry"- raise ImgGenParameterError(msg, error_category=InferenceErrorCategory.CONFIGURATION)+ raise ImgGenParameterError(msg, error_category=InferenceErrorCategory.CONFIGURATION).with_error_code(PipelexErrorCode.CONFIG_INVALID)try:return await self.hf_async_client.text_to_image(prompt=prompt,@@ -60,7 +61,7 @@ class HuggingFaceImgGenWorker(ImgGenWorkerAbstract):)except (InferenceTimeoutError, HfHubHTTPError) as exc:metadata = extract_huggingface_metadata(exc)- classification = classify_inference_error(metadata)+ classification = classify_inference_error(metadata, family=InferenceErrorFamily.IMG_GEN)raise render_inference_error(metadata=metadata,classification=classification,diff --git a/pipelex/providers/linkup/linkup_exceptions.py b/pipelex/providers/linkup/linkup_exceptions.pyindex d1d1e10ee..9e6221e5e 100644--- a/pipelex/providers/linkup/linkup_exceptions.py+++ b/pipelex/providers/linkup/linkup_exceptions.py@@ -1,13 +1,28 @@+from typing import ClassVar++from mthds.protocol.problem.registry import CoreCode+from pipelex.cogt.exceptions import CogtError+from pipelex.errors.error_code_declaration import ErrorCodeDeclaration+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodeclass LinkupError(CogtError):- """Base for every error this backend raises, so callers can catch the provider as a family."""+ """Base for every error this backend raises, so callers can catch the provider as a family.++ Raised itself for a backend with no API key, which is the deployment's missing credential.+ """++ error_code: ClassVar[ErrorCodeDeclaration] = PipelexErrorCode.CONFIG_CREDENTIAL_MISSINGclass LinkupSearchResponseError(LinkupError):"""The Linkup API answered a structured search with a payload shape the leaf cannot validate."""+ error_code = CoreCode.PROVIDER_RESPONSE_INVALID+class LinkupSearchEmptyResultError(LinkupError):"""The Linkup API answered a structured search with no object payload to fill the output structure."""++ error_code = CoreCode.MODEL_NO_RESULTdiff --git a/pipelex/providers/linkup/linkup_extract_worker.py b/pipelex/providers/linkup/linkup_extract_worker.pyindex fac8fd2c5..e04ed0326 100644--- a/pipelex/providers/linkup/linkup_extract_worker.py+++ b/pipelex/providers/linkup/linkup_extract_worker.py@@ -20,8 +20,8 @@ from pipelex.cogt.extract.extract_job import ExtractJobfrom pipelex.cogt.extract.extract_output import ExtractedImageFromPage, ExtractOutput, Pagefrom pipelex.cogt.extract.extract_worker_abstract import ExtractWorkerAbstractfrom pipelex.cogt.inference.error_classification import extract_linkup_metadata-from pipelex.cogt.inference.error_classify import classify_inference_error-from pipelex.cogt.inference.error_render import InferenceErrorFamily, render_inference_error+from pipelex.cogt.inference.error_classify import InferenceErrorFamily, classify_inference_error+from pipelex.cogt.inference.error_render import render_inference_errorfrom pipelex.cogt.model_backends.model_spec import InferenceModelSpecfrom pipelex.cogt.usage.pricing_unit import PricingUnitfrom pipelex.cogt.usage.usage_cost import record_unit_priced_usage@@ -77,7 +77,7 @@ class LinkupExtractWorker(ExtractWorkerAbstract):LinkupUnknownError,) as sdk_exc:metadata = extract_linkup_metadata(sdk_exc)- classification = classify_inference_error(metadata)+ classification = classify_inference_error(metadata, family=InferenceErrorFamily.EXTRACT)raise render_inference_error(metadata=metadata,classification=classification,diff --git a/pipelex/providers/linkup/linkup_search_worker.py b/pipelex/providers/linkup/linkup_search_worker.pyindex b65b39660..b78d7ec92 100644--- a/pipelex/providers/linkup/linkup_search_worker.py+++ b/pipelex/providers/linkup/linkup_search_worker.py@@ -17,8 +17,8 @@ from typing_extensions import overridefrom pipelex.cogt.exceptions import InferenceErrorCategoryfrom pipelex.cogt.inference.error_classification import UserAction, UserActionKind, extract_linkup_metadata-from pipelex.cogt.inference.error_classify import classify_inference_error-from pipelex.cogt.inference.error_render import InferenceErrorFamily, render_inference_error+from pipelex.cogt.inference.error_classify import InferenceErrorFamily, classify_inference_error+from pipelex.cogt.inference.error_render import render_inference_errorfrom pipelex.cogt.model_backends.model_spec import InferenceModelSpecfrom pipelex.cogt.search.search_depth import SearchDepthfrom pipelex.cogt.search.search_job import SearchJob@@ -80,7 +80,7 @@ class LinkupSearchWorker(SearchWorkerAbstract):LinkupUnknownError,) as sdk_exc:metadata = extract_linkup_metadata(sdk_exc)- classification = classify_inference_error(metadata)+ classification = classify_inference_error(metadata, family=InferenceErrorFamily.SEARCH)raise render_inference_error(metadata=metadata,classification=classification,@@ -152,7 +152,7 @@ class LinkupSearchWorker(SearchWorkerAbstract):LinkupUnknownError,) as sdk_exc:metadata = extract_linkup_metadata(sdk_exc)- classification = classify_inference_error(metadata)+ classification = classify_inference_error(metadata, family=InferenceErrorFamily.SEARCH)raise render_inference_error(metadata=metadata,classification=classification,diff --git a/pipelex/providers/mistral/mistral_exceptions.py b/pipelex/providers/mistral/mistral_exceptions.pyindex 9228acb1b..90b800a83 100644--- a/pipelex/providers/mistral/mistral_exceptions.py+++ b/pipelex/providers/mistral/mistral_exceptions.py@@ -1,17 +1,31 @@+from typing import ClassVar++from mthds.protocol.problem.registry import CoreCode+from pipelex.cogt.exceptions import CogtError+from pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeDeclaration+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodeclass MistralPluginError(CogtError):- pass+ """Base for the Mistral plugin's own errors, never raised directly."""++ error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERRORclass MistralModelListingError(MistralPluginError):- pass+ """Mistral's model listing answered with no models, which only the model listing command reads."""++ error_code = CoreCode.PROVIDER_RESPONSE_INVALIDclass MistralWorkerConfigurationError(MistralPluginError):- pass+ """A model spec missing a setting Mistral requires, such as its ``max_tokens``."""++ error_code = PipelexErrorCode.CONFIG_INVALIDclass MistralExtractResponseError(MistralPluginError):- pass+ """A Mistral OCR answer that cannot be used, such as an image without its base64 data."""++ error_code = CoreCode.PROVIDER_RESPONSE_INVALIDdiff --git a/pipelex/providers/mistral/mistral_extract_worker.py b/pipelex/providers/mistral/mistral_extract_worker.pyindex de1bc622b..e56029641 100644--- a/pipelex/providers/mistral/mistral_extract_worker.py+++ b/pipelex/providers/mistral/mistral_extract_worker.py@@ -13,8 +13,8 @@ from pipelex.cogt.extract.extract_job_components import ExtractJobParamsfrom pipelex.cogt.extract.extract_output import ExtractOutputfrom pipelex.cogt.extract.extract_worker_abstract import ExtractWorkerAbstractfrom pipelex.cogt.inference.error_classification import extract_mistral_metadata-from pipelex.cogt.inference.error_classify import classify_inference_error-from pipelex.cogt.inference.error_render import InferenceErrorFamily, render_inference_error+from pipelex.cogt.inference.error_classify import InferenceErrorFamily, classify_inference_error+from pipelex.cogt.inference.error_render import render_inference_errorfrom pipelex.cogt.model_backends.model_spec import InferenceModelSpecfrom pipelex.providers.mistral.mistral_factory import MistralFactoryfrom pipelex.reporting.reporting_protocol import ReportingProtocol@@ -115,7 +115,7 @@ class MistralExtractWorker(ExtractWorkerAbstract):)except (MistralError, httpx.TransportError) as sdk_exc:metadata = extract_mistral_metadata(sdk_exc)- classification = classify_inference_error(metadata)+ classification = classify_inference_error(metadata, family=InferenceErrorFamily.EXTRACT)raise render_inference_error(metadata=metadata,classification=classification,diff --git a/pipelex/providers/mistral/mistral_llm_worker.py b/pipelex/providers/mistral/mistral_llm_worker.pyindex 29d99a89c..8ff95faa7 100644--- a/pipelex/providers/mistral/mistral_llm_worker.py+++ b/pipelex/providers/mistral/mistral_llm_worker.py@@ -6,6 +6,7 @@ from mistralai.client.errors import MistralErrorfrom mistralai.client.models import ReasoningEffort as MistralReasoningEffortfrom mistralai.client.models import TextChunk, ThinkChunkfrom mistralai.client.types import UNSET+from mthds.protocol.problem.registry import CoreCodefrom typing_extensions import overridefrom pipelex.cogt.exceptions import InferenceErrorCategory, LLMCapabilityError, LLMCompletionError, SdkTypeError@@ -15,8 +16,8 @@ from pipelex.cogt.inference.error_classification import (extract_mistral_metadata,extract_underlying_sdk_exception,)-from pipelex.cogt.inference.error_classify import classify_inference_error-from pipelex.cogt.inference.error_render import InferenceErrorFamily, render_inference_error+from pipelex.cogt.inference.error_classify import InferenceErrorFamily, classify_inference_error+from pipelex.cogt.inference.error_render import render_inference_errorfrom pipelex.cogt.llm.instructor_retry import make_instructor_schema_retryingfrom pipelex.cogt.llm.llm_job import LLMJobfrom pipelex.cogt.llm.llm_job_components import LLMJobParams@@ -157,7 +158,7 @@ class MistralLLMWorker(LLMWorkerAbstract):)except (MistralError, httpx.TransportError) as sdk_exc:metadata = extract_mistral_metadata(sdk_exc)- classification = classify_inference_error(metadata)+ classification = classify_inference_error(metadata, family=InferenceErrorFamily.LLM)raise render_inference_error(metadata=metadata,classification=classification,@@ -176,7 +177,7 @@ class MistralLLMWorker(LLMWorkerAbstract):kind=UserActionKind.WAIT_AND_RETRY,detail="Mistral returned an empty response — wait a moment, then run it again",),- )+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)if not response.choices:msg = "Mistral response.choices is None"raise LLMCompletionError(@@ -187,7 +188,7 @@ class MistralLLMWorker(LLMWorkerAbstract):kind=UserActionKind.WAIT_AND_RETRY,detail="Mistral returned a response with no choices — wait a moment, then run it again",),- )+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)message = response.choices[0].messageif message is None:msg = "Mistral response.choices[0].message is None"@@ -199,7 +200,7 @@ class MistralLLMWorker(LLMWorkerAbstract):kind=UserActionKind.WAIT_AND_RETRY,detail="Mistral returned a choice with no message — wait a moment, then run it again",),- )+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)if (llm_tokens_usage := llm_job.job_report.llm_tokens_usage) and (usage := response.usage):llm_tokens_usage.nb_tokens_by_category = self.mistral_factory.make_nb_tokens_by_category(usage=usage)@@ -232,7 +233,7 @@ class MistralLLMWorker(LLMWorkerAbstract):kind=UserActionKind.CONTACT_SUPPORT,detail="Mistral returned an unrecognized content type — report this to Pipelex support",),- )+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)if not result_text:msg = "Mistral response text is empty"@@ -244,7 +245,7 @@ class MistralLLMWorker(LLMWorkerAbstract):kind=UserActionKind.CHANGE_INPUT,detail="Mistral returned an empty text response — try rephrasing the prompt or using a different model",),- )+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)return result_text@@ -284,7 +285,7 @@ class MistralLLMWorker(LLMWorkerAbstract):underlying_exc = extract_underlying_sdk_exception(instructor_exc=instructor_exc)if underlying_exc is not None:metadata = extract_mistral_metadata(underlying_exc)- classification = classify_inference_error(metadata)+ classification = classify_inference_error(metadata, family=InferenceErrorFamily.LLM)raise render_inference_error(metadata=metadata,classification=classification,@@ -300,10 +301,10 @@ class MistralLLMWorker(LLMWorkerAbstract):kind=UserActionKind.CONTACT_SUPPORT,detail="Structured generation failed for an unrecognized reason — retry, and report this if it persists",),- ) from instructor_exc+ ).with_error_code(CoreCode.RUNTIME_UNEXPECTED) from instructor_excexcept (MistralError, httpx.TransportError) as sdk_exc:metadata = extract_mistral_metadata(sdk_exc)- classification = classify_inference_error(metadata)+ classification = classify_inference_error(metadata, family=InferenceErrorFamily.LLM)raise render_inference_error(metadata=metadata,classification=classification,diff --git a/pipelex/providers/openai/openai_completions_img_gen_worker.py b/pipelex/providers/openai/openai_completions_img_gen_worker.pyindex 31edb0e58..afd474430 100644--- a/pipelex/providers/openai/openai_completions_img_gen_worker.py+++ b/pipelex/providers/openai/openai_completions_img_gen_worker.py@@ -1,6 +1,7 @@from typing import TYPE_CHECKING, Any, castimport openai+from mthds.protocol.problem.registry import CoreCodefrom openai import (APIConnectionError,APIStatusError,@@ -13,10 +14,11 @@ from pipelex.cogt.image.prompt_image_utils import prep_prompt_imagesfrom pipelex.cogt.img_gen.img_gen_job import ImgGenJobfrom pipelex.cogt.img_gen.img_gen_worker_abstract import ImgGenWorkerAbstractfrom pipelex.cogt.inference.error_classification import UserAction, UserActionKind, extract_openai_metadata-from pipelex.cogt.inference.error_classify import classify_inference_error-from pipelex.cogt.inference.error_render import InferenceErrorFamily, render_inference_error+from pipelex.cogt.inference.error_classify import InferenceErrorFamily, classify_inference_error+from pipelex.cogt.inference.error_render import render_inference_errorfrom pipelex.cogt.inference.inference_constants import InferenceOutputTypefrom pipelex.cogt.model_backends.model_spec import InferenceModelSpec+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.providers.openai.openai_completions_factory import OpenAICompletionsFactoryfrom pipelex.reporting.reporting_protocol import ReportingProtocolfrom pipelex.tools.misc.base64_utils import extract_base64_str_from_base64_url_if_possible@@ -90,7 +92,7 @@ class OpenAICompletionsImgGenWorker(ImgGenWorkerAbstract):)except (APIStatusError, APIConnectionError) as sdk_exc:metadata = extract_openai_metadata(sdk_exc)- classification = classify_inference_error(metadata)+ classification = classify_inference_error(metadata, family=InferenceErrorFamily.IMG_GEN)raise render_inference_error(metadata=metadata,classification=classification,@@ -120,7 +122,7 @@ class OpenAICompletionsImgGenWorker(ImgGenWorkerAbstract):detail="The provider returned no image data — try rephrasing the prompt or using a different model",),provider_metadata=None,- )+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)base64_str, base64_extracted_mime_type = extractedelif (content := openai_message.content) and content.startswith("http"):# The response message is a URL, which only a service with a fixed output format answers with:@@ -130,7 +132,7 @@ class OpenAICompletionsImgGenWorker(ImgGenWorkerAbstract):f"The completions image response is a URL, but the worker for backend '{self.inference_model.backend_name}' "f"was built with no fixed output format, so the image's format cannot be known.")- raise ImgGenParameterError(msg)+ raise ImgGenParameterError(msg).with_error_code(PipelexErrorCode.CONFIG_INVALID)actual_url = openai_message.contentelif hasattr(openai_message, "content_blocks"):content_blocks = cast("list[dict[str, Any]]", openai_message.content_blocks) # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType]@@ -149,7 +151,7 @@ class OpenAICompletionsImgGenWorker(ImgGenWorkerAbstract):detail="The provider returned no image data — try rephrasing the prompt or using a different model",),provider_metadata=None,- )+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)base64_str, base64_extracted_mime_type = extractedbreakif not base64_str and not actual_url:@@ -162,7 +164,7 @@ class OpenAICompletionsImgGenWorker(ImgGenWorkerAbstract):detail="The provider returned no image — try rephrasing the prompt or using a different model",),provider_metadata=None,- )+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)if (img_gen_tokens_usage := img_gen_job.job_report.img_gen_tokens_usage) and (usage := response.usage):img_gen_tokens_usage.nb_tokens_by_category = self.openai_completions_factory.make_nb_tokens_by_category(usage=usage)@@ -221,7 +223,7 @@ class OpenAICompletionsImgGenWorker(ImgGenWorkerAbstract):)else:msg = f"Unexpected PreparedFile type: {type(prepped_image).__name__}"- raise ImgGenParameterError(msg)+ raise ImgGenParameterError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)return [{"role": "user", "content": user_contents}]@@ -233,6 +235,6 @@ class OpenAICompletionsImgGenWorker(ImgGenWorkerAbstract):nb_images: int,) -> list[GeneratedImageRawDetails]:if nb_images > 1:- msg = f"The image genration backend '{self.inference_model.desc}' can't generate multiple images at once: {nb_images}"- raise NotImplementedError(msg)+ msg = f"The image generation backend '{self.inference_model.desc}' cannot generate several images at once, and {nb_images} were requested"+ raise ImgGenParameterError(msg)return [await self._gen_image(img_gen_job=img_gen_job)]diff --git a/pipelex/providers/openai/openai_completions_llm_worker.py b/pipelex/providers/openai/openai_completions_llm_worker.pyindex a206fec3a..787fa80b2 100644--- a/pipelex/providers/openai/openai_completions_llm_worker.py+++ b/pipelex/providers/openai/openai_completions_llm_worker.py@@ -1,6 +1,7 @@from typing import TYPE_CHECKING, Anyimport openai+from mthds.protocol.problem.registry import CoreCodefrom openai import (NOT_GIVEN,omit,@@ -15,8 +16,8 @@ from pipelex.cogt.inference.error_classification import (extract_openai_metadata,extract_underlying_sdk_exception,)-from pipelex.cogt.inference.error_classify import classify_inference_error-from pipelex.cogt.inference.error_render import InferenceErrorFamily, render_inference_error+from pipelex.cogt.inference.error_classify import InferenceErrorFamily, classify_inference_error+from pipelex.cogt.inference.error_render import render_inference_errorfrom pipelex.cogt.llm.instructor_retry import make_instructor_schema_retryingfrom pipelex.cogt.llm.llm_job import LLMJobfrom pipelex.cogt.llm.llm_job_components import LLMJobParams@@ -155,7 +156,7 @@ class OpenAICompletionsLLMWorker(LLMWorkerAbstract):)except (openai.APIStatusError, openai.APIConnectionError) as sdk_exc:metadata = extract_openai_metadata(sdk_exc)- classification = classify_inference_error(metadata)+ classification = classify_inference_error(metadata, family=InferenceErrorFamily.LLM)raise render_inference_error(metadata=metadata,classification=classification,@@ -174,7 +175,7 @@ class OpenAICompletionsLLMWorker(LLMWorkerAbstract):kind=UserActionKind.CHANGE_INPUT,detail="OpenAI returned no completion choices — try rephrasing the prompt or using a different model",),- )+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)if (llm_tokens_usage := llm_job.job_report.llm_tokens_usage) and (usage := response.usage):llm_tokens_usage.nb_tokens_by_category = self.openai_completions_factory.make_nb_tokens_by_category(usage=usage)@@ -195,7 +196,7 @@ class OpenAICompletionsLLMWorker(LLMWorkerAbstract):kind=UserActionKind.CHANGE_INPUT,detail="OpenAI returned a response with no content — try rephrasing the prompt or using a different model",),- )+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)return response_text@@ -239,7 +240,7 @@ class OpenAICompletionsLLMWorker(LLMWorkerAbstract):underlying_exc = extract_underlying_sdk_exception(instructor_exc=instructor_exc)if underlying_exc is not None:metadata = extract_openai_metadata(underlying_exc)- classification = classify_inference_error(metadata)+ classification = classify_inference_error(metadata, family=InferenceErrorFamily.LLM)raise render_inference_error(metadata=metadata,classification=classification,@@ -251,10 +252,12 @@ class OpenAICompletionsLLMWorker(LLMWorkerAbstract):f"OpenAI structured generation via 'instructor' failed with model: {self.inference_model.desc} "f"trying to generate schema: {schema} with error: {instructor_exc}")- raise LLMCompletionError(msg, error_category=InferenceErrorCategory.UNKNOWN) from instructor_exc+ raise LLMCompletionError(msg, error_category=InferenceErrorCategory.UNKNOWN).with_error_code(+ CoreCode.RUNTIME_UNEXPECTED+ ) from instructor_excexcept (openai.APIStatusError, openai.APIConnectionError) as sdk_exc:metadata = extract_openai_metadata(sdk_exc)- classification = classify_inference_error(metadata)+ classification = classify_inference_error(metadata, family=InferenceErrorFamily.LLM)raise render_inference_error(metadata=metadata,classification=classification,diff --git a/pipelex/providers/openai/openai_exceptions.py b/pipelex/providers/openai/openai_exceptions.pyindex 90a478350..07de949cd 100644--- a/pipelex/providers/openai/openai_exceptions.py+++ b/pipelex/providers/openai/openai_exceptions.py@@ -1,14 +1,21 @@from pipelex.cogt.exceptions import CogtError+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.system.exceptions import CredentialsErrorclass OpenAIClientFactoryError(CogtError):- _declared_title = "OpenAI client factory error"+ """An OpenAI client the backend's settings cannot build: an SDK handle it does not support, or no Azure endpoint."""++ error_code = PipelexErrorCode.CONFIG_INVALIDclass VertexAIConfigError(CogtError):- _declared_title = "VertexAI configuration error"+ """A Vertex AI backend whose settings are missing or wrong, refused when the backends load."""++ error_code = PipelexErrorCode.CONFIG_INVALIDclass VertexAICredentialsError(CredentialsError):- _declared_title = "VertexAI credentials error"+ """Vertex AI credentials this process cannot read: no credentials file, or a token that is not a string."""++ error_code = PipelexErrorCode.CONFIG_CREDENTIAL_MISSINGdiff --git a/pipelex/providers/openai/openai_img_gen_worker.py b/pipelex/providers/openai/openai_img_gen_worker.pyindex cac564576..2b91c143d 100644--- a/pipelex/providers/openai/openai_img_gen_worker.py+++ b/pipelex/providers/openai/openai_img_gen_worker.py@@ -2,6 +2,7 @@ import base64from typing import TYPE_CHECKING, Any, castimport openai+from mthds.protocol.problem.registry import CoreCodefrom openai import (APIConnectionError,APIStatusError,@@ -16,11 +17,13 @@ from pipelex.cogt.img_gen.img_gen_args_factory import ImgGenArgsFactoryfrom pipelex.cogt.img_gen.img_gen_job import ImgGenJobfrom pipelex.cogt.img_gen.img_gen_worker_abstract import ImgGenWorkerAbstractfrom pipelex.cogt.inference.error_classification import UserAction, UserActionKind, extract_openai_metadata-from pipelex.cogt.inference.error_classify import classify_inference_error-from pipelex.cogt.inference.error_render import InferenceErrorFamily, render_inference_error+from pipelex.cogt.inference.error_classify import InferenceErrorFamily, classify_inference_error+from pipelex.cogt.inference.error_render import render_inference_errorfrom pipelex.cogt.model_backends.model_spec import InferenceModelSpecfrom pipelex.cogt.usage.token_category import NbTokensByCategoryDict, TokenCategory+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.reporting.reporting_protocol import ReportingProtocol+from pipelex.tools.misc.exceptions import FileTypeError, UnsupportedImageMimeTypeErrorfrom pipelex.tools.misc.filetype_utils import detect_file_type_from_bytesfrom pipelex.tools.misc.image_utils import ImageFormat@@ -60,7 +63,7 @@ class OpenAIImgGenWorker(ImgGenWorkerAbstract):) -> list[GeneratedImageRawDetails]:if self.inference_model.rules is None:msg = f"Model '{self.inference_model.name}' does not have rules configured"- raise ImgGenParameterError(msg, error_category=InferenceErrorCategory.CONFIGURATION)+ raise ImgGenParameterError(msg, error_category=InferenceErrorCategory.CONFIGURATION).with_error_code(PipelexErrorCode.CONFIG_INVALID)args_dict = await ImgGenArgsFactory.make_args_for_model(model_rules=self.inference_model.rules,@@ -82,7 +85,7 @@ class OpenAIImgGenWorker(ImgGenWorkerAbstract):images_response = cast("ImagesResponse", await self.openai_client.images.generate(**args_dict))except (APIStatusError, APIConnectionError) as sdk_exc:metadata = extract_openai_metadata(sdk_exc)- classification = classify_inference_error(metadata)+ classification = classify_inference_error(metadata, family=InferenceErrorFamily.IMG_GEN)raise render_inference_error(metadata=metadata,classification=classification,@@ -101,7 +104,7 @@ class OpenAIImgGenWorker(ImgGenWorkerAbstract):detail="OpenAI returned no image — try rephrasing the prompt or using a different model",),provider_metadata=None,- )+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)response_output_format: str | None = images_response.output_formatsize: str | None = images_response.size or self._get_requested_size(args_dict=args_dict)@@ -115,7 +118,7 @@ class OpenAIImgGenWorker(ImgGenWorkerAbstract):detail="OpenAI returned an image without size metadata — try a different model",),provider_metadata=None,- )+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)size_split = size.split("x")if len(size_split) != 2:msg = f"Size from OpenAI is not a valid size: '{size}'"@@ -127,7 +130,7 @@ class OpenAIImgGenWorker(ImgGenWorkerAbstract):detail="OpenAI returned a malformed image size — try a different model",),provider_metadata=None,- )+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)width_str, height_str = size_splitwidth = int(width_str)height = int(height_str)@@ -143,7 +146,7 @@ class OpenAIImgGenWorker(ImgGenWorkerAbstract):detail="OpenAI returned an image without usage metadata — try a different model",),provider_metadata=None,- )+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)if img_gen_tokens_usage := img_gen_job.job_report.img_gen_tokens_usage:nb_tokens: NbTokensByCategoryDict = {@@ -165,13 +168,18 @@ class OpenAIImgGenWorker(ImgGenWorkerAbstract):detail="OpenAI returned no image data — try rephrasing the prompt or using a different model",),provider_metadata=None,- )+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)image_format = response_output_formatif image_format is None:image_bytes = base64.b64decode(base64_str)- file_type = detect_file_type_from_bytes(image_bytes)- image_format = ImageFormat.from_mime_type(mime_type=file_type.mime).value+ try:+ file_type = detect_file_type_from_bytes(image_bytes)+ image_format = ImageFormat.from_mime_type(mime_type=file_type.mime).value+ except (FileTypeError, UnsupportedImageMimeTypeError) as exc:+ # The bytes are the provider's answer, not an input of the caller's.+ exc.with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)+ raisegenerated_images.append(GeneratedImageRawDetails(diff --git a/pipelex/providers/openai/openai_responses_llm_worker.py b/pipelex/providers/openai/openai_responses_llm_worker.pyindex 812d12991..8203af61e 100644--- a/pipelex/providers/openai/openai_responses_llm_worker.py+++ b/pipelex/providers/openai/openai_responses_llm_worker.py@@ -3,6 +3,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, Any, castimport openai+from mthds.protocol.problem.registry import CoreCodefrom openai import (NOT_GIVEN,omit,@@ -22,14 +23,15 @@ from pipelex.cogt.inference.error_classification import (extract_openai_metadata,extract_underlying_sdk_exception,)-from pipelex.cogt.inference.error_classify import classify_inference_error-from pipelex.cogt.inference.error_render import InferenceErrorFamily, render_inference_error+from pipelex.cogt.inference.error_classify import InferenceErrorFamily, classify_inference_error+from pipelex.cogt.inference.error_render import render_inference_errorfrom pipelex.cogt.llm.completion_stop import classify_responses_stopfrom pipelex.cogt.llm.instructor_retry import make_instructor_schema_retryingfrom pipelex.cogt.llm.llm_utils import dump_error, dump_kwargs, dump_response_from_structured_genfrom pipelex.cogt.llm.llm_worker_abstract import LLMWorkerAbstractfrom pipelex.cogt.llm.thinking_mode import ThinkingModefrom pipelex.config import get_config+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.system.telemetry.otel_constants import InferenceOutputTypeif TYPE_CHECKING:@@ -164,7 +166,7 @@ class OpenAIResponsesLLMWorker(LLMWorkerAbstract):)except (openai.APIStatusError, openai.APIConnectionError) as sdk_exc:metadata = extract_openai_metadata(sdk_exc)- classification = classify_inference_error(metadata)+ classification = classify_inference_error(metadata, family=InferenceErrorFamily.LLM)raise render_inference_error(metadata=metadata,classification=classification,@@ -196,7 +198,7 @@ class OpenAIResponsesLLMWorker(LLMWorkerAbstract):kind=UserActionKind.CHANGE_INPUT,detail="OpenAI Responses API returned no text — try rephrasing the prompt or using a different model",),- )+ ).with_error_code(CoreCode.PROVIDER_RESPONSE_INVALID)return response.output_text@@ -225,7 +227,7 @@ class OpenAIResponsesLLMWorker(LLMWorkerAbstract):" — set a responses-capable structure_method or switch to a model that supports it"),),- )+ ).with_error_code(PipelexErrorCode.CONFIG_INVALID)extra_headers, extra_body = self.openai_responses_factory.make_extras(inference_model=self.inference_model, inference_job=llm_job, output_desc=schema.__name__)@@ -257,7 +259,7 @@ class OpenAIResponsesLLMWorker(LLMWorkerAbstract):underlying_exc = extract_underlying_sdk_exception(instructor_exc=instructor_exc)if underlying_exc is not None:metadata = extract_openai_metadata(underlying_exc)- classification = classify_inference_error(metadata)+ classification = classify_inference_error(metadata, family=InferenceErrorFamily.LLM)raise render_inference_error(metadata=metadata,classification=classification,@@ -269,10 +271,12 @@ class OpenAIResponsesLLMWorker(LLMWorkerAbstract):f"OpenAI structured generation via 'instructor' failed with model: {self.inference_model.desc} "f"trying to generate schema: {schema} with error: {instructor_exc}")- raise LLMCompletionError(msg, error_category=InferenceErrorCategory.UNKNOWN) from instructor_exc+ raise LLMCompletionError(msg, error_category=InferenceErrorCategory.UNKNOWN).with_error_code(+ CoreCode.RUNTIME_UNEXPECTED+ ) from instructor_excexcept (openai.APIStatusError, openai.APIConnectionError) as sdk_exc:metadata = extract_openai_metadata(sdk_exc)- classification = classify_inference_error(metadata)+ classification = classify_inference_error(metadata, family=InferenceErrorFamily.LLM)raise render_inference_error(metadata=metadata,classification=classification,diff --git a/pipelex/providers/openai/vertexai_factory.py b/pipelex/providers/openai/vertexai_factory.pyindex 9d8d98a3c..056585031 100644--- a/pipelex/providers/openai/vertexai_factory.py+++ b/pipelex/providers/openai/vertexai_factory.py@@ -1,10 +1,13 @@+import jsonfrom enum import StrEnumfrom pathlib import Pathfrom typing import Any+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.providers.openai.openai_exceptions import VertexAIConfigError, VertexAICredentialsErrorfrom pipelex.system.configuration.config_model import ConfigModelfrom pipelex.system.exceptions import MissingDependencyError+from pipelex.tools.misc.exceptions import JsonTypeErrorfrom pipelex.tools.misc.json_utils import load_json_dict_from_pathfrom pipelex.tools.misc.placeholder import value_is_placeholder@@ -68,6 +71,13 @@ class VertexAIFactory(ConfigModel):except FileNotFoundError as exc:msg = f"Could not get VertexAI credentials from GCP credentials file: File not found: {gcp_credentials_file_path}"raise VertexAICredentialsError(msg) from exc+ except json.JSONDecodeError as exc:+ msg = f"Could not get VertexAI credentials from GCP credentials file: it is not valid JSON: {gcp_credentials_file_path}"+ raise VertexAIConfigError(msg) from exc+ except JsonTypeError as exc:+ # The deployment's credentials file holds JSON that is no object: its configuration, not a request's.+ exc.with_error_code(PipelexErrorCode.CONFIG_INVALID)+ raisecredentials = Credentials.from_service_account_info( # pyright: ignore[reportUnknownMemberType]credentials_dict,diff --git a/pipelex/providers/portkey/portkey_exceptions.py b/pipelex/providers/portkey/portkey_exceptions.pyindex a00816435..1e4bdba42 100644--- a/pipelex/providers/portkey/portkey_exceptions.py+++ b/pipelex/providers/portkey/portkey_exceptions.py@@ -1,13 +1,23 @@+from typing import ClassVar+from pipelex.cogt.exceptions import CogtError+from pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeDeclaration+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodeclass PortkeyError(CogtError):- pass+ """Base for the Portkey plugin's own errors, never raised directly."""++ error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERRORclass PortkeyFactoryError(PortkeyError):- pass+ """A Portkey client the backend's settings cannot build, such as for an SDK handle it does not support."""++ error_code = PipelexErrorCode.CONFIG_INVALIDclass PortkeyCredentialsError(PortkeyError):- pass+ """A Portkey backend with no API key configured."""++ error_code = PipelexErrorCode.CONFIG_CREDENTIAL_MISSINGdiff --git a/pipelex/providers/pypdfium2/pypdfium2_worker.py b/pipelex/providers/pypdfium2/pypdfium2_worker.pyindex e7954f1e6..a4538e2f7 100644--- a/pipelex/providers/pypdfium2/pypdfium2_worker.py+++ b/pipelex/providers/pypdfium2/pypdfium2_worker.py@@ -4,13 +4,14 @@ from typing import Anyfrom typing_extensions import overridefrom pipelex import log+from pipelex.cogt.exceptions import ExtractCapabilityErrorfrom pipelex.cogt.extract.exceptions import ExtractInputErrorfrom pipelex.cogt.extract.extract_job import ExtractJobfrom pipelex.cogt.extract.extract_output import ExtractOutput, Pagefrom pipelex.cogt.extract.extract_worker_abstract import ExtractWorkerAbstractfrom pipelex.cogt.inference.error_classification import extract_local_extract_metadata-from pipelex.cogt.inference.error_classify import classify_inference_error-from pipelex.cogt.inference.error_render import InferenceErrorFamily, render_inference_error+from pipelex.cogt.inference.error_classify import InferenceErrorFamily, classify_inference_error+from pipelex.cogt.inference.error_render import render_inference_errorfrom pipelex.cogt.inference.provider_name import ProviderNamefrom pipelex.cogt.model_backends.model_spec import InferenceModelSpecfrom pipelex.reporting.reporting_protocol import ReportingProtocol@@ -68,7 +69,7 @@ class Pypdfium2Worker(ExtractWorkerAbstract):) -> ExtractOutput:if extract_job.extract_input.image_uri:msg = "Pypdfium2 only extracts text from PDFs, not from images"- raise NotImplementedError(msg)+ raise ExtractCapabilityError(msg)pdf_uri = extract_job.extract_input.document_uriif not pdf_uri:@@ -92,7 +93,7 @@ class Pypdfium2Worker(ExtractWorkerAbstract):# The exceptions below are raised by pypdfium2_renderer for corrupt/invalid PDFs or file system issues.except (FileNotFoundError, ValueError, RuntimeError, OSError) as sdk_exc:metadata = extract_local_extract_metadata(sdk_exc, provider=ProviderName.PYPDFIUM2)- classification = classify_inference_error(metadata)+ classification = classify_inference_error(metadata, family=InferenceErrorFamily.EXTRACT)raise render_inference_error(metadata=metadata,classification=classification,diff --git a/pipelex/providers/reportlab/reportlab_pdf_renderer.py b/pipelex/providers/reportlab/reportlab_pdf_renderer.pyindex a496fa564..ad7390441 100644--- a/pipelex/providers/reportlab/reportlab_pdf_renderer.py+++ b/pipelex/providers/reportlab/reportlab_pdf_renderer.py@@ -55,6 +55,7 @@ from pipelex.cogt.doc_gen.layout_tree import ()from pipelex.cogt.doc_gen.render_job import RenderedDocument, RenderJob, RenderResourcesfrom pipelex.cogt.model_backends.model_spec import InferenceModelSpec+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.providers.reportlab.markdown_flowables import markdown_to_flowablesfrom pipelex.providers.reportlab.pdf_elements import (MUTED_COLOR,@@ -147,7 +148,7 @@ class ReportlabPdfWorker(DocGenWorkerAbstract):f"The PDF engine cannot print '{job.filename}': {where} does not fit on an A4 page, ""as part of it is taller than a page and cannot be split across pages.")- raise DocGenRenderError(msg).as_caller_fault() from exc+ raise DocGenRenderError(msg).with_error_code(PipelexErrorCode.DOCGEN_CONTENT_UNPRINTABLE).as_caller_fault() from excreturn _BuiltPass(data=buffer.getvalue(), page_count=doc_template.page)@@ -216,10 +217,10 @@ def _decode_image(*, url: str, data: bytes, position: str) -> _LoadedImage:width_px, height_px = pil_image.sizeexcept (OSError, ValueError, SyntaxError, PilImage.DecompressionBombError) as exc:msg = f"The PDF engine cannot print {position}: its file is not an image it reads, such as PNG, JPEG, GIF or WebP."- raise DocGenRenderError(msg).as_caller_fault() from exc+ raise DocGenRenderError(msg).with_error_code(PipelexErrorCode.DOCGEN_CONTENT_UNPRINTABLE).as_caller_fault() from excif width_px <= 0 or height_px <= 0:msg = f"The PDF engine cannot print {position}: the image is empty."- raise DocGenRenderError(msg).as_caller_fault()+ raise DocGenRenderError(msg).with_error_code(PipelexErrorCode.DOCGEN_CONTENT_UNPRINTABLE).as_caller_fault()return _LoadedImage(url=url, data=data, width_px=width_px, height_px=height_px)diff --git a/pipelex/providers/typesafe/typesafe_error_classification.py b/pipelex/providers/typesafe/typesafe_error_classification.pyindex c22e266f0..95c9e5c82 100644--- a/pipelex/providers/typesafe/typesafe_error_classification.py+++ b/pipelex/providers/typesafe/typesafe_error_classification.py@@ -13,6 +13,8 @@ ladder already reads correctly, ``401`` and ``429`` and the 5xx range — straigclassifier, which stays provider-blind."""+from mthds.protocol.problem.registry import CoreCode+from pipelex.cogt.exceptions import InferenceErrorCategoryfrom pipelex.cogt.inference.error_classification import (TYPESAFE_API_USAGE_ERROR_TYPE,@@ -22,7 +24,7 @@ from pipelex.cogt.inference.error_classification import (SDKErrorEnvelope,UserActionKind,)-from pipelex.cogt.inference.error_classify import ClassificationResult, classify_inference_error+from pipelex.cogt.inference.error_classify import ClassificationResult, InferenceErrorFamily, classify_inference_error# What an ``api_usage_error`` says when the model name is the thing that was wrong. The only shape# of that code seen against the live API, and the one worth naming a verdict for.@@ -33,13 +35,14 @@ def classify_typesafe_error(metadata: SDKErrorEnvelope) -> ClassificationResult:"""Classify a TypeSafe failure, reading the body's ``error_type`` before the status ladder."""match metadata.provider_error_code:case None:- return classify_inference_error(metadata)+ return classify_inference_error(metadata, family=InferenceErrorFamily.JUDGMENT)case code if code == TYPESAFE_AUTHENTICATION_ERROR_TYPE:# Observed on a 401, where the ladder agrees. Named anyway because the code is the# contract and the status is not: this API answers 400 for everything else it refuses.return ClassificationResult(category=InferenceErrorCategory.CONFIGURATION,user_action_kind=UserActionKind.CHECK_CREDENTIALS,+ error_code=CoreCode.PROVIDER_CREDENTIAL_REFUSED,)case code if code == TYPESAFE_MAX_TOKENS_EXCEEDED_ERROR_TYPE:# The state plus the longest question went over the context limit. The caller's@@ -47,6 +50,7 @@ def classify_typesafe_error(metadata: SDKErrorEnvelope) -> ClassificationResult:return ClassificationResult(category=InferenceErrorCategory.CONTENT,user_action_kind=UserActionKind.CHANGE_INPUT,+ error_code=CoreCode.MODEL_CONTEXT_EXCEEDED,)case code if code == TYPESAFE_API_USAGE_ERROR_TYPE:if _UNKNOWN_MODEL_MARKER in metadata.message.lower():@@ -55,6 +59,7 @@ def classify_typesafe_error(metadata: SDKErrorEnvelope) -> ClassificationResult:return ClassificationResult(category=InferenceErrorCategory.CONFIGURATION,user_action_kind=UserActionKind.CHANGE_MODEL,+ error_code=CoreCode.MODEL_UNAVAILABLE,is_model_not_found=True,)# Some other misuse of the API. It is still not the caller's content — which is all the@@ -62,6 +67,7 @@ def classify_typesafe_error(metadata: SDKErrorEnvelope) -> ClassificationResult:return ClassificationResult(category=InferenceErrorCategory.CONFIGURATION,user_action_kind=UserActionKind.CONTACT_SUPPORT,+ error_code=CoreCode.RUNTIME_UNEXPECTED,)case code if code == TYPESAFE_MALFORMED_REQUEST_CODE:# A bare-sentence ``detail``: the question itself was illegal — no instructions and no@@ -71,6 +77,7 @@ def classify_typesafe_error(metadata: SDKErrorEnvelope) -> ClassificationResult:return ClassificationResult(category=InferenceErrorCategory.CONFIGURATION,user_action_kind=UserActionKind.CONTACT_SUPPORT,+ error_code=CoreCode.RUNTIME_UNEXPECTED,)case _:- return classify_inference_error(metadata)+ return classify_inference_error(metadata, family=InferenceErrorFamily.JUDGMENT)diff --git a/pipelex/providers/typesafe/typesafe_exceptions.py b/pipelex/providers/typesafe/typesafe_exceptions.pyindex 4e2b8a035..76cdaa749 100644--- a/pipelex/providers/typesafe/typesafe_exceptions.py+++ b/pipelex/providers/typesafe/typesafe_exceptions.py@@ -1,8 +1,19 @@+from typing import ClassVar++from mthds.protocol.problem.registry import CoreCode+from pipelex.cogt.exceptions import CogtError+from pipelex.errors.error_code_declaration import ErrorCodeDeclaration, ErrorCodeSet+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodeclass TypesafeError(CogtError):- """Base for every error this backend raises, so callers can catch the provider as a family."""+ """Base for every error this backend raises, so callers can catch the provider as a family.++ Raised itself for a backend with no API key, which is the deployment's missing credential.+ """++ error_code: ClassVar[ErrorCodeDeclaration] = PipelexErrorCode.CONFIG_CREDENTIAL_MISSINGclass TypesafeJudgmentResponseError(TypesafeError):@@ -15,11 +26,17 @@ class TypesafeJudgmentResponseError(TypesafeError):something — so this is where the wrong shape actually stops."""+ error_code = CoreCode.PROVIDER_RESPONSE_INVALID+class TypesafeQuestionUnsupportedError(TypesafeError):"""The question is legal MTHDS that this backend will not serve.The vendor's own bounds, not the language's: a rating scale longer than this backend answers.Enforcing it here rather than in the blueprint is deliberate — a method that exceeds it stays- valid and a different judgment backend may well accept it.+ valid and a different judgment backend may well accept it. The scale is written in the method, so it is+ ``model.capability_unsupported``; a rating level with neither a label nor a description, which the blueprint+ already refuses, is ``runtime.unexpected``, which its raise site chooses."""++ error_code = ErrorCodeSet(default=CoreCode.MODEL_CAPABILITY_UNSUPPORTED, others=(CoreCode.RUNTIME_UNEXPECTED,))diff --git a/pipelex/providers/typesafe/typesafe_judgment_worker.py b/pipelex/providers/typesafe/typesafe_judgment_worker.pyindex cb715b366..7adfae53e 100644--- a/pipelex/providers/typesafe/typesafe_judgment_worker.py+++ b/pipelex/providers/typesafe/typesafe_judgment_worker.py@@ -4,12 +4,14 @@ from typing_extensions import overridefrom pipelex import logfrom pipelex.cogt.exceptions import JudgmentCapabilityErrorfrom pipelex.cogt.inference.error_classification import extract_typesafe_metadata-from pipelex.cogt.inference.error_render import InferenceErrorFamily, render_inference_error+from pipelex.cogt.inference.error_classify import InferenceErrorFamily+from pipelex.cogt.inference.error_render import render_inference_errorfrom pipelex.cogt.judgment.judgment_job import JudgmentJobfrom pipelex.cogt.judgment.judgment_models import JudgmentOutcomefrom pipelex.cogt.judgment.judgment_worker_abstract import JudgmentWorkerAbstractfrom pipelex.cogt.model_backends.model_spec import InferenceModelSpecfrom pipelex.cogt.usage.token_category import NbTokensByCategoryDict, TokenCategory+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.providers.typesafe.typesafe_error_classification import classify_typesafe_errorfrom pipelex.providers.typesafe.typesafe_translation import from_typesafe_response, to_typesafe_questionsfrom pipelex.reporting.reporting_protocol import ReportingProtocol@@ -52,7 +54,7 @@ class TypesafeJudgmentWorker(JudgmentWorkerAbstract):f"TypeSafe judges text alone, and this judgment's prompt presents files for model '{self.inference_model.name}': ""its spec must not declare that it reads images or documents.")- raise JudgmentCapabilityError(msg)+ raise JudgmentCapabilityError(msg).with_error_code(PipelexErrorCode.CONFIG_INVALID)typesafe_questions = to_typesafe_questions(questions=judgment_job.questions)try:# The SDK types its state as a recursive JSON alias that pyright cannot resolve to the end.diff --git a/pipelex/providers/typesafe/typesafe_translation.py b/pipelex/providers/typesafe/typesafe_translation.pyindex 7c910d322..7ff87f5c1 100644--- a/pipelex/providers/typesafe/typesafe_translation.py+++ b/pipelex/providers/typesafe/typesafe_translation.py@@ -16,6 +16,7 @@ vendor's worker, so a second judgment backend is free to accept what this one wifrom typing import Any, assert_never+from mthds.protocol.problem.registry import CoreCodefrom typesafe_sdk import (Choice as TypesafeChoice,)@@ -125,7 +126,9 @@ def _score_criterion(*, level: RatingLevel) -> str:# `RatingLevel`'s own validator refuses a level carrying neither, so a validated level never reaches# this; it is stated for the type checker, which cannot see a validator.msg = "A rating level carries neither a label nor a description"- raise TypesafeQuestionUnsupportedError(msg, error_category=InferenceErrorCategory.CONTENT, provider_metadata=None)+ raise TypesafeQuestionUnsupportedError(msg, error_category=InferenceErrorCategory.CONTENT, provider_metadata=None).with_error_code(+ CoreCode.RUNTIME_UNEXPECTED+ )def from_typesafe_response(*, questions: dict[str, JudgmentQuestion], response: SystemOneResponse) -> dict[str, JudgmentAnswer]:diff --git a/pipelex/runtime_boot.py b/pipelex/runtime_boot.pyindex 731f2e718..8894a4da7 100644--- a/pipelex/runtime_boot.py+++ b/pipelex/runtime_boot.py@@ -43,6 +43,7 @@ from typing import TYPE_CHECKING, Any, Self, TypeVar, castfrom kajson.class_registry import ClassRegistryfrom kajson.class_registry_abstract import ClassRegistryAbstractfrom kajson.kajson_manager import KajsonManager+from mthds.protocol.problem.registry import CoreCodefrom pipelex import logfrom pipelex.base_exceptions import PipelexSetupError@@ -74,6 +75,7 @@ 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+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.graph.mermaidflow.template_set import MERMAID_TEMPLATE_SETfrom pipelex.graph.reactflow.template_set import REACTFLOW_TEMPLATE_SETfrom pipelex.observer.multi_observer import MultiObserver@@ -366,7 +368,7 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}."""if kwargs:msg = f"The base setup method does not support any additional arguments: {kwargs}"- raise PipelexSetupError(msg)+ raise PipelexSetupError(msg).with_error_code(CoreCode.RUNTIME_MISCONFIGURED)# --- Plugin discovery -----------------------------------------------------------------# Build the plugin registrar from the fully-resolved config (pure and import-light:@@ -519,16 +521,16 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.)except RoutingProfileLibraryNotFoundError as routing_not_found_exc:msg = self._get_config_file_not_found_error_msg(component=BootComponent.ROUTING_PROFILE_LIBRARY)- raise PipelexSetupError(msg) from routing_not_found_exc+ raise PipelexSetupError(msg).with_error_code(PipelexErrorCode.CONFIG_FILE_MISSING) from routing_not_found_excexcept InferenceBackendLibraryNotFoundError as backend_not_found_exc:msg = self._get_config_file_not_found_error_msg(component=BootComponent.INFERENCE_BACKEND_LIBRARY)- raise PipelexSetupError(msg) from backend_not_found_exc+ raise PipelexSetupError(msg).with_error_code(PipelexErrorCode.CONFIG_FILE_MISSING) from backend_not_found_excexcept ModelDeckNotFoundError as deck_not_found_exc:msg = self._get_config_file_not_found_error_msg(component=BootComponent.MODEL_DECK)- raise PipelexSetupError(msg) from deck_not_found_exc+ raise PipelexSetupError(msg).with_error_code(PipelexErrorCode.CONFIG_FILE_MISSING) from deck_not_found_excexcept RoutingProfileDisabledBackendError as routing_profile_exc:msg = f"Some backend(s) required for a routing profile is not enabled: {routing_profile_exc}"- raise PipelexSetupError(msg) from routing_profile_exc+ raise PipelexSetupError(msg).with_error_code(PipelexErrorCode.CONFIG_INVALID) from routing_profile_excexcept RoutingProfileLibraryError as routing_validation_exc:msg = self._get_validation_error_msg(component=BootComponent.ROUTING_PROFILE_LIBRARY, validation_exc=routing_validation_exc)raise PipelexSetupError(msg) from routing_validation_exc@@ -551,6 +553,8 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.# A person at either CLI can run on the hosted Pipelex API instead; a server's operator cannot.suggest_hosted_runs=integration_mode.is_pipelex_command_line,)+ # The credential error's own code says why it failed: a credential this process does not hold, a+ # placeholder no secrets provider reads, or a process booted without inference. The boot adds only its message.raise PipelexSetupError(error_msg) from credentials_exc# --- Plugin-derived registries --------------------------------------------------------@@ -977,7 +981,7 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.existing_boot = RuntimeBoot.get_optional_instance()if existing_boot is not None:msg = f"{type(existing_boot).__name__} is already initialized"- raise PipelexSetupError(msg)+ raise PipelexSetupError(msg).with_error_code(CoreCode.RUNTIME_MISCONFIGURED)@classmethoddef get_optional_instance(cls) -> Self | None:diff --git a/pipelex/runtime_bridge/direct_orchestrator.py b/pipelex/runtime_bridge/direct_orchestrator.pyindex 913bd44b0..180e33e0f 100644--- a/pipelex/runtime_bridge/direct_orchestrator.py+++ b/pipelex/runtime_bridge/direct_orchestrator.py@@ -10,6 +10,8 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING+from mthds.protocol.problem.registry import CoreCode+from pipelex.interpreter_hub import scoped_pipe_routerfrom pipelex.pipe_run.pipe_router import PipeRouterfrom pipelex.pipe_run.pipe_run import PipeRun@@ -57,4 +59,4 @@ class DirectOrchestrator:f"DIRECT orchestrator cannot fire-and-forget pipe '{pipe_job.pipe.code}': in-process execution has no genuine async path. ""Callers must check `supports_fire_and_forget` before dispatching a fire-and-forget job.")- raise PipelexBridgeDispatchError(msg)+ raise PipelexBridgeDispatchError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)diff --git a/pipelex/runtime_bridge/exceptions.py b/pipelex/runtime_bridge/exceptions.pyindex e25010e22..4ddc84e9a 100644--- a/pipelex/runtime_bridge/exceptions.py+++ b/pipelex/runtime_bridge/exceptions.py@@ -1,10 +1,18 @@+from typing import ClassVar++from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import PipelexError+from pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeDeclaration, ErrorCodeSet, InheritsCause+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.runtime_bridge.orchestration_mode import DIRECT_ORCHESTRATION_MODE, OrchestrationModeclass PipelexRuntimeBridgeError(PipelexError):"""Base for errors raised by the Pipelex runtime-bridge surface."""+ error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERROR+class MissingOrchestratorError(PipelexRuntimeBridgeError):"""Raised when no orchestrator is registered for a requested orchestration mode.@@ -18,12 +26,21 @@ class MissingOrchestratorError(PipelexRuntimeBridgeError):is a boot/discovery fault, not a missing plugin."""+ # A mode the deployment configured is its plugin's to install (`pipelex.plugin.not_found`, the default); a+ # mode the caller named and the policy allows is one this runtime does not offer (`runtime.unsupported`); a+ # plugin whose own dependency is absent is `pipelex.config.dependency_missing`. The raise site chooses.+ error_code = ErrorCodeSet(+ default=PipelexErrorCode.PLUGIN_NOT_FOUND,+ others=(CoreCode.RUNTIME_UNSUPPORTED, PipelexErrorCode.CONFIG_DEPENDENCY_MISSING, CoreCode.RUNTIME_UNEXPECTED),+ )+# The message is caller-actionable ("is its plugin installed?"); keep it under STRICT disclosure._authors_caller_facing_message = Truedef __init__(self, *, mode: OrchestrationMode):self.mode = modesuper().__init__(_build_missing_message(noun="orchestrator", mode=mode))+ _code_a_missing_direct_mode(error=self, mode=mode)class MissingBundleValidatorError(PipelexRuntimeBridgeError):@@ -35,12 +52,19 @@ class MissingBundleValidatorError(PipelexRuntimeBridgeError):the boot/discovery special case (its validator is core and always present)."""+ # Split as `MissingOrchestratorError`, by the mode's origin.+ error_code = ErrorCodeSet(+ default=PipelexErrorCode.PLUGIN_NOT_FOUND,+ others=(CoreCode.RUNTIME_UNSUPPORTED, PipelexErrorCode.CONFIG_DEPENDENCY_MISSING, CoreCode.RUNTIME_UNEXPECTED),+ )+# The message is caller-actionable ("is its plugin installed?"); keep it under STRICT disclosure._authors_caller_facing_message = Truedef __init__(self, *, mode: OrchestrationMode):self.mode = modesuper().__init__(_build_missing_message(noun="bundle validator", mode=mode))+ _code_a_missing_direct_mode(error=self, mode=mode)def _build_missing_message(*, noun: str, mode: OrchestrationMode) -> str:@@ -54,5 +78,22 @@ def _build_missing_message(*, noun: str, mode: OrchestrationMode) -> str:return f"No {noun} is registered for orchestration mode '{mode}'; is its plugin installed?"+def _code_a_missing_direct_mode(*, error: PipelexRuntimeBridgeError, mode: OrchestrationMode) -> None:+ """Choose `runtime.unexpected` for a miss on core's own `"direct"` mode, which is always registered.++ A plain string compare, as in `_build_missing_message`: the miss is a boot or discovery defect of ours,+ never a plugin the deployment forgot.+ """+ if mode == DIRECT_ORCHESTRATION_MODE:+ error.with_error_code(CoreCode.RUNTIME_UNEXPECTED)++class PipelexBridgeDispatchError(PipelexRuntimeBridgeError):- """Raised when a pipe dispatched through the bridge fails (validation or execution)."""+ """Raised when a pipe dispatched through the bridge fails (validation or execution).++ A carrier: it takes the code of the failure it wraps, and `runtime.unexpected` when that failure is not+ a coded error. A raise site with no cause chooses its own: `runtime.unsupported` for fire-and-forget asked+ of a blocking-only orchestrator, `request.invalid` for a host program's malformed dispatch.+ """++ error_code = InheritsCause(fallback=CoreCode.RUNTIME_UNEXPECTED, others=(CoreCode.RUNTIME_UNSUPPORTED, CoreCode.REQUEST_INVALID))diff --git a/pipelex/runtime_bridge/primitives/hydration.py b/pipelex/runtime_bridge/primitives/hydration.pyindex f197a9306..1f8c7d446 100644--- a/pipelex/runtime_bridge/primitives/hydration.py+++ b/pipelex/runtime_bridge/primitives/hydration.py@@ -10,7 +10,8 @@ from pipelex.core.concepts.exceptions import ConceptLibraryConceptNotFoundError,from pipelex.core.concepts.native.concept_native import NativeConceptCodefrom pipelex.core.memory.absence import AbsenceRecordfrom pipelex.core.memory.working_memory import WorkingMemory-from pipelex.core.qualified_ref import QualifiedRef, QualifiedRefError+from pipelex.core.qualified_ref import QualifiedRef+from pipelex.core.qualified_ref_exceptions import QualifiedRefErrorfrom pipelex.core.stuffs.composite_content import CompositeContentfrom pipelex.core.stuffs.list_content import ListContentfrom pipelex.core.stuffs.stuff import Stuffdiff --git a/pipelex/system/exceptions.py b/pipelex/system/exceptions.pyindex b36cba67e..c3013357d 100644--- a/pipelex/system/exceptions.py+++ b/pipelex/system/exceptions.py@@ -2,15 +2,23 @@ import loggingfrom enum import StrEnumfrom typing import ClassVar-from pipelex.base_exceptions import ErrorDomain, PipelexError, PipelexUnexpectedError+from mthds.protocol.problem.registry import CoreCode++from pipelex.base_exceptions import PipelexError, PipelexUnexpectedError+from pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeDeclaration+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodeclass ToolError(PipelexError):- _declared_title = "Tool error"+ """The base of the errors raised by Pipelex's own tools; never raised directly."""++ error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERRORclass JobMetadataError(PipelexUnexpectedError):- pass+ """A worker was called without the job metadata every call carries: a fault of ours."""++ error_code = CoreCode.RUNTIME_UNEXPECTEDclass InvocationPathError(PipelexUnexpectedError):@@ -20,22 +28,29 @@ class InvocationPathError(PipelexUnexpectedError):of the method."""- _declared_title = "Invocation path not derivable"+ error_code = CoreCode.RUNTIME_UNEXPECTEDclass NestedKeyConflictError(ToolError):- """Raised when attempting to create nested keys under a non-dict value."""+ """Raised when attempting to create nested keys under a non-dict value.++ Reached when a method's extra prompt parameters name a dotted key under a value that cannot hold one, so the+ method's prompt cannot be rendered.+ """++ error_code = CoreCode.PIPE_TEMPLATE_RENDER_FAILEDclass EnvVarNotFoundError(ToolError):- # A missing required env var is fixed by an operator setting it, not by the- # caller correcting input — the textbook CONFIG-domain failure.- error_domain = ErrorDomain.CONFIG- _declared_title = "Environment variable not set"+ """A required environment variable is not set: fixed by an operator setting it, not by the caller."""++ error_code = PipelexErrorCode.CONFIG_VARIABLE_MISSINGclass MissingDependencyError(PipelexError):- """Raised when a required dependency is not installed."""+ """Raised when a required dependency is not installed: an optional extra the operator installs."""++ error_code = PipelexErrorCode.CONFIG_DEPENDENCY_MISSINGdef __init__(self, dependency_name: str, extra_name: str, message: str | None = None):self.dependency_name = dependency_name@@ -48,7 +63,9 @@ class MissingDependencyError(PipelexError):class CredentialsError(PipelexError):- _declared_title = "Missing or invalid credentials"+ """The base of the errors about a missing or refused credential; never raised directly."""++ error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERRORclass TracebackMessageErrorMode(StrEnum):@@ -57,6 +74,9 @@ class TracebackMessageErrorMode(StrEnum):class TracebackMessageError(PipelexError):+ """A base whose constructor logs its message with the traceback; never raised directly."""++ error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERRORerror_mode: ClassVar[TracebackMessageErrorMode] = TracebackMessageErrorMode.EXCEPTIONdef __init__(self, message: str):@@ -71,8 +91,22 @@ class TracebackMessageError(PipelexError):class FatalError(TracebackMessageError):- _declared_title = "Fatal error"+ """The base of the errors that stop a process; never raised directly."""++ error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERRORclass ConfigValidationError(FatalError):- pass+ """A configuration value this process refuses: the operator's configuration."""++ error_code = PipelexErrorCode.CONFIG_INVALID+++class RunParameterError(PipelexError, ValueError):+ """A run parameter a host passes is not one the runtime accepts: a request id, run extras, a storage or read scope.++ Also a ``ValueError``: the same checks run inside pydantic validators, which turn only a ``ValueError`` into a+ validation error, and as plain calls at a host's entry point.+ """++ error_code = CoreCode.REQUEST_INVALIDdiff --git a/pipelex/system/job_metadata.py b/pipelex/system/job_metadata.pyindex 35fb93685..3214515ce 100644--- a/pipelex/system/job_metadata.py+++ b/pipelex/system/job_metadata.py@@ -6,6 +6,7 @@ from typing import Any, Selffrom pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator+from pipelex.system.exceptions import RunParameterErrorfrom pipelex.system.run_extras import validate_run_extrasfrom pipelex.system.storage_scope import validate_read_scope, validate_storage_scope, validate_storage_scope_within_read_scopefrom pipelex.system.telemetry.otel_context import OtelContext@@ -17,25 +18,25 @@ REQUEST_ID_PATTERN = re.compile(r"[\x20-\x7E]+")def validate_request_id(*, value: str) -> str:- """Return `value` if it is a usable inbound request id, else raise `ValueError`.+ """Return `value` if it is a usable inbound request id, else raise `RunParameterError`.The one statement of the constraint, which `RunMetadata` applies at construction and ahost entry point applies before it builds a run, so both refuse exactly the same values.Raises:- ValueError: the value is empty, longer than `REQUEST_ID_MAX_LENGTH`, or holds a+ RunParameterError: the value is empty, longer than `REQUEST_ID_MAX_LENGTH`, or holds acharacter outside printable ASCII."""if len(value) > REQUEST_ID_MAX_LENGTH:msg = f"Invalid request_id: it has {len(value)} characters, and at most {REQUEST_ID_MAX_LENGTH} are allowed."- raise ValueError(msg)+ raise RunParameterError(msg)# `fullmatch`, not `match` with a trailing `$`, which would admit one final newline.if not REQUEST_ID_PATTERN.fullmatch(value):msg = (f"Invalid request_id {value!r}: expected one or more printable ASCII characters. ""The value is quoted into log lines and error reports, so a control character in it would forge one.")- raise ValueError(msg)+ raise RunParameterError(msg)return valuediff --git a/pipelex/system/run_extras.py b/pipelex/system/run_extras.pyindex 676fd5bae..70e75ab97 100644--- a/pipelex/system/run_extras.py+++ b/pipelex/system/run_extras.py@@ -55,6 +55,8 @@ from __future__ import annotationsimport re+from pipelex.system.exceptions import RunParameterError+# An extras KEY: lowercase snake_case, starting with a letter.## Deliberately narrower than the value charset. The key is forwarded as a group@@ -86,7 +88,7 @@ RUN_EXTRAS_MAX_ENTRIES = 5def validate_run_extras(*, value: dict[str, str]) -> dict[str, str]:- """Return `value` if it is a usable run-extras mapping, else raise `ValueError`.+ """Return `value` if it is a usable run-extras mapping, else raise `RunParameterError`.Args:value: The host-supplied mapping of opaque key to opaque value. An empty@@ -98,7 +100,7 @@ def validate_run_extras(*, value: dict[str, str]) -> dict[str, str]:silently address a different entity.Raises:- ValueError: the mapping holds more than `RUN_EXTRAS_MAX_ENTRIES`+ RunParameterError: the mapping holds more than `RUN_EXTRAS_MAX_ENTRIES`entries, or a key or a value falls outside its charset — whichcovers the empty string, whitespace, control characters, andanything that could forge a line in a log or a capture payload.@@ -109,7 +111,7 @@ def validate_run_extras(*, value: dict[str, str]) -> dict[str, str]:"Each entry is forwarded as one group type a telemetry backend registers for the project, and that ""budget is small and fixed — an entry beyond it could not be honoured downstream.")- raise ValueError(msg)+ raise RunParameterError(msg)# `fullmatch`, NOT `match`. A trailing `$` in a `match` still admits one# final newline, which is how `storage_scope` once let a newline travel into@@ -122,12 +124,12 @@ def validate_run_extras(*, value: dict[str, str]) -> dict[str, str]:"at most 32 characters (e.g. 'organization'). A key is forwarded as a facet name registered with ""the telemetry backend, not tenant data.")- raise ValueError(msg)+ raise RunParameterError(msg)if not RUN_EXTRAS_VALUE_PATTERN.fullmatch(extras_value):msg = (f"Invalid extras value {extras_value!r} for key {extras_key!r}: expected 1 to 128 characters ""from [A-Za-z0-9_-] (e.g. 'org_acme'). The value is quoted into log lines and capture payloads, ""so whitespace, control characters and separators are refused.")- raise ValueError(msg)+ raise RunParameterError(msg)return valuediff --git a/pipelex/system/storage_scope.py b/pipelex/system/storage_scope.pyindex 10a234042..c5e27c372 100644--- a/pipelex/system/storage_scope.py+++ b/pipelex/system/storage_scope.py@@ -47,6 +47,8 @@ from __future__ import annotationsimport re+from pipelex.system.exceptions import RunParameterError+# One to three `[A-Za-z0-9_-]` segments joined by single slashes.## Applied with `fullmatch` (see below), it rejects in one rule: the empty string,@@ -137,10 +139,10 @@ GENERATED_CONTENT_LEAF = "generated"def validate_storage_scope(*, value: str) -> str:- """Return `value` if it is a usable storage scope, else raise `ValueError`.+ """Return `value` if it is a usable storage scope, else raise `RunParameterError`.Raises:- ValueError: the scope is empty, has more than three segments, or+ RunParameterError: the scope is empty, has more than three segments, orcontains a segment that is not `[A-Za-z0-9_-]+` — which coverstraversal (`..`), absolute paths, and empty segments."""@@ -157,19 +159,19 @@ def validate_storage_scope(*, value: str) -> str:"Empty segments, '.', '..' and leading or trailing slashes are refused — ""the value becomes a storage key prefix, so a traversal in it escapes the tenant.")- raise ValueError(msg)+ raise RunParameterError(msg)return valuedef validate_read_scope(*, value: str) -> str:- """Return `value` if it is a usable read scope, else raise `ValueError`.+ """Return `value` if it is a usable read scope, else raise `RunParameterError`.The same segment rule as the storage scope, which it must contain: one tothree `[A-Za-z0-9_-]+` segments joined by single slashes, applied with`fullmatch` for the reason `validate_storage_scope` gives.Raises:- ValueError: the scope is empty, has more than three segments, or+ RunParameterError: the scope is empty, has more than three segments, orcontains a segment that is not `[A-Za-z0-9_-]+`."""if not STORAGE_SCOPE_PATTERN.fullmatch(value):@@ -178,7 +180,7 @@ def validate_read_scope(*, value: str) -> str:"separated by single slashes (e.g. 'tenant'). Empty segments, '.', '..' and ""leading or trailing slashes are refused — the value bounds every storage key the run may read.")- raise ValueError(msg)+ raise RunParameterError(msg)return value@@ -204,7 +206,7 @@ def is_key_within_read_scope(*, key: str, read_scope: str) -> bool:def validate_storage_scope_within_read_scope(*, storage_scope: str, read_scope: str | None) -> None:- """Raise `ValueError` if a run could not read what it writes.+ """Raise `RunParameterError` if a run could not read what it writes.A run reads its own outputs back — a generated image shown to the nextmodel, a page view of its own extraction — so a storage scope outside the@@ -213,7 +215,7 @@ def validate_storage_scope_within_read_scope(*, storage_scope: str, read_scope:unscoped run (`read_scope` is `None`) reads everything and needs no check.Raises:- ValueError: the storage scope does not lie under the read scope.+ RunParameterError: the storage scope does not lie under the read scope."""if read_scope is None:return@@ -224,4 +226,4 @@ def validate_storage_scope_within_read_scope(*, storage_scope: str, read_scope:"The run's storage_scope does not lie under its read_scope: a run must be able to read ""what it writes. Pass a read_scope that is the storage_scope or one of its leading segments.")- raise ValueError(msg)+ raise RunParameterError(msg)diff --git a/pipelex/system/telemetry/exceptions.py b/pipelex/system/telemetry/exceptions.pyindex 4da145610..4c37b4633 100644--- a/pipelex/system/telemetry/exceptions.py+++ b/pipelex/system/telemetry/exceptions.py@@ -1,20 +1,34 @@+from typing import ClassVar+from pipelex.base_exceptions import PipelexConfigError, PipelexError+from pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeDeclaration+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodeclass TelemetryConfigError(PipelexConfigError):- """A telemetry configuration this process cannot use.+ """A telemetry configuration this process cannot use; never raised directly.- A :class:`PipelexConfigError` rather than a bare :class:`PipelexError`, and both halves of- that are load-bearing. It carries ``error_domain = CONFIG`` from the class instead of from the- agent CLI's lookup table, so the class is the single source of truth the drift test asks for;- and it can carry a :class:`MigrationErrorBlock`, which is what lets a stale ``telemetry.toml``- say *old* rather than *wrong* on every surface that reports it.+ A :class:`PipelexConfigError` rather than a bare :class:`PipelexError`, so that it can carry a+ :class:`MigrationErrorBlock`, which is what lets a stale ``telemetry.toml`` say *old* rather than *wrong*+ on every surface that reports it. Its subclasses carry a ``pipelex.config.*`` code, the operator's."""+ error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERROR+class TelemetryConfigValidationError(TelemetryConfigError):- pass+ """The telemetry configuration does not parse or does not validate."""++ error_code = PipelexErrorCode.CONFIG_INVALID+++class TelemetryApiKeyMissingError(TelemetryConfigError):+ """A telemetry destination is enabled without the API key it sends with: a variable the operator sets."""++ error_code = PipelexErrorCode.CONFIG_VARIABLE_MISSINGclass LangfuseCredentialsError(PipelexError):- pass+ """Langfuse telemetry is enabled without its keys: a variable the operator sets."""++ error_code = PipelexErrorCode.CONFIG_VARIABLE_MISSINGdiff --git a/pipelex/system/telemetry/telemetry_manager.py b/pipelex/system/telemetry/telemetry_manager.pyindex d49f37fa3..4d0a7044f 100644--- a/pipelex/system/telemetry/telemetry_manager.py+++ b/pipelex/system/telemetry/telemetry_manager.py@@ -9,13 +9,13 @@ from posthog.args import ExceptionArg, OptionalCaptureArgsfrom typing_extensions import Unpack, overridefrom pipelex import log-from pipelex.base_exceptions import PipelexUnexpectedErrorfrom pipelex.system.caller_identity import CallerIdentity, get_current_caller_identityfrom pipelex.system.environment import is_env_var_truthyfrom pipelex.system.exceptions import PipelexErrorfrom pipelex.system.runtime import IntegrationModefrom pipelex.system.telemetry.events import EventName, EventPropertyfrom pipelex.system.telemetry.exception_capture import ExceptionCapture+from pipelex.system.telemetry.exceptions import TelemetryApiKeyMissingErrorfrom pipelex.system.telemetry.otel_constants import OTelConstants, PostHogAttr, PostHogEventfrom pipelex.system.telemetry.otel_factory import OtelFactoryfrom pipelex.system.telemetry.telemetry_config import PostHogMode, TelemetryConfig, TelemetryRedactionConfig@@ -45,8 +45,8 @@ class TelemetryManager(TelemetryManagerAbstract):self.custom_posthog_client: Posthog | None = Noneif telemetry_config.custom_posthog.mode.is_enabled:if not telemetry_config.custom_posthog.api_key:- msg = "Custom PostHog API key is not set"- raise PipelexUnexpectedError(msg)+ msg = "Custom PostHog is enabled in the telemetry configuration, but its API key is not set"+ raise TelemetryApiKeyMissingError(msg)self.custom_posthog_client = Posthog(project_api_key=telemetry_config.custom_posthog.api_key,host=telemetry_config.custom_posthog.endpoint,diff --git a/pipelex/tools/aws/exceptions.py b/pipelex/tools/aws/exceptions.pyindex 534037070..c14ef3022 100644--- a/pipelex/tools/aws/exceptions.py+++ b/pipelex/tools/aws/exceptions.py@@ -1,5 +1,8 @@+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.system.exceptions import CredentialsErrorclass AwsCredentialsError(CredentialsError):- pass+ """Raised when the AWS credentials the configuration selects are not set."""++ error_code = PipelexErrorCode.CONFIG_CREDENTIAL_MISSINGdiff --git a/pipelex/tools/jinja2/exceptions.py b/pipelex/tools/jinja2/exceptions.pyindex ef63f80ad..f80afcb8c 100644--- a/pipelex/tools/jinja2/exceptions.py+++ b/pipelex/tools/jinja2/exceptions.py@@ -1,50 +1,112 @@-from pipelex.base_exceptions import ErrorDomain, SecurityError+from mthds.protocol.problem.registry import CoreCode++from pipelex.base_exceptions import SecurityError+from pipelex.errors.error_code_declaration import ErrorCodeSetfrom pipelex.system.exceptions import ToolError+from pipelex.tools.jinja2.template_owner import TemplateOwnerclass Jinja2TemplateSyntaxError(ToolError):- pass+ """A template Jinja2 cannot parse; the blueprint validators report it as the method's syntax."""++ error_code = CoreCode.METHOD_SYNTAXclass Jinja2TemplateRenderError(ToolError):- # Not classified as the caller's fault, although a run reaches it with the caller's own template:- # a failure of that template can come from the template (a reference or an expression its values- # never support, which validation's dry run also refuses) or from this run's data (a value that is- # absent or shaped otherwise this time), and nothing where it is raised tells the two apart. The- # same render also serves Pipelex's own templates, whose source a caller must not read.- pass+ """A template failed to render.++ The render serves the method's templates and Pipelex's own, and the raise site chooses the code by the template's+ owner (`TemplateOwner`). On a method's template the failure can come from the template or from this run's data+ (a value that is absent or shaped otherwise this time), and nothing where it is raised tells the two apart, so it+ is `pipe.template_render_failed`, the default; a filter's own finding about the template, such as a format it does+ not know, is `method.template_invalid`. On Pipelex's own template it is ours: `runtime.unexpected`, whose message+ never reaches a caller, since a caller must not read that template's source.+ """++ error_code = ErrorCodeSet(+ default=CoreCode.PIPE_TEMPLATE_RENDER_FAILED,+ others=(CoreCode.METHOD_TEMPLATE_INVALID, CoreCode.RUNTIME_UNEXPECTED),+ )+++class Jinja2TemplateInvalidError(Jinja2TemplateRenderError):+ """A template that cannot render as written, whatever the data.++ It names a filter or a test its environment does not define, or another construct Jinja2 refuses when it compiles+ the template, or, for a filter or test inside a branch, only when that branch renders. Found at render, it is+ still the template's fault: `method.template_invalid` on a method's template, the default, whose message names+ the construct Jinja2 refused and never quotes the template source; `runtime.unexpected` on Pipelex's own.+ """++ error_code = ErrorCodeSet(default=CoreCode.METHOD_TEMPLATE_INVALID, others=(CoreCode.RUNTIME_UNEXPECTED,))++ def __init__(self, message: str, *, fault: str, template_owner: TemplateOwner):+ super().__init__(message)+ # Jinja2's own finding, such as "No filter named 'frob' found.", which names the construct and never the+ # template source: the part of the message a pipe that knows the template's field quotes in its own.+ self.fault = fault+ # Whose template it is. A pipe rendering a method's template can reach one of Pipelex's own inside the same+ # render, such as the deployment's structure prompt beside a PipeLLM's prompt: it reports a refusal of its+ # template only for the method's, and lets Pipelex's own go on as ours.+ self.template_owner = template_ownerclass Jinja2TemplateSecurityError(SecurityError):- # A template reached for something the sandbox policy refuses (`jinja2_sandbox.py`): an undeclared- # private name, or a call that is not a method of a plain value. Its message names the attribute or- # the callable and the type it was reached on, and never quotes the template source, since the same- # render serves Pipelex's own templates. A `SecurityError`, not a `ToolError`, in the family of- # `UriReadRefusedError`, `SsrfBlockedError` and `UnsafeSchemaError`, so that a host catching that family- # never absorbs it into a domain answer and never retries it. A type of its own, apart from `Jinja2TemplateRenderError`,- # so that the classification of render-time template failures can tell a refusal from the rest,- # although for now both are classified alike: runtime domain, message not caller-facing.- pass+ """A template reached for something the sandbox policy refuses (`jinja2_sandbox.py`).++ That is an undeclared private name, or a call that is not a method of a plain value. Its message names the+ attribute or the callable and the type it was reached on, and never quotes the template source, since the same+ render serves Pipelex's own templates. On a method's template it is `security.template_refused`, the default; on+ Pipelex's own, our template tripping our sandbox is our bug, `runtime.unexpected`.++ A `SecurityError`, not a `ToolError`, in the family of `UriReadRefusedError`, `SsrfBlockedError` and+ `UnsafeSchemaError`, so that a host catching that family never absorbs it into a domain answer and never retries+ it. A type of its own, apart from `Jinja2TemplateRenderError`, so that the classification of render-time template+ failures tells a refusal from the rest.+ """++ error_code = ErrorCodeSet(default=CoreCode.SECURITY_TEMPLATE_REFUSED, others=(CoreCode.RUNTIME_UNEXPECTED,))class Jinja2TemplateBudgetError(ToolError):- # A render tried to spend more than its budget (`jinja2_render_budget.py`): its template repeated,- # padded, joined, looped or recursed past what one render may allocate or compute. The template is- # the caller's own, and a Pipelex template can only get there on data too large to display, which- # is still the caller's input, so it is the caller's to fix. The message names the operation and- # its size, never the template source or a value.- error_domain = ErrorDomain.INPUT+ """A render tried to spend more than its budget (`jinja2_render_budget.py`).++ Its template repeated, padded, joined, looped or recursed past what one render may allocate or compute. On a+ method's template that is the method's to fix, `pipe.template_budget_exceeded`, the default; a Pipelex template+ only gets there on data too large to display, which is the caller's input, `input.too_large`. The message names+ the operation and its size, never the template source or a value, so it is caller-facing either way.+ """++ error_code = ErrorCodeSet(default=CoreCode.PIPE_TEMPLATE_BUDGET_EXCEEDED, others=(CoreCode.INPUT_TOO_LARGE,))_authors_caller_facing_message = True- _declared_title = "Template render budget exceeded"class Jinja2StuffError(ToolError):- pass+ """A render context key is already taken, such as a method variable named like the reserved `tag_style`.++ A method naming a variable like a reserved key is `method.name_conflict`, the default; the same collision on a+ context Pipelex built for its own template is ours, `runtime.unexpected`.+ """++ error_code = ErrorCodeSet(default=CoreCode.METHOD_NAME_CONFLICT, others=(CoreCode.RUNTIME_UNEXPECTED,))class Jinja2ContextError(ToolError):- pass+ """A filter could not work with what the render context or the value gave it.++ A value the filter cannot take, such as an undefined one, is `pipe.template_render_failed`, the default; a format+ name the template wrote and the filter does not know is `method.template_invalid`; a render set up without the+ templating style or the image registry a filter needs is ours, `runtime.unexpected`. The render functions wrap it+ into `Jinja2TemplateRenderError`, which takes its code.+ """++ error_code = ErrorCodeSet(+ default=CoreCode.PIPE_TEMPLATE_RENDER_FAILED,+ others=(CoreCode.METHOD_TEMPLATE_INVALID, CoreCode.RUNTIME_UNEXPECTED),+ )class Jinja2DetectVariablesError(ToolError):- pass+ """A template whose variables cannot be read because it does not parse; its callers report the method's syntax."""++ error_code = CoreCode.METHOD_SYNTAXdiff --git a/pipelex/tools/jinja2/jinja2_filters.py b/pipelex/tools/jinja2/jinja2_filters.pyindex 04ff7c05a..f0a3c1167 100644--- a/pipelex/tools/jinja2/jinja2_filters.py+++ b/pipelex/tools/jinja2/jinja2_filters.py@@ -4,6 +4,7 @@ from typing import Anyfrom jinja2 import pass_contextfrom jinja2.runtime import Context, Undefinedfrom markupsafe import Markup+from mthds.protocol.problem.registry import CoreCodefrom pipelex.tools.jinja2.exceptions import Jinja2ContextErrorfrom pipelex.tools.jinja2.html_renderable import HtmlRenderable@@ -40,7 +41,7 @@ def require_templating_style_value(*, context: Context, jinja2_context_key: Jinj"The tag, format and with_images filters have no default to fall back on — the caller ""must resolve a templating style and pass it to the render call.")- raise Jinja2ContextError(msg)+ raise Jinja2ContextError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)return str(value)@@ -64,7 +65,7 @@ async def text_format(context: Context, value: Any, text_format: TextFormat | stnamed_text_format = TextFormat(text_format)except ValueError as exc:msg = f"Invalid text format: '{text_format}'"- raise Jinja2ContextError(msg) from exc+ raise Jinja2ContextError(msg).with_error_code(CoreCode.METHOD_TEMPLATE_INVALID) from excelse:named_text_format = Nonediff --git a/pipelex/tools/jinja2/jinja2_rendering.py b/pipelex/tools/jinja2/jinja2_rendering.pyindex cff7b9351..55502185f 100644--- a/pipelex/tools/jinja2/jinja2_rendering.py+++ b/pipelex/tools/jinja2/jinja2_rendering.py@@ -1,18 +1,24 @@from collections.abc import Awaitable, Callable-from typing import Any, Protocol+from typing import Any, Protocol, TypeVarfrom jinja2.exceptions import (+ FilterArgumentError,SecurityError,- TemplateAssertionError,+ TemplateError,TemplateNotFound,+ TemplateRuntimeError,TemplateSyntaxError,UndefinedError,)+from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import PipelexError, PipelexUnexpectedError+from pipelex.system.exceptions import ToolErrorfrom pipelex.tools.jinja2.exceptions import (Jinja2ContextError,Jinja2StuffError,Jinja2TemplateBudgetError,+ Jinja2TemplateInvalidError,Jinja2TemplateRenderError,Jinja2TemplateSecurityError,)@@ -23,13 +29,33 @@ from pipelex.tools.jinja2.jinja2_environment import (from pipelex.tools.jinja2.jinja2_models import Jinja2ContextKeyfrom pipelex.tools.jinja2.jinja2_render_budget import RenderBudgetExceededErrorfrom pipelex.tools.jinja2.template_category import TemplateCategory+from pipelex.tools.jinja2.template_owner import TemplateOwnerfrom pipelex.tools.templating.templating_style import TemplatingStyle+_TemplateError = TypeVar("_TemplateError", bound=PipelexError)-def _add_to_templating_context(templating_context: dict[str, Any], *, jinja2_context_key: Jinja2ContextKey, value: Any) -> None:++def _coded_by_owner(*, error: _TemplateError, template_owner: TemplateOwner) -> _TemplateError:+ """A failure of a template, coded by whose template it is.++ On a method's template the error keeps the code its raise site gave it, or its class's default; on Pipelex's own+ template the failure is ours, `runtime.unexpected`, whose message never reaches a caller, since a caller must not+ read that template's source. Every class it serves declares `runtime.unexpected` among its codes.+ """+ match template_owner:+ case TemplateOwner.METHOD:+ return error+ case TemplateOwner.PIPELEX:+ return error.with_error_code(CoreCode.RUNTIME_UNEXPECTED)+++def _add_to_templating_context(+ templating_context: dict[str, Any], *, jinja2_context_key: Jinja2ContextKey, value: Any, template_owner: TemplateOwner+) -> None:if jinja2_context_key in templating_context:+ # On a method's template, a method variable named like the reserved key: `method.name_conflict`, the default.msg = f"Jinja2 context key '{jinja2_context_key}' already in templating_context"- raise Jinja2StuffError(msg)+ raise _coded_by_owner(error=Jinja2StuffError(msg), template_owner=template_owner)templating_context[jinja2_context_key] = value@@ -43,6 +69,7 @@ def _compile_jinja2_template(template_source: str,*,template_category: TemplateCategory,+ template_owner: TemplateOwner,use_registry: bool = False,enable_async: bool = True,finalize: Callable[[Any], Any] | None = None,@@ -65,15 +92,17 @@ def _compile_jinja2_template(try:return jinja2_env.from_string(template_source)- except TemplateAssertionError as exc:- msg = f"Jinja2 render error: '{exc}', template_source:\n{template_source}"- raise Jinja2TemplateRenderError(msg) from exc+ except TemplateSyntaxError as exc:+ # A filter or test the environment does not define, outside any branch, is a `TemplateAssertionError`+ # that compiling finds; a method's template is only parsed at load, so this is where it surfaces.+ raise _make_invalid_template_error(template_error=exc, template_owner=template_owner) from excdef _prepare_templating_context(templating_context: dict[str, Any],*,templating_style: TemplatingStyle | None,+ template_owner: TemplateOwner,) -> dict[str, Any]:# Create a copy to avoid mutating the caller's original dictionaryprepared_templating_context = templating_context.copy()@@ -82,11 +111,13 @@ def _prepare_templating_context(templating_context=prepared_templating_context,jinja2_context_key=Jinja2ContextKey.TAG_STYLE,value=templating_style.tag_style,+ template_owner=template_owner,)_add_to_templating_context(templating_context=prepared_templating_context,jinja2_context_key=Jinja2ContextKey.TEXT_FORMAT,value=templating_style.text_format,+ template_owner=template_owner,)return prepared_templating_context@@ -120,78 +151,132 @@ def _make_non_type_error_msg(template_source: str,*,error_label: str,- error: Jinja2StuffError | TemplateSyntaxError | UndefinedError | TemplateNotFound | Jinja2ContextError | ArithmeticError,+ error: Jinja2StuffError | UndefinedError | Jinja2ContextError | FilterArgumentError | ArithmeticError,) -> str:return f"Jinja2 render — {error_label}: '{error}', template_source:\n{template_source}"-def _render_template_sync(template_source: str, *, template: _Jinja2Template, templating_context: dict[str, Any]) -> str:- try:- generated_text: str = template.render(**templating_context)- except SecurityError as exc:- raise Jinja2TemplateSecurityError(_make_security_error_msg(security_error=exc)) from exc- except RenderBudgetExceededError as exc:- raise Jinja2TemplateBudgetError(_make_budget_error_msg(budget_error=exc)) from exc- except RecursionError as exc:- raise Jinja2TemplateBudgetError(_RECURSION_MSG) from exc- except Jinja2StuffError as exc:- msg = _make_non_type_error_msg(template_source=template_source, error_label="stuff error", error=exc)- raise Jinja2TemplateRenderError(msg) from exc- except TemplateSyntaxError as exc:- msg = _make_non_type_error_msg(template_source=template_source, error_label="syntax error", error=exc)- raise Jinja2TemplateRenderError(msg) from exc- except UndefinedError as exc:- msg = _make_non_type_error_msg(template_source=template_source, error_label="undefined error", error=exc)- raise Jinja2TemplateRenderError(msg) from exc- except TemplateNotFound as exc:+def _make_invalid_template_error(*, template_error: TemplateError, template_owner: TemplateOwner) -> Jinja2TemplateInvalidError:+ """The error of a template that cannot render as written, coded by its owner.++ Its message gives Jinja2's own finding (`TemplateError.message`, which names the filter, test or template the+ template reached for), never the template source nor the line Jinja2 would quote with it, so on a method's+ template it reaches the caller under every disclosure mode.+ """+ if isinstance(template_error, TemplateNotFound):# A template without a loader (every method template) has nothing to include or extend.- msg = _make_non_type_error_msg(template_source=template_source, error_label="template not found", error=exc)- raise Jinja2TemplateRenderError(msg) from exc- except Jinja2ContextError as exc:- msg = _make_non_type_error_msg(template_source=template_source, error_label="context error", error=exc)- raise Jinja2TemplateRenderError(msg) from exc- except ArithmeticError as exc:+ fault = f"template not found: '{template_error.name}'."+ else:+ fault = template_error.message or type(template_error).__name__+ msg = f"Jinja2 render — the template cannot render as written: {fault}"+ invalid_error = _coded_by_owner(error=Jinja2TemplateInvalidError(msg, fault=fault, template_owner=template_owner), template_owner=template_owner)+ if template_owner.is_method:+ # The message names the construct Jinja2 refused and never the source, so the method's author reads it.+ invalid_error.as_caller_fault()+ return invalid_error+++def _make_data_render_error(*, msg: str, template_owner: TemplateOwner) -> Jinja2TemplateRenderError:+ """The error of a render that failed on this run's data or on the template, which nothing here tells apart."""+ return _coded_by_owner(error=Jinja2TemplateRenderError(msg), template_owner=template_owner)+++def _make_context_render_error(*, msg: str, context_error: Jinja2ContextError, template_owner: TemplateOwner) -> Jinja2TemplateRenderError:+ """The error of a render whose filter refused the context or the value: on a method's template, the filter's code."""+ render_error = Jinja2TemplateRenderError(msg)+ if context_error.own_error_code is not None:+ render_error.with_error_code(context_error.own_error_code)+ return _coded_by_owner(error=render_error, template_owner=template_owner)+++# What a render can raise, each translated by `_make_render_failure`. `SecurityError`, `UndefinedError` and+# `FilterArgumentError` are `TemplateRuntimeError`s, and `RenderBudgetExceededError` a `TemplateError`; they are named+# for the reader.+_RENDER_FAILURES: tuple[type[BaseException], ...] = (+ SecurityError,+ RenderBudgetExceededError,+ RecursionError,+ Jinja2StuffError,+ Jinja2ContextError,+ TemplateSyntaxError,+ UndefinedError,+ FilterArgumentError,+ TemplateNotFound,+ TemplateRuntimeError,+ ArithmeticError,+ TypeError,+)+++def _make_render_failure(+ *, template_source: str, render_error: BaseException, templating_context: dict[str, Any], template_owner: TemplateOwner+) -> ToolError | Jinja2TemplateSecurityError:+ """Translate what a render raised into the error the render reports, coded by the template's owner.++ The order of the arms matters: a refusal of the sandbox, an undefined value and a filter refusing its argument are+ `TemplateRuntimeError`s too, and only what is left of that family, the plain `TemplateRuntimeError` Jinja2 raises+ for the template's own constructs, such as a filter or a test inside a branch that the environment does not define,+ is the template's fault on any input.+ """+ if isinstance(render_error, SecurityError):+ security_msg = _make_security_error_msg(security_error=render_error)+ return _coded_by_owner(error=Jinja2TemplateSecurityError(security_msg), template_owner=template_owner)+ if isinstance(render_error, (RenderBudgetExceededError, RecursionError)):+ budget_msg = _make_budget_error_msg(budget_error=render_error) if isinstance(render_error, RenderBudgetExceededError) else _RECURSION_MSG+ match template_owner:+ case TemplateOwner.METHOD:+ return Jinja2TemplateBudgetError(budget_msg)+ case TemplateOwner.PIPELEX:+ # Pipelex's own template only overspends on data too large to display.+ return Jinja2TemplateBudgetError(budget_msg).with_error_code(CoreCode.INPUT_TOO_LARGE)+ if isinstance(render_error, Jinja2ContextError):+ msg = _make_non_type_error_msg(template_source=template_source, error_label="context error", error=render_error)+ return _make_context_render_error(msg=msg, context_error=render_error, template_owner=template_owner)+ if isinstance(render_error, Jinja2StuffError):+ msg = _make_non_type_error_msg(template_source=template_source, error_label="stuff error", error=render_error)+ return _make_data_render_error(msg=msg, template_owner=template_owner)+ if isinstance(render_error, UndefinedError):+ msg = _make_non_type_error_msg(template_source=template_source, error_label="undefined error", error=render_error)+ return _make_data_render_error(msg=msg, template_owner=template_owner)+ if isinstance(render_error, FilterArgumentError):+ # A filter refusing its argument may be refusing this run's value (`reverse` on a value that is not iterable)+ # as well as the template's own literal, which nothing here tells apart, so it is not the template's alone.+ msg = _make_non_type_error_msg(template_source=template_source, error_label="filter argument error", error=render_error)+ return _make_data_render_error(msg=msg, template_owner=template_owner)+ if isinstance(render_error, (TemplateSyntaxError, TemplateNotFound, TemplateRuntimeError)):+ return _make_invalid_template_error(template_error=render_error, template_owner=template_owner)+ if isinstance(render_error, ArithmeticError):# The template's own arithmetic, the sandbox's range cap included: `range` raises OverflowError past it.- msg = _make_non_type_error_msg(template_source=template_source, error_label="arithmetic error", error=exc)- raise Jinja2TemplateRenderError(msg) from exc- except TypeError as exc:- msg = _make_type_error_msg(template_source=template_source, templating_context=templating_context, type_error=exc)- raise Jinja2TemplateRenderError(msg) from exc+ msg = _make_non_type_error_msg(template_source=template_source, error_label="arithmetic error", error=render_error)+ return _make_data_render_error(msg=msg, template_owner=template_owner)+ if isinstance(render_error, TypeError):+ msg = _make_type_error_msg(template_source=template_source, templating_context=templating_context, type_error=render_error)+ return _make_data_render_error(msg=msg, template_owner=template_owner)+ msg = f"Jinja2 render — {type(render_error).__name__} is not a failure the render translates"+ raise PipelexUnexpectedError(msg) from render_error+++def _render_template_sync(+ template_source: str, *, template: _Jinja2Template, templating_context: dict[str, Any], template_owner: TemplateOwner+) -> str:+ try:+ generated_text: str = template.render(**templating_context)+ except _RENDER_FAILURES as exc:+ raise _make_render_failure(+ template_source=template_source, render_error=exc, templating_context=templating_context, template_owner=template_owner+ ) from excreturn generated_text-async def _render_template_async(template_source: str, *, template: _Jinja2Template, templating_context: dict[str, Any]) -> str:+async def _render_template_async(+ template_source: str, *, template: _Jinja2Template, templating_context: dict[str, Any], template_owner: TemplateOwner+) -> str:try:generated_text: str = await template.render_async(**templating_context)- except SecurityError as exc:- raise Jinja2TemplateSecurityError(_make_security_error_msg(security_error=exc)) from exc- except RenderBudgetExceededError as exc:- raise Jinja2TemplateBudgetError(_make_budget_error_msg(budget_error=exc)) from exc- except RecursionError as exc:- raise Jinja2TemplateBudgetError(_RECURSION_MSG) from exc- except Jinja2StuffError as exc:- msg = _make_non_type_error_msg(template_source=template_source, error_label="stuff error", error=exc)- raise Jinja2TemplateRenderError(msg) from exc- except TemplateSyntaxError as exc:- msg = _make_non_type_error_msg(template_source=template_source, error_label="syntax error", error=exc)- raise Jinja2TemplateRenderError(msg) from exc- except UndefinedError as exc:- msg = _make_non_type_error_msg(template_source=template_source, error_label="undefined error", error=exc)- raise Jinja2TemplateRenderError(msg) from exc- except TemplateNotFound as exc:- # A template without a loader (every method template) has nothing to include or extend.- msg = _make_non_type_error_msg(template_source=template_source, error_label="template not found", error=exc)- raise Jinja2TemplateRenderError(msg) from exc- except Jinja2ContextError as exc:- msg = _make_non_type_error_msg(template_source=template_source, error_label="context error", error=exc)- raise Jinja2TemplateRenderError(msg) from exc- except ArithmeticError as exc:- # The template's own arithmetic, the sandbox's range cap included: `range` raises OverflowError past it.- msg = _make_non_type_error_msg(template_source=template_source, error_label="arithmetic error", error=exc)- raise Jinja2TemplateRenderError(msg) from exc- except TypeError as exc:- msg = _make_type_error_msg(template_source=template_source, templating_context=templating_context, type_error=exc)- raise Jinja2TemplateRenderError(msg) from exc+ except _RENDER_FAILURES as exc:+ raise _make_render_failure(+ template_source=template_source, render_error=exc, templating_context=templating_context, template_owner=template_owner+ ) from excreturn generated_text@@ -202,21 +287,26 @@ def render_jinja2_sync(templating_context: dict[str, Any],templating_style: TemplatingStyle | None = None,use_registry: bool = False,+ template_owner: TemplateOwner = TemplateOwner.PIPELEX,) -> str:+ """Render a template; `template_owner` decides whose fault a failure is, Pipelex's own unless said otherwise."""template = _compile_jinja2_template(template_source=template_source,template_category=template_category,+ template_owner=template_owner,use_registry=use_registry,enable_async=False,)prepared_templating_context = _prepare_templating_context(templating_context=templating_context,templating_style=templating_style,+ template_owner=template_owner,)return _render_template_sync(template_source=template_source,template=template,templating_context=prepared_templating_context,+ template_owner=template_owner,)@@ -229,10 +319,16 @@ async def render_jinja2_async(use_registry: bool = False,finalize: Callable[[Any], Any] | None = None,is_undefined_strict: bool = False,+ template_owner: TemplateOwner = TemplateOwner.PIPELEX,) -> str:+ """Render a template; `template_owner` decides whose fault a failure is, Pipelex's own unless said otherwise.++ A method's template is rendered through `pipelex.cogt.templating.template_rendering.render_template`, which says so.+ """template = _compile_jinja2_template(template_source=template_source,template_category=template_category,+ template_owner=template_owner,use_registry=use_registry,finalize=finalize,is_undefined_strict=is_undefined_strict,@@ -240,9 +336,11 @@ async def render_jinja2_async(prepared_templating_context = _prepare_templating_context(templating_context=templating_context,templating_style=templating_style,+ template_owner=template_owner,)return await _render_template_async(template_source=template_source,template=template,templating_context=prepared_templating_context,+ template_owner=template_owner,)diff --git a/pipelex/tools/jinja2/jinja2_sandbox.py b/pipelex/tools/jinja2/jinja2_sandbox.pyindex 8485039ca..e2ca68f6c 100644--- a/pipelex/tools/jinja2/jinja2_sandbox.py+++ b/pipelex/tools/jinja2/jinja2_sandbox.py@@ -56,7 +56,7 @@ from datetime import date, datetime, time, timedeltafrom decimal import Decimalfrom typing import TYPE_CHECKING, Any, NoReturn, cast-from jinja2.exceptions import SecurityError+from jinja2.exceptions import SecurityError as JinjaSecurityErrorfrom jinja2.runtime import BlockReference, Context, LoopContext, Macro, Undefinedfrom jinja2.sandbox import ImmutableSandboxedEnvironment, safe_rangefrom jinja2.utils import Cycler, Joiner, Namespace, generate_lorem_ipsum@@ -107,7 +107,7 @@ def _refuse_callable_in_namespace(*, name: str, value: object) -> None:# An undefined value is callable only so that calling it fails as an undefined value: storing it is harmless.if callable(value) and not isinstance(value, Undefined):msg = f"A template may not store {_describe_callable(obj=value)} in a namespace, as '{name}': a namespace holds data only."- raise SecurityError(msg)+ raise JinjaSecurityError(msg)class DataNamespace(Namespace):@@ -309,7 +309,7 @@ class PipelexTemplateEnvironment(ImmutableSandboxedEnvironment):@overridedef unsafe_undefined(self, obj: Any, attribute: str) -> NoReturn:msg = f"A template may not read '{attribute}' on a '{type(obj).__name__}' value."- raise SecurityError(msg)+ raise JinjaSecurityError(msg)@overridedef wrap_str_format(self, value: Any) -> Callable[..., str] | None:@@ -324,7 +324,7 @@ class PipelexTemplateEnvironment(ImmutableSandboxedEnvironment):def call(self, context: Context, obj: Any, /, *args: Any, **kwargs: Any) -> Any:if not self.is_safe_callable(obj):msg = f"A template may not call {_describe_callable(obj=obj)}: templates read data and call methods of plain values only."- raise SecurityError(msg)+ raise JinjaSecurityError(msg)return charged_call(context=context, obj=obj, args=args, kwargs=kwargs, operation=lambda: f"calling {_describe_callable(obj=obj)}")@overridediff --git a/pipelex/tools/jinja2/jinja2_unknown_names.py b/pipelex/tools/jinja2/jinja2_unknown_names.pynew file mode 100644index 000000000..a69580f61--- /dev/null+++ b/pipelex/tools/jinja2/jinja2_unknown_names.py@@ -0,0 +1,45 @@+"""The filters and tests a template names that its environment does not define.++Jinja2 refuses such a name when it compiles the template, unless the name sits inside a branch: there it compiles to a+lookup that only fails when that branch renders. A run that reaches the failure knows what Jinja2 refused, not which+of a pipe's templates refused it, so a pipe holding several templates asks this walker which of them names an unknown+filter or test, to name that template's field in its refusal.+"""++from jinja2 import nodes+from jinja2.exceptions import TemplateSyntaxError++from pipelex.tools.jinja2.exceptions import Jinja2DetectVariablesError+from pipelex.tools.jinja2.jinja2_environment import make_jinja2_env_without_loader+from pipelex.tools.jinja2.template_category import TemplateCategory+++def find_unknown_filters_and_tests(*, template_source: str, template_category: TemplateCategory) -> list[str]:+ """Return the names of the filters and tests the template uses that its category's environment does not define.++ Args:+ template_source: Jinja2 template source (sigils already rewritten to Jinja2).+ template_category: Category of the template, which decides the filters its environment defines.++ Returns:+ Each unknown name once, in the order the template names them.++ Raises:+ Jinja2DetectVariablesError: If the template cannot be parsed.+ """+ jinja2_env = make_jinja2_env_without_loader(template_category=template_category)+ try:+ parsed_ast = jinja2_env.parse(template_source)+ except TemplateSyntaxError as syntax_error:+ msg = f"Jinja2 unknown-name lint — syntax error: '{syntax_error}', template_category: {template_category}"+ raise Jinja2DetectVariablesError(msg) from syntax_error++ unknown_names: list[str] = []+ for node in parsed_ast.find_all((nodes.Filter, nodes.Test)):+ if isinstance(node, nodes.Filter):+ is_known = node.name in jinja2_env.filters+ else:+ is_known = node.name in jinja2_env.tests+ if not is_known and node.name not in unknown_names:+ unknown_names.append(node.name)+ return unknown_namesdiff --git a/pipelex/tools/jinja2/jinja2_with_images_filter.py b/pipelex/tools/jinja2/jinja2_with_images_filter.pyindex 6be1475fb..955f3bf8e 100644--- a/pipelex/tools/jinja2/jinja2_with_images_filter.py+++ b/pipelex/tools/jinja2/jinja2_with_images_filter.py@@ -4,6 +4,7 @@ from typing import Anyfrom jinja2 import pass_contextfrom jinja2.runtime import Context, Undefined+from mthds.protocol.problem.registry import CoreCodefrom pipelex.tools.jinja2.exceptions import Jinja2ContextErrorfrom pipelex.tools.jinja2.image_registry import ImageRegistry@@ -53,7 +54,7 @@ def with_images(context: Context, value: Any, _: Any = None) -> str:# we create a temporary one (images won't persist across expressions)if not isinstance(registry, ImageRegistry):msg = f"Expected ImageRegistry in context, got {type(registry).__name__}"- raise Jinja2ContextError(msg)+ raise Jinja2ContextError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)# Get text format from context — no fallback, same as the tag and format filterstext_format = TextFormat(require_templating_style_value(context=context, jinja2_context_key=Jinja2ContextKey.TEXT_FORMAT))diff --git a/pipelex/tools/jinja2/template_owner.py b/pipelex/tools/jinja2/template_owner.pynew file mode 100644index 000000000..31027c4b5--- /dev/null+++ b/pipelex/tools/jinja2/template_owner.py@@ -0,0 +1,22 @@+from enum import StrEnum+++class TemplateOwner(StrEnum):+ """Who wrote a template, which decides whose fault a failure of the template is.++ The render serves both: a method's templates (its prompts, expressions and compositions) and the templates Pipelex+ ships to display contents and graphs. A failure of a method's template is the method's, and its message may name+ what the template did; a failure of Pipelex's own is ours, and its message never reaches a caller.+ """++ METHOD = "method"+ PIPELEX = "pipelex"++ @property+ def is_method(self) -> bool:+ """Whether the template is the method's own, whose failure is the method's to fix."""+ match self:+ case TemplateOwner.METHOD:+ return True+ case TemplateOwner.PIPELEX:+ return Falsediff --git a/pipelex/tools/log/exceptions.py b/pipelex/tools/log/exceptions.pyindex 2ff0a4e7b..bdbbcd72e 100644--- a/pipelex/tools/log/exceptions.py+++ b/pipelex/tools/log/exceptions.py@@ -1,4 +1,5 @@-from pipelex.base_exceptions import ErrorDomain+from pipelex.errors.error_code_declaration import ErrorCodeSet+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.system.exceptions import CredentialsError@@ -10,8 +11,7 @@ class GcpLogSinkCredentialsError(CredentialsError):sink, not by the caller correcting input."""- error_domain = ErrorDomain.CONFIG- _declared_title = "Log sink credentials missing or refused"+ error_code = ErrorCodeSet(default=PipelexErrorCode.CONFIG_FILE_MISSING, others=(PipelexErrorCode.CONFIG_CREDENTIAL_REFUSED,))class LogSinkVariableError(CredentialsError):@@ -24,8 +24,7 @@ class LogSinkVariableError(CredentialsError):variable, never a value. Fixed by an operator setting the variable or selecting another sink."""- error_domain = ErrorDomain.CONFIG- _declared_title = "Log sink variable did not resolve"+ error_code = PipelexErrorCode.CONFIG_VARIABLE_MISSINGdef __init__(self, *, sink_method: str, section: str, key: str, variable: str, cause: str):self.sink_method = sink_method@@ -50,8 +49,7 @@ class LogSinkHeaderValueError(CredentialsError):without the line break."""- error_domain = ErrorDomain.CONFIG- _declared_title = "Log sink header value holds a line break"+ error_code = PipelexErrorCode.CONFIG_INVALIDdef __init__(self, *, sink_method: str, section: str, key: str):self.sink_method = sink_methoddiff --git a/pipelex/tools/log/gcp_log_sink.py b/pipelex/tools/log/gcp_log_sink.pyindex d486f58b7..783807a28 100644--- a/pipelex/tools/log/gcp_log_sink.py+++ b/pipelex/tools/log/gcp_log_sink.py@@ -45,6 +45,7 @@ from typing import TYPE_CHECKING, Any, NamedTuple, Protocol, castfrom opentelemetry import tracefrom typing_extensions import override+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.system.exceptions import MissingDependencyErrorfrom pipelex.system.telemetry.current_span import current_span_context_for_logs, pipelex_trace_fields_for_logsfrom pipelex.tools.log.exceptions import GcpLogSinkCredentialsError@@ -706,7 +707,7 @@ def confirm_credentials_at_boot(*, credentials_check: GcpCredentialsCheck, remedf"was refused at boot, so every record it exported would be lost ({describe_failure(failure=verdict.failure)}). "f"{remedy}, or select the '{LogSinkMethod.JSON}' sink in [runtime.log].")- raise GcpLogSinkCredentialsError(msg) from verdict.failure+ raise GcpLogSinkCredentialsError(msg).with_error_code(PipelexErrorCode.CONFIG_CREDENTIAL_REFUSED) from verdict.failurecase GcpCredentialsOutcome.UNREACHABLE:why = f"a refresh could not reach the credential endpoint ({describe_failure(failure=verdict.failure)})"case GcpCredentialsOutcome.UNANSWERED:diff --git a/pipelex/tools/markdown/exceptions.py b/pipelex/tools/markdown/exceptions.pynew file mode 100644index 000000000..bc0a939b9--- /dev/null+++ b/pipelex/tools/markdown/exceptions.py@@ -0,0 +1,11 @@+from pipelex.errors.registry.pipelex_codes import PipelexErrorCode+from pipelex.system.exceptions import ToolError+++class MarkdownParserDependencyError(ToolError):+ """Raised when markdown-it-py is installed without linkify-it-py, which Pipelex requires to read Markdown.++ The environment was installed without a dependency Pipelex declares, so whoever installed it fixes it.+ """++ error_code = PipelexErrorCode.CONFIG_DEPENDENCY_MISSINGdiff --git a/pipelex/tools/markdown/markdown_parser.py b/pipelex/tools/markdown/markdown_parser.pyindex a3d5fb907..67cad57c1 100644--- a/pipelex/tools/markdown/markdown_parser.py+++ b/pipelex/tools/markdown/markdown_parser.py@@ -38,6 +38,7 @@ from markdown_it import MarkdownItfrom markdown_it.tree import SyntaxTreeNodefrom pipelex.tools.jinja2.jinja2_render_budget import MARKDOWN_UNITS_PER_CHARACTER, RenderBudget, active_render_budget+from pipelex.tools.markdown.exceptions import MarkdownParserDependencyErrorif TYPE_CHECKING:from markdown_it.rules_inline import StateInline@@ -71,7 +72,7 @@ def get_markdown_parser() -> MarkdownIt:linkify = parser.linkifyif linkify is None:msg = "markdown-it-py found no linkify-it-py: Pipelex requires markdown-it-py[linkify]."- raise RuntimeError(msg)+ raise MarkdownParserDependencyError(msg)linkify.set({"fuzzy_link": False, "fuzzy_email": False}) # pyright: ignore[reportUnknownMemberType]parser.inline.ruler2.at("fragments_join", _join_text_fragments)return parserdiff --git a/pipelex/tools/misc/exceptions.py b/pipelex/tools/misc/exceptions.pyindex 6f64cd780..997c6b641 100644--- a/pipelex/tools/misc/exceptions.py+++ b/pipelex/tools/misc/exceptions.py@@ -1,32 +1,60 @@-from typing import Self+from typing import ClassVar, Selfimport tomli+from mthds.protocol.problem.registry import CoreCode-from pipelex.base_exceptions import ErrorDomainfrom pipelex.cogt.inference.error_classification import UserAction, UserActionKind+from pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeDeclaration, ErrorCodeSet+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.system.exceptions import ToolErrorclass ArgumentTypeError(ToolError):- pass+ """Raised when a helper is handed a value of a type it does not take, which is a bug of its caller."""++ error_code = CoreCode.RUNTIME_UNEXPECTEDclass JsonTypeError(ToolError):- pass+ """Raised when a JSON document parses but its top level is not the type its reader expects.++ One helper serves several readers: a CLI inputs file is ``request.invalid`` (the default), a credentials+ file the configuration names is ``pipelex.config.invalid``, and a document the runtime wrote itself is+ ``runtime.unexpected``.+ """++ error_code = ErrorCodeSet(default=CoreCode.REQUEST_INVALID, others=(PipelexErrorCode.CONFIG_INVALID, CoreCode.RUNTIME_UNEXPECTED))class FileTypeError(ToolError):- pass+ """Raised when the type of a file cannot be identified from its bytes.++ An input file is ``input.file_type_unsupported`` (the default); bytes a provider returned are+ ``provider.response_invalid``, which the provider's raise site chooses.+ """++ error_code = ErrorCodeSet(default=CoreCode.INPUT_FILE_TYPE_UNSUPPORTED, others=(CoreCode.PROVIDER_RESPONSE_INVALID,))class ContextProviderError(ToolError):+ """Base of the errors a context provider raises when it cannot give a variable's value."""++ error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERROR+def __init__(self, message: str, variable_name: str):super().__init__(message=message)self.variable_name = variable_nameclass TomlError(ToolError):- _declared_title = "TOML parse error"+ """Raised when a TOML document does not parse.++ Most TOML the runtime reads is its own configuration, so the default is ``pipelex.config.syntax``. A raise+ or catch site that reads a caller's request file chooses ``request.malformed``, and one that reads a+ method's file chooses ``method.syntax``.+ """++ error_code = ErrorCodeSet(default=PipelexErrorCode.CONFIG_SYNTAX, others=(CoreCode.REQUEST_MALFORMED, CoreCode.METHOD_SYNTAX))def __init__(self, message: str, doc: str, pos: int, lineno: int, colno: int):super().__init__(message)@@ -44,16 +72,57 @@ class RemoteFileFetchError(ToolError):"""A remote file an input or a pipe referenced could not be fetched.Raised where the fetch happens — inside the operator that consumes the resource, the- one honest test that a URL serves what it claims to. The URL is caller-supplied, so- ``error_domain = INPUT`` and the message is caller-facing: it names the URL and what- the server or the network said (an HTTP status, a refused connection, a timeout), and- never a resolved address.+ one honest test that a URL serves what it claims to. The URL is caller-supplied, so the+ message is caller-facing: it names the URL and what the server or the network said (an+ HTTP status, a refused connection, a timeout), and never a resolved address.++ A server that answered but would not serve the file is ``input.file_unreadable`` (the+ default); a timeout or a refused connection, which a retry may get past, is+ ``input.url_unreachable``; a file a provider's answer pointed at is+ ``provider.response_invalid``, which the provider's raise site chooses."""- error_domain = ErrorDomain.INPUT- _declared_title = "Remote file could not be fetched"+ error_code = ErrorCodeSet(+ default=CoreCode.INPUT_FILE_UNREADABLE,+ others=(CoreCode.INPUT_URL_UNREACHABLE, CoreCode.PROVIDER_RESPONSE_INVALID),+ )_authors_caller_facing_message = Trueuser_action = UserAction(kind=UserActionKind.CHANGE_INPUT,detail="Check that the URL serves the file to a plain HTTP client, or upload the file and reference it instead.",)+++class SemVerError(ToolError):+ """Raised when a version or a version constraint a method package declares does not parse."""++ error_code = CoreCode.METHOD_PACKAGE_INVALID+++class UrlSyntaxError(ToolError, ValueError):+ """Raised when a URL is not a well-formed http(s) URL, checked without touching the network.++ Also a ``ValueError``, which the input checks that call it catch to name the input.+ """++ error_code = CoreCode.INPUT_INVALID+++class LocalFileMissingError(ToolError, ValueError):+ """Raised when a local path a value points at names no file.++ Also a ``ValueError``, which the pipe's input check that calls it catches to name the input.+ """++ error_code = CoreCode.INPUT_REFERENCE_NOT_FOUND+++class UnsupportedImageMimeTypeError(ToolError, ValueError):+ """Raised when a MIME type is not one of the image formats Pipelex reads and writes.++ An input's image is ``input.file_type_unsupported`` (the default); an image a provider returned is+ ``provider.response_invalid``, which the provider's raise site chooses. Also a ``ValueError``, since the+ check also runs inside a pydantic validator.+ """++ error_code = ErrorCodeSet(default=CoreCode.INPUT_FILE_TYPE_UNSUPPORTED, others=(CoreCode.PROVIDER_RESPONSE_INVALID,))diff --git a/pipelex/tools/misc/file_fetch_utils.py b/pipelex/tools/misc/file_fetch_utils.pyindex f5782e738..03c1b30c9 100644--- a/pipelex/tools/misc/file_fetch_utils.py+++ b/pipelex/tools/misc/file_fetch_utils.py@@ -1,11 +1,16 @@import httpxfrom httpx import USE_CLIENT_DEFAULT, Response, Timeout+from mthds.protocol.problem.registry import CoreCodefrom pipelex.config import is_fetch_ssrf_guard_enabledfrom pipelex.tools.misc.exceptions import RemoteFileFetchErrorfrom pipelex.tools.misc.http_utils import get_user_agentfrom pipelex.tools.network.ssrf_guard import SsrfGuardedTransport+# The statuses by which a server that is there says it cannot answer now, besides every 5xx: a retry may get the file.+_TRANSIENT_HTTP_STATUSES = frozenset({408, 425, 429})+_HTTP_SERVER_ERROR_FLOOR = 500+async def fetch_file_and_content_type_from_url_httpx(url: str,@@ -61,14 +66,18 @@ async def fetch_file_and_content_type_from_url_httpx()response.raise_for_status()except httpx.HTTPStatusError as exc:- msg = f"Could not fetch '{url}': the server answered HTTP {exc.response.status_code}"+ status_code = exc.response.status_code+ msg = f"Could not fetch '{url}': the server answered HTTP {status_code}"+ if status_code in _TRANSIENT_HTTP_STATUSES or status_code >= _HTTP_SERVER_ERROR_FLOOR:+ # The server is there but cannot answer now: a retry may get the file.+ raise RemoteFileFetchError(msg).with_error_code(CoreCode.INPUT_URL_UNREACHABLE) from excraise RemoteFileFetchError(msg) from excexcept httpx.TimeoutException as exc:msg = f"Could not fetch '{url}': the request timed out"- raise RemoteFileFetchError(msg) from exc+ raise RemoteFileFetchError(msg).with_error_code(CoreCode.INPUT_URL_UNREACHABLE) from excexcept httpx.ConnectError as exc:msg = f"Could not fetch '{url}': the host could not be reached"- raise RemoteFileFetchError(msg) from exc+ raise RemoteFileFetchError(msg).with_error_code(CoreCode.INPUT_URL_UNREACHABLE) from excexcept httpx.RequestError as exc:msg = f"Could not fetch '{url}': the request failed ({type(exc).__name__})"raise RemoteFileFetchError(msg) from excdiff --git a/pipelex/tools/misc/filetype_utils.py b/pipelex/tools/misc/filetype_utils.pyindex 3000dcbc6..c50378370 100644--- a/pipelex/tools/misc/filetype_utils.py+++ b/pipelex/tools/misc/filetype_utils.py@@ -81,7 +81,8 @@ def detect_file_type_from_bytes(raw_bytes: bytes) -> FileType:"""kind = filetype.guess(raw_bytes) # pyright: ignore[reportUnknownMemberType]if kind is None:- msg = f"Could not identify file type of given bytes: {raw_bytes[:300]!r}"+ # The message names the size, never the bytes: they are a caller's or a provider's content.+ msg = f"Could not identify the file type of the given {len(raw_bytes)} bytes"raise FileTypeError(msg)extension = f"{kind.extension}"mime = f"{kind.mime}"diff --git a/pipelex/tools/misc/http_utils.py b/pipelex/tools/misc/http_utils.pyindex f2a3b5a6b..ba546c724 100644--- a/pipelex/tools/misc/http_utils.py+++ b/pipelex/tools/misc/http_utils.py@@ -1,5 +1,6 @@from pydantic import HttpUrl, TypeAdapter, ValidationError+from pipelex.tools.misc.exceptions import LocalFileMissingError, UrlSyntaxErrorfrom pipelex.tools.misc.file_utils import path_existsfrom pipelex.tools.misc.package_utils import get_package_version@@ -16,14 +17,14 @@ def validate_http_url_syntax(*, url: str) -> None:"""Check that ``url`` is a well-formed http(s) URL, without touching the network.Raises:- ValueError: If the URL does not parse as an http(s) URL.+ UrlSyntaxError: If the URL does not parse as an http(s) URL."""try:_HTTP_URL_ADAPTER.validate_python(url)except ValidationError as exc:first_error = exc.errors()[0]["msg"] if exc.errors() else "not a valid http(s) URL"msg = f"URL '{url}' is not a valid http(s) URL: {first_error}"- raise ValueError(msg) from exc+ raise UrlSyntaxError(msg) from excdef get_user_agent() -> str:@@ -53,7 +54,7 @@ def validate_url_resource_exists(url: str) -> None:Skips validation for internal URIs (base64 data URLs, pipelex-storage://).Raises:- ValueError: If a local file path does not exist.+ LocalFileMissingError: If a local file path does not exist."""if url.startswith(_SKIP_VALIDATION_PREFIXES):return@@ -67,4 +68,4 @@ def validate_url_resource_exists(url: str) -> None:def _validate_local_path(url: str) -> None:if not path_exists(url):msg = f"File '{url}' does not exist"- raise ValueError(msg)+ raise LocalFileMissingError(msg)diff --git a/pipelex/tools/misc/image_utils.py b/pipelex/tools/misc/image_utils.pyindex 4a9f4df67..3df2485c5 100644--- a/pipelex/tools/misc/image_utils.py+++ b/pipelex/tools/misc/image_utils.py@@ -3,6 +3,8 @@ from enum import StrEnumfrom PIL import Image+from pipelex.tools.misc.exceptions import UnsupportedImageMimeTypeError+class ImageFormat(StrEnum):PNG = "png"@@ -60,7 +62,7 @@ class ImageFormat(StrEnum):return fmtcls.raise_if_unsupported_mime_type(mime_type)msg = f"Unsupported MIME type: {mime_type}"- raise ValueError(msg)+ raise UnsupportedImageMimeTypeError(msg)@classmethoddef get_supported_mime_types(cls) -> frozenset[str]:@@ -80,7 +82,7 @@ class ImageFormat(StrEnum):mime_type: The MIME type to validate.Raises:- ValueError: If the MIME type is not supported.+ UnsupportedImageMimeTypeError: If the MIME type is not supported."""if not cls.is_supported_mime_type(mime_type):supported = ", ".join(sorted(cls.get_supported_mime_types()))@@ -88,7 +90,7 @@ class ImageFormat(StrEnum):msg = f"Unsupported image MIME type: {mime_type}. Supported types are: {supported}"else:msg = f"Invalid image MIME type: {mime_type}. Expected format 'image/<subtype>'. Supported types are: {supported}"- raise ValueError(msg)+ raise UnsupportedImageMimeTypeError(msg)def pil_image_to_bytes(pil_image: Image.Image, *, image_format: ImageFormat | None) -> bytes:diff --git a/pipelex/tools/misc/json_utils.py b/pipelex/tools/misc/json_utils.pyindex 3560eb6a7..94f63b51e 100644--- a/pipelex/tools/misc/json_utils.py+++ b/pipelex/tools/misc/json_utils.py@@ -8,6 +8,7 @@ from typing import Any, Union, castfrom kajson import kajsonfrom kajson.exceptions import UnijsonEncoderError+from mthds.protocol.problem.registry import CoreCodefrom pydantic import BaseModelfrom pipelex.tools.misc.exceptions import ArgumentTypeError, JsonTypeError@@ -326,7 +327,7 @@ def remove_none_values_from_dict(data: Mapping[str, Any]) -> dict[str, Any]:processed = remove_none_values(json_content=data)if not isinstance(processed, dict):msg = "Removing None values from a dict, we expected a dict in return"- raise JsonTypeError(msg)+ raise JsonTypeError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)return cast("dict[str, Any]", processed) # pyright: ignore[reportUnnecessaryCast]diff --git a/pipelex/tools/misc/semver.py b/pipelex/tools/misc/semver.pyindex 6182eff94..7970dee9e 100644--- a/pipelex/tools/misc/semver.py+++ b/pipelex/tools/misc/semver.py@@ -10,9 +10,7 @@ disabled at file level for this wrapper module.from semantic_version import SimpleSpec, Version # type: ignore[import-untyped]--class SemVerError(Exception):- """Raised for semver parse failures."""+from pipelex.tools.misc.exceptions import SemVerErrordef parse_version(version_str: str) -> Version:diff --git a/pipelex/tools/network/exceptions.py b/pipelex/tools/network/exceptions.pyindex d6794922f..5058d192f 100644--- a/pipelex/tools/network/exceptions.py+++ b/pipelex/tools/network/exceptions.py@@ -1,4 +1,7 @@-from pipelex.base_exceptions import ErrorDomain, SecurityError+from mthds.protocol.problem.registry import CoreCode++from pipelex.base_exceptions import SecurityError+from pipelex.errors.error_code_declaration import ErrorCodeSetclass SsrfBlockedError(SecurityError):@@ -20,9 +23,12 @@ class SsrfBlockedError(SecurityError):delivery or a download's fallback — it surfaces and fails the delivery or thepipe.- ``error_domain = INPUT`` because the destination was supplied from outside the- runtime (a callback URL on the originating request, or a URL a method's value- carried); the caller fixes it by providing a public URL.+ The guard cannot tell who supplied the URL, so the default is+ ``security.input_url_refused``: the destination was supplied from outside the+ runtime (a callback URL on the originating request, or a URL an input carried),+ and the caller fixes it by providing a public URL. A raise or catch site that+ knows the method named the URL chooses ``security.method_url_refused``, and one+ that knows a provider's answer named it ``security.provider_url_refused``.``_authors_caller_facing_message`` lets the message survive STRICTdisclosure — it deliberately names only the requested hostname, never theresolved private IP, so it never reveals an internal address to a probing@@ -30,6 +36,8 @@ class SsrfBlockedError(SecurityError):since the refusal is told apart from a host that cannot be reached."""- error_domain = ErrorDomain.INPUT- _declared_title = "Outbound request blocked (SSRF guard)"+ error_code = ErrorCodeSet(+ default=CoreCode.SECURITY_INPUT_URL_REFUSED,+ others=(CoreCode.SECURITY_METHOD_URL_REFUSED, CoreCode.SECURITY_PROVIDER_URL_REFUSED),+ )_authors_caller_facing_message = Truediff --git a/pipelex/tools/pdf/exceptions.py b/pipelex/tools/pdf/exceptions.pydeleted file mode 100644index 87981bb84..000000000--- a/pipelex/tools/pdf/exceptions.py+++ /dev/null@@ -1,5 +0,0 @@-from pipelex.system.exceptions import ToolError---class PyPdfium2RendererError(ToolError):- passdiff --git a/pipelex/tools/secrets/env_secrets_provider.py b/pipelex/tools/secrets/env_secrets_provider.pyindex 2eddc304e..3e9e47712 100644--- a/pipelex/tools/secrets/env_secrets_provider.py+++ b/pipelex/tools/secrets/env_secrets_provider.py@@ -2,7 +2,7 @@ from typing_extensions import overridefrom pipelex.system.environment import get_optional_env, get_required_envfrom pipelex.system.exceptions import EnvVarNotFoundError-from pipelex.tools.secrets.exceptions import SecretNotFoundError+from pipelex.tools.secrets.exceptions import SecretNotFoundError, SecretVersionUnsupportedErrorfrom pipelex.tools.secrets.secrets_provider_abstract import SecretsProviderAbstract@@ -22,12 +22,12 @@ class EnvSecretsProvider(SecretsProviderAbstract):@overridedef get_required_secret_specific_version(self, secret_id: str, *, version_id: str) -> str:msg = "EnvSecretsProvider does not support specific versions"- raise NotImplementedError(msg)+ raise SecretVersionUnsupportedError(msg)@overridedef get_optional_secret_specific_version(self, secret_id: str, *, version_id: str) -> str | None:msg = "EnvSecretsProvider does not support specific versions"- raise NotImplementedError(msg)+ raise SecretVersionUnsupportedError(msg)@overridedef set_secret_as_env_var(self, secret_id: str, *, version_id: str = "latest"):diff --git a/pipelex/tools/secrets/exceptions.py b/pipelex/tools/secrets/exceptions.pyindex a1b50c22d..81a7ea973 100644--- a/pipelex/tools/secrets/exceptions.py+++ b/pipelex/tools/secrets/exceptions.py@@ -1,23 +1,42 @@+from mthds.protocol.problem.registry import CoreCode++from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.system.exceptions import ToolErrorclass SecretNotFoundError(ToolError):- pass+ """Raised when the secrets provider holds no value for a secret the configuration names."""++ error_code = PipelexErrorCode.CONFIG_VARIABLE_MISSINGclass VarNotFoundError(ToolError):+ """Raised when a variable named in a ``${…}`` placeholder is set nowhere."""++ error_code = PipelexErrorCode.CONFIG_VARIABLE_MISSING+def __init__(self, var_name: str, message: str):self.var_name = var_namesuper().__init__(message)class VarFallbackPatternError(ToolError):- pass+ """Raised when no variable of a ``${a|b}`` fallback placeholder is set."""++ error_code = PipelexErrorCode.CONFIG_VARIABLE_MISSINGclass UnknownVarPrefixError(ToolError):"""Raised when an unknown variable prefix is used in variable substitution."""+ error_code = PipelexErrorCode.CONFIG_INVALID+def __init__(self, var_name: str, message: str):self.var_name = var_namesuper().__init__(message)+++class SecretVersionUnsupportedError(ToolError):+ """Raised when a specific version of a secret is asked of a secrets provider that keeps no versions."""++ error_code = CoreCode.RUNTIME_UNSUPPORTEDdiff --git a/pipelex/tools/storage/exceptions.py b/pipelex/tools/storage/exceptions.pyindex 176ea3d78..17ed6e2e1 100644--- a/pipelex/tools/storage/exceptions.py+++ b/pipelex/tools/storage/exceptions.py@@ -1,50 +1,117 @@+from typing import ClassVar++from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import PipelexConfigError+from pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeDeclaration, ErrorCodeSet+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.system.exceptions import ToolErrorclass StorageError(ToolError):"""Base exception for storage-related errors."""- _declared_title = "Storage error"+ error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERROR++class StorageConfigError(PipelexConfigError, StorageError):+ """Raised when a storage configuration is invalid.-class StorageConfigError(StorageError, PipelexConfigError):- """Raised when a storage configuration is invalid."""+ It shares the configuration code rather than a storage one: an operator handles it like any other+ configuration error.+ """++ error_code: ClassVar[ErrorCodeDeclaration] = PipelexErrorCode.CONFIG_INVALIDclass StorageFileNotFoundError(StorageError):- """Raised when a requested file does not exist in storage."""+ """Raised when a requested file does not exist in storage.++ A stored file a run wrote or was handed has vanished, which is nobody's input, so the default is+ ``pipelex.storage.not_found``. A URI of the wrong scheme reaching a provider is a routing fault of the+ runtime, ``runtime.unexpected``.+ """++ error_code = ErrorCodeSet(default=PipelexErrorCode.STORAGE_NOT_FOUND, others=(CoreCode.RUNTIME_UNEXPECTED,))+++class StorageNotConfiguredError(StorageError):+ """Raised when a ``pipelex-storage://`` URI must be read on a runtime that has no storage provider."""++ error_code = PipelexErrorCode.STORAGE_NOT_CONFIGUREDclass StorageInvalidUriError(StorageError):- """Raised when a URI is invalid (e.g., path traversal attempt or absolute path)."""+ """Raised when a URI is invalid (e.g., path traversal attempt or absolute path).++ The provider cannot tell who supplied the key, so the default is ``security.input_path_refused``, the+ reading of the input seam where a caller passes a storage key. A site that knows a pipe or a function+ produced the key chooses ``security.method_url_refused``, and a payload codec that finds a reference it did+ not write chooses ``runtime.unexpected``.+ """++ error_code = ErrorCodeSet(+ default=CoreCode.SECURITY_INPUT_PATH_REFUSED,+ others=(CoreCode.SECURITY_METHOD_URL_REFUSED, CoreCode.RUNTIME_UNEXPECTED),+ )class StorageInvalidKeyError(StorageError):"""Raised when a storage key is invalid (e.g., contains scheme prefix)."""+ error_code = CoreCode.RUNTIME_UNEXPECTED+class StorageChecksumMismatchError(StorageError):- """Raised when the bytes a create-only write was handed do not hash to the checksum it was handed with them."""+ """Raised when the bytes a create-only write was handed do not hash to the checksum it was handed with them.- _declared_title = "Storage checksum mismatch"+ The caller hashes the bytes it hands over, so a mismatch is a bug of the caller, never the storage's fault.+ """++ error_code = CoreCode.RUNTIME_UNEXPECTEDclass StorageLocalError(StorageError):- """Raised when a local filesystem storage operation fails."""+ """Raised when a local filesystem storage operation fails.++ A permission or disk-full error does not heal on retry: whoever runs the runtime fixes the directory.+ """- _declared_title = "Local storage error"+ error_code = CoreCode.RUNTIME_MISCONFIGUREDclass StorageS3Error(StorageError):- """Raised when an S3 storage operation fails."""+ """Raised when an S3 storage operation fails.- _declared_title = "S3 storage error"+ An S3 failure is ``pipelex.storage.unavailable`` unless S3 names its cause: a missing bucket is the+ configured bucket name, ``pipelex.config.invalid``; credentials S3 refuses are+ ``pipelex.config.credential_refused``; and credentials the runtime could not find are+ ``pipelex.config.credential_missing``.+ """++ error_code = ErrorCodeSet(+ default=PipelexErrorCode.STORAGE_UNAVAILABLE,+ others=(+ PipelexErrorCode.CONFIG_INVALID,+ PipelexErrorCode.CONFIG_CREDENTIAL_REFUSED,+ PipelexErrorCode.CONFIG_CREDENTIAL_MISSING,+ ),+ )class StorageGcpError(StorageError):- """Raised when a GCP storage operation fails."""+ """Raised when a GCP storage operation fails.++ A GCS failure is ``pipelex.storage.unavailable`` unless GCS refuses the credentials, which is+ ``pipelex.config.credential_refused``.+ """++ error_code: ClassVar[ErrorCodeDeclaration] = ErrorCodeSet(+ default=PipelexErrorCode.STORAGE_UNAVAILABLE, others=(PipelexErrorCode.CONFIG_CREDENTIAL_REFUSED,)+ )class StorageGcpCredentialsError(StorageGcpError):"""Raised when GCP credentials file is not found or invalid."""++ error_code = PipelexErrorCode.CONFIG_FILE_MISSINGdiff --git a/pipelex/tools/storage/gcp_storage_provider.py b/pipelex/tools/storage/gcp_storage_provider.pyindex 4701cb479..19964a1d3 100644--- a/pipelex/tools/storage/gcp_storage_provider.py+++ b/pipelex/tools/storage/gcp_storage_provider.py@@ -7,6 +7,7 @@ from urllib.parse import quotefrom typing_extensions import override+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.system.exceptions import MissingDependencyErrorfrom pipelex.tools.storage.exceptions import (StorageFileNotFoundError,@@ -98,8 +99,10 @@ class GcpStorageProvider(StorageProviderAbstract):bucket = self._get_bucket()from google.api_core.exceptions import ( # type: ignore[import-untyped] # ruff: ignore[import-outside-top-level] - optional dependency, lazy import+ Forbidden,GoogleAPIError,NotFound,+ Unauthorized,)try:@@ -112,6 +115,9 @@ class GcpStorageProvider(StorageProviderAbstract):except NotFound as exc: # pyright: ignore[reportUnknownVariableType]msg = f"Object not found in GCS: '{key}'"raise StorageFileNotFoundError(msg) from exc+ except (Forbidden, Unauthorized) as exc: # pyright: ignore[reportUnknownVariableType]+ msg = f"Failed to load object from GCS: '{key}': {exc}"+ raise StorageGcpError(msg).with_error_code(PipelexErrorCode.CONFIG_CREDENTIAL_REFUSED) from excexcept GoogleAPIError as exc: # pyright: ignore[reportUnknownVariableType]msg = f"Failed to load object from GCS: '{key}': {exc}"raise StorageGcpError(msg) from exc@@ -149,9 +155,11 @@ class GcpStorageProvider(StorageProviderAbstract):bucket = self._get_bucket()from google.api_core.exceptions import ( # type: ignore[import-untyped] # ruff: ignore[import-outside-top-level] - optional dependency, lazy import+ Forbidden,GoogleAPIError,NotFound,RequestRangeNotSatisfiable,+ Unauthorized,)try:@@ -165,6 +173,9 @@ class GcpStorageProvider(StorageProviderAbstract):except RequestRangeNotSatisfiable: # pyright: ignore[reportUnknownVariableType]# GCS refuses any range over an empty object: its head is empty.return b""+ except (Forbidden, Unauthorized) as exc: # pyright: ignore[reportUnknownVariableType]+ msg = f"Failed to load object from GCS: '{key}': {exc}"+ raise StorageGcpError(msg).with_error_code(PipelexErrorCode.CONFIG_CREDENTIAL_REFUSED) from excexcept GoogleAPIError as exc: # pyright: ignore[reportUnknownVariableType]msg = f"Failed to load object from GCS: '{key}': {exc}"raise StorageGcpError(msg) from exc@@ -196,12 +207,17 @@ class GcpStorageProvider(StorageProviderAbstract):bucket = self._get_bucket()from google.api_core.exceptions import ( # type: ignore[import-untyped] # ruff: ignore[import-outside-top-level] - optional dependency, lazy import+ Forbidden,GoogleAPIError,+ Unauthorized,)try:# Fetches the object's metadata alone, None when there is no such object.blob = bucket.get_blob(key)+ except (Forbidden, Unauthorized) as exc: # pyright: ignore[reportUnknownVariableType]+ msg = f"Failed to read the size of the GCS object '{key}': {exc}"+ raise StorageGcpError(msg).with_error_code(PipelexErrorCode.CONFIG_CREDENTIAL_REFUSED) from excexcept GoogleAPIError as exc: # pyright: ignore[reportUnknownVariableType]msg = f"Failed to read the size of the GCS object '{key}': {exc}"raise StorageGcpError(msg) from exc@@ -235,12 +251,17 @@ class GcpStorageProvider(StorageProviderAbstract):bucket = self._get_bucket()from google.api_core.exceptions import ( # type: ignore[import-untyped] # ruff: ignore[import-outside-top-level] - optional dependency, lazy import+ Forbidden,GoogleAPIError,+ Unauthorized,)try:blob = bucket.blob(key)blob.upload_from_string(data, content_type=content_type)+ except (Forbidden, Unauthorized) as exc: # pyright: ignore[reportUnknownVariableType]+ msg = f"Failed to store object to GCS: '{key}': {exc}"+ raise StorageGcpError(msg).with_error_code(PipelexErrorCode.CONFIG_CREDENTIAL_REFUSED) from excexcept GoogleAPIError as exc: # pyright: ignore[reportUnknownVariableType]msg = f"Failed to store object to GCS: '{key}': {exc}"raise StorageGcpError(msg) from exc@@ -268,8 +289,10 @@ class GcpStorageProvider(StorageProviderAbstract):bucket = self._get_bucket()from google.api_core.exceptions import ( # type: ignore[import-untyped] # ruff: ignore[import-outside-top-level] - optional dependency, lazy import+ Forbidden,GoogleAPIError,PreconditionFailed,+ Unauthorized,)try:@@ -278,6 +301,9 @@ class GcpStorageProvider(StorageProviderAbstract):blob.upload_from_string(data, content_type=content_type, if_generation_match=0)except PreconditionFailed: # pyright: ignore[reportUnknownVariableType]return False+ except (Forbidden, Unauthorized) as exc: # pyright: ignore[reportUnknownVariableType]+ msg = f"Failed to store object to GCS: '{key}': {exc}"+ raise StorageGcpError(msg).with_error_code(PipelexErrorCode.CONFIG_CREDENTIAL_REFUSED) from excexcept GoogleAPIError as exc: # pyright: ignore[reportUnknownVariableType]msg = f"Failed to store object to GCS: '{key}': {exc}"raise StorageGcpError(msg) from excdiff --git a/pipelex/tools/storage/s3_storage_provider.py b/pipelex/tools/storage/s3_storage_provider.pyindex 7ac3e27e9..f6e9e4429 100644--- a/pipelex/tools/storage/s3_storage_provider.py+++ b/pipelex/tools/storage/s3_storage_provider.py@@ -6,6 +6,8 @@ from urllib.parse import quotefrom typing_extensions import override+from pipelex.errors.error_codes import ErrorCode+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.system.exceptions import MissingDependencyErrorfrom pipelex.tools.storage.exceptions import (StorageFileNotFoundError,@@ -13,6 +15,19 @@ from pipelex.tools.storage.exceptions import ()from pipelex.tools.storage.storage_provider_abstract import StorageProviderAbstract, StoredData+# The S3 error codes by which S3 refuses the credentials themselves, rather than failing to serve: an operator fixes these.+_S3_CREDENTIAL_REFUSAL_CODES = frozenset({"AccessDenied", "InvalidAccessKeyId", "SignatureDoesNotMatch", "ExpiredToken", "InvalidToken"})+++def _code_for_s3_client_error(*, s3_error_code: str) -> ErrorCode:+ """The registry code of an S3 ``ClientError`` that is not a missing object, read from the code S3 answered."""+ if s3_error_code == "NoSuchBucket":+ return PipelexErrorCode.CONFIG_INVALID+ if s3_error_code in _S3_CREDENTIAL_REFUSAL_CODES:+ return PipelexErrorCode.CONFIG_CREDENTIAL_REFUSED+ return PipelexErrorCode.STORAGE_UNAVAILABLE++# What S3 answers a conditional write whose condition fails: `412` when the key holds an object (`If-None-Match: *`),# `409 ConditionalRequestConflict` when another conditional write to the same key is in flight._PRECONDITION_FAILED_CODES = frozenset({"412", "PreconditionFailed"})@@ -125,6 +140,7 @@ class S3StorageProvider(StorageProviderAbstract):from botocore.exceptions import ( # ruff: ignore[import-outside-top-level] - optional dependency, lazy importBotoCoreError,ClientError,+ NoCredentialsError,)session = self._get_session()@@ -143,14 +159,17 @@ class S3StorageProvider(StorageProviderAbstract):raise StorageFileNotFoundError(msg) from excexcept client.exceptions.NoSuchBucket as exc:msg = f"Bucket not found in S3: '{self._bucket_name}'"- raise StorageS3Error(msg) from exc+ raise StorageS3Error(msg).with_error_code(PipelexErrorCode.CONFIG_INVALID) from excexcept ClientError as exc:error_code = (exc.response.get("Error") or {}).get("Code", "Unknown")if error_code == "NoSuchKey":msg = f"Object not found in S3: '{key}'"raise StorageFileNotFoundError(msg) from excmsg = f"S3 ClientError ({error_code}) for key '{key}'"- raise StorageS3Error(msg) from exc+ raise StorageS3Error(msg).with_error_code(_code_for_s3_client_error(s3_error_code=error_code)) from exc+ except NoCredentialsError as exc:+ msg = f"S3 credentials not found for key '{key}': {type(exc).__name__}"+ raise StorageS3Error(msg).with_error_code(PipelexErrorCode.CONFIG_CREDENTIAL_MISSING) from excexcept BotoCoreError as exc:msg = f"S3 backend error for key '{key}': {type(exc).__name__}"raise StorageS3Error(msg) from exc@@ -173,6 +192,7 @@ class S3StorageProvider(StorageProviderAbstract):from botocore.exceptions import ( # ruff: ignore[import-outside-top-level] - optional dependency, lazy importBotoCoreError,ClientError,+ NoCredentialsError,)session = self._get_session()@@ -190,7 +210,7 @@ class S3StorageProvider(StorageProviderAbstract):raise StorageFileNotFoundError(msg) from excexcept client.exceptions.NoSuchBucket as exc:msg = f"Bucket not found in S3: '{self._bucket_name}'"- raise StorageS3Error(msg) from exc+ raise StorageS3Error(msg).with_error_code(PipelexErrorCode.CONFIG_INVALID) from excexcept ClientError as exc:error_code = (exc.response.get("Error") or {}).get("Code", "Unknown")if error_code == "InvalidRange":@@ -200,7 +220,10 @@ class S3StorageProvider(StorageProviderAbstract):msg = f"Object not found in S3: '{key}'"raise StorageFileNotFoundError(msg) from excmsg = f"S3 ClientError ({error_code}) for key '{key}'"- raise StorageS3Error(msg) from exc+ raise StorageS3Error(msg).with_error_code(_code_for_s3_client_error(s3_error_code=error_code)) from exc+ except NoCredentialsError as exc:+ msg = f"S3 credentials not found for key '{key}': {type(exc).__name__}"+ raise StorageS3Error(msg).with_error_code(PipelexErrorCode.CONFIG_CREDENTIAL_MISSING) from excexcept BotoCoreError as exc:msg = f"S3 backend error for key '{key}': {type(exc).__name__}"raise StorageS3Error(msg) from exc@@ -222,6 +245,7 @@ class S3StorageProvider(StorageProviderAbstract):from botocore.exceptions import ( # ruff: ignore[import-outside-top-level] - optional dependency, lazy importBotoCoreError,ClientError,+ NoCredentialsError,)session = self._get_session()@@ -237,7 +261,10 @@ class S3StorageProvider(StorageProviderAbstract):msg = f"Object not found in S3: '{key}'"raise StorageFileNotFoundError(msg) from excmsg = f"S3 ClientError ({error_code}) for key '{key}'"- raise StorageS3Error(msg) from exc+ raise StorageS3Error(msg).with_error_code(_code_for_s3_client_error(s3_error_code=error_code)) from exc+ except NoCredentialsError as exc:+ msg = f"S3 credentials not found for key '{key}': {type(exc).__name__}"+ raise StorageS3Error(msg).with_error_code(PipelexErrorCode.CONFIG_CREDENTIAL_MISSING) from excexcept BotoCoreError as exc:msg = f"S3 backend error for key '{key}': {type(exc).__name__}"raise StorageS3Error(msg) from exc@@ -259,6 +286,7 @@ class S3StorageProvider(StorageProviderAbstract):from botocore.exceptions import ( # ruff: ignore[import-outside-top-level] - optional dependency, lazy importBotoCoreError,ClientError,+ NoCredentialsError,)session = self._get_session()@@ -276,11 +304,14 @@ class S3StorageProvider(StorageProviderAbstract):await client.put_object(**put_params)except client.exceptions.NoSuchBucket as exc:msg = f"Bucket not found in S3: '{self._bucket_name}'"- raise StorageS3Error(msg) from exc+ raise StorageS3Error(msg).with_error_code(PipelexErrorCode.CONFIG_INVALID) from excexcept ClientError as exc:error_code = (exc.response.get("Error") or {}).get("Code", "Unknown")msg = f"S3 ClientError ({error_code}) for key '{key}'"- raise StorageS3Error(msg) from exc+ raise StorageS3Error(msg).with_error_code(_code_for_s3_client_error(s3_error_code=error_code)) from exc+ except NoCredentialsError as exc:+ msg = f"S3 credentials not found for key '{key}': {type(exc).__name__}"+ raise StorageS3Error(msg).with_error_code(PipelexErrorCode.CONFIG_CREDENTIAL_MISSING) from excexcept BotoCoreError as exc:msg = f"S3 backend error for key '{key}': {type(exc).__name__}"raise StorageS3Error(msg) from exc@@ -341,14 +372,14 @@ class S3StorageProvider(StorageProviderAbstract):await client.put_object(**put_params)except client.exceptions.NoSuchBucket as exc:msg = f"Bucket not found in S3: '{self._bucket_name}'"- raise StorageS3Error(msg) from exc+ raise StorageS3Error(msg).with_error_code(PipelexErrorCode.CONFIG_INVALID) from excexcept ClientError as exc:error_code = (exc.response.get("Error") or {}).get("Code", "Unknown")if error_code in _PRECONDITION_FAILED_CODES:return Falseif error_code not in _CONDITIONAL_CONFLICT_CODES:msg = f"S3 ClientError ({error_code}) for key '{key}'"- raise StorageS3Error(msg) from exc+ raise StorageS3Error(msg).with_error_code(_code_for_s3_client_error(s3_error_code=error_code)) from excconditional_conflict = exccontinueexcept BotoCoreError as exc:diff --git a/pipelex/tools/storage/storage_provider_abstract.py b/pipelex/tools/storage/storage_provider_abstract.pyindex 8d31eae39..add5b9b98 100644--- a/pipelex/tools/storage/storage_provider_abstract.py+++ b/pipelex/tools/storage/storage_provider_abstract.py@@ -2,6 +2,8 @@ import hashlibfrom abc import ABC, abstractmethodfrom typing import NamedTuple+from mthds.protocol.problem.registry import CoreCode+from pipelex.tools.storage.exceptions import StorageChecksumMismatchError, StorageFileNotFoundError, StorageInvalidKeyErrorPIPELEX_STORAGE_SCHEME = "pipelex-storage://"@@ -39,8 +41,9 @@ class StorageProviderAbstract(ABC):StorageFileNotFoundError: If URI doesn't start with the expected scheme."""if not uri.startswith(PIPELEX_STORAGE_SCHEME):+ # A URI of another scheme reaching this provider is a routing fault of the runtime, not a missing file.msg = f"Invalid URI '{uri}': must start with '{PIPELEX_STORAGE_SCHEME}'"- raise StorageFileNotFoundError(msg)+ raise StorageFileNotFoundError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)return uri.removeprefix(PIPELEX_STORAGE_SCHEME)def _add_scheme(self, key: str) -> str:diff --git a/pipelex/tools/tabular/csv_codec.py b/pipelex/tools/tabular/csv_codec.pyindex d57abc6e9..e44d4cf88 100644--- a/pipelex/tools/tabular/csv_codec.py+++ b/pipelex/tools/tabular/csv_codec.py@@ -20,6 +20,7 @@ from enum import Enumfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, Literal, Union, get_args, get_origin+from mthds.protocol.problem.registry import CoreCodefrom pydantic import ValidationErrorfrom pipelex.core.stuffs.list_content import ListContent@@ -122,14 +123,14 @@ def _assert_single_char_delimiter(delimiter: str) -> None:"""if len(delimiter) != 1:msg = f"CSV delimiter must be a single character, got {delimiter!r}."- raise CsvError(msg)+ raise CsvError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)if delimiter in {"\n", "\r"}:msg = f"CSV delimiter cannot be a newline character, got {delimiter!r}."- raise CsvError(msg)+ raise CsvError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)if delimiter == '"':# The default quote character; csv raises "bad delimiter or quotechar value" if they collide.msg = f"CSV delimiter cannot be the quote character, got {delimiter!r}."- raise CsvError(msg)+ raise CsvError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)def _validate_header(header: list[str], *, path: Path) -> None:@@ -249,13 +250,13 @@ def write_rows(writer.writerow([row.get(column, "") for column in headers])except LookupError as exc:msg = f"Unknown encoding {encoding!r} for CSV file {path}: {exc}"- raise CsvError(msg) from exc+ raise CsvError(msg).with_error_code(CoreCode.REQUEST_INVALID) from excexcept UnicodeEncodeError as exc:msg = f"Could not encode CSV file {path} as {encoding}: {exc}"- raise CsvError(msg) from exc+ raise CsvError(msg).with_error_code(CoreCode.REQUEST_INVALID) from excexcept OSError as exc:msg = f"Could not write CSV file {path}: {exc}"- raise CsvError(msg) from exc+ raise CsvError(msg).with_error_code(CoreCode.REQUEST_INVALID) from exc# ---------------------------------------------------------------------------------------@@ -406,7 +407,7 @@ def csv_from_list_content(for item_index, item in enumerate(list_content.items):if not isinstance(item, row_model):msg = f"Cannot write CSV: item {item_index} is a {type(item).__name__}, not the declared row model {row_model.__name__!r}."- raise CsvError(msg)+ raise CsvError(msg).with_error_code(CoreCode.RUNTIME_UNEXPECTED)dumped = item.model_dump(mode="json")rows.append({field_name: _to_cell(dumped.get(field_name)) for field_name in headers})write_rows(path=path, headers=headers, rows=rows, delimiter=delimiter, encoding=encoding)diff --git a/pipelex/tools/tabular/exceptions.py b/pipelex/tools/tabular/exceptions.pyindex 0838c9969..6e827e5e8 100644--- a/pipelex/tools/tabular/exceptions.py+++ b/pipelex/tools/tabular/exceptions.py@@ -1,17 +1,24 @@-from pipelex.base_exceptions import ErrorDomain+from typing import ClassVar++from mthds.protocol.problem.registry import CoreCode++from pipelex.errors.error_code_declaration import ErrorCodeDeclaration, ErrorCodeSetfrom pipelex.system.exceptions import ToolErrorclass CsvError(ToolError):- """Base for CSV codec errors.+ """Base for CSV codec errors, also raised directly.- CSV problems are caller-fixable input issues (a missing/unreadable file, a header- that does not match the row concept, a cell that cannot be coerced), so the whole- family is classified under the ``INPUT`` error domain.+ CSV problems are mostly caller-fixable input issues (a missing/unreadable file, a header+ that does not match the row concept, a cell that cannot be coerced), so the default is+ ``input.invalid``. Writing a table the CLI's ``--save-csv`` asked for is+ ``request.invalid``, and a delimiter or a row the codec was handed by its own caller is+ ``runtime.unexpected``."""- error_domain = ErrorDomain.INPUT- _declared_title = "CSV error"+ error_code: ClassVar[ErrorCodeDeclaration] = ErrorCodeSet(+ default=CoreCode.INPUT_INVALID, others=(CoreCode.REQUEST_INVALID, CoreCode.RUNTIME_UNEXPECTED)+ )# The whole family describes faults in the caller's OWN CSV input (a missing file, a header that# does not match the concept, a cell that will not coerce), so the message is safe and useful to# expose. Opt in so STRICT disclosure keeps it instead of redacting it to a generic placeholder.@@ -26,7 +33,7 @@ class CsvReadError(CsvError):third-party exception escapes into core/runner."""- _declared_title = "CSV read error"+ error_code = CoreCode.INPUT_FILE_UNREADABLEclass CsvFlatnessError(CsvError):@@ -38,7 +45,7 @@ class CsvFlatnessError(CsvError):offending field and telling the author to project to a flat concept first."""- _declared_title = "CSV flatness error"+ error_code = CoreCode.INPUT_INVALIDclass CsvColumnError(CsvError):@@ -50,7 +57,7 @@ class CsvColumnError(CsvError):that default."""- _declared_title = "CSV column error"+ error_code = CoreCode.INPUT_INVALIDclass CsvCoercionError(CsvError):@@ -60,4 +67,4 @@ class CsvCoercionError(CsvError):the offending cell."""- _declared_title = "CSV coercion error"+ error_code = CoreCode.INPUT_INVALIDdiff --git a/pipelex/tools/typing/exceptions.py b/pipelex/tools/typing/exceptions.pyindex 7224078de..e0329ca8b 100644--- a/pipelex/tools/typing/exceptions.py+++ b/pipelex/tools/typing/exceptions.py@@ -1,5 +1,9 @@+from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import PipelexErrorclass ModuleFileError(PipelexError):"""Exception raised for errors related to module file operations."""++ error_code = CoreCode.RUNTIME_UNEXPECTEDdiff --git a/pipelex/tools/uri/exceptions.py b/pipelex/tools/uri/exceptions.pyindex 0eda7a796..669bd7fbd 100644--- a/pipelex/tools/uri/exceptions.py+++ b/pipelex/tools/uri/exceptions.py@@ -1,6 +1,9 @@from enum import StrEnum-from pipelex.base_exceptions import ErrorDomain, SecurityError+from mthds.protocol.problem.registry import CoreCode++from pipelex.base_exceptions import SecurityError+from pipelex.errors.error_code_declaration import ErrorCodeSetclass UriReadRefusalReason(StrEnum):@@ -28,16 +31,16 @@ class UriReadRefusedError(SecurityError):result — so the refusal happens where the value is read, whichever pipe produced it.A :class:`SecurityError`, so that a domain-level ``except`` around a read cannot swallow it.- ``error_domain = INPUT``, answered as a 422, because the method or its inputs asked for the- read and the caller fixes it by passing the file as an input or an upload. The message is+ The default is ``security.input_url_refused``, answered as a 422: an input asked for the read+ and the caller fixes it by passing the file as an input or an upload. A raise or catch site that+ knows the method named the URL chooses ``security.method_url_refused``. The message iscaller-facing and keeps its text under STRICT disclosure: it names where the URL sat (animage of a pipe's prompt, an input) and why it was refused, and quotes neither the URL nor theread scope. The refusal happens before any IO, so it says nothing about whether the fileexists."""- error_domain = ErrorDomain.INPUT- _declared_title = "Read outside the run's scope refused"+ error_code = ErrorCodeSet(default=CoreCode.SECURITY_INPUT_URL_REFUSED, others=(CoreCode.SECURITY_METHOD_URL_REFUSED,))_authors_caller_facing_message = Truedef __init__(self, message: str, *, reason: UriReadRefusalReason):diff --git a/pipelex/tools/uri/uri_base64.py b/pipelex/tools/uri/uri_base64.pyindex 63cebcebe..3c3d7276c 100644--- a/pipelex/tools/uri/uri_base64.py+++ b/pipelex/tools/uri/uri_base64.py@@ -10,6 +10,7 @@ from pathlib import Pathfrom pipelex.tools.misc.base64_utils import make_base64_url_from_bytes, make_base64_url_from_pathfrom pipelex.tools.misc.file_fetch_utils import fetch_file_from_url_httpx+from pipelex.tools.storage.exceptions import StorageNotConfiguredErrorfrom pipelex.tools.storage.storage_provider_abstract import StorageProviderAbstractfrom pipelex.tools.uri.resolved_uri import (ResolvedBase64DataUrl,@@ -52,7 +53,7 @@ async def make_base64_url_from_any_uri(A base64 data URL string containing the base64-encoded data, whichever way we got it.Raises:- ValueError: If the URI is a pipelex-storage:// URI and no storage provider is given.+ StorageNotConfiguredError: If the URI is a pipelex-storage:// URI and no storage provider is given.SsrfBlockedError: If the URI is an http(s) URL whose destination, or a redirect hop's,is a private, loopback, link-local or metadata address."""@@ -69,7 +70,7 @@ async def make_base64_url_from_any_uri(case ResolvedPipelexStorage():if storage_provider is None:msg = f"Cannot convert pipelex-storage:// URI to base64 without a storage provider: {uri}"- raise ValueError(msg)+ raise StorageNotConfiguredError(msg)raw_bytes = await storage_provider.load(uri=resolved_uri.storage_uri)base64_url = make_base64_url_from_bytes(raw_bytes=raw_bytes)return base64_urldiff --git a/pipelex/tools/uri/uri_bytes.py b/pipelex/tools/uri/uri_bytes.pyindex e72fa35ed..2a1d36362 100644--- a/pipelex/tools/uri/uri_bytes.py+++ b/pipelex/tools/uri/uri_bytes.py@@ -18,6 +18,7 @@ from typing import NamedTuplefrom pipelex.tools.misc.file_fetch_utils import fetch_file_and_content_type_from_url_httpxfrom pipelex.tools.misc.file_utils import load_binary_asyncfrom pipelex.tools.misc.filetype_utils import base_mime_type+from pipelex.tools.storage.exceptions import StorageNotConfiguredErrorfrom pipelex.tools.storage.storage_provider_abstract import StorageProviderAbstractfrom pipelex.tools.uri.resolved_uri import (ResolvedBase64DataUrl,@@ -53,7 +54,7 @@ async def load_bytes_and_mime_type_from_any_uri(Required when the URI is a pipelex-storage:// URI.Raises:- ValueError: If the URI is a pipelex-storage:// URI and no storage provider is given.+ StorageNotConfiguredError: If the URI is a pipelex-storage:// URI and no storage provider is given.RemoteFileFetchError: The server answered with an error status, refused the connection, or did not answer in time.SsrfBlockedError: The destination, or a redirect hop's, is a private, loopback, link-local or metadata address."""@@ -72,7 +73,7 @@ async def load_bytes_and_mime_type_from_any_uri(case ResolvedPipelexStorage():if storage_provider is None:msg = f"Cannot load a pipelex-storage:// URI without a storage provider: {uri}"- raise ValueError(msg)+ raise StorageNotConfiguredError(msg)raw_bytes, declared_mime_type = await storage_provider.load_with_metadata(uri=resolved_uri.storage_uri)mime_type = base_mime_type(mime_type=declared_mime_type) if declared_mime_type else Nonereturn UriBytes(data=raw_bytes, mime_type=mime_type or None)@@ -86,7 +87,7 @@ async def load_bytes_from_any_uri("""Load the bytes a URI points at, whichever kind of URI it is, for a caller that has no use for their media type.Raises:- ValueError: If the URI is a pipelex-storage:// URI and no storage provider is given.+ StorageNotConfiguredError: If the URI is a pipelex-storage:// URI and no storage provider is given.RemoteFileFetchError: The server answered with an error status, refused the connection, or did not answer in time.SsrfBlockedError: The destination, or a redirect hop's, is a private, loopback, link-local or metadata address."""diff --git a/pipelex/tracing/exceptions.py b/pipelex/tracing/exceptions.pyindex 7da25a7d1..b38ffea4c 100644--- a/pipelex/tracing/exceptions.py+++ b/pipelex/tracing/exceptions.py@@ -1,9 +1,16 @@+from typing import ClassVar++from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import PipelexError+from pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeDeclarationclass EventLogError(PipelexError):"""Base error for trace-event log backend failures."""+ error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERROR+class EventLogReadError(EventLogError):"""Raised when reading trace events from the configured backend fails.@@ -14,8 +21,13 @@ class EventLogReadError(EventLogError):best-effort observability callers — graph assembly degrades to ``None``rather than failing the pipeline run — catch a single Pipelex error insteadof re-widening their ``except`` clauses to raw third-party exception types.++ Its causes mix throttling and network failures, which pass, with a refused credential; the code follows+ the common case, and the cause rides the report's diagnostics."""+ error_code = CoreCode.RUNTIME_UNAVAILABLE+class EventLogSchemaMismatchError(EventLogReadError):"""Raised when a trace event is well-formed JSON the current models refuse.@@ -29,6 +41,8 @@ class EventLogSchemaMismatchError(EventLogReadError):truncated version of the record returns none of it, and says why."""+ error_code = CoreCode.RUNTIME_UNEXPECTED+class EventLogSetupError(EventLogError):"""Raised when constructing the configured event-log backend fails.@@ -42,6 +56,8 @@ class EventLogSetupError(EventLogError):aborting the pipeline run."""+ error_code = CoreCode.RUNTIME_MISCONFIGURED+class TraceEventModeError(PipelexError):"""Raised when a set of trace events states no single run mode to build a graph in.@@ -51,3 +67,5 @@ class TraceEventModeError(PipelexError):more than one run, such as a dry run and a live run written under one pipeline run id, and an empty set states nomode at all: neither describes one run, so the assembler builds no graph from it rather than guess its mode."""++ error_code = CoreCode.RUNTIME_UNEXPECTEDdiff --git a/pyproject.toml b/pyproject.tomlindex 47141bb15..ff4b9409e 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -31,7 +31,7 @@ dependencies = ["json2html>=1.3.0","kajson==0.7.1","markdown-it-py[linkify]>=3.0.0", # the Markdown concept, the `markdown` filter and the built-in PDF engine- "mthds==0.22.0",+ "mthds==0.22.1","networkx>=3.4.2","openai>=2.0.0","packaging>=24.0", # reads a method's requirements.txt: PEP 508 requirements, markers and versions@@ -44,7 +44,7 @@ dependencies = [# The client for the hosted Pipelex API, behind hosted runs (pipelex/hosted/). Pinned exactly, like# mthds: each pipelex-sdk release pins mthds exactly too, so the release chosen here must pin the# same mthds as this file, and the two pins move together (the bump-mthds skill says so).- "pipelex-sdk==0.45.0",+ "pipelex-sdk==0.46.0","polyfactory>=2.21.0","portkey-ai>=2.1.0","posthog>=6.7.0",diff --git a/subject_grants.toml b/subject_grants.tomlindex bf930a8ab..91a4d7a24 100644--- a/subject_grants.toml+++ b/subject_grants.toml@@ -1,5 +1,9 @@version = 1+["pipelex/base_exceptions.py::ErrorDomain.from_problem_domain"]+param = "problem_domain"+rationale = "Converts its one operand, a registry domain: ErrorDomain.from_problem_domain(spec.domain) reads as a conversion."+["pipelex/base_exceptions.py::ErrorReport.from_dict"]param = "data"rationale = "Factory from source: builds the report from the dict; single operand."@@ -8,9 +12,9 @@ rationale = "Factory from source: builds the report from the dict; single operanparam = "report"rationale = "Verb-object: enriches the report; single operand."-["pipelex/base_exceptions.py::_humanize_class_name"]-param = "class_name"-rationale = "Transforms the class name into a human title; single operand."+["pipelex/base_exceptions.py::PipelexError.with_error_code"]+param = "error_code"+rationale = "Chained at every raise site on its one operand, the chosen code: raise SomeError(msg).with_error_code(CoreCode.INPUT_MISSING)."["pipelex/base_exceptions.py::_redact_provider_metadata_for_strict"]param = "metadata_payload"@@ -3024,6 +3028,50 @@ rationale = "Verb-object: renders the stuff; options stay keyword."param = "cls"rationale = "Predicate on the error class; single operand."+["pipelex/errors/error_code_declaration.py::declared_error_codes"]+param = "declaration"+rationale = "Lists the codes of its one operand, a class's declaration: declared_error_codes(cls.error_code)."++["pipelex/errors/error_code_declaration.py::describe_error_code_declaration"]+param = "declaration"+rationale = "Describes its one operand, a class's declaration: describe_error_code_declaration(cls.error_code)."++["pipelex/errors/error_code_sites.py::_chosen_code"]+param = "call"+rationale = "Reads the code its one operand, a with_error_code call node, chooses: _chosen_code(call)."++["pipelex/errors/error_code_sites.py::constructed_class_name"]+param = "node"+rationale = "Names the class its one operand, an AST expression, constructs: constructed_class_name(node)."++["pipelex/errors/error_codes.py::error_code_spec"]+param = "code"+rationale = "Looks up its one operand, a code: error_code_spec(code) reads as the code's spec."++["pipelex/errors/error_codes.py::parse_error_code"]+param = "value"+rationale = "Parses its one operand, a code string: parse_error_code(value) reads as a parse."++["pipelex/errors/foreign_raises.py::_decorator_names"]+param = "function"+rationale = "Lists the decorators of its one operand, a function node: _decorator_names(function)."++["pipelex/errors/foreign_raises.py::_expression_name"]+param = "node"+rationale = "Names its one operand, an AST expression: _expression_name(node), applied recursively."++["pipelex/errors/foreign_raises.py::_raised_class_name"]+param = "node"+rationale = "Names the class its one operand, a raise's expression, constructs: _raised_class_name(node.exc)."++["pipelex/errors/retired_error_pages.py::_code_page_target"]+param = "code"+rationale = "Maps its one operand, a code, to its page: _code_page_target(code)."++["pipelex/errors/retired_error_pages.py::_representative_code"]+param = "cls"+rationale = "Picks the code of its one operand, an error class: _representative_code(cls)."+["pipelex/fix_ops/applier.py::_as_tomlkit_value"]param = "value"rationale = "Single-operand conversion of the value."@@ -4780,14 +4828,6 @@ rationale = "Submits the img-gen job and returns its result; single operand."param = "registrar"rationale = "Plugin protocol register: the registrar is the sole sink the plugin populates."-["pipelex/providers/fal/fal_poller.py::FalPoller._is_transient_http"]-param = "exc"-rationale = "Predicate on the exc; single operand."--["pipelex/providers/fal/fal_poller.py::FalPoller.poll_queue_until_complete"]-param = "response_dict"-rationale = "Parses/consumes the response_dict; single operand."-["pipelex/providers/google/google_config.py::GoogleConfig.get_reasoning_level"]param = "effort"rationale = "Maps the reasoning effort to a provider reasoning level; single operand."diff --git a/tests/data/errors/error_identity.txt b/tests/data/errors/error_identity.txtindex eaae7c828..5b9a17356 100644--- a/tests/data/errors/error_identity.txt+++ b/tests/data/errors/error_identity.txt@@ -1,389 +1,405 @@-# Wire identity of every PipelexError subclass: error_type | title | type_uri+# Wire identity of every PipelexError subclass: error_type | code declaration## `error_type` is the Python class name, verbatim — base_exceptions.py builds it as# `type(self).__name__`. Consumers outside this repo switch on that string, so renaming# an error class is a wire break that no build anywhere catches: they stay green and-# silently fall through to a generic branch. A diff in this file IS that wire break.+# silently fall through to a generic branch. The declaration is the registry code the+# class raises, the set its raise sites choose from, the cause it takes its code from,+# or `abstract`; a change to it changes what every reader of the code is told to do.+# A diff in this file IS that wire change.## Generated — do not hand-edit. Regenerate with `make generate-error-identity` (alias `make gei`).# Verified by tests/unit/pipelex/errors/test_error_identity_snapshot.py.-AmbiguousInputsFilesError | Ambiguous inputs files | https://docs.pipelex.com/latest/errors/ambiguous-inputs-files-error/-AnthropicFactoryError | Anthropic factory | https://docs.pipelex.com/latest/errors/anthropic-factory-error/-AnthropicModelListingError | Anthropic model listing | https://docs.pipelex.com/latest/errors/anthropic-model-listing-error/-AnthropicSDKUnsupportedError | Anthropic SDK unsupported | https://docs.pipelex.com/latest/errors/anthropic-sdk-unsupported-error/-AnthropicWorkerConfigurationError | Anthropic worker configuration | https://docs.pipelex.com/latest/errors/anthropic-worker-configuration-error/-ArgumentTypeError | Argument type | https://docs.pipelex.com/latest/errors/argument-type-error/-AsyncExecutionNotEnabledError | Async execution not enabled | https://docs.pipelex.com/latest/errors/async-execution-not-enabled-error/-AutoDetectedInputsFileError | Auto-detected inputs file is not a regular file | https://docs.pipelex.com/latest/errors/auto-detected-inputs-file-error/-AwsCredentialsError | Aws credentials | https://docs.pipelex.com/latest/errors/aws-credentials-error/-AzureCredentialsError | Azure credentials | https://docs.pipelex.com/latest/errors/azure-credentials-error/-BatchParamsError | Batch params | https://docs.pipelex.com/latest/errors/batch-params-error/-BedrockFactoryError | Bedrock factory | https://docs.pipelex.com/latest/errors/bedrock-factory-error/-BedrockWorkerConfigurationError | Bedrock worker configuration | https://docs.pipelex.com/latest/errors/bedrock-worker-configuration-error/-BindingPathUnresolvedError | Binding path unresolved | https://docs.pipelex.com/latest/errors/binding-path-unresolved-error/-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/-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/-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/-CogtError | AI inference failed | https://docs.pipelex.com/latest/errors/cogt-error/-ConceptCodeError | Concept code | https://docs.pipelex.com/latest/errors/concept-code-error/-ConceptError | Concept error | https://docs.pipelex.com/latest/errors/concept-error/-ConceptFactoryError | Concept factory | https://docs.pipelex.com/latest/errors/concept-factory-error/-ConceptLibraryConceptNotFoundError | Concept library concept not found | https://docs.pipelex.com/latest/errors/concept-library-concept-not-found-error/-ConceptLibraryError | Concept library | https://docs.pipelex.com/latest/errors/concept-library-error/-ConceptLoadingError | Concept loading | https://docs.pipelex.com/latest/errors/concept-loading-error/-ConceptRefAmbiguousError | Concept ref ambiguous | https://docs.pipelex.com/latest/errors/concept-ref-ambiguous-error/-ConceptRefineError | Concept refine | https://docs.pipelex.com/latest/errors/concept-refine-error/-ConceptStringError | Concept string | https://docs.pipelex.com/latest/errors/concept-string-error/-ConceptStructureGeneratorError | Concept structure generator | https://docs.pipelex.com/latest/errors/concept-structure-generator-error/-ConceptStructureValidationError | Concept structure validation | https://docs.pipelex.com/latest/errors/concept-structure-validation-error/-ConfigValidationError | Config validation | https://docs.pipelex.com/latest/errors/config-validation-error/-ConstructFieldBlueprintTypeError | Construct field blueprint type | https://docs.pipelex.com/latest/errors/construct-field-blueprint-type-error/-ConstructFieldBlueprintValueError | Construct field blueprint value | https://docs.pipelex.com/latest/errors/construct-field-blueprint-value-error/-ContextProviderError | 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/-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/-CsvColumnError | CSV column error | https://docs.pipelex.com/latest/errors/csv-column-error/-CsvError | CSV error | https://docs.pipelex.com/latest/errors/csv-error/-CsvFlatnessError | CSV flatness error | https://docs.pipelex.com/latest/errors/csv-flatness-error/-CsvReadError | CSV read error | https://docs.pipelex.com/latest/errors/csv-read-error/-DateContentError | Date content | https://docs.pipelex.com/latest/errors/date-content-error/-DeliveryError | Delivery | https://docs.pipelex.com/latest/errors/delivery-error/-DocGenEngineMissingError | Doc gen engine missing | https://docs.pipelex.com/latest/errors/doc-gen-engine-missing-error/-DocGenHandleNotFoundError | Doc gen handle not found | https://docs.pipelex.com/latest/errors/doc-gen-handle-not-found-error/-DocGenModelCapabilityError | Doc gen model capability | https://docs.pipelex.com/latest/errors/doc-gen-model-capability-error/-DocGenRenderError | Doc gen render | https://docs.pipelex.com/latest/errors/doc-gen-render-error/-DomainCodeError | Domain code | https://docs.pipelex.com/latest/errors/domain-code-error/-DomainFactoryError | Domain factory | https://docs.pipelex.com/latest/errors/domain-factory-error/-DomainLibraryError | Domain library | https://docs.pipelex.com/latest/errors/domain-library-error/-DomainLoadingError | Domain loading | https://docs.pipelex.com/latest/errors/domain-loading-error/-DriftAckError | Drift ack | https://docs.pipelex.com/latest/errors/drift-ack-error/-DriftError | Drift | https://docs.pipelex.com/latest/errors/drift-error/-DriftGitError | Drift git | https://docs.pipelex.com/latest/errors/drift-git-error/-DriftManifestError | Drift manifest | https://docs.pipelex.com/latest/errors/drift-manifest-error/-DryRunError | Dry run | https://docs.pipelex.com/latest/errors/dry-run-error/-DryRunGraphNotProducedError | Dry run graph not produced | https://docs.pipelex.com/latest/errors/dry-run-graph-not-produced-error/-DryRunMockBuildError | Dry run mock build | https://docs.pipelex.com/latest/errors/dry-run-mock-build-error/-DryRunObjectFidelityError | Dry run object fidelity | https://docs.pipelex.com/latest/errors/dry-run-object-fidelity-error/-DuplicateBundleValidatorError | Duplicate bundle validator | https://docs.pipelex.com/latest/errors/duplicate-bundle-validator-error/-DuplicateDocGenDefaultError | Duplicate doc gen default | https://docs.pipelex.com/latest/errors/duplicate-doc-gen-default-error/-DuplicateHttpErrorMapperError | Duplicate http error mapper | https://docs.pipelex.com/latest/errors/duplicate-http-error-mapper-error/-DuplicateInferenceBackendError | Duplicate inference backend | https://docs.pipelex.com/latest/errors/duplicate-inference-backend-error/-DuplicateInternalModelError | Duplicate internal model | https://docs.pipelex.com/latest/errors/duplicate-internal-model-error/-DuplicateLogSinkError | Duplicate log sink | https://docs.pipelex.com/latest/errors/duplicate-log-sink-error/-DuplicateModelListerError | Duplicate model lister | https://docs.pipelex.com/latest/errors/duplicate-model-lister-error/-DuplicateOrchestratorError | Duplicate orchestrator | https://docs.pipelex.com/latest/errors/duplicate-orchestrator-error/-DuplicatePipeFuncExecutorError | Duplicate pipe func executor | https://docs.pipelex.com/latest/errors/duplicate-pipe-func-executor-error/-DuplicatePipeFuncPackageOfferError | Duplicate pipe func package offer | https://docs.pipelex.com/latest/errors/duplicate-pipe-func-package-offer-error/-DuplicateSecretsProviderError | Duplicate secrets provider | https://docs.pipelex.com/latest/errors/duplicate-secrets-provider-error/-DuplicateServiceErrorCodeError | Duplicate service error code | https://docs.pipelex.com/latest/errors/duplicate-service-error-code-error/-DuplicateStorageProviderError | Duplicate storage provider | https://docs.pipelex.com/latest/errors/duplicate-storage-provider-error/-EmptyMethodTreeError | Empty method tree | https://docs.pipelex.com/latest/errors/empty-method-tree-error/-EntryPipeAmbiguousError | Entry pipe ambiguous | https://docs.pipelex.com/latest/errors/entry-pipe-ambiguous-error/-EntryPipeNotFoundError | Entry pipe not found | https://docs.pipelex.com/latest/errors/entry-pipe-not-found-error/-EnvVarNotFoundError | Environment variable not set | https://docs.pipelex.com/latest/errors/env-var-not-found-error/-ErrorRegistryError | Error registry | https://docs.pipelex.com/latest/errors/error-registry-error/-EventLogError | Event log | https://docs.pipelex.com/latest/errors/event-log-error/-EventLogReadError | Event log read | https://docs.pipelex.com/latest/errors/event-log-read-error/-EventLogSchemaMismatchError | Event log schema mismatch | https://docs.pipelex.com/latest/errors/event-log-schema-mismatch-error/-EventLogSetupError | Event log setup | https://docs.pipelex.com/latest/errors/event-log-setup-error/-ExplicitConceptIncompatibleError | Explicit concept incompatible | https://docs.pipelex.com/latest/errors/explicit-concept-incompatible-error/-ExtractCapabilityError | Extract capability | https://docs.pipelex.com/latest/errors/extract-capability-error/-ExtractHandleNotFoundError | Extract handle not found | https://docs.pipelex.com/latest/errors/extract-handle-not-found-error/-ExtractInputError | Extract input | https://docs.pipelex.com/latest/errors/extract-input-error/-ExtractInputFormatError | Extract input format | https://docs.pipelex.com/latest/errors/extract-input-format-error/-ExtractJobFailureError | Extract job failure | https://docs.pipelex.com/latest/errors/extract-job-failure-error/-ExtractModelNotFoundError | Extract model not found | https://docs.pipelex.com/latest/errors/extract-model-not-found-error/-ExtractOutputError | Extract output | https://docs.pipelex.com/latest/errors/extract-output-error/-FalCredentialsError | Fal credentials | https://docs.pipelex.com/latest/errors/fal-credentials-error/-FatalError | Fatal error | https://docs.pipelex.com/latest/errors/fatal-error/-FileTypeError | File type | https://docs.pipelex.com/latest/errors/file-type-error/-FixTransactionError | Fix transaction | https://docs.pipelex.com/latest/errors/fix-transaction-error/-FixWriteConflictError | Fix write conflict | https://docs.pipelex.com/latest/errors/fix-write-conflict-error/-FormerReleaseConfigError | Configuration left by a former release | https://docs.pipelex.com/latest/errors/former-release-config-error/-FunctionNamesMigrationError | Function names migration error | https://docs.pipelex.com/latest/errors/function-names-migration-error/-GcpLogSinkCredentialsError | Log sink credentials missing or refused | https://docs.pipelex.com/latest/errors/gcp-log-sink-credentials-error/-GeneratedImageError | Generated image | https://docs.pipelex.com/latest/errors/generated-image-error/-GoogleImgGenWorkerError | Google img gen worker | https://docs.pipelex.com/latest/errors/google-img-gen-worker-error/-GoogleLLMWorkerError | Google LLM worker | https://docs.pipelex.com/latest/errors/google-llm-worker-error/-GraphSpecError | Graph spec | https://docs.pipelex.com/latest/errors/graph-spec-error/-GraphSpecValidationError | Graph spec validation | https://docs.pipelex.com/latest/errors/graph-spec-validation-error/-HostLibraryRequirementsError | Host library requirements | https://docs.pipelex.com/latest/errors/host-library-requirements-error/-HostLibraryTreeError | Host library tree | https://docs.pipelex.com/latest/errors/host-library-tree-error/-HostedBaseUrlError | Hosted base url | https://docs.pipelex.com/latest/errors/hosted-base-url-error/-HostedLocalFileUploadUnavailableError | Hosted local file upload unavailable | https://docs.pipelex.com/latest/errors/hosted-local-file-upload-unavailable-error/-HostedMethodInvalidError | Hosted method invalid | https://docs.pipelex.com/latest/errors/hosted-method-invalid-error/-HostedRunError | Hosted run error | https://docs.pipelex.com/latest/errors/hosted-run-error/-HostedRunInterruptedError | Hosted run interrupted | https://docs.pipelex.com/latest/errors/hosted-run-interrupted-error/-HostedRunOutcomeUnknownError | Hosted run outcome unknown | https://docs.pipelex.com/latest/errors/hosted-run-outcome-unknown-error/-HostedRunPollingError | Hosted run polling | https://docs.pipelex.com/latest/errors/hosted-run-polling-error/-HostedRunSourceError | Hosted run source | https://docs.pipelex.com/latest/errors/hosted-run-source-error/-HubSlotAlreadyClaimedError | Hub slot already claimed | https://docs.pipelex.com/latest/errors/hub-slot-already-claimed-error/-ImageContentError | Image content | https://docs.pipelex.com/latest/errors/image-content-error/-ImgGenGeneratedTypeError | Img gen generated type | https://docs.pipelex.com/latest/errors/img-gen-generated-type-error/-ImgGenGenerationError | Img gen generation | https://docs.pipelex.com/latest/errors/img-gen-generation-error/-ImgGenHandleNotFoundError | Img gen handle not found | https://docs.pipelex.com/latest/errors/img-gen-handle-not-found-error/-ImgGenModelNotFoundError | Img gen model not found | https://docs.pipelex.com/latest/errors/img-gen-model-not-found-error/-ImgGenParameterError | Img gen parameter | https://docs.pipelex.com/latest/errors/img-gen-parameter-error/-ImgGenPromptError | Img gen prompt | https://docs.pipelex.com/latest/errors/img-gen-prompt-error/-ImgGenSettingsValidationError | Img gen settings validation | https://docs.pipelex.com/latest/errors/img-gen-settings-validation-error/-InferenceBackendCredentialsError | Inference backend credentials | https://docs.pipelex.com/latest/errors/inference-backend-credentials-error/-InferenceBackendLibraryError | Inference backend library | https://docs.pipelex.com/latest/errors/inference-backend-library-error/-InferenceBackendLibraryNotFoundError | Inference backend library not found | https://docs.pipelex.com/latest/errors/inference-backend-library-not-found-error/-InferenceBackendLibraryValidationError | Inference backend library validation | https://docs.pipelex.com/latest/errors/inference-backend-library-validation-error/-InferenceBackendNotFoundError | Inference backend not found | https://docs.pipelex.com/latest/errors/inference-backend-not-found-error/-InferenceModelSpecError | Inference model spec | https://docs.pipelex.com/latest/errors/inference-model-spec-error/-InputShapingError | Input shaping | https://docs.pipelex.com/latest/errors/input-shaping-error/-InputStuffSpecNotFoundError | Input stuff spec not found | https://docs.pipelex.com/latest/errors/input-stuff-spec-not-found-error/-InputStuffSpecsError | Input stuff specs | https://docs.pipelex.com/latest/errors/input-stuff-specs-error/-InputStuffSpecsFactoryError | Input stuff specs factory | https://docs.pipelex.com/latest/errors/input-stuff-specs-factory-error/-InvocationPathError | Invocation path not derivable | https://docs.pipelex.com/latest/errors/invocation-path-error/-Jinja2ContextError | Jinja 2 context | https://docs.pipelex.com/latest/errors/jinja2-context-error/-Jinja2DetectVariablesError | Jinja 2 detect variables | https://docs.pipelex.com/latest/errors/jinja2-detect-variables-error/-Jinja2StuffError | Jinja 2 stuff | https://docs.pipelex.com/latest/errors/jinja2-stuff-error/-Jinja2TemplateBudgetError | Template render budget exceeded | https://docs.pipelex.com/latest/errors/jinja2-template-budget-error/-Jinja2TemplateRenderError | Jinja 2 template render | https://docs.pipelex.com/latest/errors/jinja2-template-render-error/-Jinja2TemplateSecurityError | Jinja 2 template security | https://docs.pipelex.com/latest/errors/jinja2-template-security-error/-Jinja2TemplateSyntaxError | Jinja 2 template syntax | https://docs.pipelex.com/latest/errors/jinja2-template-syntax-error/-JobMetadataError | Job metadata | https://docs.pipelex.com/latest/errors/job-metadata-error/-JsonTypeError | Json type | https://docs.pipelex.com/latest/errors/json-type-error/-JudgmentAnswerMismatchError | Judgment answer mismatch | https://docs.pipelex.com/latest/errors/judgment-answer-mismatch-error/-JudgmentCapabilityError | Judgment capability | https://docs.pipelex.com/latest/errors/judgment-capability-error/-JudgmentHandleNotFoundError | Judgment handle not found | https://docs.pipelex.com/latest/errors/judgment-handle-not-found-error/-JudgmentJobFailureError | Judgment job failure | https://docs.pipelex.com/latest/errors/judgment-job-failure-error/-JudgmentModelMissingError | Judgment model missing | https://docs.pipelex.com/latest/errors/judgment-model-missing-error/-JudgmentModelNotFoundError | Judgment model not found | https://docs.pipelex.com/latest/errors/judgment-model-not-found-error/-JudgmentRefusedError | Judgment refused | https://docs.pipelex.com/latest/errors/judgment-refused-error/-KitError | Kit | https://docs.pipelex.com/latest/errors/kit-error/-KitIndexLoadingError | Kit index loading | https://docs.pipelex.com/latest/errors/kit-index-loading-error/-LLMAssignmentError | LLM assignment | https://docs.pipelex.com/latest/errors/llm-assignment-error/-LLMCapabilityError | LLM capability | https://docs.pipelex.com/latest/errors/llm-capability-error/-LLMCompletionError | LLM completion | https://docs.pipelex.com/latest/errors/llm-completion-error/-LLMCompletionRefusedError | LLM completion refused | https://docs.pipelex.com/latest/errors/llm-completion-refused-error/-LLMCompletionTruncatedError | LLM completion truncated | https://docs.pipelex.com/latest/errors/llm-completion-truncated-error/-LLMConfigError | LLM config | https://docs.pipelex.com/latest/errors/llm-config-error/-LLMHandleNotFoundError | LLM handle not found | https://docs.pipelex.com/latest/errors/llm-handle-not-found-error/-LLMModelNotFoundError | LLM model not found | https://docs.pipelex.com/latest/errors/llm-model-not-found-error/-LLMPromptParameterError | LLM prompt parameter | https://docs.pipelex.com/latest/errors/llm-prompt-parameter-error/-LLMPromptSpecError | LLM prompt spec | https://docs.pipelex.com/latest/errors/llm-prompt-spec-error/-LLMSettingRefusedError | LLM setting refused | https://docs.pipelex.com/latest/errors/llm-setting-refused-error/-LLMSettingsValidationError | LLM settings validation | https://docs.pipelex.com/latest/errors/llm-settings-validation-error/-LangfuseCredentialsError | Langfuse credentials | https://docs.pipelex.com/latest/errors/langfuse-credentials-error/-LibraryError | Library error | https://docs.pipelex.com/latest/errors/library-error/-LibraryLoadingError | Library loading | https://docs.pipelex.com/latest/errors/library-loading-error/-LinkupError | Linkup | https://docs.pipelex.com/latest/errors/linkup-error/-LinkupSearchEmptyResultError | Linkup search empty result | https://docs.pipelex.com/latest/errors/linkup-search-empty-result-error/-LinkupSearchResponseError | Linkup search response | https://docs.pipelex.com/latest/errors/linkup-search-response-error/-ListWhereSingularError | List where singular | https://docs.pipelex.com/latest/errors/list-where-singular-error/-LogSinkHeaderValueError | Log sink header value holds a line break | https://docs.pipelex.com/latest/errors/log-sink-header-value-error/-LogSinkVariableError | Log sink variable did not resolve | https://docs.pipelex.com/latest/errors/log-sink-variable-error/-MarkdownFormattingBudgetError | Markdown formatting budget exceeded | https://docs.pipelex.com/latest/errors/markdown-formatting-budget-error/-MethodDependencyFetchError | Method dependency fetch | https://docs.pipelex.com/latest/errors/method-dependency-fetch-error/-MethodDependencyNotShippedError | Method dependency not shipped | https://docs.pipelex.com/latest/errors/method-dependency-not-shipped-error/-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/-MethodPackageSymlinkError | Method package symlink | https://docs.pipelex.com/latest/errors/method-package-symlink-error/-MethodPackageTooLargeError | Method package too large | https://docs.pipelex.com/latest/errors/method-package-too-large-error/-MethodRefError | Method reference error | https://docs.pipelex.com/latest/errors/method-ref-error/-MethodRefParseError | Method ref parse | https://docs.pipelex.com/latest/errors/method-ref-parse-error/-MethodRequirementsError | Method requirements | https://docs.pipelex.com/latest/errors/method-requirements-error/-MethodRequirementsFileError | Method requirements file | https://docs.pipelex.com/latest/errors/method-requirements-file-error/-MethodRequirementsNotMetError | Method requirements not met | https://docs.pipelex.com/latest/errors/method-requirements-not-met-error/-MethodStructuresRefusedError | Method structures refused | https://docs.pipelex.com/latest/errors/method-structures-refused-error/-MethodTreeLoadError | Method tree load | https://docs.pipelex.com/latest/errors/method-tree-load-error/-MigrationError | Migration error | https://docs.pipelex.com/latest/errors/migration-error/-MigrationGoldenError | Migration golden error | https://docs.pipelex.com/latest/errors/migration-golden-error/-MigrationLedgerError | Migration ledger error | https://docs.pipelex.com/latest/errors/migration-ledger-error/-MigrationRegistryError | Migration registry error | https://docs.pipelex.com/latest/errors/migration-registry-error/-MigrationSnapshotRefusedError | Migration snapshot refused | https://docs.pipelex.com/latest/errors/migration-snapshot-refused-error/-MissingBundleValidatorError | Missing bundle validator | https://docs.pipelex.com/latest/errors/missing-bundle-validator-error/-MissingDependencyError | Missing dependency | https://docs.pipelex.com/latest/errors/missing-dependency-error/-MissingOrchestratorError | Missing orchestrator | https://docs.pipelex.com/latest/errors/missing-orchestrator-error/-MistralExtractResponseError | Mistral extract response | https://docs.pipelex.com/latest/errors/mistral-extract-response-error/-MistralModelListingError | Mistral model listing | https://docs.pipelex.com/latest/errors/mistral-model-listing-error/-MistralPluginError | Mistral plugin | https://docs.pipelex.com/latest/errors/mistral-plugin-error/-MistralWorkerConfigurationError | Mistral worker configuration | https://docs.pipelex.com/latest/errors/mistral-worker-configuration-error/-ModelChoiceNotFoundError | Model choice not found | https://docs.pipelex.com/latest/errors/model-choice-not-found-error/-ModelDeckNotFoundError | Model deck not found | https://docs.pipelex.com/latest/errors/model-deck-not-found-error/-ModelDeckPresetValidatonError | Model deck preset validaton | https://docs.pipelex.com/latest/errors/model-deck-preset-validaton-error/-ModelDeckValidationError | Model deck validation | https://docs.pipelex.com/latest/errors/model-deck-validation-error/-ModelDeckValidatonError | Model deck validaton | https://docs.pipelex.com/latest/errors/model-deck-validaton-error/-ModelListingUnsupportedError | Model listing unsupported | https://docs.pipelex.com/latest/errors/model-listing-unsupported-error/-ModelManagerError | Model manager | https://docs.pipelex.com/latest/errors/model-manager-error/-ModelNotFoundError | Model not found | https://docs.pipelex.com/latest/errors/model-not-found-error/-ModelReferenceParseError | Model reference parse | https://docs.pipelex.com/latest/errors/model-reference-parse-error/-ModelWaterfallError | Model waterfall | https://docs.pipelex.com/latest/errors/model-waterfall-error/-ModuleFileError | Module file | https://docs.pipelex.com/latest/errors/module-file-error/-MthdsParserError | MTHDS parser | https://docs.pipelex.com/latest/errors/mthds-parser-error/-MultiplicityCountMismatchError | Multiplicity count mismatch | https://docs.pipelex.com/latest/errors/multiplicity-count-mismatch-error/-NativeConceptDefinitionError | Native concept definition | https://docs.pipelex.com/latest/errors/native-concept-definition-error/-NeitherUrlNorDataError | Neither url nor data | https://docs.pipelex.com/latest/errors/neither-url-nor-data-error/-NestedKeyConflictError | Nested key conflict | https://docs.pipelex.com/latest/errors/nested-key-conflict-error/-NullInputError | Null input | https://docs.pipelex.com/latest/errors/null-input-error/-OpenAIClientFactoryError | OpenAI client factory error | https://docs.pipelex.com/latest/errors/open-ai-client-factory-error/-OptionalValueAbsentError | Optional value absent | https://docs.pipelex.com/latest/errors/optional-value-absent-error/-OutputStructureSchemaError | Output structure schema | https://docs.pipelex.com/latest/errors/output-structure-schema-error/-PipeBatchFactoryError | Pipe batch factory | https://docs.pipelex.com/latest/errors/pipe-batch-factory-error/-PipeComposeError | Pipe compose | https://docs.pipelex.com/latest/errors/pipe-compose-error/-PipeComposeFactoryError | Pipe compose factory | https://docs.pipelex.com/latest/errors/pipe-compose-factory-error/-PipeConditionFactoryError | Pipe condition factory | https://docs.pipelex.com/latest/errors/pipe-condition-factory-error/-PipeControllerError | Pipe controller | https://docs.pipelex.com/latest/errors/pipe-controller-error/-PipeControllerOutputConceptMismatchError | Pipe controller output concept mismatch | https://docs.pipelex.com/latest/errors/pipe-controller-output-concept-mismatch-error/-PipeDocGenFactoryError | 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/-PipeFactoryError | Pipe factory | https://docs.pipelex.com/latest/errors/pipe-factory-error/-PipeFuncExecutionError | Pipe func execution | https://docs.pipelex.com/latest/errors/pipe-func-execution-error/-PipeFuncFunctionError | Pipe func function | https://docs.pipelex.com/latest/errors/pipe-func-function-error/-PipeFuncPackageSetUnstatedError | Pipe func package set unstated | https://docs.pipelex.com/latest/errors/pipe-func-package-set-unstated-error/-PipeFuncTransportError | Pipe func transport | https://docs.pipelex.com/latest/errors/pipe-func-transport-error/-PipeIOContractError | Pipe IO contract | https://docs.pipelex.com/latest/errors/pipe-io-contract-error/-PipeImgGenFactoryError | Pipe img gen factory | https://docs.pipelex.com/latest/errors/pipe-img-gen-factory-error/-PipeImgGenRunError | Pipe img gen run | https://docs.pipelex.com/latest/errors/pipe-img-gen-run-error/-PipeInputError | Pipe input | https://docs.pipelex.com/latest/errors/pipe-input-error/-PipeInputsFactoryError | Pipe inputs factory | https://docs.pipelex.com/latest/errors/pipe-inputs-factory-error/-PipeJobError | Pipe job | https://docs.pipelex.com/latest/errors/pipe-job-error/-PipeJudgeError | Pipe judge | https://docs.pipelex.com/latest/errors/pipe-judge-error/-PipeJudgeInputCapabilityError | Pipe judge input capability | https://docs.pipelex.com/latest/errors/pipe-judge-input-capability-error/-PipeLLMFactoryError | Pipe LLM factory | https://docs.pipelex.com/latest/errors/pipe-llm-factory-error/-PipeLibraryError | Pipe library | https://docs.pipelex.com/latest/errors/pipe-library-error/-PipeLoadRefusalError | Pipe load refusal | https://docs.pipelex.com/latest/errors/pipe-load-refusal-error/-PipeLoadingError | Pipe loading | https://docs.pipelex.com/latest/errors/pipe-loading-error/-PipeNotFoundError | Pipe not found | https://docs.pipelex.com/latest/errors/pipe-not-found-error/-PipeOperatorModelAvailabilityError | Pipe operator model availability | https://docs.pipelex.com/latest/errors/pipe-operator-model-availability-error/-PipeOperatorModelChoiceError | Pipe operator model choice | https://docs.pipelex.com/latest/errors/pipe-operator-model-choice-error/-PipeParallelFactoryError | Pipe parallel factory | https://docs.pipelex.com/latest/errors/pipe-parallel-factory-error/-PipeRouterError | Pipe router | https://docs.pipelex.com/latest/errors/pipe-router-error/-PipeRunError | Pipe run | https://docs.pipelex.com/latest/errors/pipe-run-error/-PipeRunInputsError | Pipe run inputs | https://docs.pipelex.com/latest/errors/pipe-run-inputs-error/-PipeRunParamsError | Pipe run params | https://docs.pipelex.com/latest/errors/pipe-run-params-error/-PipeSearchError | Pipe search | https://docs.pipelex.com/latest/errors/pipe-search-error/-PipeSearchFactoryError | Pipe search factory | https://docs.pipelex.com/latest/errors/pipe-search-factory-error/-PipeSequenceFactoryError | Pipe sequence factory | https://docs.pipelex.com/latest/errors/pipe-sequence-factory-error/-PipeSignatureNotExecutableError | Pipe signature not executable | https://docs.pipelex.com/latest/errors/pipe-signature-not-executable-error/-PipeStackOverflowError | Pipe stack overflow | https://docs.pipelex.com/latest/errors/pipe-stack-overflow-error/-PipelexBridgeDispatchError | Pipelex bridge dispatch | https://docs.pipelex.com/latest/errors/pipelex-bridge-dispatch-error/-PipelexCLIError | Pipelex CLI | https://docs.pipelex.com/latest/errors/pipelex-cli-error/-PipelexConfigError | Pipelex config | https://docs.pipelex.com/latest/errors/pipelex-config-error/-PipelexError | Pipelex error | https://docs.pipelex.com/latest/errors/pipelex-error/-PipelexRuntimeBridgeError | Pipelex runtime bridge | https://docs.pipelex.com/latest/errors/pipelex-runtime-bridge-error/-PipelexSetupError | Pipelex setup | https://docs.pipelex.com/latest/errors/pipelex-setup-error/-PipelexUnexpectedError | Unexpected internal error | https://docs.pipelex.com/latest/errors/pipelex-unexpected-error/-PipelineExecutionError | Pipeline execution | https://docs.pipelex.com/latest/errors/pipeline-execution-error/-PipelineInputContentError | Pipeline input content | https://docs.pipelex.com/latest/errors/pipeline-input-content-error/-PipelineInputFormatError | Pipeline input format | https://docs.pipelex.com/latest/errors/pipeline-input-format-error/-PipelineInputFormatUnsupportedError | Pipeline input format unsupported | https://docs.pipelex.com/latest/errors/pipeline-input-format-unsupported-error/-PipelineInputNotAnImageError | Pipeline input not an image | https://docs.pipelex.com/latest/errors/pipeline-input-not-an-image-error/-PipelineInputUrlInvalidError | Pipeline input url invalid | https://docs.pipelex.com/latest/errors/pipeline-input-url-invalid-error/-PipelineInputUrlMissingError | Pipeline input url missing | https://docs.pipelex.com/latest/errors/pipeline-input-url-missing-error/-PipelineManagerAlreadyExistsError | Pipeline manager already exists | https://docs.pipelex.com/latest/errors/pipeline-manager-already-exists-error/-PipelineManagerNotFoundError | Pipeline manager not found | https://docs.pipelex.com/latest/errors/pipeline-manager-not-found-error/-PluginApiVersionMismatchError | Plugin api version mismatch | https://docs.pipelex.com/latest/errors/plugin-api-version-mismatch-error/-PluginDeclaredInMultipleGroupsError | Plugin declared in multiple groups | https://docs.pipelex.com/latest/errors/plugin-declared-in-multiple-groups-error/-PluginError | Plugin error | https://docs.pipelex.com/latest/errors/plugin-error/-PluginLayerViolationError | Plugin layer violation | https://docs.pipelex.com/latest/errors/plugin-layer-violation-error/-PluginModelDeclarationError | Plugin model declaration | https://docs.pipelex.com/latest/errors/plugin-model-declaration-error/-PortkeyCredentialsError | Portkey credentials | https://docs.pipelex.com/latest/errors/portkey-credentials-error/-PortkeyError | Portkey | https://docs.pipelex.com/latest/errors/portkey-error/-PortkeyFactoryError | Portkey factory | https://docs.pipelex.com/latest/errors/portkey-factory-error/-PromptDocumentFactoryError | Prompt document factory | https://docs.pipelex.com/latest/errors/prompt-document-factory-error/-PromptDocumentFormatError | Prompt document format | https://docs.pipelex.com/latest/errors/prompt-document-format-error/-PromptImageFactoryError | Prompt image factory | https://docs.pipelex.com/latest/errors/prompt-image-factory-error/-PromptImageFormatError | Prompt image format | https://docs.pipelex.com/latest/errors/prompt-image-format-error/-PyPdfium2RendererError | Py pdfium 2 renderer | https://docs.pipelex.com/latest/errors/py-pdfium2-renderer-error/-ReadinessCheckError | Readiness check | https://docs.pipelex.com/latest/errors/readiness-check-error/-RemoteFileFetchError | Remote file could not be fetched | https://docs.pipelex.com/latest/errors/remote-file-fetch-error/-ReportingManagerError | Reporting manager | https://docs.pipelex.com/latest/errors/reporting-manager-error/-ReservedServiceErrorCodeError | Reserved service error code | https://docs.pipelex.com/latest/errors/reserved-service-error-code-error/-RetiredPluginEntryPointGroupError | Retired plugin entry point group | https://docs.pipelex.com/latest/errors/retired-plugin-entry-point-group-error/-RoutingProfileBlueprintValueError | Routing profile blueprint value | https://docs.pipelex.com/latest/errors/routing-profile-blueprint-value-error/-RoutingProfileDisabledBackendError | Routing profile disabled backend | https://docs.pipelex.com/latest/errors/routing-profile-disabled-backend-error/-RoutingProfileLibraryError | Routing profile library | https://docs.pipelex.com/latest/errors/routing-profile-library-error/-RoutingProfileLibraryNotFoundError | Routing profile library not found | https://docs.pipelex.com/latest/errors/routing-profile-library-not-found-error/-SdkTypeError | Sdk type | https://docs.pipelex.com/latest/errors/sdk-type-error/-SearchHandleNotFoundError | Search handle not found | https://docs.pipelex.com/latest/errors/search-handle-not-found-error/-SearchJobFailureError | Search job failure | https://docs.pipelex.com/latest/errors/search-job-failure-error/-SearchModelNotFoundError | Search model not found | https://docs.pipelex.com/latest/errors/search-model-not-found-error/-SecretNotFoundError | Secret not found | https://docs.pipelex.com/latest/errors/secret-not-found-error/-SecurityError | Security policy violation | https://docs.pipelex.com/latest/errors/security-error/-SsrfBlockedError | Outbound request blocked (SSRF guard) | https://docs.pipelex.com/latest/errors/ssrf-blocked-error/-StorageChecksumMismatchError | Storage checksum mismatch | https://docs.pipelex.com/latest/errors/storage-checksum-mismatch-error/-StorageConfigError | Storage config | https://docs.pipelex.com/latest/errors/storage-config-error/-StorageDeliveryError | Storage delivery | https://docs.pipelex.com/latest/errors/storage-delivery-error/-StorageError | Storage error | https://docs.pipelex.com/latest/errors/storage-error/-StorageFileNotFoundError | Storage file not found | https://docs.pipelex.com/latest/errors/storage-file-not-found-error/-StorageGcpCredentialsError | Storage gcp credentials | https://docs.pipelex.com/latest/errors/storage-gcp-credentials-error/-StorageGcpError | Storage gcp | https://docs.pipelex.com/latest/errors/storage-gcp-error/-StorageInvalidKeyError | Storage invalid key | https://docs.pipelex.com/latest/errors/storage-invalid-key-error/-StorageInvalidUriError | Storage invalid uri | https://docs.pipelex.com/latest/errors/storage-invalid-uri-error/-StorageLocalError | Local storage error | https://docs.pipelex.com/latest/errors/storage-local-error/-StorageS3Error | S3 storage error | https://docs.pipelex.com/latest/errors/storage-s3-error/-StructureClassError | Structure class | https://docs.pipelex.com/latest/errors/structure-class-error/-StructureValidationError | Structure validation | https://docs.pipelex.com/latest/errors/structure-validation-error/-StructuredContentComposerTypeError | Structured content composer type | https://docs.pipelex.com/latest/errors/structured-content-composer-type-error/-StructuredContentComposerValidationError | Structured content composer validation | https://docs.pipelex.com/latest/errors/structured-content-composer-validation-error/-StructuredContentComposerValueError | Structured content composer value | https://docs.pipelex.com/latest/errors/structured-content-composer-value-error/-StuffArtefactError | Stuff artefact | https://docs.pipelex.com/latest/errors/stuff-artefact-error/-StuffArtefactReservedFieldError | Stuff artefact reserved field | https://docs.pipelex.com/latest/errors/stuff-artefact-reserved-field-error/-StuffContentFactoryError | Stuff content factory | https://docs.pipelex.com/latest/errors/stuff-content-factory-error/-StuffContentTypeError | Stuff content type | https://docs.pipelex.com/latest/errors/stuff-content-type-error/-StuffContentValidationError | Stuff content validation | https://docs.pipelex.com/latest/errors/stuff-content-validation-error/-StuffError | Stuff error | https://docs.pipelex.com/latest/errors/stuff-error/-StuffFactoryError | Stuff factory | https://docs.pipelex.com/latest/errors/stuff-factory-error/-StuffSpecError | Stuff spec | https://docs.pipelex.com/latest/errors/stuff-spec-error/-StuffSpecFactoryError | Stuff spec factory | https://docs.pipelex.com/latest/errors/stuff-spec-factory-error/-TelemetryConfigError | Telemetry config | https://docs.pipelex.com/latest/errors/telemetry-config-error/-TelemetryConfigValidationError | Telemetry config validation | https://docs.pipelex.com/latest/errors/telemetry-config-validation-error/-TemplateSigilSyntaxError | Template sigil syntax | https://docs.pipelex.com/latest/errors/template-sigil-syntax-error/-TemplateUrlRefusedError | Relative URL refused | https://docs.pipelex.com/latest/errors/template-url-refused-error/-TomlError | TOML parse error | https://docs.pipelex.com/latest/errors/toml-error/-ToolError | Tool error | https://docs.pipelex.com/latest/errors/tool-error/-TraceEventModeError | Trace event mode | https://docs.pipelex.com/latest/errors/trace-event-mode-error/-TracebackMessageError | Traceback message | https://docs.pipelex.com/latest/errors/traceback-message-error/-TreeModuleShadowingError | Tree module shadowing | https://docs.pipelex.com/latest/errors/tree-module-shadowing-error/-TreePythonError | Tree python | https://docs.pipelex.com/latest/errors/tree-python-error/-TreePythonHeldError | Tree python held | https://docs.pipelex.com/latest/errors/tree-python-held-error/-TypesafeError | Typesafe | https://docs.pipelex.com/latest/errors/typesafe-error/-TypesafeJudgmentResponseError | Typesafe judgment response | https://docs.pipelex.com/latest/errors/typesafe-judgment-response-error/-TypesafeQuestionUnsupportedError | Typesafe question unsupported | https://docs.pipelex.com/latest/errors/typesafe-question-unsupported-error/-UnknownBootOrchestratorError | Unknown boot orchestrator | https://docs.pipelex.com/latest/errors/unknown-boot-orchestrator-error/-UnknownInputNameError | Unknown input name | https://docs.pipelex.com/latest/errors/unknown-input-name-error/-UnknownLogSinkError | Unknown log sink | https://docs.pipelex.com/latest/errors/unknown-log-sink-error/-UnknownPipeFuncExecutionModeError | Unknown pipe func execution mode | https://docs.pipelex.com/latest/errors/unknown-pipe-func-execution-mode-error/-UnknownSecretsMethodError | Unknown secrets method | https://docs.pipelex.com/latest/errors/unknown-secrets-method-error/-UnknownStorageMethodError | Unknown storage method | https://docs.pipelex.com/latest/errors/unknown-storage-method-error/-UnknownVarPrefixError | Unknown var prefix | https://docs.pipelex.com/latest/errors/unknown-var-prefix-error/-UnsafeSchemaError | Unsafe schema | https://docs.pipelex.com/latest/errors/unsafe-schema-error/-UriReadRefusedError | Read outside the run's scope refused | https://docs.pipelex.com/latest/errors/uri-read-refused-error/-ValidateBundleError | Validate bundle | https://docs.pipelex.com/latest/errors/validate-bundle-error/-VarFallbackPatternError | Var fallback pattern | https://docs.pipelex.com/latest/errors/var-fallback-pattern-error/-VarNotFoundError | Var not found | https://docs.pipelex.com/latest/errors/var-not-found-error/-VertexAIConfigError | VertexAI configuration error | https://docs.pipelex.com/latest/errors/vertex-ai-config-error/-VertexAICredentialsError | VertexAI credentials error | https://docs.pipelex.com/latest/errors/vertex-ai-credentials-error/-WebhookDeliveryError | Webhook delivery | https://docs.pipelex.com/latest/errors/webhook-delivery-error/-WithImagesFilterError | With images filter | https://docs.pipelex.com/latest/errors/with-images-filter-error/-WorkingMemoryConsistencyError | Working memory consistency | https://docs.pipelex.com/latest/errors/working-memory-consistency-error/-WorkingMemoryError | Working memory | https://docs.pipelex.com/latest/errors/working-memory-error/-WorkingMemoryFactoryError | Working memory factory | https://docs.pipelex.com/latest/errors/working-memory-factory-error/-WorkingMemoryStuffAttributeNotFoundError | Working memory stuff attribute not found | https://docs.pipelex.com/latest/errors/working-memory-stuff-attribute-not-found-error/-WorkingMemoryStuffNotFoundError | Working memory stuff not found | https://docs.pipelex.com/latest/errors/working-memory-stuff-not-found-error/-WorkingMemoryTypeError | Working memory type | https://docs.pipelex.com/latest/errors/working-memory-type-error/-WorkingMemoryVariableError | Working memory variable | https://docs.pipelex.com/latest/errors/working-memory-variable-error/-WrongScalarKindError | Wrong scalar kind | https://docs.pipelex.com/latest/errors/wrong-scalar-kind-error/+AmbiguousInputsFilesError | request.invalid+AnthropicFactoryError | one of pipelex.config.invalid, runtime.unexpected+AnthropicModelListingError | provider.response_invalid+AnthropicSDKUnsupportedError | runtime.unsupported+AnthropicWorkerConfigurationError | pipelex.config.invalid+ArgumentTypeError | runtime.unexpected+AsyncExecutionNotEnabledError | runtime.unsupported+AutoDetectedInputsFileError | request.invalid+AwsCredentialsError | pipelex.config.credential_missing+AzureCredentialsError | pipelex.config.credential_missing+AzureWorkerConfigurationError | pipelex.config.invalid+BedrockFactoryError | pipelex.config.invalid+BedrockWorkerConfigurationError | pipelex.config.invalid+BindingPathUnresolvedError | method.field_path_unresolved+BindingStepRunError | one of pipe.binding_failed, pipe.output_multiplicity+BrokenPluginError | pipelex.plugin.broken+BundleClosureEmptyError | method.not_found+BundleElaboratorError | method.schema_violation+BundleResourceNotNamedError | request.invalid+BundleResourcePathError | one of security.input_path_refused, request.invalid+CodegenError | pipelex.codegen.output_conflict+CodegenLockError | one of pipelex.codegen.lock_invalid, pipelex.codegen.lock_unsupported+CodegenStampError | runtime.unexpected+CogtError | abstract+ConceptCodeError | method.schema_violation+ConceptError | abstract+ConceptFactoryError | one of method.concept_invalid, method.schema_violation, runtime.unexpected+ConceptLibraryConceptNotFoundError | one of input.wrong_concept, runtime.unexpected+ConceptLibraryError | one of method.concept_unresolved, method.name_conflict, runtime.unexpected+ConceptRefAmbiguousError | method.ref_ambiguous+ConceptStringError | method.schema_violation+ConceptStructureClassNotFoundError | method.concept_invalid+ConceptStructureGeneratorError | one of method.concept_invalid, runtime.unexpected+ConceptStructureValidationError | method.concept_invalid+ConceptValueError | one of method.schema_violation, request.unsupported+ConfigValidationError | pipelex.config.invalid+ConstructFieldBlueprintTypeError | method.schema_violation+ConstructFieldBlueprintValueError | method.schema_violation+ContextProviderError | abstract+CoreUnconditionalPluginDisabledError | pipelex.config.invalid+CostRegistryError | runtime.unexpected+CrateNormalizationError | one of runtime.unexpected, method.cycle+CredentialsError | abstract+CsvCoercionError | input.invalid+CsvColumnError | input.invalid+CsvError | one of input.invalid, request.invalid, runtime.unexpected+CsvFlatnessError | input.invalid+CsvReadError | input.file_unreadable+DateContentError | pipe.function_raised+DeliveryError | abstract+DocGenChoiceKeyError | pipelex.config.invalid+DocGenEngineMissingError | pipelex.docgen.engine_unavailable+DocGenHandleNotFoundError | pipelex.config.invalid+DocGenModelCapabilityError | model.capability_unsupported+DocGenRenderError | one of runtime.unexpected, pipelex.docgen.content_unprintable, pipelex.docgen.print_timeout, pipelex.docgen.resource_refused, pipelex.docgen.template_invalid, security.method_url_refused+DomainCodeError | method.schema_violation+DomainFactoryError | runtime.unexpected+DomainLibraryError | runtime.unexpected+DriftAckError | request.invalid+DriftError | runtime.unexpected+DriftGitError | runtime.unexpected+DriftManifestError | pipelex.config.invalid+DryRunError | inherits cause, else runtime.unexpected+DryRunGraphNotProducedError | runtime.unexpected+DryRunMockBuildError | method.mock_unsatisfiable+DryRunObjectFidelityError | method.mock_unsatisfiable+DuplicateBundleValidatorError | pipelex.plugin.conflict+DuplicateDocGenDefaultError | pipelex.plugin.conflict+DuplicateHttpErrorMapperError | pipelex.plugin.conflict+DuplicateInferenceBackendError | pipelex.plugin.conflict+DuplicateInternalModelError | pipelex.plugin.conflict+DuplicateLogSinkError | pipelex.plugin.conflict+DuplicateMethodNameError | method.ambiguous+DuplicateModelListerError | pipelex.plugin.conflict+DuplicateOrchestratorError | pipelex.plugin.conflict+DuplicatePipeFuncExecutorError | pipelex.plugin.conflict+DuplicatePipeFuncPackageOfferError | pipelex.plugin.conflict+DuplicateSecretsProviderError | pipelex.plugin.conflict+DuplicateServiceErrorCodeError | pipelex.plugin.conflict+DuplicateStorageProviderError | pipelex.plugin.conflict+EmptyMethodTreeError | method.invalid+EntryPipeAmbiguousError | one of request.pipe_ambiguous, method.pipe_unresolved+EntryPipeNotFoundError | one of request.pipe_not_found, request.pipe_unspecified, method.pipe_unresolved+EnvVarNotFoundError | pipelex.config.variable_missing+ErrorRegistryError | runtime.unexpected+EventLogError | abstract+EventLogReadError | runtime.unavailable+EventLogSchemaMismatchError | runtime.unexpected+EventLogSetupError | runtime.misconfigured+ExplicitConceptIncompatibleError | input.wrong_concept+ExportedPipeAmbiguousError | request.pipe_ambiguous+ExportedPipeNotFoundError | request.pipe_not_found+ExtractCapabilityError | model.capability_unsupported+ExtractHandleNotFoundError | pipelex.config.invalid+ExtractInputError | one of runtime.unexpected, model.capability_unsupported+ExtractInputFormatError | input.file_type_unsupported+ExtractJobFailureError | inherits cause, else runtime.unexpected; or chosen: runtime.misconfigured, provider.rate_limited, provider.unavailable, provider.timeout, provider.failed, provider.response_invalid, provider.credential_refused, provider.quota_exhausted, provider.outcome_unknown, model.unavailable, model.capability_unsupported, model.context_exceeded, model.content_refused, model.output_schema_mismatch, model.no_result, input.too_large, input.file_type_unsupported, input.file_unreadable, input.reference_not_found, input.url_unreachable, security.input_url_refused, security.method_url_refused, pipelex.config.invalid, pipelex.config.credential_missing, pipelex.billing.credit_exhausted+ExtractModelNotFoundError | model.unavailable+FatalError | abstract+FileTypeError | one of input.file_type_unsupported, provider.response_invalid+FixTransactionError | runtime.unexpected+FixWriteConflictError | method.changed_concurrently+FormerReleaseConfigError | pipelex.config.invalid+FuncOutputTypeError | pipe.output_invalid+FunctionNamesMigrationError | inherits cause, else runtime.unexpected; or chosen: request.invalid+GcpLogSinkCredentialsError | one of pipelex.config.file_missing, pipelex.config.credential_refused+GeneratedImageError | provider.response_invalid+GoogleLLMWorkerError | model.output_schema_mismatch+GraphSpecError | abstract+GraphSpecValidationError | one of runtime.unexpected, request.invalid+HostLibraryLoadRefusalError | pipelex.config.invalid+HostLibraryRequirementsError | pipelex.config.invalid+HostLibraryTreeError | pipelex.config.invalid+HostedBaseUrlError | client.not_configured+HostedLocalFileUploadUnavailableError | request.unsupported+HostedMethodInvalidError | method.invalid+HostedRunError | abstract+HostedRunInterruptedError | one of client.outcome_unknown, client.follow_failed+HostedRunOutcomeUnknownError | client.outcome_unknown+HostedRunPollingError | client.follow_failed+HostedRunSourceError | client.argument_invalid+HubSlotAlreadyClaimedError | pipelex.plugin.conflict+HuggingFaceProviderUnknownError | pipelex.config.invalid+ImgGenGenerationError | inherits cause, else provider.outcome_unknown; or chosen: runtime.unexpected, runtime.misconfigured, provider.rate_limited, provider.unavailable, provider.timeout, provider.failed, provider.response_invalid, provider.credential_refused, provider.quota_exhausted, model.unavailable, model.capability_unsupported, model.context_exceeded, model.content_refused, model.output_schema_mismatch, model.no_result, input.too_large, input.file_type_unsupported, input.file_unreadable, input.reference_not_found, input.url_unreachable, security.input_url_refused, security.method_url_refused, pipelex.config.invalid, pipelex.config.credential_missing, pipelex.billing.credit_exhausted+ImgGenHandleNotFoundError | pipelex.config.invalid+ImgGenModelNotFoundError | model.unavailable+ImgGenParameterError | one of model.capability_unsupported, pipelex.config.invalid, runtime.unexpected+ImgGenPromptError | pipe.prompt_empty+ImgGenSettingValueError | method.model_setting_invalid+InferenceBackendCredentialsError | one of pipelex.config.credential_missing, pipelex.config.invalid, runtime.misconfigured+InferenceBackendLibraryError | pipelex.config.invalid+InferenceBackendLibraryNotFoundError | pipelex.config.invalid+InferenceBackendLibraryValidationError | pipelex.config.invalid+InferenceBackendNotFoundError | model.unavailable+InferenceModelSpecError | pipelex.config.invalid+InputShapingError | abstract+InputStuffSpecNotFoundError | method.wiring_invalid+InputStuffSpecsError | abstract+InputStuffSpecsFactoryError | method.schema_violation+InvalidPipeCodeSyntaxError | method.identifier_invalid+InvocationPathError | runtime.unexpected+Jinja2ContextError | one of pipe.template_render_failed, method.template_invalid, runtime.unexpected+Jinja2DetectVariablesError | method.syntax+Jinja2StuffError | one of method.name_conflict, runtime.unexpected+Jinja2TemplateBudgetError | one of pipe.template_budget_exceeded, input.too_large+Jinja2TemplateInvalidError | one of method.template_invalid, runtime.unexpected+Jinja2TemplateRenderError | one of pipe.template_render_failed, method.template_invalid, runtime.unexpected+Jinja2TemplateSecurityError | one of security.template_refused, runtime.unexpected+Jinja2TemplateSyntaxError | method.syntax+JobMetadataError | runtime.unexpected+JsonTypeError | one of request.invalid, pipelex.config.invalid, runtime.unexpected+JudgmentAnswerMismatchError | model.output_schema_mismatch+JudgmentCapabilityError | one of model.capability_unsupported, model.context_exceeded, pipelex.config.invalid+JudgmentHandleNotFoundError | pipelex.config.invalid+JudgmentJobFailureError | inherits cause, else runtime.unexpected; or chosen: runtime.misconfigured, provider.rate_limited, provider.unavailable, provider.timeout, provider.failed, provider.response_invalid, provider.credential_refused, provider.quota_exhausted, provider.outcome_unknown, model.unavailable, model.capability_unsupported, model.context_exceeded, model.content_refused, model.output_schema_mismatch, model.no_result, input.too_large, input.file_type_unsupported, input.file_unreadable, input.reference_not_found, input.url_unreachable, security.input_url_refused, security.method_url_refused, pipelex.config.invalid, pipelex.config.credential_missing, pipelex.billing.credit_exhausted+JudgmentModelMissingError | model.unspecified+JudgmentModelNotFoundError | model.unavailable+JudgmentOutputFieldsError | runtime.unexpected+JudgmentRefusedError | model.content_refused+KitError | runtime.unexpected+KitIndexLoadingError | runtime.unexpected+LLMCapabilityError | one of model.capability_unsupported, model.context_exceeded+LLMCompletionError | inherits cause, else runtime.unexpected; or chosen: runtime.misconfigured, provider.rate_limited, provider.unavailable, provider.timeout, provider.failed, provider.response_invalid, provider.credential_refused, provider.quota_exhausted, provider.outcome_unknown, model.unavailable, model.capability_unsupported, model.context_exceeded, model.content_refused, model.output_schema_mismatch, model.no_result, input.too_large, input.file_type_unsupported, input.file_unreadable, input.reference_not_found, input.url_unreachable, security.input_url_refused, security.method_url_refused, pipelex.config.invalid, pipelex.config.credential_missing, pipelex.billing.credit_exhausted+LLMCompletionRefusedError | model.content_refused+LLMCompletionTruncatedError | one of model.output_truncated, model.context_exceeded+LLMConfigError | pipelex.config.invalid+LLMHandleNotFoundError | pipelex.config.invalid+LLMModelNotFoundError | model.unavailable+LLMPromptParameterError | pipe.prompt_empty+LLMSettingRefusedError | model.capability_unsupported+LLMSettingValueError | method.model_setting_invalid+LangfuseCredentialsError | pipelex.config.variable_missing+LibraryError | one of runtime.unexpected, request.invalid, method.concept_unresolved, pipelex.config.invalid+LibraryLoadingError | one of method.invalid, method.cycle, method.name_conflict, method.pipe_not_exported, method.dependency_missing, method.concept_invalid, method.not_found+LinkupError | pipelex.config.credential_missing+LinkupSearchEmptyResultError | model.no_result+LinkupSearchResponseError | provider.response_invalid+ListWhereSingularError | input.wrong_multiplicity+LocalFileMissingError | input.reference_not_found+LogSinkHeaderValueError | pipelex.config.invalid+LogSinkVariableError | pipelex.config.variable_missing+MarkdownFormattingBudgetError | input.too_large+MarkdownParserDependencyError | pipelex.config.dependency_missing+MethodDependencyFetchError | method.dependency_missing+MethodDependencyNotShippedError | method.dependency_missing+MethodEntryError | one of request.pipe_unspecified, request.pipe_ambiguous, request.pipe_not_found, method.pipe_unresolved, method.package_invalid, method.syntax, method.invalid+MethodFetchDisabledError | method.dependency_missing+MethodFetchError | one of method.fetch_failed, pipelex.config.dependency_missing, method.not_found, method.package_invalid+MethodFileUnavailableError | one of runtime.unexpected, method.resource_missing+MethodInstallError | one of pipelex.config.invalid, method.package_invalid+MethodNotFoundError | method.not_found+MethodPackageAmbiguityError | method.ambiguous+MethodPackageNotFoundError | method.not_found+MethodPackageSymlinkError | method.package_invalid+MethodPackageTooLargeError | method.package_invalid+MethodRefError | abstract+MethodRefParseError | one of request.invalid, request.unsupported+MethodRequirementsError | abstract+MethodRequirementsFileError | method.package_invalid+MethodRequirementsNotMetError | method.dependency_missing+MethodStructuresRefusedError | pipelex.deployment.python_structures_refused+MethodTreeLoadError | method.package_invalid+MigrationError | abstract+MigrationGoldenError | runtime.unexpected+MigrationLedgerError | runtime.unexpected+MigrationRegistryError | runtime.unexpected+MigrationSnapshotRefusedError | runtime.unexpected+MissingBundleValidatorError | one of pipelex.plugin.not_found, runtime.unsupported, pipelex.config.dependency_missing, runtime.unexpected+MissingDependencyError | pipelex.config.dependency_missing+MissingOrchestratorError | one of pipelex.plugin.not_found, runtime.unsupported, pipelex.config.dependency_missing, runtime.unexpected+MistralExtractResponseError | provider.response_invalid+MistralModelListingError | provider.response_invalid+MistralPluginError | abstract+MistralWorkerConfigurationError | pipelex.config.invalid+MockUsageOnLiveRunError | request.invalid+ModelChoiceNotFoundError | one of model.unknown, model.capability_unsupported+ModelDeckChoiceUnresolvedError | one of pipelex.config.invalid, model.unavailable+ModelDeckNotFoundError | pipelex.config.invalid+ModelDeckPresetValidationError | pipelex.config.invalid+ModelDeckValidationError | pipelex.config.invalid+ModelListingUnsupportedError | runtime.unsupported+ModelManagerError | pipelex.config.invalid+ModelNotFoundError | one of model.unavailable, model.unknown+ModelReferenceParseError | one of method.model_setting_invalid, pipelex.config.invalid+ModelWaterfallError | model.unavailable+ModuleFileError | runtime.unexpected+MthdsParserError | one of method.invalid, method.syntax, method.schema_violation, method.dependency_invalid, request.invalid, request.pipe_unspecified, runtime.unexpected+MultiplicityCountMismatchError | input.wrong_multiplicity+NativeConceptDefinitionError | runtime.unexpected+NativeConceptRedeclarationError | method.name_conflict+NeitherUrlNorDataError | provider.response_invalid+NestedKeyConflictError | pipe.template_render_failed+NoInputsRequiredError | request.unsupported+NullInputError | input.invalid+OpenAIClientFactoryError | pipelex.config.invalid+OptionalValueAbsentError | pipe.forced_input_absent+OutputShapeUnavailableError | request.unsupported+OutputStructureSchemaError | method.concept_invalid+PipeComposeError | inherits cause, else pipe.output_invalid+PipeComposeFactoryError | one of method.template_invalid, method.schema_violation+PipeComposeTemplateError | method.template_invalid+PipeConditionFactoryError | method.schema_violation+PipeControllerError | abstract+PipeDocGenFactoryError | one of method.template_invalid, method.output_concept_mismatch, method.resource_missing, security.method_path_refused, method.input_undeclared, method.field_path_unresolved+PipeDocGenRunError | inherits cause, else pipe.template_render_failed; or chosen: runtime.unexpected, method.template_invalid+PipeDocGenTemplateCheckError | pipelex.docgen.template_invalid+PipeDocGenTemplateFileUncheckedError | runtime.unsupported+PipeDocGenUndefinedValueError | pipe.template_render_failed+PipeExecutionError | one of runtime.unexpected, request.pipe_unspecified, input.invalid+PipeExtractFactoryError | method.schema_violation+PipeFactoryError | one of method.schema_violation, method.concept_unresolved, runtime.unexpected+PipeFuncExecutionError | inherits cause, else runtime.unexpected; or chosen: pipe.function_timed_out+PipeFuncFunctionError | method.function_invalid+PipeFuncPackageSetUnstatedError | runtime.misconfigured+PipeFuncRaisedError | pipe.function_raised+PipeFuncTransportError | runtime.misconfigured+PipeIOContractError | method.concept_invalid+PipeImgGenFactoryError | model.context_exceeded+PipeImgGenRunError | inherits cause, else pipe.input_unresolved+PipeJobError | runtime.unexpected+PipeJudgeError | abstract+PipeJudgeInputCapabilityError | model.capability_unsupported+PipeLLMFactoryError | method.template_invalid+PipeLibraryError | one of method.name_conflict, method.ref_ambiguous, method.signature_mismatch, request.unsupported, runtime.unexpected+PipeLoadRefusalError | inherits cause, else method.schema_violation+PipeNotFoundError | method.pipe_unresolved+PipeOperatorModelAvailabilityError | inherits cause, else model.unavailable+PipeOperatorModelChoiceError | inherits cause, else model.unknown+PipeParallelFactoryError | method.schema_violation+PipeRouterError | inherits cause, else runtime.unexpected+PipeRunError | inherits cause, else runtime.unexpected; or chosen: model.output_schema_mismatch, pipe.condition_unmatched, pipe.condition_refused, pipe.input_unresolved, method.function_invalid, method.template_invalid, method.pipe_unresolved, method.schema_violation, method.wiring_invalid, method.name_conflict, method.optional_unhandled+PipeRunInputsError | one of pipe.input_unresolved, input.missing, input.reference_not_found, method.wiring_invalid+PipeRunParamsError | method.schema_violation+PipeSequenceValueError | method.wiring_invalid+PipeSignatureNotExecutableError | method.not_runnable+PipeStackOverflowError | pipe.stack_overflow+PipeValidationError | one of method.schema_violation, method.input_undeclared, method.input_unused, method.input_concept_mismatch, method.output_concept_mismatch, method.output_multiplicity_mismatch, method.identifier_invalid, method.pipe_type_invalid, method.name_conflict, method.binding_step_invalid, method.field_path_unresolved, method.optional_marker_invalid, method.optional_unhandled, method.template_private_name, method.optional_force_redundant, method.input_presence_vacuous, method.concept_unresolved, method.pipe_unresolved, method.dependency_missing, method.pipe_not_exported, method.function_invalid, method.wiring_invalid, model.unknown, model.capability_unsupported, runtime.unexpected+PipeVariableMultiplicityError | method.schema_violation+PipelexBridgeDispatchError | inherits cause, else runtime.unexpected; or chosen: runtime.unsupported, request.invalid+PipelexCLIError | inherits cause, else runtime.unexpected; or chosen: pipelex.config.invalid, pipelex.config.variable_missing, pipelex.config.credential_missing, provider.credential_refused, provider.failed+PipelexConfigError | one of pipelex.config.invalid, pipelex.config.syntax, pipelex.config.file_missing+PipelexError | abstract+PipelexRequestError | one of request.invalid, request.unsupported+PipelexRuntimeBridgeError | abstract+PipelexSetupError | inherits cause, else runtime.misconfigured; or chosen: runtime.unexpected, pipelex.config.file_missing, pipelex.config.invalid, pipelex.config.syntax+PipelexUnexpectedError | runtime.unexpected+PipelineExecutionError | inherits cause, else runtime.unexpected+PipelineInputContentError | inherits cause, else pipelex.storage.uri_invalid; or chosen: input.reference_not_found, input.file_unreadable+PipelineInputFormatError | abstract+PipelineInputFormatUnsupportedError | input.file_type_unsupported+PipelineInputNotAnImageError | input.file_type_unsupported+PipelineInputUrlInvalidError | input.invalid+PipelineInputUrlMissingError | input.invalid+PipelineManagerAlreadyExistsError | pipelex.run.already_exists+PipelineManagerNotFoundError | runtime.unexpected+PluginApiVersionMismatchError | pipelex.plugin.api_mismatch+PluginDeclaredInMultipleGroupsError | pipelex.plugin.broken+PluginError | abstract+PluginErrorCodeNotRegisteredError | pipelex.plugin.broken+PluginLayerViolationError | pipelex.plugin.broken+PluginModelDeclarationError | pipelex.config.invalid+PortkeyCredentialsError | pipelex.config.credential_missing+PortkeyError | abstract+PortkeyFactoryError | pipelex.config.invalid+PromptContentError | one of runtime.unexpected, method.wiring_invalid+PromptDocumentFactoryError | runtime.unexpected+PromptDocumentFormatError | input.file_type_unsupported+PromptImageFactoryError | runtime.unexpected+PromptImageFormatError | input.file_type_unsupported+QualifiedRefError | method.schema_violation+ReadinessCheckError | runtime.misconfigured+RemoteFileFetchError | one of input.file_unreadable, input.url_unreachable, provider.response_invalid+ReservedServiceErrorCodeError | pipelex.plugin.broken+RetiredPluginEntryPointGroupError | pipelex.plugin.broken+RoutingProfileBlueprintValueError | pipelex.config.invalid+RoutingProfileDisabledBackendError | pipelex.config.invalid+RoutingProfileLibraryError | pipelex.config.invalid+RoutingProfileLibraryNotFoundError | pipelex.config.invalid+RunParameterError | request.invalid+SdkTypeError | runtime.unexpected+SearchHandleNotFoundError | pipelex.config.invalid+SearchJobFailureError | inherits cause, else runtime.unexpected; or chosen: runtime.misconfigured, provider.rate_limited, provider.unavailable, provider.timeout, provider.failed, provider.response_invalid, provider.credential_refused, provider.quota_exhausted, provider.outcome_unknown, model.unavailable, model.capability_unsupported, model.context_exceeded, model.content_refused, model.output_schema_mismatch, model.no_result, input.too_large, input.file_type_unsupported, input.file_unreadable, input.reference_not_found, input.url_unreachable, security.input_url_refused, security.method_url_refused, pipelex.config.invalid, pipelex.config.credential_missing, pipelex.billing.credit_exhausted+SearchModelNotFoundError | model.unavailable+SecretNotFoundError | pipelex.config.variable_missing+SecretVersionUnsupportedError | runtime.unsupported+SecurityError | abstract+SemVerError | method.package_invalid+SsrfBlockedError | one of security.input_url_refused, security.method_url_refused, security.provider_url_refused+StorageChecksumMismatchError | runtime.unexpected+StorageConfigError | pipelex.config.invalid+StorageDeliveryError | inherits cause, else pipelex.storage.unavailable+StorageError | abstract+StorageFileNotFoundError | one of pipelex.storage.not_found, runtime.unexpected+StorageGcpCredentialsError | pipelex.config.file_missing+StorageGcpError | one of pipelex.storage.unavailable, pipelex.config.credential_refused+StorageInvalidKeyError | runtime.unexpected+StorageInvalidUriError | one of security.input_path_refused, security.method_url_refused, runtime.unexpected+StorageLocalError | runtime.misconfigured+StorageNotConfiguredError | pipelex.storage.not_configured+StorageS3Error | one of pipelex.storage.unavailable, pipelex.config.invalid, pipelex.config.credential_refused, pipelex.config.credential_missing+StructureValidationError | one of input.invalid, input.wrong_concept+StructuredContentComposerTypeError | pipe.output_invalid+StructuredContentComposerValidationError | pipe.output_invalid+StructuredContentComposerValueError | one of runtime.unexpected, method.field_path_unresolved+StuffContentFactoryError | one of input.invalid, runtime.unexpected+StuffContentTypeError | method.wiring_invalid+StuffContentValidationError | method.wiring_invalid+StuffError | abstract+StuffFactoryError | one of input.invalid, input.wrong_concept, pipe.output_invalid, pipe.output_multiplicity+StuffSpecFactoryError | method.schema_violation+TelemetryApiKeyMissingError | pipelex.config.variable_missing+TelemetryConfigError | abstract+TelemetryConfigValidationError | pipelex.config.invalid+TemplateSigilSyntaxError | method.syntax+TemplateUrlRefusedError | security.method_path_refused+TomlError | one of pipelex.config.syntax, request.malformed, method.syntax+ToolError | abstract+TraceContextRunModeError | runtime.unexpected+TraceEventModeError | runtime.unexpected+TracebackMessageError | abstract+TreeModuleShadowingError | method.name_conflict+TreePythonError | one of runtime.unexpected, request.unsupported, method.name_conflict+TreePythonHeldError | runtime.unavailable+TypesafeError | pipelex.config.credential_missing+TypesafeJudgmentResponseError | provider.response_invalid+TypesafeQuestionUnsupportedError | one of model.capability_unsupported, runtime.unexpected+UnknownBootOrchestratorError | pipelex.plugin.not_found+UnknownInputNameError | input.unexpected+UnknownLogSinkError | pipelex.plugin.not_found+UnknownPipeFuncExecutionModeError | pipelex.plugin.not_found+UnknownSecretsMethodError | pipelex.plugin.not_found+UnknownStorageMethodError | pipelex.plugin.not_found+UnknownVarPrefixError | pipelex.config.invalid+UnsafeSchemaError | security.schema_refused+UnsupportedImageMimeTypeError | one of input.file_type_unsupported, provider.response_invalid+UriReadRefusedError | one of security.input_url_refused, security.method_url_refused+UrlSyntaxError | input.invalid+ValidateBundleError | one of method.invalid, request.invalid+VarFallbackPatternError | pipelex.config.variable_missing+VarNotFoundError | pipelex.config.variable_missing+VertexAIConfigError | pipelex.config.invalid+VertexAICredentialsError | pipelex.config.credential_missing+WebhookDeliveryError | pipelex.webhook.delivery_failed+WithImagesFilterError | method.template_invalid+WorkingMemoryConsistencyError | runtime.unexpected+WorkingMemoryError | abstract+WorkingMemoryFactoryError | runtime.unexpected+WorkingMemoryStuffAttributeNotFoundError | one of method.wiring_invalid, method.template_private_name+WorkingMemoryStuffNotFoundError | runtime.unexpected+WorkingMemoryTypeError | one of method.wiring_invalid, input.invalid+WorkingMemoryVariableError | abstract+WrongScalarKindError | input.invaliddiff --git a/tests/data/errors/foreign_raises.txt b/tests/data/errors/foreign_raises.txtnew file mode 100644index 000000000..5ae991f65--- /dev/null+++ b/tests/data/errors/foreign_raises.txt@@ -0,0 +1,202 @@+# The raises, in pipelex/ and api/pipelex_api/, of a class outside the PipelexError root that are right as they are.+#+# Each line is `path | function | exception | disposition`, one per raise site, so a function raising the same class+# twice is listed twice. tests/unit/pipelex/errors/test_foreign_raises.py fails on a foreign raise this file does not+# list and on a listed one that is gone. The dispositions:+#+# - invariant: a builtin raised only on a bug of ours, which a boundary reports as runtime.unexpected;+# - validator: a builtin raised in a helper only pydantic validators call, which pydantic wraps;+# - private: a private class caught in the module that defines it, which no reader sees;+# - carrier: a class a library or protocol expects by type (the import system's ImportError, httpx's transport+# errors, the standard's method tree refusal its callers translate, the runner's own ApiError) that the scan+# cannot recognise by its name alone;+# - tooling: developer or release code outside the exempt directories, which only the development CLI calls;+# - caught: a builtin raised in a module that must import nothing of Pipelex, which its every caller catches by type.+#+# A new raise belongs here only when it is one of these; otherwise raise a coded PipelexError subclass.+api/pipelex_api/errors.py | _raise_api_error | ApiError | carrier+api/pipelex_api/schemas/models.py | _ensure_mthds_file_within_bytes_limit | ValueError | validator+pipelex/base_exceptions.py | PipelexError.__init_subclass__ | TypeError | invariant+pipelex/base_exceptions.py | PipelexError.with_error_code | ValueError | invariant+pipelex/cli/commands/init/ui/setup_path_ui.py | _option_number | ValueError | invariant+pipelex/codegen/stamp.py | _reject_json_constant | ValueError | carrier+pipelex/cogt/content_generation/content_generator.py | ContentGenerator.make_render_page_views | ValueError | invariant+pipelex/cogt/content_generation/content_generator_protocol.py | update_job_metadata.wrapper | RuntimeError | invariant+pipelex/cogt/content_generation/content_generator_protocol.py | update_job_metadata.wrapper | TypeError | invariant+pipelex/cogt/content_generation/doc_gen_generate.py | RunRenderResources.load | RuntimeError | invariant+pipelex/cogt/content_generation/schema_to_model_factory.py | SchemaToModelFactory._exec_and_extract_class | ValueError | invariant+pipelex/cogt/doc_gen/document_composition.py | DocumentComposition._validate_url_base | ValueError | validator+pipelex/cogt/doc_gen/document_composition.py | DocumentComposition._validate_url_base | ValueError | validator+pipelex/cogt/doc_gen/method_file_urls.py | RelativeUrlBase._tree_path_of_joined | MethodTreeRefusedError | carrier+pipelex/cogt/doc_gen/method_file_urls.py | RelativeUrlBase._tree_path_of_joined | MethodTreeRefusedError | carrier+pipelex/cogt/img_gen/img_gen_job_components.py | parse_img_gen_size | ValueError | validator+pipelex/cogt/llm/llm_worker_abstract.py | LLMWorkerAbstract._start_otel_span_llm | NotImplementedError | invariant+pipelex/cogt/models/model_manager.py | ModelManager.get_inference_model | RuntimeError | invariant+pipelex/cogt/models/model_manager.py | ModelManager.get_model_deck | RuntimeError | invariant+pipelex/cogt/models/model_manager.py | ModelManager.routing_profile | RuntimeError | invariant+pipelex/config.py | get_config | TypeError | invariant+pipelex/core/concepts/concept_representation_generator.py | ConceptRepresentationGenerator._generate_basemodel_representation | ValueError | invariant+pipelex/core/concepts/concept_representation_generator.py | ConceptRepresentationGenerator.generate_class_representation | ValueError | invariant+pipelex/core/concepts/concept_structure_blueprint.py | ConceptStructureBlueprint._raise_type_mismatch_error | ValueError | validator+pipelex/core/method_trees/file_references.py | _join_lexically | MethodTreeRefusedError | carrier+pipelex/core/method_trees/file_references.py | _join_lexically | MethodTreeRefusedError | carrier+pipelex/core/method_trees/file_references.py | _join_lexically | MethodTreeRefusedError | carrier+pipelex/core/method_trees/file_references.py | _join_lexically | MethodTreeRefusedError | carrier+pipelex/core/method_trees/file_references.py | resolve_bundle_file_reference | MethodTreeRefusedError | carrier+pipelex/core/method_trees/method_file_store.py | LocalMethodFileStore.hold_tree | ValueError | invariant+pipelex/core/method_trees/tree_bundle.py | TreeBundle.location | ValueError | invariant+pipelex/core/method_trees/tree_python.py | TreeModuleGuard.find_spec | TreeModuleExcludedError | carrier+pipelex/core/pipes/inputs/input_stuff_specs.py | InputStuffSpecs.get_single_stuff_spec | ValueError | invariant+pipelex/core/stuffs/iso_temporal.py | parse_iso_date | ValueError | validator+pipelex/core/stuffs/iso_temporal.py | parse_iso_date | ValueError | validator+pipelex/core/stuffs/iso_temporal.py | parse_iso_time | ValueError | validator+pipelex/core/stuffs/iso_temporal.py | parse_iso_time | ValueError | validator+pipelex/core/stuffs/iso_temporal.py | parse_iso_time | ValueError | validator+pipelex/core/stuffs/non_null_any.py | _refuse_none | PydanticCustomError | validator+pipelex/core/stuffs/stuff_artefact.py | _get_content_html | AttributeError | carrier+pipelex/core/stuffs/stuff_artefact.py | _get_template_value | KeyError | carrier+pipelex/errors/error_class_discovery.py | _force_load_all_error_modules | RuntimeError | invariant+pipelex/errors/registry/registry_document.py | _check_enum_values | ValueError | validator+pipelex/errors/registry/registry_document.py | _check_enum_values | ValueError | validator+pipelex/errors/registry/registry_document.py | _check_enum_values | ValueError | validator+pipelex/errors/registry/registry_document.py | _check_enum_values | ValueError | validator+pipelex/errors/retired_error_pages.py | _split_block | RetiredErrorPagesError | tooling+pipelex/errors/retired_error_pages.py | _split_block | RetiredErrorPagesError | tooling+pipelex/errors/retired_error_pages.py | retired_page_names | RetiredErrorPagesError | tooling+pipelex/interpreter_hub.py | InterpreterHub.get_instance | RuntimeError | invariant+pipelex/interpreter_hub.py | InterpreterHub.get_library | RuntimeError | invariant+pipelex/interpreter_hub.py | InterpreterHub.get_library_manager | RuntimeError | invariant+pipelex/interpreter_hub.py | InterpreterHub.get_pipe_func_executor_registry | RuntimeError | invariant+pipelex/interpreter_hub.py | InterpreterHub.get_pipe_func_package_offer_registry | RuntimeError | invariant+pipelex/interpreter_hub.py | InterpreterHub.get_required_concept_library | RuntimeError | invariant+pipelex/interpreter_hub.py | InterpreterHub.get_required_domain_library | RuntimeError | invariant+pipelex/interpreter_hub.py | InterpreterHub.get_required_pipe_func_executor | RuntimeError | invariant+pipelex/interpreter_hub.py | InterpreterHub.get_required_pipe_library | RuntimeError | invariant+pipelex/interpreter_hub.py | InterpreterHub.get_required_pipe_router | RuntimeError | invariant+pipelex/interpreter_hub.py | InterpreterHub.get_required_pipe_run | RuntimeError | invariant+pipelex/interpreter_hub.py | InterpreterHub.get_required_pipeline_manager | RuntimeError | invariant+pipelex/interpreter_hub.py | get_current_library | RuntimeError | invariant+pipelex/kernel/pipelex_kernel.py | PipelexKernel._resolve_pipeline_run_id | ValueError | invariant+pipelex/kernel/pipelex_kernel.py | PipelexKernel._resolve_pipeline_run_id | ValueError | invariant+pipelex/kit/single_file_agent_rules.py | build_merged_rules | ValueError | tooling+pipelex/language/mthds_factory.py | MthdsFactory.make_table_obj_for_concept | TypeError | invariant+pipelex/language/mthds_factory.py | MthdsFactory.make_table_obj_for_concept | TypeError | invariant+pipelex/language/mthds_factory.py | MthdsFactory.make_table_obj_for_concept | TypeError | invariant+pipelex/language/mthds_schema_generator.py | _split_levels_scale | RuntimeError | tooling+pipelex/migration/surfaces.py | _reject_duplicates | ValueError | validator+pipelex/migration/surfaces.py | _reject_duplicates_per_directory | ValueError | validator+pipelex/pipe_controllers/batch/pipe_batch_blueprint.py | PipeBatchBlueprint.validate_inputs | ValueError | validator+pipelex/pipe_controllers/batch/pipe_batch_blueprint.py | PipeBatchBlueprint.validate_inputs | ValueError | validator+pipelex/pipe_controllers/condition/pipe_condition_blueprint.py | PipeConditionBlueprint.validate_inputs | ValueError | validator+pipelex/pipe_controllers/condition/pipe_condition_blueprint.py | PipeConditionBlueprint.validate_inputs | ValueError | validator+pipelex/pipe_controllers/parallel/pipe_parallel_blueprint.py | PipeParallelBlueprint.validate_output | ValueError | validator+pipelex/pipe_controllers/parallel/pipe_parallel_blueprint.py | PipeParallelBlueprint.validate_output | ValueError | validator+pipelex/pipe_machinery/pipe_blueprint.py | PipeBlueprint.generic_validate_inputs | ValueError | validator+pipelex/pipe_machinery/pipe_blueprint.py | PipeBlueprint.generic_validate_inputs | ValueError | validator+pipelex/pipe_machinery/pipe_blueprint.py | PipeBlueprint.generic_validate_inputs | ValueError | validator+pipelex/pipe_machinery/pipe_blueprint.py | PipeBlueprint.generic_validate_output | ValueError | validator+pipelex/pipe_machinery/pipe_blueprint.py | PipeBlueprint.generic_validate_output | ValueError | validator+pipelex/pipe_machinery/pipe_blueprint.py | normalize_typeless_signature_section | ValueError | validator+pipelex/pipe_machinery/pipe_blueprint.py | normalize_typeless_signature_section | ValueError | validator+pipelex/pipe_operators/compose/pipe_compose_blueprint.py | PipeComposeBlueprint._validate_template_inputs | ValueError | validator+pipelex/pipe_operators/compose/pipe_compose_blueprint.py | PipeComposeBlueprint._validate_template_inputs | ValueError | validator+pipelex/pipe_operators/compose/pipe_compose_blueprint.py | PipeComposeBlueprint.validate_output | ValueError | validator+pipelex/pipe_operators/doc_gen/pipe_doc_gen_blueprint.py | PipeDocGenBlueprint._check_roots_are_inputs | ValueError | validator+pipelex/pipe_operators/doc_gen/pipe_doc_gen_blueprint.py | PipeDocGenBlueprint.validate_output | ValueError | validator+pipelex/pipe_operators/doc_gen/pipe_doc_gen_blueprint.py | template_required_roots | ValueError | validator+pipelex/pipe_operators/doc_gen/pipe_doc_gen_blueprint.py | template_required_roots | ValueError | validator+pipelex/pipe_operators/extract/pipe_extract_blueprint.py | PipeExtractBlueprint.validate_inputs | ValueError | validator+pipelex/pipe_operators/extract/pipe_extract_blueprint.py | PipeExtractBlueprint.validate_inputs | ValueError | validator+pipelex/pipe_operators/extract/pipe_extract_blueprint.py | PipeExtractBlueprint.validate_inputs | ValueError | validator+pipelex/pipe_operators/extract/pipe_extract_blueprint.py | PipeExtractBlueprint.validate_output | ValueError | validator+pipelex/pipe_operators/func/function_name.py | split_function_name | ValueError | invariant+pipelex/pipe_operators/img_gen/pipe_img_gen_blueprint.py | PipeImgGenBlueprint._read_variable_paths | ValueError | validator+pipelex/pipe_operators/img_gen/pipe_img_gen_blueprint.py | PipeImgGenBlueprint._read_variable_paths | ValueError | validator+pipelex/pipe_operators/judge/pipe_judge_blueprint.py | PipeJudgeBlueprint.validate_output | ValueError | validator+pipelex/pipe_operators/judge/pipe_judge_blueprint.py | PipeJudgeBlueprint.validate_output | ValueError | validator+pipelex/pipe_operators/judge/pipe_judge_blueprint.py | _template_variable_paths | ValueError | validator+pipelex/pipe_operators/judge/pipe_judge_blueprint.py | _template_variable_paths | ValueError | validator+pipelex/pipe_operators/judge/pipe_judge_blueprint.py | _validate_levels | ValueError | validator+pipelex/pipe_operators/judge/pipe_judge_blueprint.py | _validate_levels | ValueError | validator+pipelex/pipe_operators/judge/pipe_judge_blueprint.py | _validate_levels | ValueError | validator+pipelex/pipe_operators/judge/pipe_judge_blueprint.py | _validate_levels | ValueError | validator+pipelex/pipe_operators/judge/pipe_judge_blueprint.py | _validate_levels | ValueError | validator+pipelex/pipe_operators/judge/pipe_judge_blueprint.py | _validate_levels | ValueError | validator+pipelex/pipe_operators/judge/pipe_judge_blueprint.py | _validate_question_kind | ValueError | validator+pipelex/pipe_operators/judge/pipe_judge_blueprint.py | _validate_question_kind | ValueError | validator+pipelex/pipe_operators/judge/pipe_judge_blueprint.py | _validate_question_kind | ValueError | validator+pipelex/pipe_operators/judge/pipe_judge_blueprint.py | _validate_question_kind | ValueError | validator+pipelex/pipe_operators/judge/pipe_judge_blueprint.py | _validate_question_kind | ValueError | validator+pipelex/pipe_operators/llm/pipe_llm_blueprint.py | PipeLLMBlueprint.validate_inputs | ValueError | validator+pipelex/pipe_operators/llm/pipe_llm_blueprint.py | PipeLLMBlueprint.validate_inputs | ValueError | validator+pipelex/pipe_operators/llm/pipe_llm_blueprint.py | PipeLLMBlueprint.validate_inputs | ValueError | validator+pipelex/pipe_operators/llm/pipe_llm_blueprint.py | PipeLLMBlueprint.validate_inputs | ValueError | validator+pipelex/pipe_operators/search/pipe_search_blueprint.py | PipeSearchBlueprint.validate_inputs | ValueError | validator+pipelex/pipe_operators/search/pipe_search_blueprint.py | PipeSearchBlueprint.validate_inputs | ValueError | validator+pipelex/pipe_operators/structure/pipe_structure_blueprint.py | PipeStructureBlueprint.validate_inputs | ValueError | validator+pipelex/pipe_operators/structure/pipe_structure_blueprint.py | PipeStructureBlueprint.validate_inputs | ValueError | validator+pipelex/pipe_operators/structure/pipe_structure_blueprint.py | PipeStructureBlueprint.validate_output | ValueError | validator+pipelex/providers/anthropic/anthropic_factory.py | AnthropicFactory._make_document_block_param | TypeError | invariant+pipelex/providers/anthropic/anthropic_factory.py | AnthropicFactory._make_image_block_param | TypeError | invariant+pipelex/providers/azure_rest/azure_img_gen_worker.py | AzureImgGenWorker.__init__ | NotImplementedError | invariant+pipelex/providers/linkup/linkup_extract_worker.py | LinkupExtractWorker._extract_pages | ValueError | invariant+pipelex/providers/mistral/mistral_factory.py | MistralFactory.make_mistral_document_url | TypeError | invariant+pipelex/providers/mistral/mistral_factory.py | MistralFactory.make_mistral_document_url_chunk_from_uri | TypeError | invariant+pipelex/providers/mistral/mistral_factory.py | MistralFactory.make_mistral_image_url | TypeError | invariant+pipelex/providers/mistral/mistral_factory.py | MistralFactory.make_mistral_image_url_chunk_from_uri | TypeError | invariant+pipelex/providers/mistral/mistral_factory.py | MistralFactory.make_simple_messages_openai_typed | TypeError | invariant+pipelex/providers/openai/openai_completions_factory.py | OpenAICompletionsFactory.make_simple_messages | TypeError | invariant+pipelex/providers/openai/openai_completions_factory.py | OpenAICompletionsFactory.make_simple_messages | TypeError | invariant+pipelex/providers/openai/openai_responses_factory.py | OpenAIResponsesFactory.make_input_items | TypeError | invariant+pipelex/providers/openai/openai_responses_factory.py | OpenAIResponsesFactory.make_input_items | TypeError | invariant+pipelex/providers/portkey/portkey_completions_factory.py | PortkeyCompletionsFactory.make_simple_messages | TypeError | invariant+pipelex/providers/portkey/portkey_completions_factory.py | PortkeyCompletionsFactory.make_simple_messages | TypeError | invariant+pipelex/runtime_boot.py | RuntimeBoot.get_instance | RuntimeError | invariant+pipelex/runtime_hub.py | RuntimeHub.get_bundle_validator_registry | RuntimeError | invariant+pipelex/runtime_hub.py | RuntimeHub.get_inference_backend_registry | RuntimeError | invariant+pipelex/runtime_hub.py | RuntimeHub.get_instance | RuntimeError | invariant+pipelex/runtime_hub.py | RuntimeHub.get_model_lister_registry | RuntimeError | invariant+pipelex/runtime_hub.py | RuntimeHub.get_orchestrator_registry | RuntimeError | invariant+pipelex/runtime_hub.py | RuntimeHub.get_required_config | RuntimeError | invariant+pipelex/runtime_hub.py | RuntimeHub.get_required_content_generator | RuntimeError | invariant+pipelex/runtime_hub.py | RuntimeHub.get_required_models_manager | RuntimeError | invariant+pipelex/runtime_hub.py | RuntimeHub.get_required_secrets_provider | RuntimeError | invariant+pipelex/runtime_hub.py | RuntimeHub.get_sdk_client_manager | RuntimeError | invariant+pipelex/runtime_hub.py | RuntimeHub.get_secrets_provider_registry | RuntimeError | invariant+pipelex/runtime_hub.py | RuntimeHub.get_storage_provider | RuntimeError | invariant+pipelex/runtime_hub.py | RuntimeHub.get_storage_provider_registry | RuntimeError | invariant+pipelex/runtime_hub.py | RuntimeHub.get_telemetry_manager | RuntimeError | invariant+pipelex/runtime_hub.py | RuntimeHub.get_template_file_stage | RuntimeError | invariant+pipelex/runtime_hub.py | RuntimeHub.set_console_print_target | ValueError | invariant+pipelex/suggested_fix.py | _refuse_wildcard_key | ValueError | validator+pipelex/system/telemetry/otel_constants.py | make_otel_gen_ai_output_type | ValueError | invariant+pipelex/system/usage_stats/usage_stats_core.py | UsageStatsState.replace_installation_id | OSError | caught+pipelex/tools/jinja2/jinja2_render_budget.py | RenderBudget._refuse | RenderBudgetExceededError | carrier+pipelex/tools/jinja2/jinja2_render_budget.py | refuse_int_result | RenderBudgetExceededError | carrier+pipelex/tools/jinja2/jinja2_render_charging.py | charged_filter | TypeError | invariant+pipelex/tools/jinja2/jinja2_render_charging.py | charged_test | TypeError | invariant+pipelex/tools/jinja2/jinja2_render_charging.py | render_budget_of | TypeError | invariant+pipelex/tools/jinja2/jinja2_render_rewrite.py | rewrite_for_render_budget | TypeError | invariant+pipelex/tools/jinja2/jinja2_sandbox.py | PipelexTemplateEnvironment._generate | RuntimeError | invariant+pipelex/tools/jinja2/jinja2_template_loader.py | TemplateLoader.load | ValueError | invariant+pipelex/tools/jinja2/jinja2_template_registry.py | TemplateRegistry.get | KeyError | invariant+pipelex/tools/jinja2/template_surface.py | TemplateSurface.__post_init__ | ValueError | invariant+pipelex/tools/log/console_layouts.py | PipeRunLayout.derived_values | TypeError | invariant+pipelex/tools/log/console_layouts.py | PipeRunLayout.derived_values | ValueError | invariant+pipelex/tools/log/console_layouts.py | _format_token_count | TypeError | invariant+pipelex/tools/log/console_layouts.py | format_cost | TypeError | invariant+pipelex/tools/log/console_layouts.py | format_duration | TypeError | invariant+pipelex/tools/log/console_layouts.py | format_duration | ValueError | invariant+pipelex/tools/log/gcp_log_sink.py | GcpLogSink.make_handler | RuntimeError | invariant+pipelex/tools/log/log.py | Log.configure | RuntimeError | invariant+pipelex/tools/log/log.py | Log.install_sink | RuntimeError | invariant+pipelex/tools/log/log.py | Log.install_sink | RuntimeError | invariant+pipelex/tools/log/log_dispatch.py | LogDispatch.configure | RuntimeError | invariant+pipelex/tools/log/log_sink.py | stream_for_target | ValueError | invariant+pipelex/tools/log/otlp_log_sink.py | OtlpLogSink.make_handler | RuntimeError | invariant+pipelex/tools/misc/async_utils.py | gather_bounded | ValueError | invariant+pipelex/tools/misc/file_utils.py | mirror_dir | FileNotFoundError | tooling+pipelex/tools/misc/file_utils.py | mirror_dir | NotADirectoryError | tooling+pipelex/tools/misc/file_utils.py | reject_bare_str_or_path | TypeError | invariant+pipelex/tools/network/ssrf_guard.py | resolve_to_allowed_ips | ConnectTimeout | carrier+pipelex/tools/typing/pydantic_utils.py | clean_model_to_dict | TypeError | invariantdiff --git a/tests/helpers/error_report.py b/tests/helpers/error_report.pyindex 4eec8da40..62cc31cfe 100644--- a/tests/helpers/error_report.py+++ b/tests/helpers/error_report.py@@ -1,16 +1,19 @@"""Test helper for building ``ErrorReport`` instances with sensible defaults.-After Item A introduced required ``title`` / ``type_uri`` fields, every test-fixture that constructs an ``ErrorReport`` directly must pass them. Tests whose-focus is classification, HTTP status, or domain — not serialization — use this-helper so each fixture stays a single readable call. Serialization /-round-trip / disclosure tests should pass real values instead.+Every ``ErrorReport`` requires its ``code``, ``title`` and ``type_uri``, so every+test fixture that constructs one directly must pass them. Tests whose focus is+classification, HTTP status, or domain — not serialization — use this helper so+each fixture stays a single readable call. Serialization / round-trip /+disclosure tests should pass real values instead, or build the report with+``ErrorReport.make_for_code``, which reads them from the code."""from __future__ import annotationsfrom typing import TYPE_CHECKING+from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import ErrorReportif TYPE_CHECKING:@@ -24,6 +27,7 @@ def make_error_report(error_type: str = "TestError",message: str = "test error message",*,+ code: str = CoreCode.RUNTIME_UNEXPECTED,title: str = _DEFAULT_TITLE,type_uri: str = _DEFAULT_TYPE_URI,error_category: str | None = None,@@ -34,8 +38,9 @@ def make_error_report(provider: str | None = None,provider_metadata: ProviderErrorMetadata | None = None,) -> ErrorReport:- """Build an ``ErrorReport`` with test-friendly defaults for ``title`` / ``type_uri``."""+ """Build an ``ErrorReport`` with test-friendly defaults for ``code`` / ``title`` / ``type_uri``."""return ErrorReport(+ code=code,error_type=error_type,message=message,title=title,diff --git a/tests/integration/pipelex/libraries/test_unresolved_package_dependency.py b/tests/integration/pipelex/libraries/test_unresolved_package_dependency.pyindex 229af1f31..4790291b0 100644--- a/tests/integration/pipelex/libraries/test_unresolved_package_dependency.py+++ b/tests/integration/pipelex/libraries/test_unresolved_package_dependency.py@@ -17,14 +17,15 @@ from mthds.package.exceptions import VCSFetchErrorfrom mthds.package.manifest.parser import parse_methods_tomlfrom pytest_mock import MockerFixture-from pipelex.base_exceptions import DisclosureMode, ValidationErrorCategory, ValidationErrorItem+from pipelex.base_exceptions import DisclosureMode, ErrorDomain, ValidationErrorCategory, ValidationErrorItem+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.interpreter_hub import get_library_managerfrom pipelex.libraries.exceptions import LibraryLoadingErrorfrom pipelex.methods.exceptions import MethodInstallError, MethodPackageNotFoundErrorfrom pipelex.methods.fetching import FetchedMethodPackage, fetch_method_packagefrom pipelex.methods.method_ref import MethodRef, parse_method_reffrom pipelex.mthds_parsing.parser import MthdsParser-from pipelex.pipeline.exceptions import ValidateBundleError+from pipelex.pipeline.exceptions import HostLibraryLoadRefusalError, ValidateBundleErrorfrom pipelex.pipeline.execution_seams import acquire_libraryfrom pipelex.pipeline.validate_bundle import validate_bundlefrom pipelex.tools.log.error_fields import ERROR_MESSAGE_FIELD, ERROR_TYPE_FIELD@@ -225,8 +226,11 @@ class TestUnresolvedPackageDependency:host_dir.mkdir()write_consumer(root=host_dir, bundles={"consumer.mthds": ProbePackageTestData.CONSUMER_BUNDLE})- with pytest.raises(LibraryLoadingError) as exc_info:+ with pytest.raises(HostLibraryLoadRefusalError) as exc_info:acquire_library(library_id="", library_dirs=[str(host_dir)])- assert not isinstance(exc_info.value, ValidateBundleError)- assert exc_info.value.to_error_report().error_domain is None+ # The refusal is the deployment's misconfiguration, raised from the library's own refusal, which the operator reads.+ assert isinstance(exc_info.value.__cause__, LibraryLoadingError)+ report = exc_info.value.to_error_report()+ assert report.code == PipelexErrorCode.CONFIG_INVALID+ assert report.error_domain is not ErrorDomain.INPUTdiff --git a/tests/integration/pipelex/pipeline/test_condition_expression_parse_refusal.py b/tests/integration/pipelex/pipeline/test_condition_expression_parse_refusal.pyindex ae7aea19f..c417b2666 100644--- a/tests/integration/pipelex/pipeline/test_condition_expression_parse_refusal.py+++ b/tests/integration/pipelex/pipeline/test_condition_expression_parse_refusal.py@@ -6,8 +6,8 @@ bundle answers with the same verdict, which a hosted run serves as HTTP 422. Befescaped the load, so validation gave no verdict and a hosted run answered 500 "An internal error occurred.".The item quotes neither the expression nor the parser's diagnosis, which names the token it stopped at: the-verdict is kept verbatim under STRICT disclosure, and a condition declared in a host's library directories must-not put its text there.+verdict is kept verbatim under STRICT disclosure. A condition declared in a host's library directories is no+verdict at all but the deployment's fault, whose text STRICT redacts."""import json@@ -17,7 +17,7 @@ from typing import Anyimport pytestfrom pipelex.base_exceptions import DisclosureMode, ValidationErrorCategory, ValidationErrorItem-from pipelex.pipeline.exceptions import ValidateBundleError+from pipelex.pipeline.exceptions import HostLibraryLoadRefusalError, ValidateBundleErrorfrom pipelex.pipeline.runner import PipelexMTHDSProtocolfrom pipelex.pipeline.validate_bundle import validate_bundlefrom tests.integration.pipelex.pipeline.test_data import ConditionExpressionParseTestData, ConditionMethodFaultsTestData@@ -115,17 +115,17 @@ class TestConditionExpressionParseRefusal:assert document["user_action"]["kind"] == "change_input"assert expression_text not in json.dumps(document)- async def test_a_host_library_condition_puts_none_of_its_text_in_the_strict_verdict(self, tmp_path: Path) -> None:- """Beside a host's library directory, the refusal of its condition names neither its expression nor its file."""+ async def test_a_host_library_condition_puts_none_of_its_text_in_the_strict_payload(self, tmp_path: Path) -> None:+ """Beside a host's library directory, the refusal of its condition is the host's fault, naming neither its expression nor its file."""host_library_dir = tmp_path / "host" / "library"host_library_dir.mkdir(parents=True)(host_library_dir / "routing.mthds").write_text(ConditionExpressionParseTestData.UNKNOWN_TAG_TEMPLATE_MTHDS, encoding="utf-8")- with pytest.raises(ValidateBundleError) as exc_info:+ with pytest.raises(HostLibraryLoadRefusalError) as exc_info:await validate_bundle(mthds_contents=[ConditionExpressionParseTestData.VALID_CALLER_MTHDS], library_dirs=[host_library_dir])strict_payload = exc_info.value.to_error_report().to_dict(disclosure_mode=DisclosureMode.STRICT)- assert _strict_item_messages(strict_payload) == [_TEMPLATE_REASON]+ assert "validation_errors" not in strict_payloadserialized_payload = json.dumps(strict_payload)assert "frobnicate_the_parcel" not in serialized_payloadassert "lane ==" not in serialized_payloaddiff --git a/tests/integration/pipelex/pipeline/test_data.py b/tests/integration/pipelex/pipeline/test_data.pyindex 44c7177e3..569d610e4 100644--- a/tests/integration/pipelex/pipeline/test_data.py+++ b/tests/integration/pipelex/pipeline/test_data.py@@ -569,6 +569,90 @@ prompt = "Pitch this company in one sentence: $description""""+class RenderTimeTemplateTestData:+ """Bundles whose template names a filter its environment lacks inside a branch, which only rendering that branch finds."""++ UNKNOWN_FILTER: ClassVar[str] = "frob_the_lane"+ # Text of the templates that no refusal may quote.+ TEMPLATE_TEXT: ClassVar[str] = "quietly_routed"++ # A condition whose expression parses and compiles, since its unknown filter sits in a branch, and which a run taking+ # that branch cannot render.+ CONDITION_MTHDS: ClassVar[str] = """+domain = "render_time_template_condition"+description = "Send a parcel down the lane the request names"+main_pipe = "route_parcel"++[concept]+Parcel = "A parcel waiting at the sorting bench"++[pipe.route_parcel]+type = "PipeCondition"+description = "Choose the lane a parcel goes down"+inputs = { parcel = "Parcel", lane = "Text" }+output = "Parcel"+expression_template = "{% if lane.text == 'express' %}{{ lane.text | frob_the_lane }}{% else %}quietly_routed{% endif %}"+outcomes = { express = "send_express" }+default_outcome = "send_standard"++[pipe.send_express]+type = "PipeCompose"+description = "Note the parcel onto the express lane"+inputs = { parcel = "Parcel" }+output = "Parcel"+template = "Express: $parcel"++[pipe.send_standard]+type = "PipeCompose"+description = "Note the parcel onto the standard lane"+inputs = { parcel = "Parcel" }+output = "Parcel"+template = "Standard: $parcel"+"""++ # Replaced by the prompt field each case puts the branch in, `prompt` or `system_prompt`.+ PROMPT_FIELD_SLOT: ClassVar[str] = "<prompt-field>"+ # A step whose prompt is only parsed at load, so its unknown filter in a branch passes the load and fails the render.+ LLM_MTHDS: ClassVar[str] = """+domain = "render_time_template_llm"+description = "Summarize a topic"+main_pipe = "summarize"++[pipe.summarize]+type = "PipeLLM"+description = "Summarize the topic"+inputs = { topic = "Text" }+output = "Text"+<prompt-field> = "{% if topic %}Summarize {{ topic.text | frob_the_lane }}{% else %}quietly_routed{% endif %}"+"""+ # The other prompt field, which renders, beside the one naming the unknown filter.+ PLAIN_PROMPT: ClassVar[str] = 'prompt = "Summarize $topic"'++ # A filter the deployment's structure-prompt template names and its environment lacks, which no method wrote.+ UNKNOWN_STRUCTURE_FILTER: ClassVar[str] = "frob_the_structure"+ # The deployment's structure-prompt template, edited to name that filter inside a branch.+ BROKEN_STRUCTURE_PROMPT: ClassVar[str] = "{% if class_structure_str %}{{ class_structure_str | frob_the_structure }}{% endif %}"+ # A step with a structured output, whose prompt renders and whose structure prompt is the deployment's template.+ STRUCTURED_LLM_MTHDS: ClassVar[str] = """+domain = "render_time_template_structure"+description = "Read a parcel label"+main_pipe = "read_label"++[concept.ParcelLabel]+description = "The label on a parcel"++[concept.ParcelLabel.structure]+recipient = { type = "text", description = "Who the parcel is for" }++[pipe.read_label]+type = "PipeLLM"+description = "Read the label off a note"+inputs = { note = "Text" }+output = "ParcelLabel"+prompt = "Read the label from $note"+"""++class ResolveBundleTestData:"""Bundles the host-facing resolve cores are pinned with."""diff --git a/tests/integration/pipelex/pipeline/test_execute_request_id.py b/tests/integration/pipelex/pipeline/test_execute_request_id.pyindex 89089590b..6fcf56b4c 100644--- a/tests/integration/pipelex/pipeline/test_execute_request_id.py+++ b/tests/integration/pipelex/pipeline/test_execute_request_id.py@@ -3,11 +3,13 @@ from __future__ import annotationsfrom typing import TYPE_CHECKINGimport pytest+from mthds.protocol.problem.registry import CoreCodefrom typing_extensions import overridefrom pipelex.interpreter_hub import get_pipe_runfrom pipelex.pipe_run.pipe_run_protocol import PipeRunProtocolfrom pipelex.pipeline.runner import PipelexMTHDSProtocol+from pipelex.system.exceptions import RunParameterErrorfrom tests.integration.pipelex.pipeline.test_data import ExecuteRequestIdTestDataif TYPE_CHECKING:@@ -56,11 +58,11 @@ class TestExecuteRequestId:@pytest.mark.parametrize("bad_request_id", ["forged\nline", "", "x" * 129])async def test_malformed_request_id_is_the_hosts_bug_refused_before_the_run(self, bad_request_id: str) -> None:- """Refused as a `ValueError`, not relabelled as the caller's invalid input, and no job is set up."""+ """Refused as the host's own run parameter, not relabelled as the caller's bundle or inputs, and no job is set up."""pipe_run = _RecordingPipeRun()runner = PipelexMTHDSProtocol(pipe_run=pipe_run)- with pytest.raises(ValueError, match="Invalid request_id") as exc_info:+ with pytest.raises(RunParameterError, match="Invalid request_id") as exc_info:await runner.execute(pipe_code="restate",mthds_contents=[ExecuteRequestIdTestData.COMPOSE_MTHDS],@@ -68,5 +70,6 @@ class TestExecuteRequestId:request_id=bad_request_id,)- assert type(exc_info.value) is ValueError+ assert type(exc_info.value) is RunParameterError+ assert exc_info.value.to_error_report().code == CoreCode.REQUEST_INVALIDassert pipe_run.pipe_jobs == []diff --git a/tests/integration/pipelex/pipeline/test_host_library_load_refusals.py b/tests/integration/pipelex/pipeline/test_host_library_load_refusals.pynew file mode 100644index 000000000..f8b65f807--- /dev/null+++ b/tests/integration/pipelex/pipeline/test_host_library_load_refusals.py@@ -0,0 +1,139 @@+"""Pin: a method of a host's own library directories that refuses to load is the deployment's fault, not the caller's input.++A server loads its library directories beside a request's bundles, and those directories are the deployment's, not the+caller's (`library_dirs_are_callers` False). A pipe there that its factory refuses, or that names a model the deck does+not define, used to be answered as the caller's invalid input, a 422 carrying the host library's own text. It is now+`pipelex.config.invalid`, an operator fault, whose message STRICT disclosure withholds. The same refusal in the caller's+own content stays the caller's: a 422 verdict with one input item.+"""++import json+from pathlib import Path++import pytest++from pipelex.base_exceptions import INTERNAL_ERROR_PLACEHOLDER, DisclosureMode, ErrorDomain, PipelexError+from pipelex.errors.registry.pipelex_codes import PipelexErrorCode+from pipelex.pipeline.exceptions import HostLibraryLoadRefusalError, ValidateBundleError+from pipelex.pipeline.runner import PipelexMTHDSProtocol+from pipelex.pipeline.validate_bundle import validate_bundle++# Text of the host library's bundles that no STRICT answer may carry.+_HOST_TEXT = "almanac"++# A factory refusal: a PipeExtract whose input is neither an image nor a document.+_FACTORY_REFUSAL_BUNDLE = """+domain = "host_almanac_reading"+description = "Read the pages of a tide almanac"++[pipe.read_almanac_pages]+type = "PipeExtract"+description = "Read each page of the tide almanac"+inputs = { almanac_text = "Text" }+output = "Page[]"+"""++# A model-choice refusal: a PipeLLM naming a model the deck does not define.+_MODEL_CHOICE_REFUSAL_BUNDLE = """+domain = "host_almanac_notes"+description = "Write notes about a tide almanac"++[pipe.write_almanac_note]+type = "PipeLLM"+description = "Write a note about the tide almanac"+inputs = { almanac_text = "Text" }+output = "Text"+model = "gpt-5.6-almanac-lunna"+prompt = "Write a note about this tide almanac: $almanac_text"+"""++# The caller's own bundle, which is valid.+_CALLER_BUNDLE = """+domain = "caller_greeting"+description = "Greet someone"+main_pipe = "greet"++[pipe.greet]+type = "PipeCompose"+description = "Greet someone by name"+inputs = { name = "Text" }+output = "Text"+template = "Hello $name"+"""++_REFUSING_BUNDLES = pytest.mark.parametrize(+ "refusing_bundle",+ [_FACTORY_REFUSAL_BUNDLE, _MODEL_CHOICE_REFUSAL_BUNDLE],+ ids=["factory_refusal", "model_choice_refusal"],+)+++def _host_library_dir(*, directory: Path, refusing_bundle: str) -> Path:+ library_dir = directory / "host_library"+ library_dir.mkdir()+ (library_dir / "almanac.mthds").write_text(refusing_bundle, encoding="utf-8")+ return library_dir+++def _assert_is_the_deployments_fault(*, error: PipelexError) -> None:+ report = error.to_error_report()+ assert report.code == PipelexErrorCode.CONFIG_INVALID+ assert report.error_domain != ErrorDomain.INPUT+ assert report.validation_errors is None+ # Locally the operator reads which method refused; a STRICT caller reads none of the host library's text.+ assert _HOST_TEXT in report.message+ strict_payload = report.to_dict(disclosure_mode=DisclosureMode.STRICT)+ assert strict_payload["message"] == INTERNAL_ERROR_PLACEHOLDER+ assert _HOST_TEXT not in json.dumps(strict_payload)+ document = report.to_problem_document(disclosure_mode=DisclosureMode.STRICT)+ assert document["status"] == 500+ assert _HOST_TEXT not in json.dumps(document)++[email protected](loop_scope="class")+class TestHostLibraryLoadRefusals:+ @_REFUSING_BUNDLES+ async def test_a_host_library_refusal_at_validation_is_the_deployments_fault(self, tmp_path: Path, refusing_bundle: str) -> None:+ """Validating the caller's bundle beside a host library that refuses: no verdict, an operator fault."""+ library_dir = _host_library_dir(directory=tmp_path, refusing_bundle=refusing_bundle)++ with pytest.raises(HostLibraryLoadRefusalError) as exc_info:+ await validate_bundle(mthds_contents=[_CALLER_BUNDLE], library_dirs=[library_dir])++ _assert_is_the_deployments_fault(error=exc_info.value)++ @_REFUSING_BUNDLES+ async def test_a_host_library_refusal_at_run_is_the_deployments_fault(self, tmp_path: Path, refusing_bundle: str) -> None:+ """Running the caller's bundle beside a host library that refuses: an operator fault, never the caller's input."""+ library_dir = _host_library_dir(directory=tmp_path, refusing_bundle=refusing_bundle)++ with pytest.raises(PipelexError) as exc_info:+ await PipelexMTHDSProtocol(library_dirs=[str(library_dir)]).execute(+ pipe_code="greet", mthds_contents=[_CALLER_BUNDLE], inputs={"name": "Ada"}+ )++ assert not isinstance(exc_info.value, ValidateBundleError)+ _assert_is_the_deployments_fault(error=exc_info.value)++ @_REFUSING_BUNDLES+ async def test_the_same_refusal_in_the_callers_content_stays_the_callers(self, refusing_bundle: str) -> None:+ """The refusal in the caller's own content: a 422 verdict with one input item, as before."""+ with pytest.raises(ValidateBundleError) as exc_info:+ await validate_bundle(mthds_contents=[refusing_bundle])++ report = exc_info.value.to_error_report()+ assert report.error_domain == ErrorDomain.INPUT+ assert report.to_problem_document(disclosure_mode=DisclosureMode.STRICT)["status"] == 422+ assert len(report.validation_errors or []) == 1++ @_REFUSING_BUNDLES+ async def test_a_refusal_in_the_callers_own_library_dirs_stays_the_callers(self, tmp_path: Path, refusing_bundle: str) -> None:+ """A local run whose library directories are the caller's own: the refusal is the caller's invalid bundle."""+ library_dir = _host_library_dir(directory=tmp_path, refusing_bundle=refusing_bundle)++ with pytest.raises(ValidateBundleError) as exc_info:+ await PipelexMTHDSProtocol(library_dirs=[str(library_dir)], library_dirs_are_callers=True).execute(+ pipe_code="greet", mthds_contents=[_CALLER_BUNDLE], inputs={"name": "Ada"}+ )++ assert exc_info.value.to_error_report().error_domain == ErrorDomain.INPUTdiff --git a/tests/integration/pipelex/pipeline/test_located_run_failure.py b/tests/integration/pipelex/pipeline/test_located_run_failure.pyindex 0cf47dff4..c1a9bf939 100644--- a/tests/integration/pipelex/pipeline/test_located_run_failure.py+++ b/tests/integration/pipelex/pipeline/test_located_run_failure.py@@ -3,11 +3,13 @@ from __future__ import annotationsfrom typing import TYPE_CHECKINGimport pytest+from mthds.protocol.problem.registry import CoreCodefrom typing_extensions import overridefrom pipelex.base_exceptions import INTERNAL_ERROR_PLACEHOLDER, DisclosureMode, ErrorReport, PipelexErrorfrom pipelex.cogt.inference.error_classification import UserAction, UserActionKindfrom pipelex.config import get_config+from pipelex.errors.error_codes import error_code_specfrom pipelex.pipe_run.exceptions import PipeRouterError, find_failure_locationfrom pipelex.pipe_run.pipe_router import PipeRouterfrom pipelex.pipe_run.pipe_run import PipeRun@@ -97,8 +99,9 @@ class TestLocatedRunFailure:report = error.to_error_report()assert report.error_type == "ModelNotFoundError"- assert report.title == "Model not found"- assert report.type_uri.endswith("/model-not-found-error/")+ assert report.code == CoreCode.MODEL_UNKNOWN+ assert report.title == error_code_spec(CoreCode.MODEL_UNKNOWN).title+ assert report.type_uri == error_code_spec(CoreCode.MODEL_UNKNOWN).type_uriunserved_handle = LocatedRunFailureTestData.UNSERVED_MODEL_HANDLEassert report.message == f"Pipe 'summarize' failed (two_steps → summarize): Model handle '{unserved_handle}' was not found in the model deck."# The local-deck remedy is the local CLI's to give: the message reaches hosted readers too.diff --git a/tests/integration/pipelex/pipeline/test_render_time_template_refusals.py b/tests/integration/pipelex/pipeline/test_render_time_template_refusals.pynew file mode 100644index 000000000..4988b4e21--- /dev/null+++ b/tests/integration/pipelex/pipeline/test_render_time_template_refusals.py@@ -0,0 +1,117 @@+"""Pin: a template that names a filter its environment lacks, inside a branch, is refused at render as the method's fault.++Jinja2 compiles a filter or a test inside a branch to a lookup that only fails when the branch renders, and a prompt is+only parsed at load, so such a template passes the load and fails the run. The failure used to escape as a raw+`TemplateRuntimeError`, or as a `Jinja2TemplateRenderError` that is not the caller's fault, and a hosted run answered+500 "An internal error occurred.". It is now `method.template_invalid`: a located refusal naming the pipe, the+template's field and the filter Jinja2 refused, kept under STRICT disclosure, which never quotes the template's text.+"""++from __future__ import annotations++import json+from typing import TYPE_CHECKING, Any++import pytest+from mthds.protocol.problem.registry import CoreCode++from pipelex.base_exceptions import INTERNAL_ERROR_PLACEHOLDER, DisclosureMode+from pipelex.config import get_config+from pipelex.pipeline.exceptions import PipelineExecutionError+from pipelex.pipeline.runner import PipelexMTHDSProtocol+from pipelex.system.pipe_run_mode import PipeRunMode+from tests.integration.pipelex.pipeline.test_data import RenderTimeTemplateTestData++if TYPE_CHECKING:+ from pytest_mock import MockerFixture++_UNKNOWN_FILTER_FAULT = f"No filter named '{RenderTimeTemplateTestData.UNKNOWN_FILTER}' found."+++def _llm_bundle(*, prompt_field: str) -> str:+ bundle = RenderTimeTemplateTestData.LLM_MTHDS.replace(RenderTimeTemplateTestData.PROMPT_FIELD_SLOT, prompt_field)+ if prompt_field == "system_prompt":+ bundle += RenderTimeTemplateTestData.PLAIN_PROMPT + "\n"+ return bundle+++async def _failed_run(*, pipe_code: str, bundle: str, inputs: dict[str, Any], pipe_run_mode: PipeRunMode) -> PipelineExecutionError:+ with pytest.raises(PipelineExecutionError) as exc_info:+ await PipelexMTHDSProtocol(pipe_run_mode=pipe_run_mode).execute(pipe_code=pipe_code, mthds_contents=[bundle], inputs=inputs)+ return exc_info.value+++def _assert_is_the_refusal(*, error: PipelineExecutionError, detail: str, next_step: str) -> None:+ report = error.to_error_report()+ assert report.code == CoreCode.METHOD_TEMPLATE_INVALID+ assert report.message == detail+ assert report.user_action is not None+ assert report.user_action.detail == next_step++ strict_payload = report.to_dict(disclosure_mode=DisclosureMode.STRICT)+ assert strict_payload["message"] == detail+ assert strict_payload["message"] != INTERNAL_ERROR_PLACEHOLDER+ assert strict_payload["user_action"] == {"kind": "change_input", "detail": next_step}+ document = report.to_problem_document(disclosure_mode=DisclosureMode.STRICT)+ assert document["status"] == 422+ assert document["detail"] == detail+ # Neither the template's text nor the branch it would have rendered reaches the caller.+ assert RenderTimeTemplateTestData.TEMPLATE_TEXT not in json.dumps(document)+ assert "{%" not in json.dumps(document)++[email protected](loop_scope="class")+class TestRenderTimeTemplateRefusals:+ async def test_a_condition_expression_naming_an_unknown_filter_in_a_branch_is_refused(self) -> None:+ """A live run taking the branch: `method.template_invalid` at the condition, its expression and the unknown filter named."""+ error = await _failed_run(+ pipe_code="route_parcel",+ bundle=RenderTimeTemplateTestData.CONDITION_MTHDS,+ inputs={"parcel": "a box of books", "lane": "express"},+ pipe_run_mode=PipeRunMode.LIVE,+ )++ _assert_is_the_refusal(+ error=error,+ detail=f"Pipe 'route_parcel' failed: PipeCondition 'route_parcel': its expression cannot render: {_UNKNOWN_FILTER_FAULT}",+ next_step=f"Fix the expression of PipeCondition 'route_parcel': {_UNKNOWN_FILTER_FAULT}",+ )++ @pytest.mark.parametrize("prompt_field", ["prompt", "system_prompt"])+ async def test_an_llm_prompt_naming_an_unknown_filter_in_a_branch_is_refused(self, prompt_field: str) -> None:+ """A dry run renders the prompt as a live run does: `method.template_invalid` naming the step, the prompt field and the filter."""+ error = await _failed_run(+ pipe_code="summarize",+ bundle=_llm_bundle(prompt_field=prompt_field),+ inputs={"topic": "the tides"},+ pipe_run_mode=PipeRunMode.DRY,+ )++ _assert_is_the_refusal(+ error=error,+ detail=f"Pipe 'summarize' failed: PipeLLM 'summarize': its {prompt_field} cannot render: {_UNKNOWN_FILTER_FAULT}",+ next_step=f"Fix the {prompt_field} of PipeLLM 'summarize': {_UNKNOWN_FILTER_FAULT}",+ )++ async def test_a_broken_deployment_structure_prompt_is_ours_and_withheld(self, mocker: MockerFixture) -> None:+ """The structure prompt is the deployment's template, rendered in the step: `runtime.unexpected`, a 500 whose message STRICT withholds."""+ mocker.patch.dict(+ get_config().inference.llm.generic_templates,+ {"output_structure_prompt": RenderTimeTemplateTestData.BROKEN_STRUCTURE_PROMPT},+ )++ error = await _failed_run(+ pipe_code="read_label",+ bundle=RenderTimeTemplateTestData.STRUCTURED_LLM_MTHDS,+ inputs={"note": "To Ada, third floor"},+ pipe_run_mode=PipeRunMode.DRY,+ )++ report = error.to_error_report()+ assert report.code == CoreCode.RUNTIME_UNEXPECTED+ assert report.error_type == "Jinja2TemplateInvalidError"+ assert report.to_dict(disclosure_mode=DisclosureMode.STRICT)["message"] == INTERNAL_ERROR_PLACEHOLDER+ document = report.to_problem_document(disclosure_mode=DisclosureMode.STRICT)+ assert document["status"] == 500+ # Neither the deployment's template nor what Jinja2 refused in it reaches the caller.+ assert RenderTimeTemplateTestData.UNKNOWN_STRUCTURE_FILTER not in json.dumps(document)diff --git a/tests/integration/pipelex/pipeline/test_run_path_bundle_verdict.py b/tests/integration/pipelex/pipeline/test_run_path_bundle_verdict.pyindex 42342b5cf..7be798f83 100644--- a/tests/integration/pipelex/pipeline/test_run_path_bundle_verdict.py+++ b/tests/integration/pipelex/pipeline/test_run_path_bundle_verdict.py@@ -15,7 +15,8 @@ reading "Input validation failed".``runtime`` input-validation failure.- **The unknown entry pipe** is not a bundle fault: it still raises its own ``PipeNotFoundError``.- **Whose library directories.** A local caller's directories are theirs, so a refusal while loading- them is the verdict too, located on their file; a host's directories load untranslated by default.+ them is the verdict too, located on their file; by default the directories are the host's, and their refusal is the host's fault+ (``HostLibraryLoadRefusalError``), never a verdict."""from pathlib import Path@@ -25,9 +26,10 @@ import pytestfrom pipelex.base_exceptions import DisclosureModefrom pipelex.config import get_config+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.libraries.exceptions import LibraryErrorfrom pipelex.libraries.pipe.exceptions import PipeNotFoundError-from pipelex.pipeline.exceptions import PipeExecutionError, ValidateBundleError+from pipelex.pipeline.exceptions import HostLibraryLoadRefusalError, PipeExecutionError, ValidateBundleErrorfrom pipelex.pipeline.pipeline_run_setup import pipeline_run_setupfrom pipelex.pipeline.runner import PipelexMTHDSProtocolfrom pipelex.pipeline.validate_bundle import validate_bundle@@ -224,11 +226,12 @@ class TestRunPathBundleVerdict:await validate_bundle(mthds_file_path=bundle_path, library_dirs=[tmp_path])assert items == validated.value.to_error_report().validation_errors- async def test_a_hosts_library_dir_refusal_loads_untranslated_by_default(self, tmp_path: Path) -> None:+ async def test_a_hosts_library_dir_refusal_is_the_hosts_fault_by_default(self, tmp_path: Path) -> None:bundle_path = tmp_path / "bundle.mthds"bundle_path.write_text(_MISSPELLED_CONCEPT_BUNDLE, encoding="utf-8")- with pytest.raises(LibraryError) as raised:+ with pytest.raises(HostLibraryLoadRefusalError) as raised:await _run_setup(library_dirs=[str(tmp_path)], pipe_code="write_tide_notice")- assert not isinstance(raised.value, ValidateBundleError)+ assert isinstance(raised.value.__cause__, LibraryError)+ assert raised.value.to_error_report().code == PipelexErrorCode.CONFIG_INVALIDdiff --git a/tests/integration/pipelex/pipeline/test_validate_bundle_load_refusals.py b/tests/integration/pipelex/pipeline/test_validate_bundle_load_refusals.pyindex adfc541b2..7cfa5c0da 100644--- a/tests/integration/pipelex/pipeline/test_validate_bundle_load_refusals.py+++ b/tests/integration/pipelex/pipeline/test_validate_bundle_load_refusals.py@@ -24,15 +24,17 @@ full, except for the one-suggestion alias whose rename fix is the point of its c"""from pathlib import Path-from typing import ClassVar, NamedTuple+from typing import NamedTupleimport pytest+from mthds.protocol.problem.registry import CoreCodefrom pytest_mock import MockerFixture-from pipelex.base_exceptions import DisclosureMode, ErrorDomain, PipelexError, ValidationErrorCategory, ValidationErrorItem+from pipelex.base_exceptions import DisclosureMode, PipelexError, ValidationErrorCategory, ValidationErrorItemfrom pipelex.cogt.model_backends.model_type import ModelTypefrom pipelex.config import get_configfrom pipelex.core.pipes.exceptions import PipeOperatorModelChoiceError+from pipelex.errors.error_codes import PipelexErrorCode, error_code_specfrom pipelex.pipeline.exceptions import ValidateBundleErrorfrom pipelex.pipeline.fixes.planner import RENAME_MODEL_FIX_CODEfrom pipelex.pipeline.pipeline_run_setup import pipeline_run_setup@@ -236,21 +238,20 @@ async def _single_item(*, bundle_path: Path) -> ValidationErrorItem:class _CallerFacingRefusalError(PipelexError):"""An input refusal whose message was authored for the caller — stands in for any future one."""- error_domain = ErrorDomain.INPUT+ error_code = CoreCode.METHOD_INVALID_authors_caller_facing_message = Trueclass _InternalInputRefusalError(PipelexError):"""An input refusal whose message is internal text the verdict must not carry."""- error_domain = ErrorDomain.INPUT- _declared_title: ClassVar[str | None] = "Harbour board refusal"+ error_code = CoreCode.METHOD_SCHEMA_VIOLATIONclass _ConfigFaultError(PipelexError):"""A fault of the environment, which is no verdict about the bundle."""- error_domain = ErrorDomain.CONFIG+ error_code = PipelexErrorCode.CONFIG_INVALID@pytest.mark.asyncio(loop_scope="class")@@ -372,7 +373,7 @@ class TestValidateBundleLoadRefusals:assert item.pipe_code == "write_tide_note"assert item.source == str(bundle_path)- assert "Harbour board refusal" in item.message+ assert error_code_spec(CoreCode.METHOD_SCHEMA_VIOLATION).title in item.messageassert "registry slot 7" not in item.messageasync def test_config_fault_at_load_stays_no_verdict(self, tmp_path: Path, mocker: MockerFixture) -> None:diff --git a/tests/integration/pipelex/pipeline/test_validation_detail_kept.py b/tests/integration/pipelex/pipeline/test_validation_detail_kept.pyindex 3853b3403..af01f3baf 100644--- a/tests/integration/pipelex/pipeline/test_validation_detail_kept.py+++ b/tests/integration/pipelex/pipeline/test_validation_detail_kept.py@@ -18,11 +18,13 @@ Validation used to lose detail before the verdict was built. These tests load refrom pathlib import Pathimport pytest+from mthds.protocol.problem.registry import CoreCodefrom pytest_mock import MockerFixturefrom pipelex.base_exceptions import ValidationErrorCategory, ValidationErrorItemfrom pipelex.cogt.inference.error_classification import UserActionfrom pipelex.core.stuffs.exceptions import StuffFactoryError+from pipelex.errors.error_codes import error_code_specfrom pipelex.pipeline.exceptions import ValidateBundleErrorfrom pipelex.pipeline.validate_bundle import validate_bundlefrom pipelex.validation_error_types import PipeValidationErrorType@@ -88,7 +90,8 @@ class TestValidationDetailKept:(item,) = itemsassert item.pipe_code == "analyze_topic"- assert item.message == f"Pipe 'analyze_topic' failed its dry run: {StuffFactoryError.title()}"+ # The multiplicity refusal's code, which the combine chooses before it says whose fault it is.+ assert item.message == f"Pipe 'analyze_topic' failed its dry run: {error_code_spec(CoreCode.PIPE_OUTPUT_MULTIPLICITY).title}"@pytest.mark.asyncioasync def test_the_enclosing_pipe_alone_reports_the_innermost_failing_pipe(self) -> None:diff --git a/tests/integration/pipelex/pipeline/test_verdict_names_no_host_path.py b/tests/integration/pipelex/pipeline/test_verdict_names_no_host_path.pyindex 769e305be..ff5c22e6d 100644--- a/tests/integration/pipelex/pipeline/test_verdict_names_no_host_path.py+++ b/tests/integration/pipelex/pipeline/test_verdict_names_no_host_path.py@@ -8,10 +8,11 @@ used to put one there:and its bundles were named by their install path. They are named by the package's address and thebundle's path inside the package instead, on every surface: the ``source`` of an item located inside thedependency, and the files a duplicate declaration inside it names.-- **The host's own library directories.** When submitted content is validated, the library directories- loaded beside it are the host's: an item located in one of their files carries no ``source``, and a message- naming one of their files names ``<host library file>`` instead. A run loads a host's directories- untranslated, so their refusal is no verdict at all, and STRICT redacts it.+- **The host's own library directories.** When submitted content is validated or run, the library+ directories loaded beside it are the host's. A method of theirs that refuses to load is the deployment's+ fault, a ``HostLibraryLoadRefusalError`` and no verdict at all, so STRICT redacts it. A verdict on the+ caller's own content keeps their files out too: an item located in one of them carries no ``source``,+ and a message naming one of them names ``<host library file>`` instead.A bundle validated from a file keeps the full paths of its library directories: there they are the caller's, asthey are for a runtime told its library directories are the caller's own (``library_dirs_are_callers``).@@ -26,8 +27,9 @@ from pytest_mock import MockerFixturefrom pipelex.base_exceptions import DisclosureMode, ErrorDomain, PipelexError, ValidationErrorItemfrom pipelex.config import get_config+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.libraries.exceptions import HostLibraryTreeError-from pipelex.pipeline.exceptions import ValidateBundleError+from pipelex.pipeline.exceptions import HostLibraryLoadRefusalError, ValidateBundleErrorfrom pipelex.pipeline.pipeline_run_setup import pipeline_run_setupfrom pipelex.pipeline.runner import PipelexMTHDSProtocolfrom pipelex.pipeline.validate_bundle import validate_bundle@@ -352,60 +354,45 @@ class TestVerdictNamesNoHostPath:assert "linked_board.mthds" in raised.value.message- async def test_a_host_library_item_carries_no_source_on_submitted_content(self, tmp_path: Path) -> None:- host_library_dir = tmp_path / "host" / "library"- _write(path=host_library_dir / "harbour_board.mthds", content=_MISSPELLED_CONCEPT_LIBRARY_BUNDLE)-- with pytest.raises(ValidateBundleError) as raised:- await validate_bundle(mthds_contents=[_VALID_CALLER_BUNDLE], library_dirs=[host_library_dir])-- items = raised.value.to_error_report().validation_errors or []- concept_items = [item for item in items if item.error_type == PipeValidationErrorType.UNRESOLVED_CONCEPT]- assert concept_items, f"expected an unresolved_concept item, got {items!r}"- assert all(item.pipe_code == "pin_board_notice" for item in concept_items)- # Located by its pipe and domain, never by its file on the host.- assert all(item.source is None for item in items)- _assert_names_no_host_path(payload=_strict_payload(raised.value), tmp_path=tmp_path)-- async def test_a_host_library_pipe_located_from_its_source_names_no_host_file(self, tmp_path: Path) -> None:+ @pytest.mark.parametrize(+ "host_library_files",+ [+ {"harbour_board.mthds": _MISSPELLED_CONCEPT_LIBRARY_BUNDLE},+ {"harbour_board.mthds": _OUTPUT_MISMATCH_LIBRARY_BUNDLE},+ {"harbour_board.mthds": _BOARD_NOTICE_PIPE_BUNDLE, "harbour_board_copy.mthds": _BOARD_NOTICE_PIPE_BUNDLE},+ {"harbour_board.mthds": _HOST_PIPE_FUNC_BUNDLE, "board_formatting.py": _HOST_PIPE_FUNC_MODULE, "json.py": "SHADOW = True\n"},+ ],+ ids=["unresolved_concept", "sequence_output_mismatch", "duplicate_declaration", "pipe_func_refused"],+ )+ async def test_a_host_library_refusal_beside_submitted_content_is_the_host_s_fault(+ self, host_library_files: dict[str, str], tmp_path: Path+ ) -> None:+ """A method of the host's own directories that refuses to load is the deployment's fault: no verdict, and no host path."""host_library_dir = tmp_path / "host" / "library"- _write(path=host_library_dir / "harbour_board.mthds", content=_OUTPUT_MISMATCH_LIBRARY_BUNDLE)+ for file_name, content in host_library_files.items():+ _write(path=host_library_dir / file_name, content=content)- with pytest.raises(ValidateBundleError) as raised:+ with pytest.raises(HostLibraryLoadRefusalError) as raised:await validate_bundle(mthds_contents=[_VALID_CALLER_BUNDLE], library_dirs=[host_library_dir])- (item,) = raised.value.to_error_report().validation_errors or []- assert item.pipe_code == "post_board_notice"- assert item.source is None- assert item.field_path is None- _assert_names_no_host_path(payload=_strict_payload(raised.value), tmp_path=tmp_path)+ report = raised.value.to_error_report()+ assert report.code == PipelexErrorCode.CONFIG_INVALID+ assert report.error_domain != ErrorDomain.INPUT+ strict_payload = report.to_dict(disclosure_mode=DisclosureMode.STRICT)+ assert "validation_errors" not in strict_payload+ _assert_names_no_host_path(payload=strict_payload, tmp_path=tmp_path)- async def test_a_host_library_message_names_no_host_file_on_submitted_content(self, tmp_path: Path) -> None:+ async def test_a_verdict_on_the_callers_content_names_no_host_library_file(self, tmp_path: Path) -> None:+ """The caller's content declaring a pipe the host's directories declare too: the caller's verdict, naming no host file."""host_library_dir = tmp_path / "host" / "library"_write(path=host_library_dir / "harbour_board.mthds", content=_BOARD_NOTICE_PIPE_BUNDLE)- _write(path=host_library_dir / "harbour_board_copy.mthds", content=_BOARD_NOTICE_PIPE_BUNDLE)with pytest.raises(ValidateBundleError) as raised:- await validate_bundle(mthds_contents=[_VALID_CALLER_BUNDLE], library_dirs=[host_library_dir])+ await validate_bundle(mthds_contents=[_BOARD_NOTICE_PIPE_BUNDLE], library_dirs=[host_library_dir])(item,) = raised.value.to_error_report().validation_errors or []assert "harbour_board.pin_board_notice" in item.message- assert item.message.count(HOST_LIBRARY_FILE_PLACEHOLDER) >= 2- _assert_names_no_host_path(payload=_strict_payload(raised.value), tmp_path=tmp_path)-- async def test_a_host_library_pipe_func_refusal_names_no_host_path(self, tmp_path: Path) -> None:- host_library_dir = tmp_path / "host" / "library"- _write(path=host_library_dir / "harbour_board.mthds", content=_HOST_PIPE_FUNC_BUNDLE)- _write(path=host_library_dir / "board_formatting.py", content=_HOST_PIPE_FUNC_MODULE)- _write(path=host_library_dir / "json.py", content="SHADOW = True\n")-- with pytest.raises(ValidateBundleError) as raised:- await validate_bundle(mthds_contents=[_VALID_CALLER_BUNDLE], library_dirs=[host_library_dir])-- items = raised.value.to_error_report().validation_errors or []- refused_items = [item for item in items if item.error_type == PipeValidationErrorType.PIPE_FUNC_FUNCTION_REFUSED]- assert refused_items, f"expected a pipe_func_function_refused item, got {items!r}"- assert "standard-library module 'json'" in refused_items[0].message+ assert HOST_LIBRARY_FILE_PLACEHOLDER in item.message_assert_names_no_host_path(payload=_strict_payload(raised.value), tmp_path=tmp_path)async def test_a_run_answers_a_host_library_refusal_without_a_host_path(self, tmp_path: Path) -> None:@@ -433,13 +420,26 @@ class TestVerdictNamesNoHostPath:assert concept_items, f"expected an unresolved_concept item, got {items!r}"assert all(item.source == str(library_file) for item in concept_items)- @pytest.mark.parametrize("library_dirs_are_callers", [False, True], ids=["hosts_library", "callers_library"])- async def test_a_runtime_validates_content_against_the_library_it_is_told_is_whose(self, library_dirs_are_callers: bool, tmp_path: Path) -> None:+ async def test_a_runtime_told_its_library_is_the_hosts_answers_its_refusal_as_the_hosts_fault(self, tmp_path: Path) -> None:+ library_dir = tmp_path / "library"+ _write(path=library_dir / "harbour_board.mthds", content=_MISSPELLED_CONCEPT_LIBRARY_BUNDLE)+ runtime = PipelexMTHDSProtocol(+ library_dirs=[str(library_dir)],+ pipe_run_mode=PipeRunMode.DRY,+ execution_config=_execution_config(),+ )++ with pytest.raises(HostLibraryLoadRefusalError) as raised:+ await runtime.validate([_VALID_CALLER_BUNDLE])++ _assert_names_no_host_path(payload=raised.value.to_error_report().to_dict(disclosure_mode=DisclosureMode.STRICT), tmp_path=tmp_path)++ async def test_a_runtime_told_its_library_is_the_callers_validates_content_against_it(self, tmp_path: Path) -> None:library_dir = tmp_path / "library"library_file = _write(path=library_dir / "harbour_board.mthds", content=_MISSPELLED_CONCEPT_LIBRARY_BUNDLE)runtime = PipelexMTHDSProtocol(library_dirs=[str(library_dir)],- library_dirs_are_callers=library_dirs_are_callers,+ library_dirs_are_callers=True,pipe_run_mode=PipeRunMode.DRY,execution_config=_execution_config(),)@@ -450,5 +450,4 @@ class TestVerdictNamesNoHostPath:items = raised.value.to_error_report().validation_errors or []concept_items = [item for item in items if item.error_type == PipeValidationErrorType.UNRESOLVED_CONCEPT]assert concept_items, f"expected an unresolved_concept item, got {items!r}"- expected_source = str(library_file) if library_dirs_are_callers else None- assert all(item.source == expected_source for item in concept_items)+ assert all(item.source == str(library_file) for item in concept_items)diff --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 c23abe2e4..cd2a5272c 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@@ -4,8 +4,10 @@ from typing import TYPE_CHECKING, Anyimport pytestfrom typing_extensions import override+from pipelex.base_exceptions import DisclosureModefrom pipelex.cogt.doc_gen.doc_gen_format import DocGenFormat, DocGenSourcefrom pipelex.cogt.doc_gen.doc_gen_worker_abstract import DocGenWorkerAbstract+from pipelex.cogt.doc_gen.exceptions import DocGenEngineMissingErrorfrom pipelex.cogt.doc_gen.render_job import RenderedDocument, RenderJob, RenderResourcesfrom pipelex.cogt.doc_gen.template_check import TemplateCheckRequest, TemplateFindingfrom pipelex.cogt.inference.inference_worker_abstract import InferenceWorkerAbstract@@ -15,6 +17,7 @@ from pipelex.cogt.models.model_manager import ModelManagerfrom pipelex.config import get_configfrom pipelex.core.method_trees.method_file_store import MethodFileStoreProtocolfrom pipelex.core.pipes.pipe_output import PipeOutput+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.interpreter_hub import get_current_library, get_library_manager, set_current_libraryfrom pipelex.pipe_run.delivery_assignment import DeliveryAssignmentfrom pipelex.pipe_run.pipe_job import PipeJob@@ -155,6 +158,21 @@ def make_models_manager(*, plugin_model_declarations: PluginModelDeclarations, breturn models_manager+async def engine_unavailable_report(*, step_fields: str) -> str:+ """The error report, as text, of validating the test bundle with a PipeDocGen step no engine of this runtime prints.++ The bundle is not at fault: the runtime lacks the engine, which is the operator's to install or enable, so validation+ gives no verdict and the load's `DocGenEngineMissingError` propagates as `pipelex.docgen.engine_unavailable`, its+ message kept for the caller under STRICT disclosure.+ """+ with pytest.raises(DocGenEngineMissingError) as exc_info:+ await validate_bundle(mthds_contents=[PipeDocGenTestData.bundle(step_fields=step_fields)])+ report = exc_info.value.to_error_report()+ assert report.code == PipelexErrorCode.DOCGEN_ENGINE_UNAVAILABLE+ assert report.to_dict(disclosure_mode=DisclosureMode.STRICT)["message"] == report.message+ return str(report.model_dump())++async def refusal_report(*, step_fields: str) -> str:"""The error report, as text, of validating the test bundle with the given PipeDocGen step, which must be refused."""with pytest.raises(ValidateBundleError) as exc_info:diff --git a/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_host_template_files.py b/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_host_template_files.pyindex 3b1850919..063626d95 100644--- a/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_host_template_files.py+++ b/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_host_template_files.py@@ -1,11 +1,14 @@+import jsonfrom collections.abc import Iteratorfrom pathlib import Pathimport pytest+from pipelex.base_exceptions import DisclosureModefrom pipelex.cogt.doc_gen.template_check import TemplateFinding, TemplateFindingSeverity+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.interpreter_hub import clear_current_library, get_current_library_id_or_none, get_library_manager, set_current_library-from pipelex.pipeline.exceptions import ValidateBundleError+from pipelex.pipeline.exceptions import HostLibraryLoadRefusalError, ValidateBundleErrorfrom pipelex.pipeline.validate_bundle_translation import HOST_LIBRARY_FILE_PLACEHOLDERfrom pipelex.pipeline.validate_in_process import validate_bundles_in_processfrom tests.integration.pipelex.pipes.operator.pipe_doc_gen.doc_gen_helpers import StubEngines, write_bundle@@ -35,6 +38,15 @@ async def _caller_verdict(*, mthds_content: str, host_dir: Path) -> str:return exc_info.value.to_error_report().model_dump_json()+async def _host_fault_strict_payload(*, mthds_content: str, host_dir: Path) -> str:+ """The STRICT payload, as JSON, of a host's library refusing to load beside submitted content: the deployment's fault."""+ with pytest.raises(HostLibraryLoadRefusalError) as exc_info:+ await validate_bundles_in_process(mthds_contents=[mthds_content], library_dirs=[host_dir])+ report = exc_info.value.to_error_report()+ assert report.code == PipelexErrorCode.CONFIG_INVALID+ return json.dumps(report.to_dict(disclosure_mode=DisclosureMode.STRICT))++@pytest.mark.asyncio(loop_scope="class")class TestPipeDocGenHostTemplateFiles:async def test_a_host_step_s_template_check_error_names_no_template_file(self, tmp_path: Path, stub_engines: StubEngines) -> None:@@ -60,25 +72,24 @@ class TestPipeDocGenHostTemplateFiles:)@pytest.mark.usefixtures("stub_engines")async def test_a_host_step_s_load_refusal_names_no_template_file(self, tmp_path: Path, step_fields: str) -> None:- """A host step refused while the host's library loads beside submitted content names no template file of it."""+ """A host step refused while the host's library loads beside submitted content is the host's fault, naming no template file of it."""write_bundle(directory=tmp_path, step_fields=step_fields)- verdict = await _caller_verdict(mthds_content=PipeDocGenTestData.CALLER_BUNDLE_MTHDS, host_dir=tmp_path)+ strict_payload = await _host_fault_strict_payload(mthds_content=PipeDocGenTestData.CALLER_BUNDLE_MTHDS, host_dir=tmp_path)- assert HOST_LIBRARY_FILE_PLACEHOLDER in verdict- assert "host-invoice" not in verdict+ assert "host-invoice" not in strict_payload+ assert str(tmp_path) not in strict_payload@pytest.mark.usefixtures("stub_engines")async def test_a_host_step_naming_its_template_file_by_an_absolute_path_names_no_host_path(self, tmp_path: Path) -> None:- """The blueprint refuses the absolute path without repeating it, so the verdict carries nothing of the host's disk."""+ """A host step naming its template file by an absolute path is the host's fault, whose STRICT payload carries nothing of the host's disk."""(tmp_path / "invoice.docx").write_bytes(b"docx bytes")write_bundle(directory=tmp_path, step_fields=f'format = "docx"\ntemplate_file = "{(tmp_path / "invoice.docx").resolve()}"')- verdict = await _caller_verdict(mthds_content=PipeDocGenTestData.CALLER_BUNDLE_MTHDS, host_dir=tmp_path)+ strict_payload = await _host_fault_strict_payload(mthds_content=PipeDocGenTestData.CALLER_BUNDLE_MTHDS, host_dir=tmp_path)- assert "a path relative to the bundle's file, in its method, and this one cannot be: it is absolute" in verdict- assert str(tmp_path.resolve()) not in verdict- assert str(tmp_path) not in verdict+ assert str(tmp_path.resolve()) not in strict_payload+ assert str(tmp_path) not in strict_payload@pytest.mark.usefixtures("stub_engines")async def test_a_caller_step_keeps_naming_a_template_file_a_host_step_names_too(self, tmp_path: Path) -> None:diff --git a/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_load_refusals.py b/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_load_refusals.pyindex e00e53b63..135a3ea1e 100644--- a/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_load_refusals.py+++ b/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_load_refusals.py@@ -2,7 +2,7 @@ import pytestfrom pipelex.pipeline.exceptions import ValidateBundleErrorfrom pipelex.pipeline.validate_bundle import validate_bundle-from tests.integration.pipelex.pipes.operator.pipe_doc_gen.doc_gen_helpers import refusal_report+from tests.integration.pipelex.pipes.operator.pipe_doc_gen.doc_gen_helpers import engine_unavailable_report, refusal_reportfrom tests.integration.pipelex.pipes.operator.pipe_doc_gen.test_data import PipeDocGenTestData@@ -18,14 +18,14 @@ class TestPipeDocGenLoadRefusals:)async def test_a_step_no_installed_engine_prints_names_the_plugin(self, step_fields: str, asks: str) -> None:"""Open Pipelex declares a default for a pdf without a template only: any other step is refused at load, naming the plugin."""- report = await refusal_report(step_fields=step_fields)+ report = await engine_unavailable_report(step_fields=step_fields)assert asks in reportassert "pipelex-doc-gen" in reportassert "pipelex update" not in reportasync def test_a_step_naming_a_plugin_engine_is_refused_where_the_plugin_is_absent(self) -> None:"""A step may name the plugin's `pipelex-pdf` for a pdf without a template, and open Pipelex refuses it at load, naming the plugin."""- report = await refusal_report(step_fields='format = "pdf"\nmodel = "pipelex-pdf"')+ report = await engine_unavailable_report(step_fields='format = "pdf"\nmodel = "pipelex-pdf"')assert "pipelex-pdf" in reportassert "pipelex-doc-gen" in reportassert "was not found in the model deck" not in report@@ -38,7 +38,7 @@ class TestPipeDocGenLoadRefusals:)async def test_a_pdf_layout_step_is_refused_where_internal_toml_predates_the_built_in_engine(self, step_fields: str) -> None:"""An installation whose internal.toml does not declare `reportlab-pdf` is told to run `pipelex update`, not that the model is unknown."""- report = await refusal_report(step_fields=step_fields)+ report = await engine_unavailable_report(step_fields=step_fields)assert "reportlab-pdf" in reportassert "pipelex update" in reportassert "was not found in the model deck" not in report@@ -60,7 +60,7 @@ class TestPipeDocGenLoadRefusals:@pytest.mark.usefixtures("no_engines")async def test_a_pdf_layout_step_is_refused_where_the_built_in_engine_is_disabled(self) -> None:"""A host that disables the built-in engine and installs no plugin refuses even a pdf without a template."""- report = await refusal_report(step_fields=PipeDocGenTestData.PDF_LAYOUT_STEP)+ report = await engine_unavailable_report(step_fields=PipeDocGenTestData.PDF_LAYOUT_STEP)assert "built into Pipelex and disabled" in report@pytest.mark.usefixtures("stub_engines")diff --git a/tests/unit/pipelex/cli/test_agent_cli_factory.py b/tests/unit/pipelex/cli/test_agent_cli_factory.pyindex 1a2a15af9..2a91579ab 100644--- a/tests/unit/pipelex/cli/test_agent_cli_factory.py+++ b/tests/unit/pipelex/cli/test_agent_cli_factory.py@@ -13,7 +13,7 @@ if TYPE_CHECKING:from pytest_mock import MockerFixturefrom pipelex.cli.agent_cli.commands.agent_cli_factory import make_pipelex_for_agent_cli-from pipelex.cogt.exceptions import ModelDeckPresetValidatonError+from pipelex.cogt.exceptions import ModelDeckPresetValidationErrorfrom pipelex.cogt.model_backends.model_type import ModelTypefrom pipelex.system.telemetry.exceptions import TelemetryConfigValidationErrorfrom pipelex.tools.misc.pretty import PrettyPrinter@@ -79,8 +79,8 @@ class TestMakePipelexForAgentCli:mocker: MockerFixture,capsys: pytest.CaptureFixture[str],) -> None:- """ModelDeckPresetValidatonError should include preset_id, model_type, model_handle, enabled_backends."""- exc = ModelDeckPresetValidatonError(+ """ModelDeckPresetValidationError should include preset_id, model_type, model_handle, enabled_backends."""+ exc = ModelDeckPresetValidationError(message="preset validation failed",preset_id="my_preset",model_type=ModelType.LLM,@@ -96,7 +96,7 @@ class TestMakePipelexForAgentCli:make_pipelex_for_agent_cli()parsed = json.loads(capsys.readouterr().err)- assert parsed["error_type"] == "ModelDeckPresetValidatonError"+ assert parsed["error_type"] == "ModelDeckPresetValidationError"assert parsed["preset_id"] == "my_preset"assert parsed["model_handle"] == "claude-3-opus"assert sorted(parsed["enabled_backends"]) == ["anthropic", "openai"]diff --git a/tests/unit/pipelex/cli/test_agent_codegen_types_cmd.py b/tests/unit/pipelex/cli/test_agent_codegen_types_cmd.pyindex 81a724d42..41694bffa 100644--- a/tests/unit/pipelex/cli/test_agent_codegen_types_cmd.py+++ b/tests/unit/pipelex/cli/test_agent_codegen_types_cmd.py@@ -17,6 +17,7 @@ import typerfrom pipelex.cli.agent_cli.commands.agent_output import CliOutputFormatfrom pipelex.cli.agent_cli.commands.codegen.types_cmd import agent_codegen_types_cmd+from pipelex.cli.exceptions import BundleClosureEmptyErrorfrom pipelex.codegen.emitters.target import CodegenTarget, EmittedFilefrom pipelex.codegen.lock import CODEGEN_LOCK_FILENAMEfrom pipelex.libraries.exceptions import LibraryLoadingError@@ -103,9 +104,23 @@ class TestAgentCodegenTypesCmd:assert error["error_type"] == "LibraryLoadingError"assert "duplicate pipe" in error["message"]- def test_unassembled_closure_is_no_verdict_exit_2(self, mocker: MockerFixture, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:+ @pytest.mark.parametrize(+ ("raised", "expected_error_type"),+ [+ (FileNotFoundError("the library directory does not exist."), "FileNotFoundError"),+ (BundleClosureEmptyError("no .mthds bundles found in the closure."), "BundleClosureEmptyError"),+ ],+ )+ def test_unassembled_closure_is_no_verdict_exit_2(+ self,+ mocker: MockerFixture,+ tmp_path: Path,+ capsys: pytest.CaptureFixture[str],+ raised: Exception,+ expected_error_type: str,+ ) -> None:self._neutralize_boot(mocker)- mocker.patch(f"{CMD_MODULE}.load_normalized_crate", side_effect=FileNotFoundError("no .mthds bundles found in the closure."))+ mocker.patch(f"{CMD_MODULE}.load_normalized_crate", side_effect=raised)with pytest.raises(typer.Exit) as exc_info:agent_codegen_types_cmd(@@ -119,7 +134,7 @@ class TestAgentCodegenTypesCmd:assert exc_info.value.exit_code == 2error = json.loads(capsys.readouterr().err)- assert error["error_type"] == "FileNotFoundError"+ assert error["error_type"] == expected_error_typedef test_boot_loads_model_specs_for_offline_validation(self, mocker: MockerFixture, tmp_path: Path) -> None:"""Like the bare CLI, the agent mirror boots offline but WITH model specs: library validationdiff --git a/tests/unit/pipelex/cli/test_agent_output.py b/tests/unit/pipelex/cli/test_agent_output.pyindex 7d4762600..9104dc6f1 100644--- a/tests/unit/pipelex/cli/test_agent_output.py+++ b/tests/unit/pipelex/cli/test_agent_output.py@@ -9,6 +9,7 @@ from typing import TYPE_CHECKINGimport pytestimport typer+from mthds.protocol.problem.registry import CoreCodefrom typer.testing import CliRunnerfrom pipelex.base_exceptions import PipelexConfigError, PipelexError@@ -36,6 +37,7 @@ from pipelex.cogt.model_backends.model_type import ModelTypefrom pipelex.pipe_run.exceptions import PipeRouterErrorfrom pipelex.pipeline.exceptions import PipelineExecutionError, ValidateBundleErrorfrom pipelex.system.pipe_run_mode import PipeRunMode+from pipelex.tools.misc.exceptions import RemoteFileFetchErrorif TYPE_CHECKING:from collections.abc import Iterator@@ -282,14 +284,36 @@ class TestAgentOutput:parsed = json.loads(capsys.readouterr().err)assert parsed["hint"] == "Check your API key and try again"- def test_agent_error_uses_report_retryable_from_cogt_error(self, capsys: pytest.CaptureFixture[str]) -> None:- """agent_error should set retryable=True when error_category is TRANSIENT."""- cause = CogtError("rate limited", error_category=InferenceErrorCategory.TRANSIENT)+ def test_agent_error_uses_report_retryable_from_the_code(self, capsys: pytest.CaptureFixture[str]) -> None:+ """agent_error sets retryable=True when the cause's code says a retry can succeed."""+ cause = RemoteFileFetchError("Could not fetch 'https://example.com/a.pdf': the request timed out").with_error_code(+ CoreCode.INPUT_URL_UNREACHABLE+ )with pytest.raises(typer.Exit):- agent_error("rate limited", error_type="CogtError", cause=cause)+ agent_error("fetch timed out", error_type="RemoteFileFetchError", cause=cause)parsed = json.loads(capsys.readouterr().err)assert parsed["retryable"] is True+ assert parsed["error_domain"] == "input"++ def test_agent_error_carries_the_cause_registry_code(self, capsys: pytest.CaptureFixture[str]) -> None:+ """agent_error names the cause's registry code as error_code, the member a hosted refusal carries too."""+ cause = RemoteFileFetchError("Could not fetch 'https://example.com/a.pdf': the request timed out").with_error_code(+ CoreCode.INPUT_URL_UNREACHABLE+ )+ with pytest.raises(typer.Exit):+ agent_error("fetch timed out", error_type="RemoteFileFetchError", cause=cause)++ parsed = json.loads(capsys.readouterr().err)+ assert parsed["error_code"] == CoreCode.INPUT_URL_UNREACHABLE++ def test_agent_error_has_no_error_code_without_a_coded_cause(self, capsys: pytest.CaptureFixture[str]) -> None:+ """A builtin cause carries no registry code, so the envelope names none rather than inventing one."""+ with pytest.raises(typer.Exit):+ agent_error("file not found", error_type="FileNotFoundError", cause=FileNotFoundError("missing.mthds"))++ parsed = json.loads(capsys.readouterr().err)+ assert "error_code" not in parseddef test_agent_error_uses_report_error_category(self, capsys: pytest.CaptureFixture[str]) -> None:"""agent_error should include error_category from to_error_report()."""@@ -369,27 +393,23 @@ class TestAgentOutput:parsed = json.loads(capsys.readouterr().err)assert "retryable" not in parsed- def test_agent_error_error_domain_and_category_coexist(self, capsys: pytest.CaptureFixture[str]) -> None:- """error_domain (from lookup) and error_category (from report) should both appear.+ def test_agent_error_domain_lookup_serves_an_uncoded_cause(self, capsys: pytest.CaptureFixture[str]) -> None:+ """An error that carries no registry code takes its domain from the lookup, and no category.- The cause carries the ``UNKNOWN`` category deliberately: every other category derives an- ``error_domain`` onto the report, and the report-first read then wins outright, so the- lookup fallback would never be exercised. ``UNKNOWN`` asserts no domain — classification- itself failed — which leaves exactly the composition this test is about: the category comes- from the report, the domain from the lookup.+ Every ``PipelexError`` carries a code, whose domain the report always holds, so the lookup is read only+ for a builtin or third-party cause, or for a synthetic label with no cause at all."""- # An error_type in AGENT_ERROR_DOMAINS that is NOT a CogtError subclass, so no derived- # domain can pre-empt the lookup.- error_type = "PipeOperatorModelAvailabilityError"+ error_type = "FileNotFoundError"assert error_type in AGENT_ERROR_DOMAINS, "precondition: error_type must be in AGENT_ERROR_DOMAINS"- cause = CogtError("model not found", error_category=InferenceErrorCategory.UNKNOWN)+ cause = FileNotFoundError("inputs.json")with pytest.raises(typer.Exit):- agent_error("model not found", error_type=error_type, cause=cause)+ agent_error("Input file not found", error_type=error_type, cause=cause)parsed = json.loads(capsys.readouterr().err)assert parsed["error_domain"] == AGENT_ERROR_DOMAINS[error_type]- assert parsed["error_category"] == "unknown"+ assert "error_category" not in parsed+ assert "retryable" not in parseddef test_agent_error_report_domain_beats_the_lookup(self, capsys: pytest.CaptureFixture[str]) -> None:"""A categorized CogtError cause supplies the domain itself, so the lookup is not consulted.diff --git a/tests/unit/pipelex/cli/test_agent_output_drift.py b/tests/unit/pipelex/cli/test_agent_output_drift.pyindex 8f83ef8cb..5c904c84f 100644--- a/tests/unit/pipelex/cli/test_agent_output_drift.py+++ b/tests/unit/pipelex/cli/test_agent_output_drift.py@@ -1,35 +1,18 @@"""Drift-detection tests for the agent CLI error lookup dicts.-AGENT_ERROR_HINTS / AGENT_ERROR_DOMAINS / RETRYABLE_ERROR_TYPES are string-keyed-by exception class name (or synthetic error_type label). These tests catch:+AGENT_ERROR_HINTS / AGENT_ERROR_DOMAINS are string-keyed by exception class name (or+synthetic error_type label). These tests catch:- stale keys left behind when an exception class is renamed or deleted;-- a PipelexError subclass that carries class-level metadata yet still has a- redundant lookup-dict entry (the class must be the single source of truth).+- a PipelexError subclass in AGENT_ERROR_DOMAINS, whose entry can never be read: every+ PipelexError carries a registry code, and the report's domain is that code's."""-import importlib-from pipelex.base_exceptions import PipelexError-from pipelex.cli.agent_cli.commands.agent_output import AGENT_ERROR_DOMAINS, AGENT_ERROR_HINTS, RETRYABLE_ERROR_TYPES-from pipelex.cogt.exceptions import CogtError--# Modules defining every PipelexError subclass referenced by the lookup dicts.-# Imported so PipelexError.__subclasses__() sees them when the registry is built.-_EXCEPTION_MODULES: tuple[str, ...] = (- "pipelex.codegen.exceptions",- "pipelex.cogt.exceptions",- "pipelex.mthds_parsing.exceptions",- "pipelex.core.pipes.exceptions",- "pipelex.pipe_operators.exceptions",- "pipelex.pipeline.exceptions",- "pipelex.pipeline.validate_bundle",- "pipelex.system.telemetry.exceptions",- "pipelex.tools.misc.json_utils",- "pipelex.tools.misc.toml_utils",-)+from pipelex.cli.agent_cli.commands.agent_output import AGENT_ERROR_DOMAINS, AGENT_ERROR_HINTS+from pipelex.errors.error_class_discovery import iter_pipelex_error_subclasses# Lookup-dict keys that are intentionally NOT PipelexError subclasses and-# therefore cannot carry class-level metadata:+# therefore carry no registry code:# - builtin / third-party exception classes# - synthetic error_type labels passed straight to agent_error(...)_NON_PIPELEX_ERROR_KEYS: frozenset[str] = frozenset(@@ -38,11 +21,9 @@ _NON_PIPELEX_ERROR_KEYS: frozenset[str] = frozenset("JSONDecodeError", # json builtin"ValueError", # builtin"ValidationError", # pydantic- "PipeValidationError", # subclass of ValueError, not of PipelexError"ArgumentError", # synthetic error_type label"BinaryNotFoundError", # synthetic error_type label"FixBundleError", # synthetic error_type label- "GraphSpecParseError", # synthetic error_type label"BundleError", # synthetic error_type label"CodegenDriftError", # synthetic error_type label (a drift verdict, not an exception)"CodegenLockNotFoundError", # synthetic error_type label@@ -53,70 +34,39 @@ _NON_PIPELEX_ERROR_KEYS: frozenset[str] = frozenset()-def _all_pipelex_error_subclasses() -> set[type[PipelexError]]:- """Return every imported PipelexError subclass, walking the hierarchy recursively."""- for module_name in _EXCEPTION_MODULES:- importlib.import_module(module_name)- collected: set[type[PipelexError]] = set()- pending: list[type[PipelexError]] = [PipelexError]- while pending:- current = pending.pop()- for subclass in current.__subclasses__():- if subclass not in collected:- collected.add(subclass)- pending.append(subclass)- return collected+def _pipelex_error_names() -> set[str]:+ """The name of every PipelexError subclass, every error module force-loaded."""+ return {cls.__name__ for cls in iter_pipelex_error_subclasses() if cls is not PipelexError}class TestAgentOutputDrift:- """Guards the agent CLI lookup dicts against class renames and redundant entries."""+ """Guards the agent CLI lookup dicts against class renames and unreadable entries."""def test_every_dict_key_is_a_known_error_type(self) -> None:"""Every lookup-dict key resolves to a PipelexError subclass or a documented non-PipelexError type."""- known_pipelex_names = {cls.__name__ for cls in _all_pipelex_error_subclasses()}- all_keys = set(AGENT_ERROR_HINTS) | set(AGENT_ERROR_DOMAINS) | set(RETRYABLE_ERROR_TYPES)- for key in all_keys:+ known_pipelex_names = _pipelex_error_names()+ for key in set(AGENT_ERROR_HINTS) | set(AGENT_ERROR_DOMAINS):assert key in known_pipelex_names or key in _NON_PIPELEX_ERROR_KEYS, (f"Lookup-dict key {key!r} is neither a known PipelexError subclass nor a documented "f"non-PipelexError type — likely a stale entry after a rename or delete.")- def test_class_level_error_domain_not_duplicated_in_dict(self) -> None:- """A subclass that declares class-level error_domain must not also sit in AGENT_ERROR_DOMAINS."""- for cls in _all_pipelex_error_subclasses():- if cls.error_domain is not None:- assert cls.__name__ not in AGENT_ERROR_DOMAINS, (- f"{cls.__name__} carries a class-level error_domain; its AGENT_ERROR_DOMAINS entry "- f"is redundant — remove it so the class is the single source of truth."- )-- def test_category_derived_error_domain_not_duplicated_in_dict(self) -> None:- """A CogtError subclass whose error_category derives a domain must not sit in AGENT_ERROR_DOMAINS either.+ def test_no_documented_non_pipelex_key_is_a_pipelex_error(self) -> None:+ """A key documented as carrying no code must not name a PipelexError subclass, which carries one."""+ joined = sorted(_NON_PIPELEX_ERROR_KEYS & _pipelex_error_names())+ assert not joined, f"These keys now name PipelexError subclasses; drop them from _NON_PIPELEX_ERROR_KEYS: {joined}"- Such a class self-describes without declaring an ``error_domain`` of its own:- ``InferenceErrorCategory.error_domain`` derives one and ``CogtError.to_error_report()``- puts it on the report, so ``agent_error()``'s report-first read always wins and the- lookup entry is unreachable. ``test_class_level_error_domain_not_duplicated_in_dict``- does not catch these, because the class attribute is genuinely ``None``.- """- for cls in _all_pipelex_error_subclasses():- if not issubclass(cls, CogtError):- continue- category = cls.error_category- if category is None:- continue- derived_domain = category.error_domain- if derived_domain is None:- continue- assert cls.__name__ not in AGENT_ERROR_DOMAINS, (- f"{cls.__name__} derives error_domain {derived_domain!r} from its {category!r} category, "- f"so its AGENT_ERROR_DOMAINS entry can never be read — remove it. If that derived domain "- f"is wrong for this class, declare an explicit class-level error_domain on the class instead."- )+ def test_no_pipelex_error_has_a_domain_entry(self) -> None:+ """A PipelexError subclass's domain is its code's, so an AGENT_ERROR_DOMAINS entry for it is never read."""+ offenders = sorted(set(AGENT_ERROR_DOMAINS) & _pipelex_error_names())+ assert not offenders, (+ f"These AGENT_ERROR_DOMAINS keys name PipelexError subclasses, whose report carries the domain of their code: "+ f"{offenders}. Remove the entries; if the domain is wrong, the class needs another code."+ )def test_class_level_user_action_not_duplicated_in_dict(self) -> None:"""A subclass that declares class-level user_action must not also sit in AGENT_ERROR_HINTS."""- for cls in _all_pipelex_error_subclasses():+ for cls in iter_pipelex_error_subclasses():if cls.user_action is not None:assert cls.__name__ not in AGENT_ERROR_HINTS, (f"{cls.__name__} carries a class-level user_action; its AGENT_ERROR_HINTS entry "diff --git a/tests/unit/pipelex/cli/test_error_handlers.py b/tests/unit/pipelex/cli/test_error_handlers.pyindex 22d651ca4..eaccdcb1d 100644--- a/tests/unit/pipelex/cli/test_error_handlers.py+++ b/tests/unit/pipelex/cli/test_error_handlers.py@@ -14,7 +14,7 @@ from pipelex.cli.error_handlers import (handle_model_deck_preset_error,handle_validate_bundle_error,)-from pipelex.cogt.exceptions import ModelDeckPresetValidatonError+from pipelex.cogt.exceptions import ModelDeckPresetValidationErrorfrom pipelex.cogt.model_backends.model_type import ModelTypefrom pipelex.core.pipes.exceptions import PipeOperatorModelChoiceErrorfrom pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityError@@ -71,7 +71,7 @@ class TestErrorHandlers:def test_handle_model_deck_preset_error_exits_and_calls_to_error_report(self, mocker: MockerFixture) -> None:"""handle_model_deck_preset_error should call to_error_report() and exit with code 1."""mocker.patch("pipelex.cli.error_handlers.get_console")- exc = ModelDeckPresetValidatonError(+ exc = ModelDeckPresetValidationError(message="preset references unavailable model",model_type=ModelType.LLM,preset_id="default",diff --git a/tests/unit/pipelex/cli/test_error_handlers_more.py b/tests/unit/pipelex/cli/test_error_handlers_more.pyindex 4f091f83f..c41f7bb32 100644--- a/tests/unit/pipelex/cli/test_error_handlers_more.py+++ b/tests/unit/pipelex/cli/test_error_handlers_more.py@@ -23,7 +23,7 @@ from pipelex.cli.error_handlers import (handle_telemetry_config_validation_error,handle_validate_bundle_error,)-from pipelex.cogt.exceptions import ModelDeckPresetValidatonError+from pipelex.cogt.exceptions import ModelDeckPresetValidationErrorfrom pipelex.cogt.inference.error_classification import UserAction, UserActionKindfrom pipelex.cogt.model_backends.model_type import ModelTypefrom pipelex.core.exceptions import DryRunFailureErrorData, PipelexBundleBlueprintValidationErrorData, PipesAndConceptValidationErrorData@@ -94,8 +94,8 @@ class TestErrorHandlersExtended:assert "first line" in outputassert "second line" in output- def _make_deck_preset_error(self, enabled_backends: set[str] | None) -> ModelDeckPresetValidatonError:- return ModelDeckPresetValidatonError(+ def _make_deck_preset_error(self, enabled_backends: set[str] | None) -> ModelDeckPresetValidationError:+ return ModelDeckPresetValidationError(message="preset references unavailable model",model_type=ModelType.LLM,preset_id="default_text",diff --git a/tests/unit/pipelex/cli/test_installed_methods.py b/tests/unit/pipelex/cli/test_installed_methods.pyindex b06757d73..d9e34f7e7 100644--- a/tests/unit/pipelex/cli/test_installed_methods.py+++ b/tests/unit/pipelex/cli/test_installed_methods.py@@ -8,10 +8,9 @@ import pytestfrom mthds.package.discovery import MANIFEST_FILENAMEfrom mthds.package.manifest.parser import parse_methods_toml+from pipelex.cli.exceptions import DuplicateMethodNameError, MethodNotFoundErrorfrom pipelex.cli.installed_methods import (- DuplicateMethodNameError,InstalledMethod,- MethodNotFoundError,discover_methods_from_library_dirs,find_method_by_name,)diff --git a/tests/unit/pipelex/cli/test_show_cmd.py b/tests/unit/pipelex/cli/test_show_cmd.pyindex 002fc097e..c8a69881b 100644--- a/tests/unit/pipelex/cli/test_show_cmd.py+++ b/tests/unit/pipelex/cli/test_show_cmd.py@@ -16,6 +16,7 @@ from pipelex.base_exceptions import PipelexConfigErrorfrom pipelex.cli.commands.show_cmd import do_list_pipes, do_show_backends, do_show_config, do_show_pipefrom pipelex.cli.exceptions import PipelexCLIErrorfrom pipelex.cogt.model_backends.credential_resolution import CredentialResolution+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.tools.misc.exceptions import TomlErrorif TYPE_CHECKING:@@ -88,13 +89,27 @@ class TestShowCmd:pretty_print_mock.assert_called_once_with(fake_config, title="Pipelex configuration")- def test_do_show_config_wraps_toml_error(self, mocker: MockerFixture) -> None:- """A TOML load failure surfaces as PipelexConfigError with context."""+ @pytest.mark.parametrize(+ ("failure", "expected_message", "expected_code"),+ [+ (TomlError(message="bad toml", doc="", pos=0, lineno=1, colno=1), "bad toml", PipelexErrorCode.CONFIG_SYNTAX),+ (FileNotFoundError("pipelex.toml"), "pipelex.toml", PipelexErrorCode.CONFIG_FILE_MISSING),+ ],+ )+ def test_do_show_config_wraps_load_failures(+ self,+ mocker: MockerFixture,+ failure: Exception,+ expected_message: str,+ expected_code: PipelexErrorCode,+ ) -> None:+ """A load failure surfaces as PipelexConfigError with context: a syntax error, or a file that cannot be read."""mocked_manager = mocker.patch("pipelex.cli.commands.show_cmd.config_manager")- mocked_manager.load_config.side_effect = TomlError(message="bad toml", doc="", pos=0, lineno=1, colno=1)+ mocked_manager.load_config.side_effect = failure- with pytest.raises(PipelexConfigError, match="Error loading configuration: bad toml"):+ with pytest.raises(PipelexConfigError, match=f"Error loading configuration: {expected_message}") as exc_info:do_show_config()+ assert exc_info.value.resolve_error_code() == expected_codedef test_do_list_pipes_tracks_pipe_count(self, mocker: MockerFixture, telemetry: Any) -> None:"""Listing pipes delegates to the library and reports the count to telemetry."""@@ -261,5 +276,6 @@ class TestShowCmd:"""Failures while accessing backend config surface as PipelexCLIError."""mocker.patch("pipelex.cli.commands.show_cmd.get_secrets_provider", side_effect=OSError("denied"))- with pytest.raises(PipelexCLIError, match="Error accessing backend or routing configuration: denied"):+ with pytest.raises(PipelexCLIError, match="Error accessing backend or routing configuration: denied") as exc_info:do_show_backends()+ assert exc_info.value.resolve_error_code() == PipelexErrorCode.CONFIG_INVALIDdiff --git a/tests/unit/pipelex/cli/test_traceback_flag_error_handlers.py b/tests/unit/pipelex/cli/test_traceback_flag_error_handlers.pyindex cbb3e4c75..eff75946b 100644--- a/tests/unit/pipelex/cli/test_traceback_flag_error_handlers.py+++ b/tests/unit/pipelex/cli/test_traceback_flag_error_handlers.py@@ -14,15 +14,15 @@ import typerfrom rich.traceback import Tracebackfrom pipelex.cli.error_handlers import ErrorContext, handle_model_deck_preset_error-from pipelex.cogt.exceptions import ModelDeckPresetValidatonError+from pipelex.cogt.exceptions import ModelDeckPresetValidationErrorfrom pipelex.cogt.model_backends.model_type import ModelTypeif TYPE_CHECKING:from pytest_mock import MockerFixture-def _deck_preset_error() -> ModelDeckPresetValidatonError:- return ModelDeckPresetValidatonError(+def _deck_preset_error() -> ModelDeckPresetValidationError:+ return ModelDeckPresetValidationError(message="preset references unavailable model",model_type=ModelType.LLM,preset_id="default",@@ -44,7 +44,7 @@ class TestTracebackFlagInErrorHandlers:with ctx:try:raise exc- except ModelDeckPresetValidatonError:+ except ModelDeckPresetValidationError:with pytest.raises(typer.Exit):handle_model_deck_preset_error(exc, context=ErrorContext.VALIDATION)@@ -62,7 +62,7 @@ class TestTracebackFlagInErrorHandlers:with ctx:try:raise exc- except ModelDeckPresetValidatonError:+ except ModelDeckPresetValidationError:with pytest.raises(typer.Exit):handle_model_deck_preset_error(exc, context=ErrorContext.VALIDATION)diff --git a/tests/unit/pipelex/cogt/content_generation/test_doc_gen_render_resources.py b/tests/unit/pipelex/cogt/content_generation/test_doc_gen_render_resources.pyindex 27152703d..b1184ebca 100644--- a/tests/unit/pipelex/cogt/content_generation/test_doc_gen_render_resources.py+++ b/tests/unit/pipelex/cogt/content_generation/test_doc_gen_render_resources.py@@ -4,6 +4,7 @@ from urllib.parse import urljoinimport pytestfrom mthds.method_tree.vocabulary import TreeRefusalCode+from mthds.protocol.problem.registry import CoreCodefrom pytest_mock import MockerFixturefrom pipelex.cogt.content_generation import doc_gen_generate@@ -165,8 +166,9 @@ class TestRunRenderResources:loaded = await asyncio.to_thread(unscoped.load, uri=str(photo_path), position="image 1 of the document")assert loaded.data == b"\x89PNG local"- with pytest.raises(UriReadRefusedError):+ with pytest.raises(UriReadRefusedError) as exc_info:await asyncio.to_thread(scoped.load, uri=str(photo_path), position="image 1 of the document")+ assert exc_info.value.resolve_error_code() == CoreCode.SECURITY_METHOD_URL_REFUSEDasync def test_a_method_file_url_in_a_document_with_no_html_is_refused_for_its_source(self, mocker: MockerFixture) -> None:loader = mocker.patch.object(doc_gen_generate, "load_bytes_and_mime_type_from_any_uri", new_callable=mocker.AsyncMock)diff --git a/tests/unit/pipelex/cogt/content_generation/test_generated_content_factory.py b/tests/unit/pipelex/cogt/content_generation/test_generated_content_factory.pyindex 18cd05592..64d2c1d29 100644--- a/tests/unit/pipelex/cogt/content_generation/test_generated_content_factory.py+++ b/tests/unit/pipelex/cogt/content_generation/test_generated_content_factory.py@@ -1,10 +1,12 @@import pytest+from mthds.protocol.problem.registry import CoreCodefrom pytest_mock import MockerFixturefrom pipelex.cogt.content_generation.generated_content_factory import GeneratedContentFactoryfrom pipelex.cogt.image.generated_image import GeneratedImageRawDetailsfrom pipelex.config import get_configfrom pipelex.tools.misc.exceptions import RemoteFileFetchError+from pipelex.tools.network.exceptions import SsrfBlockedErrorfrom pipelex.tools.storage.storage_provider_abstract import StorageProviderAbstractFAKE_IMAGE_BYTES = b"fake-image-bytes-for-hashing"@@ -196,3 +198,22 @@ class TestGeneratedContentFactoryFetchedRemoteImage:storage_provider.store.assert_not_awaited()assert image_content.url == "https://example.com/gone"assert image_content.public_url == "https://example.com/gone"++ @pytest.mark.usefixtures("_remote_fetch_enabled")+ async def test_a_refused_provider_url_fails_as_the_provider_s(self, mocker: MockerFixture):+ """A generated image's URL is one the provider's answer named, so the guard's refusal of it is the provider's, not the caller's."""+ storage_provider = mocker.MagicMock(spec=StorageProviderAbstract)+ mocker.patch(+ "pipelex.cogt.content_generation.generated_content_factory.fetch_file_and_content_type_from_url_httpx",+ new=mocker.AsyncMock(side_effect=SsrfBlockedError("Refused a request to 'internal.example': it resolves to a private address")),+ )+ factory = GeneratedContentFactory(storage_provider=storage_provider)++ with pytest.raises(SsrfBlockedError) as exc_info:+ await factory.make_image_content(+ storage_scope="test/scope",+ raw_details=GeneratedImageRawDetails(size=None, actual_url="https://internal.example/image.png"),+ )++ assert exc_info.value.resolve_error_code() == CoreCode.SECURITY_PROVIDER_URL_REFUSED+ storage_provider.store.assert_not_awaited()diff --git a/tests/unit/pipelex/cogt/content_generation/test_leaf_read_scope.py b/tests/unit/pipelex/cogt/content_generation/test_leaf_read_scope.pyindex 34bd0a0ca..0330ffb7d 100644--- a/tests/unit/pipelex/cogt/content_generation/test_leaf_read_scope.py+++ b/tests/unit/pipelex/cogt/content_generation/test_leaf_read_scope.py@@ -10,6 +10,7 @@ from collections.abc import Awaitable, Callablefrom typing import Anyimport pytest+from mthds.protocol.problem.registry import CoreCodefrom pydantic import BaseModelfrom pytest_mock import MockerFixture@@ -206,6 +207,8 @@ class TestLeafReadScope:with pytest.raises(UriReadRefusedError) as exc_info:await call_leaf(FOREIGN_KEY, PipeRunMode.DRY, factory)assert exc_info.value.reason == UriReadRefusalReason.FOREIGN_STORAGE_KEY, leaf_name+ # The run took its inputs through the same scope, so what a leaf refuses is a URL the method produced.+ assert exc_info.value.resolve_error_code() == CoreCode.SECURITY_METHOD_URL_REFUSED, leaf_nameassert f"of pipe '{PIPE_CODE}'" in str(exc_info.value)assert factory.method_calls == []for worker_spy in no_workers.values():diff --git a/tests/unit/pipelex/cogt/content_generation/test_schema_to_model.py b/tests/unit/pipelex/cogt/content_generation/test_schema_to_model.pyindex 0040a1aa9..e9b25c608 100644--- a/tests/unit/pipelex/cogt/content_generation/test_schema_to_model.py+++ b/tests/unit/pipelex/cogt/content_generation/test_schema_to_model.py@@ -5,6 +5,7 @@ import uuidfrom typing import Any, Literal, get_args, get_originimport pytest+from mthds.protocol.problem.registry import CoreCodefrom pydantic import BaseModel, Field, ValidationErrorfrom pytest_mock import MockerFixture@@ -449,15 +450,16 @@ class TestSchemaToModel:# ---- Layer 2: __import__ allowlist (defense-in-depth at the exec boundary) ----def test_exec_blocks_import_subprocess(self) -> None:- """Even bypassing Layer 1, the restricted __import__ blocks `import subprocess`."""+ """Even bypassing Layer 1, the restricted __import__ blocks `import subprocess`, as the perimeter's refusal."""malicious_source = "from pydantic import BaseModel\nimport subprocess\nclass Innocent(BaseModel):\n name: str = 'ok'\n"- with pytest.raises(ImportError, match="subprocess"):+ with pytest.raises(UnsafeSchemaError, match="subprocess") as exc_info:SchemaToModelFactory._exec_and_extract_class(malicious_source, class_name="Innocent") # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ assert exc_info.value.resolve_error_code() == CoreCode.SECURITY_SCHEMA_REFUSEDdef test_exec_blocks_direct_dunder_import_call(self) -> None:"""A direct __import__('subprocess') call is also blocked."""malicious_source = "from pydantic import BaseModel\nclass Innocent(BaseModel):\n name: str = 'ok'\n_leak = __import__('subprocess')\n"- with pytest.raises(ImportError, match="subprocess"):+ with pytest.raises(UnsafeSchemaError, match="subprocess"):SchemaToModelFactory._exec_and_extract_class(malicious_source, class_name="Innocent") # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]@pytest.mark.parametrize(@@ -472,7 +474,7 @@ class TestSchemaToModel:def test_exec_blocks_dangerous_imports(self, import_line: str, expected_module: str) -> None:"""A range of dangerous stdlib imports is blocked by the allowlist."""malicious_source = f"from pydantic import BaseModel\n{import_line}\nclass Innocent(BaseModel):\n name: str = 'ok'\n"- with pytest.raises(ImportError, match=expected_module):+ with pytest.raises(UnsafeSchemaError, match=expected_module):SchemaToModelFactory._exec_and_extract_class(malicious_source, class_name="Innocent") # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]@pytest.mark.parametrize(diff --git a/tests/unit/pipelex/cogt/inference/test_classify_inference_error.py b/tests/unit/pipelex/cogt/inference/test_classify_inference_error.pyindex 3d711d26e..3e098183f 100644--- a/tests/unit/pipelex/cogt/inference/test_classify_inference_error.py+++ b/tests/unit/pipelex/cogt/inference/test_classify_inference_error.py@@ -6,28 +6,55 @@ envelopes and assert the classification, with no SDK installed or imported.from __future__ import annotations-from typing import ClassVar+from typing import TYPE_CHECKING, ClassVarimport pytest+from mthds.protocol.problem.registry import CoreCode+from pydantic import ValidationErrorfrom pipelex.cogt.exceptions import InferenceErrorCategoryfrom pipelex.cogt.inference.error_classification import ProviderErrorMetadata, UserActionKind-from pipelex.cogt.inference.error_classify import classify_inference_error+from pipelex.cogt.inference.error_classify import ClassificationResult, InferenceErrorFamily, classify_inference_errorfrom pipelex.cogt.inference.provider_name import ProviderName+from pipelex.errors.registry.pipelex_codes import PipelexErrorCode++if TYPE_CHECKING:+ from pipelex.errors.error_codes import ErrorCode++_LLM = InferenceErrorFamily.LLM+_IMG_GEN = InferenceErrorFamily.IMG_GEN+_EXTRACT = InferenceErrorFamily.EXTRACT+_SEARCH = InferenceErrorFamily.SEARCHclass _TestCases:- # (topic, provider, sdk_exception_type, message, status_code,- # expected_category, expected_action, expected_is_model_not_found)- PARITY: ClassVar[list[tuple[str, ProviderName, str, str, int | None, InferenceErrorCategory, UserActionKind, bool]]] = [+ # (topic, provider, sdk_exception_type, message, status_code, family,+ # expected_category, expected_action, expected_error_code, expected_is_model_not_found)+ PARITY: ClassVar[+ list[tuple[str, ProviderName, str, str, int | None, InferenceErrorFamily, InferenceErrorCategory, UserActionKind, ErrorCode, bool]]+ ] = [("rate_limit_429",ProviderName.OPENAI,"RateLimitError","Rate limit reached",429,+ _LLM,InferenceErrorCategory.TRANSIENT,UserActionKind.WAIT_AND_RETRY,+ CoreCode.PROVIDER_RATE_LIMITED,+ False,+ ),+ (+ "rate_limit_429_on_an_image_generation_ran_nothing",+ ProviderName.OPENAI,+ "RateLimitError",+ "Rate limit reached",+ 429,+ _IMG_GEN,+ InferenceErrorCategory.TRANSIENT,+ UserActionKind.WAIT_AND_RETRY,+ CoreCode.PROVIDER_RATE_LIMITED,False,),(@@ -36,8 +63,10 @@ class _TestCases:"RateLimitError","You exceeded your current quota",429,+ _LLM,InferenceErrorCategory.CAPACITY,UserActionKind.CHECK_BILLING,+ CoreCode.PROVIDER_QUOTA_EXHAUSTED,False,),(@@ -46,8 +75,10 @@ class _TestCases:"SDKError","Payment required",402,+ _LLM,InferenceErrorCategory.CAPACITY,UserActionKind.CHECK_BILLING,+ CoreCode.PROVIDER_QUOTA_EXHAUSTED,False,),(@@ -56,8 +87,10 @@ class _TestCases:"AuthenticationError","Invalid API key",401,+ _LLM,InferenceErrorCategory.CONFIGURATION,UserActionKind.CHECK_CREDENTIALS,+ CoreCode.PROVIDER_CREDENTIAL_REFUSED,False,),(@@ -66,8 +99,10 @@ class _TestCases:"PermissionDeniedError","Forbidden",403,+ _LLM,InferenceErrorCategory.CONFIGURATION,UserActionKind.CHECK_CREDENTIALS,+ CoreCode.PROVIDER_CREDENTIAL_REFUSED,False,),(@@ -76,8 +111,10 @@ class _TestCases:"PermissionDeniedError","Your credit balance is too low",403,+ _LLM,InferenceErrorCategory.CAPACITY,UserActionKind.CHECK_BILLING,+ CoreCode.PROVIDER_QUOTA_EXHAUSTED,False,),(@@ -86,18 +123,70 @@ class _TestCases:"NotFoundError","The model does not exist",404,+ _LLM,InferenceErrorCategory.CONFIGURATION,UserActionKind.CHANGE_MODEL,+ CoreCode.MODEL_UNAVAILABLE,True,),(- "bad_request_400",+ "bad_request_400_is_a_request_of_ours",ProviderName.OPENAI,"BadRequestError","Bad request",400,+ _LLM,InferenceErrorCategory.CONTENT,UserActionKind.CHANGE_INPUT,+ CoreCode.RUNTIME_UNEXPECTED,+ False,+ ),+ (+ "bad_request_400_with_a_content_policy_signal",+ ProviderName.OPENAI,+ "BadRequestError",+ "Your request was rejected as a result of our safety system",+ 400,+ _IMG_GEN,+ InferenceErrorCategory.CONTENT,+ UserActionKind.CHANGE_INPUT,+ CoreCode.MODEL_CONTENT_REFUSED,+ False,+ ),+ (+ "request_too_large_413",+ ProviderName.ANTHROPIC,+ "RequestTooLargeError",+ "Request too large",+ 413,+ _LLM,+ InferenceErrorCategory.CONFIGURATION,+ UserActionKind.CHANGE_INPUT,+ CoreCode.INPUT_TOO_LARGE,+ False,+ ),+ (+ "request_timeout_408_is_retried",+ ProviderName.OPENAI,+ "APIStatusError",+ "Request timeout",+ 408,+ _LLM,+ InferenceErrorCategory.TRANSIENT,+ UserActionKind.WAIT_AND_RETRY,+ CoreCode.PROVIDER_TIMEOUT,+ False,+ ),+ (+ "image_timeout_408_through_the_gateway_is_retried",+ ProviderName.GATEWAY,+ "APIStatusError",+ "The operation was timeout.",+ 408,+ _IMG_GEN,+ InferenceErrorCategory.TRANSIENT,+ UserActionKind.WAIT_AND_RETRY,+ CoreCode.PROVIDER_TIMEOUT,False,),(@@ -106,8 +195,10 @@ class _TestCases:"UnprocessableEntityError","Unprocessable entity",422,+ _LLM,InferenceErrorCategory.CONFIGURATION,UserActionKind.CHANGE_INPUT,+ CoreCode.RUNTIME_UNEXPECTED,False,),(@@ -116,8 +207,22 @@ class _TestCases:"InternalServerError","Internal server error",500,+ _LLM,InferenceErrorCategory.TRANSIENT,UserActionKind.WAIT_AND_RETRY,+ CoreCode.PROVIDER_FAILED,+ False,+ ),+ (+ "bad_gateway_502",+ ProviderName.OPENAI,+ "InternalServerError",+ "Bad gateway",+ 502,+ _LLM,+ InferenceErrorCategory.TRANSIENT,+ UserActionKind.WAIT_AND_RETRY,+ CoreCode.PROVIDER_FAILED,False,),(@@ -126,8 +231,46 @@ class _TestCases:"ServerError","Service unavailable",503,+ _LLM,InferenceErrorCategory.TRANSIENT,UserActionKind.WAIT_AND_RETRY,+ CoreCode.PROVIDER_UNAVAILABLE,+ False,+ ),+ (+ "gateway_timeout_504",+ ProviderName.GOOGLE,+ "ServerError",+ "Gateway timeout",+ 504,+ _EXTRACT,+ InferenceErrorCategory.TRANSIENT,+ UserActionKind.WAIT_AND_RETRY,+ CoreCode.PROVIDER_TIMEOUT,+ False,+ ),+ (+ "anthropic_overloaded_529",+ ProviderName.ANTHROPIC,+ "OverloadedError",+ "Overloaded",+ 529,+ _LLM,+ InferenceErrorCategory.TRANSIENT,+ UserActionKind.WAIT_AND_RETRY,+ CoreCode.PROVIDER_UNAVAILABLE,+ False,+ ),+ (+ "server_error_on_an_image_generation_may_have_run",+ ProviderName.OPENAI,+ "InternalServerError",+ "Internal server error",+ 500,+ _IMG_GEN,+ InferenceErrorCategory.AMBIGUOUS,+ UserActionKind.WAIT_AND_RETRY,+ CoreCode.PROVIDER_OUTCOME_UNKNOWN,False,),(@@ -136,8 +279,22 @@ class _TestCases:"ConflictError","Conflict",409,+ _LLM,InferenceErrorCategory.CONFIGURATION,UserActionKind.CHANGE_INPUT,+ CoreCode.RUNTIME_UNEXPECTED,+ False,+ ),+ (+ "non_error_status_on_an_error_envelope",+ ProviderName.AZURE,+ "JSONDecodeError",+ "Expecting value",+ 200,+ _IMG_GEN,+ InferenceErrorCategory.UNKNOWN,+ UserActionKind.CONTACT_SUPPORT,+ CoreCode.PROVIDER_RESPONSE_INVALID,False,),(@@ -146,8 +303,46 @@ class _TestCases:"APIConnectionError","Connection failed",None,+ _LLM,InferenceErrorCategory.TRANSIENT,UserActionKind.WAIT_AND_RETRY,+ CoreCode.PROVIDER_UNAVAILABLE,+ False,+ ),+ (+ "statusless_sdk_connection_error_on_an_image_generation_may_have_been_sent",+ ProviderName.OPENAI,+ "APIConnectionError",+ "Connection failed",+ None,+ _IMG_GEN,+ InferenceErrorCategory.AMBIGUOUS,+ UserActionKind.WAIT_AND_RETRY,+ CoreCode.PROVIDER_OUTCOME_UNKNOWN,+ False,+ ),+ (+ "statusless_httpx_connect_error_on_an_image_generation_was_never_sent",+ ProviderName.AZURE,+ "ConnectError",+ "Connection refused",+ None,+ _IMG_GEN,+ InferenceErrorCategory.TRANSIENT,+ UserActionKind.WAIT_AND_RETRY,+ CoreCode.PROVIDER_UNAVAILABLE,+ False,+ ),+ (+ "statusless_connect_timeout_is_an_outage_not_a_timeout",+ ProviderName.AZURE,+ "ConnectTimeout",+ "Connect timed out",+ None,+ _LLM,+ InferenceErrorCategory.TRANSIENT,+ UserActionKind.WAIT_AND_RETRY,+ CoreCode.PROVIDER_UNAVAILABLE,False,),(@@ -156,8 +351,22 @@ class _TestCases:"APITimeoutError","Request timed out",None,+ _LLM,InferenceErrorCategory.TRANSIENT,UserActionKind.WAIT_AND_RETRY,+ CoreCode.PROVIDER_TIMEOUT,+ False,+ ),+ (+ "statusless_read_timeout_on_an_image_generation",+ ProviderName.HUGGINGFACE,+ "InferenceTimeoutError",+ "Inference timed out",+ None,+ _IMG_GEN,+ InferenceErrorCategory.AMBIGUOUS,+ UserActionKind.WAIT_AND_RETRY,+ CoreCode.PROVIDER_OUTCOME_UNKNOWN,False,),(@@ -166,8 +375,10 @@ class _TestCases:"ValidationError","Schema validation failed",None,+ _LLM,InferenceErrorCategory.CONTENT,UserActionKind.CHANGE_INPUT,+ CoreCode.MODEL_OUTPUT_SCHEMA_MISMATCH,False,),(@@ -176,8 +387,22 @@ class _TestCases:"FileNotFoundError","No such file",None,+ _EXTRACT,InferenceErrorCategory.CONTENT,UserActionKind.CHANGE_INPUT,+ CoreCode.INPUT_REFERENCE_NOT_FOUND,+ False,+ ),+ (+ "statusless_file_that_does_not_parse",+ ProviderName.PYPDFIUM2,+ "ValueError",+ "Failed to load document",+ None,+ _EXTRACT,+ InferenceErrorCategory.CONTENT,+ UserActionKind.CHANGE_INPUT,+ CoreCode.INPUT_FILE_UNREADABLE,False,),(@@ -186,8 +411,10 @@ class _TestCases:"OSError","I/O error",None,- InferenceErrorCategory.TRANSIENT,- UserActionKind.WAIT_AND_RETRY,+ _EXTRACT,+ InferenceErrorCategory.UNKNOWN,+ UserActionKind.CONTACT_SUPPORT,+ CoreCode.RUNTIME_UNEXPECTED,False,),(@@ -196,8 +423,10 @@ class _TestCases:"LinkupAuthenticationError","Authentication failed",None,+ _SEARCH,InferenceErrorCategory.CONFIGURATION,UserActionKind.CHECK_CREDENTIALS,+ CoreCode.PROVIDER_CREDENTIAL_REFUSED,False,),(@@ -206,8 +435,34 @@ class _TestCases:"LinkupInsufficientCreditError","Insufficient credits",None,+ _SEARCH,InferenceErrorCategory.CAPACITY,UserActionKind.CHECK_BILLING,+ CoreCode.PROVIDER_QUOTA_EXHAUSTED,+ False,+ ),+ (+ "statusless_linkup_failed_fetch_is_the_caller_s_url",+ ProviderName.LINKUP,+ "LinkupFailedFetchError",+ "Failed to fetch the page",+ None,+ _EXTRACT,+ InferenceErrorCategory.TRANSIENT,+ UserActionKind.WAIT_AND_RETRY,+ CoreCode.INPUT_URL_UNREACHABLE,+ False,+ ),+ (+ "statusless_linkup_no_result",+ ProviderName.LINKUP,+ "LinkupNoResultError",+ "No result",+ None,+ _SEARCH,+ InferenceErrorCategory.CONTENT,+ UserActionKind.CHANGE_INPUT,+ CoreCode.MODEL_NO_RESULT,False,),(@@ -216,18 +471,22 @@ class _TestCases:"MissingCredentialsError","FAL API key is not configured",None,+ _IMG_GEN,InferenceErrorCategory.CONFIGURATION,UserActionKind.CHECK_CREDENTIALS,+ PipelexErrorCode.CONFIG_CREDENTIAL_MISSING,False,),(- "statusless_fal_client_error",+ "statusless_fal_client_error_may_have_run",ProviderName.FAL,"FalClientError","FAL SDK failed without a recoverable HTTP status",None,- InferenceErrorCategory.TRANSIENT,+ _IMG_GEN,+ InferenceErrorCategory.AMBIGUOUS,UserActionKind.WAIT_AND_RETRY,+ CoreCode.PROVIDER_OUTCOME_UNKNOWN,False,),(@@ -236,8 +495,10 @@ class _TestCases:"BrandNewSdkError","Something nobody has seen before",None,+ _LLM,InferenceErrorCategory.UNKNOWN,UserActionKind.CONTACT_SUPPORT,+ CoreCode.RUNTIME_UNEXPECTED,False,),# httpx TransportError subclasses whose class names lack a recognized network token@@ -250,8 +511,10 @@ class _TestCases:"ReadError","stream read failed",None,+ _LLM,InferenceErrorCategory.TRANSIENT,UserActionKind.WAIT_AND_RETRY,+ CoreCode.PROVIDER_UNAVAILABLE,False,),(@@ -260,8 +523,10 @@ class _TestCases:"RemoteProtocolError","server disconnected",None,+ _LLM,InferenceErrorCategory.TRANSIENT,UserActionKind.WAIT_AND_RETRY,+ CoreCode.PROVIDER_UNAVAILABLE,False,),(@@ -270,8 +535,10 @@ class _TestCases:"ProxyError","proxy refused",None,+ _LLM,InferenceErrorCategory.TRANSIENT,UserActionKind.WAIT_AND_RETRY,+ CoreCode.PROVIDER_UNAVAILABLE,False,),]@@ -279,7 +546,7 @@ class _TestCases:class TestClassifyInferenceError:@pytest.mark.parametrize(- ("_topic", "provider", "sdk_exception_type", "message", "status_code", "provider_error_code", "expected_category"),+ ("_topic", "provider", "sdk_exception_type", "message", "status_code", "provider_error_code", "expected_category", "expected_error_code"),[("fal_content_policy_on_422",@@ -289,6 +556,7 @@ class TestClassifyInferenceError:422,"ContentPolicyViolation",InferenceErrorCategory.CONTENT,+ CoreCode.MODEL_CONTENT_REFUSED,),("content_policy_message_on_422",@@ -298,6 +566,7 @@ class TestClassifyInferenceError:422,None,InferenceErrorCategory.CONTENT,+ CoreCode.MODEL_CONTENT_REFUSED,),("plain_422_stays_configuration",@@ -307,6 +576,7 @@ class TestClassifyInferenceError:422,None,InferenceErrorCategory.CONFIGURATION,+ CoreCode.RUNTIME_UNEXPECTED,),("bedrock_service_quota_via_error_code",@@ -316,6 +586,7 @@ class TestClassifyInferenceError:400,"ServiceQuotaExceededException",InferenceErrorCategory.CAPACITY,+ CoreCode.PROVIDER_QUOTA_EXHAUSTED,),],)@@ -328,6 +599,7 @@ class TestClassifyInferenceError:status_code: int | None,provider_error_code: str | None,expected_category: InferenceErrorCategory,+ expected_error_code: ErrorCode,) -> None:"""Extra signals beyond status code: provider_error_code and content-policy detection."""metadata = ProviderErrorMetadata(@@ -338,9 +610,10 @@ class TestClassifyInferenceError:provider_error_code=provider_error_code,)- result = classify_inference_error(metadata)+ result = classify_inference_error(metadata, family=InferenceErrorFamily.IMG_GEN)assert result.category == expected_category+ assert result.error_code == expected_error_code@pytest.mark.parametrize((@@ -349,8 +622,10 @@ class TestClassifyInferenceError:"sdk_exception_type","message","status_code",+ "family","expected_category","expected_action",+ "expected_error_code","expected_model_not_found",),_TestCases.PARITY,@@ -362,8 +637,10 @@ class TestClassifyInferenceError:sdk_exception_type: str,message: str,status_code: int | None,+ family: InferenceErrorFamily,expected_category: InferenceErrorCategory,expected_action: UserActionKind,+ expected_error_code: ErrorCode,expected_model_not_found: bool,) -> None:metadata = ProviderErrorMetadata(@@ -373,10 +650,11 @@ class TestClassifyInferenceError:status_code=status_code,)- result = classify_inference_error(metadata)+ result = classify_inference_error(metadata, family=family)assert result.category == expected_categoryassert result.user_action_kind == expected_action+ assert result.error_code == expected_error_codeassert result.is_model_not_found is expected_model_not_found@pytest.mark.parametrize(@@ -402,7 +680,34 @@ class TestClassifyInferenceError:status_code=429,)- result = classify_inference_error(metadata)+ result = classify_inference_error(metadata, family=InferenceErrorFamily.LLM)assert result.category == InferenceErrorCategory.TRANSIENTassert result.user_action_kind == UserActionKind.WAIT_AND_RETRY+ assert result.error_code == CoreCode.PROVIDER_RATE_LIMITED++ @pytest.mark.parametrize(+ ("category", "error_code", "is_model_not_found", "expected_fragment"),+ [+ (InferenceErrorCategory.UNKNOWN, CoreCode.PIPE_PROMPT_EMPTY, False, "not one an inference failure class declares"),+ (InferenceErrorCategory.UNKNOWN, PipelexErrorCode.CONFIG_VARIABLE_MISSING, False, "not one an inference failure class declares"),+ (InferenceErrorCategory.UNKNOWN, CoreCode.PROVIDER_FAILED, True, "reports 'model.unavailable'"),+ # The run repeats a transient call, so its report cannot say no retry clears it.+ (InferenceErrorCategory.TRANSIENT, CoreCode.RUNTIME_UNEXPECTED, False, "reports a code that invites a retry"),+ ],+ )+ def test_a_classification_refuses_a_code_its_render_could_not_report(+ self,+ category: InferenceErrorCategory,+ error_code: ErrorCode,+ is_model_not_found: bool,+ expected_fragment: str,+ ) -> None:+ """The render constructs a family's class with the code, so a code no family class declares, or its category contradicts, is refused first."""+ with pytest.raises(ValidationError, match=expected_fragment):+ ClassificationResult(+ category=category,+ user_action_kind=UserActionKind.CONTACT_SUPPORT,+ error_code=error_code,+ is_model_not_found=is_model_not_found,+ )diff --git a/tests/unit/pipelex/cogt/inference/test_model_not_allowed.py b/tests/unit/pipelex/cogt/inference/test_model_not_allowed.pyindex 635a5d004..c689af53f 100644--- a/tests/unit/pipelex/cogt/inference/test_model_not_allowed.py+++ b/tests/unit/pipelex/cogt/inference/test_model_not_allowed.py@@ -33,6 +33,7 @@ from typing import TYPE_CHECKING, Anyimport anthropicimport httpximport pytest+from mthds.protocol.problem.registry import CoreCodefrom openai import OpenAIfrom portkey_ai import Portkey@@ -46,8 +47,8 @@ from pipelex.cogt.inference.error_classification import (extract_gateway_metadata,extract_openai_metadata,)-from pipelex.cogt.inference.error_classify import classify_inference_error-from pipelex.cogt.inference.error_render import InferenceErrorFamily, render_inference_error+from pipelex.cogt.inference.error_classify import InferenceErrorFamily, classify_inference_error+from pipelex.cogt.inference.error_render import render_inference_errorfrom pipelex.cogt.inference.provider_name import ProviderNamefrom pipelex.pipe_run.exceptions import PipeRouterErrorfrom pipelex.system.pipe_run_mode import PipeRunMode@@ -137,7 +138,7 @@ def _rendered_error() -> CogtError:return render_inference_error(metadata=metadata,- classification=classify_inference_error(metadata),+ classification=classify_inference_error(metadata, family=family),family=family,model_desc=f"{model_handle} → Model[{_MODEL_NOT_ALLOWED_WIRE_ID}]",model_handle=model_handle,@@ -204,22 +205,24 @@ class TestClassification:So ``CHANGE_MODEL`` is what the caller can do, and the flag stays unset:"not found" would be false."""- result = classify_inference_error(_envelope(MODEL_NOT_ALLOWED_ERROR_CODE))+ result = classify_inference_error(_envelope(MODEL_NOT_ALLOWED_ERROR_CODE), family=InferenceErrorFamily.LLM)assert result.is_model_not_allowed is Trueassert result.category == InferenceErrorCategory.CONFIGURATIONassert result.category.is_retryable is Falseassert result.user_action_kind == UserActionKind.CHANGE_MODELassert result.is_model_not_found is False+ assert result.error_code == CoreCode.MODEL_UNAVAILABLEassert result.service_error_code is Nonedef test_a_412_without_the_code_still_takes_the_status_ladder(self) -> None:"""The contrast: the ladder's generic 4xx arm, which is what the refusal would otherwise read as."""- result = classify_inference_error(_envelope("something-else"))+ result = classify_inference_error(_envelope("something-else"), family=InferenceErrorFamily.LLM)assert result.is_model_not_allowed is Falseassert result.category == InferenceErrorCategory.CONFIGURATIONassert result.user_action_kind == UserActionKind.CHANGE_INPUT+ assert result.error_code == CoreCode.RUNTIME_UNEXPECTEDclass TestEndToEnd:@@ -286,19 +289,17 @@ class TestRenderedAdvice:class TestWhatItAnswersOverHTTP:- def test_it_answers_500_as_an_unrecognized_412_does(self) -> None:- """At its real status the refusal's answer does not move: only its advice does.+ def test_it_answers_as_the_operator_s_where_an_unrecognized_412_is_a_runtime_fault(self) -> None:+ """Recognizing the code moves the refusal from a request of ours the provider could not take to the operator's.- The ladder's generic 4xx arm already reads a 412 as ``CONFIGURATION``, so- recognizing the code changes this refusal's ``user_action`` and nothing about- its status.+ The ladder's generic 4xx arm reads an unrecognized 412 as ``runtime.unexpected``; the refusal's code is+ ``model.unavailable``, which the deployment's operator settles by serving or allowing the model."""report = _rendered_error(_envelope(MODEL_NOT_ALLOWED_ERROR_CODE)).to_error_report()unrecognized_report = _rendered_error(_envelope("something-else")).to_error_report()assert report.error_domain == ErrorDomain.CONFIG- assert report.http_status == 500- assert unrecognized_report.error_domain == ErrorDomain.CONFIG+ assert unrecognized_report.error_domain == ErrorDomain.RUNTIMEassert unrecognized_report.http_status == 500diff --git a/tests/unit/pipelex/cogt/inference/test_render_inference_error.py b/tests/unit/pipelex/cogt/inference/test_render_inference_error.pyindex e9500df81..cc3b11a5c 100644--- a/tests/unit/pipelex/cogt/inference/test_render_inference_error.py+++ b/tests/unit/pipelex/cogt/inference/test_render_inference_error.py@@ -6,30 +6,37 @@ Builds synthetic envelopes + classifications and asserts the renderedfrom __future__ import annotations-from typing import ClassVar+from typing import TYPE_CHECKING, ClassVarimport pytest+from mthds.protocol.problem.registry import CoreCodefrom pipelex.cogt.exceptions import (+ INFERENCE_FAILURE_CODES,CogtError,ExtractJobFailureError,ExtractModelNotFoundError,ImgGenGenerationError,ImgGenModelNotFoundError,InferenceErrorCategory,+ JudgmentJobFailureError,+ JudgmentModelNotFoundError,LLMCompletionError,LLMModelNotFoundError,SearchJobFailureError,SearchModelNotFoundError,)from pipelex.cogt.inference.error_classification import ProviderErrorMetadata, UserActionKind-from pipelex.cogt.inference.error_classify import ClassificationResult-from pipelex.cogt.inference.error_render import InferenceErrorFamily, render_inference_error+from pipelex.cogt.inference.error_classify import ClassificationResult, InferenceErrorFamily+from pipelex.cogt.inference.error_render import render_inference_errorfrom pipelex.cogt.inference.provider_name import ProviderNamefrom pipelex.pipe_run.exceptions import PipeRouterErrorfrom pipelex.pipeline.exceptions import PipelineExecutionErrorfrom pipelex.system.pipe_run_mode import PipeRunMode+if TYPE_CHECKING:+ from pipelex.errors.error_codes import ErrorCode+class _TestCases:# (topic, family, expected_failure_class, expected_not_found_class)@@ -38,6 +45,7 @@ class _TestCases:("img_gen", InferenceErrorFamily.IMG_GEN, ImgGenGenerationError, ImgGenModelNotFoundError),("extract", InferenceErrorFamily.EXTRACT, ExtractJobFailureError, ExtractModelNotFoundError),("search", InferenceErrorFamily.SEARCH, SearchJobFailureError, SearchModelNotFoundError),+ ("judgment", InferenceErrorFamily.JUDGMENT, JudgmentJobFailureError, JudgmentModelNotFoundError),]@@ -66,6 +74,7 @@ class TestRenderInferenceError:classification = ClassificationResult(category=InferenceErrorCategory.TRANSIENT,user_action_kind=UserActionKind.WAIT_AND_RETRY,+ error_code=CoreCode.PROVIDER_FAILED,)rendered = render_inference_error(@@ -77,6 +86,7 @@ class TestRenderInferenceError:)assert type(rendered) is expected_failure_class+ assert rendered.resolve_error_code() == CoreCode.PROVIDER_FAILEDassert rendered.error_category == InferenceErrorCategory.TRANSIENTassert rendered.user_action is not Noneassert rendered.user_action.kind == UserActionKind.WAIT_AND_RETRY@@ -98,6 +108,7 @@ class TestRenderInferenceError:classification = ClassificationResult(category=InferenceErrorCategory.CONFIGURATION,user_action_kind=UserActionKind.CHANGE_MODEL,+ error_code=CoreCode.MODEL_UNAVAILABLE,is_model_not_found=True,)@@ -110,6 +121,7 @@ class TestRenderInferenceError:)assert type(rendered) is expected_not_found_class+ assert rendered.resolve_error_code() == CoreCode.MODEL_UNAVAILABLEassert rendered.error_category == InferenceErrorCategory.CONFIGURATIONassert rendered.model_handle == "fake-handle"assert rendered.provider_metadata is metadata@@ -124,6 +136,7 @@ class TestRenderInferenceError:classification = ClassificationResult(category=InferenceErrorCategory.CONTENT,user_action_kind=UserActionKind.CHANGE_INPUT,+ error_code=CoreCode.MODEL_CONTENT_REFUSED,)rendered = render_inference_error(@@ -162,6 +175,7 @@ class TestRenderInferenceError:classification = ClassificationResult(category=InferenceErrorCategory.TRANSIENT,user_action_kind=UserActionKind.WAIT_AND_RETRY,+ error_code=CoreCode.PROVIDER_RATE_LIMITED,)root_fault = render_inference_error(metadata=metadata,@@ -191,3 +205,55 @@ class TestRenderInferenceError:assert report_payload["user_action"] == {"kind": "wait_and_retry", "detail": expected_detail}assert "automatically" not in report_payload["user_action"]["detail"]++ @pytest.mark.parametrize("error_code", INFERENCE_FAILURE_CODES, ids=str)+ @pytest.mark.parametrize(+ ("_topic", "family", "expected_failure_class", "_expected_not_found_class"),+ _TestCases.FAMILIES,+ )+ def test_every_classified_code_renders_for_every_family(+ self,+ _topic: str,+ family: InferenceErrorFamily,+ expected_failure_class: type[CogtError],+ _expected_not_found_class: type[CogtError],+ error_code: ErrorCode,+ ) -> None:+ """Each family's failure class declares every code a classification may carry, so the render never refuses one."""+ classification = ClassificationResult(+ category=InferenceErrorCategory.UNKNOWN,+ user_action_kind=UserActionKind.CONTACT_SUPPORT,+ error_code=error_code,+ )++ rendered = render_inference_error(+ metadata=_metadata(),+ classification=classification,+ family=family,+ model_desc="gpt-fake",+ model_handle="fake-handle",+ )++ assert type(rendered) is expected_failure_class+ assert rendered.resolve_error_code() == error_code++ def test_an_outcome_nobody_knows_is_not_advised_to_be_run_again_blind(self) -> None:+ """An image generation that may have run is checked for before it is repeated, whatever the kind says."""+ classification = ClassificationResult(+ category=InferenceErrorCategory.AMBIGUOUS,+ user_action_kind=UserActionKind.WAIT_AND_RETRY,+ error_code=CoreCode.PROVIDER_OUTCOME_UNKNOWN,+ )++ rendered = render_inference_error(+ metadata=_metadata(),+ classification=classification,+ family=InferenceErrorFamily.IMG_GEN,+ model_desc="gpt-image-fake",+ model_handle="fake-handle",+ )++ assert type(rendered) is ImgGenGenerationError+ assert rendered.resolve_error_code() == CoreCode.PROVIDER_OUTCOME_UNKNOWN+ assert rendered.user_action is not None+ assert "check for one before running it again" in rendered.user_action.detaildiff --git a/tests/unit/pipelex/cogt/inference/test_service_error_vocabulary.py b/tests/unit/pipelex/cogt/inference/test_service_error_vocabulary.pyindex 209806409..b83c8f6e6 100644--- a/tests/unit/pipelex/cogt/inference/test_service_error_vocabulary.py+++ b/tests/unit/pipelex/cogt/inference/test_service_error_vocabulary.py@@ -11,11 +11,12 @@ from __future__ import annotationsfrom typing import TYPE_CHECKINGimport pytest+from mthds.protocol.problem.registry import CoreCodefrom pipelex.cogt.exceptions import ExtractJobFailureError, ExtractModelNotFoundError, InferenceErrorCategory, LLMCompletionErrorfrom pipelex.cogt.inference.error_classification import ProviderErrorMetadata, UserActionKind-from pipelex.cogt.inference.error_classify import classify_inference_error-from pipelex.cogt.inference.error_render import InferenceErrorFamily, render_inference_error+from pipelex.cogt.inference.error_classify import InferenceErrorFamily, classify_inference_error+from pipelex.cogt.inference.error_render import render_inference_errorfrom pipelex.cogt.inference.provider_name import ProviderNamefrom pipelex.cogt.inference.service_error_vocabulary import ServiceErrorCode, ServiceErrorVocabulary@@ -28,12 +29,14 @@ _TOO_LARGE = ServiceErrorCode(code="svc-too-large",category=InferenceErrorCategory.CONTENT,user_action_kind=UserActionKind.CHANGE_INPUT,+ error_code=CoreCode.INPUT_TOO_LARGE,detail="The request was over the service's limit — send less.",)_UNKNOWN_MODEL = ServiceErrorCode(code="svc-unknown-model",category=InferenceErrorCategory.CONFIGURATION,user_action_kind=UserActionKind.CHANGE_MODEL,+ error_code=CoreCode.MODEL_UNAVAILABLE,detail="The service does not serve that model.",is_model_not_found=True,)@@ -41,6 +44,7 @@ _NOT_CONFIGURED = ServiceErrorCode(code="svc-not-configured",category=InferenceErrorCategory.CONFIGURATION,user_action_kind=UserActionKind.CONTACT_SUPPORT,+ error_code=CoreCode.RUNTIME_MISCONFIGURED,detail="The service is not configured for this — contact support.",)@@ -64,18 +68,19 @@ class TestClassification:def test_a_contributed_code_decides_ahead_of_the_ladder(self, mocker: MockerFixture, entry: ServiceErrorCode) -> None:mocker.patch(_ACCESSOR, return_value=_vocabulary())- classification = classify_inference_error(_metadata(status_code=400, code=entry.code))+ classification = classify_inference_error(_metadata(status_code=400, code=entry.code), family=InferenceErrorFamily.LLM)assert classification.service_error_code == entryassert classification.category == entry.categoryassert classification.user_action_kind == entry.user_action_kindassert classification.is_model_not_found == entry.is_model_not_found+ assert classification.error_code == entry.error_codedef test_it_runs_ahead_of_the_quota_rules(self, mocker: MockerFixture) -> None:"""A 402 the quota rules would call billing is the service's own refusal when it carries a contributed code."""mocker.patch(_ACCESSOR, return_value=_vocabulary())- classification = classify_inference_error(_metadata(status_code=402, code=_NOT_CONFIGURED.code))+ classification = classify_inference_error(_metadata(status_code=402, code=_NOT_CONFIGURED.code), family=InferenceErrorFamily.LLM)assert classification.category == InferenceErrorCategory.CONFIGURATIONassert classification.user_action_kind == UserActionKind.CONTACT_SUPPORT@@ -83,7 +88,7 @@ class TestClassification:def test_a_code_nobody_contributed_takes_the_ladder(self, mocker: MockerFixture) -> None:mocker.patch(_ACCESSOR, return_value=_vocabulary())- classification = classify_inference_error(_metadata(status_code=400, code="svc-unheard-of"))+ classification = classify_inference_error(_metadata(status_code=400, code="svc-unheard-of"), family=InferenceErrorFamily.LLM)assert classification.service_error_code is Noneassert classification.category == InferenceErrorCategory.CONTENT@@ -93,7 +98,7 @@ class TestClassification:def test_without_the_contribution_the_ladder_reads_the_status(self, mocker: MockerFixture, vocabulary: ServiceErrorVocabulary | None) -> None:mocker.patch(_ACCESSOR, return_value=vocabulary)- classification = classify_inference_error(_metadata(status_code=400, code=_NOT_CONFIGURED.code))+ classification = classify_inference_error(_metadata(status_code=400, code=_NOT_CONFIGURED.code), family=InferenceErrorFamily.LLM)assert classification.service_error_code is Noneassert classification.category == InferenceErrorCategory.CONTENT@@ -103,7 +108,7 @@ class TestClassification:accessor = mocker.patch(_ACCESSOR, return_value=_vocabulary())metadata = ProviderErrorMetadata(provider=ProviderName.GATEWAY, sdk_exception_type="ConnectTimeout", message="timed out")- classification = classify_inference_error(metadata)+ classification = classify_inference_error(metadata, family=InferenceErrorFamily.LLM)assert classification.category == InferenceErrorCategory.TRANSIENTaccessor.assert_not_called()@@ -116,13 +121,14 @@ class TestRendering:error = render_inference_error(metadata=metadata,- classification=classify_inference_error(metadata),+ classification=classify_inference_error(metadata, family=InferenceErrorFamily.LLM),family=InferenceErrorFamily.LLM,model_desc="some-model",model_handle="some-model",)assert isinstance(error, LLMCompletionError)+ assert error.resolve_error_code() == CoreCode.INPUT_TOO_LARGEassert error.user_action is not Noneassert error.user_action.detail == _TOO_LARGE.detailassert error.error_category == InferenceErrorCategory.CONTENT@@ -134,13 +140,14 @@ class TestRendering:error = render_inference_error(metadata=metadata,- classification=classify_inference_error(metadata),+ classification=classify_inference_error(metadata, family=InferenceErrorFamily.LLM),family=InferenceErrorFamily.EXTRACT,model_desc="some-model",model_handle="some-handle",)assert isinstance(error, ExtractModelNotFoundError)+ assert error.resolve_error_code() == CoreCode.MODEL_UNAVAILABLEassert error.user_action is not Noneassert error.user_action.detail == _UNKNOWN_MODEL.detail@@ -150,7 +157,7 @@ class TestRendering:error = render_inference_error(metadata=metadata,- classification=classify_inference_error(metadata),+ classification=classify_inference_error(metadata, family=InferenceErrorFamily.LLM),family=InferenceErrorFamily.EXTRACT,model_desc="some-model",model_handle="some-handle",@@ -158,3 +165,4 @@ class TestRendering:assert isinstance(error, ExtractJobFailureError)assert not isinstance(error, ExtractModelNotFoundError)+ assert error.resolve_error_code() == CoreCode.RUNTIME_MISCONFIGUREDdiff --git a/tests/unit/pipelex/cogt/models/test_model_deck_check.py b/tests/unit/pipelex/cogt/models/test_model_deck_check.pyindex 6445c95d2..8aaed9126 100644--- a/tests/unit/pipelex/cogt/models/test_model_deck_check.py+++ b/tests/unit/pipelex/cogt/models/test_model_deck_check.py@@ -1,6 +1,7 @@from typing import Any, Callableimport pytest+from mthds.protocol.problem.registry import CoreCodefrom pytest_mock import MockerFixturefrom pipelex.cogt.config_cogt import ModelDeckConfig@@ -376,7 +377,7 @@ class TestModelDeckCheck:model_choice: str,needed_model: str,) -> None:- """A bare handle the deck serves only as another model type is refused, and the sentence names that mismatch rather than a missing handle."""+ """A bare handle the deck serves only as another model type is refused as a capability it lacks, and the sentence names that mismatch."""model_deck = self._create_test_model_deck()mocker.patch(GET_MODEL_DECK_TARGET, return_value=model_deck)@@ -389,6 +390,7 @@ class TestModelDeckCheck:assert error.reference_kind == ModelReferenceKind.HANDLEassert str(error).startswith(f"Model handle '{name}' is served by the model deck, but not as {needed_model}")assert "was not found" not in str(error)+ assert error.resolve_error_code() == CoreCode.MODEL_CAPABILITY_UNSUPPORTED@pytest.mark.parametrize(("check_fn", "model_type"),diff --git a/tests/unit/pipelex/cogt/models/test_model_deck_choice_unresolved.py b/tests/unit/pipelex/cogt/models/test_model_deck_choice_unresolved.pynew file mode 100644index 000000000..2fa9388e3--- /dev/null+++ b/tests/unit/pipelex/cogt/models/test_model_deck_choice_unresolved.py@@ -0,0 +1,245 @@+"""Whose fault an unresolved model choice is: the method's when its step named the model, the deployment's when the deck did.++The deck's lookups refuse a reference they do not resolve as ``ModelChoiceNotFoundError``, ``model.unknown`` and+caller-facing, which is right for a model the method named. A default or an override the deck names itself reaches the+same lookups when a step names no model, and a miss there is the deck's: ``ModelDeckChoiceUnresolvedError``, which a+caller cannot fix by changing their input, reports ``model.unavailable`` for a bare handle no backend serves and+``pipelex.config.invalid`` for a preset, alias or waterfall the deck does not define, and is never caller-facing.+"""++from __future__ import annotations++from typing import TYPE_CHECKING, Any++import pytest+from mthds.protocol.problem.registry import CoreCode++from pipelex.cogt.config_cogt import ModelDeckConfig+from pipelex.cogt.doc_gen.doc_gen_engine import resolve_doc_gen_setting+from pipelex.cogt.doc_gen.doc_gen_format import DocGenFormat, DocGenSource+from pipelex.cogt.exceptions import ModelChoiceNotFoundError, ModelDeckChoiceUnresolvedError+from pipelex.cogt.img_gen.img_gen_job_components import Quality+from pipelex.cogt.llm.llm_setting import LLMSettingChoices, LLMSettingChoicesDefaults+from pipelex.cogt.llm.thinking_mode import ThinkingMode+from pipelex.cogt.model_backends.model_spec import InferenceModelSpec+from pipelex.cogt.model_backends.model_spec_index import ModelSpecIndex+from pipelex.cogt.model_backends.model_type import ModelType+from pipelex.cogt.models.model_deck import ModelDeck+from pipelex.cogt.usage.cost_category import CostCategory+from pipelex.errors.registry.pipelex_codes import PipelexErrorCode+from pipelex.kernel.extract_ops import resolve_extract_setting+from pipelex.kernel.img_gen_ops import resolve_img_gen_setting+from pipelex.kernel.judgment_ops import judgment_setting_of_choice+from pipelex.kernel.llm_ops import resolve_llm_setting_for_object, resolve_llm_setting_for_text+from pipelex.kernel.search_ops import resolve_search_setting+from pipelex.system.runtime import ProblemReaction++if TYPE_CHECKING:+ from collections.abc import Callable++ from pytest_mock import MockerFixture++ from pipelex.errors.error_codes import ErrorCode++_DECK_ACCESSORS: tuple[str, ...] = (+ "pipelex.kernel.llm_ops.get_model_deck",+ "pipelex.kernel.extract_ops.get_model_deck",+ "pipelex.kernel.img_gen_ops.get_model_deck",+ "pipelex.kernel.search_ops.get_model_deck",+ "pipelex.kernel.judgment_ops.get_model_deck",+ "pipelex.cogt.doc_gen.doc_gen_engine.get_model_deck",+)+++def _served_model(*, name: str, model_type: ModelType) -> InferenceModelSpec:+ return InferenceModelSpec(+ backend_name="test_backend",+ name=name,+ sdk="test_sdk",+ model_type=model_type,+ model_id=f"test_{name}",+ costs={CostCategory.INPUT: 0.001, CostCategory.OUTPUT: 0.002},+ thinking_mode=ThinkingMode.NONE,+ max_tokens=1000,+ max_prompt_images=None,+ )+++def _make_deck(*, llm_choice_overrides: LLMSettingChoices | None = None) -> ModelDeck:+ """A deck serving one LLM and one image model, every default of which names a model it does not resolve."""+ return ModelDeck(+ inference_models=ModelSpecIndex.make_from_specs(+ model_specs=[+ _served_model(name="served-llm", model_type=ModelType.LLM),+ _served_model(name="served-img-gen", model_type=ModelType.IMG_GEN),+ ]+ ),+ llm_default_temperature=0.7,+ llm_aliases={},+ llm_waterfalls={},+ llm_presets={},+ llm_choice_defaults=LLMSettingChoicesDefaults(+ default_temperature=0.7,+ # A stale scalar default: a handle the deck once served.+ for_text="stale-text-model",+ for_object="$missing-object-preset",+ ),+ llm_choice_overrides=llm_choice_overrides or LLMSettingChoices(for_text=None, for_object=None),+ extract_aliases={},+ extract_waterfalls={},+ extract_presets={},+ extract_choice_default="$missing-extract-preset",+ img_gen_default_quality=Quality.MEDIUM,+ img_gen_aliases={},+ img_gen_waterfalls={},+ img_gen_presets={},+ img_gen_choice_default="stale-img-gen-model",+ search_aliases={},+ search_waterfalls={},+ search_presets={},+ search_choice_default="~missing-search-waterfall",+ doc_gen_choice_defaults={"pdf.layout": "@missing-doc-gen-alias"},+ judgment_choice_default="@missing-judgment-alias",+ model_deck_config=ModelDeckConfig(is_model_fallback_enabled=True, missing_presets_reaction=ProblemReaction.NONE),+ )+++def _use_deck(mocker: MockerFixture, *, model_deck: ModelDeck) -> None:+ for accessor in _DECK_ACCESSORS:+ mocker.patch(accessor, return_value=model_deck)+++def _resolve_doc_gen_default() -> Any:+ return resolve_doc_gen_setting(doc_gen_choice=None, doc_gen_format=DocGenFormat.PDF, source=DocGenSource.LAYOUT, pipe_code=None)+++def _deck_llm_setting_of_img_gen_model(model_deck: ModelDeck) -> Any:+ return model_deck.get_llm_setting(llm_choice="served-img-gen")+++def _deck_check_of_img_gen_model(model_deck: ModelDeck) -> Any:+ return model_deck.check_llm_choice(llm_choice="served-img-gen")+++class TestModelDeckChoiceUnresolved:+ @pytest.mark.parametrize(+ ("_topic", "resolve", "expected_deck_setting", "expected_code"),+ [+ ("llm_text_stale_handle", resolve_llm_setting_for_text, "llm.choice_defaults.for_text", CoreCode.MODEL_UNAVAILABLE),+ ("llm_object_preset", resolve_llm_setting_for_object, "llm.choice_defaults.for_object", PipelexErrorCode.CONFIG_INVALID),+ ("extract_preset", resolve_extract_setting, "extract.choice_default", PipelexErrorCode.CONFIG_INVALID),+ ("img_gen_stale_handle", resolve_img_gen_setting, "img_gen.choice_default", CoreCode.MODEL_UNAVAILABLE),+ ("search_waterfall", resolve_search_setting, "search.choice_default", PipelexErrorCode.CONFIG_INVALID),+ ("judgment_alias", judgment_setting_of_choice, "judgment.choice_default", PipelexErrorCode.CONFIG_INVALID),+ ("doc_gen_alias", _resolve_doc_gen_default, 'doc_gen.choice_defaults["pdf.layout"]', PipelexErrorCode.CONFIG_INVALID),+ ],+ )+ def test_a_deck_default_that_does_not_resolve_is_the_deployment_s_fault(+ self,+ mocker: MockerFixture,+ _topic: str,+ resolve: Callable[[], Any],+ expected_deck_setting: str,+ expected_code: ErrorCode,+ ) -> None:+ """A step naming no model runs on the deck's default, so the deck's miss is no input of the caller's."""+ _use_deck(mocker, model_deck=_make_deck())++ with pytest.raises(ModelDeckChoiceUnresolvedError) as exc_info:+ resolve()++ unresolved = exc_info.value+ # Still a choice the deck does not resolve, so a handler that leaves an unresolvable choice to the run skips it.+ assert isinstance(unresolved, ModelChoiceNotFoundError)+ assert unresolved.deck_setting == expected_deck_setting+ assert expected_deck_setting in unresolved.message+ assert unresolved.resolve_error_code() == expected_code+ assert isinstance(unresolved.__cause__, ModelChoiceNotFoundError)+ report = unresolved.to_error_report()+ assert report.caller_facing_message is False+ assert report.error_domain != "input"++ @pytest.mark.parametrize(+ ("_topic", "resolve", "expected_choice"),+ [+ ("llm_text", lambda: resolve_llm_setting_for_text(llm_choice="$unknown-method-preset"), "$unknown-method-preset"),+ ("llm_object", lambda: resolve_llm_setting_for_object(llm_choice="unknown-method-model"), "unknown-method-model"),+ ("extract", lambda: resolve_extract_setting(extract_choice="@unknown-method-alias"), "@unknown-method-alias"),+ ("img_gen", lambda: resolve_img_gen_setting(img_gen_choice="unknown-method-model"), "unknown-method-model"),+ ("judgment", lambda: judgment_setting_of_choice(judgment_choice="~unknown-method-waterfall"), "~unknown-method-waterfall"),+ ],+ )+ def test_a_model_the_step_names_stays_the_caller_s_input(+ self,+ mocker: MockerFixture,+ _topic: str,+ resolve: Callable[[], Any],+ expected_choice: str,+ ) -> None:+ """The method named the model, so the miss is the method's own: `model.unknown`, caller-facing, input domain."""+ _use_deck(mocker, model_deck=_make_deck())++ with pytest.raises(ModelChoiceNotFoundError) as exc_info:+ resolve()++ not_found = exc_info.value+ assert not isinstance(not_found, ModelDeckChoiceUnresolvedError)+ assert not_found.model_choice == expected_choice+ assert not_found.resolve_error_code() == CoreCode.MODEL_UNKNOWN+ report = not_found.to_error_report()+ assert report.caller_facing_message is True+ assert report.error_domain == "input"++ @pytest.mark.parametrize(+ ("_topic", "llm_choice_overrides", "expected_deck_setting", "expected_code"),+ [+ (+ "preset",+ LLMSettingChoices(for_text="$missing-override-preset", for_object=None),+ "llm.choice_overrides.for_text",+ PipelexErrorCode.CONFIG_INVALID,+ ),+ (+ "stale_handle",+ LLMSettingChoices(for_text=None, for_object="stale-override-model"),+ "llm.choice_overrides.for_object",+ CoreCode.MODEL_UNAVAILABLE,+ ),+ ],+ )+ def test_a_deck_override_that_does_not_resolve_refuses_the_deck(+ self,+ _topic: str,+ llm_choice_overrides: LLMSettingChoices,+ expected_deck_setting: str,+ expected_code: ErrorCode,+ ) -> None:+ """The deck checks its overrides when it loads, and a miss there is the deck's, before any caller is involved."""+ with pytest.raises(ModelDeckChoiceUnresolvedError) as exc_info:+ _make_deck(llm_choice_overrides=llm_choice_overrides)++ unresolved = exc_info.value+ assert unresolved.deck_setting == expected_deck_setting+ assert unresolved.resolve_error_code() == expected_code+ assert unresolved.to_error_report().caller_facing_message is False++ @pytest.mark.parametrize(+ ("_topic", "resolve"),+ [+ ("deck_setting", _deck_llm_setting_of_img_gen_model),+ ("deck_check", _deck_check_of_img_gen_model),+ ],+ )+ def test_a_handle_served_only_as_another_type_is_a_capability_the_model_lacks(+ self,+ _topic: str,+ resolve: Callable[[ModelDeck], Any],+ ) -> None:+ """The model exists and is served, only not as the type the step needs: not an unknown model."""+ with pytest.raises(ModelChoiceNotFoundError) as exc_info:+ resolve(_make_deck())++ not_found = exc_info.value+ assert "served by the model deck, but not as an LLM" in not_found.message+ assert not_found.resolve_error_code() == CoreCode.MODEL_CAPABILITY_UNSUPPORTED+ assert not_found.to_error_report().caller_facing_message is Truediff --git a/tests/unit/pipelex/cogt/models/test_model_deck_type_strictness.py b/tests/unit/pipelex/cogt/models/test_model_deck_type_strictness.pyindex 3f044b1d0..b6ff0426a 100644--- a/tests/unit/pipelex/cogt/models/test_model_deck_type_strictness.py+++ b/tests/unit/pipelex/cogt/models/test_model_deck_type_strictness.py@@ -5,7 +5,7 @@ from pytest_mock import MockerFixturefrom pipelex import logfrom pipelex.cogt.config_cogt import ModelDeckConfig-from pipelex.cogt.exceptions import ImgGenHandleNotFoundError, LLMHandleNotFoundError, ModelChoiceNotFoundError, ModelDeckPresetValidatonError+from pipelex.cogt.exceptions import ImgGenHandleNotFoundError, LLMHandleNotFoundError, ModelChoiceNotFoundError, ModelDeckPresetValidationErrorfrom pipelex.cogt.img_gen.img_gen_job_components import Qualityfrom pipelex.cogt.img_gen.img_gen_setting import ImgGenSettingfrom pipelex.cogt.llm.llm_setting import LLMSetting, LLMSettingChoicesDefaults@@ -123,7 +123,7 @@ class TestModelDeckTypeStrictness:missing_presets_reaction=ProblemReaction.RAISE,)- with pytest.raises(ModelDeckPresetValidatonError, match=r"Failed to validate all LLM presets: LLM preset 'painter': .* but not as an LLM"):+ with pytest.raises(ModelDeckPresetValidationError, match=r"Failed to validate all LLM presets: LLM preset 'painter': .* but not as an LLM"):model_deck.validate_registered_models()def test_a_deck_that_logs_its_unresolvable_presets_warns_once_per_model_type_with_the_same_fields(self, mocker: MockerFixture) -> None:diff --git a/tests/unit/pipelex/cogt/models/test_model_deck_unknown_reference.py b/tests/unit/pipelex/cogt/models/test_model_deck_unknown_reference.pyindex 96fb60218..fac351d44 100644--- a/tests/unit/pipelex/cogt/models/test_model_deck_unknown_reference.py+++ b/tests/unit/pipelex/cogt/models/test_model_deck_unknown_reference.py@@ -1,4 +1,5 @@import pytest+from mthds.protocol.problem.registry import CoreCodefrom pipelex.base_exceptions import INTERNAL_ERROR_PLACEHOLDER, DisclosureMode, ErrorReportfrom pipelex.cogt.config_cogt import ModelDeckConfig@@ -98,6 +99,7 @@ class TestModelDeckUnknownReference:assert report.error_type == "ModelNotFoundError"assert report.message == f"Model handle '{model_handle}' was not found in the model deck."+ assert report.code == CoreCode.MODEL_UNKNOWNassert report.error_domain == "input"assert report.caller_facing_message is Trueassert report.http_status == 422@@ -131,6 +133,7 @@ class TestModelDeckUnknownReference:report = _raise_not_found(model_handle=model_handle, model_type=model_type).to_error_report()assert report.error_type == "ModelNotFoundError"+ assert report.code == CoreCode.MODEL_UNAVAILABLEassert report.error_domain == "config"assert report.caller_facing_message is Falseassert report.http_status == 500diff --git a/tests/unit/pipelex/cogt/test_data.py b/tests/unit/pipelex/cogt/test_data.pyindex f8dc63774..2cef05d2b 100644--- a/tests/unit/pipelex/cogt/test_data.py+++ b/tests/unit/pipelex/cogt/test_data.py@@ -1,7 +1,10 @@from typing import ClassVar+from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import ErrorDomainfrom pipelex.cogt.exceptions import InferenceErrorCategory+from pipelex.errors.error_codes import ErrorCodeclass ExceptionTestData:@@ -14,15 +17,15 @@ class ExceptionTestData:("ambiguous_not_retryable", InferenceErrorCategory.AMBIGUOUS, False),]- # (topic, category, expected_error_domain, expected_http_status)- # Exhaustive over InferenceErrorCategory — the exhaustiveness itself is asserted by- # ``test_category_domain_cases_cover_every_category``, so a new category cannot be added- # without deciding which domain it maps to.- CATEGORY_DOMAIN_CASES: ClassVar[list[tuple[str, InferenceErrorCategory, ErrorDomain | None, int]]] = [- ("transient_is_runtime", InferenceErrorCategory.TRANSIENT, ErrorDomain.RUNTIME, 500),- ("configuration_is_config", InferenceErrorCategory.CONFIGURATION, ErrorDomain.CONFIG, 500),- ("content_is_input", InferenceErrorCategory.CONTENT, ErrorDomain.INPUT, 422),- ("capacity_is_runtime", InferenceErrorCategory.CAPACITY, ErrorDomain.RUNTIME, 500),- ("ambiguous_is_runtime", InferenceErrorCategory.AMBIGUOUS, ErrorDomain.RUNTIME, 500),- ("unknown_asserts_no_domain", InferenceErrorCategory.UNKNOWN, None, 500),+ # (topic, category, expected_code, expected_error_domain, expected_retryable)+ # What a failure built by hand with a category and no code reports. Exhaustive over InferenceErrorCategory — the+ # exhaustiveness itself is asserted by ``test_category_code_cases_cover_every_category``, so a new category cannot+ # be added without deciding what such a failure reports.+ CATEGORY_CODE_CASES: ClassVar[list[tuple[str, InferenceErrorCategory, ErrorCode, ErrorDomain, bool]]] = [+ ("transient_invites_a_retry", InferenceErrorCategory.TRANSIENT, CoreCode.PROVIDER_UNAVAILABLE, ErrorDomain.RUNTIME, True),+ ("configuration_is_the_operator_s", InferenceErrorCategory.CONFIGURATION, CoreCode.RUNTIME_MISCONFIGURED, ErrorDomain.CONFIG, False),+ ("content_keeps_the_fallback", InferenceErrorCategory.CONTENT, CoreCode.RUNTIME_UNEXPECTED, ErrorDomain.RUNTIME, False),+ ("capacity_is_the_quota", InferenceErrorCategory.CAPACITY, CoreCode.PROVIDER_QUOTA_EXHAUSTED, ErrorDomain.CONFIG, False),+ ("ambiguous_is_an_unknown_outcome", InferenceErrorCategory.AMBIGUOUS, CoreCode.PROVIDER_OUTCOME_UNKNOWN, ErrorDomain.RUNTIME, True),+ ("unknown_keeps_the_fallback", InferenceErrorCategory.UNKNOWN, CoreCode.RUNTIME_UNEXPECTED, ErrorDomain.RUNTIME, False),]diff --git a/tests/unit/pipelex/cogt/test_exceptions.py b/tests/unit/pipelex/cogt/test_exceptions.pyindex c7964ccf4..e96482345 100644--- a/tests/unit/pipelex/cogt/test_exceptions.py+++ b/tests/unit/pipelex/cogt/test_exceptions.py@@ -1,6 +1,7 @@import jsonimport pytest+from mthds.protocol.problem.registry import CoreCodefrom pydantic import ValidationErrorfrom pipelex.base_exceptions import ErrorReport, PipelexError@@ -133,42 +134,46 @@ class TestErrorCategoryInfrastructure:# --- to_error_report() ---def test_to_error_report_pipelex_error_minimal(self) -> None:- """PipelexError.to_error_report returns an ErrorReport with error_type and message."""+ """PipelexError.to_error_report returns an ErrorReport with error_type and message, and the fallback code's verdict."""err = PipelexError("basic error")report = err.to_error_report()assert report.error_type == "PipelexError"assert report.message == "basic error"+ assert report.code == CoreCode.RUNTIME_UNEXPECTEDassert report.error_category is None- assert report.retryable is None+ assert report.retryable is Falsedef test_to_error_report_cogt_error_no_category(self) -> None:- """CogtError report has None for optional fields when not set."""- err = CogtError("plain error")+ """A failure with no category and no cause reports its class's fallback code, and None for the optional fields."""+ err = LLMCompletionError("plain error")report = err.to_error_report()- assert report.error_type == "CogtError"+ assert report.error_type == "LLMCompletionError"assert report.message == "plain error"+ assert report.code == CoreCode.RUNTIME_UNEXPECTEDassert report.error_category is None- assert report.retryable is None+ assert report.retryable is Falseassert report.user_action is Noneassert report.model is Noneassert report.provider is Nonedef test_to_error_report_with_category(self) -> None:- """CogtError report includes category and retryable when set."""- err = CogtError("oops", error_category=InferenceErrorCategory.CONTENT)+ """A report includes the category, and a content failure with no code keeps its class's fallback."""+ err = LLMCompletionError("oops", error_category=InferenceErrorCategory.CONTENT)report = err.to_error_report()assert report.error_category == "content"+ assert report.code == CoreCode.RUNTIME_UNEXPECTEDassert report.retryable is Falsedef test_to_error_report_with_all_cogt_fields(self) -> None:- """Report includes user_action when set."""- err = CogtError(+ """Report includes user_action when set, and a transient failure with no code reports a code that invites a retry."""+ err = LLMCompletionError("oops",error_category=InferenceErrorCategory.TRANSIENT,user_action=UserAction(kind=UserActionKind.WAIT_AND_RETRY, detail="Retry in a moment"),)report = err.to_error_report()assert report.error_category == "transient"+ assert report.code == CoreCode.PROVIDER_UNAVAILABLEassert report.retryable is Trueassert report.user_action is not Noneassert report.user_action.kind is UserActionKind.WAIT_AND_RETRY@@ -195,18 +200,20 @@ class TestErrorCategoryInfrastructure:def test_to_error_report_to_dict_omits_none(self) -> None:"""to_dict() omits None-valued fields."""- err = CogtError("plain error")+ err = LLMCompletionError("plain error")report_dict = err.to_error_report().to_dict()assert "error_category" not in report_dict- assert "retryable" not in report_dictassert "user_action" not in report_dictassert "model" not in report_dictassert "provider" not in report_dictassert report_dict == {- "error_type": "CogtError",+ "code": "runtime.unexpected",+ "error_type": "LLMCompletionError","message": "plain error",- "title": "AI inference failed",- "type_uri": "https://docs.pipelex.com/latest/errors/cogt-error/",+ "title": "An unexpected error occurred",+ "type_uri": "https://mthds.ai/errors/runtime.unexpected",+ "error_domain": "runtime",+ "retryable": False,}def test_to_error_report_to_dict_json_serializable(self) -> None:@@ -219,12 +226,7 @@ class TestErrorCategoryInfrastructure:def test_error_report_is_frozen(self) -> None:"""ErrorReport is immutable."""- report = ErrorReport(- error_type="CogtError",- message="test",- title="AI inference failed",- type_uri="https://docs.pipelex.com/latest/errors/cogt-error/",- )+ report = ErrorReport.make_for_code(code=CoreCode.PROVIDER_FAILED, error_type="LLMCompletionError", message="test")with pytest.raises(ValidationError):report.message = "mutated" # type: ignore[misc]@@ -233,7 +235,7 @@ class TestErrorCategoryInfrastructure:original = ValueError("original error")msg = "wrapped"with pytest.raises(CogtError) as exc_info:- raise CogtError(msg, error_category=InferenceErrorCategory.TRANSIENT) from original+ raise LLMCompletionError(msg, error_category=InferenceErrorCategory.TRANSIENT) from originalassert exc_info.value.__cause__ is originalreport = exc_info.value.to_error_report()assert report.error_category == "transient"diff --git a/tests/unit/pipelex/cogt/test_inference_error_domain.py b/tests/unit/pipelex/cogt/test_inference_error_domain.pyindex 159ebf6a0..d7d4bf89a 100644--- a/tests/unit/pipelex/cogt/test_inference_error_domain.py+++ b/tests/unit/pipelex/cogt/test_inference_error_domain.py@@ -1,135 +1,108 @@-"""The `InferenceErrorCategory` -> `ErrorDomain` derivation on the `CogtError` family.+"""What an inference failure built with a category and no code reports.-An inference failure used to report no `error_domain` at all, so every one of them — a-content-policy refusal included — answered HTTP 500. The category the worker already-assigned is the authoritative statement of *whose fault it is*, so the domain is derived-from it rather than declared a second time on each of the several dozen leaf classes.+The classification picks a code with every category it reads, and a worker raising a failure itself chooses one. A+failure a worker or a plugin builds by hand with a category alone still reports a code, and its domain and retry+verdict are that code's: the category's own (``InferenceErrorCategory.default_error_code``), unless a code was chosen+or a cause carries one, so that a transient failure, which the run repeats, never reports a failure no retry clears."""import pytest+from mthds.protocol.problem.registry import CoreCodefrom pipelex.base_exceptions import ErrorDomain, PipelexError-from pipelex.cogt.exceptions import CogtError, InferenceErrorCategory, LLMCompletionError-from pipelex.cogt.inference.error_classification import ProviderErrorMetadata-from pipelex.cogt.inference.provider_name import ProviderName+from pipelex.cogt.exceptions import InferenceErrorCategory, LLMCompletionError+from pipelex.errors.error_code_declaration import InheritsCause+from pipelex.errors.error_codes import ErrorCode+from pipelex.pipe_run.located_failure import find_root_faultfrom tests.unit.pipelex.cogt.test_data import ExceptionTestData-class _ExplicitInputDomainError(CogtError):- """Test-only leaf that declares a domain of its own, against its category's grain."""+class _CodedCauseError(PipelexError):+ """Test-only cause carrying a code of its own."""- error_domain = ErrorDomain.INPUT- error_category = InferenceErrorCategory.CONFIGURATION+ error_code = CoreCode.INPUT_TOO_LARGE-class _InputDomainCauseError(PipelexError):- """Test-only non-Cogt cause carrying an INPUT domain, to exercise the cause fallback."""+class _WrapperError(PipelexError):+ """Test-only wrapper that takes its cause's code, as the pipe and run wrappers do."""- error_domain = ErrorDomain.INPUT+ error_code = InheritsCause(fallback=CoreCode.RUNTIME_UNEXPECTED)class TestInferenceErrorDomain:- """InferenceErrorCategory.error_domain, and how CogtError.to_error_report() derives from it."""-- # --- the mapping itself ----@pytest.mark.parametrize(- ("_topic", "category", "expected_domain", "_expected_status"),- ExceptionTestData.CATEGORY_DOMAIN_CASES,+ ("_topic", "category", "expected_code", "expected_domain", "expected_retryable"),+ ExceptionTestData.CATEGORY_CODE_CASES,)- def test_category_error_domain(+ def test_a_category_alone_reports_its_code(self,_topic: str,category: InferenceErrorCategory,- expected_domain: ErrorDomain | None,- _expected_status: int,+ expected_code: ErrorCode,+ expected_domain: ErrorDomain,+ expected_retryable: bool,) -> None:- """Each category maps to the domain that says who can fix that class of failure."""- assert category.error_domain is expected_domain+ """A failure naming only a category reports the category's code, and that code's domain and retry verdict."""+ report = LLMCompletionError("boom", error_category=category).to_error_report()- def test_category_domain_cases_cover_every_category(self) -> None:+ assert report.code == expected_code+ assert report.error_domain == expected_domain+ assert report.retryable is expected_retryable+ assert report.error_category == category++ def test_category_code_cases_cover_every_category(self) -> None:"""The parametrized table is exhaustive — a new category cannot slip in undecided."""- covered = {category for _topic, category, _domain, _status in ExceptionTestData.CATEGORY_DOMAIN_CASES}+ covered = {category for _topic, category, _code, _domain, _retryable in ExceptionTestData.CATEGORY_CODE_CASES}assert covered == set(InferenceErrorCategory)- def test_unknown_asserts_no_domain(self) -> None:- """UNKNOWN means classification failed, so it must not assert a domain it does not know."""- assert InferenceErrorCategory.UNKNOWN.error_domain is None-- # --- the derivation on the report ----- @pytest.mark.parametrize(- ("_topic", "category", "expected_domain", "expected_status"),- ExceptionTestData.CATEGORY_DOMAIN_CASES,- )- def test_report_derives_domain_from_category(- self,- _topic: str,- category: InferenceErrorCategory,- expected_domain: ErrorDomain | None,- expected_status: int,- ) -> None:- """A categorized CogtError reports the derived domain and the HTTP status it implies."""- report = LLMCompletionError("boom", error_category=category).to_error_report()- assert report.error_domain == expected_domain- assert report.http_status == expected_status-- def test_content_failure_is_now_a_422(self) -> None:- """The behavior change: a content-classified inference failure is the caller's to fix."""- report = LLMCompletionError("the prompt was refused", error_category=InferenceErrorCategory.CONTENT).to_error_report()- assert report.error_domain == ErrorDomain.INPUT- assert report.http_status == 422-- def test_uncategorized_cogt_error_still_has_no_domain(self) -> None:- """No category means nothing to derive from — the report stays unclassified, and 500."""- report = CogtError("plain error").to_error_report()- assert report.error_domain is None- assert report.http_status == 500-- def test_explicit_class_domain_beats_the_derivation(self) -> None:- """A leaf that declares its own domain keeps it, even when its category maps elsewhere."""- report = _ExplicitInputDomainError("declared its own domain").to_error_report()- assert report.error_category == InferenceErrorCategory.CONFIGURATION- assert report.error_domain == ErrorDomain.INPUT-- def test_uncategorized_cogt_error_still_inherits_the_cause_domain(self) -> None:- """With nothing of its own to derive from, the cause chain still supplies the domain."""- cogt_error = CogtError("wrapped")- cogt_error.__cause__ = _InputDomainCauseError("the caller's fault")- report = cogt_error.to_error_report()- assert report.error_domain == ErrorDomain.INPUT-- def test_own_category_beats_the_cause_domain(self) -> None:- """Wrapper-wins: the outer error's own category decides, as it already does for the category."""- cogt_error = CogtError("wrapped", error_category=InferenceErrorCategory.CONFIGURATION)- cogt_error.__cause__ = _InputDomainCauseError("the caller's fault")- report = cogt_error.to_error_report()- assert report.error_domain == ErrorDomain.CONFIG-- def test_provider_429_still_wins_over_the_derived_domain(self) -> None:- """The rate-limit passthrough is checked before the domain, so CAPACITY -> RUNTIME cannot mask it."""- report = LLMCompletionError(- "rate limited",- error_category=InferenceErrorCategory.CAPACITY,- provider_metadata=ProviderErrorMetadata(provider=ProviderName.OPENAI, sdk_exception_type="RateLimitError", status_code=429),- ).to_error_report()- assert report.error_domain == ErrorDomain.RUNTIME- assert report.http_status == 429-- # --- the invariant that keeps the two fields from disagreeing on the wire ----- @pytest.mark.parametrize(- ("_topic", "category", "_expected_domain", "_expected_status"),- ExceptionTestData.CATEGORY_DOMAIN_CASES,- )- def test_domain_and_category_never_disagree(- self,- _topic: str,- category: InferenceErrorCategory,- _expected_domain: ErrorDomain | None,- _expected_status: int,- ) -> None:- """For any CogtError with a category and no declared domain, the two report fields agree."""- report = LLMCompletionError("boom", error_category=category).to_error_report()- assert report.error_category is not None- assert report.error_domain == InferenceErrorCategory(report.error_category).error_domain+ def test_a_retryable_category_never_reports_a_code_no_retry_clears(self) -> None:+ """The run repeats a call whose category is retryable, so the report of one built with no code must invite a retry too."""+ for category in InferenceErrorCategory:+ report = LLMCompletionError("boom", error_category=category).to_error_report()+ if category.is_retryable:+ assert report.retryable is True, category++ def test_a_chosen_code_beats_the_category(self) -> None:+ """The raise site that chose a code knows more than the category."""+ error = LLMCompletionError("rate limited", error_category=InferenceErrorCategory.TRANSIENT).with_error_code(CoreCode.PROVIDER_RATE_LIMITED)++ assert error.resolve_error_code() == CoreCode.PROVIDER_RATE_LIMITED++ def test_a_coded_cause_beats_the_category(self) -> None:+ """A failure class takes its cause's code, and the category is only for a failure whose chain carries none."""+ error = LLMCompletionError("wrapped", error_category=InferenceErrorCategory.TRANSIENT)+ error.__cause__ = _CodedCauseError("too large")++ assert error.resolve_error_code() == CoreCode.INPUT_TOO_LARGE++ def test_a_cause_that_is_no_pipelex_error_leaves_the_category_its_say(self) -> None:+ """An SDK exception under the failure carries no code, so the category still names one."""+ error = LLMCompletionError("connection reset", error_category=InferenceErrorCategory.TRANSIENT)+ error.__cause__ = ConnectionResetError("reset by peer")++ assert error.resolve_error_code() == CoreCode.PROVIDER_UNAVAILABLE++ def test_a_wrapper_reports_the_category_s_code(self) -> None:+ """The pipe and run wrappers take their cause's code, so a transient failure stays retryable through them."""+ failure = LLMCompletionError("connection reset", error_category=InferenceErrorCategory.TRANSIENT)+ wrapper = _WrapperError("Pipe 'greet' failed")+ wrapper.__cause__ = failure++ report = wrapper.to_error_report()++ assert report.code == CoreCode.PROVIDER_UNAVAILABLE+ assert report.retryable is True++ def test_a_cyclic_pair_of_category_failures_reports_without_recursing(self) -> None:+ """Two failures chained to each other report the category's code, under a wrapper too, where the walk of each recursed."""+ outer = LLMCompletionError("connection reset", error_category=InferenceErrorCategory.TRANSIENT)+ inner = LLMCompletionError("connection reset again", error_category=InferenceErrorCategory.TRANSIENT)+ outer.__cause__ = inner+ inner.__cause__ = outer+ wrapper = _WrapperError("Pipe 'greet' failed")+ wrapper.__cause__ = outer++ assert outer.resolve_error_code() == CoreCode.PROVIDER_UNAVAILABLE+ assert outer.to_error_report().code == CoreCode.PROVIDER_UNAVAILABLE+ assert wrapper.to_error_report().code == CoreCode.PROVIDER_UNAVAILABLE+ assert find_root_fault(error=wrapper) is innerdiff --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 c033d5dc0..a76feabb2 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,26 @@import pytest+from mthds.protocol.problem.registry import CoreCodefrom pipelex.base_exceptions import DisclosureMode, ErrorDomain, PipelexErrorfrom pipelex.core.bundle_resources.exceptions import BundleResourceNotNamedError, BundleResourcePathError+from pipelex.errors.error_codes import ErrorCodeclass TestBundleResourceExceptions:- @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:+ @pytest.mark.parametrize(+ ("error_class", "expected_code"),+ [+ (BundleResourceNotNamedError, CoreCode.REQUEST_INVALID),+ (BundleResourcePathError, CoreCode.SECURITY_INPUT_PATH_REFUSED),+ ],+ )+ def test_a_refusal_of_the_files_sent_says_running_it_again_cannot_succeed(+ self, error_class: type[PipelexError], expected_code: ErrorCode+ ) -> None:"""Deterministic refusals of what the caller sent, so their problem documents carry `retryable: false`."""report = error_class("The files sent are refused.").to_error_report()+ assert report.code == expected_codeassert report.retryable is Falseassert report.error_domain == ErrorDomain.INPUTassert report.caller_facing_message is True@@ -30,8 +41,10 @@ class TestBundleResourceExceptions:assert report.error_type == "PipelexError"assert report.retryable is False- def test_an_error_that_declares_nothing_carries_no_retryable(self) -> None:- report = PipelexError("Something failed.").to_error_report()+ def test_two_paths_naming_one_file_are_an_invalid_request(self) -> None:+ """A raise site that refuses paths that cannot make one tree chooses the request's code, not the path refusal's."""+ report = BundleResourcePathError("Two files name one file.").with_error_code(CoreCode.REQUEST_INVALID).to_error_report()- assert report.retryable is None- assert "retryable" not in report.to_dict()+ assert report.code == CoreCode.REQUEST_INVALID+ assert report.error_domain == ErrorDomain.INPUT+ assert report.retryable is Falsediff --git a/tests/unit/pipelex/core/concepts/helpers/test_get_structure_class_name_from_blueprint.py b/tests/unit/pipelex/core/concepts/helpers/test_get_structure_class_name_from_blueprint.pyindex 04b1e09f0..ca15d6850 100644--- a/tests/unit/pipelex/core/concepts/helpers/test_get_structure_class_name_from_blueprint.py+++ b/tests/unit/pipelex/core/concepts/helpers/test_get_structure_class_name_from_blueprint.py@@ -3,6 +3,7 @@import pytestfrom pipelex.core.concepts.concept_blueprint import ConceptBlueprint+from pipelex.core.concepts.exceptions import ConceptStringErrorfrom pipelex.core.concepts.helpers import get_structure_class_name_from_blueprint@@ -84,8 +85,8 @@ class TestGetStructureClassNameFromBlueprint:assert result == "MyConceptName"def test_invalid_concept_ref_or_code_raises_error(self):- """Invalid concept_ref_or_code raises ValueError."""- with pytest.raises(ValueError, match="Invalid concept_ref_or_code"):+ """Invalid concept_ref_or_code raises ConceptStringError."""+ with pytest.raises(ConceptStringError, match="Invalid concept_ref_or_code"):get_structure_class_name_from_blueprint(blueprint_or_string_description="A description",concept_ref_or_code="invalid_lowercase_code",@@ -100,8 +101,8 @@ class TestGetStructureClassNameFromBlueprint:assert result == "ConceptName"def test_empty_string_raises_error(self):- """Empty string raises ValueError."""- with pytest.raises(ValueError, match="Invalid concept_ref_or_code"):+ """Empty string raises ConceptStringError."""+ with pytest.raises(ConceptStringError, match="Invalid concept_ref_or_code"):get_structure_class_name_from_blueprint(blueprint_or_string_description="A description",concept_ref_or_code="",diff --git a/tests/unit/pipelex/core/memory/input_shaper/test_fallback_refusal.py b/tests/unit/pipelex/core/memory/input_shaper/test_fallback_refusal.pyindex 4499f4fa0..cc9dec048 100644--- a/tests/unit/pipelex/core/memory/input_shaper/test_fallback_refusal.py+++ b/tests/unit/pipelex/core/memory/input_shaper/test_fallback_refusal.py@@ -46,7 +46,7 @@ class TestInputShaperFallbackRefusal:# the chain as the cause and out of what a caller reads.assert "typing.Union" not in messageassert isinstance(error.__cause__, StuffFactoryError)- assert error.error_domain == ErrorDomain.INPUT+ assert error.to_error_report().error_domain == ErrorDomain.INPUT# The fix is on the author's side: the declaration, and no envelope.assert error.user_action is not Noneassert error.user_action.kind == UserActionKind.CHANGE_INPUTdiff --git a/tests/unit/pipelex/core/stuffs/test_structured_content_render_with_images.py b/tests/unit/pipelex/core/stuffs/test_structured_content_render_with_images.pyindex b54cee15e..784a8c7ac 100644--- a/tests/unit/pipelex/core/stuffs/test_structured_content_render_with_images.py+++ b/tests/unit/pipelex/core/stuffs/test_structured_content_render_with_images.py@@ -14,6 +14,7 @@ from pipelex.core.stuffs.stuff_factory import StuffFactoryfrom pipelex.core.stuffs.text_and_images_content import TextAndImagesContentfrom pipelex.core.stuffs.text_content import TextContentfrom pipelex.interpreter_hub import get_native_concept+from pipelex.tools.jinja2.exceptions import Jinja2ContextErrorfrom pipelex.tools.jinja2.image_registry import ImageRegistryfrom pipelex.tools.templating.text_format import TextFormatfrom pipelex.urls import URLs@@ -185,8 +186,8 @@ class TestStructuredContentRenderWithImages:class TestStuffArtefactWithImagesFailFast:"""Tests for fail-fast behavior when | with_images is used on non-image content."""- def test_text_content_raises_type_error_via_artefact(self, load_test_library: Callable[[list[Path]], None]) -> None:- """Test that TextContent wrapped in StuffArtefact raises TypeError."""+ def test_text_content_raises_context_error_via_artefact(self, load_test_library: Callable[[list[Path]], None]) -> None:+ """Test that TextContent wrapped in StuffArtefact raises Jinja2ContextError, which the render reports."""load_test_library([Path("tests/integration/pipelex/pipes/pipelines")])stuff = StuffFactory.make_stuff(@@ -197,5 +198,5 @@ class TestStuffArtefactWithImagesFailFast:artefact = StuffArtefact(stuff)registry = ImageRegistry()- with pytest.raises(TypeError, match="does not implement ImageRenderable"):+ with pytest.raises(Jinja2ContextError, match="does not implement ImageRenderable"):artefact.render_with_images(registry=registry, text_format=TextFormat.PLAIN)diff --git a/tests/unit/pipelex/core/test_qualified_ref.py b/tests/unit/pipelex/core/test_qualified_ref.pyindex 42f0e7728..fde46b975 100644--- a/tests/unit/pipelex/core/test_qualified_ref.py+++ b/tests/unit/pipelex/core/test_qualified_ref.py@@ -1,7 +1,8 @@import pytestfrom pydantic import ValidationError-from pipelex.core.qualified_ref import QualifiedRef, QualifiedRefError+from pipelex.core.qualified_ref import QualifiedRef+from pipelex.core.qualified_ref_exceptions import QualifiedRefErrorclass TestQualifiedRef:diff --git a/tests/unit/pipelex/errors/test_error_code_gate.py b/tests/unit/pipelex/errors/test_error_code_gate.pynew file mode 100644index 000000000..ec3f9aaa0--- /dev/null+++ b/tests/unit/pipelex/errors/test_error_code_gate.py@@ -0,0 +1,126 @@+"""The error-code gate: every ``PipelexError`` subclass declares its registry code, and every raise site agrees.++The code an error carries decides its title, its documentation page, who must act and whether a retry can+succeed, so a class without one would report the catch-all ``runtime.unexpected`` for a fault that has a+precise reading. These tests fail the build on:++- a subclass that declares no ``error_code`` in its own body, whatever its parents declare;+- a subclass that still declares what its code now decides (a domain, a retry verdict, a title, a page);+- a ``raise`` that constructs an abstract base directly;+- a raise site that chooses, with ``with_error_code``, a code its class does not declare.++The set of classes comes from ``iter_pipelex_error_subclasses()``, which force-loads every error module; the+raise sites are read from the source of the package and of the runner, ``api/pipelex_api``.+"""++from __future__ import annotations++from pathlib import Path+from typing import TYPE_CHECKING++from mthds.protocol.problem.registry import CoreCode++import pipelex+from pipelex.errors.error_class_discovery import iter_pipelex_error_subclasses+from pipelex.errors.error_code_declaration import AbstractError, declared_error_codes, describe_error_code_declaration+from pipelex.errors.error_code_sites import iter_chosen_code_sites, iter_raised_class_sites+from pipelex.errors.error_codes import ErrorCode, error_code_spec+from pipelex.errors.registry.pipelex_codes import PipelexErrorCode++if TYPE_CHECKING:+ from pipelex.base_exceptions import PipelexError++_PACKAGE_ROOT: Path = Path(pipelex.__file__).resolve().parent+_REPO_ROOT: Path = _PACKAGE_ROOT.parent+_SOURCE_ROOTS: tuple[Path, ...] = (_PACKAGE_ROOT, _REPO_ROOT / "api" / "pipelex_api")++# What a code decides, which a class no longer declares: ``ErrorReport`` reads all four from the code.+_ATTRIBUTES_THE_CODE_DECIDES: tuple[str, ...] = ("error_domain", "retryable", "_declared_title", "_declared_type_uri")+++def _error_classes_by_name() -> dict[str, type[PipelexError]]:+ return {cls.__name__: cls for cls in iter_pipelex_error_subclasses()}+++def _source_files() -> list[Path]:+ files: list[Path] = []+ for root in _SOURCE_ROOTS:+ files.extend(path for path in sorted(root.rglob("*.py")) if "__pycache__" not in path.parts)+ return files+++def _relative(path: Path) -> str:+ return str(path.relative_to(_REPO_ROOT))+++class TestErrorCodeGate:+ def test_the_gate_reads_a_non_empty_set(self) -> None:+ """Anti-vacuity: the discovery found the error classes and the source files."""+ classes = _error_classes_by_name()+ assert "PipelexError" in classes+ assert len(classes) > 1+ assert _source_files()++ def test_every_error_class_declares_its_code(self) -> None:+ missing = sorted(f"{cls.__module__}.{cls.__qualname__}" for cls in iter_pipelex_error_subclasses() if "error_code" not in cls.__dict__)+ if missing:+ lines = [+ "These PipelexError subclasses declare no `error_code` in their own class body:",+ "",+ *(f" - {name}" for name in missing),+ "",+ "Declare the registry code the class raises, an ErrorCodeSet its raise sites choose from, InheritsCause",+ "with a fallback for a wrapper that adds no fact deciding the code, or ABSTRACT_ERROR for a base that is",+ "never raised directly (pipelex/errors/error_code_declaration.py). A code the registry lacks is added to",+ "pipelex/errors/registry/pipelex-error-registry.yaml first.",+ ]+ raise AssertionError("\n".join(lines))++ def test_every_declared_code_is_registered(self) -> None:+ for cls in iter_pipelex_error_subclasses():+ for code in declared_error_codes(cls.error_code):+ assert isinstance(code, (CoreCode, PipelexErrorCode)), f"{cls.__name__} declares {code!r}, which is no registered code"+ assert error_code_spec(code).code == code++ def test_no_error_class_declares_what_its_code_decides(self) -> None:+ offenders = sorted(+ f"{cls.__module__}.{cls.__qualname__}.{attribute}"+ for cls in iter_pipelex_error_subclasses()+ for attribute in _ATTRIBUTES_THE_CODE_DECIDES+ if attribute in cls.__dict__+ )+ assert not offenders, "These classes declare what their code decides; remove the attribute and choose the code instead:\n" + "\n".join(+ f" - {offender}" for offender in offenders+ )++ def test_no_abstract_class_is_raised_directly(self) -> None:+ classes = _error_classes_by_name()+ abstract_names = {name for name, cls in classes.items() if isinstance(cls.__dict__.get("error_code"), AbstractError)}+ offenders: list[str] = []+ for path in _source_files():+ for site in iter_raised_class_sites(path=path, source=path.read_text(encoding="utf-8")):+ if site.class_name in abstract_names:+ offenders.append(f" - {_relative(site.path)}:{site.line} raises {site.class_name}")+ assert not offenders, (+ "These raise sites construct an abstract base, which reports no code of its own; raise the subclass that "+ "names the fault, or give the class a code:\n" + "\n".join(offenders)+ )++ def test_every_chosen_code_is_one_its_class_declares(self) -> None:+ classes = _error_classes_by_name()+ offenders: list[str] = []+ for path in _source_files():+ for site in iter_chosen_code_sites(path=path, source=path.read_text(encoding="utf-8")):+ cls = classes.get(site.class_name)+ if cls is None:+ continue+ enum_class = CoreCode if site.enum_name == "CoreCode" else PipelexErrorCode+ chosen: ErrorCode | None = getattr(enum_class, site.member_name, None)+ where = f"{_relative(site.path)}:{site.line}"+ if chosen is None:+ offenders.append(f" - {where}: {site.enum_name}.{site.member_name} is no registered code")+ continue+ if chosen not in declared_error_codes(cls.error_code):+ declared = describe_error_code_declaration(cls.error_code)+ offenders.append(f" - {where}: {site.class_name} chooses {chosen}, but declares {declared}")+ assert not offenders, "These raise sites choose a code their class does not declare:\n" + "\n".join(offenders)diff --git a/tests/unit/pipelex/errors/test_error_code_resolution.py b/tests/unit/pipelex/errors/test_error_code_resolution.pynew file mode 100644index 000000000..10c845126--- /dev/null+++ b/tests/unit/pipelex/errors/test_error_code_resolution.py@@ -0,0 +1,136 @@+"""How a ``PipelexError`` resolves the registry code its report carries, and what the code decides on the report."""++import itertools+import re++import pytest+from mthds.protocol.problem.registry import CORE_CODE_SPECS, CoreCode++from pipelex.base_exceptions import ErrorDomain, ErrorReport, PipelexConfigError, PipelexError, PipelexUnexpectedError+from pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeSet, InheritsCause+from pipelex.errors.error_codes import error_code_spec, parse_error_code+from pipelex.errors.registry.pipelex_codes import PipelexErrorCode+++class _ModelUnknownError(PipelexError):+ error_code = CoreCode.MODEL_UNKNOWN+++class _FunctionRaisedError(PipelexError):+ error_code = CoreCode.PIPE_FUNCTION_RAISED+++class _WrapperError(PipelexError):+ error_code = InheritsCause(fallback=CoreCode.RUNTIME_UNEXPECTED, others=(CoreCode.PIPE_INPUT_UNRESOLVED,))+++class _InputWrapperError(PipelexError):+ error_code = InheritsCause(fallback=CoreCode.INPUT_INVALID)+++class _ProviderError(PipelexError):+ error_code = ErrorCodeSet(default=CoreCode.PROVIDER_FAILED, others=(CoreCode.PROVIDER_RATE_LIMITED, CoreCode.PROVIDER_UNAVAILABLE))+++class _AbstractBaseError(PipelexError):+ error_code = ABSTRACT_ERROR+++def _raise_chain(*errors: BaseException) -> BaseException:+ """Chain ``errors`` outermost first, each raised from the next, and return the outermost."""+ for outer, inner in itertools.pairwise(errors):+ outer.__cause__ = inner+ return errors[0]+++class TestErrorCodeResolution:+ def test_a_class_code_decides_the_report(self) -> None:+ report = _ModelUnknownError("no such model").to_error_report()+ spec = CORE_CODE_SPECS[CoreCode.MODEL_UNKNOWN]+ assert report.code == CoreCode.MODEL_UNKNOWN+ assert report.title == spec.title+ assert report.type_uri == f"https://mthds.ai/errors/{CoreCode.MODEL_UNKNOWN}"+ assert report.error_domain == ErrorDomain.INPUT+ assert report.retryable is False++ def test_a_pipelex_code_points_at_the_pipelex_docs(self) -> None:+ report = PipelexConfigError("bad config").to_error_report()+ assert report.code == PipelexErrorCode.CONFIG_INVALID+ assert report.type_uri == f"https://docs.pipelex.com/errors/{PipelexErrorCode.CONFIG_INVALID}"+ assert report.title == error_code_spec(PipelexErrorCode.CONFIG_INVALID).title+ assert report.error_domain == ErrorDomain.CONFIG++ def test_a_raise_site_chooses_from_the_set(self) -> None:+ assert _ProviderError("boom").to_error_report().code == CoreCode.PROVIDER_FAILED+ chosen = _ProviderError("slow down").with_error_code(CoreCode.PROVIDER_RATE_LIMITED).to_error_report()+ assert chosen.code == CoreCode.PROVIDER_RATE_LIMITED+ assert chosen.retryable is True++ def test_a_raise_site_cannot_choose_a_code_its_class_does_not_declare(self) -> None:+ with pytest.raises(ValueError, match=re.escape("does not declare the code 'model.unknown'")):+ _ProviderError("boom").with_error_code(CoreCode.MODEL_UNKNOWN)++ def test_an_inheriting_wrapper_takes_its_cause_code(self) -> None:+ error = _raise_chain(_WrapperError("outer"), _ModelUnknownError("inner"))+ assert isinstance(error, PipelexError)+ report = error.to_error_report()+ assert report.code == CoreCode.MODEL_UNKNOWN+ assert report.error_type == "_WrapperError"+ assert report.message == "outer"++ def test_the_walk_stops_at_the_first_class_that_declares_a_code(self) -> None:+ error = _raise_chain(_WrapperError("outer"), _FunctionRaisedError("the function raised"), _ModelUnknownError("inside the function"))+ assert isinstance(error, PipelexError)+ assert error.resolve_error_code() == CoreCode.PIPE_FUNCTION_RAISED++ def test_a_chosen_code_stops_the_walk_at_an_inheriting_wrapper(self) -> None:+ error = _raise_chain(_WrapperError("outer").with_error_code(CoreCode.PIPE_INPUT_UNRESOLVED), _ModelUnknownError("inner"))+ assert isinstance(error, PipelexError)+ assert error.resolve_error_code() == CoreCode.PIPE_INPUT_UNRESOLVED++ def test_a_foreign_cause_gives_the_deepest_fallback(self) -> None:+ error = _raise_chain(_WrapperError("outer"), _InputWrapperError("inner"), KeyError("raw"))+ assert isinstance(error, PipelexError)+ assert error.resolve_error_code() == CoreCode.INPUT_INVALID++ def test_no_code_anywhere_is_the_catch_all(self) -> None:+ assert _AbstractBaseError("raised by mistake").resolve_error_code() == CoreCode.RUNTIME_UNEXPECTED+ assert PipelexError("bare root").to_error_report().code == CoreCode.RUNTIME_UNEXPECTED++ def test_an_abstract_wrapper_keeps_walking(self) -> None:+ error = _raise_chain(_AbstractBaseError("outer"), _ModelUnknownError("inner"))+ assert isinstance(error, PipelexError)+ assert error.resolve_error_code() == CoreCode.MODEL_UNKNOWN++ def test_a_cyclic_cause_chain_terminates(self) -> None:+ outer = _WrapperError("outer")+ inner = _InputWrapperError("inner")+ outer.__cause__ = inner+ inner.__cause__ = outer+ assert outer.resolve_error_code() == CoreCode.INPUT_INVALID++ def test_the_caller_fault_flag_does_not_change_the_domain(self) -> None:+ report = PipelexUnexpectedError("ours").as_caller_fault().to_error_report()+ assert report.caller_facing_message is True+ assert report.error_domain == ErrorDomain.RUNTIME++ def test_a_declaration_of_the_wrong_type_refuses_the_class(self) -> None:+ with pytest.raises(TypeError, match="error_code must be"):+ type("_StringCodeError", (PipelexError,), {"error_code": "model.unknown"})++ def test_round_trip_preserves_the_code(self) -> None:+ report = PipelexConfigError("config gone").with_error_code(PipelexErrorCode.CONFIG_SYNTAX).to_error_report()+ recovered = ErrorReport.from_dict(report.to_dict())+ assert recovered.code == PipelexErrorCode.CONFIG_SYNTAX+ assert recovered == report+++class TestParseErrorCode:+ def test_a_core_code(self) -> None:+ assert parse_error_code("model.unknown") == CoreCode.MODEL_UNKNOWN++ def test_a_pipelex_code(self) -> None:+ assert parse_error_code("pipelex.config.invalid") == PipelexErrorCode.CONFIG_INVALID++ def test_an_unregistered_string(self) -> None:+ assert parse_error_code("not.a.code") is Nonediff --git a/tests/unit/pipelex/errors/test_error_identity_snapshot.py b/tests/unit/pipelex/errors/test_error_identity_snapshot.pyindex d697746f0..1f8583218 100644--- a/tests/unit/pipelex/errors/test_error_identity_snapshot.py+++ b/tests/unit/pipelex/errors/test_error_identity_snapshot.py@@ -1,4 +1,4 @@-"""Gate on the committed ``(error_type, title, type_uri)`` snapshot.+"""Gate on the committed ``(error_type, code declaration)`` snapshot.``error_type`` is the Python class name with no indirection, and consumersoutside this repo branch on that string, so renaming an error class breaks them@@ -49,7 +49,7 @@ class TestErrorIdentitySnapshot:"",*(f" - {row.error_type}: {row!r}" for row in offenders),"",- "Rename the class or curate a _declared_title without the separator.",+ "Rename the class.",]raise AssertionError("\n".join(lines))@@ -75,9 +75,10 @@ class TestErrorIdentitySnapshot:lines = ["The committed error-identity snapshot is out of date.","",- "A diff on `error_type` is a WIRE BREAK: consumers outside this repo switch on that",- "string and fall through silently when it changes. Confirm the rename is intended and",- "that the consumers are updated in the cross-repo sweep, then run `make gei`.",+ "A diff on `error_type` or on a code declaration is a WIRE CHANGE: consumers outside this",+ "repo switch on the class name and on the code, and fall through silently when either changes.",+ "Confirm the change is intended and that the consumers are updated in the cross-repo sweep,",+ "then run `make gei`.","",*(line.rstrip("\n") for line in diff),]diff --git a/tests/unit/pipelex/errors/test_foreign_raises.py b/tests/unit/pipelex/errors/test_foreign_raises.pynew file mode 100644index 000000000..887191edb--- /dev/null+++ b/tests/unit/pipelex/errors/test_foreign_raises.py@@ -0,0 +1,120 @@+"""The foreign-raise check: our own code raises no class outside the ``PipelexError`` root that a reader can see.++``pipelex/errors/foreign_raises.py`` scans the package and the runner, ``api/pipelex_api``, and allows by their+shape the raises that are right: inside pydantic validators, abstract methods, data-model dunders, the framework+carriers and the developer tooling. Every other foreign raise is listed, with its disposition, in+``tests/data/errors/foreign_raises.txt``. This test fails on a foreign raise the file does not list, which is+a new raise to code under the root (or, when it is a genuine invariant or carrier, to list with its+disposition), and on a listed one that is gone, so the file never keeps a stale line.+"""++from __future__ import annotations++from collections import Counter+from pathlib import Path++import pipelex+from pipelex.errors.foreign_raises import ForeignRaiseSite, collect_root_error_class_names, is_exempt_path, iter_foreign_raise_sites++_PACKAGE_ROOT: Path = Path(pipelex.__file__).resolve().parent+_REPO_ROOT: Path = _PACKAGE_ROOT.parent+_SOURCE_ROOTS: tuple[Path, ...] = (_PACKAGE_ROOT, _REPO_ROOT / "api" / "pipelex_api")+_BASELINE_FILE: Path = _REPO_ROOT / "tests" / "data" / "errors" / "foreign_raises.txt"+_SEPARATOR = " | "++# Why a listed foreign raise is right.+_DISPOSITIONS: frozenset[str] = frozenset(+ {+ # A builtin raised only on a bug of ours, which a boundary reports as runtime.unexpected.+ "invariant",+ # A builtin raised in a helper only pydantic validators call, which pydantic wraps.+ "validator",+ # A private class caught in the module that defines it, which no reader sees.+ "private",+ # A class a library expects by type that the scan cannot recognise by its name alone.+ "carrier",+ # Developer or release code outside the exempt directories, which only the development CLI calls.+ "tooling",+ # A builtin raised in a module that must import nothing of Pipelex, which its every caller catches by type.+ "caught",+ }+)+++def _sources() -> list[tuple[Path, str]]:+ sources: list[tuple[Path, str]] = []+ for root in _SOURCE_ROOTS:+ for path in sorted(root.rglob("*.py")):+ if "__pycache__" in path.parts:+ continue+ sources.append((path, path.read_text(encoding="utf-8")))+ return sources+++def _live_sites() -> list[ForeignRaiseSite]:+ sources = _sources()+ root_names = collect_root_error_class_names(sources=sources)+ sites: list[ForeignRaiseSite] = []+ for path, source in sources:+ relative = path.relative_to(_REPO_ROOT)+ if is_exempt_path(relative_parts=relative.parts):+ continue+ sites.extend(iter_foreign_raise_sites(path=str(relative), source=source, root_names=root_names))+ return sites+++def _baseline() -> list[tuple[str, str, str, str]]:+ rows: list[tuple[str, str, str, str]] = []+ for raw_line in _BASELINE_FILE.read_text(encoding="utf-8").splitlines():+ if not raw_line.strip() or raw_line.startswith("#"):+ continue+ fields = raw_line.split(_SEPARATOR)+ assert len(fields) == 4, f"A line of {_BASELINE_FILE.name} has {len(fields)} fields, not 4: {raw_line!r}"+ path, function, exception, disposition = fields+ rows.append((path, function, exception, disposition))+ return rows+++class TestForeignRaises:+ def test_the_scan_reads_the_sources(self) -> None:+ """Anti-vacuity: the scan read the package and found the root's family."""+ sources = _sources()+ assert sources+ root_names = collect_root_error_class_names(sources=sources)+ assert {"PipelexError", "PipelexUnexpectedError", "CogtError"} <= root_names++ def test_every_listed_disposition_is_known(self) -> None:+ unknown = sorted({row[3] for row in _baseline()} - _DISPOSITIONS)+ assert not unknown, f"{_BASELINE_FILE.name} uses dispositions this check does not know: {unknown}; use one of {sorted(_DISPOSITIONS)}"++ def test_every_foreign_raise_is_listed_and_every_listed_one_exists(self) -> None:+ live = Counter(site.key for site in _live_sites())+ listed = Counter((path, function, exception) for path, function, exception, _disposition in _baseline())+ unlisted = live - listed+ stale = listed - live+ lines: list[str] = []+ if unlisted:+ where = {site.key: site.line for site in _live_sites()}+ lines.extend(+ [+ "These raises construct a class outside the PipelexError root and are not listed:",+ "",+ *(+ f" - {path}:{where[path, function, exception]} ({function}) raises {exception}"+ for path, function, exception in sorted(unlisted)+ ),+ "",+ "A reader that sees one gets no code: raise a coded PipelexError subclass instead. When the raise is",+ f"right as it is, list it in tests/data/errors/foreign_raises.txt with one of {sorted(_DISPOSITIONS)}.",+ ]+ )+ if stale:+ lines.extend(+ [+ "",+ "These listed foreign raises are gone; remove their lines from tests/data/errors/foreign_raises.txt:",+ "",+ *(f" - {_SEPARATOR.join(key)}" for key in sorted(stale)),+ ]+ )+ assert not lines, "\n".join(lines)diff --git a/tests/unit/pipelex/errors/test_retired_error_page_redirects.py b/tests/unit/pipelex/errors/test_retired_error_page_redirects.pynew file mode 100644index 000000000..c31c14629--- /dev/null+++ b/tests/unit/pipelex/errors/test_retired_error_page_redirects.py@@ -0,0 +1,76 @@+"""The static redirects of the retired per-class error pages follow each class's code."""++from __future__ import annotations++from difflib import unified_diff+from pathlib import Path++from mthds.protocol.problem.registry import CoreCode++import pipelex+from pipelex.base_exceptions import PipelexError+from pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeSet, InheritsCause+from pipelex.errors.registry.pipelex_codes import PipelexErrorCode+from pipelex.errors.retired_error_pages import ERROR_CODES_INDEX_PAGE, render_retired_error_page_redirects, retired_page_names, retired_page_target++_REPO_ROOT: Path = Path(pipelex.__file__).resolve().parent.parent+_MKDOCS_FILE: Path = _REPO_ROOT / "mkdocs.yml"+++class _CoreCodedError(PipelexError):+ error_code = CoreCode.MODEL_UNKNOWN+++class _PipelexCodedSetError(PipelexError):+ error_code = ErrorCodeSet(default=PipelexErrorCode.CONFIG_SYNTAX, others=(PipelexErrorCode.CONFIG_INVALID,))+++class _WrapperError(PipelexError):+ error_code = InheritsCause(fallback=CoreCode.PIPE_INPUT_UNRESOLVED)+++class _BaseError(PipelexError):+ error_code = ABSTRACT_ERROR+++class TestRetiredErrorPageRedirects:+ def test_the_block_records_the_retired_pages(self) -> None:+ names = retired_page_names(mkdocs_text=_MKDOCS_FILE.read_text(encoding="utf-8"))+ assert "pipelex-config-error" in names+ assert len(names) == len(set(names)), "A retired page is listed twice"++ def test_targets_follow_the_class_code(self) -> None:+ classes_by_kebab: dict[str, type[PipelexError]] = {+ "core-coded-error": _CoreCodedError,+ "pipelex-coded-set-error": _PipelexCodedSetError,+ "wrapper-error": _WrapperError,+ "base-error": _BaseError,+ }+ assert retired_page_target(kebab_name="core-coded-error", classes_by_kebab=classes_by_kebab) == "https://mthds.ai/errors/model.unknown"+ assert retired_page_target(kebab_name="pipelex-coded-set-error", classes_by_kebab=classes_by_kebab) == "errors/pipelex/config/syntax.md"+ assert retired_page_target(kebab_name="wrapper-error", classes_by_kebab=classes_by_kebab) == "https://mthds.ai/errors/pipe.input_unresolved"+ assert retired_page_target(kebab_name="base-error", classes_by_kebab=classes_by_kebab) == ERROR_CODES_INDEX_PAGE+ assert retired_page_target(kebab_name="gone-error", classes_by_kebab=classes_by_kebab) == ERROR_CODES_INDEX_PAGE++ def test_every_pipelex_target_is_a_generated_page(self) -> None:+ for line in _MKDOCS_FILE.read_text(encoding="utf-8").splitlines():+ stripped = line.strip()+ if not stripped.startswith("'errors/") or "': 'errors/" not in stripped:+ continue+ target = stripped.split("': '")[1].rstrip("'")+ assert (_REPO_ROOT / "docs" / target).is_file(), f"The redirect {stripped} names a page that does not exist"++ def test_committed_redirects_match_the_classes(self) -> None:+ existing = _MKDOCS_FILE.read_text(encoding="utf-8")+ expected = render_retired_error_page_redirects(mkdocs_text=existing)+ if existing == expected:+ return+ diff = unified_diff(+ existing.splitlines(), expected.splitlines(), fromfile="mkdocs.yml (on disk)", tofile="rendered from the classes", lineterm=""+ )+ lines = [+ "The redirects of the retired error class pages in mkdocs.yml do not follow the classes' codes; run `make gei`.",+ "",+ *diff,+ ]+ raise AssertionError("\n".join(lines))diff --git a/tests/unit/pipelex/exceptions/test_as_caller_fault.py b/tests/unit/pipelex/exceptions/test_as_caller_fault.pyindex f03be6140..b7e92c9f4 100644--- a/tests/unit/pipelex/exceptions/test_as_caller_fault.py+++ b/tests/unit/pipelex/exceptions/test_as_caller_fault.py@@ -1,3 +1,5 @@+from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import INTERNAL_ERROR_PLACEHOLDER, DisclosureMode, ErrorDomain, PipelexErrorfrom pipelex.cogt.exceptions import InferenceErrorCategory, ModelNotFoundErrorfrom pipelex.cogt.inference.error_classification import UserAction, UserActionKind@@ -9,18 +11,17 @@ from pipelex.system.pipe_run_mode import PipeRunModeclass TestAsCallerFault:def test_classifies_this_error_only(self) -> None:"""The raise site's classification applies to its own error, never to the class or to another instance."""- caller_fault = StuffFactoryError("Error combining stuffs for concept Report").as_caller_fault()+ caller_fault = StuffFactoryError("Error combining stuffs for concept Report").with_error_code(CoreCode.PIPE_OUTPUT_INVALID).as_caller_fault()other = StuffFactoryError("A factory refusal that is not the caller's")caller_report = caller_fault.to_error_report()- assert caller_report.error_domain == ErrorDomain.INPUT+ assert caller_report.code == CoreCode.PIPE_OUTPUT_INVALIDassert caller_report.caller_facing_message is Trueassert caller_report.http_status == 422other_report = other.to_error_report()- assert other_report.error_domain is None+ assert other_report.code == CoreCode.INPUT_INVALIDassert other_report.caller_facing_message is False- assert StuffFactoryError.error_domain is Nonedef test_strict_disclosure_keeps_the_message_and_the_user_action(self) -> None:"""A caller fault reads its own message and next step under STRICT, instead of the placeholder."""@@ -31,16 +32,30 @@ class TestAsCallerFault:assert payload["message"] == "Input 'topic' is missing"assert payload["user_action"] == {"kind": "change_input", "detail": "Provide the input 'topic'."}- def test_wins_over_a_domain_the_category_derives(self) -> None:- """On a `CogtError`, the raise site's domain wins over the one its category derives."""- error = ModelNotFoundError(message="Model handle 'x' was not found in the model deck.", model_handle="x").as_caller_fault()+ def test_the_chosen_code_decides_the_domain_not_the_category(self) -> None:+ """On a `CogtError`, the code the raise site chooses decides the domain, while the category stays the runtime's."""+ error = (+ ModelNotFoundError(message="Model handle 'x' was not found in the model deck.", model_handle="x")+ .with_error_code(CoreCode.MODEL_UNKNOWN)+ .as_caller_fault()+ )report = error.to_error_report()assert error.error_category is InferenceErrorCategory.CONFIGURATIONassert report.error_category == "configuration"+ assert report.code == CoreCode.MODEL_UNKNOWNassert report.error_domain == ErrorDomain.INPUTassert report.caller_facing_message is True+ def test_does_not_change_the_code(self) -> None:+ """Marking a message caller-facing leaves the code, and every fact it decides, as the class declares them."""+ error = ModelNotFoundError(message="Model handle 'x' was not found in the model deck.", model_handle="x").as_caller_fault()++ report = error.to_error_report()+ assert report.code == CoreCode.MODEL_UNAVAILABLE+ assert report.error_domain == ErrorDomain.CONFIG+ assert report.caller_facing_message is True+def test_a_wrapper_inherits_the_domain_but_never_the_caller_facing_flag(self) -> None:"""The flag records who wrote the message: a plain wrapper's own message stays redacted."""cause = StuffFactoryError("Error combining stuffs for concept Report").as_caller_fault()diff --git a/tests/unit/pipelex/exceptions/test_class_level_metadata.py b/tests/unit/pipelex/exceptions/test_class_level_metadata.pyindex 7f9b9a1f5..99136e823 100644--- a/tests/unit/pipelex/exceptions/test_class_level_metadata.py+++ b/tests/unit/pipelex/exceptions/test_class_level_metadata.py@@ -1,21 +1,22 @@import pytest+from mthds.protocol.problem.registry import CoreCodefrom pipelex.base_exceptions import ErrorDomain, PipelexConfigError, PipelexError, PipelexSetupErrorfrom pipelex.cogt.exceptions import (CogtError,- ImageContentError,ImgGenParameterError,ImgGenPromptError,InferenceBackendLibraryError,InferenceErrorCategory,LLMPromptParameterError,- LLMPromptSpecError,PromptDocumentFactoryError,PromptImageFactoryError,PromptImageFormatError,SdkTypeError,)from pipelex.core.stuffs.exceptions import DateContentError+from pipelex.errors.error_codes import ErrorCode+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.libraries.pipe.exceptions import EntryPipeAmbiguousError, EntryPipeNotFoundError, PipeLibraryError, PipeNotFoundErrorfrom pipelex.mthds_parsing.exceptions import MthdsParserErrorfrom pipelex.pipeline.exceptions import (@@ -40,28 +41,30 @@ _PIPELINE_EXEC_ERROR = PipelineExecutionError(class TestClassLevelMetadata:- """Key exceptions self-describe error_domain / user_action / error_category at the class level."""+ """Key exceptions self-describe their code, user_action and error_category at the class level."""@pytest.mark.parametrize(- ("_topic", "exc", "expected_domain"),+ ("_topic", "exc", "expected_code", "expected_domain"),[- ("pipeline_execution", _PIPELINE_EXEC_ERROR, ErrorDomain.RUNTIME),- ("pipe_execution", PipeExecutionError("boom"), ErrorDomain.RUNTIME),- ("validate_bundle", ValidateBundleError("boom"), ErrorDomain.INPUT),- ("pipeline_input_content", PipelineInputContentError("boom"), ErrorDomain.INPUT),+ # The run's wrapper takes its cause's code, and with no cause its fallback.+ ("pipeline_execution", _PIPELINE_EXEC_ERROR, CoreCode.RUNTIME_UNEXPECTED, ErrorDomain.RUNTIME),+ ("pipe_execution", PipeExecutionError("boom"), CoreCode.RUNTIME_UNEXPECTED, ErrorDomain.RUNTIME),+ ("validate_bundle", ValidateBundleError("boom"), CoreCode.METHOD_INVALID, ErrorDomain.INPUT),+ ("pipeline_input_content", PipelineInputContentError("boom"), PipelexErrorCode.STORAGE_URI_INVALID, ErrorDomain.INPUT),# The entry-shaped lookups report a pipe_code the caller supplied, so a typo is theirs- # to fix — 422, never the 500 an undomained error renders as.- ("entry_pipe_not_found", EntryPipeNotFoundError("boom"), ErrorDomain.INPUT),- ("entry_pipe_ambiguous", EntryPipeAmbiguousError("boom"), ErrorDomain.INPUT),- ("interpreter", MthdsParserError("boom"), ErrorDomain.INPUT),- ("setup", PipelexSetupError("boom"), ErrorDomain.CONFIG),- ("config", PipelexConfigError("boom"), ErrorDomain.CONFIG),- ("env_var_not_found", EnvVarNotFoundError("boom"), ErrorDomain.CONFIG),+ # to fix — 422, never the 500 a runtime fault renders as.+ ("entry_pipe_not_found", EntryPipeNotFoundError("boom"), CoreCode.REQUEST_PIPE_NOT_FOUND, ErrorDomain.INPUT),+ ("entry_pipe_ambiguous", EntryPipeAmbiguousError("boom"), CoreCode.REQUEST_PIPE_AMBIGUOUS, ErrorDomain.INPUT),+ ("interpreter", MthdsParserError("boom"), CoreCode.METHOD_INVALID, ErrorDomain.INPUT),+ ("setup", PipelexSetupError("boom"), CoreCode.RUNTIME_MISCONFIGURED, ErrorDomain.CONFIG),+ ("config", PipelexConfigError("boom"), PipelexErrorCode.CONFIG_INVALID, ErrorDomain.CONFIG),+ ("env_var_not_found", EnvVarNotFoundError("boom"), PipelexErrorCode.CONFIG_VARIABLE_MISSING, ErrorDomain.CONFIG),],)- def test_error_domain(self, _topic: str, exc: PipelexError, expected_domain: ErrorDomain) -> None:- """The targeted exceptions carry their expected error_domain in to_error_report()."""+ def test_error_code(self, _topic: str, exc: PipelexError, expected_code: ErrorCode, expected_domain: ErrorDomain) -> None:+ """The targeted exceptions report their class's code, and the domain it decides, in to_error_report()."""report = exc.to_error_report()+ assert report.code == expected_codeassert report.error_domain == expected_domain@pytest.mark.parametrize(@@ -94,14 +97,12 @@ class TestClassLevelMetadata:@pytest.mark.parametrize(("_topic", "exc", "expected_category"),[- ("prompt_spec", LLMPromptSpecError("x"), InferenceErrorCategory.CONTENT),("prompt_parameter", LLMPromptParameterError("x"), InferenceErrorCategory.CONTENT),("prompt_image_factory", PromptImageFactoryError("x"), InferenceErrorCategory.CONTENT),("prompt_image_format", PromptImageFormatError("x"), InferenceErrorCategory.CONTENT),("prompt_document_factory", PromptDocumentFactoryError("x"), InferenceErrorCategory.CONTENT),("imggen_prompt", ImgGenPromptError("x"), InferenceErrorCategory.CONTENT),("imggen_parameter", ImgGenParameterError("x"), InferenceErrorCategory.CONTENT),- ("image_content", ImageContentError("x"), InferenceErrorCategory.CONTENT),("sdk_type", SdkTypeError("x"), InferenceErrorCategory.CONFIGURATION),("backend_library", InferenceBackendLibraryError("x"), InferenceErrorCategory.CONFIGURATION),],@@ -158,8 +159,8 @@ class TestClassLevelMetadata:Pins the deliberate inheritance contract on ``_authors_caller_facing_message``(plain attribute access — see ``base_exceptions.py``): a future refactor- swapping the flag to ``cls.__dict__`` lookup (the path used by- ``_declared_title`` / ``_declared_type_uri``) would silently downgrade+ swapping the flag to ``cls.__dict__`` lookup (the path the error-code gate+ uses for ``error_code``) would silently downgradeSTRICT disclosure for every subclass and let internal messages leak underSTRICT — or, more likely, silently redact authored caller-facing copy."""diff --git a/tests/unit/pipelex/exceptions/test_error_domain.py b/tests/unit/pipelex/exceptions/test_error_domain.pyindex 750f881a2..7b83765b5 100644--- a/tests/unit/pipelex/exceptions/test_error_domain.py+++ b/tests/unit/pipelex/exceptions/test_error_domain.py@@ -1,15 +1,17 @@from enum import StrEnumimport pytest+from mthds.protocol.problem.registry import ProblemDomainfrom pipelex.base_exceptions import ErrorDomain, PipelexError, error_domain_is_input+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom tests.helpers.error_report import make_error_report-class _ConfigDomainError(PipelexError):- """Test-only subclass that declares a class-level error_domain."""+class _ConfigCodedError(PipelexError):+ """Test-only subclass whose code is in the operator's domain."""- error_domain = ErrorDomain.CONFIG+ error_code = PipelexErrorCode.CONFIG_INVALIDclass TestErrorDomain:@@ -26,17 +28,32 @@ class TestErrorDomain:assert ErrorDomain.RUNTIME == "runtime"assert set(ErrorDomain) == {ErrorDomain.INPUT, ErrorDomain.CONFIG, ErrorDomain.RUNTIME}- def test_to_error_report_omits_error_domain_when_undeclared(self) -> None:- """A PipelexError that declares no error_domain reports it as None."""+ def test_to_error_report_reports_the_fallback_domain_without_a_code(self) -> None:+ """A PipelexError that names no code reports runtime.unexpected, and so the runtime domain."""report = PipelexError("plain error").to_error_report()- assert report.error_domain is None+ assert report.code == "runtime.unexpected"+ assert report.error_domain == ErrorDomain.RUNTIME- def test_to_error_report_carries_error_domain_when_declared(self) -> None:- """A PipelexError subclass with a class-level error_domain forwards it into the report."""- report = _ConfigDomainError("config broke").to_error_report()+ def test_to_error_report_reads_the_domain_from_the_code(self) -> None:+ """A PipelexError subclass's report reads its domain from its code's registry domain."""+ report = _ConfigCodedError("config broke").to_error_report()assert report.error_domain == ErrorDomain.CONFIGassert report.error_domain == "config"+ @pytest.mark.parametrize(+ ("problem_domain", "expected_error_domain"),+ [+ (ProblemDomain.INPUT, ErrorDomain.INPUT),+ (ProblemDomain.METHOD, ErrorDomain.INPUT),+ (ProblemDomain.ACCOUNT, ErrorDomain.CONFIG),+ (ProblemDomain.OPERATOR, ErrorDomain.CONFIG),+ (ProblemDomain.RUNTIME, ErrorDomain.RUNTIME),+ ],+ )+ def test_from_problem_domain(self, problem_domain: ProblemDomain, expected_error_domain: ErrorDomain) -> None:+ """A code's registry domain projects onto the report's domain: the caller's, the operator's or the runtime's."""+ assert ErrorDomain.from_problem_domain(problem_domain) is expected_error_domain+def test_to_dict_drops_error_domain_when_none(self) -> None:"""ErrorReport.to_dict() omits error_domain when it is None."""report_dict = make_error_report(error_type="X", message="m").to_dict()diff --git a/tests/unit/pipelex/exceptions/test_wrapper_error_enrichment.py b/tests/unit/pipelex/exceptions/test_wrapper_error_enrichment.pyindex d1c8f6717..27763cb3b 100644--- a/tests/unit/pipelex/exceptions/test_wrapper_error_enrichment.py+++ b/tests/unit/pipelex/exceptions/test_wrapper_error_enrichment.py@@ -1,5 +1,7 @@+from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import ErrorDomain-from pipelex.cogt.exceptions import CogtError, InferenceErrorCategory+from pipelex.cogt.exceptions import InferenceErrorCategory, LLMCompletionErrorfrom pipelex.cogt.inference.error_classification import UserAction, UserActionKindfrom pipelex.core.pipes.exceptions import PipeRunErrorfrom pipelex.pipe_run.exceptions import PipeRouterError@@ -21,11 +23,11 @@ def _make_pipeline_execution_error(cause: BaseException | None) -> PipelineExecuclass TestWrapperErrorEnrichment:- """PipelineExecutionError must surface the wrapped cause's categorized action, not mask it with its generic floor."""+ """PipelineExecutionError must surface the wrapped cause's code and categorized action, not mask them."""def test_preserves_categorized_cause_action(self) -> None:- """A transient CogtError wrapped through PipeRunError/PipeRouterError keeps its WAIT_AND_RETRY action and category."""- cogt_error = CogtError(+ """A transient inference failure wrapped through PipeRunError/PipeRouterError keeps its action, its category and its retryable code."""+ cogt_error = LLMCompletionError(message="rate limited",error_category=InferenceErrorCategory.TRANSIENT,user_action=UserAction(kind=UserActionKind.WAIT_AND_RETRY, detail="Wait a moment and retry"),@@ -47,17 +49,19 @@ class TestWrapperErrorEnrichment:assert report.user_action.kind == UserActionKind.WAIT_AND_RETRY, "the cause's actionable advice must not be masked by the wrapper"assert report.user_action.detail == "Wait a moment and retry"assert report.error_category == InferenceErrorCategory.TRANSIENT+ # A category with no code of its own reports the category's code, which invites a retry.+ assert report.code == CoreCode.PROVIDER_UNAVAILABLEassert report.retryable is True- def test_surfaces_input_domain_of_a_content_categorized_cause(self) -> None:- """A CONTENT-categorized CogtError reaches the wrapper as INPUT / 422, not the generic RUNTIME floor.+ def test_surfaces_the_code_of_a_caller_fixable_cause(self) -> None:+ """A content refusal coded `model.content_refused` reaches the wrapper as its code, INPUT / 422, not a runtime fault.- This is what the class docstring has always promised — that the RUNTIME floor applies only- when the cause chain surfaces no domain. Until the CogtError family derived a domain from its- category, no inference failure ever surfaced one, so the promise was vacuous and the floor- fired every time.+ The run's wrappers take their cause's code, so the report reads the refusal's own code and every fact it+ decides, rather than the runtime fault a wrapper with a code of its own would report."""- cogt_error = CogtError(message="the prompt was refused", error_category=InferenceErrorCategory.CONTENT)+ cogt_error = LLMCompletionError(message="the prompt was refused", error_category=InferenceErrorCategory.CONTENT).with_error_code(+ CoreCode.MODEL_CONTENT_REFUSED+ )pipe_run_error = PipeRunError(message="pipe failed", run_mode=PipeRunMode.LIVE, pipe_code="some_pipe")pipe_run_error.__cause__ = cogt_errorpipe_router_error = PipeRouterError(@@ -71,14 +75,16 @@ class TestWrapperErrorEnrichment:report = _make_pipeline_execution_error(cause=pipe_router_error).to_error_report()- assert report.error_domain == ErrorDomain.INPUT, "the wrapper's RUNTIME floor must not mask a caller-fixable cause"+ assert report.code == CoreCode.MODEL_CONTENT_REFUSED+ assert report.error_domain == ErrorDomain.INPUT, "the wrapper must not mask a caller-fixable cause"assert report.http_status == 422assert report.error_category == InferenceErrorCategory.CONTENTdef test_falls_back_to_runtime_unknown_without_cause(self) -> None:- """With no PipelexError cause, PipelineExecutionError reports the RUNTIME floor and a fallback naming the failing pipe."""+ """With no PipelexError cause, PipelineExecutionError reports its fallback code and a next step naming the failing pipe."""report = _make_pipeline_execution_error(cause=None).to_error_report()+ assert report.code == CoreCode.RUNTIME_UNEXPECTEDassert report.error_domain == ErrorDomain.RUNTIMEassert report.user_action is not Noneassert report.user_action.kind == UserActionKind.UNKNOWNdiff --git a/tests/unit/pipelex/kernel/test_func_ops.py b/tests/unit/pipelex/kernel/test_func_ops.pyindex a0765f0b8..8fd18a9b3 100644--- a/tests/unit/pipelex/kernel/test_func_ops.py+++ b/tests/unit/pipelex/kernel/test_func_ops.py@@ -15,12 +15,14 @@ from collections.abc import Callablefrom typing import Anyimport pytest+from mthds.protocol.problem.registry import CoreCodefrom pipelex.core.concepts.concept_factory import ConceptFactoryfrom pipelex.core.concepts.native.concept_native import NativeConceptCodefrom pipelex.core.memory.working_memory import WorkingMemoryfrom pipelex.core.memory.working_memory_factory import WorkingMemoryFactoryfrom pipelex.core.stuffs.text_content import TextContent+from pipelex.kernel.exceptions import FuncOutputTypeErrorfrom pipelex.kernel.func_ops import call_function, run_funcASYNC_TEXT = "produced by the async function"@@ -39,6 +41,18 @@ def _sync_producer(working_memory: WorkingMemory) -> TextContent: # ruff: ignorreturn TextContent(text=SYNC_TEXT)+def _number_producer(working_memory: WorkingMemory) -> int: # ruff: ignore[unused-function-argument]+ return 42+++def _dict_list_producer(working_memory: WorkingMemory) -> list[dict[str, int]]: # ruff: ignore[unused-function-argument]+ return [{"parcel": 7}]+++def _number_list_producer(working_memory: WorkingMemory) -> list[Any]: # ruff: ignore[unused-function-argument]+ return [TextContent(text=SYNC_TEXT), 42]++@pytest.mark.asyncio(loop_scope="class")class TestFuncOps:@pytest.mark.parametrize(@@ -80,3 +94,19 @@ class TestFuncOps:assert main_stuff.content.text == ASYNC_TEXTassert result.content is main_stuff.contentassert result.memory.get_stuff(name=RESULT_NAME).content is main_stuff.content++ @pytest.mark.parametrize(+ ("function", "refused_type"),+ [+ pytest.param(_number_producer, "int", id="no-content"),+ pytest.param(_dict_list_producer, "dict", id="list-holding-a-dict"),+ pytest.param(_number_list_producer, "int", id="list-holding-a-number"),+ ],+ )+ async def test_a_function_returning_no_content_fails_the_step_output(self, function: Callable[..., Any], refused_type: str) -> None:+ """A registered function's wrong return shape is the step's output failing, not a runtime defect, and never a silent empty content."""+ with pytest.raises(FuncOutputTypeError, match=function.__name__) as exc_info:+ await call_function(function=function, memory=WorkingMemoryFactory.make_empty())++ assert f"<class '{refused_type}'>" in exc_info.value.message+ assert exc_info.value.resolve_error_code() == CoreCode.PIPE_OUTPUT_INVALIDdiff --git a/tests/unit/pipelex/kernel/test_structure_prompt_owner.py b/tests/unit/pipelex/kernel/test_structure_prompt_owner.pynew file mode 100644index 000000000..7b7197b45--- /dev/null+++ b/tests/unit/pipelex/kernel/test_structure_prompt_owner.py@@ -0,0 +1,32 @@+"""The structure prompt is Pipelex's own template, so a failure to render it is ours, not the method's.++The template is config-editable: an edit naming a filter the environment lacks must report+`runtime.unexpected`, never the method's `method.template_invalid`, since no method wrote it.+"""++import pytest+from mthds.protocol.problem.registry import CoreCode+from pytest_mock import MockerFixture++from pipelex.cogt.config_cogt import LLMConfig+from pipelex.kernel.llm_ops import derive_structure_prompt+from pipelex.test_extras.registry_test_models import FictionCharacter+from pipelex.tools.jinja2.exceptions import Jinja2TemplateInvalidError+from pipelex.tools.templating.templating_style import TagStyle, TemplatingStyle+from pipelex.tools.templating.text_format import TextFormat++_TEMPLATING_STYLE = TemplatingStyle(tag_style=TagStyle.NO_TAG, text_format=TextFormat.PLAIN)++#: An edited structure-prompt template naming a filter the environment lacks.+_EDITED_TEMPLATE_WITH_AN_UNKNOWN_FILTER = "{{ class_structure_str | frob_the_structure }}"+++class TestStructurePromptOwner:+ @pytest.mark.asyncio(loop_scope="class")+ async def test_a_broken_structure_prompt_template_is_ours(self, mocker: MockerFixture) -> None:+ mocker.patch.object(LLMConfig, "get_template", return_value=_EDITED_TEMPLATE_WITH_AN_UNKNOWN_FILTER)++ with pytest.raises(Jinja2TemplateInvalidError) as exc_info:+ await derive_structure_prompt(output_class=FictionCharacter, templating_style=_TEMPLATING_STYLE)++ assert exc_info.value.to_error_report().code == CoreCode.RUNTIME_UNEXPECTEDdiff --git a/tests/unit/pipelex/libraries/test_dependency_pipe_build_refusals.py b/tests/unit/pipelex/libraries/test_dependency_pipe_build_refusals.pyindex e0d7b66fd..b72b51024 100644--- a/tests/unit/pipelex/libraries/test_dependency_pipe_build_refusals.py+++ b/tests/unit/pipelex/libraries/test_dependency_pipe_build_refusals.py@@ -3,9 +3,10 @@ from pathlib import Pathimport pytestfrom mthds.package.dependency_resolver import ResolvedDependencyfrom mthds.package.manifest.schema import MethodsManifest+from mthds.protocol.problem.registry import CoreCodefrom pytest_mock import MockerFixture-from pipelex.base_exceptions import ErrorDomain, PipelexError+from pipelex.base_exceptions import PipelexErrorfrom pipelex.core.pipes.exceptions import PipeLoadRefusalError, PipeOperatorModelChoiceErrorfrom pipelex.interpreter_hub import get_library_managerfrom pipelex.libraries.library_factory import LibraryFactory@@ -46,7 +47,7 @@ def _dep_bundle(*, pipes: str) -> str:class _InternalInputRefusalError(PipelexError):- error_domain = ErrorDomain.INPUT+ error_code = CoreCode.INPUT_INVALIDclass TestDependencyPipeBuildRefusals:diff --git a/tests/unit/pipelex/libraries/test_pipe_library_lookup.py b/tests/unit/pipelex/libraries/test_pipe_library_lookup.pyindex 92ff9160f..0aae40b85 100644--- a/tests/unit/pipelex/libraries/test_pipe_library_lookup.py+++ b/tests/unit/pipelex/libraries/test_pipe_library_lookup.py@@ -1,6 +1,7 @@from typing import Anyimport pytest+from mthds.protocol.problem.registry import CoreCodefrom pytest_mock import MockerFixturefrom pipelex.base_exceptions import ErrorDomain@@ -93,6 +94,7 @@ class TestPipeLibraryLookup:assert "scoring.compute_score" in str(exc_info.value)report = exc_info.value.to_error_report()+ assert report.code == CoreCode.REQUEST_PIPE_AMBIGUOUSassert report.error_domain == ErrorDomain.INPUTassert report.http_status == 422@@ -107,6 +109,7 @@ class TestPipeLibraryLookup:library.get_required_entry_pipe("nonexistent")report = exc_info.value.to_error_report()+ assert report.code == CoreCode.REQUEST_PIPE_NOT_FOUNDassert report.error_domain == ErrorDomain.INPUTassert report.http_status == 422@@ -147,10 +150,10 @@ class TestPipeLibraryLookup:assert not isinstance(exc_info.value, EntryPipeAmbiguousError)def test_in_body_aliased_ambiguity_is_not_translated(self, mocker: MockerFixture):- """The same lookup through the in-body door keeps the plain, unclassified error.+ """The same lookup through the in-body door keeps the plain error, with the method's code.- In-body resolution failures are not a caller's input mistake — the ref was written in a- bundle — so the entry classification must not leak onto them.+ In-body resolution failures are not a caller's request mistake — the ref was written in a+ bundle — so the entry classification must not leak onto them: the method's author fixes it."""library = PipeLibrary.make_empty()library.add_dependency_pipe(alias="lib", pipe=_make_stub_pipe(mocker, code="compute_score", domain_code="scoring"), is_exported=True)@@ -159,15 +162,19 @@ class TestPipeLibraryLookup:with pytest.raises(PipeLibraryError) as exc_info:library.get_optional_pipe("lib->compute_score")assert not isinstance(exc_info.value, EntryPipeAmbiguousError)- assert exc_info.value.to_error_report().error_domain is None+ report = exc_info.value.to_error_report()+ assert report.code == CoreCode.METHOD_REF_AMBIGUOUS+ assert report.caller_facing_message is False- def test_in_body_required_miss_stays_unclassified(self):- """`get_required_pipe` is the in-body door and keeps raising the plain, domain-less error."""+ def test_in_body_required_miss_carries_the_method_code(self):+ """`get_required_pipe` is the in-body door and keeps raising the plain error, with the method's code."""library = PipeLibrary.make_empty()with pytest.raises(PipeNotFoundError) as exc_info:library.get_required_pipe("scoring.nonexistent")assert not isinstance(exc_info.value, EntryPipeNotFoundError)- assert exc_info.value.to_error_report().error_domain is None+ report = exc_info.value.to_error_report()+ assert report.code == CoreCode.METHOD_PIPE_UNRESOLVED+ assert report.caller_facing_message is Falsedef test_entry_pipe_ignores_aliased_dependency_entries(self, mocker: MockerFixture):"""An installed package must not make a host pipe's bare code ambiguous.diff --git a/tests/unit/pipelex/pipe_machinery/test_execution_data_coverage.py b/tests/unit/pipelex/pipe_machinery/test_execution_data_coverage.pyindex b1b6bb6c6..bdc3173e0 100644--- a/tests/unit/pipelex/pipe_machinery/test_execution_data_coverage.py+++ b/tests/unit/pipelex/pipe_machinery/test_execution_data_coverage.py@@ -31,7 +31,8 @@ def _discover_pipe_classes() -> list[type[PipeAbstract]]:Excludes signature pipes: a `PipeSignature` is a contract-only placeholder. Its live-runraises before any runtime data exists, and its dry-run only mints a mock output — neither- is a place to register execution data for the graph tracer.+ is a place to register execution data for the graph tracer. Excludes the test doubles other+ test modules define too, which exist only when a run collects those modules first."""for package in (pipe_operators, pipe_controllers):for module_info in pkgutil.walk_packages(package.__path__, prefix=f"{package.__name__}."):@@ -50,7 +51,8 @@ def _discover_pipe_classes() -> list[type[PipeAbstract]]:leaves = [clsfor cls in seen- if not cls.__module__.endswith((".pipe_operator", ".pipe_controller", ".pipe_abstract"))+ if cls.__module__.startswith("pipelex.")+ and not cls.__module__.endswith((".pipe_operator", ".pipe_controller", ".pipe_abstract"))and not cls.__module__.startswith("pipelex.pipe_signature.")]return sorted(leaves, key=lambda c: c.__name__)diff --git a/tests/unit/pipelex/pipe_operators/pipe_func/test_pipe_func_failure_code.py b/tests/unit/pipelex/pipe_operators/pipe_func/test_pipe_func_failure_code.pynew file mode 100644index 000000000..6ed109214--- /dev/null+++ b/tests/unit/pipelex/pipe_operators/pipe_func/test_pipe_func_failure_code.py@@ -0,0 +1,194 @@+from collections.abc import Callable+from typing import Any++import pytest+from mthds.protocol.problem.registry import CoreCode+from pytest_mock import MockerFixture+from typing_extensions import override++from pipelex.core.memory.working_memory import WorkingMemory+from pipelex.core.memory.working_memory_factory import WorkingMemoryFactory+from pipelex.core.pipes.exceptions import PipeRunError+from pipelex.core.stuffs.text_content import TextContent+from pipelex.errors.error_codes import ErrorCode+from pipelex.interpreter_hub import scoped_pipe_func_executor+from pipelex.kernel.exceptions import FuncOutputTypeError+from pipelex.pipe_machinery.pipe_factory import PipeFactory+from pipelex.pipe_operators.func.direct_pipe_func_executor import DirectPipeFuncExecutor+from pipelex.pipe_operators.func.exceptions import PipeFuncExecutionError, PipeFuncRaisedError+from pipelex.pipe_operators.func.pipe_func import PipeFunc+from pipelex.pipe_operators.func.pipe_func_blueprint import PipeFuncBlueprint+from pipelex.pipe_operators.func.pipe_func_call_context import pipe_func_call_in_flight+from pipelex.pipe_operators.func.pipe_func_execution_dtos import PipeFuncExecutionRequest, PipeFuncExecutionResponse+from pipelex.pipe_operators.func.pipe_func_executor_protocol import PipeFuncExecutionResult, PipeFuncExecutorProtocol+from pipelex.pipe_run.pipe_run_params import PipeRunParams+from pipelex.system.exceptions import RunParameterError+from pipelex.system.job_metadata import JobMetadata, RunMetadata+from pipelex.system.pipe_run_mode import PipeRunMode+from pipelex.tools.storage.exceptions import StorageS3Error+++def _raises_a_request_refusal(working_memory: WorkingMemory) -> TextContent:+ """A function whose own code calls a helper that refuses a run parameter."""+ _ = working_memory+ msg = "The storage scope 'elsewhere' is outside the read scope"+ raise RunParameterError(msg)+++def _raises_a_storage_outage(working_memory: WorkingMemory) -> TextContent:+ _ = working_memory+ msg = "The storage could not be reached"+ raise StorageS3Error(msg)+++def _raises_a_plain_error(working_memory: WorkingMemory) -> TextContent:+ _ = working_memory+ msg = "the ledger has no line for this parcel"+ raise KeyError(msg)+++def _returns_a_list_holding_a_dict(working_memory: WorkingMemory) -> list[dict[str, str]]:+ _ = working_memory+ return [{"parcel": "7"}]+++def _returns_a_list_holding_a_number(working_memory: WorkingMemory) -> list[Any]:+ _ = working_memory+ return [TextContent(text="line 7"), 7]+++class _TimedOutExecutor(PipeFuncExecutorProtocol):+ """An executor whose own seam fails: the function ran past its timeout."""++ @override+ async def run_pipe_func(+ self,+ *,+ job_metadata: JobMetadata,+ pipe_code: str,+ function_name: str,+ working_memory: WorkingMemory,+ pipe_run_params: PipeRunParams,+ ) -> PipeFuncExecutionResult:+ msg = f"PipeFunc '{function_name}' exceeded its 30s timeout"+ raise PipeFuncExecutionError(msg).with_error_code(CoreCode.PIPE_FUNCTION_TIMED_OUT)++ @override+ async def run_pipe_func_transported(self, *, request: PipeFuncExecutionRequest) -> PipeFuncExecutionResponse:+ msg = "Not used by this test"+ raise NotImplementedError(msg)+++class _TransportFailingExecutor(PipeFuncExecutorProtocol):+ """An out-of-process executor whose transport failed with an exception that is not a Pipelex error."""++ @override+ async def run_pipe_func(+ self,+ *,+ job_metadata: JobMetadata,+ pipe_code: str,+ function_name: str,+ working_memory: WorkingMemory,+ pipe_run_params: PipeRunParams,+ ) -> PipeFuncExecutionResult:+ msg = "The connection to the sandbox was reset"+ raise ConnectionResetError(msg)++ @override+ async def run_pipe_func_transported(self, *, request: PipeFuncExecutionRequest) -> PipeFuncExecutionResponse:+ msg = "Not used by this test"+ raise NotImplementedError(msg)+++def _make_pipe_func() -> PipeFunc:+ blueprint = PipeFuncBlueprint(+ description="Read the parcel's line in the ledger",+ inputs={},+ output="native.Text",+ function_name="ledger_funcs.lines.read_line",+ )+ return PipeFactory[PipeFunc].make_from_blueprint(domain_code="failure_code", pipe_code="read_line", blueprint=blueprint)+++async def _failure_of(*, pipe_func: PipeFunc, executor: PipeFuncExecutorProtocol, function: Callable[..., Any]) -> PipeRunError:+ job_metadata = JobMetadata(run_metadata=RunMetadata(storage_scope="test/scope", read_scope=None, user_id="user", pipeline_run_id="run"))+ with (+ scoped_pipe_func_executor(pipe_func_executor=executor),+ pipe_func_call_in_flight(pipe_ref=pipe_func.pipe_ref, function=function),+ pytest.raises(PipeRunError) as exc_info,+ ):+ await pipe_func._live_run_operator_pipe( # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ job_metadata=job_metadata,+ working_memory=WorkingMemoryFactory.make_empty(),+ pipe_run_params=PipeRunParams(run_mode=PipeRunMode.LIVE, pipe_stack_limit=10, batch_max_concurrency=None),+ )+ return exc_info.value+++class TestPipeFuncFailureCode:+ @pytest.mark.parametrize(+ ("function", "raised_type"),+ [+ (_raises_a_request_refusal, "RunParameterError"),+ (_raises_a_storage_outage, "StorageS3Error"),+ (_raises_a_plain_error, "KeyError"),+ ],+ ids=["coded_request_refusal", "coded_storage_outage", "plain_exception"],+ )+ @pytest.mark.asyncio+ async def test_what_the_function_raised_is_the_functions_failure(+ self, load_empty_library: Callable[[], str], mocker: MockerFixture, function: Callable[..., Any], raised_type: str+ ) -> None:+ """A coded Pipelex error a helper raised inside the function is still the function's failure, and rides as the cause."""+ load_empty_library()+ mocker.patch("pipelex.pipe_operators.func.pipe_func.is_pipe_func_sandbox_hosted", return_value=True)++ failure = await _failure_of(pipe_func=_make_pipe_func(), executor=DirectPipeFuncExecutor(), function=function)++ assert failure.to_error_report().code == CoreCode.PIPE_FUNCTION_RAISED+ assert isinstance(failure.__cause__, PipeFuncRaisedError)+ assert type(failure.__cause__.__cause__).__name__ == raised_type+ assert f"Error: {raised_type}: " in failure.message++ @pytest.mark.parametrize(+ ("executor", "expected_code"),+ [+ (_TimedOutExecutor(), CoreCode.PIPE_FUNCTION_TIMED_OUT),+ (_TransportFailingExecutor(), CoreCode.RUNTIME_UNEXPECTED),+ ],+ ids=["timed_out", "foreign_transport_failure"],+ )+ @pytest.mark.asyncio+ async def test_a_failure_of_the_executor_keeps_its_own_code(+ self,+ load_empty_library: Callable[[], str],+ mocker: MockerFixture,+ executor: PipeFuncExecutorProtocol,+ expected_code: ErrorCode,+ ) -> None:+ """A failure of the seam is not the function's, and an exception no executor marked proves nothing about the function."""+ load_empty_library()+ mocker.patch("pipelex.pipe_operators.func.pipe_func.is_pipe_func_sandbox_hosted", return_value=True)++ failure = await _failure_of(pipe_func=_make_pipe_func(), executor=executor, function=_raises_a_plain_error)++ assert failure.to_error_report().code == expected_code++ @pytest.mark.parametrize(+ "function",+ [_returns_a_list_holding_a_dict, _returns_a_list_holding_a_number],+ ids=["list_holding_a_dict", "list_holding_a_number"],+ )+ @pytest.mark.asyncio+ async def test_a_return_shape_the_coercion_refuses_is_the_step_s_output_failing(+ self, load_empty_library: Callable[[], str], mocker: MockerFixture, function: Callable[..., Any]+ ) -> None:+ """The function returned, so what it returned failing the coercion is no failure of the function's, whatever its shape."""+ load_empty_library()+ mocker.patch("pipelex.pipe_operators.func.pipe_func.is_pipe_func_sandbox_hosted", return_value=True)++ failure = await _failure_of(pipe_func=_make_pipe_func(), executor=DirectPipeFuncExecutor(), function=function)++ assert failure.to_error_report().code == CoreCode.PIPE_OUTPUT_INVALID+ assert isinstance(failure.__cause__, FuncOutputTypeError)diff --git a/tests/unit/pipelex/pipe_operators/pipe_img_gen/test_pipe_img_gen_model_choice_code.py b/tests/unit/pipelex/pipe_operators/pipe_img_gen/test_pipe_img_gen_model_choice_code.pynew file mode 100644index 000000000..73b771a15--- /dev/null+++ b/tests/unit/pipelex/pipe_operators/pipe_img_gen/test_pipe_img_gen_model_choice_code.py@@ -0,0 +1,45 @@+from typing import Callable++import pytest+from mthds.protocol.problem.registry import CoreCode++from pipelex.cogt.model_backends.model_type import ModelType+from pipelex.core.pipes.exceptions import PipeOperatorModelChoiceError+from pipelex.pipe_machinery.pipe_factory import PipeFactory+from pipelex.pipe_operators.img_gen.pipe_img_gen import PipeImgGen+from pipelex.pipe_operators.img_gen.pipe_img_gen_blueprint import PipeImgGenBlueprint+from pipelex.runtime_hub import get_model_deck+++def _llm_only_handle() -> str:+ """A bare handle the booted deck serves as an LLM and never as an image-generation model."""+ model_deck = get_model_deck()+ for handle in model_deck.inference_models.handles_of_type(model_type=ModelType.LLM):+ if model_deck.is_served_only_as_other_types(name=handle, model_type=ModelType.IMG_GEN):+ return handle+ pytest.fail("The test deck serves no LLM that is not also an image-generation model")+++def _refusal_of(*, model: str) -> PipeOperatorModelChoiceError:+ blueprint = PipeImgGenBlueprint(description="Paint the scene", inputs={}, output="Image", prompt="A lighthouse at dusk", model=model)+ with pytest.raises(PipeOperatorModelChoiceError) as exc_info:+ PipeFactory[PipeImgGen].make_from_blueprint(domain_code="model_choice_code", pipe_code="paint_scene", blueprint=blueprint)+ return exc_info.value+++class TestPipeImgGenModelChoiceCode:+ def test_an_llm_named_in_an_image_step_reads_capability_unsupported(self, load_empty_library: Callable[[], str]) -> None:+ """The located refusal keeps its cause's code: the model exists and is served, only not as an image model."""+ load_empty_library()++ refusal = _refusal_of(model=_llm_only_handle())++ assert refusal.field_name == "model"+ assert refusal.to_error_report().code == CoreCode.MODEL_CAPABILITY_UNSUPPORTED++ def test_a_model_no_deck_defines_reads_unknown(self, load_empty_library: Callable[[], str]) -> None:+ load_empty_library()++ refusal = _refusal_of(model="no-such-painter-anywhere")++ assert refusal.to_error_report().code == CoreCode.MODEL_UNKNOWNdiff --git a/tests/unit/pipelex/pipe_operators/pipe_judge/test_pipe_judge_deck_default.py b/tests/unit/pipelex/pipe_operators/pipe_judge/test_pipe_judge_deck_default.pynew file mode 100644index 000000000..3287b6753--- /dev/null+++ b/tests/unit/pipelex/pipe_operators/pipe_judge/test_pipe_judge_deck_default.py@@ -0,0 +1,105 @@+import pytest+from mthds.protocol.problem.registry import CoreCode+from pytest_mock import MockerFixture++from pipelex.base_exceptions import INTERNAL_ERROR_PLACEHOLDER, DisclosureMode+from pipelex.cogt.config_cogt import ModelDeckConfig+from pipelex.cogt.exceptions import ModelChoiceNotFoundError, ModelDeckChoiceUnresolvedError+from pipelex.cogt.img_gen.img_gen_job_components import Quality+from pipelex.cogt.judgment.judgment_models import YesNoQuestion+from pipelex.cogt.llm.llm_setting import LLMSettingChoices, LLMSettingChoicesDefaults+from pipelex.cogt.model_backends.model_spec_index import ModelSpecIndex+from pipelex.cogt.model_backends.model_type import ModelType+from pipelex.cogt.models.model_deck import ModelDeck+from pipelex.cogt.templating.template_blueprint import TemplateBlueprint+from pipelex.core.concepts.concept_factory import ConceptFactory+from pipelex.core.concepts.native.concept_native import NativeConceptCode+from pipelex.core.pipes.exceptions import PipeOperatorModelChoiceError+from pipelex.core.pipes.stuff_spec.stuff_spec import StuffSpec+from pipelex.errors.registry.pipelex_codes import PipelexErrorCode+from pipelex.kernel.prompt_assembly import UserPromptContent+from pipelex.pipe_operators.judge.pipe_judge import PipeJudge, PipeJudgeQuestion+from pipelex.pipeline.validate_bundle_translation import translate_to_validate_bundle_error+from pipelex.system.runtime import ProblemReaction+from pipelex.tools.jinja2.template_category import TemplateCategory++_MISSING_JUDGMENT_PRESET = "$missing-judgment-preset"+++def _deck_whose_judgment_default_is_undefined() -> ModelDeck:+ """A deck serving no model, whose judgment default names a preset it does not define."""+ return ModelDeck(+ inference_models=ModelSpecIndex.make_from_specs(model_specs=[]),+ llm_default_temperature=0.7,+ llm_aliases={},+ llm_waterfalls={},+ llm_presets={},+ llm_choice_defaults=LLMSettingChoicesDefaults(default_temperature=0.7, for_text="no-text-model", for_object="no-object-model"),+ llm_choice_overrides=LLMSettingChoices(for_text=None, for_object=None),+ extract_aliases={},+ extract_waterfalls={},+ extract_presets={},+ extract_choice_default="no-extract-model",+ img_gen_default_quality=Quality.MEDIUM,+ img_gen_aliases={},+ img_gen_waterfalls={},+ img_gen_presets={},+ img_gen_choice_default="no-img-gen-model",+ search_aliases={},+ search_waterfalls={},+ search_presets={},+ search_choice_default="no-search-model",+ doc_gen_choice_defaults={},+ judgment_choice_default=_MISSING_JUDGMENT_PRESET,+ model_deck_config=ModelDeckConfig(is_model_fallback_enabled=True, missing_presets_reaction=ProblemReaction.NONE),+ )+++def _pipe_judge_naming_no_model() -> PipeJudge:+ return PipeJudge(+ code="judge_urgency",+ domain_code="deck_default",+ description="Judge whether the message is urgent",+ output=StuffSpec(concept=ConceptFactory.make_native_concept(NativeConceptCode.YES_NO)),+ judgment_choice=None,+ prompt_content=UserPromptContent(template=TemplateBlueprint(template="$message", category=TemplateCategory.LLM_PROMPT)),+ question=PipeJudgeQuestion(judgment_question=YesNoQuestion(instructions="Is it urgent?")),+ )+++class TestPipeJudgeDeckDefault:+ def test_an_undefined_deck_default_leaves_as_the_deck_s_fault(self, mocker: MockerFixture) -> None:+ """The step names no model, so the deck's miss is no unknown model of the method's, and no verdict item."""+ mocker.patch("pipelex.kernel.judgment_ops.get_model_deck", return_value=_deck_whose_judgment_default_is_undefined())+ pipe_judge = _pipe_judge_naming_no_model()++ with pytest.raises(ModelDeckChoiceUnresolvedError) as exc_info, translate_to_validate_bundle_error():+ pipe_judge.validate_inputs_with_library()++ deck_fault = exc_info.value+ assert deck_fault.deck_setting == "judgment.choice_default"+ assert deck_fault.resolve_error_code() == PipelexErrorCode.CONFIG_INVALID++ strict_payload = deck_fault.to_error_report().to_dict(disclosure_mode=DisclosureMode.STRICT)+ assert strict_payload["code"] == PipelexErrorCode.CONFIG_INVALID+ assert strict_payload["error_type"] == "ModelDeckChoiceUnresolvedError"+ assert strict_payload["error_domain"] == "config"+ assert strict_payload["message"] == INTERNAL_ERROR_PLACEHOLDER+ assert "validation_errors" not in strict_payload++ def test_a_model_the_step_names_is_still_located_on_the_pipe(self) -> None:+ """Only the deck's own miss passes through: a reference the method wrote is the caller's unknown model."""+ pipe_judge = _pipe_judge_naming_no_model()+ not_found = ModelChoiceNotFoundError(+ message="The judgment model '$unknown-method-preset' is not defined",+ model_type=ModelType.JUDGMENT,+ model_choice="$unknown-method-preset",+ )++ with pytest.raises(PipeOperatorModelChoiceError) as exc_info, pipe_judge.locating_model_choice(field_name="model"):+ raise not_found++ located = exc_info.value+ assert located.__cause__ is not_found+ assert located.field_name == "model"+ assert located.to_error_report().code == CoreCode.MODEL_UNKNOWNdiff --git a/tests/unit/pipelex/pipe_operators/shared/test_llm_setting_check.py b/tests/unit/pipelex/pipe_operators/shared/test_llm_setting_check.pyindex 0eb4e74bf..2cb2c1201 100644--- a/tests/unit/pipelex/pipe_operators/shared/test_llm_setting_check.py+++ b/tests/unit/pipelex/pipe_operators/shared/test_llm_setting_check.py@@ -4,12 +4,14 @@ from types import SimpleNamespacefrom typing import TYPE_CHECKINGimport pytest+from mthds.protocol.problem.registry import CoreCodefrom pipelex.cogt.exceptions import LLMCapabilityError, LLMSettingRefusedErrorfrom pipelex.cogt.llm.llm_job_components import ReasoningEffortfrom pipelex.cogt.llm.llm_setting import LLMModelChoice, LLMSettingfrom pipelex.cogt.models.model_reference import ModelReferencefrom pipelex.core.pipes.exceptions import PipeValidationError+from pipelex.errors.error_codes import error_code_specfrom pipelex.pipe_operators.shared.llm_setting_check import refuse_llm_setting_its_model_refusesfrom pipelex.validation_error_types import PipeValidationErrorType@@ -175,4 +177,5 @@ class TestLLMSettingCheck:)message = str(exc_info.value)assert "internal" not in message- assert "which the model it resolves to refuses: LLM capability. " in message+ capability_title = error_code_spec(CoreCode.MODEL_CAPABILITY_UNSUPPORTED).title.rstrip(".")+ assert f"which the model it resolves to refuses: {capability_title}. " in messagediff --git a/tests/unit/pipelex/pipe_run/test_delivery_executor.py b/tests/unit/pipelex/pipe_run/test_delivery_executor.pyindex c56b84233..f173db50b 100644--- a/tests/unit/pipelex/pipe_run/test_delivery_executor.py+++ b/tests/unit/pipelex/pipe_run/test_delivery_executor.py@@ -4,10 +4,11 @@ import socketfrom datetime import UTC, datetimeimport pytest+from mthds.protocol.problem.registry import CoreCodefrom pytest_mock import MockerFixture, MockTypefrom pipelex import log-from pipelex.base_exceptions import ErrorDomain, ErrorReport+from pipelex.base_exceptions import ErrorReportfrom pipelex.cogt.inference.error_classification import ProviderErrorMetadata, UserAction, UserActionKindfrom pipelex.cogt.inference.provider_name import ProviderNamefrom pipelex.cogt.llm.llm_report import LLMTokensUsage@@ -881,24 +882,24 @@ class TestDeliveryExecutor:mock_client.post = mocker.AsyncMock(return_value=mock_response)mocker.patch("pipelex.pipe_run.delivery_executor.httpx.AsyncClient", return_value=mock_client)- error_report = ErrorReport(+ error_report = ErrorReport.make_for_code(+ code=CoreCode.PROVIDER_RATE_LIMITED,error_type="LLMCompletionError",message="provider returned 429",- title="AI inference failed",- type_uri="https://docs.pipelex.com/latest/errors/llm-completion-error/",- error_category="transient",- error_domain=ErrorDomain.RUNTIME,- retryable=True,user_action=UserAction(kind=UserActionKind.WAIT_AND_RETRY, detail="Wait a moment and retry"),- model="gpt-4o-mini",- provider="openai",- provider_metadata=ProviderErrorMetadata(- provider=ProviderName.OPENAI,- sdk_exception_type="RateLimitError",- message="429 Too Many Requests",- status_code=429,- retry_after_seconds=2.5,- ),+ ).model_copy(+ update={+ "error_category": "transient",+ "model": "gpt-4o-mini",+ "provider": "openai",+ "provider_metadata": ProviderErrorMetadata(+ provider=ProviderName.OPENAI,+ sdk_exception_type="RateLimitError",+ message="429 Too Many Requests",+ status_code=429,+ retry_after_seconds=2.5,+ ),+ })executor = DeliveryExecutor()@@ -1014,15 +1015,11 @@ class TestDeliveryExecutor:(DeliveryStatus.COMPLETED, None),(DeliveryStatus.FAILED,- ErrorReport(+ ErrorReport.make_for_code(+ code=CoreCode.PROVIDER_RATE_LIMITED,error_type="LLMCompletionError",message="provider returned 429",- title="AI inference failed",- type_uri="https://docs.pipelex.com/latest/errors/llm-completion-error/",- error_category="transient",- error_domain=ErrorDomain.RUNTIME,- retryable=True,- ),+ ).model_copy(update={"error_category": "transient"}),),],)diff --git a/tests/unit/pipelex/pipe_run/test_located_failure.py b/tests/unit/pipelex/pipe_run/test_located_failure.pyindex 642884bde..8270f7787 100644--- a/tests/unit/pipelex/pipe_run/test_located_failure.py+++ b/tests/unit/pipelex/pipe_run/test_located_failure.py@@ -1,13 +1,15 @@from __future__ import annotationsimport pytest+from mthds.protocol.problem.registry import CoreCodefrom typing_extensions import overridefrom pipelex.base_exceptions import INTERNAL_ERROR_PLACEHOLDER, DisclosureMode, ErrorDomain, ErrorReport, PipelexError-from pipelex.cogt.exceptions import CogtError, InferenceErrorCategory+from pipelex.cogt.exceptions import CogtError, InferenceErrorCategory, LLMCompletionErrorfrom pipelex.cogt.inference.error_classification import UserAction, UserActionKindfrom pipelex.core.memory.absence import AbsenceKind, AbsenceRecordfrom pipelex.core.pipes.inputs.exceptions import OptionalValueAbsentError+from pipelex.errors.error_codes import error_code_specfrom pipelex.pipe_run.exceptions import PipeRouterError, find_failure_locationfrom pipelex.pipe_run.located_failure import compose_located_message, find_foreign_fault, find_root_fault, make_unexpected_failurefrom pipelex.pipeline.exceptions import PipelineExecutionError@@ -106,7 +108,9 @@ class TestLocatedFailureReport:def test_identity_and_message_are_the_root_faults(self) -> None:"""Through the router, a bridge and the runner, the report is the root fault's, located once."""- root_fault = CogtError(message="rate limited", error_category=InferenceErrorCategory.TRANSIENT)+ root_fault = LLMCompletionError(message="rate limited", error_category=InferenceErrorCategory.TRANSIENT).with_error_code(+ CoreCode.PROVIDER_RATE_LIMITED+ )located = _locate(root_fault, pipe_stack=["flow", "analyze", "gen_ideas"])bridge_error = PipelexBridgeDispatchError(f"Pipe execution failed in DIRECT mode for pipe 'flow': {located}")bridge_error.__cause__ = located@@ -118,12 +122,14 @@ class TestLocatedFailureReport:assert run_failure.pipe_stack == ["flow", "analyze", "gen_ideas"]report = run_failure.to_error_report()- assert report.error_type == "CogtError"- assert report.title == CogtError.title()- assert report.type_uri == CogtError.type_uri()+ assert report.error_type == "LLMCompletionError"+ root_spec = error_code_spec(CoreCode.PROVIDER_RATE_LIMITED)+ assert report.code == root_spec.code+ assert report.title == root_spec.title+ assert report.type_uri == root_spec.type_uriassert report.message == "Pipe 'gen_ideas' failed (flow → analyze → gen_ideas): rate limited"assert run_failure.message == report.message- # Classification inherited from the chain, untouched by the floor.+ # Classification inherited from the chain, and the retry verdict the root fault's code decides.assert report.error_category == InferenceErrorCategory.TRANSIENTassert report.retryable is Trueassert report == located.to_error_report()@@ -186,7 +192,8 @@ class TestLocatedFailureReport:assert report.error_type == "CogtError"assert report.message == "Pipe 'summarize' failed (flow → summarize): model refused"- assert report.error_domain == ErrorDomain.CONFIG+ assert report.code == leaf_report.code+ assert report.error_domain == leaf_report.error_domaindef test_a_cyclic_chain_reports_the_wrapper_as_itself(self) -> None:"""A chain that loops back to the wrapper cannot make the report recurse."""diff --git a/tests/unit/pipelex/pipe_run/test_pipe_router_run.py b/tests/unit/pipelex/pipe_run/test_pipe_router_run.pyindex 9111f2db3..addbfd1b3 100644--- a/tests/unit/pipelex/pipe_run/test_pipe_router_run.py+++ b/tests/unit/pipelex/pipe_run/test_pipe_router_run.py@@ -1,11 +1,12 @@from typing import TYPE_CHECKING, castimport pytest+from mthds.protocol.problem.registry import CoreCodefrom pydantic import BaseModel, ValidationErrorfrom typing_extensions import overridefrom pipelex.base_exceptions import ErrorReport, PipelexError, PipelexUnexpectedError-from pipelex.cogt.exceptions import CogtError, InferenceErrorCategory+from pipelex.cogt.exceptions import CogtError, InferenceErrorCategory, LLMCompletionErrorfrom pipelex.core.pipes.exceptions import PipeRunErrorfrom pipelex.core.pipes.pipe_output import PipeOutputfrom pipelex.core.stuffs.exceptions import StuffFactoryError@@ -111,15 +112,19 @@ class TestPipeRouterRun:Pins the "direct = single attempt" contract against a future re-introduction of a retry loop.The error leaves located at the pipe, chained to the CogtError, and still reports as it."""- error = CogtError(message="rate limited", error_category=InferenceErrorCategory.TRANSIENT)+ error = LLMCompletionError(message="rate limited", error_category=InferenceErrorCategory.TRANSIENT).with_error_code(+ CoreCode.PROVIDER_RATE_LIMITED+ )router = _StubPipeRouter(error=error)with pytest.raises(PipeRouterError) as exc_info:await router.run(_make_pipe_job())assert exc_info.value.__cause__ is error- assert exc_info.value.to_error_report().error_type == "CogtError"- assert exc_info.value.to_error_report().retryable is True+ report = exc_info.value.to_error_report()+ assert report.error_type == "LLMCompletionError"+ assert report.code == CoreCode.PROVIDER_RATE_LIMITED+ assert report.retryable is Trueassert router.call_count == 1async def test_pipe_run_error_wraps_as_pipe_router_error(self) -> None:diff --git a/tests/unit/pipelex/pipeline/test_dry_run_failure_location.py b/tests/unit/pipelex/pipeline/test_dry_run_failure_location.pyindex 19c02fda0..77aef3836 100644--- a/tests/unit/pipelex/pipeline/test_dry_run_failure_location.py+++ b/tests/unit/pipelex/pipeline/test_dry_run_failure_location.py@@ -2,12 +2,15 @@ from pathlib import Pathfrom typing import ClassVarimport pytest+from mthds.protocol.problem.registry import CoreCodefrom polyfactory.exceptions import FactoryExceptionfrom pytest_mock import MockerFixture-from pipelex.base_exceptions import ErrorDomain, PipelexError+from pipelex.base_exceptions import PipelexErrorfrom pipelex.core.exceptions import DryRunFailureErrorDatafrom pipelex.core.pipes.exceptions import PipeRunError+from pipelex.errors.error_codes import error_code_spec+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.pipe_run.exceptions import DryRunError, PipeRouterErrorfrom pipelex.pipeline.bundle_validator import (BundleValidator,@@ -21,12 +24,12 @@ from pipelex.system.pipe_run_mode import PipeRunModeclass _CallerFacingMethodFaultError(PipelexError):- error_domain = ErrorDomain.INPUT+ error_code = CoreCode.METHOD_WIRING_INVALID_authors_caller_facing_message: ClassVar[bool] = Trueclass _StorageFaultError(PipelexError):- error_domain = ErrorDomain.CONFIG+ error_code = PipelexErrorCode.STORAGE_UNAVAILABLEclass TestDryRunFailureLocation:@@ -93,8 +96,11 @@ class TestDryRunFailureLocation:("error", "expected_text"),[(_CallerFacingMethodFaultError("branch 'ideas' is plural"), "branch 'ideas' is plural"),- (_StorageFaultError("bucket s3://internal-bucket refused the write"), _StorageFaultError.title()),- (PipeRunError(message="expression rendered nothing", run_mode=PipeRunMode.DRY, pipe_code="route"), PipeRunError.title()),+ (_StorageFaultError("bucket s3://internal-bucket refused the write"), error_code_spec(PipelexErrorCode.STORAGE_UNAVAILABLE).title),+ (+ PipeRunError(message="expression rendered nothing", run_mode=PipeRunMode.DRY, pipe_code="route"),+ error_code_spec(CoreCode.RUNTIME_UNEXPECTED).title,+ ),(FactoryException("polyfactory internals"), "The dry run could not generate mock data for this pipe"),],ids=["caller_facing", "config_fault", "not_caller_facing", "foreign"],diff --git a/tests/unit/pipelex/pipeline/test_input_format_errors.py b/tests/unit/pipelex/pipeline/test_input_format_errors.pyindex 43d24de37..36515fc39 100644--- a/tests/unit/pipelex/pipeline/test_input_format_errors.py+++ b/tests/unit/pipelex/pipeline/test_input_format_errors.py@@ -6,10 +6,16 @@ leave the caller with nothing to act on. The family sits in the input domain, so"""import pytest+from mthds.protocol.problem.registry import CoreCodefrom pipelex.base_exceptions import INTERNAL_ERROR_PLACEHOLDER, DisclosureMode, ErrorDomain, error_domain_to_http_statusfrom pipelex.cogt.inference.error_classification import UserActionKind-from pipelex.pipeline.exceptions import PipelineInputContentError, PipelineInputFormatError, PipelineInputNotAnImageError+from pipelex.pipeline.exceptions import (+ PipelineInputContentError,+ PipelineInputFormatError,+ PipelineInputFormatUnsupportedError,+ PipelineInputNotAnImageError,+)NOT_AN_IMAGE_MESSAGE = ("Input 'referral_letter' expects an image, but the file is a PDF document (.pdf). Give an image file such as PNG, JPEG or WebP."@@ -17,20 +23,22 @@ NOT_AN_IMAGE_MESSAGE = (class TestPipelineInputFormatErrors:- @pytest.mark.parametrize("error_class", [PipelineInputFormatError, PipelineInputNotAnImageError])+ @pytest.mark.parametrize("error_class", [PipelineInputNotAnImageError, PipelineInputFormatUnsupportedError])def test_the_family_is_an_input_content_error_the_caller_can_fix(self, error_class: type[PipelineInputFormatError]):error = error_class(NOT_AN_IMAGE_MESSAGE)+ report = error.to_error_report()assert isinstance(error, PipelineInputContentError)- assert error.error_domain == ErrorDomain.INPUT- assert error_domain_to_http_status(error.error_domain) == 422+ assert report.code == CoreCode.INPUT_FILE_TYPE_UNSUPPORTED+ assert report.error_domain == ErrorDomain.INPUT+ assert error_domain_to_http_status(report.error_domain) == 422assert error.user_action is not Noneassert error.user_action.kind == UserActionKind.CHANGE_INPUTdef test_not_an_image_is_a_format_error(self):assert issubclass(PipelineInputNotAnImageError, PipelineInputFormatError)- @pytest.mark.parametrize("error_class", [PipelineInputFormatError, PipelineInputNotAnImageError])+ @pytest.mark.parametrize("error_class", [PipelineInputNotAnImageError, PipelineInputFormatUnsupportedError])def test_the_message_survives_strict_disclosure(self, error_class: type[PipelineInputFormatError]):strict = error_class(NOT_AN_IMAGE_MESSAGE).to_error_report().to_dict(disclosure_mode=DisclosureMode.STRICT)diff --git a/tests/unit/pipelex/pipeline/test_inputs_template.py b/tests/unit/pipelex/pipeline/test_inputs_template.pyindex 2364d39b7..ac9689fc9 100644--- a/tests/unit/pipelex/pipeline/test_inputs_template.py+++ b/tests/unit/pipelex/pipeline/test_inputs_template.py@@ -8,8 +8,10 @@ from types import SimpleNamespacefrom typing import TYPE_CHECKING, Anyimport pytest+from mthds.protocol.problem.registry import CoreCodefrom pipelex.core.pipes.inputs.exceptions import NoInputsRequiredError+from pipelex.pipeline.exceptions import MethodEntryErrorfrom pipelex.pipeline.inputs_template import build_inputs_for_pipeif TYPE_CHECKING:@@ -68,7 +70,7 @@ class TestBuildInputsForPipe:)def test_mthds_contents_without_any_main_pipe_raises(self, ops_mocks: dict[str, Any]) -> None:- """When no blueprint declares a main_pipe and no pipe code is given, a ValueError is raised."""+ """When no blueprint declares a main_pipe and no pipe code is given, the request names no pipe to start at."""ops_mocks["validate_bundle"].return_value = SimpleNamespace(blueprints=[SimpleNamespace(main_pipe=None, domain="alpha_domain"),@@ -76,9 +78,11 @@ class TestBuildInputsForPipe:])- with pytest.raises(ValueError, match="Bundle does not declare a main_pipe"):+ with pytest.raises(MethodEntryError, match="Bundle does not declare a main_pipe") as exc_info:asyncio.run(build_inputs_for_pipe(mthds_contents=["mthds content"]))+ assert exc_info.value.to_error_report().code == CoreCode.REQUEST_PIPE_UNSPECIFIED+def test_mthds_contents_explicit_pipe_code_skips_scan(self, ops_mocks: dict[str, Any]) -> None:"""An explicit pipe code selects the pipe verbatim, and the result names the pipe it resolved to, qualified."""ops_mocks["get_required_entry_pipe"].return_value = SimpleNamespace(@@ -105,14 +109,15 @@ class TestBuildInputsForPipe:assert result["pipe_ref"] == "demo_domain.bundle_main"def test_bundle_path_without_main_pipe_raises_with_path(self, ops_mocks: dict[str, Any], tmp_path: Path) -> None:- """A bundle file without a main_pipe raises a ValueError naming the bundle path."""+ """A bundle file without a main_pipe is refused with a message naming the bundle path."""bundle_path = tmp_path / "demo.mthds"ops_mocks["validate_bundle"].return_value = SimpleNamespace(blueprints=[SimpleNamespace(main_pipe=None, domain="demo_domain")])- with pytest.raises(ValueError, match="does not declare a main_pipe") as exc_info:+ with pytest.raises(MethodEntryError, match="does not declare a main_pipe") as exc_info:asyncio.run(build_inputs_for_pipe(bundle_path=bundle_path))assert str(bundle_path) in str(exc_info.value)+ assert exc_info.value.to_error_report().code == CoreCode.REQUEST_PIPE_UNSPECIFIEDdef test_bundle_path_explicit_pipe_code_wins(self, ops_mocks: dict[str, Any], tmp_path: Path) -> None:"""With a bundle path, an explicit pipe code overrides the bundle's main_pipe, and the result names it qualified."""@@ -147,9 +152,11 @@ class TestBuildInputsForPipe:def test_no_bundle_and_no_pipe_code_raises(self, ops_mocks: dict[str, Any]) -> None:"""Neither a bundle nor a pipe code is an immediate error."""- with pytest.raises(ValueError, match="No pipe code specified"):+ with pytest.raises(MethodEntryError, match="No pipe code specified") as exc_info:asyncio.run(build_inputs_for_pipe())+ assert exc_info.value.to_error_report().code == CoreCode.REQUEST_PIPE_UNSPECIFIED+ops_mocks["get_required_entry_pipe"].assert_not_called()def test_happy_path_return_shape(self, ops_mocks: dict[str, Any]) -> None:diff --git a/tests/unit/pipelex/pipeline/test_refusal_verdict_arms.py b/tests/unit/pipelex/pipeline/test_refusal_verdict_arms.pyindex 719119620..b1ef4d26a 100644--- a/tests/unit/pipelex/pipeline/test_refusal_verdict_arms.py+++ b/tests/unit/pipelex/pipeline/test_refusal_verdict_arms.py@@ -1,28 +1,29 @@-from typing import ClassVar-import pytest+from mthds.protocol.problem.registry import CoreCode-from pipelex.base_exceptions import ErrorDomain, PipelexError, SecurityError, ValidationErrorCategory, ValidationErrorItem+from pipelex.base_exceptions import PipelexError, SecurityError, ValidationErrorCategory, ValidationErrorItemfrom pipelex.cogt.model_backends.model_type import ModelTypefrom pipelex.core.exceptions import DryRunFailureErrorDatafrom pipelex.core.pipes.exceptions import PipeLoadRefusalError, PipeOperatorModelChoiceError+from pipelex.errors.error_codes import error_code_spec+from pipelex.errors.registry.pipelex_codes import PipelexErrorCode+from pipelex.libraries.exceptions import LibraryErrorfrom pipelex.pipeline.exceptions import ValidateBundleErrorfrom pipelex.pipeline.validate_bundle_translation import translate_to_validate_bundle_errorfrom pipelex.validation_error_types import PipeValidationErrorTypeclass _CallerFacingInputRefusalError(PipelexError):- error_domain = ErrorDomain.INPUT+ error_code = CoreCode.METHOD_INVALID_authors_caller_facing_message = Trueclass _InternalInputRefusalError(PipelexError):- error_domain = ErrorDomain.INPUT- _declared_title: ClassVar[str | None] = "Harbour board refusal"+ error_code = CoreCode.METHOD_SCHEMA_VIOLATIONclass _RuntimeFaultError(PipelexError):- error_domain = ErrorDomain.RUNTIME+ error_code = CoreCode.RUNTIME_UNAVAILABLEclass _UnclassifiedFaultError(PipelexError):@@ -30,10 +31,14 @@ class _UnclassifiedFaultError(PipelexError):class _InputSecurityRefusalError(SecurityError):- error_domain = ErrorDomain.INPUT+ error_code = CoreCode.SECURITY_TEMPLATE_REFUSED_authors_caller_facing_message = True+# What a non-caller-facing refusal's item reads: its code's title.+_INTERNAL_REFUSAL_TITLE = error_code_spec(CoreCode.METHOD_SCHEMA_VIOLATION).title++def _verdict_items(refusal: BaseException) -> tuple[ValidateBundleError, list[ValidationErrorItem]]:with pytest.raises(ValidateBundleError) as raised, translate_to_validate_bundle_error():raise refusal@@ -57,7 +62,7 @@ class TestRefusalVerdictArms:def test_non_caller_facing_input_refusal_is_named_by_its_title(self) -> None:_, items = _verdict_items(_InternalInputRefusalError("internal detail: registry slot 7 is stale"))- assert [item.message for item in items] == ["Harbour board refusal"]+ assert [item.message for item in items] == [_INTERNAL_REFUSAL_TITLE]def test_located_refusal_is_one_pipe_item_with_pipe_domain_and_source(self) -> None:cause = _InternalInputRefusalError("internal detail: registry slot 7 is stale")@@ -71,7 +76,7 @@ class TestRefusalVerdictArms:pipe_code="write_tide_note",domain_code="tide_tables",source="tides.mthds",- message="Pipe 'write_tide_note' could not be loaded: Harbour board refusal",+ message=f"Pipe 'write_tide_note' could not be loaded: {_INTERNAL_REFUSAL_TITLE}",)]@@ -112,8 +117,10 @@ class TestRefusalVerdictArms:_RuntimeFaultError("the worker lost its connection"),_UnclassifiedFaultError("something nobody classified"),_InputSecurityRefusalError("a fetch was blocked"),+ LibraryError("the library manager lost a library it had opened"),+ LibraryError("one PipeFunc source sits in two library directories").with_error_code(PipelexErrorCode.CONFIG_INVALID),],- ids=["runtime", "unclassified", "security"],+ ids=["runtime", "unclassified", "security", "library_invariant", "library_configuration"],)def test_no_verdict_faults_propagate_unchanged(self, fault: PipelexError) -> None:"""A failure of the tool or its environment, and a security refusal, are never reported as the bundle's fault."""diff --git a/tests/unit/pipelex/pipeline/test_runner_protocol_surfaces.py b/tests/unit/pipelex/pipeline/test_runner_protocol_surfaces.pyindex 01ff04800..d769a9505 100644--- a/tests/unit/pipelex/pipeline/test_runner_protocol_surfaces.py+++ b/tests/unit/pipelex/pipeline/test_runner_protocol_surfaces.py@@ -14,9 +14,12 @@ from typing import TYPE_CHECKING, Anyimport pytestfrom mthds.protocol.exceptions import PipelineRequestErrorfrom mthds.protocol.models import ModelCategory as MthdsModelCategory+from mthds.protocol.problem.registry import CoreCodefrom mthds.protocol.protocol import PROTOCOL_VERSIONfrom pipelex.cogt.models.model_listing import ModelCategory+from pipelex.pipe_run.exceptions import AsyncExecutionNotEnabledError+from pipelex.pipeline.request_exceptions import PipelexRequestErrorfrom pipelex.pipeline.runner import (PipelexModelDeck,PipelexMTHDSProtocol,@@ -53,7 +56,10 @@ class TestRunnerProtocolSurfaces:with pytest.raises(PipelineRequestError) as exc_info:await runner.execute(pipe_code="any_pipe", extra={"zed": 1, "abc": 2})- assert str(exc_info.value) == "The local runtime defines no extension args; got ['abc', 'zed']."+ assert isinstance(exc_info.value, PipelexRequestError)+ assert exc_info.value.message == "The local runtime defines no extension args; got ['abc', 'zed']."+ assert exc_info.value.problem.code == CoreCode.REQUEST_UNSUPPORTED+ assert exc_info.value.to_error_report().code == CoreCode.REQUEST_UNSUPPORTEDasync def test_validate_rejects_blank_graph_pipe_code_extra(self) -> None:"""A blank explicit graph target must not silently fall back to main_pipe."""@@ -65,15 +71,19 @@ class TestRunnerProtocolSurfaces:extra={"graph_pipe_code": " "},)- assert str(exc_info.value) == "validate extra 'graph_pipe_code' must not be blank when provided."+ assert isinstance(exc_info.value, PipelexRequestError)+ assert exc_info.value.message == "validate extra 'graph_pipe_code' must not be blank when provided."+ assert exc_info.value.field == "extra.graph_pipe_code"+ assert exc_info.value.to_error_report().code == CoreCode.REQUEST_INVALIDasync def test_start_raises_not_implemented_pointing_at_execute(self) -> None:"""The local runtime does not implement async start; the message redirects to execute."""runner = PipelexMTHDSProtocol()- with pytest.raises(NotImplementedError) as exc_info:+ with pytest.raises(AsyncExecutionNotEnabledError) as exc_info:await runner.start(pipe_code="any_pipe")+ assert exc_info.value.to_error_report().code == CoreCode.RUNTIME_UNSUPPORTEDassert "execute" in str(exc_info.value)assert "not implemented by the local runtime" in str(exc_info.value)diff --git a/tests/unit/pipelex/plugins/test_error_code_declaration_seam.py b/tests/unit/pipelex/plugins/test_error_code_declaration_seam.pynew file mode 100644index 000000000..e1882ded2--- /dev/null+++ b/tests/unit/pipelex/plugins/test_error_code_declaration_seam.py@@ -0,0 +1,88 @@+"""A plugin declares the public codes it raises at registration; the registrar binds each to the registry, refusing an unregistered one."""++from __future__ import annotations++from types import SimpleNamespace+from typing import TYPE_CHECKING, cast++import pytest+from mthds.protocol.problem.registry import CoreCode++from pipelex.errors.registry.pipelex_codes import PipelexErrorCode+from pipelex.plugins.contract import PLUGIN_API_VERSION+from pipelex.plugins.exceptions import PluginErrorCodeNotRegisteredError+from pipelex.plugins.plugin_group import PluginGroup+from pipelex.plugins.registrar import PluginOrigin, PluginRegistrar++if TYPE_CHECKING:+ from pipelex.system.configuration.configs import PipelexConfig+++def _make_registrar() -> PluginRegistrar:+ return PluginRegistrar(config=cast("PipelexConfig", SimpleNamespace(runtime=SimpleNamespace(plugins=SimpleNamespace(disabled=[])))))+++class TestErrorCodeDeclarationSeam:+ def test_declared_codes_are_bound_to_the_registry_and_attributed(self) -> None:+ """A core code and a Pipelex code, given as strings, are bound to their registry constants under the plugin's name."""+ registrar = _make_registrar()+ discovery = registrar.begin_plugin(name="alpha", origin=PluginOrigin.EXTERNAL, targets_api=PLUGIN_API_VERSION, group=None)++ registrar.declare_error_codes(codes=["model.unavailable", "pipelex.docgen.content_unprintable"])++ assert registrar.declared_error_codes == {"alpha": (CoreCode.MODEL_UNAVAILABLE, PipelexErrorCode.DOCGEN_CONTENT_UNPRINTABLE)}+ assert discovery.contributions == ["error codes model.unavailable, pipelex.docgen.content_unprintable"]++ def test_a_plugin_declaring_twice_accumulates_its_codes_once_each(self) -> None:+ registrar = _make_registrar()+ registrar.begin_plugin(name="alpha", origin=PluginOrigin.EXTERNAL, targets_api=PLUGIN_API_VERSION, group=None)++ registrar.declare_error_codes(codes=[CoreCode.PROVIDER_FAILED])+ registrar.declare_error_codes(codes=["provider.failed", "provider.timeout"])++ assert registrar.declared_error_codes == {"alpha": (CoreCode.PROVIDER_FAILED, CoreCode.PROVIDER_TIMEOUT)}++ def test_two_plugins_may_declare_the_same_code(self) -> None:+ """A public code means one thing whoever raises it, so declaring it is no claim another plugin collides with."""+ registrar = _make_registrar()+ registrar.begin_plugin(name="alpha", origin=PluginOrigin.EXTERNAL, targets_api=PLUGIN_API_VERSION, group=None)+ registrar.declare_error_codes(codes=["runtime.unexpected"])+ registrar.begin_plugin(name="beta", origin=PluginOrigin.EXTERNAL, targets_api=PLUGIN_API_VERSION, group=PluginGroup.KERNEL)+ registrar.declare_error_codes(codes=["runtime.unexpected"])++ assert registrar.declared_error_codes == {"alpha": (CoreCode.RUNTIME_UNEXPECTED,), "beta": (CoreCode.RUNTIME_UNEXPECTED,)}++ @pytest.mark.parametrize(+ "unregistered_code",+ [+ "pig-07",+ "model.unknwon",+ "pipelex.manifold.body_too_large",+ "",+ ],+ )+ def test_an_unregistered_code_refuses_the_boot_as_a_broken_plugin(self, unregistered_code: str) -> None:+ """The refusal names the plugin and the code, carries `pipelex.plugin.broken`, and binds none of the plugin's codes."""+ registrar = _make_registrar()+ discovery = registrar.begin_plugin(name="alpha", origin=PluginOrigin.EXTERNAL, targets_api=PLUGIN_API_VERSION, group=None)++ with pytest.raises(PluginErrorCodeNotRegisteredError) as exc_info:+ registrar.declare_error_codes(codes=["model.unavailable", unregistered_code])++ refusal = exc_info.value+ assert refusal.plugin_name == "alpha"+ assert refusal.code == unregistered_code+ assert refusal.resolve_error_code() == PipelexErrorCode.PLUGIN_BROKEN+ assert f"'{unregistered_code}'" in refusal.message+ assert "alpha" in refusal.message+ assert not registrar.declared_error_codes+ assert not discovery.contributions++ def test_an_empty_declaration_records_nothing(self) -> None:+ registrar = _make_registrar()+ discovery = registrar.begin_plugin(name="alpha", origin=PluginOrigin.EXTERNAL, targets_api=PLUGIN_API_VERSION, group=None)++ registrar.declare_error_codes(codes=[])++ assert not registrar.declared_error_codes+ assert not discovery.contributionsdiff --git a/tests/unit/pipelex/plugins/test_http_error_mapper_seam.py b/tests/unit/pipelex/plugins/test_http_error_mapper_seam.pyindex c9c0aa463..7ece8416d 100644--- a/tests/unit/pipelex/plugins/test_http_error_mapper_seam.py+++ b/tests/unit/pipelex/plugins/test_http_error_mapper_seam.py@@ -6,6 +6,7 @@ from types import SimpleNamespacefrom typing import TYPE_CHECKING, castimport pytest+from mthds.protocol.problem.registry import CoreCodefrom pipelex.base_exceptions import ErrorReportfrom pipelex.plugins.contract import PLUGIN_API_VERSION@@ -25,13 +26,7 @@ def _make_registrar() -> PluginRegistrar:def _to_report(exc: Exception) -> ErrorReport:- return ErrorReport(- error_type="FakeTransportError",- message=str(exc),- title="Fake transport error",- type_uri="https://errors.pipelex.com/fake-transport-error",- retryable=True,- )+ return ErrorReport.make_for_code(code=CoreCode.PROVIDER_UNAVAILABLE, error_type="FakeTransportError", message=str(exc))class TestHttpErrorMapperSeam:@@ -47,9 +42,9 @@ class TestHttpErrorMapperSeam:mappers = registrar.get_http_error_mappers()assert set(mappers) == {_FakeTransportError}report = mappers[_FakeTransportError](_FakeTransportError("server unreachable"))+ assert report.code == CoreCode.PROVIDER_UNAVAILABLEassert report.retryable is Trueassert report.message == "server unreachable"- assert report.type_uri == "https://errors.pipelex.com/fake-transport-error"def test_provider_resolved_lazily_not_at_registration(self) -> None:"""The exc-type provider runs only on get_http_error_mappers (read time), never at register — the import-light invariant."""diff --git a/tests/unit/pipelex/plugins/test_service_error_codes_seam.py b/tests/unit/pipelex/plugins/test_service_error_codes_seam.pyindex 1dadd7b51..8f78288bc 100644--- a/tests/unit/pipelex/plugins/test_service_error_codes_seam.py+++ b/tests/unit/pipelex/plugins/test_service_error_codes_seam.py@@ -6,6 +6,7 @@ from types import SimpleNamespacefrom typing import TYPE_CHECKING, castimport pytest+from mthds.protocol.problem.registry import CoreCodefrom pipelex.cogt.exceptions import InferenceErrorCategoryfrom pipelex.cogt.inference.error_classification import MODEL_NOT_ALLOWED_ERROR_CODE, UserActionKind@@ -29,6 +30,7 @@ def _entry(code: str) -> ServiceErrorCode:code=code,category=InferenceErrorCategory.CONTENT,user_action_kind=UserActionKind.CHANGE_INPUT,+ error_code=CoreCode.INPUT_TOO_LARGE,detail=f"advice for {code}",)diff --git a/tests/unit/pipelex/providers/docling/test_data.py b/tests/unit/pipelex/providers/docling/test_data.pyindex ca31a55f9..96873db7b 100644--- a/tests/unit/pipelex/providers/docling/test_data.py+++ b/tests/unit/pipelex/providers/docling/test_data.py@@ -35,18 +35,18 @@ class DoclingErrorHandlingTestData:UserActionKind.CHANGE_INPUT,),(- "io_error_transient",+ "local_io_error",OSError,"Disk read error on /tmp/doc.pdf",- InferenceErrorCategory.TRANSIENT,- UserActionKind.WAIT_AND_RETRY,+ InferenceErrorCategory.UNKNOWN,+ UserActionKind.CONTACT_SUPPORT,),("permission_error_subclass_of_os_error",PermissionError,"Permission denied: /tmp/restricted.pdf",- InferenceErrorCategory.TRANSIENT,- UserActionKind.WAIT_AND_RETRY,+ InferenceErrorCategory.UNKNOWN,+ UserActionKind.CONTACT_SUPPORT,),("not_implemented_error_subclass_of_runtime_error",diff --git a/tests/unit/pipelex/providers/docling/test_docling_worker_error_handling.py b/tests/unit/pipelex/providers/docling/test_docling_worker_error_handling.pyindex d5245afcf..96f8a8a41 100644--- a/tests/unit/pipelex/providers/docling/test_docling_worker_error_handling.py+++ b/tests/unit/pipelex/providers/docling/test_docling_worker_error_handling.py@@ -5,6 +5,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKINGimport pytest+from mthds.protocol.problem.registry import CoreCodeif TYPE_CHECKING:from pytest_mock import MockerFixture@@ -86,7 +87,7 @@ class TestDoclingWorkerErrorHandling:assert report.error_type == "ExtractJobFailureError"async def test_error_report_for_io_error(self, mocker: MockerFixture) -> None:- """to_error_report() for OSError has TRANSIENT category and is retryable."""+ """A local disk failure is this machine's, not the input's and not one a retry is known to clear: runtime.unexpected."""worker = _make_docling_extract_worker(mocker)sdk_exc = OSError("Disk I/O failure")@@ -99,5 +100,6 @@ class TestDoclingWorkerErrorHandling:await worker._extract_from_source(source_uri="/tmp/test.pdf") # ruff: ignore[private-member-access, hardcoded-temp-file] # pyright: ignore[reportPrivateUsage]report = exc_info.value.to_error_report()- assert report.error_category == "transient"- assert report.retryable is True+ assert report.error_category == "unknown"+ assert report.code == CoreCode.RUNTIME_UNEXPECTED+ assert report.retryable is Falsediff --git a/tests/unit/pipelex/providers/docling/test_docling_worker_semantic.py b/tests/unit/pipelex/providers/docling/test_docling_worker_semantic.pyindex 502479e50..efd7c6a6f 100644--- a/tests/unit/pipelex/providers/docling/test_docling_worker_semantic.py+++ b/tests/unit/pipelex/providers/docling/test_docling_worker_semantic.py@@ -44,7 +44,7 @@ class TestDoclingWorkerSemantic:(FileNotFoundError, "No such file", InferenceErrorCategory.CONTENT, UserActionKind.CHANGE_INPUT),(ValueError, "Unsupported format", InferenceErrorCategory.CONTENT, UserActionKind.CHANGE_INPUT),(RuntimeError, "Conversion failed", InferenceErrorCategory.CONTENT, UserActionKind.CHANGE_INPUT),- (OSError, "Disk read error", InferenceErrorCategory.TRANSIENT, UserActionKind.WAIT_AND_RETRY),+ (OSError, "Disk read error", InferenceErrorCategory.UNKNOWN, UserActionKind.CONTACT_SUPPORT),],)async def test_local_exception_carries_semantic_user_action(diff --git a/tests/unit/pipelex/providers/fal/test_data.py b/tests/unit/pipelex/providers/fal/test_data.pyindex 298040d7f..4f09757ee 100644--- a/tests/unit/pipelex/providers/fal/test_data.py+++ b/tests/unit/pipelex/providers/fal/test_data.py@@ -49,10 +49,11 @@ class FalErrorHandlingTestData:UserActionKind.CHANGE_INPUT,),(+ # An image generation is billed and not idempotent, so a failure after it was sent is an unknown outcome."server_error_500",500,"Internal server error",- InferenceErrorCategory.TRANSIENT,+ InferenceErrorCategory.AMBIGUOUS,UserActionKind.WAIT_AND_RETRY,),]@@ -68,7 +69,7 @@ class FalErrorHandlingTestData:TIMEOUT_CASES: ClassVar[list[tuple[str, InferenceErrorCategory, UserActionKind]]] = [("request_timeout",- InferenceErrorCategory.TRANSIENT,+ InferenceErrorCategory.AMBIGUOUS,UserActionKind.WAIT_AND_RETRY,),]@@ -76,7 +77,7 @@ class FalErrorHandlingTestData:GENERIC_CLIENT_ERROR_CASES: ClassVar[list[tuple[str, InferenceErrorCategory, UserActionKind]]] = [("generic_fal_error",- InferenceErrorCategory.TRANSIENT,+ InferenceErrorCategory.AMBIGUOUS,UserActionKind.WAIT_AND_RETRY,),]diff --git a/tests/unit/pipelex/providers/fal/test_fal_img_gen_worker_semantic.py b/tests/unit/pipelex/providers/fal/test_fal_img_gen_worker_semantic.pyindex 886b8386a..59333ead9 100644--- a/tests/unit/pipelex/providers/fal/test_fal_img_gen_worker_semantic.py+++ b/tests/unit/pipelex/providers/fal/test_fal_img_gen_worker_semantic.py@@ -59,7 +59,8 @@ class TestFalImgGenWorkerSemantic:# Unhandled 4xx: non-retryable client error, not TRANSIENT.(409, InferenceErrorCategory.CONFIGURATION, UserActionKind.CHANGE_INPUT),(422, InferenceErrorCategory.CONFIGURATION, UserActionKind.CHANGE_INPUT),- (500, InferenceErrorCategory.TRANSIENT, UserActionKind.WAIT_AND_RETRY),+ # Billed and not idempotent: a 5xx after the request was sent is an unknown outcome.+ (500, InferenceErrorCategory.AMBIGUOUS, UserActionKind.WAIT_AND_RETRY),],)async def test_http_error_carries_semantic_user_action(@@ -125,7 +126,7 @@ class TestFalImgGenWorkerSemantic:with pytest.raises(ImgGenGenerationError) as exc_info:await worker._submit_and_get_result(img_gen_job=_make_img_gen_job(mocker), nb_images=1) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]- assert exc_info.value.error_category is InferenceErrorCategory.TRANSIENT+ assert exc_info.value.error_category is InferenceErrorCategory.AMBIGUOUSassert exc_info.value.user_action is not Noneassert exc_info.value.user_action.kind is UserActionKind.WAIT_AND_RETRYassert exc_info.value.provider_metadata is not None@@ -145,7 +146,7 @@ class TestFalImgGenWorkerSemantic:with pytest.raises(ImgGenGenerationError) as exc_info:await worker._submit_and_get_result(img_gen_job=_make_img_gen_job(mocker), nb_images=1) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]- assert exc_info.value.error_category is InferenceErrorCategory.TRANSIENT+ assert exc_info.value.error_category is InferenceErrorCategory.AMBIGUOUSassert exc_info.value.user_action is not Noneassert exc_info.value.user_action.kind is UserActionKind.WAIT_AND_RETRYassert exc_info.value.provider_metadata is not Nonediff --git a/tests/unit/pipelex/providers/fal/test_fal_worker_error_handling.py b/tests/unit/pipelex/providers/fal/test_fal_worker_error_handling.pyindex d299d60b8..4e1f6f005 100644--- a/tests/unit/pipelex/providers/fal/test_fal_worker_error_handling.py+++ b/tests/unit/pipelex/providers/fal/test_fal_worker_error_handling.py@@ -135,7 +135,7 @@ class TestFalWorkerErrorHandling:("_topic", "expected_category", "expected_user_action_kind"),FalErrorHandlingTestData.TIMEOUT_CASES,)- async def test_timeout_error_is_transient(+ async def test_timeout_error_is_an_unknown_outcome(self,mocker: MockerFixture,_topic: str,@@ -165,7 +165,7 @@ class TestFalWorkerErrorHandling:("_topic", "expected_category", "expected_user_action_kind"),FalErrorHandlingTestData.GENERIC_CLIENT_ERROR_CASES,)- async def test_generic_client_error_is_transient(+ async def test_generic_client_error_is_an_unknown_outcome(self,mocker: MockerFixture,_topic: str,diff --git a/tests/unit/pipelex/providers/google/test_google_img_gen_worker_error_handling.py b/tests/unit/pipelex/providers/google/test_google_img_gen_worker_error_handling.pyindex d3d88b3ea..b7462b7be 100644--- a/tests/unit/pipelex/providers/google/test_google_img_gen_worker_error_handling.py+++ b/tests/unit/pipelex/providers/google/test_google_img_gen_worker_error_handling.py@@ -169,7 +169,7 @@ class TestGoogleImgGenWorkerErrorHandling:assert exc_info.value.user_action is not Noneassert exc_info.value.user_action.kind is UserActionKind.CHANGE_INPUT- async def test_server_error_500_is_wait_and_retry(self, mocker: MockerFixture) -> None:+ async def test_server_error_500_is_an_unknown_outcome(self, mocker: MockerFixture) -> None:worker = _make_worker(mocker)sdk_exc = _make_google_server_error(500, "Internal server error")worker.genai_async_client.models.generate_content.side_effect = sdk_exc # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue]@@ -177,29 +177,32 @@ class TestGoogleImgGenWorkerErrorHandling:with pytest.raises(ImgGenGenerationError) as exc_info:await worker._gen_image(img_gen_job=_make_img_gen_job(mocker)) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]- assert exc_info.value.error_category is InferenceErrorCategory.TRANSIENT+ assert exc_info.value.error_category is InferenceErrorCategory.AMBIGUOUSassert exc_info.value.user_action is not Noneassert exc_info.value.user_action.kind is UserActionKind.WAIT_AND_RETRYassert exc_info.value.provider_metadata is not Noneassert exc_info.value.provider_metadata.status_code == 500@pytest.mark.parametrize(- ("exc_class", "expected_sdk_type"),+ ("exc_class", "expected_sdk_type", "expected_category"),[- (httpx.ConnectError, "ConnectError"),- (httpx.ConnectTimeout, "ConnectTimeout"),- (httpx.ReadError, "TransportError"),- (httpx.RemoteProtocolError, "TransportError"),+ # Never sent: the connection was not opened, so the image was not generated.+ (httpx.ConnectError, "ConnectError", InferenceErrorCategory.TRANSIENT),+ (httpx.ConnectTimeout, "ConnectTimeout", InferenceErrorCategory.TRANSIENT),+ # Dropped after the request left: the image may exist and be billed.+ (httpx.ReadError, "TransportError", InferenceErrorCategory.AMBIGUOUS),+ (httpx.RemoteProtocolError, "TransportError", InferenceErrorCategory.AMBIGUOUS),],)- async def test_httpx_transport_error_is_wrapped_as_transient(+ async def test_httpx_transport_error_is_wrapped_by_whether_it_was_sent(self,mocker: MockerFixture,exc_class: type[httpx.TransportError],expected_sdk_type: str,+ expected_category: InferenceErrorCategory,) -> None:- """A direct httpx.TransportError from generate_content() must be caught and routed through- the categorizer as a TRANSIENT ImgGenGenerationError, matching the Google LLM worker.+ """A direct httpx.TransportError from generate_content() is caught and routed through the categorizer as an+ ImgGenGenerationError: transient when the request was never sent, an unknown outcome when it may have been."""worker = _make_worker(mocker)request = httpx.Request("POST", "https://generativelanguage.googleapis.com/v1/models/imagen-3.0-generate-002:generateContent")@@ -209,7 +212,7 @@ class TestGoogleImgGenWorkerErrorHandling:with pytest.raises(ImgGenGenerationError) as exc_info:await worker._gen_image(img_gen_job=_make_img_gen_job(mocker)) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]- assert exc_info.value.error_category is InferenceErrorCategory.TRANSIENT+ assert exc_info.value.error_category is expected_categoryassert exc_info.value.user_action is not Noneassert exc_info.value.user_action.kind is UserActionKind.WAIT_AND_RETRYassert exc_info.value.provider_metadata is not Nonediff --git a/tests/unit/pipelex/providers/google/test_google_worker_error_handling.py b/tests/unit/pipelex/providers/google/test_google_worker_error_handling.pyindex 5265287c1..13d65da21 100644--- a/tests/unit/pipelex/providers/google/test_google_worker_error_handling.py+++ b/tests/unit/pipelex/providers/google/test_google_worker_error_handling.py@@ -225,8 +225,8 @@ class TestGoogleWorkerErrorHandling:# ---- ImgGen worker ServerError test ----- async def test_img_gen_server_error_has_transient_category(self, mocker: MockerFixture) -> None:- """ServerError should be categorized as TRANSIENT for ImgGen worker."""+ async def test_img_gen_server_error_is_an_unknown_outcome(self, mocker: MockerFixture) -> None:+ """A ServerError on an image generation, which is billed and not idempotent, is an unknown outcome."""worker = _make_google_img_gen_worker(mocker)sdk_exc = _make_google_server_error(code=500, message="Internal server error")worker.genai_async_client.models.generate_content.side_effect = sdk_exc # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue]@@ -234,7 +234,7 @@ class TestGoogleWorkerErrorHandling:with pytest.raises(ImgGenGenerationError) as exc_info:await worker._gen_image(img_gen_job=_make_img_gen_job(mocker)) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]- assert exc_info.value.error_category is InferenceErrorCategory.TRANSIENT+ assert exc_info.value.error_category is InferenceErrorCategory.AMBIGUOUSassert exc_info.value.__cause__ is sdk_exc# ---- to_error_report() integration ----diff --git a/tests/unit/pipelex/providers/huggingface/test_data.py b/tests/unit/pipelex/providers/huggingface/test_data.pyindex 1b2827bd7..c75a83d65 100644--- a/tests/unit/pipelex/providers/huggingface/test_data.py+++ b/tests/unit/pipelex/providers/huggingface/test_data.py@@ -58,10 +58,11 @@ class HuggingFaceErrorHandlingTestData:UserActionKind.CONTACT_SUPPORT,),(+ # An image generation is billed and not idempotent, so a failure after it was sent is an unknown outcome."server_error_503",503,"Service unavailable",- InferenceErrorCategory.TRANSIENT,+ InferenceErrorCategory.AMBIGUOUS,UserActionKind.WAIT_AND_RETRY,),]@@ -69,7 +70,7 @@ class HuggingFaceErrorHandlingTestData:TIMEOUT_CASES: ClassVar[list[tuple[str, InferenceErrorCategory, UserActionKind]]] = [("inference_timeout",- InferenceErrorCategory.TRANSIENT,+ InferenceErrorCategory.AMBIGUOUS,UserActionKind.WAIT_AND_RETRY,),]diff --git a/tests/unit/pipelex/providers/huggingface/test_hf_worker_error_handling.py b/tests/unit/pipelex/providers/huggingface/test_hf_worker_error_handling.pyindex 7ee5ebf1d..7690b4f80 100644--- a/tests/unit/pipelex/providers/huggingface/test_hf_worker_error_handling.py+++ b/tests/unit/pipelex/providers/huggingface/test_hf_worker_error_handling.py@@ -101,7 +101,7 @@ class TestHuggingFaceWorkerErrorHandling:("_topic", "expected_category", "expected_user_action_kind"),HuggingFaceErrorHandlingTestData.TIMEOUT_CASES,)- async def test_inference_timeout_is_transient(+ async def test_inference_timeout_is_an_unknown_outcome(self,mocker: MockerFixture,_topic: str,diff --git a/tests/unit/pipelex/providers/huggingface/test_huggingface_img_gen_worker_semantic.py b/tests/unit/pipelex/providers/huggingface/test_huggingface_img_gen_worker_semantic.pyindex 4f6e3e980..a7a825345 100644--- a/tests/unit/pipelex/providers/huggingface/test_huggingface_img_gen_worker_semantic.py+++ b/tests/unit/pipelex/providers/huggingface/test_huggingface_img_gen_worker_semantic.py@@ -62,7 +62,8 @@ class TestHuggingFaceImgGenWorkerSemantic:# Unhandled 4xx: non-retryable client error, not TRANSIENT.(409, InferenceErrorCategory.CONFIGURATION, UserActionKind.CHANGE_INPUT),(422, InferenceErrorCategory.CONFIGURATION, UserActionKind.CHANGE_INPUT),- (500, InferenceErrorCategory.TRANSIENT, UserActionKind.WAIT_AND_RETRY),+ # Billed and not idempotent: a 5xx after the request was sent is an unknown outcome.+ (500, InferenceErrorCategory.AMBIGUOUS, UserActionKind.WAIT_AND_RETRY),],)async def test_http_error_carries_semantic_user_action(@@ -128,7 +129,7 @@ class TestHuggingFaceImgGenWorkerSemantic:with pytest.raises(ImgGenGenerationError) as exc_info:await worker._generate_single_image(img_gen_job=_make_img_gen_job(mocker)) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]- assert exc_info.value.error_category is InferenceErrorCategory.TRANSIENT+ assert exc_info.value.error_category is InferenceErrorCategory.AMBIGUOUSassert exc_info.value.user_action is not Noneassert exc_info.value.user_action.kind is UserActionKind.WAIT_AND_RETRYassert exc_info.value.provider_metadata is not Nonediff --git a/tests/unit/pipelex/providers/openai/test_openai_completions_img_gen_worker_error_handling.py b/tests/unit/pipelex/providers/openai/test_openai_completions_img_gen_worker_error_handling.pyindex 6f52234f2..5f238e853 100644--- a/tests/unit/pipelex/providers/openai/test_openai_completions_img_gen_worker_error_handling.py+++ b/tests/unit/pipelex/providers/openai/test_openai_completions_img_gen_worker_error_handling.py@@ -91,7 +91,7 @@ class TestOpenAICompletionsImgGenWorkerErrorHandling:assert exc_info.value.user_action is not Noneassert exc_info.value.user_action.kind is UserActionKind.CHECK_BILLING- async def test_timeout_is_transient(self, mocker: MockerFixture) -> None:+ async def test_timeout_is_an_unknown_outcome(self, mocker: MockerFixture) -> None:worker = _make_worker(mocker)request = httpx.Request("POST", "https://api.openai.com/v1/chat/completions")sdk_exc = openai.APITimeoutError(request=request)@@ -100,11 +100,11 @@ class TestOpenAICompletionsImgGenWorkerErrorHandling:with pytest.raises(ImgGenGenerationError) as exc_info:await worker._gen_image(img_gen_job=_make_img_gen_job(mocker)) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]- assert exc_info.value.error_category is InferenceErrorCategory.TRANSIENT+ assert exc_info.value.error_category is InferenceErrorCategory.AMBIGUOUSassert exc_info.value.user_action is not Noneassert exc_info.value.user_action.kind is UserActionKind.WAIT_AND_RETRY- async def test_connection_error_is_transient(self, mocker: MockerFixture) -> None:+ async def test_connection_error_is_an_unknown_outcome(self, mocker: MockerFixture) -> None:worker = _make_worker(mocker)request = httpx.Request("POST", "https://api.openai.com/v1/chat/completions")sdk_exc = openai.APIConnectionError(message="boom", request=request)@@ -113,9 +113,9 @@ class TestOpenAICompletionsImgGenWorkerErrorHandling:with pytest.raises(ImgGenGenerationError) as exc_info:await worker._gen_image(img_gen_job=_make_img_gen_job(mocker)) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]- assert exc_info.value.error_category is InferenceErrorCategory.TRANSIENT+ assert exc_info.value.error_category is InferenceErrorCategory.AMBIGUOUS- async def test_server_error_is_transient(self, mocker: MockerFixture) -> None:+ async def test_server_error_is_an_unknown_outcome(self, mocker: MockerFixture) -> None:worker = _make_worker(mocker)sdk_exc = openai.InternalServerError("server error", response=_make_response(500), body={"type": "server_error"})worker.openai_client.chat.completions.create.side_effect = sdk_exc # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue]@@ -123,7 +123,7 @@ class TestOpenAICompletionsImgGenWorkerErrorHandling:with pytest.raises(ImgGenGenerationError) as exc_info:await worker._gen_image(img_gen_job=_make_img_gen_job(mocker)) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]- assert exc_info.value.error_category is InferenceErrorCategory.TRANSIENT+ assert exc_info.value.error_category is InferenceErrorCategory.AMBIGUOUSassert exc_info.value.user_action is not Noneassert exc_info.value.user_action.kind is UserActionKind.WAIT_AND_RETRY@@ -224,8 +224,8 @@ class TestOpenAICompletionsImgGenWorkerErrorHandling:assert exc_info.value.provider_metadata is not Noneassert exc_info.value.provider_metadata.status_code == 409- async def test_generic_status_error_503_is_transient(self, mocker: MockerFixture) -> None:- """An unhandled 5xx APIStatusError is categorized TRANSIENT via the generic fallback."""+ async def test_generic_status_error_503_is_an_unknown_outcome(self, mocker: MockerFixture) -> None:+ """An unhandled 5xx APIStatusError on an image generation, which is billed and not idempotent, is an unknown outcome."""worker = _make_worker(mocker)sdk_exc = openai.APIStatusError("service unavailable", response=_make_response(503), body=None)worker.openai_client.chat.completions.create.side_effect = sdk_exc # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue]@@ -233,7 +233,7 @@ class TestOpenAICompletionsImgGenWorkerErrorHandling:with pytest.raises(ImgGenGenerationError) as exc_info:await worker._gen_image(img_gen_job=_make_img_gen_job(mocker)) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]- assert exc_info.value.error_category is InferenceErrorCategory.TRANSIENT+ assert exc_info.value.error_category is InferenceErrorCategory.AMBIGUOUSassert exc_info.value.user_action is not Noneassert exc_info.value.user_action.kind is UserActionKind.WAIT_AND_RETRYassert exc_info.value.provider_metadata is not Nonediff --git a/tests/unit/pipelex/providers/openai/test_openai_img_gen_worker_error_handling.py b/tests/unit/pipelex/providers/openai/test_openai_img_gen_worker_error_handling.pyindex e83868a7d..2002a0290 100644--- a/tests/unit/pipelex/providers/openai/test_openai_img_gen_worker_error_handling.py+++ b/tests/unit/pipelex/providers/openai/test_openai_img_gen_worker_error_handling.py@@ -100,7 +100,7 @@ class TestOpenAIImgGenWorkerErrorHandling:assert exc_info.value.provider_metadata is not Noneassert exc_info.value.provider_metadata.status_code == 429- async def test_timeout_is_transient(self, mocker: MockerFixture) -> None:+ async def test_timeout_is_an_unknown_outcome(self, mocker: MockerFixture) -> None:worker = _make_openai_img_gen_worker(mocker)request = httpx.Request("POST", "https://api.openai.com/v1/images/generations")sdk_exc = openai.APITimeoutError(request=request)@@ -115,13 +115,13 @@ class TestOpenAIImgGenWorkerErrorHandling:with pytest.raises(ImgGenGenerationError) as exc_info:await worker._gen_image_list(img_gen_job=_make_img_gen_job(mocker), nb_images=1) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]- assert exc_info.value.error_category is InferenceErrorCategory.TRANSIENT+ assert exc_info.value.error_category is InferenceErrorCategory.AMBIGUOUSassert exc_info.value.user_action is not Noneassert exc_info.value.user_action.kind is UserActionKind.WAIT_AND_RETRYassert exc_info.value.provider_metadata is not Noneassert exc_info.value.provider_metadata.sdk_exception_type == "APITimeoutError"- async def test_connection_error_is_transient(self, mocker: MockerFixture) -> None:+ async def test_connection_error_is_an_unknown_outcome(self, mocker: MockerFixture) -> None:worker = _make_openai_img_gen_worker(mocker)request = httpx.Request("POST", "https://api.openai.com/v1/images/generations")sdk_exc = openai.APIConnectionError(message="Connection refused", request=request)@@ -136,11 +136,11 @@ class TestOpenAIImgGenWorkerErrorHandling:with pytest.raises(ImgGenGenerationError) as exc_info:await worker._gen_image_list(img_gen_job=_make_img_gen_job(mocker), nb_images=1) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]- assert exc_info.value.error_category is InferenceErrorCategory.TRANSIENT+ assert exc_info.value.error_category is InferenceErrorCategory.AMBIGUOUSassert exc_info.value.user_action is not Noneassert exc_info.value.user_action.kind is UserActionKind.WAIT_AND_RETRY- async def test_internal_server_error_is_transient(self, mocker: MockerFixture) -> None:+ async def test_internal_server_error_is_an_unknown_outcome(self, mocker: MockerFixture) -> None:worker = _make_openai_img_gen_worker(mocker)sdk_exc = openai.InternalServerError("server error",@@ -158,7 +158,7 @@ class TestOpenAIImgGenWorkerErrorHandling:with pytest.raises(ImgGenGenerationError) as exc_info:await worker._gen_image_list(img_gen_job=_make_img_gen_job(mocker), nb_images=1) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]- assert exc_info.value.error_category is InferenceErrorCategory.TRANSIENT+ assert exc_info.value.error_category is InferenceErrorCategory.AMBIGUOUSassert exc_info.value.user_action is not Noneassert exc_info.value.user_action.kind is UserActionKind.WAIT_AND_RETRYassert exc_info.value.provider_metadata is not Nonediff --git a/tests/unit/pipelex/providers/pypdfium2/test_data.py b/tests/unit/pipelex/providers/pypdfium2/test_data.pyindex ca4394bd0..4a0eb828e 100644--- a/tests/unit/pipelex/providers/pypdfium2/test_data.py+++ b/tests/unit/pipelex/providers/pypdfium2/test_data.py@@ -35,10 +35,10 @@ class Pypdfium2ErrorHandlingTestData:UserActionKind.CHANGE_INPUT,),(- "io_error_transient",+ "local_io_error",OSError,"Permission denied: /tmp/locked.pdf",- InferenceErrorCategory.TRANSIENT,- UserActionKind.WAIT_AND_RETRY,+ InferenceErrorCategory.UNKNOWN,+ UserActionKind.CONTACT_SUPPORT,),]diff --git a/tests/unit/pipelex/providers/pypdfium2/test_pypdfium2_worker_error_handling.py b/tests/unit/pipelex/providers/pypdfium2/test_pypdfium2_worker_error_handling.pyindex 594378e1a..e34f14238 100644--- a/tests/unit/pipelex/providers/pypdfium2/test_pypdfium2_worker_error_handling.py+++ b/tests/unit/pipelex/providers/pypdfium2/test_pypdfium2_worker_error_handling.py@@ -5,6 +5,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, Anyimport pytest+from mthds.protocol.problem.registry import CoreCodeif TYPE_CHECKING:from pytest_mock import MockerFixture@@ -106,8 +107,8 @@ class TestPypdfium2WorkerErrorHandling:assert report.retryable is Falseassert report.error_type == "ExtractJobFailureError"- async def test_error_report_for_os_error_is_retryable(self, mocker: MockerFixture) -> None:- """to_error_report() for OSError has TRANSIENT category and is retryable."""+ async def test_error_report_for_os_error_is_the_runtime_s(self, mocker: MockerFixture) -> None:+ """A local disk failure is this machine's, not the input's and not one a retry is known to clear: runtime.unexpected."""worker = _make_pypdfium2_worker(mocker)sdk_exc = OSError("Disk read error")@@ -127,5 +128,6 @@ class TestPypdfium2WorkerErrorHandling:await worker._extract_pages(extract_job=_make_extract_job(mocker)) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]report = exc_info.value.to_error_report()- assert report.error_category == "transient"- assert report.retryable is True+ assert report.error_category == "unknown"+ assert report.code == CoreCode.RUNTIME_UNEXPECTED+ assert report.retryable is Falsediff --git a/tests/unit/pipelex/providers/pypdfium2/test_pypdfium2_worker_semantic.py b/tests/unit/pipelex/providers/pypdfium2/test_pypdfium2_worker_semantic.pyindex d67fd2425..73accef9f 100644--- a/tests/unit/pipelex/providers/pypdfium2/test_pypdfium2_worker_semantic.py+++ b/tests/unit/pipelex/providers/pypdfium2/test_pypdfium2_worker_semantic.py@@ -43,7 +43,7 @@ class TestPypdfium2WorkerSemantic:(FileNotFoundError, "No such file", InferenceErrorCategory.CONTENT, UserActionKind.CHANGE_INPUT),(ValueError, "Invalid PDF", InferenceErrorCategory.CONTENT, UserActionKind.CHANGE_INPUT),(RuntimeError, "PDF parsing failed", InferenceErrorCategory.CONTENT, UserActionKind.CHANGE_INPUT),- (OSError, "Disk read error", InferenceErrorCategory.TRANSIENT, UserActionKind.WAIT_AND_RETRY),+ (OSError, "Disk read error", InferenceErrorCategory.UNKNOWN, UserActionKind.CONTACT_SUPPORT),],)async def test_local_exception_carries_semantic_user_action(diff --git a/tests/unit/pipelex/providers/reportlab/test_reportlab_pdf_renderer.py b/tests/unit/pipelex/providers/reportlab/test_reportlab_pdf_renderer.pyindex eac21f1af..b6a78576e 100644--- a/tests/unit/pipelex/providers/reportlab/test_reportlab_pdf_renderer.py+++ b/tests/unit/pipelex/providers/reportlab/test_reportlab_pdf_renderer.py@@ -25,6 +25,7 @@ from pipelex.cogt.doc_gen.layout_tree import (TableBlock,)from pipelex.cogt.doc_gen.render_job import RenderJob+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom tests.unit.pipelex.providers.reportlab.reportlab_test_helpers import (TEST_FILENAME,TEST_TITLE,@@ -130,7 +131,11 @@ class TestReportlabPdfRenderer:resources = StubRenderResources(answer=b"<svg xmlns='http://www.w3.org/2000/svg'/>")with pytest.raises(DocGenRenderError, match="image 1 of the document") as exc_info:render_layout(blocks=[ImageBlock(url="pipelex-storage://run/chart.svg", caption=None)], resources=resources)- assert exc_info.value.error_domain == ErrorDomain.INPUT+ # The run's data the engine cannot lay out: the caller's to change, and caller-facing.+ report = exc_info.value.to_error_report()+ assert report.code == PipelexErrorCode.DOCGEN_CONTENT_UNPRINTABLE+ assert report.error_domain == ErrorDomain.INPUT+ assert report.caller_facing_message is Truedef test_a_job_that_is_not_a_pdf_from_the_layout_is_refused(self) -> None:job = RenderJob(@@ -159,7 +164,11 @@ class TestReportlabPdfRenderer:f"The PDF engine cannot print '{TEST_FILENAME}': the table 'Line items' does not fit on an A4 page, ""as part of it is taller than a page and cannot be split across pages.")- assert exc_info.value.error_domain == ErrorDomain.INPUT+ # The run's data the engine cannot lay out: the caller's to change, and caller-facing.+ report = exc_info.value.to_error_report()+ assert report.code == PipelexErrorCode.DOCGEN_CONTENT_UNPRINTABLE+ assert report.error_domain == ErrorDomain.INPUT+ assert report.caller_facing_message is Truedef test_table_cells_print_their_scalars(self) -> None:table = TableBlock(diff --git a/tests/unit/pipelex/providers/typesafe/test_typesafe_error_classification.py b/tests/unit/pipelex/providers/typesafe/test_typesafe_error_classification.pyindex acd22c552..e2e27007e 100644--- a/tests/unit/pipelex/providers/typesafe/test_typesafe_error_classification.py+++ b/tests/unit/pipelex/providers/typesafe/test_typesafe_error_classification.py@@ -11,7 +11,8 @@ from pipelex.cogt.inference.error_classification import (UserActionKind,extract_typesafe_metadata,)-from pipelex.cogt.inference.error_render import InferenceErrorFamily, render_inference_error+from pipelex.cogt.inference.error_classify import InferenceErrorFamily+from pipelex.cogt.inference.error_render import render_inference_errorfrom pipelex.cogt.inference.provider_name import ProviderNamefrom pipelex.providers.typesafe.typesafe_error_classification import classify_typesafe_errorfrom tests.unit.pipelex.providers.typesafe.test_data import TestData, rebuild_recorded_exceptiondiff --git a/tests/unit/pipelex/test_base_exceptions.py b/tests/unit/pipelex/test_base_exceptions.pyindex 9e1af4b8b..9fc6b1c68 100644--- a/tests/unit/pipelex/test_base_exceptions.py+++ b/tests/unit/pipelex/test_base_exceptions.py@@ -13,20 +13,23 @@ class TestErrorReportColdImport:itself crashed. Runs in a subprocess so a clean interpreter is guaranteed; thein-process pytest session has already imported ``cogt`` and would mask the bug.- ``ErrorReport`` is constructed directly with literal ``title`` / ``type_uri``- (instead of via ``PipelexConfigError(...).to_error_report()`` which would call- ``type_uri()`` -> ``get_config()`` and fail in this no-bootstrap subprocess —- a separate test exercises that path with config loaded).+ ``ErrorReport`` is constructed both directly, with literal ``code`` / ``title`` /+ ``type_uri``, and from a code through ``ErrorReport.make_for_code``, which reads+ the registry's generated tables and so needs no bootstrap either."""code = ("import sys\n""from pipelex.base_exceptions import ErrorReport\n""assert 'pipelex.cogt.exceptions' not in sys.modules, ""'cogt.exceptions already loaded — test no longer exercises the cold path'\n"- "direct = ErrorReport(error_type='X', message='m', "- "title='X error', type_uri='https://docs.pipelex.com/latest/errors/x/')\n"- "assert direct.to_dict() == {'error_type': 'X', 'message': 'm', "- "'title': 'X error', 'type_uri': 'https://docs.pipelex.com/latest/errors/x/'}\n"+ "direct = ErrorReport(code='runtime.unexpected', error_type='X', message='m', "+ "title='X error', type_uri='https://mthds.ai/errors/runtime.unexpected')\n"+ "assert direct.to_dict() == {'code': 'runtime.unexpected', 'error_type': 'X', 'message': 'm', "+ "'title': 'X error', 'type_uri': 'https://mthds.ai/errors/runtime.unexpected'}\n"+ "from mthds.protocol.problem.registry import CoreCode\n"+ "coded = ErrorReport.make_for_code(code=CoreCode.RUNTIME_UNEXPECTED, error_type='X', message='m')\n"+ "assert coded.type_uri == 'https://mthds.ai/errors/runtime.unexpected'\n"+ "assert 'pipelex.cogt.exceptions' not in sys.modules\n")result = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, check=False) # ruff: ignore[subprocess-without-shell-equals-true]assert result.returncode == 0, f"cold-path ErrorReport construction failed:\nstdout: {result.stdout}\nstderr: {result.stderr}"diff --git a/tests/unit/pipelex/test_error_report_disclosure_mode.py b/tests/unit/pipelex/test_error_report_disclosure_mode.pyindex 488c7c8d1..cea5aad15 100644--- a/tests/unit/pipelex/test_error_report_disclosure_mode.py+++ b/tests/unit/pipelex/test_error_report_disclosure_mode.py@@ -21,6 +21,7 @@ be redacted. ``caller_facing_message`` is not inherited, so STRICT redacts it.from typing import Anyimport pytest+from mthds.protocol.problem.registry import CoreCodefrom pydantic import ValidationErrorfrom pipelex.base_exceptions import (@@ -28,17 +29,25 @@ from pipelex.base_exceptions import (DisclosureMode,ErrorDomain,ErrorReport,- PipelexUnexpectedError,+ PipelexError,ValidationErrorCategory,ValidationErrorItem,)from pipelex.cogt.inference.error_classification import ProviderErrorMetadata, UserAction, UserActionKindfrom pipelex.cogt.inference.provider_name import ProviderName+from pipelex.errors.error_code_declaration import InheritsCausefrom pipelex.mthds_parsing.exceptions import MthdsParserError+class _PassThroughWrapperError(PipelexError):+ """A wrapper that adds no fact deciding the code: it takes its cause's."""++ error_code = InheritsCause(fallback=CoreCode.RUNTIME_UNEXPECTED)++def _runtime_report(message: str = "rate limited on the worker") -> ErrorReport:return ErrorReport(+ code="provider.quota_exhausted",error_type="CogtError",message=message,title="AI inference failed",@@ -60,6 +69,7 @@ def _runtime_report(message: str = "rate limited on the worker") -> ErrorReport:def _config_report(message: str = "OPENAI_API_KEY is not set") -> ErrorReport:return ErrorReport(+ code="pipelex.config.variable_missing",error_type="EnvVarNotFoundError",message=message,title="Environment variable not set",@@ -71,6 +81,7 @@ def _config_report(message: str = "OPENAI_API_KEY is not set") -> ErrorReport:def _caller_facing_report(message: str = "pipe 'summarize' references unknown concept 'Reportt' at line 14") -> ErrorReport:"""A report whose message was authored as caller-facing copy (interpreter / bundle-validation)."""return ErrorReport(+ code="method.syntax",error_type="MthdsParserError",message=message,title="MTHDS parser",@@ -88,6 +99,7 @@ def _input_domain_wrapper_report(message: str = "internal invariant violated: ca``__cause__`` chain while keeping its own internal ``message``."""return ErrorReport(+ code="runtime.unexpected",error_type="PipelexUnexpectedError",message=message,title="Unexpected internal error",@@ -249,21 +261,23 @@ class TestErrorReportDisclosureMode:assert provider_metadata["retry_after_seconds"] == 12.0def test_strict_redacts_domain_less_wrapper_raised_from_input_cause(self) -> None:- """A domain-less wrapper raised ``from`` an INPUT cause must not leak its own message in STRICT.-- ``PipelexUnexpectedError`` (no domain, internal message) wrapping a- ``MthdsParserError`` (INPUT) produces a report classified- ``error_domain=INPUT`` via ``__cause__``-chain inheritance — yet the- report's ``message`` is the wrapper's internal text. ``caller_facing_message``- is NOT inherited, so STRICT redacts the message.+ """A wrapper that takes its cause's code must not leak its own message in STRICT.++ ``_PassThroughWrapperError`` (inherits its cause's code, internal message)+ wrapping a ``MthdsParserError`` (a method code, caller-facing) produces a+ report carrying the cause's code, and with it the cause's domain, through+ the ``__cause__`` walk — yet the report's ``message`` is the wrapper's+ internal text. ``caller_facing_message`` is NOT inherited, so STRICT+ redacts the message."""cause = MthdsParserError("parse failed at /srv/secret/internal/bundle.mthds")wrapper_message = "internal invariant violated: cache slot is None"try:- raise PipelexUnexpectedError(wrapper_message) from cause- except PipelexUnexpectedError as exc:+ raise _PassThroughWrapperError(wrapper_message) from cause+ except _PassThroughWrapperError as exc:report = exc.to_error_report()- # error_domain IS inherited from the INPUT cause ...+ # The code, and the domain it decides, are the cause's ...+ assert report.code == cause.resolve_error_code()assert report.error_domain == ErrorDomain.INPUT# ... but caller_facing_message is NOT — the wrapper authored the message.assert report.caller_facing_message is False@@ -307,6 +321,7 @@ class TestErrorReportDisclosureMode:def test_retryable_survives_disclosure_mode(self, retryable: bool | None, mode: DisclosureMode) -> None:"""``retryable`` is a stable identifier — kept in both modes for True / False / None."""report = ErrorReport(+ code="provider.quota_exhausted",error_type="CogtError",message="boom",title="AI inference failed",@@ -403,6 +418,7 @@ class TestErrorReportDisclosureMode:# exercise each branch — using ``model_copy`` so pyright sees the# concrete field types instead of the union we'd get from ``**kwargs``.caller_facing_report = ErrorReport(+ code="method.syntax",error_type="MthdsParserError",message="pipe references unknown concept",title="MTHDS parser",@@ -448,6 +464,7 @@ class TestErrorReportDisclosureMode:non-caller-facing report carrying it is not silently redacted."""report = ErrorReport(+ code="method.invalid",error_type="ValidateBundleError",message="bundle failed validation",title="Validate bundle error",diff --git a/tests/unit/pipelex/test_error_report_from_dict.py b/tests/unit/pipelex/test_error_report_from_dict.pyindex f0ab20349..ab244dff8 100644--- a/tests/unit/pipelex/test_error_report_from_dict.py+++ b/tests/unit/pipelex/test_error_report_from_dict.py@@ -23,6 +23,7 @@ class TestErrorReportFromDict:[pytest.param(ErrorReport(+ code="runtime.unexpected",error_type="X",message="m",title="X error",@@ -32,6 +33,7 @@ class TestErrorReportFromDict:),pytest.param(ErrorReport(+ code="provider.quota_exhausted",error_type="CogtError",message="rate limited",title="AI inference failed",@@ -47,6 +49,7 @@ class TestErrorReportFromDict:),pytest.param(ErrorReport(+ code="runtime.unexpected",error_type="LLMCompletionError",message="429 Too Many Requests",title="LLM completion",diff --git a/tests/unit/pipelex/test_error_report_problem_document.py b/tests/unit/pipelex/test_error_report_problem_document.pyindex a4091d5ba..4b00fe527 100644--- a/tests/unit/pipelex/test_error_report_problem_document.py+++ b/tests/unit/pipelex/test_error_report_problem_document.py@@ -17,6 +17,7 @@ from pipelex.cogt.inference.provider_name import ProviderNamedef _runtime_report() -> ErrorReport:return ErrorReport(+ code="provider.quota_exhausted",error_type="CogtError",message="rate limited on the worker",title="AI inference failed",@@ -91,6 +92,7 @@ class TestErrorReportProblemDocument:def test_status_follows_http_status_property(self, error_domain: ErrorDomain, expected_status: int) -> None:"""``status`` follows ``ErrorReport.http_status`` so the domain → HTTP mapping is honored."""report = ErrorReport(+ code="runtime.unexpected",error_type="X",message="m",title="X",@@ -124,6 +126,7 @@ class TestErrorReportProblemDocument:def test_strict_mode_passes_through_detail_for_caller_facing_report(self) -> None:"""A caller-facing-message report reflects ``detail`` back unchanged in STRICT mode."""report = ErrorReport(+ code="method.syntax",error_type="MthdsParserError",message="pipe 'summarize' references unknown concept at line 14",title="MTHDS parser",@@ -142,6 +145,7 @@ class TestErrorReportProblemDocument:passthrough — only ``caller_facing_message`` does."""report = ErrorReport(+ code="runtime.unexpected",error_type="PipelexUnexpectedError",message="internal invariant violated at /srv/secret/handler.py",title="Unexpected internal error",@@ -159,6 +163,7 @@ class TestErrorReportProblemDocument:the RFC 7807 envelope."""report = ErrorReport(+ code="method.syntax",error_type="MthdsParserError",message="pipe 'summarize' references unknown concept at line 14",title="MTHDS parser",@@ -178,6 +183,7 @@ class TestErrorReportProblemDocument:def test_caller_facing_message_flag_never_rides_as_extension_member(self) -> None:"""``caller_facing_message`` is internal redaction plumbing — never an RFC 7807 extension member."""report = ErrorReport(+ code="method.syntax",error_type="MthdsParserError",message="pipe 'summarize' references unknown concept at line 14",title="MTHDS parser",diff --git a/tests/unit/pipelex/test_pipelex_error_class_name_uniqueness.py b/tests/unit/pipelex/test_pipelex_error_class_name_uniqueness.pynew file mode 100644index 000000000..ed45825ef--- /dev/null+++ b/tests/unit/pipelex/test_pipelex_error_class_name_uniqueness.py@@ -0,0 +1,22 @@+"""Class-name uniqueness guard for the ``error_type`` keyspace.++Every report carries ``error_type``, the class name verbatim, and consumers branch on it, so two distinct+``PipelexError`` subclasses sharing a name would be one error to every reader. The type URI no longer+derives from the class name (it is the page of the error's registry code), so the guard is on the name+itself, case-folded so that acronym-casing variants (``LLMError`` and ``LlmError``) collide here too.+"""++from pipelex.errors.error_class_discovery import iter_pipelex_error_subclasses+++class TestPipelexErrorClassNameUniqueness:+ def test_all_error_class_names_are_unique(self) -> None:+ """Every loaded ``PipelexError`` subclass has a name no other one shares, ignoring case."""+ seen: dict[str, str] = {}+ for cls in iter_pipelex_error_subclasses():+ folded_name = cls.__name__.casefold()+ qualified_name = f"{cls.__module__}.{cls.__qualname__}"+ if folded_name in seen and seen[folded_name] != qualified_name:+ msg = f"error_type collision: {qualified_name} and {seen[folded_name]} share the name {cls.__name__!r}"+ raise AssertionError(msg)+ seen[folded_name] = qualified_namediff --git a/tests/unit/pipelex/test_pipelex_error_title_and_type_uri.py b/tests/unit/pipelex/test_pipelex_error_title_and_type_uri.pydeleted file mode 100644index 9aadf40af..000000000--- a/tests/unit/pipelex/test_pipelex_error_title_and_type_uri.py+++ /dev/null@@ -1,88 +0,0 @@-"""Unit tests for ``PipelexError.title()`` / ``type_uri()`` and end-to-end-``to_error_report()`` population. These need the Pipelex config loaded-(the standard pytest fixture chain handles bootstrapping).-"""--from pipelex.base_exceptions import ErrorDomain, ErrorReport, PipelexConfigError, PipelexError, SecurityError-from pipelex.mthds_parsing.exceptions import BundleElaboratorError, MthdsParserError---class TestPipelexErrorTitleAndTypeUri:- def test_to_error_report_populates_title_and_type_uri(self) -> None:- """``to_error_report()`` populates ``title`` / ``type_uri`` from the class methods."""- report = PipelexConfigError("bad config").to_error_report()- assert report.title == "Pipelex config"- assert report.type_uri == "https://docs.pipelex.com/latest/errors/pipelex-config-error/"- assert report.error_domain == ErrorDomain.CONFIG-- def test_auto_derive_title(self) -> None:- """A subclass with no ``_declared_title`` auto-derives from the class name."""-- class FooBarError(PipelexError):- pass-- assert FooBarError.title() == "Foo bar"- assert FooBarError.type_uri() == "https://docs.pipelex.com/latest/errors/foo-bar-error/"-- def test_declared_title_wins_over_auto_derive(self) -> None:- """``_declared_title`` set on a subclass overrides the auto-derived title."""-- class HasCuratedTitleError(PipelexError):- _declared_title = "Curated title"-- assert HasCuratedTitleError.title() == "Curated title"- # type_uri still auto-derives unless _declared_type_uri is also set.- assert HasCuratedTitleError.type_uri() == "https://docs.pipelex.com/latest/errors/has-curated-title-error/"-- def test_declared_type_uri_wins_over_auto_derive(self) -> None:- """``_declared_type_uri`` set on a subclass overrides the auto-derived URI."""-- class CustomUriError(PipelexError):- _declared_type_uri = "https://example.com/custom-error"-- assert CustomUriError.type_uri() == "https://example.com/custom-error"-- def test_declared_title_does_not_leak_through_inheritance(self) -> None:- """A parent's ``_declared_title`` is not silently inherited — each class- either declares its own title or auto-derives from its own name.-- ``SecurityError`` curates ``"Security policy violation"``. A bare- subclass should NOT inherit that — it should auto-derive from its own- class name.- """-- class CustomSecurityError(SecurityError):- pass-- assert CustomSecurityError.title() == "Custom security"-- def test_curated_titles_for_high_traffic_classes(self) -> None:- """The curated ``_declared_title`` overrides shipped with Item A."""- assert PipelexError.title() == "Pipelex error"- assert SecurityError.title() == "Security policy violation"-- def test_mthds_parser_error_identity_is_pinned(self) -> None:- """The parser error's wire-visible identity triple, pinned against silent drift.-- ``error_type`` (the class name), ``title`` and ``type_uri`` all travel on every- ``ErrorReport``, and clients branch on them. Nothing asserted the trio before, which is- how a rename left the repo's own fixtures carrying a shape the class cannot produce.- The title is *declared* rather than auto-derived because ``_humanize_class_name`` would- render the standard's name as "Mthds parser" — see ``mthds_parsing/exceptions.py``.- """- report = MthdsParserError("bad .mthds").to_error_report()- assert report.error_type == "MthdsParserError"- assert report.title == "MTHDS parser"- assert report.type_uri == "https://docs.pipelex.com/latest/errors/mthds-parser-error/"-- # The declared title must not capture the subclass — it derives from its own name.- assert BundleElaboratorError.title() == "Bundle elaborator"- assert BundleElaboratorError.type_uri() == "https://docs.pipelex.com/latest/errors/bundle-elaborator-error/"-- def test_round_trip_preserves_title_and_type_uri(self) -> None:- """``ErrorReport.from_dict(report.to_dict())`` preserves the new fields."""- report = PipelexConfigError("config gone").to_error_report()- recovered = ErrorReport.from_dict(report.to_dict())- assert recovered.title == report.title- assert recovered.type_uri == report.type_uri- assert recovered == reportdiff --git a/tests/unit/pipelex/test_pipelex_error_type_uri_uniqueness.py b/tests/unit/pipelex/test_pipelex_error_type_uri_uniqueness.pydeleted file mode 100644index f1d1b68b9..000000000--- a/tests/unit/pipelex/test_pipelex_error_type_uri_uniqueness.py+++ /dev/null@@ -1,23 +0,0 @@-"""Class-name uniqueness guard for the ``PipelexError.type_uri()`` keyspace.--Every loaded ``PipelexError`` subclass whose ``type_uri`` is derived from its class name must produce-a unique one. A collision there would mean two distinct error classes kebab to the same URI by-accident — this catches class-name reuses at CI time. A class that declares ``_declared_type_uri``-shares a URI on purpose, so it is left out.-"""--from pipelex.errors.error_class_discovery import iter_pipelex_error_subclasses---class TestPipelexErrorTypeUriUniqueness:- def test_all_derived_type_uris_are_unique(self) -> None:- """Every loaded ``PipelexError`` subclass that derives its ``type_uri`` produces a unique one."""- seen: dict[str, str] = {}- for cls in iter_pipelex_error_subclasses():- if isinstance(cls.__dict__.get("_declared_type_uri"), str):- continue- uri = cls.type_uri()- if uri in seen and seen[uri] != cls.__name__:- msg = f"type_uri collision: {cls.__name__} and {seen[uri]} both produce {uri!r}"- raise AssertionError(msg)- seen[uri] = cls.__name__diff --git a/tests/unit/pipelex/test_runtime_boot_credential_refusals.py b/tests/unit/pipelex/test_runtime_boot_credential_refusals.pynew file mode 100644index 000000000..c3d256e47--- /dev/null+++ b/tests/unit/pipelex/test_runtime_boot_credential_refusals.py@@ -0,0 +1,58 @@+import pytest+from mthds.protocol.problem.registry import CoreCode+from pytest_mock import MockerFixture++from pipelex.base_exceptions import PipelexSetupError+from pipelex.cogt.exceptions import InferenceBackendCredentialsError, InferenceBackendCredentialsErrorType+from pipelex.errors.error_codes import ErrorCode+from pipelex.errors.registry.pipelex_codes import PipelexErrorCode+from pipelex.pipelex import Pipelex+from pipelex.system.runtime import IntegrationMode, runtime_manager+++def _test_integration_mode() -> IntegrationMode:+ """The boot mode the session conftest uses, so a re-boot here matches the one it replaces."""+ return IntegrationMode.CI if runtime_manager.is_ci_testing else IntegrationMode.PYTEST+++class TestRuntimeBootCredentialRefusals:+ @pytest.mark.parametrize(+ ("credentials_error_type", "expected_code"),+ [+ (InferenceBackendCredentialsErrorType.VAR_NOT_FOUND, PipelexErrorCode.CONFIG_CREDENTIAL_MISSING),+ (InferenceBackendCredentialsErrorType.VAR_FALLBACK_PATTERN, PipelexErrorCode.CONFIG_CREDENTIAL_MISSING),+ (InferenceBackendCredentialsErrorType.UNKNOWN_VAR_PREFIX, PipelexErrorCode.CONFIG_INVALID),+ (InferenceBackendCredentialsErrorType.NOT_RESOLVED_ON_KEYLESS_BOOT, CoreCode.RUNTIME_MISCONFIGURED),+ ],+ )+ def test_a_credential_refusal_keeps_its_own_code_through_the_boot(+ self,+ mocker: MockerFixture,+ credentials_error_type: InferenceBackendCredentialsErrorType,+ expected_code: ErrorCode,+ ) -> None:+ """The boot's setup error adds its message and keeps why the credential failed, never forcing a missing variable."""+ refusal = InferenceBackendCredentialsError(+ credentials_error_type=credentials_error_type,+ backend_name="lighthouse_backend",+ message="The lighthouse backend's credential cannot be resolved",+ key_name="LIGHTHOUSE_API_KEY",+ )+ refusing_models_manager = mocker.Mock()+ refusing_models_manager.setup.side_effect = refusal++ Pipelex.teardown_if_needed()+ try:+ with pytest.raises(PipelexSetupError) as raised:+ Pipelex.make(+ integration_mode=_test_integration_mode(),+ needs_inference=False,+ models_manager=refusing_models_manager,+ )++ assert raised.value.__cause__ is refusal+ assert "LIGHTHOUSE_API_KEY" in str(raised.value)+ assert raised.value.to_error_report().code == expected_code+ finally:+ Pipelex.teardown_if_needed()+ Pipelex.make(integration_mode=_test_integration_mode())diff --git a/tests/unit/pipelex/tools/jinja2/test_jinja2_render_owner.py b/tests/unit/pipelex/tools/jinja2/test_jinja2_render_owner.pynew file mode 100644index 000000000..2fc7613a0--- /dev/null+++ b/tests/unit/pipelex/tools/jinja2/test_jinja2_render_owner.py@@ -0,0 +1,206 @@+from __future__ import annotations++from typing import TYPE_CHECKING, Any++import pytest+from mthds.protocol.problem.registry import CoreCode++from pipelex.base_exceptions import INTERNAL_ERROR_PLACEHOLDER, DisclosureMode, PipelexError+from pipelex.system.exceptions import ToolError+from pipelex.tools.jinja2.exceptions import (+ Jinja2StuffError,+ Jinja2TemplateBudgetError,+ Jinja2TemplateInvalidError,+ Jinja2TemplateRenderError,+ Jinja2TemplateSecurityError,+)+from pipelex.tools.jinja2.jinja2_models import Jinja2ContextKey+from pipelex.tools.jinja2.jinja2_rendering import render_jinja2_async, render_jinja2_sync+from pipelex.tools.jinja2.jinja2_unknown_names import find_unknown_filters_and_tests+from pipelex.tools.jinja2.template_category import TemplateCategory+from pipelex.tools.jinja2.template_owner import TemplateOwner+from pipelex.tools.templating.templating_style import TagStyle, TemplatingStyle+from pipelex.tools.templating.text_format import TextFormat++if TYPE_CHECKING:+ from pipelex.errors.error_codes import ErrorCode++_TEMPLATING_STYLE = TemplatingStyle(tag_style=TagStyle.NO_TAG, text_format=TextFormat.PLAIN)++# A filter the environment lacks inside a branch: it compiles, and only rendering the branch finds it.+_UNKNOWN_FILTER_IN_A_BRANCH = "{% if lane %}{{ lane | frob_the_lane }}{% else %}quietly_routed{% endif %}"+# The same filter outside any branch: compiling the template finds it.+_UNKNOWN_FILTER_AT_THE_TOP = "{{ lane | frob_the_lane }}"+# An unknown test inside a branch.+_UNKNOWN_TEST_IN_A_BRANCH = "{% if lane %}{% if lane is frobbed %}a{% endif %}{% endif %}"+++async def _render_failure(+ template_source: str,+ *,+ template_owner: TemplateOwner,+ context: dict[str, Any] | None = None,+ category: TemplateCategory = TemplateCategory.LLM_PROMPT,+ is_undefined_strict: bool = False,+) -> PipelexError:+ # The sandbox's refusal is a `SecurityError`, not a `ToolError`: every other render failure is a `ToolError`.+ with pytest.raises((ToolError, Jinja2TemplateSecurityError)) as exc_info:+ await render_jinja2_async(+ template_source=template_source,+ template_category=category,+ templating_context={"lane": "express"} if context is None else context,+ templating_style=_TEMPLATING_STYLE,+ is_undefined_strict=is_undefined_strict,+ template_owner=template_owner,+ )+ return exc_info.value+++class TestJinja2RenderOwner:+ @pytest.mark.parametrize(+ ("template_source", "fault"),+ [+ (_UNKNOWN_FILTER_IN_A_BRANCH, "No filter named 'frob_the_lane' found."),+ (_UNKNOWN_FILTER_AT_THE_TOP, "No filter named 'frob_the_lane'."),+ (_UNKNOWN_TEST_IN_A_BRANCH, "No test named 'frobbed' found."),+ ],+ ids=["filter_in_a_branch", "filter_at_compile", "test_in_a_branch"],+ )+ @pytest.mark.asyncio(loop_scope="class")+ async def test_an_invalid_method_template_is_the_methods_and_caller_facing(self, template_source: str, fault: str) -> None:+ """A method's template naming what its environment lacks: `method.template_invalid`, kept under STRICT, never quoting the source."""+ error = await _render_failure(template_source, template_owner=TemplateOwner.METHOD)++ assert isinstance(error, Jinja2TemplateInvalidError)+ assert isinstance(error, Jinja2TemplateRenderError)+ assert error.fault == fault+ report = error.to_error_report()+ assert report.code == CoreCode.METHOD_TEMPLATE_INVALID+ assert report.message == f"Jinja2 render — the template cannot render as written: {fault}"+ strict_payload = report.to_dict(disclosure_mode=DisclosureMode.STRICT)+ assert strict_payload["message"] == report.message+ assert "quietly_routed" not in strict_payload["message"]++ @pytest.mark.parametrize("template_source", [_UNKNOWN_FILTER_IN_A_BRANCH, _UNKNOWN_FILTER_AT_THE_TOP])+ @pytest.mark.asyncio(loop_scope="class")+ async def test_an_invalid_pipelex_template_is_ours_and_withheld(self, template_source: str) -> None:+ """Pipelex's own template, the default owner: `runtime.unexpected`, whose message STRICT withholds."""+ error = await _render_failure(template_source, template_owner=TemplateOwner.PIPELEX)++ assert isinstance(error, Jinja2TemplateInvalidError)+ report = error.to_error_report()+ assert report.code == CoreCode.RUNTIME_UNEXPECTED+ assert report.to_dict(disclosure_mode=DisclosureMode.STRICT)["message"] == INTERNAL_ERROR_PLACEHOLDER++ @pytest.mark.parametrize(+ ("topic", "template_source", "context", "is_undefined_strict", "error_class", "method_code", "pipelex_code"),+ [+ (+ "undefined_value",+ "{{ missing.name }}",+ {},+ True,+ Jinja2TemplateRenderError,+ CoreCode.PIPE_TEMPLATE_RENDER_FAILED,+ CoreCode.RUNTIME_UNEXPECTED,+ ),+ (+ "filter_refusing_a_value_of_the_run",+ "{{ lane | reverse }}",+ {"lane": 42},+ False,+ Jinja2TemplateRenderError,+ CoreCode.PIPE_TEMPLATE_RENDER_FAILED,+ CoreCode.RUNTIME_UNEXPECTED,+ ),+ (+ "arithmetic",+ "{{ 1 // 0 }}",+ {},+ False,+ Jinja2TemplateRenderError,+ CoreCode.PIPE_TEMPLATE_RENDER_FAILED,+ CoreCode.RUNTIME_UNEXPECTED,+ ),+ (+ "unknown_text_format",+ "{{ lane | format('bogus') }}",+ {"lane": "express"},+ False,+ Jinja2TemplateRenderError,+ CoreCode.METHOD_TEMPLATE_INVALID,+ CoreCode.RUNTIME_UNEXPECTED,+ ),+ (+ "sandbox_refusal",+ "{{ lane.__class__ }}",+ {"lane": "express"},+ False,+ Jinja2TemplateSecurityError,+ CoreCode.SECURITY_TEMPLATE_REFUSED,+ CoreCode.RUNTIME_UNEXPECTED,+ ),+ (+ "render_budget",+ "{{ 'x' * (10 ** 9) }}",+ {},+ False,+ Jinja2TemplateBudgetError,+ CoreCode.PIPE_TEMPLATE_BUDGET_EXCEEDED,+ CoreCode.INPUT_TOO_LARGE,+ ),+ (+ "reserved_context_key",+ "{{ lane }}",+ {"lane": "express", Jinja2ContextKey.TAG_STYLE: "taken"},+ False,+ Jinja2StuffError,+ CoreCode.METHOD_NAME_CONFLICT,+ CoreCode.RUNTIME_UNEXPECTED,+ ),+ ],+ )+ @pytest.mark.asyncio(loop_scope="class")+ async def test_each_failure_takes_its_owners_code(+ self,+ topic: str,+ template_source: str,+ context: dict[str, Any],+ is_undefined_strict: bool,+ error_class: type[PipelexError],+ method_code: ErrorCode,+ pipelex_code: ErrorCode,+ ) -> None:+ """The same failure is the method's on a method's template and ours, or the data's, on Pipelex's own."""+ for template_owner, expected_code in ((TemplateOwner.METHOD, method_code), (TemplateOwner.PIPELEX, pipelex_code)):+ error = await _render_failure(+ template_source,+ template_owner=template_owner,+ context=context,+ category=TemplateCategory.BASIC,+ is_undefined_strict=is_undefined_strict,+ )+ assert type(error) is error_class, topic+ assert error.to_error_report().code == expected_code, f"{topic} on a {template_owner} template"++ def test_the_sync_render_is_coded_alike(self) -> None:+ with pytest.raises(Jinja2TemplateInvalidError) as exc_info:+ render_jinja2_sync(+ template_source=_UNKNOWN_FILTER_IN_A_BRANCH,+ template_category=TemplateCategory.BASIC,+ templating_context={"lane": "express"},+ template_owner=TemplateOwner.METHOD,+ )+ assert exc_info.value.to_error_report().code == CoreCode.METHOD_TEMPLATE_INVALID++ @pytest.mark.parametrize(+ ("template_source", "expected_names"),+ [+ (_UNKNOWN_FILTER_IN_A_BRANCH, ["frob_the_lane"]),+ (_UNKNOWN_TEST_IN_A_BRANCH, ["frobbed"]),+ ("{{ lane | upper | frob }}{% if lane is defined and lane is frob %}{{ lane | frob }}{% endif %}", ["frob"]),+ ("{{ lane | upper | tag }}{% if lane is defined %}{{ lane | format }}{% endif %}", []),+ ],+ )+ def test_the_unknown_names_a_template_uses_are_found(self, template_source: str, expected_names: list[str]) -> None:+ assert find_unknown_filters_and_tests(template_source=template_source, template_category=TemplateCategory.LLM_PROMPT) == expected_namesdiff --git a/tests/unit/pipelex/tools/misc/test_file_fetch_utils.py b/tests/unit/pipelex/tools/misc/test_file_fetch_utils.pyindex cb7edc2e2..a2f3ceda8 100644--- a/tests/unit/pipelex/tools/misc/test_file_fetch_utils.py+++ b/tests/unit/pipelex/tools/misc/test_file_fetch_utils.py@@ -1,5 +1,6 @@import httpximport pytest+from mthds.protocol.problem.registry import CoreCodefrom pipelex.base_exceptions import DisclosureModefrom pipelex.tools.misc.exceptions import RemoteFileFetchError@@ -25,27 +26,42 @@ class TestFetchFileFromUrl:raw_bytes = await fetch_file_from_url_httpx(url=URL, transport=_transport_answering(200, b"%PDF-1.4"))assert raw_bytes == b"%PDF-1.4"- @pytest.mark.parametrize("status_code", [404, 403, 500])- async def test_error_status_raises_caller_facing_error(self, status_code: int) -> None:- """A 4xx/5xx becomes an INPUT-domain error naming the URL and the status, kept under STRICT disclosure."""+ @pytest.mark.parametrize(+ ("status_code", "expected_code"),+ [+ (404, CoreCode.INPUT_FILE_UNREADABLE),+ (403, CoreCode.INPUT_FILE_UNREADABLE),+ (429, CoreCode.INPUT_URL_UNREACHABLE),+ (500, CoreCode.INPUT_URL_UNREACHABLE),+ (503, CoreCode.INPUT_URL_UNREACHABLE),+ ],+ )+ async def test_error_status_raises_caller_facing_error(self, status_code: int, expected_code: CoreCode) -> None:+ """A 4xx/5xx becomes an input error naming the URL and the status, kept under STRICT disclosure.++ A server that will not serve the file is ``input.file_unreadable``; one that cannot answer now, a 5xx or a+ 429, is ``input.url_unreachable``, which a retry may get past.+ """with pytest.raises(RemoteFileFetchError) as exc_info:await fetch_file_from_url_httpx(url=URL, transport=_transport_answering(status_code))+ assert exc_info.value.resolve_error_code() == expected_codestrict = exc_info.value.to_error_report().to_dict(disclosure_mode=DisclosureMode.STRICT)assert f"HTTP {status_code}" in strict["message"]assert URL in strict["message"]@pytest.mark.parametrize(- ("exc", "expected"),+ ("exc", "expected", "expected_code"),[- pytest.param(httpx.ConnectError("boom"), "could not be reached", id="connect"),- pytest.param(httpx.ReadTimeout("slow"), "timed out", id="timeout"),- pytest.param(httpx.RemoteProtocolError("bad"), "request failed", id="protocol"),+ pytest.param(httpx.ConnectError("boom"), "could not be reached", CoreCode.INPUT_URL_UNREACHABLE, id="connect"),+ pytest.param(httpx.ReadTimeout("slow"), "timed out", CoreCode.INPUT_URL_UNREACHABLE, id="timeout"),+ pytest.param(httpx.RemoteProtocolError("bad"), "request failed", CoreCode.INPUT_FILE_UNREADABLE, id="protocol"),],)- async def test_network_failure_raises_caller_facing_error(self, exc: httpx.RequestError, expected: str) -> None:- with pytest.raises(RemoteFileFetchError, match=expected):+ async def test_network_failure_raises_caller_facing_error(self, exc: httpx.RequestError, expected: str, expected_code: CoreCode) -> None:+ with pytest.raises(RemoteFileFetchError, match=expected) as exc_info:await fetch_file_from_url_httpx(url=URL, transport=_transport_raising(exc))+ assert exc_info.value.resolve_error_code() == expected_code@pytest.mark.asyncio(loop_scope="class")diff --git a/tests/unit/pipelex/tools/misc/test_filetype_utils.py b/tests/unit/pipelex/tools/misc/test_filetype_utils.pyindex ca5e42347..0fc98fe39 100644--- a/tests/unit/pipelex/tools/misc/test_filetype_utils.py+++ b/tests/unit/pipelex/tools/misc/test_filetype_utils.py@@ -3,6 +3,7 @@ import binasciifrom pathlib import Pathimport pytest+from mthds.protocol.problem.registry import CoreCodefrom pytest_mock import MockerFixturefrom pipelex.tools.misc.filetype_utils import (@@ -83,24 +84,23 @@ class TestDetectFileTypeFromBytes:mock_filetype_guess = mocker.patch("filetype.guess", return_value=None)test_bytes = b"unknown file content"- with pytest.raises(FileTypeError, match="Could not identify file type of given bytes: b'unknown file content'"):+ with pytest.raises(FileTypeError, match=r"Could not identify the file type of the given 20 bytes$") as exc_info:detect_file_type_from_bytes(test_bytes)+ assert exc_info.value.resolve_error_code() == CoreCode.INPUT_FILE_TYPE_UNSUPPORTEDmock_filetype_guess.assert_called_once_with(test_bytes)- def test_detect_file_type_from_bytes_failure_long_bytes(self, mocker: MockerFixture):- # Mock filetype.guess to return None and test truncation of long bytes in error message+ def test_detect_file_type_from_bytes_failure_never_quotes_the_bytes(self, mocker: MockerFixture):+ """The message names the size of the bytes, never their content, which is a caller's or a provider's."""mock_filetype_guess = mocker.patch("filetype.guess", return_value=None)- # Create bytes longer than 300 characters to test truncation- test_bytes = b"a" * 350+ test_bytes = b"secret-ish content " * 20with pytest.raises(FileTypeError) as exc_info:detect_file_type_from_bytes(test_bytes)- # Check that the error message contains truncated bytes (first 300 chars)error_message = str(exc_info.value)- assert "Could not identify file type of given bytes:" in error_message- assert len(error_message) < len(f"Could not identify file type of given bytes: {test_bytes!r}")+ assert error_message == f"Could not identify the file type of the given {len(test_bytes)} bytes"+ assert "secret-ish" not in error_messagemock_filetype_guess.assert_called_once_with(test_bytes)diff --git a/tests/unit/pipelex/tools/misc/test_semver.py b/tests/unit/pipelex/tools/misc/test_semver.pyindex f8af91a49..01d52b2b0 100644--- a/tests/unit/pipelex/tools/misc/test_semver.py+++ b/tests/unit/pipelex/tools/misc/test_semver.py@@ -2,8 +2,8 @@import pytestfrom semantic_version import SimpleSpec, Version # type: ignore[import-untyped]+from pipelex.tools.misc.exceptions import SemVerErrorfrom pipelex.tools.misc.semver import (- SemVerError,parse_constraint,parse_version,parse_version_tag,diff --git a/tests/unit/pipelex/tools/misc/test_semver_spec_constraint_syntax.py b/tests/unit/pipelex/tools/misc/test_semver_spec_constraint_syntax.pyindex 19fc8ff2f..72349a4b3 100644--- a/tests/unit/pipelex/tools/misc/test_semver_spec_constraint_syntax.py+++ b/tests/unit/pipelex/tools/misc/test_semver_spec_constraint_syntax.py@@ -10,7 +10,8 @@ leading space of the second clause made the whole constraint invalid.import pytest-from pipelex.tools.misc.semver import SemVerError, parse_constraint, parse_version, version_satisfies+from pipelex.tools.misc.exceptions import SemVerError+from pipelex.tools.misc.semver import parse_constraint, parse_version, version_satisfiesclass TestSpecVersionConstraintSyntax:diff --git a/tests/unit/pipelex/tools/storage/test_gcp_storage_provider.py b/tests/unit/pipelex/tools/storage/test_gcp_storage_provider.pyindex 8a5a14b6d..c91e3f9e9 100644--- a/tests/unit/pipelex/tools/storage/test_gcp_storage_provider.py+++ b/tests/unit/pipelex/tools/storage/test_gcp_storage_provider.py@@ -5,6 +5,7 @@ from typing import Anyimport pytestfrom pytest_mock import MockerFixture+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.tools.storage.exceptions import (StorageFileNotFoundError,StorageGcpCredentialsError,@@ -166,6 +167,32 @@ class TestGcpStorageProvider:assert "nonexistent/file.bin" in str(exc_info.value)+ @pytest.mark.parametrize(+ ("failure_name", "expected_code"),+ [+ ("Forbidden", PipelexErrorCode.CONFIG_CREDENTIAL_REFUSED),+ ("Unauthorized", PipelexErrorCode.CONFIG_CREDENTIAL_REFUSED),+ ("ServiceUnavailable", PipelexErrorCode.STORAGE_UNAVAILABLE),+ ],+ )+ async def test_load_failure_code_tells_a_refusal_from_an_outage(+ self,+ gcp_provider_no_signed_urls: GcpStorageProvider,+ mock_gcp_storage: dict[str, Any],+ failure_name: str,+ expected_code: PipelexErrorCode,+ ) -> None:+ """GCS refusing the credentials is the operator's configuration; any other GCS failure is storage unavailable."""+ from google.api_core import exceptions as google_exceptions # type: ignore[import-untyped] # ruff: ignore[import-outside-top-level]++ failure_class = getattr(google_exceptions, failure_name)+ mock_gcp_storage["blob"].download_as_bytes.side_effect = failure_class("refused or down")++ with pytest.raises(StorageGcpError) as exc_info:+ await gcp_provider_no_signed_urls.load(uri=f"{PIPELEX_STORAGE_SCHEME}test/file.bin")++ assert exc_info.value.resolve_error_code() == expected_code+async def test_store_raises_if_key_has_scheme_prefix(self,gcp_provider_no_signed_urls: GcpStorageProvider,diff --git a/tests/unit/pipelex/tools/storage/test_s3_storage_provider.py b/tests/unit/pipelex/tools/storage/test_s3_storage_provider.pyindex 737f276c7..497e7fe25 100644--- a/tests/unit/pipelex/tools/storage/test_s3_storage_provider.py+++ b/tests/unit/pipelex/tools/storage/test_s3_storage_provider.py@@ -6,6 +6,7 @@ import pytestfrom botocore.exceptions import BotoCoreError, ClientError, EndpointConnectionError, NoCredentialsError, ReadTimeoutErrorfrom pytest_mock import MockerFixture+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.tools.storage.exceptions import StorageFileNotFoundError, StorageInvalidKeyError, StorageS3Errorfrom pipelex.tools.storage.s3_storage_provider import CONDITIONAL_CONFLICT_RETRY_DELAYS_SECONDS, S3StorageProvider, checksum_sha256_header_valuefrom pipelex.tools.storage.storage_provider_abstract import PIPELEX_STORAGE_SCHEME@@ -254,6 +255,7 @@ class TestS3StorageProvider:await s3_provider_no_signed_urls.store(data=b"test", key="test.bin")assert "Bucket not found" in str(exc_info.value)+ assert exc_info.value.resolve_error_code() == PipelexErrorCode.CONFIG_INVALIDasync def test_load_bucket_not_found_raises_error(self,@@ -269,6 +271,7 @@ class TestS3StorageProvider:await s3_provider_no_signed_urls.load(uri=uri)assert "Bucket not found" in str(exc_info.value)+ assert exc_info.value.resolve_error_code() == PipelexErrorCode.CONFIG_INVALIDasync def test_load_client_error_with_no_such_key_code_raises_file_not_found(self,@@ -301,6 +304,7 @@ class TestS3StorageProvider:await s3_provider_no_signed_urls.load(uri=uri)assert "AccessDenied" in str(exc_info.value)+ assert exc_info.value.resolve_error_code() == PipelexErrorCode.CONFIG_CREDENTIAL_REFUSEDasync def test_store_client_error_raises_s3_error(self,@@ -316,6 +320,7 @@ class TestS3StorageProvider:await s3_provider_no_signed_urls.store(data=b"test", key="test.bin")assert "InvalidAccessKeyId" in str(exc_info.value)+ assert exc_info.value.resolve_error_code() == PipelexErrorCode.CONFIG_CREDENTIAL_REFUSEDasync def test_load_no_credentials_error_raises_s3_error(self,@@ -332,6 +337,7 @@ class TestS3StorageProvider:assert "NoCredentialsError" in str(exc_info.value)assert isinstance(exc_info.value.__cause__, BotoCoreError)+ assert exc_info.value.resolve_error_code() == PipelexErrorCode.CONFIG_CREDENTIAL_MISSINGasync def test_store_no_credentials_error_raises_s3_error(self,@@ -347,6 +353,7 @@ class TestS3StorageProvider:assert "NoCredentialsError" in str(exc_info.value)assert isinstance(exc_info.value.__cause__, BotoCoreError)+ assert exc_info.value.resolve_error_code() == PipelexErrorCode.CONFIG_CREDENTIAL_MISSINGasync def test_load_endpoint_connection_error_raises_s3_error(self,@@ -363,6 +370,7 @@ class TestS3StorageProvider:assert "EndpointConnectionError" in str(exc_info.value)assert isinstance(exc_info.value.__cause__, BotoCoreError)+ assert exc_info.value.resolve_error_code() == PipelexErrorCode.STORAGE_UNAVAILABLEasync def test_load_read_timeout_error_raises_s3_error(self,diff --git a/tests/unit/pipelex/tools/uri/test_make_base64_url_from_uri_async.py b/tests/unit/pipelex/tools/uri/test_make_base64_url_from_uri_async.pyindex 3a7337d0a..0bb2b8e6c 100644--- a/tests/unit/pipelex/tools/uri/test_make_base64_url_from_uri_async.py+++ b/tests/unit/pipelex/tools/uri/test_make_base64_url_from_uri_async.py@@ -5,6 +5,8 @@ import httpximport pytestfrom pytest_mock import MockerFixture+from pipelex.errors.registry.pipelex_codes import PipelexErrorCode+from pipelex.tools.storage.exceptions import StorageNotConfiguredErrorfrom pipelex.tools.storage.storage_provider_abstract import PIPELEX_STORAGE_SCHEMEfrom pipelex.tools.uri.uri_base64 import make_base64_url_from_any_urifrom tests.cases import ImageTestCases@@ -79,12 +81,13 @@ class TestMakeBase64UrlFromUriAsync:assert decoded == png_bytesmock_storage.load.assert_called_once_with(uri=storage_uri)- async def test_pipelex_storage_raises_value_error_without_storage(self) -> None:- """Test that pipelex-storage:// URIs raise ValueError when no storage provider is given."""+ async def test_pipelex_storage_is_refused_without_storage(self) -> None:+ """A pipelex-storage:// URI is refused as storage not configured when no storage provider is given."""storage_uri = f"{PIPELEX_STORAGE_SCHEME}images/photo.png"- with pytest.raises(ValueError, match="Cannot convert pipelex-storage"):+ with pytest.raises(StorageNotConfiguredError, match="Cannot convert pipelex-storage") as exc_info:await make_base64_url_from_any_uri(storage_uri)+ assert exc_info.value.resolve_error_code() == PipelexErrorCode.STORAGE_NOT_CONFIGUREDasync def test_http_url_converts_to_base64_data_url(self, mocker: MockerFixture) -> None:"""Test that HTTP URLs are fetched and converted to base64 data URLs."""diff --git a/tests/unit/pipelex/tools/uri/test_uri_bytes.py b/tests/unit/pipelex/tools/uri/test_uri_bytes.pyindex 7916335f6..62eabd0df 100644--- a/tests/unit/pipelex/tools/uri/test_uri_bytes.py+++ b/tests/unit/pipelex/tools/uri/test_uri_bytes.py@@ -6,6 +6,7 @@ import pytestfrom pytest_mock import MockerFixturefrom pipelex.tools.misc.file_fetch_utils import fetch_file_and_content_type_from_url_httpx+from pipelex.tools.storage.exceptions import StorageNotConfiguredErrorfrom pipelex.tools.storage.storage_provider_abstract import PIPELEX_STORAGE_SCHEME, StorageProviderAbstract, StoredDatafrom pipelex.tools.uri import uri_bytesfrom pipelex.tools.uri.uri_bytes import UriBytes, load_bytes_and_mime_type_from_any_uri, load_bytes_from_any_uri@@ -91,7 +92,7 @@ class TestLoadBytesAndMimeTypeFromAnyUri:load_with_metadata.assert_awaited_once_with(uri=storage_uri)async def test_a_storage_key_without_a_provider_is_refused(self) -> None:- with pytest.raises(ValueError, match="without a storage provider"):+ with pytest.raises(StorageNotConfiguredError, match="without a storage provider"):await load_bytes_and_mime_type_from_any_uri(f"{PIPELEX_STORAGE_SCHEME}scope/assets/theme.css")async def test_a_local_path_returns_no_type(self, tmp_path: Path) -> None:diff --git a/uv.lock b/uv.lockindex d7267697d..79379f296 100644--- a/uv.lock+++ b/uv.lock@@ -2754,7 +2754,7 @@ wheels = [[[package]]name = "mthds"-version = "0.22.0"+version = "0.22.1"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "httpx" },@@ -2763,9 +2763,9 @@ dependencies = [{ name = "tomlkit" },{ name = "typing-extensions" },]-sdist = { url = "https://files.pythonhosted.org/packages/d7/e7/d765bd459f47d7c1773c1af847eefc6e1e1cc5e7e7b9266eb99d54945375/mthds-0.22.0.tar.gz", hash = "sha256:0ece0af23f2e412d3fdfa08c2b07881a837292b69c2df721137bf1b319916d1b", size = 365343, upload-time = "2026-10-15T22:04:58.59Z" }+sdist = { url = "https://files.pythonhosted.org/packages/0d/00/86fbece07c3adbe53aa1a935fee525c89cf03438287172762e479a7a71a8/mthds-0.22.1.tar.gz", hash = "sha256:53de0f874786d9ff71912f1bf070bd2c0216a8b25f93a5b3b77f870919e26def", size = 478852, upload-time = "2026-10-18T22:44:12.284Z" }wheels = [- { url = "https://files.pythonhosted.org/packages/ac/f3/2ce468930b48bac1f750a97426f141cded85702c83b02ba3801b11fdefcd/mthds-0.22.0-py3-none-any.whl", hash = "sha256:bed9d09dac9c76c07cdb26675bbcf4eca79c4b926bfff8c0c02bdaa7b643e2e7", size = 149743, upload-time = "2026-10-15T22:04:56.956Z" },+ { url = "https://files.pythonhosted.org/packages/78/16/bea1ef16bf3398b7d1942ae014d9913942209885d939cbd595fed41894ae/mthds-0.22.1-py3-none-any.whl", hash = "sha256:af592e279ee5c7a3395c49171526f03b62462a45b171cb4232bbcb98e17c1066", size = 197875, upload-time = "2026-10-18T22:44:10.145Z" },][[package]]@@ -3736,7 +3736,7 @@ requires-dist = [{ name = "mkdocs-meta-manager", marker = "extra == 'docs'", specifier = ">=1.1.0" },{ name = "mkdocs-redirects", marker = "extra == 'docs'", specifier = "==1.2.2" },{ name = "moto", extras = ["dynamodb", "s3"], marker = "extra == 'dev'", specifier = ">=5.0.0" },- { name = "mthds", specifier = "==0.22.0" },+ { name = "mthds", specifier = "==0.22.1" },{ name = "mypy", marker = "extra == 'dev'", specifier = "==1.19.1" },{ name = "networkx", specifier = ">=3.4.2" },{ name = "openai", specifier = ">=2.0.0" },@@ -3746,7 +3746,7 @@ requires-dist = [{ name = "opentelemetry-semantic-conventions", specifier = ">=0.59b0" },{ name = "packaging", specifier = ">=24.0" },{ name = "pillow", specifier = ">=12.1.1" },- { name = "pipelex-sdk", specifier = "==0.45.0" },+ { name = "pipelex-sdk", specifier = "==0.46.0" },{ name = "pipelex-tools", marker = "extra == 'dev'", specifier = ">=0.7.2" },{ name = "pipelex-tools-py", specifier = ">=0.1.3" },{ name = "polyfactory", specifier = ">=2.21.0" },@@ -3858,7 +3858,7 @@ provides-extras = ["dev"][[package]]name = "pipelex-sdk"-version = "0.45.0"+version = "0.46.0"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "httpx" },@@ -3866,9 +3866,9 @@ dependencies = [{ name = "pydantic" },{ name = "typing-extensions" },]-sdist = { url = "https://files.pythonhosted.org/packages/f8/31/50cb829da5577dbfdaca032b0c4dc2285daa5ceb8c05b299341190ce82a1/pipelex_sdk-0.45.0.tar.gz", hash = "sha256:8e9de14ff0c4fa8787a03ef3f93130dcafd32b97b157cd519460ec5edaba19e3", size = 622581, upload-time = "2026-10-15T22:28:11.191Z" }+sdist = { url = "https://files.pythonhosted.org/packages/cd/66/9f0e2148d96b646357125c30859046e93e7530ba85d82419a5972aaadbbb/pipelex_sdk-0.46.0.tar.gz", hash = "sha256:9c3f7ad921c6d1399125e9c687b8ac720199fb29ba1ffeac7bef008118a41f25", size = 644042, upload-time = "2026-10-19T07:19:39.969Z" }wheels = [- { url = "https://files.pythonhosted.org/packages/b9/7c/9ec2d03af8aabe69ac272153f36543809f58b4d5de4243b41ad1767b0545/pipelex_sdk-0.45.0-py3-none-any.whl", hash = "sha256:b037e34aec048b85b60e70dac6098f8753a0e1472ed71b9274dfef805a8280c2", size = 241187, upload-time = "2026-10-15T22:28:09.638Z" },+ { url = "https://files.pythonhosted.org/packages/82/fe/6a2cc6394ed34f89096fa0fbc3a5330a99df716958f5799dc6abcde13d87/pipelex_sdk-0.46.0-py3-none-any.whl", hash = "sha256:db6b6c8e27578671984352a806294062e91aa0b5189ced658be94a8ee1e4f175", size = 254349, upload-time = "2026-10-19T07:19:38.333Z" },][[package]]