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/Problem-replaces-errorreport · L-261015-751c9a (#1450)
Louis Choquel2b9c721ad982
diff --git a/.drift/acks/cli-docs.toml b/.drift/acks/cli-docs.tomlindex 95c423347..7882bc2e4 100644--- a/.drift/acks/cli-docs.toml+++ b/.drift/acks/cli-docs.toml@@ -1,8 +1,8 @@contract = "cli-docs"-digest = "sha256:50fca9184cd1ec73cf925205ddb1cc75ee36db1d45ef3e025ef213fbe4bf4e95"+digest = "sha256:b626be1be5722c6a18de9dc925647ab01eff48908a67a4f568da6295a1e711aa"reviewed_by = "Louis Choquel"-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."+reviewed_at = "2026-10-18T10:52:34Z"+rationale = "clean-pass: merging code-on-every-error, which carries dev's v0.89.0, into the Problem branch combines changes each side reviewed; run bundle keeps both arms, the run's own MethodEntryError for a folder with no single main_pipe and dev's pre-boot configuration refusal, now through bundle_target_resolution.py. docs/tools/cli/run.md and agent-cli.md, and pipelex/cli/agent_cli/CLAUDE.md, which this merge updated to dev's paths and anchors, describe both."[trigger_files]"pipelex/cli/__init__.py" = "blob:8b137891791fe96927ad78e64b0aad7bded08bdc"@@ -11,7 +11,7 @@ rationale = "clean-pass: merging the error registry branch, which carries dev's"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:1e816dea1a7439e0bd0030754a5c519112aeead0"-"pipelex/cli/agent_cli/commands/agent_output.py" = "blob:bdc4f04b61c8824de88afdf76cf394a41e102a82"+"pipelex/cli/agent_cli/commands/agent_output.py" = "blob:0e6c177a0e7b8156f6b43c57ae87b2e87cadf661""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"@@ -40,7 +40,7 @@ rationale = "clean-pass: merging the error registry branch, which carries dev's"pipelex/cli/agent_cli/commands/run/_run_core.py" = "blob:d71aee873856cfa72eb0ff18eb82c79e348f124a""pipelex/cli/agent_cli/commands/run/_run_hosted.py" = "blob:cea011e61feb082a7b9d82d7693b4fd3246737e5""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/bundle_cmd.py" = "blob:81ce053d4401a782bfce0d5536d6e4d3fc748a6d""pipelex/cli/agent_cli/commands/run/method_cmd.py" = "blob:776d1cf4bfbdce645f3cbfcd28be46bfb97174b0""pipelex/cli/agent_cli/commands/run/pipe_cmd.py" = "blob:f6be2d8b0a5e20c087a12fdaf8c42eb2549dfb00""pipelex/cli/agent_cli/commands/run/stdin_resolver.py" = "blob:847552a863af5f8e98a4ce1c473c2e828b86a5d6"@@ -50,7 +50,7 @@ rationale = "clean-pass: merging the error registry branch, which carries dev's"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:c945950c88d4049b5c6400111ccb85b0cb4cc657"-"pipelex/cli/bundle_target_resolution.py" = "blob:0a8fb2b29a9386a9b488d000756da2914713060c"+"pipelex/cli/bundle_target_resolution.py" = "blob:fd4c1da386c33f4542c11a68ad4ce5bed64bc4aa""pipelex/cli/cli_factory.py" = "blob:9768ead842eecbfc9509dc68aafca31957a27439""pipelex/cli/commands/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391""pipelex/cli/commands/build/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"@@ -74,7 +74,7 @@ rationale = "clean-pass: merging the error registry branch, which carries dev's"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:3e02d407446ef745116ade9cd08a81990c97bbf8"+"pipelex/cli/commands/crate_loading.py" = "blob:d7bc8e226945cd9ee8fe443adbf252fb0bb14831""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"@@ -115,8 +115,8 @@ rationale = "clean-pass: merging the error registry branch, which carries dev's"pipelex/cli/commands/run/_run_hosted.py" = "blob:80df4e50e7f4ece31ebf4d51e34dbddef9466cae""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:badc192d5239fe402d4d7a18504bb4a01e9c260a"+"pipelex/cli/commands/run/bundle_cmd.py" = "blob:faff9a7cba8027bb7b13f7f5a3b94666f3742b80"+"pipelex/cli/commands/run/exceptions.py" = "blob:cebeb5950c87a1e113ed717565ae8cb783bb5001""pipelex/cli/commands/run/method_cmd.py" = "blob:924bca6e242d8490e32eeb9ed2329db3d1b58b8d""pipelex/cli/commands/run/pipe_cmd.py" = "blob:c967729a039518a718d7bc28d77797423ce20fc4""pipelex/cli/commands/show_cmd.py" = "blob:764665c787525a52d44bff1fb6e64acd008729aa"@@ -130,7 +130,7 @@ rationale = "clean-pass: merging the error registry branch, which carries dev's"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:bbe95242b498478557832dcab625dc4fe2694f44"+"pipelex/cli/error_handlers.py" = "blob:a54aba5689ffcb6bfda2b842b2875f4121683787""pipelex/cli/exceptions.py" = "blob:5c66f20b0a06c8ae8c20b94f92e2c30b78f5b6c5""pipelex/cli/installed_methods.py" = "blob:1de9b36e7717786fe0454af69011e05ef50610ba""pipelex/cli/judged_target.py" = "blob:8d3f3b3359992feeeca2bd4acd1d404262cbaf87"diff --git a/.drift/acks/pipelex-kernel-docs.toml b/.drift/acks/pipelex-kernel-docs.tomlindex a1071e60e..91d85dacf 100644--- a/.drift/acks/pipelex-kernel-docs.toml+++ b/.drift/acks/pipelex-kernel-docs.toml@@ -1,8 +1,8 @@contract = "pipelex-kernel-docs"-digest = "sha256:4d57f0b48f71d64483bf0b6eaae5fdb46e569781477e23f31625ba2e4a49f4aa"+digest = "sha256:16fabe1ce1d3ef30ab6c155bf87f87acc09b63d9b5443256570c3b38a49af871"reviewed_by = "Louis Choquel"-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."+reviewed_at = "2026-10-17T00:39:22Z"+rationale = "clean-pass: the served-model check now gives its refusal the model handle and the capability as params; pipelex-kernel.md stays accurate and now names both params."[trigger_files]"pipelex/kernel/__init__.py" = "blob:c4f1b0fe2ccc17db9110733f71b612f4ac1ba4ce"@@ -18,7 +18,7 @@ rationale = "real-catch: the kernel split call_function into invoke_function and"pipelex/kernel/img_gen_results.py" = "blob:46b4ca11c70d906ae6d58ce66461f9b3414f1bfa""pipelex/kernel/judgment_ops.py" = "blob:6bf523ecd35390e76a8150755a71295d24977698""pipelex/kernel/judgment_results.py" = "blob:4dbbcb204309265999de59a179f4420a0f83be93"-"pipelex/kernel/llm_ops.py" = "blob:ce23b49ee5050ac38af7ba518fc6a632216f78fb"+"pipelex/kernel/llm_ops.py" = "blob:730c080684a1f3c1bb90d599105b1789eb6ee10a""pipelex/kernel/llm_prompt_content.py" = "blob:f996cead6e7789494f01f69c128ae71d6dcf8466""pipelex/kernel/llm_results.py" = "blob:6e3b8a2878b5bb284ece5fac10262fb59ac2029d""pipelex/kernel/memory_ops.py" = "blob:7fbbfaaec99f9712d8e215520cb02e26aad3fb40"diff --git a/.test_durations b/.test_durationsindex e02874ce4..8eaed1ccc 100644--- a/.test_durations+++ b/.test_durations@@ -465,9 +465,6 @@"tests/integration/pipelex/csv/test_csv_roundtrip.py::TestCsvRoundtrip::test_csv_input_builds_typed_list": 1.3523,"tests/integration/pipelex/csv/test_csv_roundtrip.py::TestCsvRoundtrip::test_full_pipeline_round_trip": 8.8683,"tests/integration/pipelex/csv/test_csv_roundtrip.py::TestCsvRoundtrip::test_list_content_writes_to_csv": 0.4644,- "tests/integration/pipelex/error_handling/test_error_report_local_full_chain.py::TestErrorReportLocalFullChain::test_error_report_from_local_execution": 1.9127,- "tests/integration/pipelex/error_handling/test_judge_error_report_local_full_chain.py::TestJudgeErrorReportLocalFullChain::test_error_report_from_local_execution": 0.0941,- "tests/integration/pipelex/error_handling/test_search_error_report_local_full_chain.py::TestSearchErrorReportLocalFullChain::test_error_report_from_local_execution": 1.5547,"tests/integration/pipelex/kernel/test_usage_parity.py::TestKernelUsageParity::test_both_callers_produce_the_same_usage_records": 2.7057,"tests/integration/pipelex/kernel/test_usage_parity.py::TestKernelUsageParity::test_the_direct_call_facade_stays_deliberately_anonymous": 0.6139,"tests/integration/pipelex/kit/test_cursor_rules_update.py::TestUpdateCursorRules::test_update_cursor_rules_creates_mdc_files[all]": 1.1355,@@ -1017,13 +1014,6 @@"tests/integration/pipelex/pipeline/test_sequence_output_enrichment.py::TestSequenceOutputEnrichment::test_sub_pipe_multiplicity_override_wins_in_expected_ref": 0.1426,"tests/integration/pipelex/pipeline/test_sequence_output_enrichment.py::TestSequenceOutputEnrichment::test_wrong_concept_carries_expected_output_ref": 1.1122,"tests/integration/pipelex/pipeline/test_sequence_output_enrichment.py::TestSequenceOutputEnrichment::test_wrong_multiplicity_carries_expected_output_ref": 0.1664,- "tests/integration/pipelex/pipeline/test_strict_method_faults.py::TestStrictMethodFaults::test_missing_required_input_is_the_callers_fault": 0.0089,- "tests/integration/pipelex/pipeline/test_strict_method_faults.py::TestStrictMethodFaults::test_model_only_the_method_names_is_the_callers_fault": 0.0662,- "tests/integration/pipelex/pipeline/test_strict_method_faults.py::TestStrictMethodFaults::test_model_output_that_does_not_fit_its_structure_stays_redacted": 0.0173,- "tests/integration/pipelex/pipeline/test_strict_method_faults.py::TestStrictMethodFaults::test_model_the_deck_names_but_does_not_serve_stays_redacted[alias-@strict-faults-deck-alias]": 0.0219,- "tests/integration/pipelex/pipeline/test_strict_method_faults.py::TestStrictMethodFaults::test_model_the_deck_names_but_does_not_serve_stays_redacted[preset-$strict-faults-deck-preset]": 0.0275,- "tests/integration/pipelex/pipeline/test_strict_method_faults.py::TestStrictMethodFaults::test_parallel_combine_mismatch_is_the_callers_fault": 0.1342,- "tests/integration/pipelex/pipeline/test_strict_method_faults.py::TestStrictMethodFaults::test_parallel_combine_refusal_no_multiplicity_explains_is_the_callers_fault": 0.0165,"tests/integration/pipelex/pipeline/test_strip_namespace_enrichment.py::TestStripNamespaceEnrichment::test_dotted_declaration_carries_rename_enrichment": 1.1527,"tests/integration/pipelex/pipeline/test_strip_namespace_enrichment.py::TestStripNamespaceEnrichment::test_dotted_main_pipe_carries_strip_enrichment_without_pipe_code": 0.1347,"tests/integration/pipelex/pipeline/test_strip_namespace_enrichment.py::TestStripNamespaceEnrichment::test_main_pipe_strip_enriched_when_dotted_declaration_will_rename": 0.1261,@@ -7114,7 +7104,7 @@"tests/unit/pipelex/cogt/test_cogt_dependency_boundaries.py::TestCogtDependencyBoundaries::test_import_target_resolves_a_submodule_but_not_a_symbol[from pipelex.providers.anthropic.anthropic_config import AnthropicConfig-expected3]": 0.0017,"tests/unit/pipelex/cogt/test_cogt_dependency_boundaries.py::TestCogtDependencyBoundaries::test_import_target_resolves_a_submodule_but_not_a_symbol[from pydantic import BaseModel-expected5]": 0.0007,"tests/unit/pipelex/cogt/test_cogt_dependency_boundaries.py::TestCogtDependencyBoundaries::test_import_target_resolves_a_submodule_but_not_a_symbol[import pipelex.providers.openai.openai_config-expected6]": 0.0007,- "tests/unit/pipelex/cogt/test_cogt_provider_metadata_wrapper_wins.py::TestCogtProviderMetadataWrapperWins::test_wrapper_provider_metadata_wins_even_when_cause_has_richer_metadata": 0.9254,+ "tests/unit/pipelex/cogt/test_cogt_provider_facts_merge.py::TestCogtProviderFactsMerge::test_a_wrapper_keeps_what_its_cause_recorded_of_the_provider_answer": 0.9254,"tests/unit/pipelex/cogt/test_error_classification.py::TestErrorClassification::test_is_content_policy_violation[blocked_by_safety-The response was blocked by safety systems-True]": 0.0003,"tests/unit/pipelex/cogt/test_error_classification.py::TestErrorClassification::test_is_content_policy_violation[case_insensitive-Content_Policy violation detected-True]": 0.0004,"tests/unit/pipelex/cogt/test_error_classification.py::TestErrorClassification::test_is_content_policy_violation[content_filter-content_filter triggered for this request-True]": 0.0009,@@ -9291,11 +9281,6 @@"tests/unit/pipelex/errors/test_validation_error_types.py::TestValidationErrorTypeRegistry::test_registry_holds_every_member_of_every_contributing_enum": 1.305,"tests/unit/pipelex/errors/test_validation_error_types.py::TestValidationErrorTypeRegistry::test_registry_order_is_deterministic": 0.0169,"tests/unit/pipelex/errors/test_validation_error_types.py::TestValidationErrorTypeRegistry::test_the_parse_level_residual_may_carry_no_error_type": 0.0123,- "tests/unit/pipelex/exceptions/test_as_caller_fault.py::TestAsCallerFault::test_a_located_wrapper_reports_the_caller_fault_it_locates": 0.0011,- "tests/unit/pipelex/exceptions/test_as_caller_fault.py::TestAsCallerFault::test_a_wrapper_inherits_the_domain_but_never_the_caller_facing_flag": 0.0006,- "tests/unit/pipelex/exceptions/test_as_caller_fault.py::TestAsCallerFault::test_classifies_this_error_only": 0.1161,- "tests/unit/pipelex/exceptions/test_as_caller_fault.py::TestAsCallerFault::test_strict_disclosure_keeps_the_message_and_the_user_action": 0.0011,- "tests/unit/pipelex/exceptions/test_as_caller_fault.py::TestAsCallerFault::test_wins_over_a_domain_the_category_derives": 0.0005,"tests/unit/pipelex/exceptions/test_class_level_metadata.py::TestClassLevelMetadata::test_caller_facing_message[cogt-exc14-False]": 0.0488,"tests/unit/pipelex/exceptions/test_class_level_metadata.py::TestClassLevelMetadata::test_caller_facing_message[cogt-exc8-False]": 0.0009,"tests/unit/pipelex/exceptions/test_class_level_metadata.py::TestClassLevelMetadata::test_caller_facing_message[config-exc12-False]": 0.0959,@@ -9867,11 +9852,6 @@"tests/unit/pipelex/graph/test_trace_context_emit_flags.py::TestTraceContextEmitFlags::test_copy_for_child_preserves_describe_pipe_io_off": 0.2496,"tests/unit/pipelex/graph/test_trace_context_emit_flags.py::TestTraceContextEmitFlags::test_copy_for_child_preserves_graph_only_flags": 0.1706,"tests/unit/pipelex/graph/test_trace_context_emit_flags.py::TestTraceContextEmitFlags::test_defaults_emit_both_streams": 1.1304,- "tests/unit/pipelex/graph/test_traced_failure.py::TestTracedFailure::test_a_failure_records_its_message_and_whether_it_was_written_for_the_caller[caller_fault]": 0.1103,- "tests/unit/pipelex/graph/test_traced_failure.py::TestTracedFailure::test_a_failure_records_its_message_and_whether_it_was_written_for_the_caller[foreign_exception]": 0.1763,- "tests/unit/pipelex/graph/test_traced_failure.py::TestTracedFailure::test_a_failure_records_its_message_and_whether_it_was_written_for_the_caller[pipelex_error]": 0.0006,- "tests/unit/pipelex/graph/test_traced_failure.py::TestTracedFailure::test_a_pipelex_error_records_its_report_message": 0.0012,- "tests/unit/pipelex/graph/test_traced_failure.py::TestTracedFailure::test_a_report_that_cannot_be_built_records_the_errors_text": 0.0051,"tests/unit/pipelex/hosted/test_api_key_check.py::TestApiKeyCheck::test_a_401_or_a_403_refuses_the_key[401]": 0.0032,"tests/unit/pipelex/hosted/test_api_key_check.py::TestApiKeyCheck::test_a_401_or_a_403_refuses_the_key[403]": 0.0024,"tests/unit/pipelex/hosted/test_api_key_check.py::TestApiKeyCheck::test_a_base_url_that_is_not_an_origin_leaves_the_key_unchecked": 0.004,@@ -16032,74 +16012,6 @@"tests/unit/pipelex/test_config_pre_boot.py::TestConfigPreBoot::test_fetch_ssrf_guard_is_enabled_without_hub": 0.0765,"tests/unit/pipelex/test_config_pre_boot.py::TestConfigPreBoot::test_get_optional_config_returns_none_without_hub": 1.0436,"tests/unit/pipelex/test_config_pre_boot.py::TestConfigPreBoot::test_pipe_func_execution_mode_defaults_to_direct_without_hub": 0.1066,- "tests/unit/pipelex/test_error_http_status.py::TestErrorHttpStatus::test_error_domain_to_http_status[None-500]": 0.0008,- "tests/unit/pipelex/test_error_http_status.py::TestErrorHttpStatus::test_error_domain_to_http_status[config-500_0]": 0.0025,- "tests/unit/pipelex/test_error_http_status.py::TestErrorHttpStatus::test_error_domain_to_http_status[config-500_1]": 0.0003,- "tests/unit/pipelex/test_error_http_status.py::TestErrorHttpStatus::test_error_domain_to_http_status[domain-from-the-future-500]": 0.001,- "tests/unit/pipelex/test_error_http_status.py::TestErrorHttpStatus::test_error_domain_to_http_status[input-422_0]": 1.7516,- "tests/unit/pipelex/test_error_http_status.py::TestErrorHttpStatus::test_error_domain_to_http_status[input-422_1]": 0.0004,- "tests/unit/pipelex/test_error_http_status.py::TestErrorHttpStatus::test_error_domain_to_http_status[runtime-500_0]": 0.0005,- "tests/unit/pipelex/test_error_http_status.py::TestErrorHttpStatus::test_error_domain_to_http_status[runtime-500_1]": 0.001,- "tests/unit/pipelex/test_error_http_status.py::TestErrorHttpStatus::test_error_report_http_status_follows_domain[None-500]": 0.0008,- "tests/unit/pipelex/test_error_http_status.py::TestErrorHttpStatus::test_error_report_http_status_follows_domain[config-500]": 0.0009,- "tests/unit/pipelex/test_error_http_status.py::TestErrorHttpStatus::test_error_report_http_status_follows_domain[input-422]": 0.0004,- "tests/unit/pipelex/test_error_http_status.py::TestErrorHttpStatus::test_error_report_http_status_follows_domain[runtime-500]": 0.0006,- "tests/unit/pipelex/test_error_http_status.py::TestErrorHttpStatus::test_non_429_provider_status_does_not_override_domain": 0.001,- "tests/unit/pipelex/test_error_http_status.py::TestErrorHttpStatus::test_provider_429_takes_precedence_over_domain": 0.0007,- "tests/unit/pipelex/test_error_http_status.py::TestErrorHttpStatus::test_unknown_error_domain_falls_back_to_500": 0.1779,- "tests/unit/pipelex/test_error_report_disclosure_mode.py::TestErrorReportDisclosureMode::test_caller_facing_message_serialized_only_when_set": 0.0006,- "tests/unit/pipelex/test_error_report_disclosure_mode.py::TestErrorReportDisclosureMode::test_receiver_rehydrates_verbose_payload_for_webhook": 0.1117,- "tests/unit/pipelex/test_error_report_disclosure_mode.py::TestErrorReportDisclosureMode::test_retryable_survives_disclosure_mode[strict-retryable-false]": 0.0006,- "tests/unit/pipelex/test_error_report_disclosure_mode.py::TestErrorReportDisclosureMode::test_retryable_survives_disclosure_mode[strict-retryable-none]": 0.0008,- "tests/unit/pipelex/test_error_report_disclosure_mode.py::TestErrorReportDisclosureMode::test_retryable_survives_disclosure_mode[strict-retryable-true]": 0.0007,- "tests/unit/pipelex/test_error_report_disclosure_mode.py::TestErrorReportDisclosureMode::test_retryable_survives_disclosure_mode[verbose-retryable-false]": 0.0008,- "tests/unit/pipelex/test_error_report_disclosure_mode.py::TestErrorReportDisclosureMode::test_retryable_survives_disclosure_mode[verbose-retryable-none]": 0.0008,- "tests/unit/pipelex/test_error_report_disclosure_mode.py::TestErrorReportDisclosureMode::test_retryable_survives_disclosure_mode[verbose-retryable-true]": 0.0011,- "tests/unit/pipelex/test_error_report_disclosure_mode.py::TestErrorReportDisclosureMode::test_strict_branch_kept_field_parity": 0.0003,- "tests/unit/pipelex/test_error_report_disclosure_mode.py::TestErrorReportDisclosureMode::test_strict_does_not_round_trip": 0.0005,- "tests/unit/pipelex/test_error_report_disclosure_mode.py::TestErrorReportDisclosureMode::test_strict_does_not_sanitize_paths_inside_a_caller_facing_message": 0.0003,- "tests/unit/pipelex/test_error_report_disclosure_mode.py::TestErrorReportDisclosureMode::test_strict_omits_provider_metadata_when_only_curated_subset_is_empty": 0.0005,- "tests/unit/pipelex/test_error_report_disclosure_mode.py::TestErrorReportDisclosureMode::test_strict_passes_through_caller_facing_message": 0.0005,- "tests/unit/pipelex/test_error_report_disclosure_mode.py::TestErrorReportDisclosureMode::test_strict_passes_through_real_interpreter_error_message": 0.001,- "tests/unit/pipelex/test_error_report_disclosure_mode.py::TestErrorReportDisclosureMode::test_strict_payload_with_provider_metadata_fails_from_dict_rehydration": 0.0013,- "tests/unit/pipelex/test_error_report_disclosure_mode.py::TestErrorReportDisclosureMode::test_strict_preserves_curated_provider_metadata": 0.0008,- "tests/unit/pipelex/test_error_report_disclosure_mode.py::TestErrorReportDisclosureMode::test_strict_provider_metadata_dict_carries_http_status_for_adapter": 0.0011,- "tests/unit/pipelex/test_error_report_disclosure_mode.py::TestErrorReportDisclosureMode::test_strict_redacts_domain_less_wrapper_raised_from_input_cause": 0.0007,- "tests/unit/pipelex/test_error_report_disclosure_mode.py::TestErrorReportDisclosureMode::test_strict_redacts_non_caller_facing_reports[config]": 0.0004,- "tests/unit/pipelex/test_error_report_disclosure_mode.py::TestErrorReportDisclosureMode::test_strict_redacts_non_caller_facing_reports[input-domain-wrapper]": 0.0006,- "tests/unit/pipelex/test_error_report_disclosure_mode.py::TestErrorReportDisclosureMode::test_strict_redacts_non_caller_facing_reports[runtime]": 0.0014,- "tests/unit/pipelex/test_error_report_disclosure_mode.py::TestErrorReportDisclosureMode::test_strict_retains_validation_errors_on_both_branches[caller-facing-branch]": 0.0003,- "tests/unit/pipelex/test_error_report_disclosure_mode.py::TestErrorReportDisclosureMode::test_strict_retains_validation_errors_on_both_branches[redacted-branch]": 0.0003,- "tests/unit/pipelex/test_error_report_disclosure_mode.py::TestErrorReportDisclosureMode::test_strict_strips_provider_fields_even_from_caller_facing_passthrough": 0.0013,- "tests/unit/pipelex/test_error_report_disclosure_mode.py::TestErrorReportDisclosureMode::test_to_dict_defaults_to_verbose": 0.0004,- "tests/unit/pipelex/test_error_report_disclosure_mode.py::TestErrorReportDisclosureMode::test_verbose_preserves_every_populated_field[caller-facing]": 0.0004,- "tests/unit/pipelex/test_error_report_disclosure_mode.py::TestErrorReportDisclosureMode::test_verbose_preserves_every_populated_field[config]": 0.0005,- "tests/unit/pipelex/test_error_report_disclosure_mode.py::TestErrorReportDisclosureMode::test_verbose_preserves_every_populated_field[input-domain-wrapper]": 0.0004,- "tests/unit/pipelex/test_error_report_disclosure_mode.py::TestErrorReportDisclosureMode::test_verbose_preserves_every_populated_field[runtime]": 1.1369,- "tests/unit/pipelex/test_error_report_disclosure_mode.py::TestErrorReportDisclosureMode::test_verbose_round_trip_preserves_report[caller-facing]": 0.0005,- "tests/unit/pipelex/test_error_report_disclosure_mode.py::TestErrorReportDisclosureMode::test_verbose_round_trip_preserves_report[runtime]": 0.0004,- "tests/unit/pipelex/test_error_report_from_dict.py::TestErrorReportFromDict::test_from_dict_round_trips_to_dict[full-with-user-action]": 0.001,- "tests/unit/pipelex/test_error_report_from_dict.py::TestErrorReportFromDict::test_from_dict_round_trips_to_dict[minimal]": 0.7869,- "tests/unit/pipelex/test_error_report_from_dict.py::TestErrorReportFromDict::test_from_dict_round_trips_to_dict[provider-metadata-429]": 0.0012,- "tests/unit/pipelex/test_error_report_from_dict.py::TestErrorReportFromDict::test_g1_from_dict_raises_on_malformed_dict[extra-forbidden-key]": 0.001,- "tests/unit/pipelex/test_error_report_from_dict.py::TestErrorReportFromDict::test_g1_from_dict_raises_on_malformed_dict[missing-required-error-type]": 0.0004,- "tests/unit/pipelex/test_error_report_from_dict.py::TestErrorReportFromDict::test_g1_from_dict_raises_on_malformed_dict[missing-required-message]": 0.0003,- "tests/unit/pipelex/test_error_report_from_dict.py::TestErrorReportFromDict::test_g1_from_dict_raises_on_malformed_dict[missing-required-title]": 0.0014,- "tests/unit/pipelex/test_error_report_from_dict.py::TestErrorReportFromDict::test_g1_from_dict_raises_on_malformed_dict[missing-required-type-uri]": 0.0005,- "tests/unit/pipelex/test_error_report_from_dict.py::TestErrorReportFromDict::test_g1_from_dict_raises_on_malformed_dict[wrong-field-type]": 0.1388,- "tests/unit/pipelex/test_error_report_problem_document.py::TestErrorReportProblemDocument::test_caller_facing_message_flag_never_rides_as_extension_member": 0.1066,- "tests/unit/pipelex/test_error_report_problem_document.py::TestErrorReportProblemDocument::test_extension_members_carry_pipelex_classification": 0.0014,- "tests/unit/pipelex/test_error_report_problem_document.py::TestErrorReportProblemDocument::test_instance_extension_absent_when_not_provided": 0.0007,- "tests/unit/pipelex/test_error_report_problem_document.py::TestErrorReportProblemDocument::test_request_id_extension_absent_when_not_provided": 0.0004,- "tests/unit/pipelex/test_error_report_problem_document.py::TestErrorReportProblemDocument::test_rfc_7807_mapping_does_not_duplicate_title_or_type": 0.0009,- "tests/unit/pipelex/test_error_report_problem_document.py::TestErrorReportProblemDocument::test_standard_slots_populated_from_report": 0.8332,- "tests/unit/pipelex/test_error_report_problem_document.py::TestErrorReportProblemDocument::test_status_follows_http_status_property[config-500]": 0.0008,- "tests/unit/pipelex/test_error_report_problem_document.py::TestErrorReportProblemDocument::test_status_follows_http_status_property[input-422]": 0.001,- "tests/unit/pipelex/test_error_report_problem_document.py::TestErrorReportProblemDocument::test_status_follows_http_status_property[runtime-500]": 0.0006,- "tests/unit/pipelex/test_error_report_problem_document.py::TestErrorReportProblemDocument::test_strict_mode_never_emits_provider_fields_regardless_of_error_domain": 0.0006,- "tests/unit/pipelex/test_error_report_problem_document.py::TestErrorReportProblemDocument::test_strict_mode_passes_through_detail_for_caller_facing_report": 0.0009,- "tests/unit/pipelex/test_error_report_problem_document.py::TestErrorReportProblemDocument::test_strict_mode_redacts_detail_and_drops_disclosure_fields": 0.0009,- "tests/unit/pipelex/test_error_report_problem_document.py::TestErrorReportProblemDocument::test_strict_mode_redacts_detail_for_input_domain_without_caller_facing_flag": 0.0005,"tests/unit/pipelex/test_extras/test_ci_placeholder_keys.py::TestCiPlaceholderKeys::test_every_enabled_kit_backend_variable_gets_a_ci_placeholder": 0.0593,"tests/unit/pipelex/test_extras/test_mthds_corpus_exhaustivity.py::TestMthdsCorpusExhaustivity::test_every_invalid_entry_covers_the_tag_its_expected_error_names": 0.1897,"tests/unit/pipelex/test_extras/test_mthds_corpus_exhaustivity.py::TestMthdsCorpusExhaustivity::test_every_required_error_tag_declares_the_layer_it_fails_at": 0.6326,diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0f1d884d1..45a6542d0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,30 +9,40 @@- **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.- **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`).+- **`PipelexError.with_items()`**: a raise site that finds several faults of one kind gives one problem item per fault, so a `PipeParallel` whose branches give several results of a multiplicity their fields do not declare names each one in its `pipe.output_multiplicity` problem's `errors`, beside the first in its sentence.- **`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 problem document replaces `ErrorReport` (Breaking)**: every `PipelexError` answers a problem document, `PipelexError.to_problem(view=...)` building a `PipelexProblem` (`pipelex.errors.problem`), where it built an `ErrorReport`: its `type`, `title`, `status`, `domain`, `retry` and `next_step` are its code's, its `type` the code's page (`https://mthds.ai/errors/<code>` for a core code, `https://docs.pipelex.com/errors/<code>` for a Pipelex code), its `detail` and its step are rendered from the code's templates and the parameters the error gives, the code's title standing in for a sentence a missing parameter leaves unrendered, a refusal of several faults lists them in `errors`, and the Pipelex members `request_id`, `run_error` and `diagnostics` join the standard's. A problem never writes a member a model declares as `null`, while a `null` an extension member or a free-form object holds is written as it was read, `to_wire()` writes back every problem a reader accepts however deeply an extension member nests, a parameter of a type its code does not declare, an infinite or `NaN` number and a value that is neither a JSON scalar nor a list of them included, is dropped and logged rather than raise in place of the error, and an item never carries a parameter its code keeps for the operator, whoever built it, the caller reading an item whose code this process does not know with no parameter and a generic sentence. `ErrorReport`, `TracedFailure` and the graph's `ErrorSpec` are gone, and `error_type` is no member of a problem: the operator reads the error's class as `diagnostics.error_class`.+- **The reader's identity picks the view of a failure (Breaking)**: a problem is read in the caller's view, its sentences rendered from the parameters a caller may read, or in the operator's, which adds `diagnostics` (the error's class and message, its causes, the model, the provider's answer, a migration, the runtime version and the trace) and the operator's own next step; `DisclosureMode`, the `ERROR_DISCLOSURE` setting and `caller_facing_message` are gone, and `caller_view_of()` projects an operator's problem to the caller's, giving a code this process's registries do not hold the generic step of its kind, `report` for an operator's code. The runner answers the operator's view to a request carrying its static API key (`AUTH_MODE=api_key`) or reaching it through a trusted proxy (`AUTH_MODE=none` with `TRUST_FORWARDED_IDENTITY_HEADERS=true`), which owes its own callers their caller view, and the caller's view to every other request, and a webhook receives the view its target's `problem_view` names, the caller's by default, the problem built only for a run that has a webhook and never replacing the run's own error when it cannot be built.+- **The runner answers each code's HTTP status (Breaking)**: an error response's status is its code's, from the error registry, where it followed the error's domain and a table of per-class overrides, so `provider.unavailable` answers 502, `provider.timeout` 504, `model.unavailable` 501, a method that cannot be fetched (`method.fetch_failed`) 502 where it answered 422, and a fetched method declaring Python structures (`pipelex.deployment.python_structures_refused`) 422 where it answered 403; `Retry-After` rides a 429 alone, and an exception that is not a Pipelex error answers `runtime.unexpected`, a 500.+- **An input refusal names the input and what is wrong with it**: a refusal of a run's inputs carries the input in `params.input` and `location.input`, with the facts its code declares, the expected and provided counts of `input.wrong_multiplicity`, the declared and provided concepts of `input.wrong_concept` and the field at fault of `input.invalid` when the concept's structure names one, so its `detail` names the input and its fault.+- **A run failure's problem names its pipe and path**: the problem of a run that failed inside a pipe carries the failing pipe and the pipes leading to it as `location.pipe` and `location.path`, and fills the `pipe` parameter of a code that declares one, while a failure of the entry pipe before any step carries no location. The location also keeps what the errors between the run and its root fault know, such as the field and the file a pipe met an unknown model at, and the diagnostics keep the model and the backend a worker attributed the failure to on an error above the root fault, an inner router's stand-in for a foreign exception included. A parameter a wrapper above the error whose code the problem reports gave, and its code declares, fills the one that error gave none of, and the items a wrapper gave follow that error's own.+- **A graph node's error is its problem (Breaking)**: a failed node of a `GraphSpec`, and the trace event that ended its pipe, carry the problem in the caller's view in `error`, located at the node's pipe and path, and the stack trace, when the graph's data inclusion asks for it, in `error_stack`, capped at the same length on both, where `error` held `error_type`, `message`, `stack` and `caller_facing`.+- **Plugin API v9 (Breaking)**: an HTTP-error mapper registered with `add_http_error_mapper(exc_type_provider=..., to_pipelex_error=...)` returns the `PipelexError` a transport exception stands for, where `to_error_report` returned a report, and a bundle validator's `validate_bundles` returns a `BundleValidationFailure`, the refusal's problem in the operator's view with its validation items, as its invalid verdict, and a host plugin's carrier of a problem recovered across a transport boundary overrides `PipelexError.recovered_problem()` to return it rather than overriding `to_problem()`, which a located run failure no longer reads as a carrier; `PLUGIN_API_VERSION` moves to 9, so a plugin declaring `targets_api = 8` is refused at discovery with `PluginApiVersionMismatchError`.+- **`pipelex.test_extras.problem_parity` (Breaking)**: the parity fixtures a distributed executor's tests share with the local runner's moved from `pipelex.test_extras.error_report_parity`, and their classes are `ProblemParityTestData`, `SearchProblemParityTestData` and `JudgeProblemParityTestData`.+- **A run failure reports its root fault's code (Breaking)**: the root fault a run failure's problem reports is the first error down its cause chain that declares a code of its own, and its code, title, type, domain and retry verdict are the problem'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`. A failure below an exception that is not a Pipelex error lends the error above it no code, fact, location or advice.- **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.+- **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 bare selector matching pipes in several domains `request.pipe_ambiguous`, a request with no selector over a closure declaring no `main_pipe`, or several, `request.pipe_unspecified`, naming the declared ones as its `candidates`, a manifest `main_pipe` the closure lacks `method.pipe_unresolved`, and one it declares in several domains `method.ref_ambiguous`, all still a 422, a dependency's `alias->code` matching pipes in several of its domains naming them as `candidates` too; a run of a method on disk with no pipe named refuses several declared `main_pipe`s and a manifest `main_pipe` several bundles define the same way.- **`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 context-window or 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.+- **`pipelex-agent` reads `retryable` from the code (Breaking)**: the agent CLI's error envelope takes `retryable` from the error'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, and its `hint`, when the error's chain advises nothing and the table names no hint for its class, is its code's next step as the operator reads it.+- **`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 class name, which the operator reads as `diagnostics.error_class`, its title and its 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 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 `model.unavailable`, with the reason `not_served`, for a bare handle no backend serves, answered 501, and `pipelex.config.invalid` for a preset, an alias or a waterfall the deck does not define, answered 500, with the deck setting in the operator's diagnostics alone, 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 reaches the operator's diagnostics alone, 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, 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 failure's message is bounded**: the error's message a problem carries in `diagnostics.message`, a provider's answer and every text parameter are cut at 2,000 characters, ending in ` […]`, so an oversized exception cannot swell a response, a stored run or a log line.+- **A dry run failing on a fault of the runtime's is no verdict**: validating a method whose dry run fails only on faults that are not the method's, such as a storage outage or an unexpected error, answers the first of those faults' codes, every failure listed in `errors`, where it answered `method.invalid` and blamed the method; a verdict needs one failure in the method's domain, and the first fault is chosen with a `no` retry verdict before a retryable one, then the operator's before the account's, the input's and the runtime's, the answer's sentence rendered from the failure whose code it takes. A mock value a routed pipe cannot build, a pydantic or polyfactory refusal, stays the method's `method.mock_unsatisfiable`. A refusal met while loading that is not the method's keeps its own class and code in the same way, so `pipelex run bundle` and `pipelex-agent run bundle` on a folder whose bundles declare no single `main_pipe` print the run's refusal, `request.pipe_unspecified` or `request.pipe_ambiguous`, where they printed an invalid verdict. `POST /v1/pipe-io` answers a method calling another one by its address with the `422` problem `request.unsupported`, whose `params.reason` is `address_based_dependency`, where it answered an invalid verdict, and a hosted run whose inputs name a local file reads that refusal from the code and the reason, its message no longer naming the dependency.- **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 prompt over the model's context window reads `model.context_exceeded`**: a provider 400, or another 4xx such as the 422 or 413 a gateway may answer, saying the inputs are over what the model can read, by OpenAI's `context_length_exceeded` code or by the wording OpenAI, Anthropic, Mistral, Bedrock and Gemini give it, in the error's message or its body, is the caller's `model.context_exceeded`, answered 422, where it read `runtime.unexpected`, or `input.too_large` on a 413. A language model's window holds the prompt and the output requested with `max_tokens` together, and a 400 the `max_tokens` sent caused reads the same, so its next step is to shorten the input or lower `max_tokens`, or choose a model with a larger context window; an image, extraction, search or judgment model's next step names what it reads instead. A 400 about a malformed request still reads `runtime.unexpected`.@@ -43,8 +53,8 @@### 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 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.+- **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 problem's `type` 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()` is gone too, since a caller reads the sentences a code renders and never an error's own message.## [v0.89.0] - 2026-10-17diff --git a/api/CLAUDE.md b/api/CLAUDE.mdindex 20c6f961c..d7a1934dc 100644--- a/api/CLAUDE.md+++ b/api/CLAUDE.md@@ -196,12 +196,12 @@ async def execute(## Error Responses-Every error is rendered as RFC 7807 `application/problem+json` by the global handlers in `pipelex_api/exception_handlers.py`. **Route handlers do not shape errors themselves** — they call into pipelex and let exceptions propagate. The wire contract is documented at `docs/api-server/error-responses.md`, at the repository root.+Every error is rendered as RFC 9457 `application/problem+json` by the global handlers in `pipelex_api/exception_handlers.py`. **Route handlers do not shape errors themselves** — they call into pipelex and let exceptions propagate. The wire contract is documented at `docs/api-server/error-responses.md`, at the repository root.-- **Domain errors** (pipelex `PipelexError` subclasses) — raise from your code and let them propagate. The `PipelexError` global handler obtains an `ErrorReport` via `to_error_report()` and renders it into a problem document. Do not wrap, classify, or re-shape.-- **API-authored 4xx/5xx** — use the helpers in `pipelex_api/errors.py`: `raise_validation_error`, `raise_bad_request`, `raise_forbidden`, `raise_unauthenticated`, `raise_payload_too_large`, `raise_internal_server_error`. Each raises an `ApiError` carrying a pre-built problem document; the global handler emits it. **Do not raise `HTTPException` directly** — FastAPI's default handler wraps the body as `{"detail": <whatever>}` and cannot emit a flat RFC 7807 document.+- **Domain errors** (pipelex `PipelexError` subclasses) — raise from your code and let them propagate, choosing the error's code and parameters where you raise it (`with_error_code()`, `with_params()`) when its class declares a set. The `PipelexError` global handler builds the error's problem in the operator view, `to_problem(view=ProblemView.OPERATOR)`, and `problem_response` renders it with the status the problem's code declares, in the view the request's identity gives it (`pipelex_api/problem_view.py`: the operator's for the API key and for a request the trusted proxy forwarded, the caller's otherwise). A failure a route receives as a value, such as a validator's refusal that carries no validation items, goes through `problem_response` too. Do not wrap, classify, or re-shape.+- **API-authored 4xx/5xx** — use the helpers in `pipelex_api/errors.py`: `raise_validation_error`, `raise_bad_request`, `raise_forbidden`, `raise_unauthenticated`, `raise_payload_too_large`, `raise_internal_server_error`. Each raises an `ApiError` carrying a pre-built problem document; the global handler emits it. **Do not raise `HTTPException` directly** — FastAPI's default handler wraps the body as `{"detail": <whatever>}` and cannot emit a flat RFC 9457 document.- **Auth errors** — the helpers set `WWW-Authenticate: Bearer` automatically on 401.-- **Logging** — the global handlers emit one structured record per error, with the fixed message `A request ended in an error response` (the key the error stream is selected by; there is no `event` field) and the fields `url.path`, `error.type`, `error_domain`, `retryable`, `http.response.status_code`, and `user.id` / `pipe_code` / `pipeline_run_id` when the request bound them. `detail` rides the API-authored path only: a Pipelex `ErrorReport`'s body text has been through disclosure redaction, so it is not the cause and is deliberately not logged. They travel as `fields=` on the runtime's log call, never interpolated into the message, and `request_id` is not among them: `RequestIdMiddleware` binds it on the runtime's log context, so every record emitted under the request already carries it. The server selects the `json` sink, so a record reaches stderr as one JSON object per line — see `docs/api-server/logging.md` at the repository root. Log disposition follows the final HTTP status: 4xx logs at `warning` (caller mistakes, the provider-429 passthrough, and API-level 4xx overrides like the 409 conflict); 5xx logs at `error` with traceback. Routes should not log error tracebacks themselves.+- **Logging** — the global handlers emit one structured record per error, with the fixed message `A request ended in an error response` (the key the error stream is selected by; there is no `event` field) and the fields `url.path`, `error.type`, `error_domain`, `retryable`, `http.response.status_code`, and `user.id` / `pipe_code` / `pipeline_run_id` when the request bound them. On a domain error the record also carries `error.code`, `error_category`, and the diagnostics' `backend_name`, `model_handle`, `provider_status_code` and `provider_request_id`, and its `error.type` is the class of the exception that escaped, which for an exception that is not a `PipelexError` is that exception's class rather than the stand-in its problem names. `detail` rides the API-authored path only: a domain error's record is built from the operator view, whose `diagnostics` carry the cause, while the body's `detail` is only its code's sentence. They travel as `fields=` on the runtime's log call, never interpolated into the message, and `request_id` is not among them: `RequestIdMiddleware` binds it on the runtime's log context, so every record emitted under the request already carries it. The server selects the `json` sink, so a record reaches stderr as one JSON object per line — see `docs/api-server/logging.md` at the repository root. Log disposition follows the final HTTP status: 4xx logs at `warning` (caller mistakes, the provider-429 passthrough, and API-level 4xx overrides like the 409 conflict); 5xx logs at `error` with traceback. Routes should not log error tracebacks themselves.- **Documenting a failure in OpenAPI** — the shared, typed `responses=` declarations live in `pipelex_api/openapi_responses.py` (`ProblemDocument` + one constant per status). Every auth-wrapped `/v1` route already documents `401`/`413`/`422`/`500` via the composite router's `responses=` (`pipelex_api/routes/__init__.py`); a route declares on its own decorator only the statuses **it alone** can produce. Never hand-write an error `content` block: `pipelex_api/openapi_schema.py` re-keys the generated schema onto `application/problem+json`, because FastAPI renders a response `model` under the route's response-class media type and offers no per-response override. Adding a new status means adding a constant there and referencing it — then `make openapi-export`.Typical route:diff --git a/api/pipelex_api/api_config.py b/api/pipelex_api/api_config.pyindex 968c71bad..3357f5809 100644--- a/api/pipelex_api/api_config.py+++ b/api/pipelex_api/api_config.py@@ -80,7 +80,7 @@ def get_api_config() -> ApiConfig:The config is immutable for the life of the process (``PIPELEX_ENV`` is fixedat boot), so it is loaded once and cached. ``pipelex_api.main`` warms this at startupso a malformed ``api.toml`` / baked override fails the app fast — the same- fail-fast posture as ``ERROR_DISCLOSURE``. Tests that need a different mode+ fail-fast posture as ``AUTH_MODE``. Tests that need a different modepatch this getter (or call :func:`resolve_orchestration_mode` with a hand-builtconfig) rather than mutating the cache."""diff --git a/api/pipelex_api/disclosure.py b/api/pipelex_api/disclosure.pydeleted file mode 100644index fb1ab88ad..000000000--- a/api/pipelex_api/disclosure.py+++ /dev/null@@ -1,41 +0,0 @@-"""Resolution of the `ERROR_DISCLOSURE` environment variable.--`ERROR_DISCLOSURE` selects how much of an error report reaches the client:--- `verbose` (default) — the full report, including the human-readable message.- The intended default for a self-hosted server, where the operator and the- debugging developer are usually the same person.-- `strict` — the lossy projection pipelex's `DisclosureMode.STRICT` produces,- for hosted multi-tenant deployments.--The value is resolved once, at app startup (`pipelex_api.main`). An unrecognized value-fails the app at boot rather than silently degrading — a misconfigured-disclosure mode is a security-relevant mistake the operator must see.-"""--from pipelex.base_exceptions import DisclosureMode-from pipelex.system.environment import get_optional_env--from pipelex_api.exceptions import InvalidErrorDisclosureError--ERROR_DISCLOSURE_ENV_VAR = "ERROR_DISCLOSURE"---def resolve_disclosure_mode() -> DisclosureMode:- """Resolve `ERROR_DISCLOSURE` to a `DisclosureMode`.-- Returns `DisclosureMode.VERBOSE` when the variable is unset, empty, or- whitespace-only. Raises `InvalidErrorDisclosureError` for any value other- than `verbose` or `strict` (matched case-insensitively, surrounding- whitespace ignored).- """- raw = get_optional_env(ERROR_DISCLOSURE_ENV_VAR)- normalized = (raw or "").strip().lower()- if not normalized:- return DisclosureMode.VERBOSE- try:- return DisclosureMode(normalized)- except ValueError as exc:- valid = ", ".join(f"'{mode}'" for mode in DisclosureMode)- msg = f"{ERROR_DISCLOSURE_ENV_VAR}={raw!r} is not a valid disclosure mode. Valid values: {valid}."- raise InvalidErrorDisclosureError(msg) from excdiff --git a/api/pipelex_api/error_types.py b/api/pipelex_api/error_types.pyindex 422dd7914..bc4ad3437 100644--- a/api/pipelex_api/error_types.py+++ b/api/pipelex_api/error_types.py@@ -5,9 +5,8 @@ so call sites reference symbols, not literals — easier to grep, rename, anddocument. The `pipelex_api.errors` helpers stamp one of these onto the RFC 7807problem document as the `error_type` extension member.-Pipelex domain errors carry their own open-ended `error_type` (the exception-class name, from the `ErrorReport`) and are NOT enumerated here — they are-deliberately not a fixed set.+Pipelex domain errors answer their problem document, whose identity is its+registry `code`, and are NOT enumerated here."""from enum import StrEnumdiff --git a/api/pipelex_api/error_uri.py b/api/pipelex_api/error_uri.pyindex a619d5c26..e8d118108 100644--- a/api/pipelex_api/error_uri.py+++ b/api/pipelex_api/error_uri.py@@ -1,13 +1,12 @@"""RFC 7807 `type` URI and `title` for API-authored errors.-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`.+A pipelex error's problem always carries its own `type` and `title`, both the+registry code's: 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 the-static `pipelex_api.error_types.ErrorType` enum with no `ErrorReport` behind them.+static `pipelex_api.error_types.ErrorType` enum with no pipelex error behind them.`build_problem_document_from_api_error` uses these to give an API-authorederror an RFC 7807 `type` / `title` pair. Unlike a pipelex error's, that pairis still derived from a class name (`URLs.error_docs_base`, `pascal_case_to_kebab`,diff --git a/api/pipelex_api/errors.py b/api/pipelex_api/errors.pyindex b1bf7fb9d..d619f030a 100644--- a/api/pipelex_api/errors.py+++ b/api/pipelex_api/errors.py@@ -2,7 +2,7 @@These cover failures the API detects at its own boundary — request validation,auth, payload-size limits, server misconfiguration — as opposed to pipelex-domain errors, which carry an `ErrorReport` and are translated by the global+domain errors, which answer their own problem document through the global`PipelexError` handler in `pipelex_api.exception_handlers`.Each helper builds an RFC 7807 problem document (`build_problem_document_from_api_error`)@@ -29,7 +29,7 @@ class ApiError(Exception):Raised by the `raise_*` helpers below; rendered by `handle_api_error` in`pipelex_api.exception_handlers` as `application/problem+json`. Distinct from a pipelex- `PipelexError`: there is no `ErrorReport` behind it — the failure is the+ `PipelexError`: there is no problem of a pipelex error behind it — the failure is theAPI's own request validation, auth, or configuration check. The problemdocument is built at raise time, less the request context: `instance` and`request_id` are stamped by the handler, which is the frame that holds the@@ -137,7 +137,7 @@ def raise_internal_server_error(message: str, error_type: ErrorType) -> NoReturnFor the API's own configuration / invariant failures — a missing secret, astorage backend that cannot presign, absent package metadata. NOT for- pipelex domain errors, which carry an `ErrorReport` and are handled by the+ pipelex domain errors, which answer their own problem through theglobal `PipelexError` handler. Classified `CONFIG` domain: an operator, notthe caller, fixes it."""diff --git a/api/pipelex_api/exception_handlers.py b/api/pipelex_api/exception_handlers.pyindex 683248ea9..0f99e63b3 100644--- a/api/pipelex_api/exception_handlers.py+++ b/api/pipelex_api/exception_handlers.py@@ -1,25 +1,29 @@-"""Global FastAPI exception handlers that translate any failure into RFC 7807.+"""Global FastAPI exception handlers that translate any failure into RFC 9457.The single place the API renders a failure into an HTTP response. Everyhandler produces the same `application/problem+json` shape: an `ApiError`(raised by the `pipelex_api.errors` 4xx/5xx helpers) carries a pre-built problemdocument; a FastAPI `RequestValidationError` from automatic request-validation is rendered into one; every `PipelexError` is turned into a-problem document built from its `ErrorReport`; each orchestrator plugin's+validation is rendered into one; every `PipelexError` becomes its problem+document (`PipelexError.to_problem`); each orchestrator plugin'stransport-fault mapper (contributed through the plugin SPI's`add_http_error_mapper`, discovered at app construction) gets its own handler-rendering the `ErrorReport` it produces; everything else collapses to a-catch-all 500 that discloses under VERBOSE and is sanitized under STRICT, like-every other response here. The base names no orchestrator and imports no orchestrator SDK-— the Temporal transport classification that used to live here is now owned by-the `pipelex-temporal` plugin and reaches us only as a mapper. Routes-therefore no longer need to catch and shape errors themselves.+rendering the problem of the `PipelexError` it maps the fault to; everything+else becomes the problem of a `runtime.unexpected` failure, a 500. The base+names no orchestrator and imports no orchestrator SDK — the Temporal transport+classification is owned by the `pipelex-temporal` plugin and reaches us only as+a mapper. Routes therefore never catch and shape errors themselves.++**The reader picks the view.** A problem is built in the operator's view, and+the response carries the view of whoever made the request+(`pipelex_api.problem_view`): the operator view, with `diagnostics`, for a+request the authentication marked as the operator's, and the caller view,+without it, for anyone else. The HTTP status is the problem's code's, from the+error registry, and the operator's record of the failure, the log line, is+built from the operator view whichever view the response carries.This module is deliberately import-side-effect-free — no env var reads, no-app construction. `pipelex_api/main.py` calls `register_exception_handlers(app,-disclosure_mode=...)` at startup with the already-resolved disclosure mode-(its own fail-fast read is what keeps production strict on a bad-`ERROR_DISCLOSURE` value). Keeping the handlers in their own module lets+app construction. Keeping the handlers in their own module letstests import `register_exception_handlers` without dragging in theproduction app's startup chain (`Pipelex.make`, `get_auth_dependency`,router wiring), so a misconfigured env var can't crash test collection of@@ -34,7 +38,11 @@ from fastapi import FastAPI, Request, Responsefrom fastapi.exceptions import RequestValidationErrorfrom fastapi.responses import JSONResponsefrom pipelex import log-from pipelex.base_exceptions import DisclosureMode, ErrorDomain, ErrorReport, PipelexError+from pipelex.base_exceptions import ErrorDomain, PipelexError+from pipelex.cogt.exceptions import find_inference_error_category_in_chain+from pipelex.errors.error_codes import error_code_spec, parse_error_code+from pipelex.errors.problem import PipelexProblem, ProblemView, caller_view_of+from pipelex.pipe_run.located_failure import make_unexpected_failurefrom pipelex.plugins.registrar import HttpErrorMapperFnfrom pipelex.system.telemetry.otel_constants import OTelLogAttrfrom pipelex.tools.log.error_fields import ERROR_TYPE_FIELD@@ -45,10 +53,10 @@ from pipelex_api.errors import ApiErrorfrom pipelex_api.middleware import request_id_offrom pipelex_api.problem_document import (PROBLEM_JSON_MEDIA_TYPE,- build_problem_document,build_problem_document_from_api_error,with_request_context,)+from pipelex_api.problem_view import problem_view_ofif TYPE_CHECKING:from pipelex_api.security import RequestUser@@ -135,28 +143,35 @@ def _request_fields(request: Request) -> dict[str, Any]:}-def _retry_after_header(report: ErrorReport) -> dict[str, str]:+# The HTTP status of a problem whose code the registry gives none, which only a client's own failure has.+_FALLBACK_PROBLEM_STATUS = 500+++def _retry_after_header(problem: PipelexProblem, *, status: int) -> dict[str, str]:"""Return a `Retry-After` header dict when a retry hint applies to this response.- Emitted only when the response is itself a retry invitation — the- provider-429 passthrough (`report.http_status == 429`) — so a hint never- rides a 500/422 where `Retry-After` is meaningless. The provider's- `retry_after_seconds` is rounded up and clamped to a non-negative integer;- a non-finite value (a provider sending `Retry-After: inf` / `nan`) is- dropped rather than crashing `math.ceil`. Empty dict when no usable hint- applies.+ Emitted only when the response is itself a retry invitation — a 429, such as+ a provider's rate limit passed through — so a hint never rides a 500/422+ where `Retry-After` is meaningless. The problem's `retry_after`, which only a+ code inviting a retry carries and which is always finite, is rounded up to an+ integer. Empty dict when no hint applies."""- if report.http_status != 429:+ if status != 429:return {}- metadata = report.provider_metadata- if metadata is None:- return {}- seconds = metadata.retry_after_seconds+ seconds = problem.retry_afterif seconds is None or not math.isfinite(seconds):return {}return {"Retry-After": str(max(0, math.ceil(seconds)))}+def _status_of(problem: PipelexProblem) -> int:+ """The HTTP status of the response a problem is the body of: its code's, from the error registry."""+ code = parse_error_code(problem.code)+ if code is None:+ return _FALLBACK_PROBLEM_STATUS+ return error_code_spec(code).status or _FALLBACK_PROBLEM_STATUS++def _emit_api_error(*, fields: dict[str, Any], as_error: bool) -> None:"""Emit one error record: a fixed message, everything about the failure a record attribute.@@ -189,61 +204,67 @@ def _emit_at_error_level(status: int) -> bool:A 5xx is a server fault — log at `error` with a traceback. A 4xx isclient-facing (a caller mistake or a benign conflict) — log at `warning`- without a traceback. Keying off the post-override status (see- ``_ERROR_TYPE_STATUS_OVERRIDES``) is what keeps an API-level 4xx override —- e.g. ``PipelineManagerAlreadyExistsError`` mapped to 409 — out of the error- dashboards, while still covering the `INPUT`-domain 422 caller mistakes and- the provider-429 passthrough without a second per-error-type registry.+ without a traceback. Keying off the status the code declares is what keeps+ a conflict, such as ``pipelex.run.already_exists`` answered with 409, out of+ the error dashboards, while still covering the 422 caller mistakes and the+ provider-429 passthrough without a second per-error-type registry."""return status >= 500-def _log_error_report(report: ErrorReport, *, request: Request, status: int | None = None) -> None:- """Emit the structured error record for a handled `ErrorReport`.+def _log_problem(problem: PipelexProblem, *, error: BaseException | None, request: Request, status: int) -> None:+ """Emit the structured error record for a failure answered with a problem, from the operator view.- Disposition follows the final HTTP status (see ``_emit_at_error_level``):+ Disposition follows the HTTP status (see ``_emit_at_error_level``):a 4xx is client-facing and logs at `warning` without a traceback (caller- mistakes, the provider-429 passthrough, and API-level 4xx overrides like- the 409 conflict), a 5xx logs at `error` with the traceback. The fields- mirror the response so the two never drift.- `user.id` rides every record when auth bound a caller — without it, the- storage / pipeline-backend leg of a failure carries only `request_id` and- `url.path`, and tying the failure to the caller requires correlating the- request id across unrelated records (Phase 3 deleted the per-route- `log.error(... user=...)` lines those failures used to emit).-- ``status`` defaults to ``report.http_status`` and exists so the caller can- pass the post-override value (see ``_ERROR_TYPE_STATUS_OVERRIDES``) — the- record then agrees with the HTTP status actually sent rather than the- domain default.+ mistakes, a provider's 429 passed through, and the 409 conflict), a 5xx+ logs at `error` with the traceback. `error.code` is the problem's code and+ `error.type` the class of the exception that escaped, else the class the+ operator view names. `user.id` rides every record when auth bound a caller —+ without it, the storage / pipeline-backend leg of a failure carries only+ `request_id` and `url.path`, and tying the failure to the caller requires+ correlating the request id across unrelated records.++ ``problem`` is the operator view, so the record carries the diagnostics+ whichever view the response carries. ``error`` is the exception the problem+ was built from, `None` for a failure a route received as a value, whose+ problem is all there is."""- effective_status = status if status is not None else report.http_status+ diagnostics = problem.diagnostics+ error_category = find_inference_error_category_in_chain(error) if error is not None else None+ # The class that escaped, which for an exception that is not a PipelexError is not the stand-in the problem was+ # built from; a failure received as a value has its problem's class alone.+ error_class: str | None = None+ if error is not None:+ error_class = type(error).__name__+ elif diagnostics is not None:+ error_class = diagnostics.error_classfields: dict[str, Any] = {**_request_fields(request),- ERROR_TYPE_FIELD: report.error_type,- "error_category": report.error_category,- "error_domain": report.error_domain,- "retryable": report.retryable,- OTelLogAttr.HTTP_RESPONSE_STATUS_CODE: effective_status,- # A report's `provider` is the backend the error names, which a worker attributes its failure to, and its `model`- # the handle the pipe named. The provider the SDK's metadata names, `openai` or `gateway`, is no backend's name- # and no SDK's as the backends configuration names them, so it is left off: an unattributed failure has no+ "error.code": problem.code,+ ERROR_TYPE_FIELD: error_class,+ "error_category": error_category,+ "error_domain": ErrorDomain.from_problem_domain(problem.effective_domain),+ "retryable": problem.is_retryable,+ OTelLogAttr.HTTP_RESPONSE_STATUS_CODE: status,+ # The diagnostics' `provider` is the backend the error names, which a worker attributes its failure to, and their+ # `model` the handle the pipe named. The provider the SDK's metadata names, `openai` or `gateway`, is no backend's+ # name and no SDK's as the backends configuration names them, so it is left off: an unattributed failure has no# `backend_name` rather than a second spelling of the same backend.- "backend_name": report.provider,- "model_handle": report.model,+ "backend_name": diagnostics.provider.name if diagnostics is not None and diagnostics.provider is not None else None,+ "model_handle": diagnostics.model if diagnostics is not None else None,}- metadata = report.provider_metadata- if metadata is not None:- fields["provider_status_code"] = metadata.status_code- fields["provider_request_id"] = metadata.request_id- _emit_api_error(fields=fields, as_error=_emit_at_error_level(effective_status))+ if diagnostics is not None and diagnostics.provider is not None:+ fields["provider_status_code"] = diagnostics.provider.status+ fields["provider_request_id"] = diagnostics.provider.request_id+ _emit_api_error(fields=fields, as_error=_emit_at_error_level(status))def _log_api_authored_error(*, document: dict[str, Any], status: int, request: Request) -> None:"""Emit the structured error record for an API-authored error response.- Shares the disposition rule and the common-key set of `_log_error_report`- so every error response — a pipelex `ErrorReport` translated to RFC 7807+ Shares the disposition rule and the common-key set of `_log_problem`+ so every error response — a pipelex error's problem*or* an API-authored 4xx/5xx raised by an `pipelex_api.errors` helper — producesone error record a downstream sink can filter uniformly on its message andon `request_id`, `url.path`, `error.type`, `error_domain`, `retryable`@@ -254,16 +275,14 @@ def _log_api_authored_error(*, document: dict[str, Any], status: int, request: RWhere the two helpers differ — by design, matching what each side actuallyhas to log:- - API-authored docs add `detail`, always safe because- `build_problem_document_from_api_error` does not apply strict-disclosure- redaction (only `build_problem_document` does for pipelex domain errors).- Carrying the message preserves the operator-facing cause in the record.- - API-authored docs omit `error_category`, `backend_name`, `model_handle`,+ - API-authored docs add `detail`, which the API wrote itself from what it+ checked, so it is the cause an operator reads.+ - API-authored docs omit `error.code`, `error_category`, `backend_name`, `model_handle`,`provider_status_code` and `provider_request_id` — those are inference-domain classifiers pipelexsets only on classifiable failures and the API never authors itself.A 4xx logs at `warning` without a traceback; a 5xx logs at `error` with- the traceback — same status-keyed disposition rule `_log_error_report`+ the traceback — same status-keyed disposition rule `_log_problem`uses (see ``_emit_at_error_level``), so a sink dedup'ing by level sees oneshape."""@@ -278,170 +297,70 @@ def _log_api_authored_error(*, document: dict[str, Any], status: int, request: R_emit_api_error(fields=fields, as_error=_emit_at_error_level(status))-def _json_safe_report(report: ErrorReport) -> ErrorReport:- """Return a report whose floats Starlette's JSON encoder can render.-- `JSONResponse` encodes with `allow_nan=False`, so a non-finite- `provider_metadata.retry_after_seconds` — a provider sending `Retry-After:- inf` / `nan`, which pipelex's header parser passes through unchecked —- would crash the whole response render, not just the `Retry-After` header.- Null the unusable hint out; the rest of the report renders intact.- """- metadata = report.provider_metadata- if metadata is None:- return report- seconds = metadata.retry_after_seconds- if seconds is None or math.isfinite(seconds):- return report- safe_metadata = metadata.model_copy(update={"retry_after_seconds": None})- 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- # than the CONFIG-domain default of 500) tells clients "this server does- # not provide this functionality" without inviting retries.- "AsyncExecutionNotEnabledError": 501,- # A submission reusing a pipeline_run_id that is still registered (a- # genuinely concurrent duplicate — completed/failed runs free their entry- # on the way out) is a client-visible conflict, not a server fault.- # Mapping it to 409 Conflict (rather than the no-domain default of 500)- # 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), 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, 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 hosted- # platform's unknown-`method_id` mapping); the message lists what the repo does contain.- "MethodPackageNotFoundError": 404,- # - More than one package matches the address: the caller must disambiguate with the- # package's full address → 422.- "MethodPackageAmbiguityError": 422,- # - The selected package exceeds the fetched-package ceilings: the referenced content- # cannot be processed under this deployment's bounds → 422 (not 413, which is about- # the request entity itself).- "MethodPackageTooLargeError": 422,- # - The selected package carries a symlink, file or directory, which fetched packages must- # not: a rule about the fetched content that the method's author fixes by removing the- # link → 422, like the ceilings above (not 403, kept for refusing in-process Python).- "MethodPackageSymlinkError": 422,- # - The method's Python declares structure classes, whether it was sent as a bundle or- # fetched by `method_ref`: a policy refusal (hosted execution accepts MTHDS concepts and- # sandboxed PipeFuncs, not in-process Python) → 403, the same status as the bundle- # transport's custom-code gate.- "MethodStructuresRefusedError": 403,-}---def _http_status_for(report: ErrorReport) -> int:- """Return the HTTP status to use for this report.-- Defers to ``report.http_status`` for the standard mapping (provider-429- passthrough + ``error_domain`` -> 4xx/5xx) and applies a per-error-type- override last. Overrides live in ``_ERROR_TYPE_STATUS_OVERRIDES`` so the- decisions are discoverable in one place — keep the dict small and each- entry justified.- """- return _ERROR_TYPE_STATUS_OVERRIDES.get(report.error_type, report.http_status)---def _problem_response(report: ErrorReport, *, request: Request, disclosure_mode: DisclosureMode) -> JSONResponse:- """Build the RFC 7807 `JSONResponse` for an `ErrorReport` and log the entry.+def problem_response(problem: PipelexProblem, *, error: BaseException | None, request: Request) -> JSONResponse:+ """Render a problem built in the operator's view as the response to `request`, and log the failure.- Shared by the `PipelexError` handler and every orchestrator-mapper handler:- both produce an `ErrorReport`, so both render and log it identically. The report is first- made JSON-safe (see `_json_safe_report`); the status code then comes from- `_http_status_for(report)` (the report's own mapping plus any API-layer- override registered in ``_ERROR_TYPE_STATUS_OVERRIDES``), and the response- body from the Phase 1 problem-document builder under the caller-supplied- `disclosure_mode` (`register_exception_handlers` binds the app's effective- mode into the handlers it registers).+ The single rendering of every failure a problem describes: a raised `PipelexError`, an+ orchestrator plugin's mapped transport fault, an unexpected exception, and a fault the+ `/validate` route receives as a value rather than a raise, for which `error` is `None`. The status is the code's, the+ record is logged from the operator view, and the body is the view of the request's reader+ (`pipelex_api.problem_view`), with its `status` member set to the response's."""- report = _json_safe_report(report)- request_id = request_id_of(request)- status = _http_status_for(report)- document = build_problem_document(- report,- instance=request.url.path,- request_id=request_id,- disclosure_mode=disclosure_mode,- )- # Keep the RFC 7807 ``status`` member aligned with the actual HTTP status- # when an API-layer override has bumped it away from ``report.http_status``;- # otherwise the two surfaces (header vs body) would silently disagree.- document["status"] = status- _log_error_report(report, request=request, status=status)+ status = _status_of(problem)+ _log_problem(problem, error=error, request=request, status=status)+ match problem_view_of(request):+ case ProblemView.OPERATOR:+ reader_problem = problem+ case ProblemView.CALLER:+ reader_problem = caller_view_of(problem=problem)+ document = reader_problem.model_copy(update={"status": status}).to_wire()return JSONResponse(status_code=status,content=document,media_type=PROBLEM_JSON_MEDIA_TYPE,- headers=_retry_after_header(report),+ headers=_retry_after_header(problem, status=status),)-def problem_response_from_error_report(report: ErrorReport, *, request: Request) -> JSONResponse:- """Render an `ErrorReport` value through the same RFC 7807 path as raised errors.+def operator_problem_of(error: PipelexError, *, request: Request) -> PipelexProblem:+ """The problem of a `PipelexError` answered to `request`, in the operator's view, with the request's ids."""+ return error.to_problem(view=ProblemView.OPERATOR, request_id=request_id_of(request), pipeline_run_id=_pipeline_run_id_of(request))- Most `ErrorReport`s reach this module by raising a `PipelexError` or by an- orchestrator transport mapper. `/validate` can also receive an `ErrorReport`- as a registry-returned value; when that value is a backend/config/runtime- fault rather than a validation verdict, it must still keep the same status,- disclosure, logging, and retry headers as the global handler path.- """- disclosure_mode = getattr(request.app.state, "error_disclosure_mode", DisclosureMode.VERBOSE)- return _problem_response(report, request=request, disclosure_mode=disclosure_mode)---async def handle_pipelex_error(request: Request, exc: Exception, *, disclosure_mode: DisclosureMode) -> Response:- """Translate any pipelex `PipelexError` into an RFC 7807 problem response.-- The single place in the API that consumes a `PipelexError`'s `ErrorReport`.- `to_error_report()` walks the `__cause__` chain, so a wrapper exception- still surfaces the classification of the underlying failure. `exc` is typed- `Exception` to match Starlette's handler contract; FastAPI only routes a- `PipelexError` here, so the cast is sound. An orchestrator's workflow- failure that is itself a `PipelexError` (e.g. the Temporal plugin's- `WorkflowExecutionError`, which already carries a structured `ErrorReport`)- resolves here via Starlette's MRO walk; only a *bare* orchestrator-SDK- transport error (no `PipelexError` in its MRO) is routed to that plugin's- own mapper-backed handler instead.++async def handle_pipelex_error(request: Request, exc: Exception) -> Response:+ """Translate any pipelex `PipelexError` into its problem response.++ `to_problem` reports a located failure as its root fault at the pipe where+ it happened, so a wrapper exception still answers the code of the underlying+ failure. `exc` is typed `Exception` to match Starlette's handler contract;+ FastAPI only routes a `PipelexError` here, so the cast is sound. An+ orchestrator's workflow failure that is itself a `PipelexError` (e.g. the+ Temporal plugin's `WorkflowExecutionError`, which carries the problem its+ worker built) resolves here via Starlette's MRO walk; only a *bare*+ orchestrator-SDK transport error (no `PipelexError` in its MRO) is routed to+ that plugin's own mapper-backed handler instead."""- report = cast("PipelexError", exc).to_error_report()- return _problem_response(report, request=request, disclosure_mode=disclosure_mode)+ error = cast("PipelexError", exc)+ return problem_response(operator_problem_of(error, request=request), error=error, request=request)-def _make_orchestrator_error_handler(mapper: HttpErrorMapperFn, *, disclosure_mode: DisclosureMode) -> "_ExceptionHandler":+def _make_orchestrator_error_handler(mapper: HttpErrorMapperFn) -> "_ExceptionHandler":"""Wrap one plugin-contributed error mapper into a FastAPI exception handler.The plugin owns the *classification* (it maps its bare transport/runtime- exception — e.g. `temporalio.TemporalError` — to a structured `ErrorReport`);- core owns the *transport* exception type (resolved lazily by the registrar);- the API owns the *presentation* (the same RFC 7807 + `DisclosureMode`- rendering every `ErrorReport` gets via `_problem_response`). This is what- lets the base render an orchestrator's transport fault correctly while- naming — and importing — no orchestrator SDK. `exc` is typed `Exception` to- match Starlette's handler contract; FastAPI only routes the mapper's- registered `exc_type` here.+ exception — e.g. `temporalio.TemporalError` — to a `PipelexError` carrying the+ code the fault takes); core owns the *transport* exception type (resolved+ lazily by the registrar); the API owns the *presentation* (the same problem+ rendering every `PipelexError` gets via `problem_response`). This is what lets+ the base render an orchestrator's transport fault correctly while naming — and+ importing — no orchestrator SDK. `exc` is typed `Exception` to match+ Starlette's handler contract; FastAPI only routes the mapper's registered+ `exc_type` here."""async def _handler(request: Request, exc: Exception) -> Response:- report = mapper(exc)- return _problem_response(report, request=request, disclosure_mode=disclosure_mode)+ error = mapper(exc)+ return problem_response(operator_problem_of(error, request=request), error=error, request=request)return _handler@@ -455,60 +374,20 @@ async def handle_unexpected_error(request: Request, exc: Exception) -> Response:transport/runtime error collapses here to a 500.One of the two `except Exception`-equivalent sites the project sanctions —- the outermost handler of an API. Disclosure follows the app's- `disclosure_mode`, exactly like every other handler in this module: VERBOSE- puts `Class: message` in `detail` so a caller can see what actually broke;- STRICT keeps the fully sanitized body (no exception class, no `str(exc)`).- A traceback reaches the client in neither mode — the class name and full- traceback go to the operator log, correlated by request id.-- Honoring the mode here is what stops the catch-all from being a silent hole.- An unclassified failure is *precisely* the one a caller cannot diagnose from- a request id alone, and it is the only response in the API that used to- contradict a deployment's explicit choice to disclose: a VERBOSE deployment- got real messages for every classified error and a dead end for the one- error nobody classified. STRICT still redacts, so a deployment that wants- nothing leaked keeps that.-- The mode is read off `app.state` (like `problem_response_from_error_report`)- rather than bound as a parameter, so registering this handler stays- signature-free.-- This handler also covers a failure *inside* another handler (e.g. a corrupt- `to_error_report()`): Starlette's `ServerErrorMiddleware` wraps the others,- so such a failure still lands here rather than a bodyless default.+ the outermost handler of an API. The exception is stood in for by a+ `PipelexUnexpectedError` (`make_unexpected_failure`) and answered as its+ problem, `runtime.unexpected`, through the same rendering as every other+ failure: the caller reads the code's own sentences and never the exception's+ text, and the operator reads its class and message in `diagnostics`. A+ traceback reaches no response — it goes to the operator log, correlated by+ request id.++ This handler also covers a failure *inside* another handler: Starlette's+ `ServerErrorMiddleware` wraps the others, so such a failure still lands here+ rather than a bodyless default."""- request_id = request_id_of(request)- _emit_api_error(- fields={- **_request_fields(request),- ERROR_TYPE_FIELD: type(exc).__name__,- "error_category": "unknown",- "error_domain": ErrorDomain.RUNTIME,- OTelLogAttr.HTTP_RESPONSE_STATUS_CODE: 500,- },- as_error=True,- )- disclosure_mode = getattr(request.app.state, "error_disclosure_mode", DisclosureMode.VERBOSE)- if disclosure_mode is DisclosureMode.STRICT:- detail = "An unexpected error occurred. The request id is included for support."- else:- detail = f"{type(exc).__name__}: {exc}"- # Route through the same builder every other API-authored 500 uses, so the- # catch-all shape never drifts from `handle_api_error`'s output. The one- # catch-all-specific addition is `error_category: "unknown"` — by definition- # the failure was not classifiable, and the marker lets a downstream sink- # tell a catch-all 500 apart from a classified `CONFIG`-domain one.- document = build_problem_document_from_api_error(- ErrorType.INTERNAL_SERVER_ERROR,- detail,- 500,- instance=request.url.path,- request_id=request_id,- error_domain=ErrorDomain.RUNTIME,- )- document["error_category"] = "unknown"- return JSONResponse(status_code=500, content=document, media_type=PROBLEM_JSON_MEDIA_TYPE)+ unexpected_failure = make_unexpected_failure(error=exc)+ return problem_response(operator_problem_of(unexpected_failure, request=request), error=exc, request=request)async def handle_api_error(request: Request, exc: Exception) -> Response:@@ -518,8 +397,10 @@ async def handle_api_error(request: Request, exc: Exception) -> Response:own 4xx/5xx — request validation, auth, payload limits, misconfiguration.The helper builds the problem document at raise time, where it holds no`Request`, so this handler stamps the two request-scoped members (`instance`- and `request_id`) onto a copy of it — the same two values, read from the same- place, as the pipelex-error and request-validation paths use. It then+ and `request_id`) onto a copy of it, read from the same place as the+ request-validation path reads them. A `PipelexError`'s problem carries+ `request_id` alone, since the problem document leaves the RFC's `instance`+ out: the request id already names the occurrence. It thenserializes that document, re-attaches any `WWW-Authenticate` challenge header,and emits the structured error record so an API-owned 500 from anyroute is observable (a `raise_internal_server_error` site like `version.py`'s@@ -638,7 +519,6 @@ async def handle_client_disconnect(request: Request, exc: Exception) -> Responsedef register_exception_handlers(app: FastAPI,*,- disclosure_mode: DisclosureMode = DisclosureMode.VERBOSE,http_error_mappers: dict[type[Exception], HttpErrorMapperFn] | None = None,) -> None:"""Register the app-level exception handlers on `app`.@@ -657,36 +537,27 @@ def register_exception_handlers(default `{"detail": [...]}`. Shared by the production app and by the unittests, which register the same handlers on a throwaway app.- `http_error_mappers` is the `{exc_type: to_error_report}` map an orchestrator+ `http_error_mappers` is the `{exc_type: to_pipelex_error}` map an orchestratorplugin contributes through the plugin SPI (`PluginRegistrar.add_http_error_mapper`,read back via `get_http_error_mappers`). The caller resolves it at appconstruction — `pipelex_api.main` builds the registrar and passes it; the base resolvesan empty map (it installs no orchestrator plugin), so no transport handler isregistered and the only fallback for an unclassified failure stays the catch-all500. Each entry registers one handler that runs the mapper and renders the- resulting `ErrorReport` through the shared RFC 7807 + disclosure path — so core+ resulting `PipelexError`'s problem through the shared rendering — so coreand the API name no orchestrator SDK. Keeping the parameter explicit (rather thancalling `build_registrar` in here) preserves this module's import-side-effect-freecontract: tests register handlers on a throwaway app without a booted Pipelex, anda test contributes a synthetic mapper to prove the seam without installing a plugin.- `disclosure_mode` is captured by the handlers that render a pipelex `ErrorReport`- (`handle_pipelex_error` and every mapper handler) via the closures below —- production passes the startup-resolved value (`pipelex_api.main.ERROR_DISCLOSURE_MODE`);- tests pass whatever the test needs and the default (`VERBOSE`) covers the common- case. The other handlers don't render an `ErrorReport`, so they register- directly — `handle_unexpected_error` still honors the mode, reading it back off- `app.state` (set below) rather than through a closure.+ No handler takes a disclosure setting: the view of every problem response is+ picked per request, by the identity its authentication established+ (`pipelex_api.problem_view`)."""- app.state.error_disclosure_mode = disclosure_mode-- async def _pipelex_error(request: Request, exc: Exception) -> Response:- return await handle_pipelex_error(request, exc, disclosure_mode=disclosure_mode)-app.add_exception_handler(ApiError, handle_api_error)app.add_exception_handler(RequestValidationError, handle_request_validation_error)app.add_exception_handler(ClientDisconnect, handle_client_disconnect)- app.add_exception_handler(PipelexError, _pipelex_error)+ app.add_exception_handler(PipelexError, handle_pipelex_error)for exc_type, mapper in (http_error_mappers or {}).items():- app.add_exception_handler(exc_type, _make_orchestrator_error_handler(mapper, disclosure_mode=disclosure_mode))+ app.add_exception_handler(exc_type, _make_orchestrator_error_handler(mapper))app.add_exception_handler(Exception, handle_unexpected_error)diff --git a/api/pipelex_api/exceptions.py b/api/pipelex_api/exceptions.pyindex be6f8f76d..b4d5e08b0 100644--- a/api/pipelex_api/exceptions.py+++ b/api/pipelex_api/exceptions.py@@ -7,7 +7,7 @@ beside the code that raises them, as every error class does: the same gate refus``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.+separate family with no pipelex error behind them."""from pipelex.base_exceptions import PipelexError@@ -24,9 +24,3 @@ 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/main.py b/api/pipelex_api/main.pyindex c08d4de45..c7ac2c7cb 100644--- a/api/pipelex_api/main.py+++ b/api/pipelex_api/main.py@@ -26,7 +26,6 @@ from pydantic import BaseModel, Fieldfrom starlette.middleware.base import BaseHTTPMiddlewarefrom pipelex_api.api_config import get_api_config, resolve_boot_orchestrator-from pipelex_api.disclosure import resolve_disclosure_modefrom pipelex_api.exception_handlers import register_exception_handlersfrom pipelex_api.middleware import RequestIdMiddleware, request_body_size_middlewarefrom pipelex_api.openapi_schema import PipelexFastAPI@@ -52,7 +51,7 @@ async def lifespan(_app: FastAPI) -> AsyncGenerator[None]:# can never be set inconsistently.## Loading `api.toml` here also fails the app fast on a malformed config / baked override- # (the same posture as ERROR_DISCLOSURE), now even before the singleton exists. The loader+ # (the same posture as AUTH_MODE), now even before the singleton exists. The loader# only needs `runtime_manager.environment` (from PIPELEX_ENV), which resolves without a# live singleton. get_api_config() is @cache'd, so the warm here is reused everywhere.boot_orchestrator = resolve_boot_orchestrator(get_api_config())@@ -79,29 +78,19 @@ def _resolve_cors_origins() -> tuple[list[str], bool]:return origins, True-# Resolve and validate ERROR_DISCLOSURE once, at module/startup: an unrecognized-# value raises here and the production app fails to boot rather than silently-# defaulting. Passed into `register_exception_handlers` below; the resolved-# mode drives how much of an error report reaches a client. Kept module-level-# so the production fail-fast lives on this single import path — only this-# module triggers it, not `pipelex_api.exception_handlers` (which lets tests register-# the handlers without inheriting the env-validation crash).-ERROR_DISCLOSURE_MODE = resolve_disclosure_mode()--def _resolve_http_error_mappers() -> dict[type[Exception], HttpErrorMapperFn]:"""Resolve the orchestrator plugins' HTTP-error mappers for this deployment.Runs the pure, repeatable `build_registrar` against the loaded config (the samestandalone pattern `pipelex plugins list` uses) and reads back the- `{exc_type: to_error_report}` map each installed orchestrator plugin contributed+ `{exc_type: to_pipelex_error}` map each installed orchestrator plugin contributedvia `PluginRegistrar.add_http_error_mapper`. The base installs no orchestratorplugin, so this is an empty map and no transport-error handler is registered; aflavor (e.g. the Temporal one) contributes its plugin's mapper here, and only atthis point — at app construction, where the plugin (and therefore its SDK) is bydefinition installed — is the plugin's exc-type provider thunk run. Resolved onceat module import so a duplicate/broken plugin fails the app fast, mirroring the- `ERROR_DISCLOSURE` fail-fast above.+ `AUTH_MODE` fail-fast below.Safe at import because the map is a pure function of *installed* plugins (entrypoints + `config.runtime.plugins.disabled`) — never of the `boot_orchestrator` that@@ -195,7 +184,7 @@ fastapi_app.include_router(blob_upload_router, prefix="/v1")# Register all other routes WITH authentication, the dependency selected by the AUTH_MODE env var. An# unrecognized AUTH_MODE raises `InvalidAuthModeError` here and the app fails to boot, the same fail-fast-# posture as ERROR_DISCLOSURE above: a mistyped mode must never serve these routes unauthenticated.+# posture as a broken plugin above: a mistyped mode must never serve these routes unauthenticated.# The API mounts at `/v1` — the SDKs compose `{MTHDS_BASE_URL}/v1/{endpoint}` (master D10); no `/api/v1`# mount and no alias remain.auth_dependency = get_auth_dependency()@@ -219,7 +208,7 @@ async def root() -> ServiceIdentity:return ServiceIdentity(message="Pipelex API")-register_exception_handlers(fastapi_app, disclosure_mode=ERROR_DISCLOSURE_MODE, http_error_mappers=HTTP_ERROR_MAPPERS)+register_exception_handlers(fastapi_app, http_error_mappers=HTTP_ERROR_MAPPERS)# RequestIdMiddleware wraps the *entire* FastAPI app — including Starlette'sdiff --git a/api/pipelex_api/method_cache.py b/api/pipelex_api/method_cache.pyindex c5fdbf0e9..5f4c81f81 100644--- a/api/pipelex_api/method_cache.py+++ b/api/pipelex_api/method_cache.py@@ -76,10 +76,10 @@ def _run_ls_remote(*, clone_url: str, ref_patterns: list[str], ref_str: str) -># 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).with_error_code(CoreCode.METHOD_FETCH_FAILED) from exc+ raise MethodFetchError(msg).with_error_code(CoreCode.METHOD_FETCH_FAILED).for_method_ref(method_ref=ref_str) from excexcept subprocess.TimeoutExpired as exc:msg = f"Timed out resolving method '{ref_str}' against the remote repository"- raise MethodFetchError(msg).with_error_code(CoreCode.METHOD_FETCH_FAILED) from exc+ raise MethodFetchError(msg).with_error_code(CoreCode.METHOD_FETCH_FAILED).for_method_ref(method_ref=ref_str) from excpairs: list[tuple[str, str]] = []for line in result.stdout.strip().splitlines():@@ -125,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).with_error_code(CoreCode.METHOD_NOT_FOUND)+ raise MethodFetchError(msg).with_error_code(CoreCode.METHOD_NOT_FOUND).for_method_ref(method_ref=ref.ref_str)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).with_error_code(CoreCode.METHOD_NOT_FOUND)+ raise MethodFetchError(msg).with_error_code(CoreCode.METHOD_NOT_FOUND).for_method_ref(method_ref=ref.ref_str)return head[0]diff --git a/api/pipelex_api/method_source.py b/api/pipelex_api/method_source.pyindex cf8a7be6b..85aa2b929 100644--- a/api/pipelex_api/method_source.py+++ b/api/pipelex_api/method_source.py@@ -27,7 +27,8 @@ same path, the files a step reads, such as a `PipeDocGen` template, included.The security gate (packaging invariant 7 — execution locus decides) is the request tree's(`pipelex_api.method_tree_request.ensure_python_allowed`): on a deployment that is not sandbox-hosted, a packagecarrying any `.py` is refused with a 403 `CustomCodeRequiresSandbox`; on a sandbox-hosted one, PipeFunc `.py` is-acceptable but a package declaring `StructuredContent` subclasses is refused (`MethodStructuresRefusedError` → 403).+acceptable but a package declaring `StructuredContent` subclasses is refused (`MethodStructuresRefusedError`, a 422+`pipelex.deployment.python_structures_refused`).Everything a run needs is read OUT of the cached clone before this module returns — the tree's bytes into memory —while the clone is pinned against eviction (`MethodCloneCache.pinned_package`), so cache eviction never races a read or@@ -109,10 +110,10 @@ def _run_git(*, clone_dir: Path, args: list[str], stdin: bytes | None, package_araise 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).with_error_code(CoreCode.METHOD_FETCH_FAILED) from exc+ raise MethodFetchError(msg).with_error_code(CoreCode.METHOD_FETCH_FAILED).for_method_ref(method_ref=package_address) from excexcept subprocess.TimeoutExpired as exc:msg = f"Timed out reading method package '{package_address}' from its commit"- raise MethodFetchError(msg).with_error_code(CoreCode.METHOD_FETCH_FAILED) from exc+ raise MethodFetchError(msg).with_error_code(CoreCode.METHOD_FETCH_FAILED).for_method_ref(method_ref=package_address) from excreturn result.stdout@@ -141,7 +142,11 @@ 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).with_error_code(CoreCode.METHOD_PACKAGE_INVALID) from exc+ raise (+ MethodFetchError(msg)+ .with_error_code(CoreCode.METHOD_PACKAGE_INVALID)+ .with_params(reason="a file's name is not UTF-8 text, which no method tree can hold")+ ) from excif not path.startswith(prefix):continueentries.append(_GitTreeEntry(mode=mode, object_sha=object_sha, path=path.removeprefix(prefix)))@@ -170,7 +175,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).with_error_code(CoreCode.METHOD_FETCH_FAILED)+ raise MethodFetchError(msg).with_error_code(CoreCode.METHOD_FETCH_FAILED).for_method_ref(method_ref=package.full_address)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 11f8970cf..3011698c1 100644--- a/api/pipelex_api/method_tree_request.py+++ b/api/pipelex_api/method_tree_request.py@@ -23,7 +23,7 @@ What this module does, in order:file at a tree path; other bytes under a path the tree holds are a 422 `InvalidResourcePath` naming it.5. Python is honored only on a sandbox-hosted deployment: a method holding a `.py` file is refused with a 403`CustomCodeRequiresSandbox` before anything is written, and on a sandbox-hosted deployment a tree declaring a Python- structure class is refused (`MethodStructuresRefusedError`, a 403).+ structure class is refused (`MethodStructuresRefusedError`, a 422).6. Each tree read in full is recorded in the blob store, its files then its listing, so the next request can send itby hash, and `POST /v1/blobs/missing` answers its digest with one lookup.7. The trees are written out into a temporary directory and held as written (`pipelex.libraries.written_trees`), so@@ -650,7 +650,7 @@ def ensure_python_allowed(*, request_method: RequestMethod, label: str) -> None:On a deployment that is not sandbox-hosted, any `.py` file is refused (403 `CustomCodeRequiresSandbox`): running itwould import it in-process. On a sandbox-hosted deployment, the method's own tree declaring a Python structure class- is refused (`MethodStructuresRefusedError`, a 403), naming each file by its tree path; a dependency tree is checked+ is refused (`MethodStructuresRefusedError`, a 422), naming each file by its tree path; a dependency tree is checkedonce written, by its address (`written_method`)."""if not request_method.has_python:@@ -719,7 +719,7 @@ def written_method(*, request_method: RequestMethod) -> Generator[WrittenMethod,The method's own tree is written as one directory, the library directory of the load; each dependency tree as`<name>/` in a methods directory of its own, the layout the engine's `methods_dirs` take, so two dependencies sharinga name never meet. On a sandbox-hosted deployment, a dependency tree declaring a Python structure class is refused,- naming it by its address, as a fetched package is (`MethodStructuresRefusedError`, a 403).+ naming it by its address, as a fetched package is (`MethodStructuresRefusedError`, a 422)."""with ExitStack() as stack:temp_dir = Path(tempfile.mkdtemp(prefix="pipelex-method-"))diff --git a/api/pipelex_api/openapi_responses.py b/api/pipelex_api/openapi_responses.pyindex 577912429..d45223ce6 100644--- a/api/pipelex_api/openapi_responses.py+++ b/api/pipelex_api/openapi_responses.py@@ -1,18 +1,18 @@-"""Documentation-only models and shared `responses=` declarations for the API's RFC 7807 errors.+"""Documentation-only models and shared `responses=` declarations for the API's problem documents.Every failure this server emits is an `application/problem+json` document built-by the global handlers in `pipelex_api.exception_handlers` — from a pipelex-`ErrorReport` (`build_problem_document`) or from an API-authored `ApiError`-(`build_problem_document_from_api_error`). Neither path validates through a-Pydantic model: they build plain dicts. The models here exist **only** so the+by the global handlers in `pipelex_api.exception_handlers` — the problem of a+pipelex error (`PipelexError.to_problem`, in the view of the request's reader)+or the document of an API-authored `ApiError`+(`build_problem_document_from_api_error`). The models here exist **only** so thecommitted OpenAPI artifact can publish that shape with a real schema instead ofan untyped `additionalProperties: true` blob — nothing in the request pathimports them, and adding a field here does not change a single response byte.-Keep them in step with `docs/error-responses.md`, which is the prose contract.+Keep them in step with `docs/api-server/error-responses.md`, which is the prose contract.-`ProblemDocument.validation_errors` reuses pipelex's own `ValidationErrorItem`,-so the item shape published on the error wire is the same one `/validate`'s 200-invalid arm publishes — including `suggested_fix`, which rides along for free.+The members of a pipelex error's problem reuse the problem's own models (its next+step, parameters, location, items and diagnostics), so the shapes published here+are the ones the problem is validated with.The response dicts below are attached two ways:@@ -33,20 +33,20 @@ re-keys every 4xx/5xx response onto `application/problem+json` (viafrom typing import Any-from pipelex.base_exceptions import ValidationErrorItem-from pipelex.cogt.inference.error_classification import ProviderErrorMetadata, UserAction+from mthds.protocol.problem.models import NextStep, ProblemItem, ProblemLocation, ProblemParams+from pipelex.errors.problem import ProblemDiagnosticsfrom pydantic import BaseModel, ConfigDict, Fieldclass ProblemDocument(BaseModel):- """An RFC 7807 `application/problem+json` error body — the shape of every failure response.-- 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, 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.+ """An RFC 9457 `application/problem+json` error body — the shape of every failure response.++ A pipelex error answers its problem document: the RFC's members (`type`, `title`, `status`, `detail`), the MTHDS+ core's (`code`, `domain`, `retry`, `next_step`, always present, and `retry_after`, `params`, `location`, `errors`,+ `pipeline_run_id` when they hold a value) and Pipelex's (`request_id`, and `diagnostics` in the operator view+ alone). An API-authored error carries no `code` yet, and is classified by `error_type`, `error_domain` and+ `retryable` instead, with its request path as `instance`. No member is ever written as `null`: a member with no+ value is absent. `extra="allow"` mirrors RFC 9457's open-ended extension-member rule."""model_config = ConfigDict(extra="allow")@@ -62,46 +62,58 @@ class ProblemDocument(BaseModel):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.")+ status: int = Field(..., description="HTTP status code, repeated in the body per RFC 9457: the status its `code` declares.")+ detail: str = Field(+ ...,+ description=(+ "Human-readable explanation of this specific failure, rendered from its code's template and parameters. "+ "Never parsed: a program branches on `code`."+ ),+ )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."+ "or a Pipelex code (e.g. `pipelex.config.invalid`). Present on every error the runtime raises; 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(+ domain: str | None = Field(default=None, description="Who must act, the code's domain: `input`, `method`, `account`, `operator` or `runtime`.")+ retry: str | None = Field(+ default=None, description="Whether repeating the request can succeed, the code's verdict: `yes`, `no` or `outcome_unknown`."+ )+ retry_after: float | None = Field(default=None, description="Seconds to wait before a retry, when known, on a code whose verdict is `yes`.")+ next_step: NextStep | None = Field(default=None,- description="`input` (caller can fix it → 422), `config` or `runtime` (deployment must fix it → 500). Absent for domain-less errors.",+ description="What the reader should do next: a kind and a sentence, aimed at the caller, or at the operator in the operator view.",+ )+ params: ProblemParams | None = Field(default=None, description="The code's typed parameters, the ones its templates are rendered with.")+ location: ProblemLocation | None = Field(+ default=None, description="Where the failure happened: the failing pipe and its path from the entry pipe, an input, a field, a file.")- retryable: bool | None = Field(+ errors: list[ProblemItem] | None = Field(default=None,description=(- "Whether retrying the same request can plausibly succeed. Always present: on an error carrying a `code`, it is that code's retry verdict."+ "One item per fault, for a refusal with several, such as a method that does not validate. "+ "On `/validate`, `/resolve`, `/codegen` and `/pipe-io` an invalid bundle is a **200** verdict instead."),)- error_category: str | None = Field(default=None, description="Finer classification, when the originating error provides one (inference errors).")- user_action: UserAction | None = Field(default=None, description="Structured suggestion of what the caller should do next, when available.")- model: str | None = Field(default=None, description="Inference model that failed. Stripped under `ERROR_DISCLOSURE=strict`.")- provider: str | None = Field(default=None, description="Inference provider that failed. Stripped under `ERROR_DISCLOSURE=strict`.")- provider_metadata: ProviderErrorMetadata | None = Field(- default=None,- description="Upstream provider error metadata. Stripped (bar a curated slice) under `ERROR_DISCLOSURE=strict`.",- )- validation_errors: list[ValidationErrorItem] | None = Field(+ pipeline_run_id: str | None = Field(default=None, description="The run the failure belongs to.")+ request_id: str | None = Field(default=None, description="Correlation id, echoed in the `X-Request-ID` response header.")+ diagnostics: ProblemDiagnostics | None = Field(default=None,description=(- "Structured per-error diagnostics, carried by a `ValidateBundleError`. Each item may carry a `suggested_fix`. "- "Retained under `ERROR_DISCLOSURE=strict` — it describes the caller's own bundle, not server internals. "- "On `/validate`, `/resolve`, `/codegen` and `/pipe-io` an invalid bundle is a **200** verdict instead, so the "- "items ride the response body there rather than a problem document."+ "What only the operator reads: the error's class and message, its causes, the provider's answer, the model. "+ "Present only when the request was authenticated as the operator's (`AUTH_MODE=api_key`, or a trusted proxy)."),)+ instance: str | None = Field(default=None, description="Path of the request that failed, on an API-authored error.")+ error_type: str | None = Field(default=None, description="Stable name of an API-authored error (e.g. `Unauthenticated`).")+ error_domain: str | None = Field(+ default=None,+ description="On an API-authored error: `input` (caller can fix it → 4xx) or `config` (deployment must fix it → 5xx).",+ )+ retryable: bool | None = Field(default=None, description="On an API-authored error: whether retrying the same request can plausibly succeed.")def _problem(description: str, *, headers: dict[str, Any] | None = None) -> dict[str, Any]:@@ -137,20 +149,17 @@ PROBLEM_403_RUN_POLICY: dict[str, Any] = _problem("`orchestration_mode` this deployment does not allow overriding per request ""(`allow_request_orchestration_mode_override = false`); `CustomCodeRequiresSandbox` — the method (a bundle, or a ""fetched `method_ref` package) ships custom Python and this deployment is not sandbox-hosted; or "- "`MethodStructuresRefusedError` — the method's Python declares structure classes (`StructuredContent` "- "subclasses), whether it arrived as a bundle (`files` or `bundle_b64`) or as a fetched `method_ref` package: "- "a sandbox-hosted deployment imports no caller Python into its own process, so it refuses them before "- "loading anything (express the types as MTHDS concepts instead); or `ReadScopeForbidden` — on a `jwt` deployment, "- "the request sent a `read_scope` that does not lie under the caller's own `user_id`.",+ "`ReadScopeForbidden` — on a `jwt` deployment, the request sent a `read_scope` that does not lie under the caller's "+ "own `user_id`. The refusal of a method whose Python declares structure classes, "+ "`pipelex.deployment.python_structures_refused`, is a 422 instead, since the method's author changes it.",)PROBLEM_403_METHOD_PYTHON_POLICY: dict[str, Any] = _problem("The run routes' Python policy, applied to the method's tree: `CustomCodeRequiresSandbox` — the method (sent in "- "`files`, or a fetched `method_ref` package) ships custom Python and this deployment is not sandbox-hosted; or "- "`MethodStructuresRefusedError` — the method's Python declares structure classes (`StructuredContent` subclasses), "- "which a sandbox-hosted deployment never imports into its own process (express the types as MTHDS concepts instead). "+ "`files`, or a fetched `method_ref` package) ships custom Python and this deployment is not sandbox-hosted. ""Also `ReadScopeForbidden` — on a `jwt` deployment, the request sent a `read_scope` that does not lie under the "- "caller's own `user_id`.",+ "caller's own `user_id`. The refusal of a method whose Python declares structure classes, "+ "`pipelex.deployment.python_structures_refused`, is a 422 instead, since the method's author changes it.",)PROBLEM_403_READ_SCOPE: dict[str, Any] = _problem(@@ -159,7 +168,7 @@ PROBLEM_403_READ_SCOPE: dict[str, Any] = _problem()PROBLEM_409_DUPLICATE_RUN: dict[str, Any] = _problem(- "`PipelineManagerAlreadyExistsError` — the submitted `pipeline_run_id` is still registered for an in-flight run. "+ "`pipelex.run.already_exists` — the submitted `pipeline_run_id` is still registered for an in-flight run. ""Completed and failed runs free their id, so this only fires for genuinely concurrent duplicates.",)@@ -168,9 +177,9 @@ PROBLEM_413: dict[str, Any] = _problem()PROBLEM_422: dict[str, Any] = _problem(- "The request could not be processed: a malformed body, a field failing validation, or an `input`-domain pipelex "- "error (a `.mthds` bundle the caller must fix). Note that on the diagnostic routes an *invalid bundle* is a **200** "- "verdict, not a 422 — see each route's response contract.",+ "The request could not be processed: a malformed body, a field failing validation, or a pipelex error whose code "+ "the caller fixes (a `.mthds` bundle that does not validate, a missing input). Note that on the diagnostic routes "+ "an *invalid bundle* is a **200** verdict, not a 422 — see each route's response contract.",)PROBLEM_429: dict[str, Any] = _problem(@@ -184,18 +193,16 @@ PROBLEM_429: dict[str, Any] = _problem()PROBLEM_500: dict[str, Any] = _problem(- "A `config`-domain or `runtime`-domain failure the caller cannot fix (a missing env var, a bad TOML override, a "- "backend fault), or an unclassified error sanitized by the catch-all handler. Report the `request_id`.",+ "A failure the caller cannot fix (a missing env var, a bad TOML override, a backend fault), or an unexpected "+ "error answered as `runtime.unexpected`. Report the `request_id`.",)PROBLEM_501_ASYNC_NOT_ENABLED: dict[str, Any] = _problem(- "`AsyncExecutionNotEnabledError` — this deployment does not provide async pipeline execution. Permanent under the "- "current deployment; do not retry.",+ "`runtime.unsupported` — this deployment does not provide async pipeline execution. Permanent under the current deployment; do not retry.",)PROBLEM_404_METHOD_PACKAGE: dict[str, Any] = _problem(- "`MethodPackageNotFoundError` — the `method_ref` repository was fetched, but no package in it matches the "- "requested address by manifest identity. The message lists the packages the repository does contain.",+ "`method.not_found` — the `method_ref` repository was fetched, but no package in it matches the requested address by manifest identity.",)PROBLEM_403_BLOB_UPLOAD: dict[str, Any] = _problem(diff --git a/api/pipelex_api/openapi_schema.py b/api/pipelex_api/openapi_schema.pyindex 202e2b079..062f7fe5d 100644--- a/api/pipelex_api/openapi_schema.py+++ b/api/pipelex_api/openapi_schema.py@@ -17,12 +17,12 @@ YAML alike: both go through `openapi()`.Deliberately import-side-effect-free, mirroring `pipelex_api.exception_handlers`: no env var reads, no appconstruction, no router wiring. That is what lets a test build a production-faithful app —one that renders the error media type the way the real server does — without dragging in-`pipelex_api.main`'s startup chain (`Pipelex.make`, `get_auth_dependency`, the `ERROR_DISCLOSURE`+`pipelex_api.main`'s startup chain (`Pipelex.make`, `get_auth_dependency`, the `AUTH_MODE`fail-fast), so a misconfigured env var cannot crash collection of every module that needs theapp class."""-from typing import Any+from typing import Any, castfrom fastapi import FastAPIfrom typing_extensions import override@@ -65,6 +65,59 @@ def use_problem_json_media_type(schema: dict[str, Any]) -> None:content[PROBLEM_JSON_MEDIA_TYPE] = json_content+# Two families of models share their class names: the fix vocabulary `pipelex.suggested_fix` publishes on a verdict's+# `ValidationErrorItem`, and the standard's, which a problem's `ProblemItem` carries (`file` where Pipelex's has `source`,+# and a catch-all for an operation kind it does not list). Pydantic names both by their module when they meet, which would+# rename the schemas a generated client binds to; this pass gives Pipelex's their own names back, and the standard's the+# `Problem` prefix its other models carry.+_SCHEMA_RENAMES_BY_PREFIX: dict[str, str] = {+ "pipelex__suggested_fix__": "",+ "mthds__protocol__problem__models__": "Problem",+}++_SCHEMA_REF_PREFIX = "#/components/schemas/"+++def _renamed_schema(name: str) -> str:+ for prefix, replacement in _SCHEMA_RENAMES_BY_PREFIX.items():+ if name.startswith(prefix):+ return f"{replacement}{name.removeprefix(prefix)}"+ return name+++def _with_renamed_refs(node: Any, *, renames: dict[str, str]) -> Any:+ """``node`` with every schema reference to a renamed schema pointing at its new name."""+ if isinstance(node, dict):+ return {key: _with_renamed_refs(value, renames=renames) for key, value in cast("dict[str, Any]", node).items()}+ if isinstance(node, list):+ return [_with_renamed_refs(item, renames=renames) for item in cast("list[Any]", node)]+ if isinstance(node, str) and node.startswith(_SCHEMA_REF_PREFIX):+ name = node.removeprefix(_SCHEMA_REF_PREFIX)+ return f"{_SCHEMA_REF_PREFIX}{renames.get(name, name)}"+ return node+++def name_shared_fix_schemas(schema: dict[str, Any]) -> None:+ """Rename the module-qualified fix schemas Pydantic generates for the two fix families, in place.++ Refuses a rename onto a name another schema already holds, which would merge two shapes into one.+ """+ components: dict[str, Any] = schema.get("components", {})+ schemas: dict[str, Any] = components.get("schemas", {})+ renames = {name: _renamed_schema(name) for name in schemas if _renamed_schema(name) != name}+ if not renames:+ return+ taken = set(schemas) - set(renames)+ clashes = sorted(new_name for new_name in renames.values() if new_name in taken)+ if clashes:+ msg = f"Renaming the fix schemas would overwrite the schemas {clashes}"+ raise ValueError(msg)+ renamed_schemas = {renames.get(name, name): value for name, value in schemas.items()}+ components["schemas"] = dict(sorted(renamed_schemas.items()))+ for key in list(schema):+ schema[key] = _with_renamed_refs(schema[key], renames=renames)++class PipelexFastAPI(FastAPI):"""The app class. Stock FastAPI, extended only to publish errors as `application/problem+json`."""@@ -80,4 +133,5 @@ class PipelexFastAPI(FastAPI):return self.openapi_schemaschema = super().openapi()use_problem_json_media_type(schema)+ name_shared_fix_schemas(schema)return schemadiff --git a/api/pipelex_api/problem_document.py b/api/pipelex_api/problem_document.pyindex 3ba009187..7d9e887f3 100644--- a/api/pipelex_api/problem_document.py+++ b/api/pipelex_api/problem_document.py@@ -1,23 +1,17 @@-"""RFC 7807 problem-document construction.--A pure module — no FastAPI imports, no I/O. It turns the two error sources of-the API into the single `application/problem+json` body shape clients see:--- `build_problem_document` — for a pipelex `ErrorReport`. Delegates to- `ErrorReport.to_problem_document(...)`: pipelex owns the field mapping- (standard RFC 7807 slots plus classification extension members) and the- `disclosure_mode` redaction. The API only chooses the disclosure mode and- supplies the request context.-- `build_problem_document_from_api_error` — for an API-authored 4xx that has- no `ErrorReport` behind it (`raise_validation_error` and friends in- `pipelex_api.errors`). Built from the static `ErrorType` enum; always `INPUT` domain.--Both return a plain `dict` the caller serializes as `application/problem+json`.+"""Problem-document construction for the API's own errors.++A pure module — no FastAPI imports, no I/O. A pipelex error answers its own+problem document (`PipelexError.to_problem`, rendered by+`pipelex_api.exception_handlers.problem_response`); this module builds the+document of an API-authored 4xx/5xx that has no `PipelexError` behind it+(`raise_validation_error` and friends in `pipelex_api.errors`), from the static+`ErrorType` enum. It returns a plain `dict` the caller serializes as+`application/problem+json`."""from typing import Any-from pipelex.base_exceptions import DisclosureMode, ErrorDomain, ErrorReport+from pipelex.base_exceptions import ErrorDomainfrom pipelex_api.error_types import ErrorTypefrom pipelex_api.error_uri import error_type_title, error_type_uri@@ -28,27 +22,6 @@ from pipelex_api.error_uri import error_type_title, error_type_uriPROBLEM_JSON_MEDIA_TYPE = "application/problem+json"-def build_problem_document(- report: ErrorReport,- *,- instance: str | None,- request_id: str | None,- disclosure_mode: DisclosureMode,-) -> dict[str, Any]:- """Build an RFC 7807 problem document from a pipelex `ErrorReport`.-- Thin wrapper over `ErrorReport.to_problem_document(...)`: the field mapping- and the `disclosure_mode` redaction both live upstream in pipelex. The- API's only responsibility is to choose the disclosure mode and pass the- request context through.- """- return report.to_problem_document(- instance=instance,- request_id=request_id,- disclosure_mode=disclosure_mode,- )--def build_problem_document_from_api_error(error_type: ErrorType,message: str,@@ -63,28 +36,10 @@ def build_problem_document_from_api_error(Used by the `pipelex_api.errors` 4xx/5xx helpers, whose failures are the API's ownrequest validation, auth, or configuration checks rather than a pipelex- domain error — there is no `ErrorReport` to delegate to. The `type` URI and- `title` are derived from the static `ErrorType` enum the same way pipelex- derives them for its own classes, so the standard RFC 7807 slots and the- `error_type` / `error_domain` members line up with what a pipelex error- renders.-- Extension-member parity with a pipelex `ErrorReport` is by-field, not- wholesale, with two distinct rules:-- - `retryable` is emitted unconditionally here (every API-authored error is- non-retryable; see below). pipelex emits it only when the source error- populated it, so a non-inference pipelex report (`PipelexConfigError`,- `EnvVarNotFoundError`) renders with no `retryable`. Asymmetric by design:- the API knows the answer for every error it authors, and clients can- drive retry logic uniformly without branching on field presence.- - Classification fields pipelex sets only on classifiable failures- (`error_category`, `user_action`, `model`, `provider`, `provider_metadata`)- are NOT manufactured here. The same omission rule pipelex applies to its- own non-inference reports (`PipelexConfigError`, `EnvVarNotFoundError`- carry no `error_category` either) — surfacing a fake category for an- API-authored validation or auth failure would lie about what the API- actually classified.+ domain error — there is no `PipelexError` whose problem it could answer. The+ `type` URI and `title` are derived from the static `ErrorType` enum, and the+ `error_type` / `error_domain` / `retryable` members classify it until every+ API-authored error answers a registry code.`error_domain` defaults to `INPUT` — the caller can fix a 4xx. API-owned5xx (a missing secret, a misconfigured backend) pass `CONFIG`: an operator,@@ -98,7 +53,7 @@ def build_problem_document_from_api_error(field presence.`None`-valued context (`instance`, `request_id`) is dropped rather than- emitted as `null`, matching `ErrorReport.to_problem_document` semantics.+ emitted as `null`, as a problem document never writes a member as `null`."""document: dict[str, Any] = {"type": error_type_uri(error_type),diff --git a/api/pipelex_api/problem_view.py b/api/pipelex_api/problem_view.pynew file mode 100644index 000000000..f3b8c8b48--- /dev/null+++ b/api/pipelex_api/problem_view.py@@ -0,0 +1,35 @@+"""The view of a problem a request's reader sees, picked by the identity the request authenticated.++A failure answered to a request is one problem document seen through a view, and who made the request decides which+(`pipelex.errors.problem`): the operator, whoever runs this runner, reads the operator view, with `diagnostics` and the+operator's step; anyone else reads the caller view. No deployment setting picks it.++The authentication dependencies in `pipelex_api.security` mark a request as the operator's when the identity they+authenticated is the operator's:++- `AUTH_MODE=api_key`: the static API key is the operator's own credential, so whoever presents it is the operator, as a+ developer running this server locally is.+- `AUTH_MODE=none` with `TRUST_FORWARDED_IDENTITY_HEADERS=true`: the only party that reaches this server is the trusted+ proxy in front of it, such as the hosted platform, which is the deployment's own hop and reads the operator view. It+ owes its own callers their caller view.++A request authenticated by a caller's token (`AUTH_MODE=jwt`), a request to a server with no authentication and no+trusted proxy, and a request refused before any authentication ran are a caller's, and read the caller view: the view+falls back to the caller's whenever nothing marked the request.+"""++from pipelex.errors.problem import ProblemView+from starlette.requests import Request+++def mark_operator_request(request: Request) -> None:+ """Record that the request was authenticated as the operator's, so its failures answer the operator view."""+ request.state.problem_view = ProblemView.OPERATOR+++def problem_view_of(request: Request) -> ProblemView:+ """The view of a problem the request's reader sees: the operator's when authentication marked it so, else the caller's."""+ view = getattr(request.state, "problem_view", None)+ if isinstance(view, ProblemView):+ return view+ return ProblemView.CALLERdiff --git a/api/pipelex_api/routes/pipelex/codegen.py b/api/pipelex_api/routes/pipelex/codegen.pyindex afeb2bebd..8439a0529 100644--- a/api/pipelex_api/routes/pipelex/codegen.py+++ b/api/pipelex_api/routes/pipelex/codegen.py@@ -3,11 +3,11 @@ from typing import Annotated, Literal, Self, Unionfrom fastapi import APIRouter, Requestfrom fastapi.responses import JSONResponse-from pipelex.base_exceptions import ErrorReportfrom pipelex.codegen.emission import build_stamped_projectionfrom pipelex.codegen.emitters.target import CodegenKind, CodegenTargetfrom pipelex.codegen.emitters.types_emitter import emit_typesfrom pipelex.codegen.lock import CODEGEN_LOCK_FILENAME+from pipelex.pipeline.exceptions import ValidateBundleErrorfrom pipelex.pipeline.usage_stats_reporting import CodeGenerationReport, usage_stats_codegen_targetfrom pipelex.system.usage_stats.usage_stats_contract import UsageStatsCodegenArtifactfrom pipelex.tools.misc.package_utils import get_package_version@@ -172,7 +172,7 @@ async def _generate_codegen_response(*, request: Request, request_data: CodegenRreturn JSONResponse(content=report.model_dump(mode="json", by_alias=True))outcome = await project_resolved_method(request=request, request_data=request_data, project=_projection_response)- if isinstance(outcome, ErrorReport):+ if isinstance(outcome, ValidateBundleError):generation_report.declare_failed()return invalid_crate_report_response(outcome)return outcomediff --git a/api/pipelex_api/routes/pipelex/crate_ops.py b/api/pipelex_api/routes/pipelex/crate_ops.pyindex 2af8ef464..2f43310be 100644--- a/api/pipelex_api/routes/pipelex/crate_ops.py+++ b/api/pipelex_api/routes/pipelex/crate_ops.py@@ -30,8 +30,8 @@ from typing import Literal, NamedTuple, NoReturn, TypeVarfrom fastapi import Requestfrom fastapi.responses import JSONResponsefrom mthds.protocol.problem.registry import CoreCode-from pipelex.base_exceptions import ErrorReport, ValidationErrorItem-from pipelex.cogt.inference.error_classification import UserAction, UserActionKind+from pipelex.base_exceptions import ValidationErrorItem+from pipelex.errors.problem import ProblemViewfrom pipelex.interpreter_hub import clear_current_library, get_current_library_id_or_none, get_library_manager, get_required_entry_pipefrom pipelex.libraries.library_crate import LibraryCratefrom pipelex.libraries.pipe.exceptions import EntryPipeAmbiguousError, EntryPipeNotFoundError, PipeNotFoundError@@ -78,15 +78,17 @@ class CrateInvalidReport(BaseModel):message: str = Field(default="MTHDS library could not be resolved", description="Human-readable summary of the verdict.")-def invalid_crate_report_response(error_report: ErrorReport) -> JSONResponse:+def invalid_crate_report_response(validate_error: ValidateBundleError) -> JSONResponse:"""Render a produced "could not resolve" verdict as a 200 `CrateInvalidReport`.+ The items are the error's own (`ValidateBundleError.validation_error_items`) and the message is+ its problem's `detail`, the sentence its code renders, which reads the same in every view.`exclude_none` drops each item's unset locators so the wire items match the agent CLI'sbyte-for-byte — the "one error item, two surfaces" guarantee `/validate` already keeps."""invalid_report = CrateInvalidReport(- validation_errors=error_report.validation_errors or [],- message=error_report.message,+ validation_errors=validate_error.validation_error_items(),+ message=validate_error.to_problem(view=ProblemView.CALLER).detail,)return JSONResponse(content=invalid_report.model_dump(mode="json", serialize_as_any=True, by_alias=True, exclude_none=True))@@ -116,13 +118,13 @@ class ResolvedMethod(NamedTuple):return manifest.main_pipe if manifest is not None else None-def _resolve_written_method(*, written: WrittenMethod) -> LibraryCrate | ErrorReport:+def _resolve_written_method(*, written: WrittenMethod) -> LibraryCrate | ValidateBundleError:"""The crate of a method written out, or the invalid verdict when it does not resolve."""try:return resolve_crate_from_method_dir(method_dir=written.method_dir, methods_dirs=written.methods_dirs)except ValidateBundleError as validate_error:# The produced negative verdict: the core already tore its library down.- return validate_error.to_error_report()+ return validate_errordef _project_written_method(@@ -130,7 +132,7 @@ def _project_written_method(request_method: RequestMethod,method_label: str,project: Callable[[ResolvedMethod], ProjectionT],-) -> ProjectionT | ErrorReport:+) -> ProjectionT | ValidateBundleError:"""Write the method out, resolve it, hand it to `project` while it is loaded, and release everything: blocking work.Runs whole in one worker thread, so the library the core binds as current in this thread's context is the one@@ -138,7 +140,7 @@ def _project_written_method("""with written_method(request_method=request_method) as written:resolution = _resolve_written_method(written=written)- if isinstance(resolution, ErrorReport):+ if isinstance(resolution, ValidateBundleError):return resolutiontry:return project(ResolvedMethod(crate=resolution, request_method=request_method, method_label=method_label))@@ -151,14 +153,14 @@ async def project_resolved_method(request: Request,request_data: MethodTreeRequest,project: Callable[[ResolvedMethod], ProjectionT],-) -> ProjectionT | ErrorReport:+) -> ProjectionT | ValidateBundleError:"""Resolve the method the request names into its normalized crate, and return what `project` makes of it.The method is read as `/validate` reads it (`select_request_method`), then written out as a run writes it and loadedalone as the caller's own library directory, its dependency trees as the packages it ships, in a worker thread.`project` runs in that thread with the freshly opened library loaded and current, so it can read live pipes, and thewritten tree held; both are released when it returns or raises. A method that does not resolve returns its invalid- verdict instead, an `ErrorReport` carrying the structured `validation_errors`, with `project` never called and+ verdict instead, the `ValidateBundleError` carrying the structured validation items, with `project` never called andnothing left loaded.Raises (as problem documents): 501 for a registry-form `method_ref`; the 422s and 403s of `select_request_method`;@@ -221,8 +223,11 @@ class PipeSelectionMiss(NamedTuple):"""Where the selector that missed came from, which picks the refusal's code; `None` when there was no selectorat 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."""+ selector: str | None = None+ """The selector that missed, the request's `pipe_ref` or a declared `main_pipe`; `None` when there was none."""++ candidates: list[str] | None = None+ """The qualified refs of the `main_pipe`s the closure declares, when it declares several."""def resolve_requested_pipe(crate: LibraryCrate, *, pipe_ref: str | None, manifest_main_pipe: str | None) -> RequestedPipe:@@ -253,57 +258,52 @@ def _raise_selection_refusal(miss: PipeSelectionMiss) -> NoReturn:A selection refusal must not share `ValidationError` with a malformed request, or a client has nofield to tell the two apart. So it is raised as `EntryPipeNotFoundError` or`EntryPipeAmbiguousError`, the classes the engine's entry lookup raises and the run routes answer- with for an unknown or ambiguous `pipe_code`. The global `PipelexError` handler then renders it —- the class name as `error_type`, the INPUT domain as a 422, the class's `user_action` — exactly as- it renders the run routes' refusal. Both classes declare their messages caller-facing, which every- message built here honours: it names the caller's selector, the manifest's `main_pipe`, or the- qualified refs of the closure the caller submitted, and nothing from a host library.+ with for an unknown or ambiguous `pipe_code`. The global `PipelexError` handler then renders its+ problem exactly as it renders the run routes' refusal: the code's status and sentences, filled+ with the parameters given here, the selector that missed and the candidates. The message built+ here rides the operator's diagnostics alone.The no-entry-pipe miss is a not-found and the several-`main_pipe`s miss an ambiguity, the way the- pipe-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.+ pipe-selector design classifies them.The code says who must act, which is where the selector came from. A selector the request named thatmisses 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.+ pipe where the closure gives no single `main_pipe` to default to (`request.pipe_unspecified`, naming as its+ `candidates` the `main_pipe`s the closure declares when it declares several, since there is then no selector+ for `request.pipe_ambiguous` to name). A `main_pipe` the method itself declares, in the fetched package's+ manifest or in the closure, is the method's, whose author fixes the declaration: one that names no pipe of+ the closure is `method.pipe_unresolved`, naming it as the `missing` pipe, and one that matches pipes in+ several domains is `method.ref_ambiguous`, naming it as the `ref` with its `candidates`, so the refusal+ never says a pipe that exists twice does not exist."""match miss.kind:case PipeSelectionMissKind.NOT_FOUND: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)- )+ raise (EntryPipeNotFoundError(miss.message).with_error_code(CoreCode.REQUEST_PIPE_NOT_FOUND).with_params(pipe=miss.selector))case SelectorOrigin.MANIFEST | SelectorOrigin.CLOSURE:- raise (- EntryPipeNotFoundError(miss.message)- .with_error_code(CoreCode.METHOD_PIPE_UNRESOLVED)- .as_caller_fault(user_action=miss.user_action)- )+ raise (EntryPipeNotFoundError(miss.message).with_error_code(CoreCode.METHOD_PIPE_UNRESOLVED).with_params(missing=miss.selector))case None:- raise (- EntryPipeNotFoundError(miss.message)- .with_error_code(CoreCode.REQUEST_PIPE_UNSPECIFIED)- .as_caller_fault(user_action=miss.user_action)- )+ raise (EntryPipeNotFoundError(miss.message).with_error_code(CoreCode.REQUEST_PIPE_UNSPECIFIED))case PipeSelectionMissKind.AMBIGUOUS:match miss.origin:- case SelectorOrigin.REQUEST | None:+ case SelectorOrigin.REQUEST:raise (EntryPipeAmbiguousError(miss.message).with_error_code(CoreCode.REQUEST_PIPE_AMBIGUOUS)- .as_caller_fault(user_action=miss.user_action)+ .with_params(pipe=miss.selector, candidates=miss.candidates)+ )+ case None:+ raise (+ EntryPipeAmbiguousError(miss.message)+ .with_error_code(CoreCode.REQUEST_PIPE_UNSPECIFIED)+ .with_params(candidates=miss.candidates))case SelectorOrigin.MANIFEST | SelectorOrigin.CLOSURE:raise (EntryPipeAmbiguousError(miss.message)- .with_error_code(CoreCode.METHOD_PIPE_UNRESOLVED)- .as_caller_fault(user_action=miss.user_action)+ .with_error_code(CoreCode.METHOD_REF_AMBIGUOUS)+ .with_params(ref=miss.selector, candidates=miss.candidates))@@ -336,10 +336,6 @@ def select_default_pipe(crate: LibraryCrate, *, manifest_main_pipe: str | None)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.",- ),)if len(candidates) > 1:joined = ", ".join(sorted(candidates))@@ -347,10 +343,7 @@ def select_default_pipe(crate: LibraryCrate, *, manifest_main_pipe: str | None)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.",- ),+ candidates=sorted(candidates),)return _select_entry_pipe(candidates[0], origin=SelectorOrigin.CLOSURE)@@ -386,9 +379,14 @@ def _select_entry_pipe(selector: str, *, origin: SelectorOrigin) -> RequestedPipkind=PipeSelectionMissKind.AMBIGUOUS,message=f"{described} matches pipes in several domains of {scope}, so it selects none: {exc}",origin=origin,+ selector=selector,+ # The qualified refs the entry lookup found, which the refusal names to the caller.+ candidates=exc.given_params.get("candidates"),)except PipeNotFoundError as exc:- return PipeSelectionMiss(kind=PipeSelectionMissKind.NOT_FOUND, message=f"{described} not found in {scope}: {exc}", origin=origin)+ return PipeSelectionMiss(+ kind=PipeSelectionMissKind.NOT_FOUND, message=f"{described} not found in {scope}: {exc}", origin=origin, selector=selector+ )return RequestedPipe(ref=the_pipe.pipe_ref, pipe=the_pipe)diff --git a/api/pipelex_api/routes/pipelex/pipe_io.py b/api/pipelex_api/routes/pipelex/pipe_io.pyindex debf3559b..cf4e959e0 100644--- a/api/pipelex_api/routes/pipelex/pipe_io.py+++ b/api/pipelex_api/routes/pipelex/pipe_io.py@@ -2,10 +2,9 @@ from typing import TYPE_CHECKING, Annotated, Any, Literal, Unionfrom fastapi import APIRouter, Requestfrom fastapi.responses import JSONResponse-from pipelex.base_exceptions import ErrorReportfrom pipelex.interpreter_hub import get_own_pipes, get_pipe_libraryfrom pipelex.pipeline.build_pipe_io_artifacts import build_pipe_io_artifacts-from pipelex.pipeline.exceptions import MethodEntryError+from pipelex.pipeline.exceptions import MethodEntryError, ValidateBundleErrorfrom pipelex.pipeline.input_form import InputForm, OutputFormfrom pipelex.pipeline.pipe_io_contracts import PipeIOContractsfrom pipelex.pipeline.validate_bundle import build_pending_signatures@@ -152,7 +151,7 @@ async def pipe_io(request: Request, request_data: PipeIORequest) -> JSONResponserequest_data=request_data,project=lambda resolution: _pipe_io_response(resolution=resolution, request_data=request_data),)- if isinstance(outcome, ErrorReport):+ if isinstance(outcome, ValidateBundleError):return invalid_crate_report_response(outcome)return outcomediff --git a/api/pipelex_api/routes/pipelex/pipeline.py b/api/pipelex_api/routes/pipelex/pipeline.pyindex edbb3ce02..e9e668ae7 100644--- a/api/pipelex_api/routes/pipelex/pipeline.py+++ b/api/pipelex_api/routes/pipelex/pipeline.py@@ -13,6 +13,8 @@ from mthds.protocol.problem.registry import CoreCodefrom pipelex.base_exceptions import PipelexUnexpectedErrorfrom pipelex.config import get_configfrom pipelex.core.pipes.pipe_output import PipeOutput+from pipelex.errors.bundle_validation_failure import BundleValidationFailure+from pipelex.errors.problem import ProblemViewfrom 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, WebhookTarget@@ -60,6 +62,7 @@ from pipelex_api.openapi_responses import (PROBLEM_429,PROBLEM_501_ASYNC_NOT_ENABLED,)+from pipelex_api.problem_view import problem_view_offrom pipelex_api.routes.pipelex.utils import get_current_iso_timestampfrom pipelex_api.schemas.models import (PipelexApiExecuteRequest,@@ -77,7 +80,6 @@ if TYPE_CHECKING:from mthds.protocol.pipe_output import VariableMultiplicityfrom mthds.protocol.pipeline_inputs import PipelineInputsfrom mthds.protocol.working_memory import WorkingMemoryAbstract- from pipelex.base_exceptions import ErrorReportfrom pipelex.core.memory.working_memory import WorkingMemoryfrom pipelex.methods.fetching import MethodProvenancefrom pipelex.pipe_run.pipe_job import PipeJob@@ -407,6 +409,7 @@ class ApiRunner(PipelexMTHDSProtocol):callback_urls: list[str] | None = None,request_id: str | None = None,requested_orchestration_mode: str | None = None,+ callback_problem_view: ProblemView = ProblemView.CALLER,) -> PipelexRunResultStart:"""Start a method execution asynchronously without waiting for completion.@@ -431,6 +434,9 @@ class ApiRunner(PipelexMTHDSProtocol):we accept it, and `StartAck.pipeline_run_id` echoes it back as authoritative).`callback_urls` is THIS server's extension (completion webhooks) — the wirelayer validates it (`PipelineApiExtras`) and passes it here by name.+ `callback_problem_view` is the view of a failed run's problem those webhooks carry: the+ view of the request's own reader (`pipelex_api.problem_view`), since a completion webhook+ is the same answer as the synchronous response, delivered later.`extra` is the protocol's generic extension slot; this runner's wireextras are parsed by the route layer, so nothing reaches it — anon-empty value is an in-process misuse and is rejected. `request_id`@@ -517,6 +523,7 @@ class ApiRunner(PipelexMTHDSProtocol):WebhookTarget(url=url,headers={"X-Completion-Signature": _completion_signature(resolved_pipeline_run_id)},+ problem_view=callback_problem_view,)for url in callback_urls]@@ -569,7 +576,7 @@ class ApiRunner(PipelexMTHDSProtocol):requested_orchestration_mode: str | None,graph_pipe_code: str | None,method_dir: Path | None = None,- ) -> PipelexValidationReport | ErrorReport:+ ) -> PipelexValidationReport | BundleValidationFailure:"""Validate MTHDS bundles, returning the verdict as a value (the route maps it to a 200).Mode-aware, mirroring `start`: the effective `orchestration_mode` is resolved FIRST (config@@ -580,8 +587,8 @@ class ApiRunner(PipelexMTHDSProtocol):loud with `MissingBundleValidatorError` (carrying the install hint). Validation is inherentlyblocking, so there is no delivery axis here — the registry holds one validator per mode.- Returns the verdict, not a raise: the valid `PipelexValidationReport`, or the structured- `ErrorReport` an invalid bundle produces (carrying `validation_errors`). A genuine+ Returns the verdict, not a raise: the valid `PipelexValidationReport`, or the+ `BundleValidationFailure` an invalid bundle produces (carrying `validation_errors`). A genuineno-verdict infra fault propagates to the global problem+json handler (5xx). The routediscriminates on `isinstance(verdict, PipelexValidationReport)`.@@ -624,7 +631,10 @@ class ApiRunner(PipelexMTHDSProtocol):with translate_to_validate_bundle_error():await self._ensure_served_method_requirements_met()except ValidateBundleError as invalid_method:- return invalid_method.to_error_report()+ return BundleValidationFailure(+ problem=invalid_method.to_problem(view=ProblemView.OPERATOR),+ validation_errors=invalid_method.validation_error_items(),+ )verdict = await validator.validate_bundles(mthds_contents=mthds_contents,mthds_sources=mthds_sources,@@ -645,8 +655,8 @@ class ApiRunner(PipelexMTHDSProtocol):# The core seam types its valid arm at the protocol-level ValidationReport (a leaf type)# to stay import-acyclic in core; every registered validator in fact produces the canonical# PipelexValidationReport. Recover the precise type here — the single narrowing point — so- # the route's `isinstance(verdict, PipelexValidationReport)` yields ErrorReport on the else arm.- return cast("PipelexValidationReport | ErrorReport", verdict)+ # the route's `isinstance(verdict, BundleValidationFailure)` yields the report on the else arm.+ return cast("PipelexValidationReport | BundleValidationFailure", verdict)# The object keys a kajson decoder reads as class markers: `__class__` and `__module__` name a class to@@ -1004,8 +1014,8 @@ async def execute(request: Request) -> JSONResponse:# client-supplied run id it (alone) accepts:# 400 — the resolved orchestrator is blocking-only (the in-process `direct` base): refuse# honestly rather than block-and-ack. Use `/execute`.- # 403 — a per-request `orchestration_mode` override the deployment forbids, the- # custom-code sandbox gate, or the structures refusal on a bundle or a fetched package.+ # 403 — a per-request `orchestration_mode` override the deployment forbids, or the+ # custom-code sandbox gate on a bundle or a fetched package.# 404 — a `method_ref` whose repository holds no matching package.# 409 — the submitted `pipeline_run_id` is still registered for an in-flight run.# 501 — an async-capable deployment whose async execution is not enabled.@@ -1083,6 +1093,7 @@ async def start(callback_urls=extras.callback_urls,request_id=request_id_of(request),requested_orchestration_mode=extras.orchestration_mode,+ callback_problem_view=problem_view_of(request),)# The ack plus this server's provenance extension: `(address, tag, commit_sha)` for a# `method_ref` run, null otherwise — the caller (and, on hosted, the platform's Run row)diff --git a/api/pipelex_api/routes/pipelex/resolve.py b/api/pipelex_api/routes/pipelex/resolve.pyindex aa743bb56..0d2239f67 100644--- a/api/pipelex_api/routes/pipelex/resolve.py+++ b/api/pipelex_api/routes/pipelex/resolve.py@@ -3,8 +3,8 @@ from typing import Annotated, Any, Literal, Unionfrom fastapi import APIRouter, Requestfrom fastapi.responses import JSONResponse-from pipelex.base_exceptions import ErrorReportfrom pipelex.codegen.crate_encoding import encode_crate_json+from pipelex.pipeline.exceptions import ValidateBundleErrorfrom pydantic import BaseModel, Fieldfrom pipelex_api.json_body import JsonBodyRoute@@ -68,7 +68,7 @@ async def resolve_mthds(request: Request, request_data: MethodTreeRequest) -> JS5xx. All RFC 7807 `application/problem+json` via the global handlers."""outcome = await project_resolved_method(request=request, request_data=request_data, project=_crate_response)- if isinstance(outcome, ErrorReport):+ if isinstance(outcome, ValidateBundleError):return invalid_crate_report_response(outcome)return outcomediff --git a/api/pipelex_api/routes/pipelex/validate.py b/api/pipelex_api/routes/pipelex/validate.pyindex 50d0b476f..84cdb4e35 100644--- a/api/pipelex_api/routes/pipelex/validate.py+++ b/api/pipelex_api/routes/pipelex/validate.py@@ -3,7 +3,8 @@ from typing import Annotated, Literal, Self, Unionfrom fastapi import APIRouter, Requestfrom fastapi.responses import JSONResponse-from pipelex.base_exceptions import ErrorReport, ValidationErrorItem+from pipelex.base_exceptions import ValidationErrorItem+from pipelex.errors.bundle_validation_failure import BundleValidationFailurefrom pipelex.pipe_machinery.pipe_factory import PipeFactoryfrom pipelex.pipeline.exceptions import MethodEntryError, ValidateBundleErrorfrom pipelex.pipeline.input_form import PipeInputFormDescriptor, PipeOutputFormDescriptor@@ -15,9 +16,10 @@ from pipelex.tools.typing.pydantic_utils import empty_list_factory_offrom pydantic import BaseModel, Field, field_validator, model_validatorfrom pipelex_api.bundle_resources import decode_bundle_resources-from pipelex_api.exception_handlers import problem_response_from_error_report+from pipelex_api.exception_handlers import problem_responsefrom pipelex_api.json_body import JsonBodyRoutefrom pipelex_api.method_tree_request import RequestMethod, select_tree_entry, written_method+from pipelex_api.middleware import request_id_offrom pipelex_api.openapi_responses import PROBLEM_403_RUN_POLICY, PROBLEM_404_METHOD_PACKAGEfrom pipelex_api.routes.pipelex.method_selection import select_request_methodfrom pipelex_api.routes.pipelex.pipeline import ApiRunner, bound_read_scope, get_request_user_id@@ -299,7 +301,7 @@ ValidationResponse = Annotated[Union[ValidReport, InvalidReport], Field(discrimiresponse_model=ValidationResponse,# On top of the composite router's shared 401/413/422/500: the policy 403s (the# `orchestration_mode` override gate it shares with `/start`, plus — for a `method_ref` —- # the custom-code sandbox gate and the structures refusal) and the `method_ref`+ # the custom-code sandbox gate) and the `method_ref`# package-not-found 404. Note what is deliberately NOT here: an *invalid bundle* is a# produced verdict on a 200, never a 4xx — and a selector-resolution failure is a non-2xx# problem+json, never an `is_valid: false` verdict.@@ -337,20 +339,21 @@ async def validate_mthds(request: Request, request_data: ValidateRequest) -> JSO- **Invalid verdict (200, `is_valid: false`):** the `InvalidReport` arm — `validation_errors[]`(the structured per-error diagnostics, built by pipelex's one shared builder, incl. onelocated `dry_run` item per pipe whose dry run failed) + `message`, with the structural artifacts absent. The runner- returns this as a value (`ErrorReport` with `validation_errors`) regardless of backend — the+ returns this as a value (a `BundleValidationFailure` with `validation_errors`) regardless of backend — thein-process arm from the bundle's `ValidateBundleError`, the dispatched arm recovered from theworker — so the route maps it to a 200 by matching validation diagnostics, never by catching an- exception. Returned `ErrorReport`s without validation diagnostics are backend/config/runtime- faults and keep the global RFC 7807 problem response path.+ exception. A returned failure without validation diagnostics is a backend, configuration or runtime+ fault, and its problem is answered as every raised failure's is.- **No verdict (non-2xx):** a malformed request body, an `mthds_sources` length mismatch, orboth/neither of `mthds_contents` / `method_ref` is a request-shape **422**; a forbidden`orchestration_mode` override is a **403**; a host-wiring programmer error or a genuineorchestrator fault is a **5xx**; auth is **401/403**. A `method_ref` **resolution failure**- is also a no-verdict condition — never an `is_valid: false`: a malformed reference or a- failed fetch is a **422**, no matching package in the repository a **404**, and the- custom-Python policy (the sandbox gate, the structures refusal) a **403**, each with the- originating error class as `error_type`. All are RFC 7807 `application/problem+json`- rendered by the global handler in `pipelex_api.exception_handlers` — routes never shape them.+ is also a no-verdict condition — never an `is_valid: false`: each answers the status its+ code declares, such as a **422** for a malformed reference, a **502** for a failed fetch, a+ **404** for no matching package in the repository and a **422** for the method's Python+ structure classes, and the custom-code sandbox gate a **403**. All are+ `application/problem+json` rendered by the global handlers in+ `pipelex_api.exception_handlers` — routes never shape them."""# Opt-in presentation formats (D-D): resolved once, threaded into both 200 arms. Empty by# default → no `rendered_*` field, response byte-identical to the no-`render` request.@@ -367,9 +370,9 @@ async def validate_mthds(request: Request, request_data: ValidateRequest) -> JSO# included, which reads no blob store of its own (`bound_read_scope`).read_scope = bound_read_scope(request, requested=request_data.read_scope)# Verdict-as-value: the runner resolves the orchestration mode and dispatches through the bundle- # validator registry, returning either a validation verdict or a classified fault report.- # Only `ErrorReport`s with validation diagnostics are invalid-bundle verdicts (→ 200- # InvalidReport); backend/config/runtime reports keep the global problem+json mapping.+ # validator registry, returning either a validation verdict or a failure carrying its problem.+ # Only failures with validation diagnostics are invalid-bundle verdicts (→ 200 InvalidReport);+ # a backend, configuration or runtime fault is answered as its problem, like a raised one.validated_method: RequestMethod | None = Noneif request_data.mthds_contents is not None:verdict = await ApiRunner(@@ -418,10 +421,10 @@ async def validate_mthds(request: Request, request_data: ValidateRequest) -> JSOgraph_pipe_code=tree_default_pipe_ref,method_dir=written.method_dir,)- if not isinstance(verdict, PipelexValidationReport):+ if isinstance(verdict, BundleValidationFailure):if verdict.validation_errors:return _invalid_report_response(verdict, requested_formats=requested_formats)- return problem_response_from_error_report(verdict, request=request)+ return problem_response(verdict.problem.model_copy(update={"request_id": request_id_of(request)}), error=None, request=request)report = verdict# The echo of a tree is its bundles' text, decoded strictly now that the valid verdict says they loaded.validated_contents = request_data.mthds_contents if validated_method is None else list(validated_method.tree.bundle_texts.values())@@ -459,20 +462,20 @@ async def validate_mthds(request: Request, request_data: ValidateRequest) -> JSOreturn JSONResponse(content=content)-def _invalid_report_response(error_report: ErrorReport, *, requested_formats: set[RenderFormat]) -> JSONResponse:+def _invalid_report_response(failure: BundleValidationFailure, *, requested_formats: set[RenderFormat]) -> JSONResponse:"""Render a produced "invalid" verdict as a 200 `InvalidReport` (D-A / D-C / D-D).The `validation_errors[]` come straight from pipelex's one shared builder via- `ValidateBundleError.to_error_report()`, so the hosted invalid arm carries the same typed+ `ValidateBundleError.validation_error_items()`, so the hosted invalid arm carries the same typeditems the agent CLI emits (including one located `dry_run` item per pipe whose dry run failed —the structured-info invariant, which the parse-level `blueprint_validation` residual makes total,guarantees this list is non-empty on every invalid verdict that reaches the wire,since the empty-`mthds_contents` edge case is a request-shape 422 via `min_length=1`).- `message` is the caller-facing summary the error report already carries.+ `message` is the failure's problem's `detail`, the sentence its code renders, which reads the same in every view."""invalid_report = InvalidReport(- validation_errors=error_report.validation_errors or [],- message=error_report.message,+ validation_errors=failure.validation_errors,+ message=failure.problem.detail,)# `exclude_none` drops each item's unset locators, so the wire items match the agent CLI's# `extract_validation_errors` byte-for-byte (it dumps items the same way) — the "one error item,diff --git a/api/pipelex_api/security.py b/api/pipelex_api/security.pyindex cad975fe1..9886431ea 100644--- a/api/pipelex_api/security.py+++ b/api/pipelex_api/security.py@@ -24,6 +24,7 @@ from pydantic import BaseModel, Fieldfrom pipelex_api.error_types import ErrorTypefrom pipelex_api.errors import raise_bad_request, raise_internal_server_error, raise_unauthenticatedfrom pipelex_api.exceptions import InvalidAuthModeError+from pipelex_api.problem_view import mark_operator_requestAUTH_MODE_ENV_VAR = "AUTH_MODE"@@ -238,10 +239,11 @@ async def verify_jwt(raise_unauthenticated("Invalid token", error_type=ErrorType.INVALID_TOKEN)-async def verify_api_key(credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)]) -> str:+async def verify_api_key(request: Request, credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)]) -> str:"""Validate static API key from Authorization header against API_KEY env var.- No user identity is available with static API keys — this is a shared developer key.+ No user identity is available with static API keys — this is a shared developer key. It is the operator's own+ credential, so a request presenting it reads the operator view of its failures (`pipelex_api.problem_view`)."""if credentials is None:# Missing, empty, or non-Bearer `Authorization` header. See the@@ -260,6 +262,7 @@ async def verify_api_key(credentials: Annotated[HTTPAuthorizationCredentials | Nlog.debug(CREDENTIALS_REFUSED_MESSAGE, fields={"auth_mode": AuthMode.API_KEY, "auth_refusal_reason": AuthRefusalReason.API_KEY_MISMATCH})raise_unauthenticated("Invalid authentication token", error_type=ErrorType.INVALID_TOKEN)+ mark_operator_request(request)return credentials.credentials@@ -278,6 +281,10 @@ async def no_auth(request: Request) -> None:external client could otherwise forge it when the API is reachabledirectly. With the flag enabled, you are responsible for ensuring yourproxy strips `X-User-Id` from inbound requests before adding its own.++ With the flag set, the only party that reaches this server is that proxy, the deployment's own hop, so a request it+ forwards reads the operator view of its failures (`pipelex_api.problem_view`), and the proxy owes its own callers+ their caller view. Without it, a request reads the caller view: nothing authenticated who sent it."""if get_optional_env("TRUST_FORWARDED_IDENTITY_HEADERS") != "true":return@@ -306,6 +313,7 @@ async def no_auth(request: Request) -> None:raise_bad_request("Forwarded X-User-Id must be a single path-safe segment", error_type=ErrorType.BAD_REQUEST)_set_request_user(request, user_id=user_id)+ mark_operator_request(request)async def get_request_user(request: Request) -> RequestUser | None:diff --git a/api/tests/unit/test_bundle_resources_routes.py b/api/tests/unit/test_bundle_resources_routes.pyindex 429f6236c..48dde6b0a 100644--- a/api/tests/unit/test_bundle_resources_routes.py+++ b/api/tests/unit/test_bundle_resources_routes.py@@ -20,9 +20,10 @@ from pathlib import Pathfrom typing import Anyimport pytest-from fastapi import FastAPI+from fastapi import Depends, FastAPIfrom fastapi.testclient import TestClientfrom mthds.method_tree.digest import digest_of_contents, sha256_hex, tree_files_from_contents, tree_listing+from mthds.protocol.problem.registry import CoreCodefrom pipelex.cogt.content_generation.assignment_models import RenderDocumentAssignmentfrom pipelex.cogt.doc_gen.doc_gen_setting import DocGenSettingfrom pipelex.core.method_trees.exceptions import MethodFileUnavailableError@@ -36,6 +37,7 @@ from pytest_mock import MockerFixturefrom pipelex_api.api_config import ApiConfigfrom pipelex_api.exception_handlers import register_exception_handlers+from pipelex_api.problem_view import mark_operator_requestfrom pipelex_api.routes import router as api_routerfrom tests.unit._constants import STUB_METHOD_ADDRESS@@ -90,9 +92,10 @@ def _b64(data: bytes) -> str:return base64.b64encode(data).decode("ascii")-def _build_client() -> TestClient:+def _build_client(*, as_operator: bool = False) -> TestClient:+ """The routes behind the production handlers; `as_operator` marks each request as the operator's, who reads `diagnostics`."""app = FastAPI()- app.include_router(api_router, prefix="/v1")+ app.include_router(api_router, prefix="/v1", dependencies=[Depends(mark_operator_request)] if as_operator else [])register_exception_handlers(app)return TestClient(app)@@ -195,6 +198,7 @@ def _contents_body(*, route: str, resources: dict[str, str], mthds: str = _INVOIdef _assert_problem(response: Any, *, status: int, error_type: str) -> str:+ """An API-authored refusal: its `error_type`, and the `detail` the API wrote from what it checked."""assert response.status_code == status, response.textassert response.headers["content-type"].startswith("application/problem+json")problem = response.json()@@ -204,6 +208,31 @@ def _assert_problem(response: Any, *, status: int, error_type: str) -> str:return detail+def _assert_coded_problem(response: Any, *, code: CoreCode, params: dict[str, Any]) -> dict[str, Any]:+ """A runtime refusal: a 422 problem under its code, with the parameters its sentences are rendered from."""+ assert response.status_code == 422, response.text+ assert response.headers["content-type"].startswith("application/problem+json")+ problem: dict[str, Any] = response.json()+ assert problem["code"] == code, response.text+ assert problem["status"] == 422+ assert problem["domain"] == "input"+ # A deterministic refusal of what the caller sent: the same request fails again.+ assert problem["retry"] == "no"+ assert problem.get("params") == params+ assert "is_valid" not in problem+ return problem+++def _assert_the_verdict_names_the_missing_file(*, verdict: dict[str, Any], file: str, reason: str) -> None:+ """An invalid verdict whose one item is a file of the step missing from the method's tree, in the code's sentence."""+ assert verdict["is_valid"] is False+ (item,) = verdict["validation_errors"]+ assert item["category"] == "pipe_validation"+ assert item["pipe_code"] == "print_invoice"+ # A verdict is the caller's: its item reads `method.resource_missing`'s sentence, never the runtime's own message.+ assert item["message"] == f"The file reference '{file}' resolves to no file of the method's tree (reason: {reason})."++class TestBundleResourcesRoutes:def test_validate_hands_the_step_the_submitted_template_file(self, mocker: MockerFixture) -> None:"""The validation's dry run reads the template from the submitted bytes, keyed by the path the step names."""@@ -226,21 +255,19 @@ class TestBundleResourcesRoutes:response = _build_client().post("/v1/validate", json={"mthds_contents": [_INVOICE_MTHDS]})assert response.status_code == 200, response.text- body = response.json()- assert body["is_valid"] is False- assert "which was not supplied with its bundle" in str(body["validation_errors"])+ _assert_the_verdict_names_the_missing_file(verdict=response.json(), file=_TEMPLATE_PATH, reason="not_in_tree")@pytest.mark.parametrize("route", ["/v1/validate", "/v1/execute"])def test_a_file_no_step_names_is_refused_on_every_route_that_loads_contents(self, mocker: MockerFixture, route: str) -> None:_stub_the_document_engine(mocker)body = _contents_body(route=route, resources={_TEMPLATE_PATH: _b64(_TEMPLATE_BYTES), "templates/logo.png": _b64(b"png")})- response = _build_client().post(route, json=body)- detail = _assert_problem(response, status=422, error_type="BundleResourceNotNamedError")+ response = _build_client(as_operator=True).post(route, json=body)+ problem = _assert_coded_problem(response, code=CoreCode.REQUEST_INVALID, params={"field": "resources"})- assert "'templates/logo.png'" in detail- # A deterministic refusal of what the caller sent, as InvalidResourcePath is: the same request fails again.- assert response.json()["retryable"] is False+ # The operator's diagnostics name the file no step reads.+ assert problem["diagnostics"]["error_class"] == "BundleResourceNotNamedError"+ assert "'templates/logo.png'" in problem["diagnostics"]["message"]@pytest.mark.parametrize(("path", "reason"),@@ -296,13 +323,15 @@ 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=expected_error_type)+ response = _build_client().post(route, json=body)- assert "method_ref" in detail+ # The run route refuses it in its request model, as the runtime's `request.invalid` naming the field; the crate+ # routes refuse it themselves, with the API-authored `ValidationError`.+ if route == "/v1/execute":+ _assert_coded_problem(response, code=CoreCode.REQUEST_INVALID, params={"field": "resources"})+ else:+ assert "method_ref" in _assert_problem(response, status=422, error_type="ValidationError")def test_a_source_label_naming_a_file_on_the_runner_never_reads_beside_it(self, mocker: MockerFixture, tmp_path: Path) -> None:"""A caller's absolute source naming a real bundle file, with the template file beside it, reaches nothing on the runner's disk."""@@ -316,9 +345,7 @@ class TestBundleResourcesRoutes:response = _build_client().post("/v1/validate", json=body)assert response.status_code == 200, response.text- verdict = response.json()- assert verdict["is_valid"] is False- assert "which was not supplied with its bundle" in str(verdict["validation_errors"])+ _assert_the_verdict_names_the_missing_file(verdict=response.json(), file=_TEMPLATE_PATH, reason="not_in_tree")assert read_templates == []@pytest.mark.parametrize("route", ["/v1/pipe-io", "/v1/resolve", "/v1/codegen"])@@ -341,8 +368,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="PipelexRequestError")- assert response.json()["code"] == "request.invalid"+ problem = _assert_coded_problem(response, code=CoreCode.REQUEST_INVALID, params={"field": "resources"})+ assert problem["detail"] == "The request's field 'resources' does not match the route's schema."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."""@@ -476,9 +503,10 @@ class TestBundleResourcesRoutes:assert response.status_code == 200, response.textverdict = response.json()- assert verdict["is_valid"] is sends_the_logo, response.text- if not sends_the_logo:- assert "logo.png" in json.dumps(verdict["validation_errors"])+ if sends_the_logo:+ assert verdict["is_valid"] is True, response.text+ else:+ _assert_the_verdict_names_the_missing_file(verdict=verdict, file="logo.png", reason="not_in_tree")def test_two_bundles_of_a_method_each_read_the_file_beside_them(self, mocker: MockerFixture) -> None:"""A step names its file from its bundle's own tree path, so two bundles shipping a template each under one relative path both run."""diff --git a/api/tests/unit/test_bundle_structures_refusal.py b/api/tests/unit/test_bundle_structures_refusal.pyindex b5090a843..029ac2616 100644--- a/api/tests/unit/test_bundle_structures_refusal.py+++ b/api/tests/unit/test_bundle_structures_refusal.py@@ -12,8 +12,8 @@ from pathlib import Pathimport pytestfrom fastapi import FastAPIfrom fastapi.testclient import TestClient-from pipelex.base_exceptions import DisclosureModefrom pipelex.config import get_config+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.pipe_run.delivery_assignment import DeliveryAssignmentfrom pipelex.pipe_run.pipe_job import PipeJobfrom pipelex.plugins.orchestrator_registry import OrchestratorRegistry@@ -107,7 +107,7 @@ def _build_client(mocker: MockerFixture, *, orchestrator: _RecordingOrchestratormocker.patch(f"{_PIPELINE_NS}.get_orchestrator_registry", return_value=OrchestratorRegistry({"direct": orchestrator}))app = FastAPI()app.include_router(api_router, prefix="/v1")- register_exception_handlers(app, disclosure_mode=DisclosureMode.STRICT)+ register_exception_handlers(app)return TestClient(app)@@ -122,14 +122,16 @@ class TestBundleStructuresRefusal:files = {"main.mthds": VALID_MTHDS, "structures/invoice.py": _structures_py(sentinel=sentinel)}response = client.post(path, json={"files": files, "inputs": {"text": "hello"}})- assert response.status_code == 403, response.text+ # The method's own structure classes are its author's to change: the code's 422, in the caller's view.+ assert response.status_code == 422, response.textassert response.headers["content-type"].startswith("application/problem+json")body = response.json()- assert body["error_type"] == "MethodStructuresRefusedError"- # Caller-facing even under STRICT disclosure: it names the file and the class, and gives the route.- assert "structures/invoice.py" in body["detail"]- assert "Invoice" in body["detail"]- assert "MTHDS concepts" in body["detail"]+ assert body["code"] == PipelexErrorCode.DEPLOYMENT_PYTHON_STRUCTURES_REFUSED+ assert body["domain"] == "method"+ assert body["next_step"]["kind"] == "change_method"+ # The caller reads which file declares a structure class, from the code's parameters.+ assert body.get("params") == {"files": ["structures/invoice.py"]}+ assert "diagnostics" not in bodyassert not sentinel.exists(), "the structure module was imported"assert orchestrator.dispatches == []diff --git a/api/tests/unit/test_data.py b/api/tests/unit/test_data.pynew file mode 100644index 000000000..cac74ab15--- /dev/null+++ b/api/tests/unit/test_data.py@@ -0,0 +1,85 @@+"""Test data for the server's problem documents: the failures they are built from and the identities that pick their view."""++from typing import Any, ClassVar++from mthds.protocol.problem.registry import CoreCode+from pipelex.cogt.exceptions import InferenceErrorCategory, LLMCompletionError+from pipelex.cogt.inference.error_classification import ProviderErrorMetadata+from pipelex.cogt.inference.provider_name import ProviderName+from pipelex.errors.error_codes import ErrorCode+from pipelex.errors.registry.pipelex_codes import PipelexErrorCode+++class ProblemTestData:+ """A provider's rate limit, the failure whose problem carries the most members, and the synthetic credentials of each identity."""++ RATE_LIMIT_MESSAGE = "OpenAI returned 429 (rate_limit_exceeded)"+ RATE_LIMIT_MODEL = "gpt-4o-mini"+ RATE_LIMIT_BACKEND = "openai"+ RATE_LIMIT_PROVIDER_REQUEST_ID = "req_provider_abc"+ RATE_LIMIT_RETRY_AFTER_SECONDS = 12.0+ RATE_LIMIT_DETAIL = "The provider 'openai' is rate limiting this deployment's calls to the model 'gpt-4o-mini'."++ # Synthetic credentials, valid only against the environment a test patches in.+ SYNTHETIC_API_KEY = "test-api-key-problem-views-only"+ SYNTHETIC_JWT_SECRET = "test-jwt-secret-problem-views-only"+ SYNTHETIC_CALLBACK_SECRET = "test-callback-secret-problem-views-only"+ FORWARDED_USER_ID = "22222222-2222-4222-2222-222222222222"+ JWT_USER_ID = "33333333-3333-4333-3333-333333333333"+ CALLBACK_URL = "https://example.com/done"++ # A problem whose code no registry of this server holds, as a newer worker or a stored record carries it, built in+ # the operator's view: its step and its diagnostics name a file of the host that a caller must never read.+ PRIVATE_HOST_FILE = "/srv/pipelex/private/settings.toml"+ UNKNOWN_OPERATOR_PROBLEM: ClassVar[dict[str, Any]] = {+ "type": "https://docs.pipelex.com/errors/pipelex.config.future_setting_missing",+ "title": "A setting the runtime needs is missing",+ "detail": "A setting the runtime needs is missing.",+ "code": "pipelex.config.future_setting_missing",+ "domain": "operator",+ "retry": "no",+ "next_step": {"kind": "fix_configuration", "detail": "Set the setting in '/srv/pipelex/private/settings.toml', then restart the runtime."},+ "diagnostics": {"error_class": "FutureSettingError", "message": "no setting in /srv/pipelex/private/settings.toml"},+ }++ # Each code with the status its registry entry declares, which the response must carry.+ CODE_STATUSES: ClassVar[list[tuple[ErrorCode, int]]] = [+ (CoreCode.METHOD_SYNTAX, 422),+ (CoreCode.METHOD_NOT_FOUND, 404),+ (CoreCode.RUN_FAILED, 409),+ (PipelexErrorCode.RUN_ALREADY_EXISTS, 409),+ (CoreCode.PROVIDER_RATE_LIMITED, 429),+ (PipelexErrorCode.CONFIG_INVALID, 500),+ (CoreCode.RUNTIME_UNSUPPORTED, 501),+ (CoreCode.PROVIDER_UNAVAILABLE, 502),+ (CoreCode.RUNTIME_UNAVAILABLE, 503),+ (PipelexErrorCode.DEPLOYMENT_PYTHON_STRUCTURES_REFUSED, 422),+ ]++ # A retry delay by case: (code, the delay the error knows, the status, the `Retry-After` header, the body's `retry_after`).+ RETRY_CASES: ClassVar[dict[str, tuple[ErrorCode, float | None, int, str | None, float | None]]] = {+ "finite": (CoreCode.PROVIDER_RATE_LIMITED, 12.4, 429, "13", 12.4),+ "whole": (CoreCode.PROVIDER_RATE_LIMITED, 12.0, 429, "12", 12.0),+ "infinite": (CoreCode.PROVIDER_RATE_LIMITED, float("inf"), 429, None, None),+ "nan": (CoreCode.PROVIDER_RATE_LIMITED, float("nan"), 429, None, None),+ "negative": (CoreCode.PROVIDER_RATE_LIMITED, -5.0, 429, None, None),+ "absent": (CoreCode.PROVIDER_RATE_LIMITED, None, 429, None, None),+ "non_429": (CoreCode.PROVIDER_UNAVAILABLE, 30.0, 502, None, 30.0),+ }+++def rate_limited_failure() -> LLMCompletionError:+ """A provider's 429 as the inference layer raises it, attributed to the backend and the model it addressed."""+ failure = LLMCompletionError(+ ProblemTestData.RATE_LIMIT_MESSAGE,+ error_category=InferenceErrorCategory.TRANSIENT,+ provider_metadata=ProviderErrorMetadata(+ provider=ProviderName.OPENAI,+ sdk_exception_type="RateLimitError",+ status_code=429,+ retry_after_seconds=ProblemTestData.RATE_LIMIT_RETRY_AFTER_SECONDS,+ request_id=ProblemTestData.RATE_LIMIT_PROVIDER_REQUEST_ID,+ ),+ ).with_error_code(CoreCode.PROVIDER_RATE_LIMITED)+ failure.fill_model_and_provider(ProblemTestData.RATE_LIMIT_MODEL, backend_name=ProblemTestData.RATE_LIMIT_BACKEND)+ return failurediff --git a/api/tests/unit/test_disclosure.py b/api/tests/unit/test_disclosure.pydeleted file mode 100644index cdc79a492..000000000--- a/api/tests/unit/test_disclosure.py+++ /dev/null@@ -1,39 +0,0 @@-"""Unit tests for ERROR_DISCLOSURE env var resolution."""--import pytest-from pipelex.base_exceptions import DisclosureMode--from pipelex_api.disclosure import ERROR_DISCLOSURE_ENV_VAR, resolve_disclosure_mode-from pipelex_api.exceptions import InvalidErrorDisclosureError---class TestDisclosure:- def test_defaults_to_verbose_when_unset(self, monkeypatch: pytest.MonkeyPatch):- monkeypatch.delenv(ERROR_DISCLOSURE_ENV_VAR, raising=False)- assert resolve_disclosure_mode() is DisclosureMode.VERBOSE-- @pytest.mark.parametrize("raw", ["", " ", "\t"])- def test_blank_value_defaults_to_verbose(self, monkeypatch: pytest.MonkeyPatch, raw: str):- # An empty or whitespace-only value is treated the same as unset — never- # rejected as invalid.- monkeypatch.setenv(ERROR_DISCLOSURE_ENV_VAR, raw)- assert resolve_disclosure_mode() is DisclosureMode.VERBOSE-- @pytest.mark.parametrize(- ("raw", "expected"),- [- ("verbose", DisclosureMode.VERBOSE),- ("strict", DisclosureMode.STRICT),- ("STRICT", DisclosureMode.STRICT),- (" Verbose ", DisclosureMode.VERBOSE),- ],- )- def test_resolves_valid_values(self, monkeypatch: pytest.MonkeyPatch, raw: str, expected: DisclosureMode):- monkeypatch.setenv(ERROR_DISCLOSURE_ENV_VAR, raw)- assert resolve_disclosure_mode() is expected-- @pytest.mark.parametrize("raw", ["loud", "quiet", "true", "0", "verbos"])- def test_rejects_unknown_value(self, monkeypatch: pytest.MonkeyPatch, raw: str):- monkeypatch.setenv(ERROR_DISCLOSURE_ENV_VAR, raw)- with pytest.raises(InvalidErrorDisclosureError):- resolve_disclosure_mode()diff --git a/api/tests/unit/test_error_code_gate.py b/api/tests/unit/test_error_code_gate.pyindex fc079e383..3a5b76b6f 100644--- a/api/tests/unit/test_error_code_gate.py+++ b/api/tests/unit/test_error_code_gate.py@@ -24,7 +24,7 @@ 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.+# What a code decides, which a class no longer declares: the problem document reads all four from the code._ATTRIBUTES_THE_CODE_DECIDES: tuple[str, ...] = ("error_domain", "retryable", "_declared_title", "_declared_type_uri")@@ -58,7 +58,7 @@ 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 {"ApiBootConfigError", "InvalidAuthModeError"} <= set(classes)assert _source_files()def test_every_runner_error_class_declares_its_code(self) -> None:diff --git a/api/tests/unit/test_error_log_records.py b/api/tests/unit/test_error_log_records.pyindex 53cb87071..a67ba6514 100644--- a/api/tests/unit/test_error_log_records.py+++ b/api/tests/unit/test_error_log_records.py@@ -39,6 +39,16 @@ async def pipelex_failure_route() -> None:raise PipelexConfigError(msg)+# The text of an exception that is not a Pipelex error, which may name anything on the host: the operator's alone.+_FOREIGN_FAILURE_TEXT = "the cache index at /srv/pipelex/private/index.db is corrupt"+++@_router.get("/foreign-failure")+async def foreign_failure_route() -> None:+ # A bug of ours, raised by no Pipelex error: the catch-all handler answers it as `runtime.unexpected`.+ raise RuntimeError(_FOREIGN_FAILURE_TEXT)++@_router.get("/caller-mistake")async def caller_mistake_route(detail: str) -> None:# A caller-input 422 whose `detail` is exactly what the caller sent — the `warning`-level@@ -46,12 +56,16 @@ async def caller_mistake_route(detail: str) -> None:raise_validation_error(detail, ErrorType.VALIDATION_ERROR)-def _build_client() -> TestClient:- """Wire a throwaway app with the production handlers and the request-id middleware."""+def _build_client(*, raise_server_exceptions: bool = True) -> TestClient:+ """Wire a throwaway app with the production handlers and the request-id middleware.++ `raise_server_exceptions` must be `False` for a route whose exception reaches the catch-all handler, which+ Starlette's `ServerErrorMiddleware` runs and then re-raises.+ """app = FastAPI()register_exception_handlers(app)app.include_router(_router)- return TestClient(RequestIdMiddleware(app))+ return TestClient(RequestIdMiddleware(app), raise_server_exceptions=raise_server_exceptions)# The message every error line carries, whichever handler produced it: the key the error stream is selected by.@@ -105,6 +119,25 @@ class TestErrorLogRecords:assert getattr(record, "url.path", None) == "/pipelex-failure"assert getattr(record, "error.type", None) == "PipelexConfigError"+ def test_an_unexpected_failure_keeps_its_class_and_text_for_the_operator_alone(self, caplog: pytest.LogCaptureFixture):+ # The catch-all answers the caller the code's sentences, and the operator's record keeps what escaped: its class+ # as `error.type`, and its text with its traceback under `exception`, never in a field a caller-supplied value+ # could share.+ with caplog.at_level(logging.WARNING):+ response = _build_client(raise_server_exceptions=False).get("/foreign-failure")+ assert response.status_code == 500+ assert response.json()["code"] == "runtime.unexpected"+ assert _FOREIGN_FAILURE_TEXT not in response.text+ assert "RuntimeError" not in response.text+ record = _api_error_record(caplog)+ assert record.levelno == logging.ERROR+ assert getattr(record, "error.code", None) == "runtime.unexpected"+ assert getattr(record, "error.type", None) == "RuntimeError"+ assert record.exc_info is not None+ assert isinstance(record.exc_info[1], RuntimeError)+ payload = _rendered_json(record)+ assert f"RuntimeError: {_FOREIGN_FAILURE_TEXT}" in payload["exception"]+def test_a_caller_mistake_records_a_warning_carrying_the_same_identifiers(self, caplog: pytest.LogCaptureFixture):# A 4xx is a caller mistake, so it lands at `warning` — but it carries the same message and# the same two identifiers, so one query over the message returns the whole error stream of a request.diff --git a/api/tests/unit/test_exception_handlers.py b/api/tests/unit/test_exception_handlers.pyindex 2bacdb8ad..6db20d4b6 100644--- a/api/tests/unit/test_exception_handlers.py+++ b/api/tests/unit/test_exception_handlers.py@@ -3,9 +3,12 @@These tests register the production handlers on a throwaway FastAPI app whoseroutes raise straight through — `ApiError`, `RequestValidationError`,`PipelexError`, a bare orchestrator-SDK transport error (handled via a synthetic-plugin-contributed mapper, proving the F3 seam without importing any orchestrator-SDK), and uncaught `Exception` each end up at their respective handler exactly-the way the real app routes them.+plugin-contributed mapper, proving the plugin seam without importing any+orchestrator SDK), and uncaught `Exception` each end up at their respective+handler exactly the way the real app routes them. A `PipelexError` answers its+problem with the status its code declares, in the view of whoever made the+request: `as_operator` stands in for the authentication that marks a request as+the operator's, which `test_problem_views.py` drives through the real dependencies."""import asyncio@@ -14,21 +17,17 @@ import refrom typing import Any, castimport pytest-from fastapi import APIRouter, FastAPI, Request+from fastapi import APIRouter, Depends, FastAPI, Requestfrom fastapi.testclient import TestClientfrom mthds.protocol.problem.registry import CoreCode-from pipelex.base_exceptions import (- INTERNAL_ERROR_PLACEHOLDER,- DisclosureMode,- ErrorReport,- PipelexConfigError,- PipelexError,-)+from pipelex.base_exceptions import PipelexConfigError, PipelexError, ProblemFactsfrom pipelex.cogt.exceptions import InferenceErrorCategory, LLMCompletionError-from pipelex.cogt.inference.error_classification import ProviderErrorMetadata, UserAction, UserActionKind+from pipelex.cogt.inference.error_classification import ProviderErrorMetadatafrom pipelex.cogt.inference.provider_name import ProviderNamefrom pipelex.config import get_config+from pipelex.errors.error_code_declaration import ErrorCodeSetfrom pipelex.errors.error_codes import ErrorCode, error_code_spec+from pipelex.errors.problem import ProblemView, make_problemfrom pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.methods.exceptions import MethodPackageSymlinkErrorfrom pipelex.pipe_run.exceptions import AsyncExecutionNotEnabledError@@ -43,16 +42,24 @@ from typing_extensions import overridefrom pipelex_api.error_types import ErrorTypefrom pipelex_api.errors import raise_internal_server_error, raise_validation_error-from pipelex_api.exception_handlers import register_exception_handlers+from pipelex_api.exception_handlers import problem_response, register_exception_handlersfrom pipelex_api.middleware import REQUEST_ID_HEADER, RequestIdMiddlewarefrom pipelex_api.problem_document import PROBLEM_JSON_MEDIA_TYPE+from pipelex_api.problem_view import mark_operator_requestfrom pipelex_api.routes.pipelex.pipeline import router as pipeline_routerfrom pipelex_api.routes.pipelex.tools import router as tools_routerfrom pipelex_api.security import RequestUser+from tests.unit.test_data import ProblemTestData, rate_limited_failure# Crockford Base32, 26 chars — the ULID alphabet RequestIdMiddleware mints._ULID_RE = re.compile(r"\A[0-9A-HJKMNP-TV-Z]{26}\Z")+_GATEWAY_CONFIG_MESSAGE = "the gateway config is missing"+_UNEXPECTED_MESSAGE = "something nobody anticipated"+_TRANSPORT_MESSAGE = "orchestrator cluster unreachable"+# The members of the retired error report, which no problem of a `PipelexError` carries any more.+_RETIRED_REPORT_MEMBERS = ("error_type", "error_domain", "retryable", "instance", "error_category", "user_action", "provider_metadata")+def _emitted_fields(log_spy: Any, *, as_error: bool) -> dict[str, Any]:"""The record attributes the handler shipped on its one `api_error` call.@@ -67,92 +74,80 @@ 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)+def _bare_request(path: str) -> Request:+ """A request no authentication marked, as `problem_response` receives one from a route."""+ return Request({"type": "http", "method": "GET", "path": path, "headers": [], "query_string": b""})++class _MethodSyntaxError(PipelexError):+ """A `method.syntax` failure, the method's own to fix, holding the finding its code's sentence names."""-class _SimulatedLLMError(PipelexError):- """A `PipelexError` whose report mimics a provider rate-limit (429) failure."""+ error_code = CoreCode.METHOD_SYNTAX- error_code = CoreCode.PROVIDER_RATE_LIMITED+ def __init__(self, message: str, *, finding: str) -> None:+ super().__init__(message)+ self.finding = finding@override- def to_error_report(self) -> ErrorReport:- return _coded_report(- code=CoreCode.PROVIDER_RATE_LIMITED,- error_type="LLMCompletionError",- message="OpenAI returned 429 (rate_limit_exceeded)",- 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."""+ def problem_params(self) -> dict[str, Any]:+ return {"finding": self.finding}+++class _CorruptFactsError(PipelexError):+ """A `PipelexError` whose problem cannot be built — the handler-of-handlers case."""error_code = CoreCode.RUNTIME_UNEXPECTED@override- def to_error_report(self) -> ErrorReport:- msg = "to_error_report is deliberately broken"+ def problem_facts(self) -> ProblemFacts:+ msg = "problem_facts is deliberately broken"raise RuntimeError(msg)-class _CallerFacingInputError(PipelexError):- """A `method.syntax` error, which the caller fixes, whose message is genuine caller-facing copy.+class _CraftedRetryError(PipelexError):+ """A provider failure knowing a retry delay, selected by case — exercises the `Retry-After` guards."""++ error_code = ErrorCodeSet(default=CoreCode.PROVIDER_RATE_LIMITED, others=(CoreCode.PROVIDER_UNAVAILABLE,))- `_authors_caller_facing_message` makes STRICT disclosure keep the message- verbatim — the projection pipelex applies to a `.mthds` syntax error.- """+ def __init__(self, *, retry_after: float | None) -> None:+ super().__init__("crafted retry-after scenario")+ self.retry_after = retry_after- error_code = CoreCode.METHOD_SYNTAX- _authors_caller_facing_message = True+ @override+ def problem_facts(self) -> ProblemFacts:+ return ProblemFacts(retry_after=self.retry_after)class _SyntheticTransportError(Exception):"""A bare orchestrator-SDK-style transport error — NOT a `PipelexError`, no `temporalio`.Stands in for the kind of exception an orchestrator plugin contributes a mapper for (e.g.- `temporalio.TemporalError`), so the F3 seam — plugin maps a bare transport exception to a- structured `ErrorReport`, the API renders it — is exercised without importing any orchestrator SDK.+ `temporalio.TemporalError`), so the plugin seam — the plugin maps a bare transport exception+ to a `PipelexError`, the API renders its problem — is exercised without importing any SDK."""+class _SyntheticTransportFault(PipelexError):+ """The `PipelexError` the synthetic plugin's mapper stands in for an unreachable cluster."""++ error_code = CoreCode.RUNTIME_UNAVAILABLE++class _SyntheticOrchestratorError(PipelexError):- """An orchestrator failure that IS a `PipelexError` (carries its own `ErrorReport`).+ """An orchestrator failure that IS a `PipelexError`, such as the Temporal plugin's `WorkflowExecutionError`.- Stands in for e.g. the Temporal plugin's `WorkflowExecutionError`: Starlette's MRO walk resolves- it to `handle_pipelex_error`, never to the transport mapper handler registered for a bare- transport exception.+ Starlette's MRO walk resolves it to `handle_pipelex_error`, never to the transport mapper+ handler registered for a bare 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 for an- unreachable cluster — `runtime.unavailable`, a retryable `transient` failure.- """- return _coded_report(- code=CoreCode.RUNTIME_UNAVAILABLE,- error_type="SyntheticTransportError",- message=str(exc),- classification={"error_category": "transient"},- )+def _synthetic_transport_to_pipelex_error(exc: Exception) -> PipelexError:+ """The mapper an orchestrator plugin would contribute: an unreachable cluster is `runtime.unavailable`, a retryable failure."""+ fault = _SyntheticTransportFault(str(exc)).with_params(dependency="orchestrator")+ fault.__cause__ = exc+ return faultdef _synthetic_http_error_mappers() -> dict[type[Exception], HttpErrorMapperFn]:@@ -167,54 +162,10 @@ def _synthetic_http_error_mappers() -> dict[type[Exception], HttpErrorMapperFn]:# `group=None` is what a built-in carries: the entry-point group is how an *external* plugin# declares its layer, and a built-in arrives under none — it is filed by layer in-tree instead.registrar.begin_plugin(name="synthetic-transport-plugin", origin=PluginOrigin.BUILTIN, targets_api=PLUGIN_API_VERSION, group=None)- registrar.add_http_error_mapper(exc_type_provider=lambda: _SyntheticTransportError, to_error_report=_synthetic_transport_to_report)+ registrar.add_http_error_mapper(exc_type_provider=lambda: _SyntheticTransportError, to_pipelex_error=_synthetic_transport_to_pipelex_error)return registrar.get_http_error_mappers()-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 _coded_report(- code=CoreCode.PROVIDER_RATE_LIMITED if status_code == 429 else CoreCode.PROVIDER_UNAVAILABLE,- error_type="LLMCompletionError",- message="provider error",- classification={- "error_category": "transient",- "provider_metadata": ProviderErrorMetadata(- provider=ProviderName.OPENAI,- sdk_exception_type="RateLimitError",- status_code=status_code,- retry_after_seconds=retry_after_seconds,- ),- },- )---# Reports exercising every branch of `_retry_after_header`: a finite hint, the-# two non-finite values a provider could emit, a negative value, and a hint-# carried on a non-429 status (where `Retry-After` must not be emitted).-_RETRY_REPORTS: dict[str, ErrorReport] = {- "finite": _report_with_retry(status_code=429, retry_after_seconds=12.4),- "infinite": _report_with_retry(status_code=429, retry_after_seconds=float("inf")),- "nan": _report_with_retry(status_code=429, retry_after_seconds=float("nan")),- "negative": _report_with_retry(status_code=429, retry_after_seconds=-5.0),- "non_429": _report_with_retry(status_code=503, retry_after_seconds=30.0),-}---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]-- @override- def to_error_report(self) -> ErrorReport:- return self._report--# Route handlers are deliberately not underscore-prefixed: a private,# decorator-only function reads as unused to the type checker._router = APIRouter()@@ -222,8 +173,7 @@ _router = APIRouter()@_router.get("/config-error")async def config_error_route() -> None:- msg = "the gateway config is missing"- raise PipelexConfigError(msg)+ raise PipelexConfigError(_GATEWAY_CONFIG_MESSAGE)@_router.get("/env-error")@@ -235,70 +185,64 @@ async def env_error_route() -> None:@_router.get("/input-error")async def input_error_route() -> None:msg = "your .mthds file has a syntax error on line 4"- raise _CallerFacingInputError(msg)+ raise _MethodSyntaxError(msg, finding="TOML syntax error at line 4")@_router.get("/llm-error")async def llm_error_route() -> None:- msg = "simulated provider rate limit"- raise _SimulatedLLMError(msg)+ raise rate_limited_failure()@_router.get("/corrupt-error")async def corrupt_error_route() -> None:- msg = "its report builder is broken"- raise _CorruptReportError(msg)+ msg = "its problem builder is broken"+ raise _CorruptFactsError(msg)@_router.get("/orchestrator-pipelex-error")async def orchestrator_pipelex_error_route() -> None:msg = "the workflow failed"- raise _SyntheticOrchestratorError(msg)+ raise _SyntheticOrchestratorError(msg).with_params(pipeline_run_id="run-7", run_status="FAILED")@_router.get("/async-execution-not-enabled")async def async_execution_not_enabled_route() -> None:- # Pipelex raises this when an async dispatch site is reached on a- # deployment without an async execution backend enabled. The API maps it- # to 501 Not Implemented (see ``_ERROR_TYPE_STATUS_OVERRIDES``).+ # Pipelex raises this when an async dispatch site is reached on a deployment without an async+ # execution backend enabled; its code, `runtime.unsupported`, declares 501.msg = "Asynchronous pipeline execution is not enabled on this deployment."raise AsyncExecutionNotEnabledError(msg)@_router.get("/pipeline-run-id-conflict")async def pipeline_run_id_conflict_route() -> None:- # Pipelex raises this from ``add_new_pipeline`` when a submission reuses a- # ``pipeline_run_id`` that is still registered (a genuinely concurrent- # duplicate — completed/failed runs free their entry on the way out). The- # API maps it to 409 Conflict (see ``_ERROR_TYPE_STATUS_OVERRIDES``).+ # Pipelex raises this from ``add_new_pipeline`` when a submission reuses a ``pipeline_run_id``+ # that is still registered; its code, `pipelex.run.already_exists`, declares 409.msg = "Pipeline some-run-id already exists"raise PipelineManagerAlreadyExistsError(msg)@_router.get("/method-package-symlink")async def method_package_symlink_route() -> None:- # Pipelex raises this from ``ensure_package_within_bounds`` when a package fetched- # by ``method_ref`` carries a symlink. The API maps it to 422 (see- # ``_ERROR_TYPE_STATUS_OVERRIDES``).+ # Pipelex raises this from ``ensure_package_within_bounds`` when a package fetched by+ # ``method_ref`` carries a symlink; its code, `method.package_invalid`, declares 422.msg = "Method package 'github.com/acme/linked' contains a symlink ('vendored') — fetched packages must not contain symlinks."raise MethodPackageSymlinkError(msg)@_router.get("/synthetic-transport-error")async def synthetic_transport_error_route() -> None:- msg = "orchestrator cluster unreachable"- raise _SyntheticTransportError(msg)+ raise _SyntheticTransportError(_TRANSPORT_MESSAGE)@_router.get("/unexpected-error")async def unexpected_error_route() -> None:- msg = "something nobody anticipated"- raise RuntimeError(msg)+ raise RuntimeError(_UNEXPECTED_MESSAGE)-@_router.get("/crafted-retry/{report_key}")-async def crafted_retry_route(report_key: str) -> None:- raise _CraftedRetryError(report_key)+@_router.get("/crafted-retry/{case}")+async def crafted_retry_route(case: str) -> None:+ code, retry_after, _, _, _ = ProblemTestData.RETRY_CASES[case]+ raise _CraftedRetryError(retry_after=retry_after).with_error_code(code)@_router.get("/api-input-error")@@ -381,8 +325,7 @@ def _bind_test_run_state(request: Request) -> None:@_router.get("/authenticated-config-error")async def authenticated_config_error_route(request: Request) -> None:_bind_test_user(request)- msg = "the gateway config is missing"- raise PipelexConfigError(msg)+ raise PipelexConfigError(_GATEWAY_CONFIG_MESSAGE)@_router.get("/authenticated-api-input-error")@@ -394,18 +337,16 @@ async def authenticated_api_input_error_route(request: Request) -> None:@_router.get("/authenticated-unexpected-error")async def authenticated_unexpected_error_route(request: Request) -> None:_bind_test_user(request)- msg = "something nobody anticipated"- raise RuntimeError(msg)+ raise RuntimeError(_UNEXPECTED_MESSAGE)@_router.get("/pipeline-state-pipelex-error")async def run_state_pipelex_error_route(request: Request) -> None:# Stand-in for the production flow: a body went through `_parse_request`# (state bound), then pipelex raised a `PipelexError` further down the- # stack. Exercises `_log_error_report`.+ # stack. Exercises `_log_problem`._bind_test_run_state(request)- msg = "the gateway config is missing"- raise PipelexConfigError(msg)+ raise PipelexConfigError(_GATEWAY_CONFIG_MESSAGE)@_router.get("/pipeline-state-api-input-error")@@ -424,8 +365,7 @@ async def run_state_unexpected_error_route(request: Request) -> None:# classifiable upstream, so carrying the pipe-state identifiers is what# gives the operator a starting point for debugging._bind_test_run_state(request)- msg = "something nobody anticipated"- raise RuntimeError(msg)+ raise RuntimeError(_UNEXPECTED_MESSAGE)def _gateway_failure() -> LLMCompletionError:@@ -454,7 +394,7 @@ async def inference_failure_unattributed_route() -> None:def _build_client(*,raise_server_exceptions: bool = True,- disclosure_mode: DisclosureMode = DisclosureMode.VERBOSE,+ as_operator: bool = False,http_error_mappers: dict[type[Exception], HttpErrorMapperFn] | None = None,) -> TestClient:"""Wire a throwaway app with the production handlers and request-id middleware.@@ -462,175 +402,229 @@ def _build_client(`raise_server_exceptions` must be `False` for tests that hit the catch-allhandler: Starlette's `ServerErrorMiddleware` always re-raises after runningits handler, so the `TestClient` would otherwise surface the exception- instead of the sanitized response. `disclosure_mode` is the value- `register_exception_handlers` captures in the closures it registers for- `PipelexError` / the mapper handlers; the default mirrors production- (VERBOSE), tests that exercise STRICT redaction pass it explicitly.+ instead of the response. `as_operator` marks every request as the operator's,+ as `verify_api_key` and a trusted proxy's forwarded identity do, so its+ failures answer the operator view; unmarked, they answer the caller view.`http_error_mappers` are the orchestrator-plugin mappers to register atransport handler per `exc_type` for — defaults to none (the agnostic base)."""app = FastAPI()- register_exception_handlers(app, disclosure_mode=disclosure_mode, http_error_mappers=http_error_mappers)- app.include_router(_router)+ register_exception_handlers(app, http_error_mappers=http_error_mappers)+ app.include_router(_router, dependencies=[Depends(mark_operator_request)] if as_operator else [])return TestClient(RequestIdMiddleware(app), raise_server_exceptions=raise_server_exceptions)class TestExceptionHandlers:def test_pipelex_error_produces_problem_json(self):- response = _build_client().get("/config-error")+ response = _build_client(as_operator=True).get("/config-error")assert response.status_code == 500assert response.headers["content-type"] == PROBLEM_JSON_MEDIA_TYPEbody = response.json()config_invalid = error_code_spec(PipelexErrorCode.CONFIG_INVALID)- assert body["code"] == "pipelex.config.invalid"+ assert body["code"] == PipelexErrorCode.CONFIG_INVALIDassert body["type"] == config_invalid.type_uriassert body["title"] == config_invalid.titleassert body["status"] == 500- assert body["detail"] == "the gateway config is missing"- assert body["error_type"] == "PipelexConfigError"- assert body["error_domain"] == "config"- assert body["instance"] == "/config-error"+ # The detail is the code's own sentence; the error's message is what the operator reads in `diagnostics`.+ assert body["detail"] == config_invalid.detail+ assert body["domain"] == "operator"+ assert body["retry"] == "no"+ assert body["next_step"]["kind"] == "fix_configuration"assert body["request_id"] == response.headers[REQUEST_ID_HEADER]+ assert body["diagnostics"]["error_class"] == "PipelexConfigError"+ assert body["diagnostics"]["message"] == _GATEWAY_CONFIG_MESSAGE+ # The members of the retired error report are gone from a problem of a `PipelexError`.+ for retired_member in _RETIRED_REPORT_MEMBERS:+ assert retired_member not in body, retired_memberdef test_env_var_not_found_error_is_config_500(self):- # EnvVarNotFoundError is a ToolError that pipelex classifies under the- # config domain: a missing required env var is an operator-fixable- # misconfiguration, so it maps to HTTP 500 with error_domain "config".- response = _build_client().get("/env-error")- assert response.status_code == 500- body = response.json()- assert "COMPLETION_CALLBACK_SECRET" in body["detail"]- assert body["error_type"] == "EnvVarNotFoundError"- assert body["error_domain"] == "config"-- def test_strict_disclosure_redacts_config_preserves_input(self):- # The handler forwards the disclosure mode it was registered under- # unchanged; pipelex owns the redaction. STRICT redacts a- # non-caller-facing message and keeps a caller-facing one.- client = _build_client(disclosure_mode=DisclosureMode.STRICT)+ # A missing required env var is an operator-fixable misconfiguration: `pipelex.config.variable_missing`, a 500+ # in the operator domain, whose variable only the operator reads.+ operator_body = _build_client(as_operator=True).get("/env-error").json()+ assert operator_body["status"] == 500+ assert operator_body["code"] == PipelexErrorCode.CONFIG_VARIABLE_MISSING+ assert operator_body["domain"] == "operator"+ assert operator_body["diagnostics"]["error_class"] == "EnvVarNotFoundError"+ assert "COMPLETION_CALLBACK_SECRET" in operator_body["diagnostics"]["message"]++ caller_response = _build_client().get("/env-error")+ assert caller_response.status_code == 500+ assert caller_response.json()["code"] == PipelexErrorCode.CONFIG_VARIABLE_MISSING+ assert "COMPLETION_CALLBACK_SECRET" not in caller_response.text++ def test_the_caller_view_withholds_what_only_the_operator_reads(self):+ # An operator's fault reaches the caller as its code, its sentence and a step it can take, and never the+ # error's message; a fault of the caller's own method reaches it with the parameters its sentence names.+ client = _build_client()config_response = client.get("/config-error")assert config_response.status_code == 500- assert config_response.json()["detail"] == INTERNAL_ERROR_PLACEHOLDER- assert "the gateway config is missing" not in config_response.text+ config_body = config_response.json()+ assert config_body["code"] == PipelexErrorCode.CONFIG_INVALID+ assert config_body["next_step"]["kind"] == "report"+ assert "diagnostics" not in config_body+ assert _GATEWAY_CONFIG_MESSAGE not in config_response.textinput_response = client.get("/input-error")assert input_response.status_code == 422- assert 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"+ input_body = input_response.json()+ assert input_body["code"] == CoreCode.METHOD_SYNTAX+ assert input_body["domain"] == "method"+ assert input_body["params"] == {"finding": "TOML syntax error at line 4"}+ assert input_body["detail"] == "The method does not parse (TOML syntax error at line 4)."+ assert "diagnostics" not in input_bodydef test_provider_rate_limit_emits_retry_after(self):- response = _build_client().get("/llm-error")+ response = _build_client(as_operator=True).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 True- assert body["provider_metadata"]["status_code"] == 429+ assert body["code"] == CoreCode.PROVIDER_RATE_LIMITED+ assert body["retry"] == "yes"+ assert body["retry_after"] == ProblemTestData.RATE_LIMIT_RETRY_AFTER_SECONDS+ assert body["next_step"]["kind"] == "wait"+ assert body["params"] == {"model": ProblemTestData.RATE_LIMIT_MODEL, "provider": ProblemTestData.RATE_LIMIT_BACKEND}+ assert body["detail"] == ProblemTestData.RATE_LIMIT_DETAIL+ # What the provider said rides the operator's diagnostics, never the caller's view.+ assert body["diagnostics"]["error_class"] == "LLMCompletionError"+ assert body["diagnostics"]["message"] == ProblemTestData.RATE_LIMIT_MESSAGE+ assert body["diagnostics"]["model"] == ProblemTestData.RATE_LIMIT_MODEL+ assert body["diagnostics"]["provider"] == {+ "name": ProblemTestData.RATE_LIMIT_BACKEND,+ "status": 429,+ "request_id": ProblemTestData.RATE_LIMIT_PROVIDER_REQUEST_ID,+ }++ @pytest.mark.parametrize("case", list(ProblemTestData.RETRY_CASES))+ def test_retry_after_header_is_guarded(self, case: str):+ """`Retry-After` rides a 429 alone, and only when the delay is a finite, non-negative number, rounded up."""+ _, _, expected_status, expected_header, expected_retry_after = ProblemTestData.RETRY_CASES[case]++ response = _build_client().get(f"/crafted-retry/{case}")- @pytest.mark.parametrize(- ("report_key", "expected_status", "expected_retry_after"),- [- ("finite", 429, "13"), # 12.4 rounds up- ("infinite", 429, None), # non-finite is dropped — no crash, no header- ("nan", 429, None), # non-finite is dropped — no crash, no header- ("negative", 429, "0"), # clamped to a non-negative integer- ("non_429", 500, None), # the hint never rides a non-429 response- ],- )- def test_retry_after_header_is_guarded(self, report_key: str, expected_status: int, expected_retry_after: str | None):- response = _build_client().get(f"/crafted-retry/{report_key}")assert response.status_code == expected_status- if expected_retry_after is None:- assert "retry-after" not in response.headers- else:- assert response.headers["Retry-After"] == expected_retry_after-- def test_unexpected_error_discloses_class_and_message_under_verbose(self):- # The catch-all honors the disclosure mode like every other handler.- # Under VERBOSE an unclassified failure is the one error a caller cannot- # diagnose from a request id alone, so `detail` names it outright —- # otherwise a deployment that opted into disclosure would still hit a- # dead end here.- response = _build_client(raise_server_exceptions=False).get("/unexpected-error")+ assert response.json()["status"] == expected_status+ assert response.headers.get("Retry-After") == expected_header+ assert response.json().get("retry_after") == expected_retry_after++ @pytest.mark.parametrize(("code", "expected_status"), ProblemTestData.CODE_STATUSES)+ def test_the_status_is_the_one_the_code_declares(self, mocker: MockerFixture, code: ErrorCode, expected_status: int):+ """The response's status, the body's `status` member and the record's are the registry's, one value for all three."""+ log_spy = mocker.patch("pipelex_api.exception_handlers.log")++ response = problem_response(make_problem(code=code, view=ProblemView.OPERATOR), error=None, request=_bare_request("/coded"))++ assert error_code_spec(code).status == expected_status+ assert response.status_code == expected_status+ body = json.loads(bytes(response.body))+ assert body["status"] == expected_status+ assert body["code"] == code+ fields = _emitted_fields(log_spy, as_error=expected_status >= 500)+ assert fields["http.response.status_code"] == expected_status+ assert fields["error.code"] == code++ def test_a_code_the_registry_does_not_know_falls_back_to_500(self, mocker: MockerFixture):+ """A code no registry entry parses, which only a client's own failure has, still answers a status: 500."""+ log_spy = mocker.patch("pipelex_api.exception_handlers.log")+ problem = make_problem(code=CoreCode.RUNTIME_UNEXPECTED, view=ProblemView.OPERATOR).model_copy(update={"code": "x.unknown"})++ response = problem_response(problem, error=None, request=_bare_request("/unknown-code"))+assert response.status_code == 500- assert response.headers["content-type"] == PROBLEM_JSON_MEDIA_TYPE- body = response.json()- assert body["error_type"] == "InternalServerError"- assert body["error_domain"] == "runtime"- assert body["retryable"] is False- assert body["type"].endswith("/internal-server-error/")- assert body["instance"] == "/unexpected-error"- assert body["error_category"] == "unknown"- assert body["detail"] == "RuntimeError: something nobody anticipated"-- def test_unexpected_error_is_sanitized_under_strict(self):- # STRICT still redacts: a deployment that wants nothing leaked keeps- # exactly the old sanitized body — no class name, no `str(exc)`.- client = _build_client(disclosure_mode=DisclosureMode.STRICT, raise_server_exceptions=False)- response = client.get("/unexpected-error")+ body = json.loads(bytes(response.body))+ assert body["status"] == 500+ assert body["code"] == "x.unknown"+ assert "retry-after" not in response.headers+ fields = _emitted_fields(log_spy, as_error=True)+ assert fields["http.response.status_code"] == 500++ @pytest.mark.parametrize("as_operator", [True, False], ids=["operator", "caller"])+ def test_unexpected_error_is_runtime_unexpected(self, as_operator: bool):+ """An unclassified failure answers `runtime.unexpected`: its own sentences to the caller, its class and message to the operator."""+ response = _build_client(raise_server_exceptions=False, as_operator=as_operator).get("/unexpected-error")assert response.status_code == 500+ assert response.headers["content-type"] == PROBLEM_JSON_MEDIA_TYPEbody = response.json()- assert body["error_type"] == "InternalServerError"- assert body["error_category"] == "unknown"- assert body["detail"] == "An unexpected error occurred. The request id is included for support."- assert "RuntimeError" not in response.text- assert "something nobody anticipated" not in response.text-- def test_unexpected_error_never_leaks_a_traceback(self):- # Disclosure is the message, never the stack: a traceback stays an- # operator-log artifact in BOTH modes.- for mode in (DisclosureMode.VERBOSE, DisclosureMode.STRICT):- response = _build_client(disclosure_mode=mode, raise_server_exceptions=False).get("/unexpected-error")- assert "Traceback" not in response.text- assert "unexpected_error_route" not in response.text+ runtime_unexpected = error_code_spec(CoreCode.RUNTIME_UNEXPECTED)+ assert body["code"] == CoreCode.RUNTIME_UNEXPECTED+ assert body["type"] == runtime_unexpected.type_uri+ assert body["detail"] == runtime_unexpected.detail+ assert body["domain"] == "runtime"+ assert body["retry"] == "no"+ assert body["next_step"]["kind"] == "report"+ assert body["request_id"] == response.headers[REQUEST_ID_HEADER]+ assert "error_type" not in body+ if as_operator:+ assert body["diagnostics"]["error_class"] == "PipelexUnexpectedError"+ assert body["diagnostics"]["message"] == f"RuntimeError: {_UNEXPECTED_MESSAGE}"+ assert body["diagnostics"]["causes"] == [{"error_class": "RuntimeError"}]+ else:+ assert "diagnostics" not in body+ assert "RuntimeError" not in response.text+ assert _UNEXPECTED_MESSAGE not in response.text++ @pytest.mark.parametrize("as_operator", [True, False], ids=["operator", "caller"])+ def test_unexpected_error_never_leaks_a_traceback(self, as_operator: bool):+ # The operator reads the message, never the stack: a traceback stays an operator-log artifact in both views.+ response = _build_client(raise_server_exceptions=False, as_operator=as_operator).get("/unexpected-error")+ assert "Traceback" not in response.text+ assert "unexpected_error_route" not in response.textdef test_orchestrator_error_dispatch(self):- # The F3 seam: a synthetic plugin contributes a transport mapper through the registrar SPI,- # the app registers one handler per mapped exc_type, and a bare transport error renders the- # plugin's classified ErrorReport — all without importing any orchestrator SDK.- client = _build_client(http_error_mappers=_synthetic_http_error_mappers())+ # The plugin seam: a synthetic plugin contributes a transport mapper through the registrar SPI, the app registers+ # one handler per mapped exc_type, and a bare transport error answers the problem of the `PipelexError` the+ # mapper returned — all without importing any orchestrator SDK.+ client = _build_client(as_operator=True, http_error_mappers=_synthetic_http_error_mappers())- # An orchestrator failure that IS a PipelexError — routed to the PipelexError handler (its- # error_type is the class name), NOT the transport mapper handler.+ # An orchestrator failure that IS a PipelexError is routed to the PipelexError handler, NOT the transport+ # mapper handler: `run.failed`, which declares 409.pipelex_response = client.get("/orchestrator-pipelex-error")- assert pipelex_response.status_code == 500- assert 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.+ assert pipelex_response.status_code == 409+ pipelex_body = pipelex_response.json()+ assert pipelex_body["code"] == CoreCode.RUN_FAILED+ assert pipelex_body["detail"] == "The run 'run-7' ended as 'FAILED', without success."+ assert pipelex_body["diagnostics"]["error_class"] == "_SyntheticOrchestratorError"++ # A bare transport error is routed to the plugin's mapper-backed handler: `runtime.unavailable`, a retryable 503,+ # whose operator-only parameter rides the diagnostics.transport_response = client.get("/synthetic-transport-error")- assert transport_response.status_code == 500+ assert transport_response.status_code == 503transport_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+ assert transport_body["code"] == CoreCode.RUNTIME_UNAVAILABLE+ assert transport_body["retry"] == "yes"+ assert transport_body["diagnostics"]["error_class"] == "_SyntheticTransportFault"+ assert transport_body["diagnostics"]["message"] == _TRANSPORT_MESSAGE+ assert transport_body["diagnostics"]["params"] == {"dependency": "orchestrator"}+ assert "params" not in transport_body++ def test_mapped_transport_error_answers_the_caller_without_its_diagnostics(self):+ response = _build_client(http_error_mappers=_synthetic_http_error_mappers()).get("/synthetic-transport-error")+ assert response.status_code == 503+ body = response.json()+ assert body["code"] == CoreCode.RUNTIME_UNAVAILABLE+ assert "diagnostics" not in body+ assert _TRANSPORT_MESSAGE not in response.text+ assert "orchestrator" not in json.dumps(body.get("params", {}))def test_unmapped_transport_error_falls_back_to_catch_all_500(self):- # Without the orchestrator plugin's mapper (the agnostic base), the same bare transport error- # has no dedicated handler and collapses to the catch-all 500 — which under VERBOSE still- # tells the caller which transport class failed and why.- response = _build_client(raise_server_exceptions=False).get("/synthetic-transport-error")+ # Without the orchestrator plugin's mapper (the agnostic base), the same bare transport error has no dedicated+ # handler and collapses to the catch-all `runtime.unexpected` — whose diagnostics still tell the operator which+ # transport class failed and why.+ response = _build_client(raise_server_exceptions=False, as_operator=True).get("/synthetic-transport-error")assert response.status_code == 500body = response.json()- assert body["error_type"] == "InternalServerError"- assert body["detail"] == "_SyntheticTransportError: orchestrator cluster unreachable"-- def test_handler_of_handlers_catches_corrupt_report(self):- # When to_error_report() itself raises, the failure escapes the- # PipelexError handler; ServerErrorMiddleware funnels it into the- # catch-all — a real 500 body, never a bodyless default. The disclosed- # class is the one raised *by the broken handler*, not the original.- response = _build_client(raise_server_exceptions=False).get("/corrupt-error")+ assert body["code"] == CoreCode.RUNTIME_UNEXPECTED+ assert body["diagnostics"]["message"] == f"_SyntheticTransportError: {_TRANSPORT_MESSAGE}"++ def test_handler_of_handlers_catches_a_corrupt_problem(self):+ # When building the problem itself raises, the failure escapes the PipelexError handler; ServerErrorMiddleware+ # funnels it into the catch-all — a real 500 body, never a bodyless default. The class the diagnostics name is+ # the one raised *by the broken builder*, not the original error.+ response = _build_client(raise_server_exceptions=False, as_operator=True).get("/corrupt-error")assert response.status_code == 500body = response.json()- assert body["error_type"] == "InternalServerError"- assert body["error_category"] == "unknown"+ assert body["code"] == CoreCode.RUNTIME_UNEXPECTED+ assert body["diagnostics"]["message"] == "RuntimeError: problem_facts is deliberately broken"@pytest.mark.parametrize(("method", "path", "json_body", "expected_status"),@@ -639,7 +633,7 @@ class TestExceptionHandlers:("GET", "/env-error", None, 500),("GET", "/input-error", None, 422),("GET", "/llm-error", None, 429),- ("GET", "/orchestrator-pipelex-error", None, 500),+ ("GET", "/orchestrator-pipelex-error", None, 409),("GET", "/synthetic-transport-error", None, 500),("GET", "/corrupt-error", None, 500),("GET", "/unexpected-error", None, 500),@@ -671,12 +665,60 @@ class TestExceptionHandlers:assert response.headers[REQUEST_ID_HEADER] == "inbound-correlation-007"assert response.json()["request_id"] == "inbound-correlation-007"+ def test_pipelex_error_record_names_the_code_and_the_class(self, mocker: MockerFixture):+ # The record is built from the operator view whichever view the response carries: the caller's body names no+ # class, the record does, beside the code a sink groups failures by.+ log_spy = mocker.patch("pipelex_api.exception_handlers.log")+ response = _build_client().get("/config-error")+ assert response.status_code == 500+ assert "diagnostics" not in response.json()+ log_spy.error.assert_called_once()+ fields = _emitted_fields(log_spy, as_error=True)+ assert fields["error.code"] == PipelexErrorCode.CONFIG_INVALID+ assert fields["error.type"] == "PipelexConfigError"+ assert fields["error_domain"] == "config"+ assert fields["retryable"] is False+ assert fields["http.response.status_code"] == 500+ assert fields["url.path"] == "/config-error"+ # A domain error's record carries no `detail`: the cause is the diagnostics', the body's detail is only its code's sentence.+ assert "detail" not in fields+ assert log_spy.error.call_args.kwargs["include_exception"] is True++ def test_provider_failure_record_carries_the_providers_answer(self, mocker: MockerFixture):+ log_spy = mocker.patch("pipelex_api.exception_handlers.log")+ response = _build_client().get("/llm-error")+ assert response.status_code == 429+ # A provider's 429 passed through is no fault of this server: a warning, without a traceback.+ log_spy.warning.assert_called_once()+ log_spy.error.assert_not_called()+ fields = _emitted_fields(log_spy, as_error=False)+ assert fields["error.code"] == CoreCode.PROVIDER_RATE_LIMITED+ assert fields["error.type"] == "LLMCompletionError"+ assert fields["error_category"] == InferenceErrorCategory.TRANSIENT+ assert fields["retryable"] is True+ assert fields["backend_name"] == ProblemTestData.RATE_LIMIT_BACKEND+ assert fields["model_handle"] == ProblemTestData.RATE_LIMIT_MODEL+ assert fields["provider_status_code"] == 429+ assert fields["provider_request_id"] == ProblemTestData.RATE_LIMIT_PROVIDER_REQUEST_ID++ def test_unexpected_error_record_names_the_class_that_escaped(self, mocker: MockerFixture):+ # The catch-all's record is the operator's only handle on a failure nothing classified, so it names the class+ # that escaped, which a sink groups unexpected failures by, beside the code they all share.+ log_spy = mocker.patch("pipelex_api.exception_handlers.log")+ response = _build_client(raise_server_exceptions=False).get("/unexpected-error")+ assert response.status_code == 500+ log_spy.error.assert_called_once()+ fields = _emitted_fields(log_spy, as_error=True)+ assert fields["error.code"] == CoreCode.RUNTIME_UNEXPECTED+ assert fields["error.type"] == "RuntimeError"+ assert log_spy.error.call_args.kwargs["include_exception"] is True+def test_api_authored_500_emits_structured_error_record(self, mocker: MockerFixture):# Without `handle_api_error` logging, an `ApiError`-shaped 500 produces# zero operator output (`/version`'s `PackageNotFoundError →# raise_internal_server_error` is the canonical silent case). Assert# the handler emits one `api_error` record at `error` level whose fields- # mirror the response — the same set `_log_error_report` ships for a+ # mirror the response — the same set `_log_problem` ships for a# pipelex-derived 500, so a downstream sink queries them uniformly.log_spy = mocker.patch("pipelex_api.exception_handlers.log")response = _build_client().get("/api-config-error")@@ -697,7 +739,7 @@ class TestExceptionHandlers:def test_api_authored_4xx_emits_structured_warning_record(self, mocker: MockerFixture):# Mirror at the warning level: an INPUT-domain `ApiError` is a caller# mistake, not an operator fault, so it logs at `warning` without a- # traceback — same disposition rule `_log_error_report` uses.+ # traceback — same disposition rule `_log_problem` uses.log_spy = mocker.patch("pipelex_api.exception_handlers.log")response = _build_client().get("/api-input-error")assert response.status_code == 422@@ -786,7 +828,9 @@ class TestExceptionHandlers:"""The provider the SDK's metadata names, `gateway`, is no backend's name: it is never written under `backend_name`, nor under `sdk`."""log_spy = mocker.patch("pipelex_api.exception_handlers.log")response = _build_client().get(path)- assert response.status_code == 500+ # A provider answering 503 is `provider.unavailable`, whose registry entry declares 502.+ assert response.status_code == 502+ assert response.json()["code"] == CoreCode.PROVIDER_UNAVAILABLEfields = _emitted_fields(log_spy, as_error=True)assert fields.get("backend_name") == expected_backend_nameassert "sdk" not in fields@@ -794,11 +838,8 @@ class TestExceptionHandlers:assert fields["provider_status_code"] == 503def test_user_id_rides_authenticated_pipelex_error_record(self, mocker: MockerFixture):- # Phase 3 deleted the per-route `log.error(... user=...)` lines on- # storage / pipeline-backend failures; the global handler now reads- # `request.state.user` so the operator can still tie a `PipelexError`- # to the caller through the record alone — no correlating across- # records on `request_id` required.+ # The global handler reads `request.state.user` so the operator can tie a `PipelexError` to the caller+ # through the record alone — no correlating across records on `request_id` required.log_spy = mocker.patch("pipelex_api.exception_handlers.log")response = _build_client().get("/authenticated-config-error")assert response.status_code == 500@@ -806,12 +847,13 @@ class TestExceptionHandlers:fields = _emitted_fields(log_spy, as_error=True)assert fields["user.id"] == _TEST_USER_IDassert fields["error.type"] == "PipelexConfigError"+ assert fields["error.code"] == PipelexErrorCode.CONFIG_INVALIDdef test_user_id_rides_authenticated_api_authored_record(self, mocker: MockerFixture):# `handle_api_error` covers the API-authored 4xx surface (storage's# `raise_bad_request`, `raise_forbidden`, `raise_payload_too_large`;# uploader's same set). It must ride the same `user.id` correlation- # `_log_error_report` does so the contract is uniform — a caller+ # `_log_problem` does so the contract is uniform — a caller# mistake and a backend failure both name the caller.log_spy = mocker.patch("pipelex_api.exception_handlers.log")response = _build_client().get("/authenticated-api-input-error")@@ -831,7 +873,7 @@ class TestExceptionHandlers:log_spy.error.assert_called_once()fields = _emitted_fields(log_spy, as_error=True)assert fields["user.id"] == _TEST_USER_ID- assert fields["error.type"] == "RuntimeError"+ assert fields["error.code"] == CoreCode.RUNTIME_UNEXPECTEDdef test_user_id_absent_from_unauthenticated_error_record(self, mocker: MockerFixture):# Pre-auth paths, and a deployment with no user model, have no `request.state.user`;@@ -845,12 +887,8 @@ class TestExceptionHandlers:assert "user.id" not in _emitted_fields(log_spy, as_error=True)def test_run_state_rides_pipelex_error_record(self, mocker: MockerFixture):- # `_parse_request` binds `pipe_code` / `pipeline_run_id` on- # `request.state` so a downstream pipelex failure is tied to the- # specific pipe and run id without each backend frame having to forward- # them. Same mechanism as `user_id` (request.state + a `_*_of` getter- # in the handler), now extended to the body-derived identifiers — the- # last piece of Checkpoint B reconciliation #4.+ # `_parse_request` binds `pipe_code` / `pipeline_run_id` on `request.state` so a downstream pipelex failure is+ # tied to the specific pipe and run id without each backend frame having to forward them.log_spy = mocker.patch("pipelex_api.exception_handlers.log")response = _build_client().get("/pipeline-state-pipelex-error")assert response.status_code == 500@@ -859,6 +897,8 @@ class TestExceptionHandlers:assert fields["pipe_code"] == _TEST_PIPE_CODEassert fields["pipeline_run_id"] == _TEST_RUN_IDassert fields["error.type"] == "PipelexConfigError"+ # The bound run id rides the problem too, so a caller can name the run it asks about.+ assert response.json()["pipeline_run_id"] == _TEST_RUN_IDdef test_run_state_rides_api_authored_record(self, mocker: MockerFixture):# API-authored 4xx surface: `raise_validation_error` raised from a@@ -887,7 +927,7 @@ class TestExceptionHandlers:fields = _emitted_fields(log_spy, as_error=True)assert fields["pipe_code"] == _TEST_PIPE_CODEassert fields["pipeline_run_id"] == _TEST_RUN_ID- assert fields["error.type"] == "RuntimeError"+ assert fields["error.code"] == CoreCode.RUNTIME_UNEXPECTEDdef test_run_state_absent_when_parse_request_did_not_bind(self, mocker: MockerFixture):# A route that didn't go through `_parse_request` (here: `/config-error`,@@ -902,6 +942,7 @@ class TestExceptionHandlers:fields = _emitted_fields(log_spy, as_error=True)assert "pipe_code" not in fieldsassert "pipeline_run_id" not in fields+ assert "pipeline_run_id" not in response.json()def test_request_validation_error_emits_structured_warning_record(self, mocker: MockerFixture):# FastAPI's automatic-validation 422 goes through@@ -959,36 +1000,24 @@ 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`` 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- # transient runtime fault.+ # ``AsyncExecutionNotEnabledError`` carries ``runtime.unsupported``, whose registry entry declares 501 Not+ # Implemented: the failure is permanent under the current deployment rather than a transient runtime fault.response = _build_client().get("/async-execution-not-enabled")assert response.status_code == 501assert response.headers["content-type"] == PROBLEM_JSON_MEDIA_TYPEbody = response.json()- # The body's ``status`` member must agree with the HTTP status — if- # the override path only bumped the header status and left the body at- # 500, RFC 7807-aware clients would see a contradictory document.+ # The body's ``status`` member agrees with the HTTP status.assert body["status"] == 501runtime_unsupported = error_code_spec(CoreCode.RUNTIME_UNSUPPORTED)- assert body["code"] == "runtime.unsupported"+ assert body["code"] == CoreCode.RUNTIME_UNSUPPORTEDassert body["title"] == runtime_unsupported.title- assert body["error_type"] == "AsyncExecutionNotEnabledError"- assert body["error_domain"] == "config"- assert body["instance"] == "/async-execution-not-enabled"assert body["type"] == runtime_unsupported.type_uri+ assert body["domain"] == "operator"+ assert body["detail"] == "This runtime lacks asynchronous execution, which the request needs."assert body["request_id"] == response.headers[REQUEST_ID_HEADER]- def test_async_execution_not_enabled_logs_post_override_status(self, mocker: MockerFixture):- # ``_log_error_report`` receives the overridden status so the operator- # record agrees with what the client actually saw. Without the- # ``status=`` plumbing the record would carry 500 (the report's domain- # default) while the response shipped 501 — a silent disagreement- # between the two surfaces. Pin the alignment.+ def test_async_execution_not_enabled_logs_its_status(self, mocker: MockerFixture):+ # The record carries the status the client saw.log_spy = mocker.patch("pipelex_api.exception_handlers.log")response = _build_client().get("/async-execution-not-enabled")assert response.status_code == 501@@ -996,48 +1025,47 @@ class TestExceptionHandlers:fields = _emitted_fields(log_spy, as_error=True)assert fields["http.response.status_code"] == 501assert fields["error.type"] == "AsyncExecutionNotEnabledError"+ assert fields["error.code"] == CoreCode.RUNTIME_UNSUPPORTEDassert fields["error_domain"] == "config"def test_pipeline_run_id_conflict_maps_to_409(self):- # ``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- # from a real internal failure.+ # ``PipelineManagerAlreadyExistsError`` carries ``pipelex.run.already_exists``, a client-visible conflict whose+ # registry entry declares 409, so callers can tell "this id is currently in use" apart from an internal failure.response = _build_client().get("/pipeline-run-id-conflict")assert response.status_code == 409assert response.headers["content-type"] == PROBLEM_JSON_MEDIA_TYPEbody = response.json()- # The body's ``status`` member must agree with the HTTP status (same- # RFC 7807 agreement contract as the 501 override above).assert body["status"] == 409run_already_exists = error_code_spec(PipelexErrorCode.RUN_ALREADY_EXISTS)- assert body["code"] == "pipelex.run.already_exists"- assert body["error_type"] == "PipelineManagerAlreadyExistsError"+ assert body["code"] == PipelexErrorCode.RUN_ALREADY_EXISTSassert body["title"] == run_already_exists.title- assert body["instance"] == "/pipeline-run-id-conflict"assert body["type"] == run_already_exists.type_uri+ assert body["domain"] == "input"+ assert body["next_step"]["kind"] == "change_input"assert body["request_id"] == response.headers[REQUEST_ID_HEADER]- def test_method_package_symlink_maps_to_422(self, mocker: MockerFixture):- # ``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.+ @pytest.mark.parametrize("as_operator", [True, False], ids=["operator", "caller"])+ def test_method_package_symlink_maps_to_422(self, mocker: MockerFixture, as_operator: bool):+ # ``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 and logs at warning.log_spy = mocker.patch("pipelex_api.exception_handlers.log")- response = _build_client().get("/method-package-symlink")+ response = _build_client(as_operator=as_operator).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["code"] == CoreCode.METHOD_PACKAGE_INVALID+ assert body["domain"] == "method"assert body["request_id"] == response.headers[REQUEST_ID_HEADER]+ if as_operator:+ assert body["diagnostics"]["error_class"] == "MethodPackageSymlinkError"+ assert "contains a symlink ('vendored')" in body["diagnostics"]["message"]+ else:+ assert "diagnostics" not in bodylog_spy.warning.assert_called_once()log_spy.error.assert_not_called()- def test_pipeline_run_id_conflict_logs_at_warning_post_override_status(self, mocker: MockerFixture):+ def test_pipeline_run_id_conflict_logs_at_warning(self, mocker: MockerFixture):# A duplicate pipeline_run_id is a client-visible 409 conflict, not a# server fault: disposition is keyed off the final HTTP status, so it# logs at `warning` without a traceback — never `error` (which would@@ -1051,3 +1079,4 @@ class TestExceptionHandlers:fields = _emitted_fields(log_spy, as_error=False)assert fields["http.response.status_code"] == 409assert fields["error.type"] == "PipelineManagerAlreadyExistsError"+ assert fields["error.code"] == PipelexErrorCode.RUN_ALREADY_EXISTSdiff --git a/api/tests/unit/test_execute_dispatch.py b/api/tests/unit/test_execute_dispatch.pyindex 03a02ac6f..163a24e1c 100644--- a/api/tests/unit/test_execute_dispatch.py+++ b/api/tests/unit/test_execute_dispatch.py@@ -390,7 +390,7 @@ 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"+ assert exc_info.value.resolve_error_code() == "pipelex.plugin.not_found"@pytest.mark.asyncioasync def test_missing_orchestrator_for_the_callers_override_is_unsupported(self, mocker: MockerFixture) -> None:@@ -406,4 +406,4 @@ class TestExecuteDispatch:requested_orchestration_mode="temporal",)assert exc_info.value.mode == "temporal"- assert exc_info.value.to_error_report().code == "runtime.unsupported"+ assert exc_info.value.resolve_error_code() == "runtime.unsupported"diff --git a/api/tests/unit/test_method_cache.py b/api/tests/unit/test_method_cache.pyindex 784aee2cb..d974b8f51 100644--- a/api/tests/unit/test_method_cache.py+++ b/api/tests/unit/test_method_cache.py@@ -13,6 +13,7 @@ import timefrom pathlib import Pathimport pytest+from pipelex.errors.problem import ProblemViewfrom pipelex.methods.exceptions import MethodFetchErrorfrom pipelex.methods.fetching import fetch_method_packagefrom pipelex.methods.method_ref import parse_method_ref@@ -67,7 +68,11 @@ class TestMethodCloneCache:branch_ref = parse_method_ref("github.com/pipelex/methods/documents@main")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"+ assert exc_info.value.resolve_error_code() == "method.not_found"+ # The caller reads which reference was refused, never the code's title alone.+ problem = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert problem.to_wire()["params"] == {"method_ref": branch_ref.ref_str}+ assert branch_ref.ref_str in problem.detaildef test_a_cached_sha_is_never_recloned(self, origin: tuple[str, Path], tmp_path: Path, mocker: MockerFixture):clone_url, repo = origin@@ -188,4 +193,7 @@ class TestMethodCloneCache: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"+ assert exc_info.value.resolve_error_code() == "method.fetch_failed"+ problem = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert problem.to_wire()["params"] == {"method_ref": _BARE_REF.ref_str}+ assert _BARE_REF.ref_str in problem.detaildiff --git a/api/tests/unit/test_method_ref_run.py b/api/tests/unit/test_method_ref_run.pyindex 6cd484ac2..697a51426 100644--- a/api/tests/unit/test_method_ref_run.py+++ b/api/tests/unit/test_method_ref_run.py@@ -7,7 +7,7 @@ written as the run's one library directory, the caller's own; the entry pipe defmanifest's `main_pipe` (a request `pipe_code` overrides); provenance `{address, tag,commit_sha, tree_digest}` lands on the response; the exclusivity rules 422; theexecution-locus gate refuses Python where it must; and each resolution failure maps to its-distinct `error_type` + status as RFC 7807 `problem+json`.+distinct code + status as RFC 7807 `problem+json`, the status being the code's."""import logging@@ -16,14 +16,18 @@ from pathlib import Pathfrom typing import Anyimport pytest-from fastapi import FastAPI+from fastapi import Depends, FastAPIfrom fastapi.testclient import TestClientfrom mthds.method_tree.digest import digest_of_contents+from mthds.protocol.problem.registry import CoreCode+from pipelex.errors.error_codes import ErrorCode, error_code_spec+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.methods.exceptions import MethodFetchErrorfrom pipelex.pipeline.pipeline_response import PipelexRunResultStart, RunStatefrom pytest_mock import MockerFixturefrom pipelex_api.exception_handlers import register_exception_handlers+from pipelex_api.problem_view import mark_operator_requestfrom pipelex_api.routes.pipelex.pipeline import router as pipeline_routerfrom tests.unit._constants import STUB_METHOD_ADDRESS, STUB_METHOD_COMMIT_SHA, STUB_METHOD_MANIFEST, VALID_MTHDS@@ -44,10 +48,13 @@ class Invoice(StructuredContent):"""-def _build_client(mocker: MockerFixture) -> tuple[TestClient, dict[str, Any]]:- """Wire an app whose ApiRunner is mocked and records what the run actually saw."""+def _build_client(mocker: MockerFixture, *, as_operator: bool = False) -> tuple[TestClient, dict[str, Any]]:+ """Wire an app whose ApiRunner is mocked and records what the run actually saw.++ `as_operator` marks each request as the operator's, whose view carries a refusal's own message in `diagnostics`.+ """app = FastAPI()- app.include_router(pipeline_router, prefix="/v1")+ app.include_router(pipeline_router, prefix="/v1", dependencies=[Depends(mark_operator_request)] if as_operator else [])register_exception_handlers(app)snapshot: dict[str, Any] = {}@@ -184,42 +191,71 @@ class TestMethodRefRun:def test_method_ref_is_exclusive_with_inline_contents_and_bundles(self, mocker: MockerFixture, install_method_package: Callable[..., Path]):install_method_package(files={"documents.mthds": VALID_MTHDS})- client, _ = _build_client(mocker)+ client, _ = _build_client(mocker, as_operator=True)with_contents = client.post("/v1/execute", json={"method_ref": _METHOD_REF, "mthds_contents": [VALID_MTHDS]})with_bundle = client.post("/v1/execute", json={"method_ref": _METHOD_REF, "files": {"main.mthds": VALID_MTHDS}})for response in (with_contents, with_bundle):assert response.status_code == 422, response.text- assert "mutually exclusive" in response.json()["detail"]+ problem = response.json()+ assert problem["code"] == CoreCode.REQUEST_INVALID+ assert problem.get("params") == {"field": "method_ref"}+ assert "mutually exclusive" in problem["diagnostics"]["message"]- def test_malformed_ref_is_422_with_parse_error_type(self, mocker: MockerFixture, install_method_package: Callable[..., Path]):+ def test_an_address_this_runtime_does_not_fetch_is_a_422_naming_the_field(+ self, mocker: MockerFixture, install_method_package: Callable[..., Path]+ ):install_method_package(files={"documents.mthds": VALID_MTHDS})- client, _ = _build_client(mocker)+ client, _ = _build_client(mocker, as_operator=True)response = client.post("/v1/execute", json={"method_ref": "gitlab.com/acme/tools", "inputs": {}})assert response.status_code == 422, response.textassert response.headers["content-type"] == "application/problem+json"- assert response.json()["error_type"] == "MethodRefParseError"+ problem = response.json()+ assert problem["code"] == CoreCode.REQUEST_UNSUPPORTED+ assert problem["domain"] == "input"+ assert problem.get("params", {}).get("field") == "method_ref"+ assert problem["diagnostics"]["error_class"] == "MethodRefParseError"def test_unknown_package_is_404_problem_json(self, mocker: MockerFixture, install_method_package: Callable[..., Path]):install_method_package(files={"documents.mthds": VALID_MTHDS})- client, _ = _build_client(mocker)- response = client.post("/v1/execute", json={"method_ref": "github.com/pipelex/methods/nonexistent", "inputs": {}})+ client, _ = _build_client(mocker, as_operator=True)+ unknown_address = "github.com/pipelex/methods/nonexistent"+ response = client.post("/v1/execute", json={"method_ref": unknown_address, "inputs": {}})assert response.status_code == 404, response.textassert response.headers["content-type"] == "application/problem+json"- body = response.json()- assert body["error_type"] == "MethodPackageNotFoundError"- # The message teaches: it lists the packages the repository does contain.- assert STUB_METHOD_ADDRESS in body["detail"]+ problem = response.json()+ assert problem["code"] == CoreCode.METHOD_NOT_FOUND+ assert problem.get("params") == {"method_ref": unknown_address}+ assert problem["diagnostics"]["error_class"] == "MethodPackageNotFoundError"+ # The operator's message teaches: it lists the packages the repository does contain.+ assert STUB_METHOD_ADDRESS in problem["diagnostics"]["message"]- def test_fetch_failure_is_422_with_fetch_error_type(self, mocker: MockerFixture):+ @pytest.mark.parametrize(+ ("code", "expected_status"),+ [+ (CoreCode.METHOD_FETCH_FAILED, 502),+ (CoreCode.METHOD_NOT_FOUND, 404),+ (CoreCode.METHOD_PACKAGE_INVALID, 422),+ (PipelexErrorCode.CONFIG_DEPENDENCY_MISSING, 500),+ ],+ )+ def test_a_fetch_failure_answers_the_status_of_its_code(self, mocker: MockerFixture, code: ErrorCode, expected_status: int):+ """A failed fetch answers whatever code its raise site chose, with that code's status from the error registry."""+ fetch_error = MethodFetchError(f"Failed to fetch method '{STUB_METHOD_ADDRESS}': boom").for_method_ref(method_ref=STUB_METHOD_ADDRESS)stub_cache = mocker.MagicMock()- stub_cache.pinned_package.side_effect = MethodFetchError("Failed to fetch method 'github.com/pipelex/methods/documents': boom")+ stub_cache.pinned_package.side_effect = fetch_error.with_error_code(code)mocker.patch("pipelex_api.method_source.get_method_clone_cache", return_value=stub_cache)client, _ = _build_client(mocker)response = client.post("/v1/execute", json={"method_ref": STUB_METHOD_ADDRESS, "inputs": {}})- assert response.status_code == 422, response.text+ assert response.status_code == expected_status, response.textassert response.headers["content-type"] == "application/problem+json"- assert response.json()["error_type"] == "MethodFetchError"- assert response.json()["code"] == "method.fetch_failed"+ problem = response.json()+ assert error_code_spec(code).status == expected_status+ assert problem["status"] == expected_status+ assert problem["code"] == code+ assert problem["retry"] == error_code_spec(code).retry+ # The caller's view: the code's sentences, never the fetch's own message.+ assert "boom" not in response.text+ assert "diagnostics" not in problemdef 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})@@ -245,11 +281,15 @@ class TestMethodRefRun:def test_structures_package_refused_even_when_sandbox_hosted(self, mocker: MockerFixture, install_method_package: Callable[..., Path]):install_method_package(files={"documents.mthds": VALID_MTHDS, "structures/models.py": _STRUCTURES_PY})mocker.patch(f"{_TREE_NS}.is_pipe_func_sandbox_hosted", return_value=True)- client, _ = _build_client(mocker)+ client, _ = _build_client(mocker, as_operator=True)response = client.post("/v1/execute", json={"method_ref": _METHOD_REF, "inputs": {}})- assert response.status_code == 403, response.text+ # The method's own structure classes are its author's to change: a 422, the code's status.+ assert response.status_code == 422, response.textassert response.headers["content-type"] == "application/problem+json"- body = response.json()- assert body["error_type"] == "MethodStructuresRefusedError"- # The refusal names the rule and teaches the fix.- assert "MTHDS concepts" in body["detail"]+ problem = response.json()+ assert problem["code"] == PipelexErrorCode.DEPLOYMENT_PYTHON_STRUCTURES_REFUSED+ assert problem["domain"] == "method"+ assert problem["next_step"]["kind"] == "change_method"+ assert problem["diagnostics"]["error_class"] == "MethodStructuresRefusedError"+ # The operator's message names the rule and teaches the fix.+ assert "MTHDS concepts" in problem["diagnostics"]["message"]diff --git a/api/tests/unit/test_method_ref_validate.py b/api/tests/unit/test_method_ref_validate.pyindex 93416240f..b45d9ca32 100644--- a/api/tests/unit/test_method_ref_validate.py+++ b/api/tests/unit/test_method_ref_validate.py@@ -13,6 +13,7 @@ from pathlib import Pathfrom fastapi import FastAPIfrom fastapi.testclient import TestClient+from mthds.protocol.problem.registry import CoreCodefrom pipelex_api.exception_handlers import register_exception_handlersfrom pipelex_api.routes import router as api_router@@ -59,7 +60,8 @@ class TestMethodRefValidate:assert response.status_code == 404, response.textassert response.headers["content-type"] == "application/problem+json"body = response.json()- assert body["error_type"] == "MethodPackageNotFoundError"+ assert body["code"] == CoreCode.METHOD_NOT_FOUND+ assert body["status"] == 404# The verdict discipline: no verdict was produced, so nothing here says `is_valid`.assert "is_valid" not in bodydiff --git a/api/tests/unit/test_method_requirements_refusal.py b/api/tests/unit/test_method_requirements_refusal.pyindex f961c4dcc..e9ab12107 100644--- a/api/tests/unit/test_method_requirements_refusal.py+++ b/api/tests/unit/test_method_requirements_refusal.py@@ -13,10 +13,12 @@ from collections.abc import Callable, Generator, Mapping, Sequencefrom pathlib import Pathimport pytest-from fastapi import FastAPI+from fastapi import Depends, FastAPIfrom fastapi.testclient import TestClient-from pipelex.base_exceptions import DisclosureMode, ErrorReport+from mthds.protocol.problem.registry import CoreCodefrom pipelex.config import get_config+from pipelex.errors.bundle_validation_failure import BundleValidationFailure+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.interpreter_hub import get_interpreter_hubfrom pipelex.libraries.exceptions import MethodRequirementsNotMetErrorfrom pipelex.pipe_run.delivery_assignment import DeliveryAssignment@@ -35,6 +37,7 @@ from pytest_mock import MockerFixturefrom pipelex_api.api_config import ApiConfigfrom pipelex_api.exception_handlers import register_exception_handlers+from pipelex_api.problem_view import mark_operator_requestfrom pipelex_api.routes import router as api_routerfrom tests.unit._constants import STUB_METHOD_ADDRESS@@ -115,7 +118,7 @@ class _UnreachableValidator:method_dir: Path | None, # noqa: ARG002methods_dirs: Sequence[Path] | None, # noqa: ARG002read_scope: str | None, # noqa: ARG002- ) -> ErrorReport:+ ) -> BundleValidationFailure:self.calls += 1msg = "A method refused for its requirements must not reach the validator."raise AssertionError(msg)@@ -148,15 +151,18 @@ def sandbox_hosted_mode_fixture(mocker: MockerFixture) -> Generator[None, None,pipe_func_config.execution_mode = previous-def _build_client(mocker: MockerFixture, *, orchestrator: _RecordingOrchestrator, validator: _UnreachableValidator) -> TestClient:+def _build_client(+ mocker: MockerFixture, *, orchestrator: _RecordingOrchestrator, validator: _UnreachableValidator, as_operator: bool = False+) -> TestClient:+ """The routes behind the production handlers; `as_operator` marks each request as the operator's, who reads `diagnostics`."""mocker.patch(f"{_PIPELINE_NS}.get_api_config", return_value=ApiConfig(orchestration_mode="temporal", allow_request_orchestration_mode_override=False))mocker.patch(f"{_PIPELINE_NS}.get_orchestrator_registry", return_value=OrchestratorRegistry({"temporal": orchestrator}))mocker.patch(f"{_PIPELINE_NS}.get_bundle_validator_registry", return_value=BundleValidatorRegistry({"temporal": validator}))app = FastAPI()- app.include_router(api_router, prefix="/v1")- register_exception_handlers(app, disclosure_mode=DisclosureMode.STRICT)+ app.include_router(api_router, prefix="/v1", dependencies=[Depends(mark_operator_request)] if as_operator else [])+ register_exception_handlers(app)return TestClient(app)@@ -164,7 +170,7 @@ class TestMethodRequirementsRefusal:@pytest.mark.usefixtures("sandbox_hosted_mode")def test_a_run_whose_requirements_the_sandbox_does_not_meet_is_refused_before_dispatch(self, mocker: MockerFixture) -> None:orchestrator = _RecordingOrchestrator()- client = _build_client(mocker, orchestrator=orchestrator, validator=_UnreachableValidator())+ client = _build_client(mocker, orchestrator=orchestrator, validator=_UnreachableValidator(), as_operator=True)files = {"main.mthds": _PIPE_FUNC_MTHDS, "funcs/pipe_func.py": _PIPE_FUNC_PY, "requirements.txt": "pandas>=2\npandas>=3\npolars\n"}response = client.post("/v1/start", json={"files": files, "inputs": {"data": "1,2,3"}})@@ -172,27 +178,31 @@ class TestMethodRequirementsRefusal:assert response.status_code == 422, response.textassert response.headers["content-type"].startswith("application/problem+json")body = response.json()- assert body["error_type"] == "MethodRequirementsNotMetError"- # Caller-facing under STRICT disclosure: it names each package and the sandbox, and no directory of the runner.- assert "line 2 'pandas>=3' (pandas 2.2.3 is there); line 3 'polars' (polars is missing)" in body["detail"]- assert body["detail"].startswith(f"The method needs Python packages that {_SANDBOX_ENVIRONMENT} does not have")- assert "rooted at" not in body["detail"]+ assert body["code"] == CoreCode.METHOD_DEPENDENCY_MISSING+ assert body["domain"] == "method"+ assert body["diagnostics"]["error_class"] == "MethodRequirementsNotMetError"+ # The refusal names each package and the sandbox, and no directory of the runner.+ message = body["diagnostics"]["message"]+ assert "line 2 'pandas>=3' (pandas 2.2.3 is there); line 3 'polars' (polars is missing)" in message+ assert message.startswith(f"The method needs Python packages that {_SANDBOX_ENVIRONMENT} does not have")+ assert "rooted at" not in messageassert orchestrator.dispatches == []@pytest.mark.usefixtures("sandbox_hosted_mode")def test_a_run_whose_requirements_the_deployment_refuses_carries_its_reason_before_dispatch(self, mocker: MockerFixture) -> None:orchestrator = _RecordingOrchestrator()- client = _build_client(mocker, orchestrator=orchestrator, validator=_UnreachableValidator())+ client = _build_client(mocker, orchestrator=orchestrator, validator=_UnreachableValidator(), as_operator=True)files = {"main.mthds": _PIPE_FUNC_MTHDS, "funcs/pipe_func.py": _PIPE_FUNC_PY, "requirements.txt": f"{_UNRESOLVABLE_REQUIREMENT}\n"}response = client.post("/v1/start", json={"files": files, "inputs": {"data": "1,2,3"}})assert response.status_code == 422, response.textbody = response.json()- assert body["error_type"] == "MethodRequirementsNotMetError"- # Caller-facing under STRICT disclosure: the deployment's own reason, and no directory of the runner.+ assert body["code"] == CoreCode.METHOD_DEPENDENCY_MISSING+ assert body["diagnostics"]["error_class"] == "MethodRequirementsNotMetError"+ # The deployment's own reason, and no directory of the runner.assert (- body["detail"]+ body["diagnostics"]["message"]== f"The method needs Python packages that the Daytona sandbox cannot offer, as its requirements.txt declares: {_REFUSAL_REASON}")assert orchestrator.dispatches == []@@ -211,15 +221,16 @@ class TestMethodRequirementsRefusal:@pytest.mark.usefixtures("sandbox_hosted_mode")def test_a_refused_requirements_line_refuses_the_run(self, mocker: MockerFixture) -> None:orchestrator = _RecordingOrchestrator()- client = _build_client(mocker, orchestrator=orchestrator, validator=_UnreachableValidator())+ client = _build_client(mocker, orchestrator=orchestrator, validator=_UnreachableValidator(), as_operator=True)files = {"main.mthds": _PIPE_FUNC_MTHDS, "funcs/pipe_func.py": _PIPE_FUNC_PY, "requirements.txt": "-r base.txt\n"}response = client.post("/v1/start", json={"files": files, "inputs": {"data": "1,2,3"}})assert response.status_code == 422, response.textbody = response.json()- assert body["error_type"] == "MethodRequirementsFileError"- assert "line 1 '-r base.txt'" in body["detail"]+ assert body["code"] == CoreCode.METHOD_PACKAGE_INVALID+ assert body["diagnostics"]["error_class"] == "MethodRequirementsFileError"+ assert "line 1 '-r base.txt'" in body["diagnostics"]["message"]assert orchestrator.dispatches == []@pytest.mark.usefixtures("sandbox_hosted_mode")@@ -283,8 +294,12 @@ class TestMethodRequirementsRefusal:assert response.status_code == 500, response.textbody = response.json()- assert body["error_type"] == "HostLibraryRequirementsError"- assert body["error_domain"] == "config"+ # The deployment's own configuration: the caller reads the operator domain and is told to report it.+ assert body["code"] == PipelexErrorCode.CONFIG_INVALID+ assert body["domain"] == "operator"+ assert body["next_step"]["kind"] == "report"+ # Withheld from the caller: nothing of the host's paths, interpreter or packages reaches its view.+ assert "diagnostics" not in bodyfor host_detail in (str(tmp_path), sys.executable, _ABSENT_PACKAGE):assert host_detail not in response.text, host_detailassert orchestrator.dispatches == []diff --git a/api/tests/unit/test_method_tree_runs.py b/api/tests/unit/test_method_tree_runs.pyindex 2f4d6cb24..3e3885fc9 100644--- a/api/tests/unit/test_method_tree_runs.py+++ b/api/tests/unit/test_method_tree_runs.py@@ -14,14 +14,16 @@ from pathlib import Pathfrom typing import Anyimport pytest-from fastapi import FastAPI+from fastapi import Depends, FastAPIfrom fastapi.testclient import TestClientfrom mthds.method_tree.digest import sha256_hex+from mthds.protocol.problem.registry import CoreCodefrom pipelex.config import get_configfrom pytest_mock import MockerFixturefrom pipelex_api.api_config import ApiConfigfrom pipelex_api.exception_handlers import register_exception_handlers+from pipelex_api.problem_view import mark_operator_requestfrom pipelex_api.routes import router as api_routerfrom pipelex_api.routes.blob_upload import router as blob_upload_router@@ -66,12 +68,13 @@ def sandbox_hosted_mode_fixture() -> Generator[None, None, None]:pipe_func_config.execution_mode = previous-def _build_client(mocker: MockerFixture) -> TestClient:+def _build_client(mocker: MockerFixture, *, as_operator: bool = False) -> TestClient:+ """The routes behind the production handlers; `as_operator` marks each request as the operator's, who reads `diagnostics`."""mocker.patch(f"{_PIPELINE_NS}.get_api_config", return_value=ApiConfig(orchestration_mode="direct", allow_request_orchestration_mode_override=False))app = FastAPI()- app.include_router(api_router, prefix="/v1")+ app.include_router(api_router, prefix="/v1", dependencies=[Depends(mark_operator_request)] if as_operator else [])app.include_router(blob_upload_router, prefix="/v1")register_exception_handlers(app)return TestClient(app)@@ -97,6 +100,12 @@ def _run_output(body: dict[str, Any]) -> str:return json.dumps(body["pipe_output"]["working_memory"])+def _error_files(problem: dict[str, Any]) -> list[tuple[str, int | None, int | None]]:+ """The file, line and column each item of an invalid method's problem is located at."""+ assert problem["code"] == CoreCode.METHOD_INVALID, problem+ return [(item["location"]["file"], item["location"].get("line"), item["location"].get("column")) for item in problem["errors"]]++def _assert_no_host_path(body: Any) -> None:dump = json.dumps(body)assert "pipelex-method-" not in dump@@ -178,8 +187,8 @@ class TestMethodTreeRuns:assert response.status_code == 422, response.textbody = response.json()- assert body["error_type"] == "ValidateBundleError"- assert {item["source"] for item in body["validation_errors"]} == {"methods/broken.mthds"}+ assert body["domain"] == "method"+ assert {file for file, _, _ in _error_files(body)} == {"methods/broken.mthds"}_assert_no_host_path(body)def test_validate_a_method_tree_sent_as_files(self, mocker: MockerFixture) -> None:@@ -241,7 +250,8 @@ class TestMethodTreeRuns:for response in (inline, beside_a_tree):assert response.status_code == 422, response.text- assert response.json()["error_type"] == "WrongScalarKindError"+ assert response.json()["code"] == CoreCode.INPUT_INVALID+ assert response.json()["domain"] == "input"assert inside_the_tree.status_code == 422, inside_the_tree.textassert inside_the_tree.json()["error_type"] == "InvalidMethodFiles"@@ -256,7 +266,7 @@ class TestMethodTreeRuns:assert response.json()["is_valid"] is True, response.textdef test_a_bundle_that_is_not_utf8_text_is_the_callers_located_diagnostic(self, mocker: MockerFixture) -> None:- client = _build_client(mocker)+ client = _build_client(mocker, as_operator=True)files = {"greet.mthds": _GREET_MTHDS, "bad.mthds": {"base64": "/w=="}}run = client.post("/v1/execute", json={"files": files, "pipe_code": "greeting.greet", "inputs": {"text": "x"}})@@ -264,12 +274,12 @@ class TestMethodTreeRuns:validated = client.post("/v1/validate", json={"files": files})assert run.status_code == 422, run.text- assert run.json()["error_type"] == "ValidateBundleError"- assert [(item["source"], item["line"], item["column"]) for item in run.json()["validation_errors"]] == [("bad.mthds", 1, 1)]+ assert _error_files(run.json()) == [("bad.mthds", 1, 1)]assert run_from_the_entry.status_code == 422, run_from_the_entry.text- assert 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"]+ entry_problem = run_from_the_entry.json()+ assert entry_problem["code"] == CoreCode.METHOD_SYNTAX+ assert entry_problem["diagnostics"]["error_class"] == "MethodEntryError"+ assert "'bad.mthds'" in entry_problem["diagnostics"]["message"]assert validated.status_code == 200, validated.textverdict = validated.json()assert verdict["is_valid"] is Falsediff --git a/api/tests/unit/test_openapi_contract.py b/api/tests/unit/test_openapi_contract.pyindex b44bff206..ccdd5e208 100644--- a/api/tests/unit/test_openapi_contract.py+++ b/api/tests/unit/test_openapi_contract.py@@ -173,15 +173,25 @@ class TestOpenApiErrorContract:rate_limited = openapi_schema["paths"]["/v1/execute"]["post"]["responses"]["429"]assert "Retry-After" in rate_limited["headers"]- def test_problem_document_carries_the_structured_validation_errors(self, openapi_schema: dict[str, Any]):- """A problem document publishes `validation_errors[]` of the SAME `ValidationErrorItem`- the 200 invalid arms publish — so `suggested_fix` reaches every surface that carries the- items, and the two can never drift into separate schemas.+ def test_problem_document_items_carry_the_standard_s_suggested_fix(self, openapi_schema: dict[str, Any]):+ """A problem document publishes `errors[]` of the standard's `ProblemItem`, whose fix is the standard's+ `ProblemSuggestedFix` (naming its file `file`), while a 200 invalid arm's `ValidationErrorItem` keeps Pipelex's+ `SuggestedFix` (naming it `source`): each under its own name, never a module-qualified one."""schemas = openapi_schema["components"]["schemas"]- validation_errors = schemas["ProblemDocument"]["properties"]["validation_errors"]- item_refs = [option["items"]["$ref"] for option in validation_errors["anyOf"] if option.get("type") == "array"]- assert item_refs == ["#/components/schemas/ValidationErrorItem"]+ assert "validation_errors" not in schemas["ProblemDocument"]["properties"]+ errors = schemas["ProblemDocument"]["properties"]["errors"]+ item_refs = [option["items"]["$ref"] for option in errors["anyOf"] if option.get("type") == "array"]+ assert item_refs == ["#/components/schemas/ProblemItem"]++ def _fix_refs(item_schema: str) -> list[str]:+ return [option["$ref"] for option in schemas[item_schema]["properties"]["suggested_fix"]["anyOf"] if "$ref" in option]++ assert _fix_refs("ProblemItem") == ["#/components/schemas/ProblemSuggestedFix"]+ assert _fix_refs("ValidationErrorItem") == ["#/components/schemas/SuggestedFix"]+ assert "file" in schemas["ProblemSuggestedFix"]["properties"]+ assert "source" in schemas["SuggestedFix"]["properties"]+ assert not [name for name in schemas if "__" in name]def test_suggested_fix_surface_is_published(self, openapi_schema: dict[str, Any]):"""The codegen fix planner's output is part of the published contract: a `ValidationErrorItem`diff --git a/api/tests/unit/test_pipe_io_route.py b/api/tests/unit/test_pipe_io_route.pyindex d18175452..6a9738c20 100644--- a/api/tests/unit/test_pipe_io_route.py+++ b/api/tests/unit/test_pipe_io_route.py@@ -16,14 +16,17 @@ from pathlib import Pathfrom typing import Anyimport pytest-from fastapi import FastAPI+from fastapi import Depends, FastAPIfrom fastapi.testclient import TestClient+from mthds.protocol.problem.registry import CoreCode+from pipelex.errors.problem import ProblemView, make_problemfrom pipelex.interpreter_hub import get_library_managerfrom pipelex.pipeline.exceptions import PipeIOContractErrorfrom pytest_mock import MockerFixturefrom pipelex_api.exception_handlers import register_exception_handlersfrom pipelex_api.limits import MAX_PIPE_CODE_LEN+from pipelex_api.problem_view import mark_operator_requestfrom pipelex_api.routes import router as api_routerfrom tests.unit._constants import (COLLIDING_ECHO_LIST_MTHDS,@@ -50,11 +53,9 @@ STUB_METHOD_REF = f"{STUB_METHOD_ADDRESS}@v0.1.0"# The three artifact maps the valid arm carries, sharing one key set.ARTIFACT_FIELDS = ("pipe_io_contracts", "input_form", "output_form")-# The `error_type`s of a no-verdict 422: a malformed request, and the two pipe-selection refusals,-# which carry the pipelex entry-lookup class names the run routes answer for the same failure.+# The `error_type` of a malformed request's 422, which the API authors itself; a pipe-selection refusal is the+# runtime's, answered under its registry code.REQUEST_SHAPE_ERROR = "ValidationError"-PIPE_NOT_FOUND_ERROR = "EntryPipeNotFoundError"-PIPE_AMBIGUOUS_ERROR = "EntryPipeAmbiguousError"# A `files` member that is no method tree, refused by the standard's reader as on `/v1/validate`.INVALID_METHOD_FILES_ERROR = "InvalidMethodFiles"@@ -62,9 +63,10 @@ INVALID_METHOD_FILES_ERROR = "InvalidMethodFiles"VALID_ARM_ONLY_FIELDS = ("pipe_ref", "default_pipe_ref", *ARTIFACT_FIELDS, "pending_signatures", "is_runnable", "files")-def _build_client() -> TestClient:+def _build_client(*, as_operator: bool = False) -> TestClient:+ """The routes behind the production handlers; `as_operator` marks each request as the operator's, who reads `diagnostics`."""app = FastAPI()- app.include_router(api_router, prefix="/v1")+ app.include_router(api_router, prefix="/v1", dependencies=[Depends(mark_operator_request)] if as_operator else [])register_exception_handlers(app)return TestClient(app)@@ -89,7 +91,7 @@ def _assert_keys(body: dict[str, Any], expected: set[str]) -> None:def _assert_input_422(response: Any, *, error_type: str) -> str:- """Assert a no-verdict input 422 of the given `error_type`, and return its detail."""+ """Assert an API-authored no-verdict input 422 of the given `error_type`, and return its detail."""assert response.status_code == 422, response.textassert response.headers["content-type"] == "application/problem+json"problem = response.json()@@ -100,6 +102,21 @@ def _assert_input_422(response: Any, *, error_type: str) -> str:return detail+def _assert_selection_refusal(response: Any, *, code: CoreCode, params: dict[str, Any]) -> dict[str, Any]:+ """Assert a no-verdict selection 422 is the problem of `code`, its sentences rendered from `params`, and return it.++ The response is compared whole with the problem the registry builds for the code and the parameters, in the view of+ the request's reader, so a missing parameter shows as the sentence it could not render.+ """+ assert response.status_code == 422, response.text+ assert response.headers["content-type"] == "application/problem+json"+ problem: dict[str, Any] = response.json()+ view = ProblemView.OPERATOR if "diagnostics" in problem else ProblemView.CALLER+ expected = make_problem(code=code, view=view, params=params).model_copy(update={"status": 422}).to_wire()+ assert {member: value for member, value in problem.items() if member != "diagnostics"} == expected+ return problem++class TestPipeIoRoute:def test_one_pipe_by_default(self):client = _build_client()@@ -224,26 +241,35 @@ class TestPipeIoRoute:assert body["pipe_ref"] is Noneassert body["default_pipe_ref"] is None_assert_keys(body, {"other.shout"})- response = client.post(PIPE_IO_PATH, json={"method_ref": STUB_METHOD_REF})- detail = _assert_input_422(response, error_type=PIPE_NOT_FOUND_ERROR)+ response = _build_client(as_operator=True).post(PIPE_IO_PATH, json={"method_ref": STUB_METHOD_REF})# 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 detail- assert "not found" in detail+ problem = _assert_selection_refusal(response, code=CoreCode.METHOD_PIPE_UNRESOLVED, params={"missing": "echo"})+ assert problem["domain"] == "method"+ assert problem["diagnostics"]["error_class"] == "EntryPipeNotFoundError"+ message = problem["diagnostics"]["message"]+ assert "manifest" in message+ assert "not found" in messagedef test_an_ambiguous_manifest_main_pipe_says_ambiguous(self, install_method_package: Callable[..., Path]):# The manifest names `echo`, declared by both `smoke` and `twin`: the selection refuses it as# 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()+ client = _build_client(as_operator=True)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 detail- assert "several domains" in detail- assert "smoke.echo" in detail- assert "twin.echo" in detail- assert "not found" not in detail, f"an ambiguous selector must not read as a missing pipe: {detail}"+ # The author's manifest names a pipe that exists twice: an ambiguous reference of the method, never a missing pipe.+ problem = _assert_selection_refusal(+ response, code=CoreCode.METHOD_REF_AMBIGUOUS, params={"ref": "echo", "candidates": ["smoke.echo", "twin.echo"]}+ )+ assert problem["domain"] == "method"+ assert problem["detail"] == "The reference 'echo' matches several declarations: smoke.echo, twin.echo."+ assert "does not exist" not in problem["title"]+ assert problem["diagnostics"]["error_class"] == "EntryPipeAmbiguousError"+ message = problem["diagnostics"]["message"]+ assert "manifest" in message+ assert "several domains" in message+ assert "smoke.echo" in message+ assert "twin.echo" in message+ assert "not found" not in message, f"an ambiguous selector must not read as a missing pipe: {message}"body = _valid_arm(client, {"method_ref": STUB_METHOD_REF, "all_pipes": True})assert body["pipe_ref"] is Noneassert body["default_pipe_ref"] is None@@ -253,13 +279,12 @@ class TestPipeIoRoute:client = _build_client()payload = {"files": _files(VALID_MTHDS, COLLIDING_ECHO_LIST_MTHDS), "pipe_ref": "echo", "all_pipes": all_pipes}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 detail- assert "several domains" in detail- assert "smoke.echo" in detail- assert "twin.echo" in detail- assert "not found" not in detail, f"an ambiguous selector must not read as a missing pipe: {detail}"+ # The caller reads which pipes its selector matched, in the code's own sentence.+ problem = _assert_selection_refusal(+ response, code=CoreCode.REQUEST_PIPE_AMBIGUOUS, params={"pipe": "echo", "candidates": ["smoke.echo", "twin.echo"]}+ )+ assert "smoke.echo" in problem["detail"]+ assert "twin.echo" in problem["detail"]def test_runnability_facts_match_validate(self):client = _build_client()@@ -322,7 +347,11 @@ class TestPipeIoRoute:assert named["default_pipe_ref"] is Noneunnamed = client.post(PIPE_IO_PATH, json={"files": files, "all_pipes": all_pipes})- _assert_input_422(unnamed, error_type="MethodEntryError")+ assert unnamed.status_code == 422, unnamed.text+ assert unnamed.headers["content-type"] == "application/problem+json"+ problem = unnamed.json()+ assert problem["code"] == CoreCode.METHOD_PACKAGE_INVALID, unnamed.text+ assert "is_valid" not in problem@pytest.mark.parametrize("request_fields",@@ -347,60 +376,64 @@ class TestPipeIoRoute:assert field_name not in body, f"the invalid arm never carries `{field_name}`"@pytest.mark.parametrize(- ("contents", "request_fields", "refusal", "detail_fragment", "fix_fragment"),+ ("contents", "request_fields", "code", "params", "operator_reads"),[pytest.param((VALID_MTHDS,),{"pipe_ref": "smoke.not_a_pipe"},- (PIPE_NOT_FOUND_ERROR, "request.pipe_not_found"),- "not found",- "Check the pipe code",+ CoreCode.REQUEST_PIPE_NOT_FOUND,+ {"pipe": "smoke.not_a_pipe"},+ ("EntryPipeNotFoundError", "not found"),id="unknown-ref",),pytest.param((VALID_MTHDS,),{"pipe_ref": "smoke.not_a_pipe", "all_pipes": True},- (PIPE_NOT_FOUND_ERROR, "request.pipe_not_found"),- "not found",- "Check the pipe code",+ CoreCode.REQUEST_PIPE_NOT_FOUND,+ {"pipe": "smoke.not_a_pipe"},+ ("EntryPipeNotFoundError", "not found"),id="unknown-ref-under-all-pipes",),pytest.param((NO_MAIN_PIPE_MTHDS,),{},- (PIPE_NOT_FOUND_ERROR, "request.pipe_unspecified"),- "declares no `main_pipe`",- "Send a `pipe_ref` naming the pipe to select",+ CoreCode.REQUEST_PIPE_UNSPECIFIED,+ {},+ ("EntryPipeNotFoundError", "declares no `main_pipe`"),id="no-entry-pipe",),pytest.param((VALID_MTHDS, SECOND_MAIN_PIPE_MTHDS),{},- (PIPE_AMBIGUOUS_ERROR, "request.pipe_ambiguous"),- "several `main_pipe`s",- "one of the declared `main_pipe`s",+ # No selector to name: the caller is told to pick one of the declared entry pipes.+ CoreCode.REQUEST_PIPE_UNSPECIFIED,+ {"candidates": ["other.shout", "smoke.echo"]},+ ("EntryPipeAmbiguousError", "several `main_pipe`s"),id="several-entry-pipes",),],)- def test_selection_refusals_carry_the_entry_lookup_error_type(- self, contents: tuple[str, ...], request_fields: dict[str, Any], refusal: tuple[str, str], detail_fragment: str, fix_fragment: str+ def test_selection_refusals_carry_their_code_and_params(+ self,+ contents: tuple[str, ...],+ request_fields: dict[str, Any],+ code: CoreCode,+ params: dict[str, Any],+ operator_reads: tuple[str, 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 = refusal- client = _build_client()+ # A selection refusal is an input 422 like a malformed request, but under the registry code that names the+ # miss, so a client branches on it: its `type` names the selection, its `params` the selector and the+ # candidates, and its step the fix for this very miss. The operator reads the entry-lookup class that refused+ # and its message, `operator_reads`.+ client = _build_client(as_operator=True)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 detail- problem = response.json()- assert problem["code"] == code+ problem = _assert_selection_refusal(response, code=code, params=params)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"]+ assert problem["next_step"]["kind"] == "change_input"+ entry_lookup_class, message_fragment = operator_reads+ assert problem["diagnostics"]["error_class"] == entry_lookup_class+ assert message_fragment in problem["diagnostics"]["message"]@pytest.mark.parametrize("payload",@@ -456,9 +489,7 @@ class TestPipeIoRoute:install_method_package(files={"documents.mthds": NO_MAIN_PIPE_MTHDS}, manifest_toml=STUB_METHOD_MANIFEST_NO_MAIN_PIPE)client = _build_client()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+ _assert_selection_refusal(response, code=CoreCode.REQUEST_PIPE_UNSPECIFIED, params={})@pytest.mark.parametrize(("contents", "request_fields"),diff --git a/api/tests/unit/test_pipeline_bundle.py b/api/tests/unit/test_pipeline_bundle.pyindex e47e9baa7..cc9c305cc 100644--- a/api/tests/unit/test_pipeline_bundle.py+++ b/api/tests/unit/test_pipeline_bundle.py@@ -17,12 +17,14 @@ from pathlib import Pathfrom typing import Anyimport pytest-from fastapi import FastAPI+from fastapi import Depends, FastAPIfrom fastapi.testclient import TestClient+from mthds.protocol.problem.registry import CoreCodefrom pipelex.pipeline.pipeline_response import PipelexRunResultStart, RunStatefrom pytest_mock import MockerFixturefrom pipelex_api.exception_handlers import register_exception_handlers+from pipelex_api.problem_view import mark_operator_requestfrom pipelex_api.routes.pipelex.pipeline import router as pipeline_routerfrom tests.unit._constants import (UNRESOLVED_PACKAGE_MTHDS,@@ -146,16 +148,17 @@ def _zip_b64_of_entries(entries: list[tuple[str, str]]) -> str:return base64.b64encode(buffer.getvalue()).decode("ascii")-def _build_client(mocker: MockerFixture) -> tuple[TestClient, dict[str, Any]]:+def _build_client(mocker: MockerFixture, *, as_operator: bool = False) -> tuple[TestClient, dict[str, Any]]:"""Wire an app whose ApiRunner is mocked and records what the run actually saw.The `snapshot` captures BOTH what the runner was asked to run — the`mthds_contents` and `pipe_code` passed to `execute`/`start` — and the`library_dirs` it was constructed with plus the files on disk at run time.Together they prove the tree was written whole and torn down after the request.+ `as_operator` marks each request as the operator's, whose view carries a refusal's own message in `diagnostics`."""app = FastAPI()- app.include_router(pipeline_router, prefix="/v1")+ app.include_router(pipeline_router, prefix="/v1", dependencies=[Depends(mark_operator_request)] if as_operator else [])register_exception_handlers(app)snapshot: dict[str, Any] = {}@@ -249,16 +252,20 @@ class TestPipelineBundle:assert snapshot["pipe_code"] == "echo"def test_a_tree_with_no_entry_pipe_and_no_pipe_code_is_refused(self, mocker: MockerFixture):- client, snapshot = _build_client(mocker)+ client, snapshot = _build_client(mocker, as_operator=True)files = {"a.mthds": VALID_MTHDS, "b.mthds": VALID_MTHDS.replace('domain = "smoke"', 'domain = "other"')}response = client.post("/v1/execute", json={"files": files, "inputs": {"text": "hi"}})assert response.status_code == 422, response.textproblem = response.json()- assert problem["error_type"] == "MethodEntryError"- assert "'a.mthds'" in problem["detail"]- assert "'b.mthds'" in problem["detail"]+ # Both bundles declare a main_pipe, so the run that names no pipe has several to start at, which it names.+ assert problem["code"] == CoreCode.REQUEST_PIPE_UNSPECIFIED+ assert problem["params"] == {"candidates": ["other.echo", "smoke.echo"]}+ assert problem["domain"] == "input"+ assert problem["diagnostics"]["error_class"] == "MethodEntryError"+ assert "'a.mthds'" in problem["diagnostics"]["message"]+ assert "'b.mthds'" in problem["diagnostics"]["message"]assert snapshot == {}, "the runner was reached"def test_no_bundle_passes_request_mthds_contents(self, mocker: MockerFixture):@@ -335,13 +342,16 @@ class TestPipelineBundle:assert snapshot == {}, "the runner was reached"def test_bundle_and_mthds_contents_are_mutually_exclusive(self, mocker: MockerFixture):- client, _ = _build_client(mocker)+ client, _ = _build_client(mocker, as_operator=True)response = client.post("/v1/execute",json={"files": {"main.mthds": VALID_MTHDS}, "mthds_contents": [VALID_MTHDS]},)assert response.status_code == 422- assert "mutually exclusive" in response.text+ problem = response.json()+ assert problem["code"] == CoreCode.REQUEST_INVALID+ assert problem.get("params") == {"field": "mthds_contents"}+ assert "mutually exclusive" in problem["diagnostics"]["message"]@pytest.mark.parametrize("transport", ["dependencies", "bundle_b64"])@pytest.mark.parametrize("path", ["/v1/execute", "/v1/start"])@@ -389,9 +399,10 @@ 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"]+ problem = response.json()+ assert problem["code"] == CoreCode.REQUEST_INVALID+ assert problem.get("params") == {"field": "dependencies"}+ assert problem["detail"] == "The request's field 'dependencies' does not match the route's schema."assert snapshot == {}, "the runner was reached"def test_a_bundle_shipping_no_package_gets_no_methods_dir(self, mocker: MockerFixture):diff --git a/api/tests/unit/test_problem_document.py b/api/tests/unit/test_problem_document.pyindex 4a3858872..1a492b04e 100644--- a/api/tests/unit/test_problem_document.py+++ b/api/tests/unit/test_problem_document.py@@ -1,111 +1,18 @@-"""Unit tests for the RFC 7807 problem-document builder."""+"""Unit tests for the problem document of an API-authored error.-import pytest-from mthds.protocol.problem.registry import CoreCode-from pipelex.base_exceptions import DisclosureMode, ErrorDomain, ErrorReport, PipelexConfigError-from pipelex.cogt.inference.error_classification import ProviderErrorMetadata, UserAction, UserActionKind-from pipelex.cogt.inference.provider_name import ProviderName-from pipelex.errors.error_codes import error_code_spec-from pipelex.errors.registry.pipelex_codes import PipelexErrorCode-from pipelex.system.exceptions import EnvVarNotFoundError-from pytest_mock import MockerFixture--from pipelex_api.error_types import ErrorType-from pipelex_api.problem_document import build_problem_document, build_problem_document_from_api_error+A `PipelexError` answers its own problem (`PipelexError.to_problem`), rendered by+`pipelex_api.exception_handlers.problem_response` and pinned in `test_exception_handlers.py` and+`test_problem_views.py`; this module covers only the document the API builds for its own 4xx and+5xx, which no `PipelexError` stands behind.+"""+from pipelex.base_exceptions import ErrorDomain-def _synthetic_llm_report() -> ErrorReport:- """A fully-populated report standing in for a provider rate-limit failure."""- report = ErrorReport.make_for_code(- code=CoreCode.PROVIDER_RATE_LIMITED,- error_type="LLMCompletionError",- message="OpenAI returned 429 (rate_limit_exceeded)",- user_action=UserAction(kind=UserActionKind.WAIT_AND_RETRY, detail="Retry after 12s."),- )- 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",- ),- }- )+from pipelex_api.error_types import ErrorType+from pipelex_api.problem_document import build_problem_document_from_api_error, with_request_contextclass TestProblemDocument:- def test_builds_from_config_error(self):- 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"] == 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"-- def test_builds_from_env_var_not_found_error(self):- # The original bug: /start with a required env var unset.- 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["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).title- assert "COMPLETION_CALLBACK_SECRET" in doc["detail"]- assert doc["error_type"] == "EnvVarNotFoundError"- assert doc["instance"] == "/v1/start"- assert doc["request_id"] == "REQ1"- # EnvVarNotFoundError is a ToolError that pipelex classifies under the- # config domain — a missing required env var is an operator-fixable- # misconfiguration, so it maps to HTTP 500 with error_domain "config".- assert doc["error_domain"] == "config"-- def test_builds_from_report_with_provider_metadata(self):- 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["code"] == "provider.rate_limited"- assert doc["type"] == "https://mthds.ai/errors/provider.rate_limited"- assert doc["title"] == error_code_spec(CoreCode.PROVIDER_RATE_LIMITED).title- assert doc["detail"] == "OpenAI returned 429 (rate_limit_exceeded)"- assert doc["error_type"] == "LLMCompletionError"- assert doc["error_category"] == "transient"- assert doc["error_domain"] == "runtime"- assert doc["retryable"] is True- assert doc["model"] == "gpt-4o-mini"- assert doc["provider"] == "openai"- assert doc["user_action"]["kind"] == "wait_and_retry"- assert doc["provider_metadata"]["status_code"] == 429- assert doc["provider_metadata"]["retry_after_seconds"] == 12.0- # 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 the- # redaction rules and tests them upstream.- report = PipelexConfigError("bad config").to_error_report()- spy = mocker.patch.object(ErrorReport, "to_problem_document", wraps=report.to_problem_document)- build_problem_document(report, instance="/x", request_id="r", disclosure_mode=disclosure_mode)- assert spy.call_args.kwargs["disclosure_mode"] is disclosure_mode-def test_api_error_variant_is_input_domain(self):doc = build_problem_document_from_api_error(ErrorType.VALIDATION_ERROR,@@ -114,22 +21,20 @@ class TestProblemDocument:instance="/v1/execute",request_id="REQ9",)- assert doc["type"] == "https://docs.pipelex.com/latest/errors/validation-error/"- assert doc["title"] == "Validation error"- assert doc["status"] == 422- assert doc["detail"] == "field 'pipe_code' is required"- assert doc["instance"] == "/v1/execute"- assert doc["request_id"] == "REQ9"- assert doc["error_type"] == "ValidationError"- assert doc["error_domain"] == "input"- # Every API-authored error is non-retryable: a caller mistake is not- # fixed by a blind retry. Carried as a uniform contract member so- # clients drive retry logic without branching on field presence.- assert doc["retryable"] is False- # Pipelex's `error_category` set is inference-domain; the API does not- # manufacture a category for a non-inference failure — same omission- # rule pipelex itself applies to `PipelexConfigError` etc.- assert "error_category" not in doc+ assert doc == {+ "type": "https://docs.pipelex.com/latest/errors/validation-error/",+ "title": "Validation error",+ "status": 422,+ "detail": "field 'pipe_code' is required",+ "instance": "/v1/execute",+ "request_id": "REQ9",+ "error_type": "ValidationError",+ "error_domain": "input",+ # Every API-authored error is non-retryable: a caller mistake is not fixed by a blind+ # retry. Carried as a uniform contract member so clients drive retry logic without+ # branching on field presence.+ "retryable": False,+ }def test_api_error_variant_config_domain_for_server_fault(self):# An API-owned 5xx (a missing secret, an unconfigured backend) classifies@@ -151,13 +56,6 @@ class TestProblemDocument:assert doc["retryable"] is Falsedef test_none_valued_fields_dropped(self):- report = EnvVarNotFoundError("missing X").to_error_report()- doc = build_problem_document(report, instance=None, request_id=None, disclosure_mode=DisclosureMode.VERBOSE)- assert None not in doc.values()- assert "instance" not in doc- assert "request_id" not in doc- assert "error_category" not in doc # never set on this report-api_doc = build_problem_document_from_api_error(ErrorType.BAD_REQUEST, "bad request", 400, instance=None, request_id=None)assert None not in api_doc.values()assert "instance" not in api_doc@@ -165,3 +63,21 @@ class TestProblemDocument:# `retryable` is a contract member, not a drop-on-None one — present# even when `instance`/`request_id` are absent.assert api_doc["retryable"] is False++ def test_request_context_is_stamped_on_a_copy(self):+ """The handler stamps the request's members on a copy, so the raised `ApiError` reads exactly as it was raised."""+ raised = build_problem_document_from_api_error(ErrorType.BAD_REQUEST, "bad request", 400, instance=None, request_id=None)+ before = dict(raised)++ stamped = with_request_context(raised, instance="/v1/start", request_id="REQ-STAMP")++ assert stamped == {**before, "instance": "/v1/start", "request_id": "REQ-STAMP"}+ assert raised == before++ def test_request_context_drops_none(self):+ raised = build_problem_document_from_api_error(ErrorType.BAD_REQUEST, "bad request", 400, instance=None, request_id=None)++ stamped = with_request_context(raised, instance=None, request_id=None)++ assert stamped == raised+ assert None not in stamped.values()diff --git a/api/tests/unit/test_problem_views.py b/api/tests/unit/test_problem_views.pynew file mode 100644index 000000000..28352ed06--- /dev/null+++ b/api/tests/unit/test_problem_views.py@@ -0,0 +1,268 @@+"""The view of a problem a response carries follows the identity the request's authentication established.++The operator, whoever runs this runner, reads the operator view, with `diagnostics`, the operator's next step and the+operator-only parameters; anyone else reads the caller view. The real authentication dependencies of+`pipelex_api.security` pick it here, each with synthetic credentials patched into the environment:++- `AUTH_MODE=api_key`: the static API key is the operator's own credential, so `verify_api_key` marks the request.+- `AUTH_MODE=none` with `TRUST_FORWARDED_IDENTITY_HEADERS=true`: `no_auth` marks a request the trusted proxy forwarded.+- `AUTH_MODE=jwt`, whose token names a caller, plain `AUTH_MODE=none`, and a request refused before any authentication+ ran read the caller view.++Every problem document the server emits, in either view, also holds no member written as `null`, at any depth.+"""++import os+from enum import StrEnum+from typing import Any, cast++import jwt+import pytest+from fastapi import APIRouter, Depends, FastAPI+from fastapi.testclient import TestClient+from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import PipelexConfigError, PipelexError+from pipelex.errors.problem import PipelexProblem, ProblemView+from pipelex.errors.registry.pipelex_codes import PipelexErrorCode+from pipelex.mthds_parsing.parser import MthdsParser+from pytest_mock import MockerFixture+from typing_extensions import override++from pipelex_api.exception_handlers import register_exception_handlers+from pipelex_api.middleware import RequestIdMiddleware+from pipelex_api.problem_view import mark_operator_request+from pipelex_api.security import ForwardedIdentityHeader, no_auth, verify_api_key, verify_jwt+from tests.unit.test_data import ProblemTestData, rate_limited_failure++_GATEWAY_CONFIG_MESSAGE = "the gateway config is missing"+_COMPONENT = "pipe_func_sandbox"+_TRUST_FORWARDED = "TRUST_FORWARDED_IDENTITY_HEADERS"+++class _Identity(StrEnum):+ """The identity a request authenticates as, one per authentication mode and trust setting."""++ API_KEY = "api_key"+ FORWARDED_IDENTITY = "forwarded_identity"+ JWT = "jwt"+ NO_AUTH = "no_auth"+++# Each identity's dependency, the environment it reads, and the view its requests read.+_IDENTITIES: dict[_Identity, tuple[Any, dict[str, str], ProblemView]] = {+ _Identity.API_KEY: (verify_api_key, {"API_KEY": ProblemTestData.SYNTHETIC_API_KEY}, ProblemView.OPERATOR),+ _Identity.FORWARDED_IDENTITY: (no_auth, {_TRUST_FORWARDED: "true"}, ProblemView.OPERATOR),+ _Identity.JWT: (verify_jwt, {"JWT_SECRET_KEY": ProblemTestData.SYNTHETIC_JWT_SECRET}, ProblemView.CALLER),+ _Identity.NO_AUTH: (no_auth, {}, ProblemView.CALLER),+}+++class _MisconfiguredComponentError(PipelexError):+ """A deployment's misconfigured component, whose name `runtime.misconfigured` declares an operator-only parameter."""++ error_code = CoreCode.RUNTIME_MISCONFIGURED+++class _RecoveredProblemError(PipelexError):+ """Carries a problem recovered across a transport boundary in the operator's view, which it reports as it is."""++ def __init__(self, message: str, *, problem: PipelexProblem):+ super().__init__(message)+ self.carried_problem = problem++ @override+ def recovered_problem(self) -> PipelexProblem | None:+ return self.carried_problem+++# Route handlers are deliberately not underscore-prefixed: a private,+# decorator-only function reads as unused to the type checker.+_router = APIRouter()+++@_router.get("/config-error")+async def config_error_route() -> None:+ raise PipelexConfigError(_GATEWAY_CONFIG_MESSAGE)+++@_router.get("/misconfigured")+async def misconfigured_route() -> None:+ msg = "the PipeFunc sandbox states no package set"+ raise _MisconfiguredComponentError(msg).with_params(component=_COMPONENT)+++@_router.get("/llm-error")+async def llm_error_route() -> None:+ raise rate_limited_failure()+++@_router.get("/invalid-method")+async def invalid_method_route() -> None:+ MthdsParser.make_pipelex_bundle_blueprint(mthds_content="this is not TOML !!!", mthds_source="bad.mthds")+++@_router.get("/unexpected-error")+async def unexpected_error_route() -> None:+ msg = "something nobody anticipated"+ raise RuntimeError(msg)+++@_router.get("/unknown-code")+async def unknown_code_route() -> None:+ msg = "a worker reported a code this server does not know"+ raise _RecoveredProblemError(msg, problem=PipelexProblem.model_validate(ProblemTestData.UNKNOWN_OPERATOR_PROBLEM))+++async def refuse_before_authentication() -> None:+ """A refusal that runs before the authentication dependency, so nothing has marked the request yet."""+ raise PipelexConfigError(_GATEWAY_CONFIG_MESSAGE)+++def _authenticated_client(mocker: MockerFixture, *, identity: _Identity, refuse_first: bool = False) -> tuple[TestClient, dict[str, str]]:+ """An app behind `identity`'s real dependency, with its synthetic environment, and the headers its credential travels in."""+ dependency, environment, _ = _IDENTITIES[identity]+ mocker.patch.dict(os.environ, environment)+ if _TRUST_FORWARDED not in environment:+ os.environ.pop(_TRUST_FORWARDED, None)+ headers: dict[str, str]+ match identity:+ case _Identity.API_KEY:+ headers = {"Authorization": f"Bearer {ProblemTestData.SYNTHETIC_API_KEY}"}+ case _Identity.FORWARDED_IDENTITY:+ headers = {ForwardedIdentityHeader.USER_ID: ProblemTestData.FORWARDED_USER_ID}+ case _Identity.JWT:+ token = jwt.encode({"user_id": ProblemTestData.JWT_USER_ID}, ProblemTestData.SYNTHETIC_JWT_SECRET, algorithm="HS256")+ headers = {"Authorization": f"Bearer {token}"}+ case _Identity.NO_AUTH:+ headers = {}+ dependencies = [Depends(refuse_before_authentication)] if refuse_first else []+ dependencies.append(Depends(dependency))+ app = FastAPI()+ app.include_router(_router, dependencies=dependencies)+ register_exception_handlers(app)+ return TestClient(app), headers+++def _marked_client(*, view: ProblemView) -> TestClient:+ """An app whose requests read `view`, marked as the authentication would, behind the request-id middleware."""+ app = FastAPI()+ match view:+ case ProblemView.OPERATOR:+ app.include_router(_router, dependencies=[Depends(mark_operator_request)])+ case ProblemView.CALLER:+ app.include_router(_router)+ register_exception_handlers(app)+ return TestClient(RequestIdMiddleware(app), raise_server_exceptions=False)+++def _null_paths(value: Any, *, path: str) -> list[str]:+ """The path of every member of `value`, at any depth, written as `null`."""+ if value is None:+ return [path]+ found: list[str] = []+ if isinstance(value, dict):+ for key, item in cast("dict[str, Any]", value).items():+ found.extend(_null_paths(item, path=f"{path}.{key}"))+ elif isinstance(value, list):+ for index, item in enumerate(cast("list[Any]", value)):+ found.extend(_null_paths(item, path=f"{path}[{index}]"))+ return found+++class TestProblemViews:+ @pytest.mark.parametrize("identity", list(_IDENTITIES))+ def test_the_view_follows_the_identity(self, mocker: MockerFixture, identity: _Identity) -> None:+ """An operator's fault: the operator reads its message and fixes the configuration, a caller reports it."""+ _, _, expected_view = _IDENTITIES[identity]+ client, headers = _authenticated_client(mocker, identity=identity)++ response = client.get("/config-error", headers=headers)++ assert response.status_code == 500+ body = response.json()+ assert body["code"] == PipelexErrorCode.CONFIG_INVALID+ assert body["domain"] == "operator"+ match expected_view:+ case ProblemView.OPERATOR:+ assert body["next_step"]["kind"] == "fix_configuration"+ assert body["diagnostics"]["error_class"] == "PipelexConfigError"+ assert body["diagnostics"]["message"] == _GATEWAY_CONFIG_MESSAGE+ case ProblemView.CALLER:+ assert body["next_step"]["kind"] == "report"+ assert "diagnostics" not in body+ assert _GATEWAY_CONFIG_MESSAGE not in response.text++ @pytest.mark.parametrize("identity", list(_IDENTITIES))+ def test_operator_only_params_ride_the_operator_view_alone(self, mocker: MockerFixture, identity: _Identity) -> None:+ _, _, expected_view = _IDENTITIES[identity]+ client, headers = _authenticated_client(mocker, identity=identity)++ response = client.get("/misconfigured", headers=headers)++ assert response.status_code == 500+ body = response.json()+ assert body["code"] == CoreCode.RUNTIME_MISCONFIGURED+ # The parameter is the operator's alone: never among the caller-visible `params`, whoever reads.+ assert "params" not in body+ match expected_view:+ case ProblemView.OPERATOR:+ assert body["diagnostics"]["params"] == {"component": _COMPONENT}+ case ProblemView.CALLER:+ assert "diagnostics" not in body+ assert _COMPONENT not in response.text++ def test_a_request_refused_before_authentication_reads_the_caller_view(self, mocker: MockerFixture) -> None:+ """The operator's own key, presented on a request refused before the key was checked, still reads the caller view."""+ client, headers = _authenticated_client(mocker, identity=_Identity.API_KEY, refuse_first=True)++ response = client.get("/config-error", headers=headers)++ assert response.status_code == 500+ body = response.json()+ assert body["code"] == PipelexErrorCode.CONFIG_INVALID+ assert body["next_step"]["kind"] == "report"+ assert "diagnostics" not in body+ assert _GATEWAY_CONFIG_MESSAGE not in response.text++ def test_a_refused_credential_marks_nothing(self, mocker: MockerFixture) -> None:+ """A wrong API key is refused with the API's own 401, which carries no diagnostics, and never reaches the route."""+ client, _ = _authenticated_client(mocker, identity=_Identity.API_KEY)++ response = client.get("/config-error", headers={"Authorization": "Bearer not-the-configured-key"})++ assert response.status_code == 401+ body = response.json()+ assert body["error_type"] == "InvalidToken"+ assert "diagnostics" not in body+ assert "code" not in body++ @pytest.mark.parametrize("identity", list(_IDENTITIES))+ def test_an_unknown_code_reaches_a_caller_without_the_operator_step(self, mocker: MockerFixture, identity: _Identity) -> None:+ """A recorded problem whose code this server does not know: its caller reads a generic step, never the operator's."""+ _, _, expected_view = _IDENTITIES[identity]+ client, headers = _authenticated_client(mocker, identity=identity)++ response = client.get("/unknown-code", headers=headers)++ assert response.status_code == 500+ body = response.json()+ assert body["code"] == ProblemTestData.UNKNOWN_OPERATOR_PROBLEM["code"]+ match expected_view:+ case ProblemView.OPERATOR:+ assert body["next_step"] == ProblemTestData.UNKNOWN_OPERATOR_PROBLEM["next_step"]+ assert body["diagnostics"]["error_class"] == "FutureSettingError"+ case ProblemView.CALLER:+ assert body["next_step"] == {"kind": "report", "detail": "Report this problem with its request id."}+ assert "diagnostics" not in body+ assert ProblemTestData.PRIVATE_HOST_FILE not in response.text++ @pytest.mark.parametrize("view", [ProblemView.OPERATOR, ProblemView.CALLER])+ @pytest.mark.parametrize("path", ["/config-error", "/misconfigured", "/llm-error", "/invalid-method", "/unexpected-error"])+ def test_no_problem_document_holds_a_null_member(self, view: ProblemView, path: str) -> None:+ response = _marked_client(view=view).get(path)++ assert response.status_code >= 400+ assert response.headers["content-type"] == "application/problem+json"+ body = response.json()+ assert body["code"]+ assert _null_paths(body, path="$") == []diff --git a/api/tests/unit/test_run_refusals.py b/api/tests/unit/test_run_refusals.pyindex 161ddd970..21c58baa2 100644--- a/api/tests/unit/test_run_refusals.py+++ b/api/tests/unit/test_run_refusals.py@@ -1,26 +1,27 @@"""What the run routes answer when the caller's own method refuses the run.-Two moments, both the caller's to fix, so both are a 422 that STRICT disclosure keeps readable:+Two moments, both the method's to fix, so both are a 422 whose caller view says everything needed to fix it:- **An invalid bundle is refused before any pipe runs, with the validation verdict.** A run loadsits bundle before it dispatches anything, and the runtime turns every refusal of that load into a- `ValidateBundleError` carrying the same located `validation_errors` validating the bundle gives,+ `method.invalid` problem whose `errors` are the same located faults validating the bundle gives,whatever check refused it: a misspelled concept used to escape as a 500, and an unknown model as araw model-choice error with no item. The orchestrator is a recording stub here, so the tests alsopin that nothing was dispatched.-- **A run that fails reports its root fault, located at the failing pipe.** The problem document's- `error_type`, `title` and `type` are the innermost Pipelex error's, never the run-level wrapper's,- and its `detail` names the failing pipe and its path from the entry pipe. This one runs the real- in-process orchestrator on a bundle whose pipes call no model, so it fails the same way whether- the run is live or dry.+- **A run that fails reports its root fault, located at the failing pipe.** The problem's `code`,+ `title` and `type` are the innermost fault's, never the run-level wrapper's, and its `location`+ names the failing pipe and its path from the entry pipe. This one runs the real in-process+ orchestrator on a bundle whose pipes call no model, so it fails the same way whether the run is+ live or dry."""from typing import Anyimport pytest-from fastapi import FastAPI+from fastapi import Depends, FastAPIfrom fastapi.testclient import TestClient-from pipelex.base_exceptions import DisclosureMode, ValidationErrorCategory+from mthds.protocol.problem.registry import CoreCode+from pipelex.errors.problem import ProblemViewfrom pipelex.pipe_run.delivery_assignment import DeliveryAssignmentfrom pipelex.pipe_run.pipe_job import PipeJobfrom pipelex.plugins.orchestrator_registry import OrchestratorRegistry@@ -29,6 +30,7 @@ from pytest_mock import MockerFixturefrom pipelex_api.api_config import ApiConfigfrom pipelex_api.exception_handlers import register_exception_handlers+from pipelex_api.problem_view import mark_operator_requestfrom pipelex_api.routes import router as api_routerfrom tests.unit._constants import MISMATCHED_PARALLEL_MTHDS, MISSPELLED_CONCEPT_MTHDS, UNKNOWN_MODEL_MTHDS@@ -54,21 +56,25 @@ class _RecordingOrchestrator:raise AssertionError(msg)-def _build_client(mocker: MockerFixture, *, disclosure_mode: DisclosureMode, orchestrator: _RecordingOrchestrator | None = None) -> TestClient:- """An app on the `direct` mode; `orchestrator` replaces the registered one when given."""+def _build_client(mocker: MockerFixture, *, view: ProblemView, orchestrator: _RecordingOrchestrator | None = None) -> TestClient:+ """An app on the `direct` mode answering in `view`; `orchestrator` replaces the registered one when given."""mocker.patch(f"{_PIPELINE_NS}.get_api_config", return_value=ApiConfig(orchestration_mode="direct", allow_request_orchestration_mode_override=False))if orchestrator is not None:mocker.patch(f"{_PIPELINE_NS}.get_orchestrator_registry", return_value=OrchestratorRegistry({"direct": orchestrator}))app = FastAPI()- app.include_router(api_router, prefix="/v1")- register_exception_handlers(app, disclosure_mode=disclosure_mode)+ match view:+ case ProblemView.OPERATOR:+ app.include_router(api_router, prefix="/v1", dependencies=[Depends(mark_operator_request)])+ case ProblemView.CALLER:+ app.include_router(api_router, prefix="/v1")+ register_exception_handlers(app)return TestClient(app)class TestRunRefusals:- @pytest.mark.parametrize("disclosure_mode", [DisclosureMode.VERBOSE, DisclosureMode.STRICT])+ @pytest.mark.parametrize("view", [ProblemView.OPERATOR, ProblemView.CALLER])@pytest.mark.parametrize("path", ["/v1/execute", "/v1/start"])@pytest.mark.parametrize(("mthds_content", "expected_item"),@@ -76,20 +82,19 @@ class TestRunRefusals:(MISSPELLED_CONCEPT_MTHDS,{- "error_type": "unresolved_concept",- "concept_code": "Summry",- "field_path": "pipe.echo.output",- "field_name": "output",+ "code": CoreCode.METHOD_CONCEPT_UNRESOLVED,+ "detail": "The method names the concept 'Summry', which no library declares.",+ "params": {"concept": "Summry"},+ "location": {"pipe": "echo", "field": "output"},},),(UNKNOWN_MODEL_MTHDS,{- "error_type": "unknown_model",- "model_reference": "no-such-model-in-any-deck",- "model_type": "llm",- "field_path": "pipe.echo.model",- "field_name": "model",+ "code": CoreCode.MODEL_UNKNOWN,+ "detail": "The method names the llm model 'no-such-model-in-any-deck', which no catalog knows.",+ "params": {"model": "no-such-model-in-any-deck", "model_type": "llm"},+ "location": {"pipe": "echo", "field": "model"},},),],@@ -98,55 +103,59 @@ class TestRunRefusals:def test_invalid_bundle_is_a_422_with_located_items(self,mocker: MockerFixture,- disclosure_mode: DisclosureMode,+ view: ProblemView,path: str,mthds_content: str,expected_item: dict[str, Any],):orchestrator = _RecordingOrchestrator()- client = _build_client(mocker, disclosure_mode=disclosure_mode, orchestrator=orchestrator)+ client = _build_client(mocker, view=view, orchestrator=orchestrator)response = client.post(path, json={"pipe_code": "echo", "mthds_contents": [mthds_content], "inputs": {"text": "hello"}})assert response.status_code == 422, response.textassert 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"]- assert len(items) == 1, items- item = items[0]- assert item["category"] == ValidationErrorCategory.PIPE_VALIDATION- assert item["pipe_code"] == "echo"- assert item["domain_code"] == "smoke"- for field_name, expected_value in expected_item.items():- assert item[field_name] == expected_value, item- # The verdict is the caller's own bundle: STRICT keeps the human summary, which is the item's message.- assert body["detail"] == item["message"]+ assert body["code"] == CoreCode.METHOD_INVALID+ assert body["domain"] == "method"+ assert body["next_step"]["kind"] == "change_method"+ # Each fault is an item with its own code, its own sentence and its place in the method, in either view.+ assert body["errors"] == [expected_item]+ match view:+ case ProblemView.OPERATOR:+ assert body["diagnostics"]["error_class"] == "ValidateBundleError"+ case ProblemView.CALLER:+ assert "diagnostics" not in body# Refused while the bundle loads: nothing reached the orchestrator.assert orchestrator.dispatches == []- @pytest.mark.parametrize("disclosure_mode", [DisclosureMode.VERBOSE, DisclosureMode.STRICT])- def test_run_failure_reports_its_root_fault_at_the_failing_pipe(self, mocker: MockerFixture, disclosure_mode: DisclosureMode):- client = _build_client(mocker, disclosure_mode=disclosure_mode)+ @pytest.mark.parametrize("view", [ProblemView.OPERATOR, ProblemView.CALLER])+ def test_run_failure_reports_its_root_fault_at_the_failing_pipe(self, mocker: MockerFixture, view: ProblemView):+ client = _build_client(mocker, view=view)response = client.post("/v1/execute", json={"mthds_contents": [MISMATCHED_PARALLEL_MTHDS], "inputs": {"topic": "tides"}})assert response.status_code == 422, response.textassert response.headers["content-type"].startswith("application/problem+json")body = response.json()- # The root fault's class, not the run-level `PipelineExecutionError` that wraps it.- assert body["error_type"] == "StuffFactoryError"- # The code names the fault: a branch's multiplicity is not its field's.- assert body["code"] == "pipe.output_multiplicity"+ # The code names the root fault, a branch's multiplicity that is not its field's, never the run-level wrapper.+ assert body["code"] == CoreCode.PIPE_OUTPUT_MULTIPLICITYassert 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.- assert body["detail"].startswith("Pipe 'analyze_topic' failed (review_topic → analyze_topic): "), body["detail"]+ assert body["domain"] == "method"+ assert body["detail"] == "Pipe 'analyze_topic' produced an output of the multiplicity 'single', but its output 'ideas' is declared 'list'."+ assert body["params"] == {"output": "ideas", "declared": "list", "produced": "single", "pipe": "analyze_topic"}+ # Located at the failing step, with its path from the entry pipe.+ assert body["location"] == {"pipe": "analyze_topic", "path": ["review_topic", "analyze_topic"]}# The next step says which of the two multiplicities to change.- assert body["user_action"]["kind"] == "change_input"- assert "Branch 'draft_idea' gives result 'ideas' as a single 'Idea'" in body["user_action"]["detail"]- assert "validation_errors" not in body+ assert body["next_step"] == {+ "kind": "change_method",+ "detail": "Declare the output 'ideas' as 'single', or make pipe 'analyze_topic' produce 'list'.",+ }+ assert "errors" not in body+ match view:+ case ProblemView.OPERATOR:+ # The root fault's class, not the run-level `PipelineExecutionError` that wraps it.+ assert body["diagnostics"]["error_class"] == "StuffFactoryError"+ assert "Branch 'draft_idea' gives result 'ideas' as a single 'Idea'" in body["diagnostics"]["message"]+ case ProblemView.CALLER:+ assert "diagnostics" not in bodydiff --git a/api/tests/unit/test_run_source_precondition.py b/api/tests/unit/test_run_source_precondition.pyindex 7531bb1a4..5fd4609d1 100644--- a/api/tests/unit/test_run_source_precondition.py+++ b/api/tests/unit/test_run_source_precondition.py@@ -15,26 +15,31 @@ because every assertion lands on a request-shape 422 raised during body parsing.from typing import Anyimport pytest-from fastapi import FastAPI+from fastapi import Depends, FastAPIfrom fastapi.testclient import TestClient+from mthds.protocol.problem.registry import CoreCode+from pipelex.errors.problem import ProblemView, make_problemfrom pipelex.pipeline.pipeline_response import PipelexRunResultStart, RunStatefrom pytest_mock import MockerFixturefrom pipelex_api.exception_handlers import register_exception_handlers+from pipelex_api.problem_view import mark_operator_requestfrom pipelex_api.routes.pipelex.pipeline import router as pipeline_routerfrom tests.unit._constants import VALID_MTHDS_BASE_PRECONDITION_FRAGMENT = "pipe_code and mthds_contents cannot both be empty"-def _build_client(mocker: MockerFixture) -> tuple[TestClient, Any]:+def _build_client(mocker: MockerFixture, *, as_operator: bool = False) -> tuple[TestClient, Any]:"""Wire a FastAPI app whose pipeline runner is fully mocked; return (client, runner_mock).The whole runner comes back rather than just `execute`, because `/v1/start` dispatchesthrough `runner.start`: a test that asserts only on `execute` pins nothing on that route.+ `as_operator` marks each request as the operator's, whose view carries the refusal's own message+ in `diagnostics`."""app = FastAPI()- app.include_router(pipeline_router, prefix="/v1")+ app.include_router(pipeline_router, prefix="/v1", dependencies=[Depends(mark_operator_request)] if as_operator else [])register_exception_handlers(app)fake_execute_response = mocker.MagicMock()@@ -57,6 +62,21 @@ def _build_client(mocker: MockerFixture) -> tuple[TestClient, Any]:return TestClient(app), fake_runner+def _assert_request_refusal(response: Any, *, code: CoreCode, params: dict[str, Any]) -> dict[str, Any]:+ """Assert a request-shape 422 under `code`, its caller sentences rendered from `params`, and return its body."""+ assert response.status_code == 422, response.text+ assert response.headers["content-type"] == "application/problem+json"+ problem: dict[str, Any] = response.json()+ caller_problem = make_problem(code=code, view=ProblemView.CALLER, params=params)+ assert problem["code"] == code+ assert problem["type"] == f"https://mthds.ai/errors/{code}"+ assert problem["status"] == 422+ assert problem["domain"] == "input"+ assert problem.get("params") == params+ assert problem["detail"] == caller_problem.detail+ return problem++class TestRunSourcePrecondition:"""A run source is required; extension args never waive it, and they are named when they are all the body has."""@@ -65,20 +85,17 @@ class TestRunSourcePrecondition:# The hosted catalog selector resolved on the platform and never crosses down to a# runner (Rule 3), so a body carrying it alone means a hosted client reached the# wrong deployment. The 422 must diagnose exactly that, by name.- client, runner = _build_client(mocker)+ client, runner = _build_client(mocker, as_operator=True)response = client.post(route, json={"method_id": "mt_abc123"})- assert response.status_code == 422- 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 detail- assert "not handled by this deployment" in detail- assert "hosted API" in detail+ # The runtime's own refusal of a field this runner does not take: `request.unsupported`, naming the field.+ problem = _assert_request_refusal(+ response, code=CoreCode.REQUEST_UNSUPPORTED, params={"field": "method_id", "reason": "hosted_only_extension"}+ )+ assert problem["diagnostics"]["error_class"] == "PipelexRequestError"+ message = problem["diagnostics"]["message"]+ assert "`method_id`" in message+ assert "not handled by this deployment" in message+ assert "hosted API" in message# The run never dispatched: this is a request-shape refusal, not a failed run.# Both dispatch methods are asserted because the two routes use different ones# (`/v1/execute` → `runner.execute`, `/v1/start` → `runner.start`).@@ -86,36 +103,37 @@ class TestRunSourcePrecondition:runner.start.assert_not_awaited()def test_every_unhandled_key_is_named_sorted(self, mocker: MockerFixture):- client, _ = _build_client(mocker)+ client, _ = _build_client(mocker, as_operator=True)response = client.post("/v1/execute", json={"method_id": "mt_abc123", "future_arg": "x"})- assert response.status_code == 422- detail = response.json()["detail"]- assert "`future_arg`, `method_id`" in detail+ # The caller's parameters name the first, the operator's message every one.+ problem = _assert_request_refusal(+ response, code=CoreCode.REQUEST_UNSUPPORTED, params={"field": "future_arg", "reason": "hosted_only_extension"}+ )+ assert "`future_arg`, `method_id`" in problem["diagnostics"]["message"]def test_empty_body_keeps_the_base_guidance(self, mocker: MockerFixture):# Nothing to name — the caller sent no extension at all, so the message stays the# one that explains what a run source IS.- client, _ = _build_client(mocker)+ client, _ = _build_client(mocker, as_operator=True)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 detail- assert "not handled by this deployment" not in detail+ problem = _assert_request_refusal(response, code=CoreCode.REQUEST_INVALID, params={"field": "pipe_code"})+ message = problem["diagnostics"]["message"]+ assert _BASE_PRECONDITION_FRAGMENT in message+ assert "not handled by this deployment" not in messagedef test_server_handled_extras_are_never_named_as_unhandled(self, mocker: MockerFixture):# `callback_urls` / `orchestration_mode` / `storage_scope` / `pipeline_run_id` ARE# handled here (`PipelineApiExtras`). A source-less body carrying only those is still# a 422, but naming them as unhandled would be a lie.- client, _ = _build_client(mocker)+ client, _ = _build_client(mocker, as_operator=True)response = client.post("/v1/start",json={"pipeline_run_id": "run-1", "callback_urls": ["https://example.com/hook"], "storage_scope": "tenant/run"},)- assert response.status_code == 422- detail = response.json()["detail"]- assert _BASE_PRECONDITION_FRAGMENT in detail- assert "not handled by this deployment" not in detail+ problem = _assert_request_refusal(response, code=CoreCode.REQUEST_INVALID, params={"field": "pipe_code"})+ message = problem["diagnostics"]["message"]+ assert _BASE_PRECONDITION_FRAGMENT in message+ assert "not handled by this deployment" not in message@pytest.mark.parametrize(("label", "body"),diff --git a/api/tests/unit/test_unresolved_package_reference.py b/api/tests/unit/test_unresolved_package_reference.pyindex 39c5d2f0d..5a3d12534 100644--- a/api/tests/unit/test_unresolved_package_reference.py+++ b/api/tests/unit/test_unresolved_package_reference.py@@ -1,8 +1,9 @@"""What the server answers when a bundle calls a method package that cannot be resolved.The reference is a property of the caller's content, so the answer is the verdict: `/v1/validate` answers `200` with-`is_valid: false`, and the run routes refuse the run with a `422` before anything is dispatched, both carrying one-`unresolved_package_dependency` item that names the reference as written. Fetch-on-miss is off and the installed+`is_valid: false` with one `unresolved_package_dependency` item that names the reference as written, and the run routes+refuse the run with a `method.invalid` `422` before anything is dispatched, its one `method.dependency_missing` item naming+the package. Fetch-on-miss is off and the installedstore is an empty temporary directory, so the refusal is deterministic and nothing reaches the network."""@@ -10,9 +11,11 @@ from pathlib import Pathfrom typing import Anyimport pytest-from fastapi import FastAPI+from fastapi import Depends, FastAPIfrom fastapi.testclient import TestClient-from pipelex.base_exceptions import DisclosureMode, ValidationErrorCategory+from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import ValidationErrorCategory+from pipelex.errors.problem import ProblemViewfrom pipelex.pipe_run.delivery_assignment import DeliveryAssignmentfrom pipelex.pipe_run.pipe_job import PipeJobfrom pipelex.plugins.orchestrator_registry import OrchestratorRegistry@@ -21,8 +24,9 @@ from pytest_mock import MockerFixturefrom pipelex_api.api_config import ApiConfigfrom pipelex_api.exception_handlers import register_exception_handlers+from pipelex_api.problem_view import mark_operator_requestfrom pipelex_api.routes import router as api_router-from tests.unit._constants import UNRESOLVED_PACKAGE_MTHDS, UNRESOLVED_PACKAGE_REFERENCE+from tests.unit._constants import UNRESOLVED_PACKAGE_MTHDS, UNRESOLVED_PACKAGE_REFERENCE, VENDORED_PROBE_ADDRESS_PIPELINE_NS = "pipelex_api.routes.pipelex.pipeline"@@ -46,9 +50,7 @@ class _RecordingOrchestrator:raise AssertionError(msg)-def _build_client(- mocker: MockerFixture, *, tmp_path: Path, disclosure_mode: DisclosureMode, orchestrator: _RecordingOrchestrator | None = None-) -> TestClient:+def _build_client(mocker: MockerFixture, *, tmp_path: Path, view: ProblemView, orchestrator: _RecordingOrchestrator | None = None) -> TestClient:mocker.patch("pipelex.cli.installed_methods.GLOBAL_METHODS_DIR", tmp_path / "global-methods")mocker.patch("pipelex.cli.installed_methods.PROJECT_METHODS_DIR", tmp_path / "project-methods")mocker.patch("pipelex.methods.fetch_on_miss.is_method_fetch_on_miss_enabled", return_value=False)@@ -58,8 +60,12 @@ def _build_client(if orchestrator is not None:mocker.patch(f"{_PIPELINE_NS}.get_orchestrator_registry", return_value=OrchestratorRegistry({"direct": orchestrator}))app = FastAPI()- app.include_router(api_router, prefix="/v1")- register_exception_handlers(app, disclosure_mode=disclosure_mode)+ match view:+ case ProblemView.OPERATOR:+ app.include_router(api_router, prefix="/v1", dependencies=[Depends(mark_operator_request)])+ case ProblemView.CALLER:+ app.include_router(api_router, prefix="/v1")+ register_exception_handlers(app)return TestClient(app)@@ -76,9 +82,9 @@ def _assert_the_package_item(items: list[dict[str, Any]]) -> None:class TestUnresolvedPackageReference:- @pytest.mark.parametrize("disclosure_mode", [DisclosureMode.VERBOSE, DisclosureMode.STRICT])- def test_validate_answers_the_invalid_verdict(self, mocker: MockerFixture, tmp_path: Path, disclosure_mode: DisclosureMode):- client = _build_client(mocker, tmp_path=tmp_path, disclosure_mode=disclosure_mode)+ @pytest.mark.parametrize("view", [ProblemView.OPERATOR, ProblemView.CALLER])+ def test_validate_answers_the_invalid_verdict(self, mocker: MockerFixture, tmp_path: Path, view: ProblemView):+ client = _build_client(mocker, tmp_path=tmp_path, view=view)response = client.post("/v1/validate", json={"mthds_contents": [UNRESOLVED_PACKAGE_MTHDS]})@@ -87,20 +93,27 @@ class TestUnresolvedPackageReference:assert body["is_valid"] is False_assert_the_package_item(body["validation_errors"])- @pytest.mark.parametrize("disclosure_mode", [DisclosureMode.VERBOSE, DisclosureMode.STRICT])+ @pytest.mark.parametrize("view", [ProblemView.OPERATOR, ProblemView.CALLER])@pytest.mark.parametrize("path", ["/v1/execute", "/v1/start"])- def test_a_run_is_refused_with_the_verdict(self, mocker: MockerFixture, tmp_path: Path, disclosure_mode: DisclosureMode, path: str):+ def test_a_run_is_refused_with_the_verdict(self, mocker: MockerFixture, tmp_path: Path, view: ProblemView, path: str):orchestrator = _RecordingOrchestrator()- client = _build_client(mocker, tmp_path=tmp_path, disclosure_mode=disclosure_mode, orchestrator=orchestrator)+ client = _build_client(mocker, tmp_path=tmp_path, view=view, orchestrator=orchestrator)response = client.post(path, json={"pipe_code": "echo", "mthds_contents": [UNRESOLVED_PACKAGE_MTHDS], "inputs": {"text": "hello"}})assert response.status_code == 422, response.textassert response.headers["content-type"].startswith("application/problem+json")body = response.json()- assert body["error_type"] == "ValidateBundleError"- assert body["error_domain"] == "input"- _assert_the_package_item(body["validation_errors"])- # The caller's own content: STRICT keeps the human summary, which is the item's message.- assert body["detail"] == body["validation_errors"][0]["message"]+ assert body["code"] == CoreCode.METHOD_INVALID+ assert body["domain"] == "method"+ (item,) = body["errors"]+ assert item["code"] == CoreCode.METHOD_DEPENDENCY_MISSING+ assert item["location"] == {"pipe": "echo", "field": "pipe.echo.steps[0].pipe"}+ # The caller reads which package the method calls and why it is not there, from the code's parameters.+ assert item.get("params") == {"kind": "package", "name": VENDORED_PROBE_ADDRESS, "reason": "not_found"}+ match view:+ case ProblemView.OPERATOR:+ assert body["diagnostics"]["error_class"] == "ValidateBundleError"+ case ProblemView.CALLER:+ assert "diagnostics" not in bodyassert orchestrator.dispatches == []diff --git a/api/tests/unit/test_validate_and_models_routes.py b/api/tests/unit/test_validate_and_models_routes.pyindex 8879519b3..7dd9fd304 100644--- a/api/tests/unit/test_validate_and_models_routes.py+++ b/api/tests/unit/test_validate_and_models_routes.py@@ -4,7 +4,9 @@ import pytestfrom fastapi import FastAPIfrom fastapi.testclient import TestClientfrom mthds.protocol.models import ModelCategory as MthdsModelCategory+from mthds.protocol.problem.registry import CoreCodefrom pipelex.cogt.models.model_listing import ModelCategory+from pipelex.errors.error_codes import error_code_specfrom pipelex.interpreter_hub import get_library_managerfrom pytest_mock import MockerFixture@@ -58,9 +60,10 @@ class TestValidateAndModelsRoutes:body = response.json()assert body["is_valid"] is Falseassert body["is_runnable"] is False- # The pipelex message is preserved (caller-facing under `_authors_caller_facing_message`) so- # the client gets the actual interpreter complaint, not a generic placeholder.- assert "TOML" in body["message"]+ # The verdict's message is the sentence its code renders, `method.invalid`'s; the interpreter's+ # actual complaint rides the item, so the client still reads what is wrong and where.+ assert body["message"] == error_code_spec(CoreCode.METHOD_INVALID).detail+ assert "TOML syntax error" in body["validation_errors"][0]["message"]# The diagnostics list is non-empty on every invalid arm — the structured-info invariant is# total. A raw TOML-syntax error is a parse-level failure the interpreter raises with no# categorized error-data, but the shared builder's last-resort residual still emits onediff --git a/api/tests/unit/test_validate_caller_identity.py b/api/tests/unit/test_validate_caller_identity.pyindex cfcf32bb4..da1fc8bf8 100644--- a/api/tests/unit/test_validate_caller_identity.py+++ b/api/tests/unit/test_validate_caller_identity.py@@ -20,7 +20,9 @@ import pytestfrom fastapi import FastAPI, Request, Responsefrom fastapi.testclient import TestClientfrom mthds.protocol.problem.registry import CoreCode-from pipelex.base_exceptions import ErrorReport, ValidationErrorCategory, ValidationErrorItem+from pipelex.base_exceptions import ValidationErrorCategory, ValidationErrorItem+from pipelex.errors.bundle_validation_failure import BundleValidationFailure+from pipelex.errors.problem import ProblemView, make_problemfrom pipelex.pipeline.validate_in_process import validate_bundles_in_processfrom pipelex.plugins.bundle_validator_registry import BundleValidatorRegistryfrom pipelex.system.caller_identity import CallerIdentity@@ -69,12 +71,10 @@ class _RecordingBundleValidator:method_dir: Path | None, # noqa: ARG002methods_dirs: Sequence[Path] | None, # noqa: ARG002read_scope: str | None, # noqa: ARG002- ) -> ErrorReport:+ ) -> BundleValidationFailure:self.caller_identities.append(caller_identity)- return ErrorReport.make_for_code(- code=CoreCode.METHOD_INVALID,- error_type="ValidateBundleError",- message="bundle is invalid",+ return BundleValidationFailure(+ problem=make_problem(code=CoreCode.METHOD_INVALID, view=ProblemView.OPERATOR),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 61d2b9965..fcc82d6e8 100644--- a/api/tests/unit/test_validate_dispatch.py+++ b/api/tests/unit/test_validate_dispatch.py@@ -3,8 +3,8 @@Pins the dispatch+route mapping independent of any real backend, with a stub validator registeredfor a non-direct mode (no `temporalio` import): the runner resolves the deployment's orchestration_mode,dispatches to the validator the registry holds for it, and the route maps the *returned* verdict —-an `ErrorReport` with validation diagnostics to a 200 `InvalidReport`, a returned backend fault report-to problem+json, and a raised fault to a 5xx. Also pins the no-validator case (`MissingBundleValidatorError`)+a `BundleValidationFailure` with validation items to a 200 `InvalidReport`, a returned failure with none+to the problem+json its code's status gives, and a raised fault to a 5xx. Also pins the no-validator case (`MissingBundleValidatorError`)and that the route threads `orchestration_mode` into the same override policy `/start` uses (a forbiddenoverride is a 403). The `direct` path is covered end-to-end by the existing `/validate` suite; this provesthe dispatch is backend-agnostic, not direct-only.@@ -18,7 +18,11 @@ import pytestfrom fastapi import FastAPIfrom fastapi.testclient import TestClientfrom mthds.protocol.problem.registry import CoreCode-from pipelex.base_exceptions import ErrorDomain, ErrorReport, PipelexConfigError, ValidationErrorCategory, ValidationErrorItem+from pipelex.base_exceptions import PipelexConfigError, ValidationErrorCategory, ValidationErrorItem+from pipelex.errors.bundle_validation_failure import BundleValidationFailure+from pipelex.errors.error_codes import error_code_spec+from pipelex.errors.problem import ProblemDiagnostics, ProblemView, make_problem+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.plugins.bundle_validator_registry import BundleValidatorRegistryfrom pipelex.runtime_bridge.exceptions import MissingBundleValidatorErrorfrom pipelex.system.caller_identity import CallerIdentity@@ -36,7 +40,7 @@ _PIPELINE_NS = "pipelex_api.routes.pipelex.pipeline"class _StubBundleValidator:"""A backend-agnostic stand-in validator: records its call, then returns or raises as configured."""- def __init__(self, *, verdict: ErrorReport | None = None, error: Exception | None = None) -> None:+ def __init__(self, *, verdict: BundleValidationFailure | None = None, error: Exception | None = None) -> None:self._verdict = verdictself._error = errorself.calls: list[dict[str, Any]] = []@@ -54,7 +58,7 @@ class _StubBundleValidator:method_dir: Path | None,methods_dirs: Sequence[Path] | None,read_scope: str | None,- ) -> ErrorReport:+ ) -> BundleValidationFailure:self.calls.append({"mthds_contents": mthds_contents,@@ -96,11 +100,9 @@ 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.make_for_code(- code=CoreCode.METHOD_INVALID,- error_type="ValidateBundleError",- message="bundle is invalid",+ """A non-direct validator's returned failure with items is mapped to a 200 InvalidReport, threading the request."""+ invalid_verdict = BundleValidationFailure(+ problem=make_problem(code=CoreCode.METHOD_INVALID, view=ProblemView.OPERATOR),validation_errors=[ValidationErrorItem(category=ValidationErrorCategory.BLUEPRINT_VALIDATION, message="bad ref")],)stub = _StubBundleValidator(verdict=invalid_verdict)@@ -112,7 +114,8 @@ class TestValidateDispatch:assert response.status_code == 200, response.textbody = response.json()assert body["is_valid"] is False- assert any(item["category"] == ValidationErrorCategory.BLUEPRINT_VALIDATION for item in body["validation_errors"])+ assert body["validation_errors"] == [{"category": ValidationErrorCategory.BLUEPRINT_VALIDATION, "message": "bad ref"}]+ assert body["message"] == error_code_spec(CoreCode.METHOD_INVALID).detail# The dispatch reached the registered non-direct validator, with the request threaded through.assert len(stub.calls) == 1assert stub.calls[0]["mthds_contents"] == [VALID_MTHDS]@@ -126,16 +129,24 @@ class TestValidateDispatch:client = _build_client()response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS]})- assert response.status_code >= 500, response.text+ # The deployment's own configuration: its code's 500, and in the caller's view nothing of its message.+ assert response.status_code == 500, response.textassert response.headers["content-type"].startswith("application/problem+json")- assert "is_valid" not in response.json()-- 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.make_for_code(- code=CoreCode.RUNTIME_UNAVAILABLE,- error_type="TemporalTransportError",- message="validator backend unavailable",+ body = response.json()+ assert body["code"] == PipelexErrorCode.CONFIG_INVALID+ assert body["domain"] == "operator"+ assert "is_valid" not in body+ assert "diagnostics" not in body+ assert "backend wiring fault" not in response.text++ def test_returned_failure_without_items_maps_to_its_codes_problem(self, mocker: MockerFixture) -> None:+ """A registry-backed validator can return a backend fault, not an invalid-bundle verdict: its code's status, in the caller's view."""+ backend_fault = BundleValidationFailure(+ problem=make_problem(+ code=CoreCode.RUNTIME_UNAVAILABLE,+ view=ProblemView.OPERATOR,+ diagnostics=ProblemDiagnostics(error_class="TemporalTransportError", message="validator backend unavailable"),+ ),)stub = _StubBundleValidator(verdict=backend_fault)_register_stub_for_temporal(mocker, stub)@@ -143,15 +154,18 @@ class TestValidateDispatch:client = _build_client()response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS]})- assert response.status_code == 500, response.text+ assert response.status_code == 503, 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.RUNTIME- assert body["status"] == 500+ assert body["code"] == CoreCode.RUNTIME_UNAVAILABLE+ assert body["status"] == 503+ assert body["retry"] == "yes"+ # Built in the operator's view by the validator, projected to the caller's by the route.+ assert "diagnostics" not in body+ assert "validator backend unavailable" not in response.textassert "is_valid" not in bodyassert "validation_errors" not in body+ assert "errors" not in body@pytest.mark.asyncioasync def test_missing_validator_for_resolved_mode_raises(self, mocker: MockerFixture) -> None:@@ -167,7 +181,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"+ assert exc_info.value.resolve_error_code() == PipelexErrorCode.PLUGIN_NOT_FOUNDdef 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_errors.py b/api/tests/unit/test_validate_errors.pyindex c7286003a..54d61f74b 100644--- a/api/tests/unit/test_validate_errors.py+++ b/api/tests/unit/test_validate_errors.py@@ -21,6 +21,7 @@ from typing import Anyfrom fastapi import FastAPIfrom fastapi.testclient import TestClient+from mthds.protocol.problem.registry import CoreCodefrom pipelex.base_exceptions import PipelexConfigError, ValidationErrorCategoryfrom pipelex.core.exceptions import (DryRunFailureErrorData,@@ -28,6 +29,8 @@ from pipelex.core.exceptions import (PipelexBundleBlueprintValidationErrorData,PipesAndConceptValidationErrorData,)+from pipelex.errors.bundle_validation_failure import BundleValidationFailure+from pipelex.errors.problem import ProblemViewfrom pipelex.pipeline.exceptions import ValidateBundleErrorfrom pipelex.validation_error_types import PipeFactoryErrorType, PipeValidationErrorTypefrom pytest_mock import MockerFixture@@ -48,6 +51,11 @@ def _build_client() -> TestClient:return TestClient(app)+def _failure_of(refusal: ValidateBundleError) -> BundleValidationFailure:+ """The invalid verdict a validator returns as a value for a refusal: its operator problem and its validation items."""+ return BundleValidationFailure(problem=refusal.to_problem(view=ProblemView.OPERATOR), validation_errors=refusal.validation_error_items())++def _multi_category_error() -> ValidateBundleError:"""A `ValidateBundleError` carrying one item per structured category, fields fully populated.@@ -180,8 +188,8 @@ class TestValidateErrors:# Every structured category lands on the 200 InvalidReport, and collectively the items cover# the full ValidationErrorItem field set (so a dropped field would fail here, not silently# vanish at the verdict->wire boundary). The runner returns the invalid verdict as a value- # (an ErrorReport) — here the ValidateBundleError's own `to_error_report()` projection.- mocker.patch.object(ApiRunner, "validate_verdict", new=mocker.AsyncMock(return_value=_multi_category_error().to_error_report()))+ # (a BundleValidationFailure) — here the one a validator builds from the ValidateBundleError.+ mocker.patch.object(ApiRunner, "validate_verdict", new=mocker.AsyncMock(return_value=_failure_of(_multi_category_error())))client = _build_client()response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS]})@@ -224,11 +232,17 @@ class TestValidateErrors:failing_dry_run = ValidateBundleError(message="Dry run failed.",dry_run_failures=[- DryRunFailureErrorData(pipe_code="summarize", domain_code="legal", source="pipe.mthds", message="Pipe 'summarize' failed: boom."),- DryRunFailureErrorData(message="Dry run failed: unlocated."),+ DryRunFailureErrorData(+ code=CoreCode.METHOD_WIRING_INVALID,+ pipe_code="summarize",+ domain_code="legal",+ source="pipe.mthds",+ message="Pipe 'summarize' failed: boom.",+ ),+ DryRunFailureErrorData(code=CoreCode.METHOD_WIRING_INVALID, message="Dry run failed: unlocated."),],)- mocker.patch.object(ApiRunner, "validate_verdict", new=mocker.AsyncMock(return_value=failing_dry_run.to_error_report()))+ mocker.patch.object(ApiRunner, "validate_verdict", new=mocker.AsyncMock(return_value=_failure_of(failing_dry_run)))client = _build_client()response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS]})@@ -249,7 +263,7 @@ class TestValidateErrors:assert locator not in unlocated_item, unlocated_itemdef test_non_verdict_failure_is_not_a_200_verdict(self, mocker: MockerFixture):- # The runner returns a produced verdict (valid report | invalid ErrorReport) as a value; only+ # The runner returns a produced verdict (valid report | BundleValidationFailure) as a value; only# a no-verdict fault propagates. A genuine host-wiring/server fault must reach the global# problem+json handler as a 5xx, never be masqueraded as a 200 verdict. (Route invariant: the# route maps the returned verdict and lets a raised fault propagate.)diff --git a/api/tests/unit/test_validate_graph_target.py b/api/tests/unit/test_validate_graph_target.pyindex 04cd3e50d..ac83e1350 100644--- a/api/tests/unit/test_validate_graph_target.py+++ b/api/tests/unit/test_validate_graph_target.py@@ -15,7 +15,9 @@ from typing import Anyfrom fastapi import FastAPIfrom fastapi.testclient import TestClientfrom mthds.protocol.problem.registry import CoreCode-from pipelex.base_exceptions import ErrorReport, ValidationErrorCategory, ValidationErrorItem+from pipelex.base_exceptions import ValidationErrorCategory, ValidationErrorItem+from pipelex.errors.bundle_validation_failure import BundleValidationFailure+from pipelex.errors.problem import ProblemView, make_problemfrom pipelex.plugins.bundle_validator_registry import BundleValidatorRegistryfrom pipelex.system.caller_identity import CallerIdentityfrom pytest_mock import MockerFixture@@ -57,12 +59,10 @@ class _RecordingBundleValidator:method_dir: Path | None, # noqa: ARG002methods_dirs: Sequence[Path] | None, # noqa: ARG002read_scope: str | None, # noqa: ARG002- ) -> ErrorReport:+ ) -> BundleValidationFailure:self.graph_pipe_codes.append(graph_pipe_code)- return ErrorReport.make_for_code(- code=CoreCode.METHOD_INVALID,- error_type="ValidateBundleError",- message="bundle is invalid",+ return BundleValidationFailure(+ problem=make_problem(code=CoreCode.METHOD_INVALID, view=ProblemView.OPERATOR),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 9111659c4..80595b0ca 100644--- a/api/tests/unit/test_validate_read_scope.py+++ b/api/tests/unit/test_validate_read_scope.py@@ -23,7 +23,9 @@ from fastapi import FastAPI, Request, Responsefrom fastapi.testclient import TestClientfrom mthds.method_tree.digest import digest_of_contentsfrom mthds.protocol.problem.registry import CoreCode-from pipelex.base_exceptions import ErrorReport, ValidationErrorCategory, ValidationErrorItem+from pipelex.base_exceptions import ValidationErrorCategory, ValidationErrorItem+from pipelex.errors.bundle_validation_failure import BundleValidationFailure+from pipelex.errors.problem import ProblemView, make_problemfrom pipelex.plugins.bundle_validator_registry import BundleValidatorRegistryfrom pipelex.system.caller_identity import CallerIdentityfrom pipelex.tools.storage.in_memory_storage_provider import InMemoryStorageProvider@@ -65,13 +67,11 @@ class _RecordingBundleValidator:method_dir: Path | None, # noqa: ARG002methods_dirs: Sequence[Path] | None, # noqa: ARG002read_scope: str | None,- ) -> ErrorReport:+ ) -> BundleValidationFailure:self.read_scopes.append(read_scope)self.held_keys.append(set(self._blob_storage.root))- return ErrorReport.make_for_code(- code=CoreCode.METHOD_INVALID,- error_type="ValidateBundleError",- message="bundle is invalid",+ return BundleValidationFailure(+ problem=make_problem(code=CoreCode.METHOD_INVALID, view=ProblemView.OPERATOR),validation_errors=[ValidationErrorItem(category=ValidationErrorCategory.BLUEPRINT_VALIDATION, message="bad ref")],)diff --git a/api/tests/unit/test_vendored_method_packages.py b/api/tests/unit/test_vendored_method_packages.pyindex 2fbd4a917..ac3a5f03d 100644--- a/api/tests/unit/test_vendored_method_packages.py+++ b/api/tests/unit/test_vendored_method_packages.py@@ -17,10 +17,11 @@ from pathlib import Pathfrom typing import Anyimport pytest-from fastapi import FastAPI+from fastapi import Depends, FastAPIfrom fastapi.testclient import TestClient-from pipelex.base_exceptions import DisclosureMode+from mthds.protocol.problem.registry import CoreCodefrom pipelex.config import get_config+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.methods.address_dependencies import ADDRESS_DEPENDENCY_REFUSAL_MARKERfrom pipelex.pipe_run.delivery_assignment import DeliveryAssignmentfrom pipelex.pipe_run.pipe_job import PipeJob@@ -32,6 +33,7 @@ from pipelex_api.api_config import ApiConfigfrom pipelex_api.errors import ApiErrorfrom pipelex_api.exception_handlers import register_exception_handlersfrom pipelex_api.method_source import fetched_method+from pipelex_api.problem_view import mark_operator_requestfrom pipelex_api.routes import router as api_routerfrom tests.unit._constants import (STUB_METHOD_ADDRESS,@@ -104,8 +106,9 @@ def _build_client(*,tmp_path: Path,orchestrator: _RecordingOrchestrator | None = None,- disclosure_mode: DisclosureMode = DisclosureMode.STRICT,+ as_operator: bool = False,) -> TestClient:+ """The routes behind the production handlers; `as_operator` marks each request as the operator's, who reads `diagnostics`."""mocker.patch("pipelex.cli.installed_methods.GLOBAL_METHODS_DIR", tmp_path / "global-methods")mocker.patch("pipelex.cli.installed_methods.PROJECT_METHODS_DIR", tmp_path / "project-methods")mocker.patch("pipelex.methods.fetch_on_miss.is_method_fetch_on_miss_enabled", return_value=False)@@ -116,8 +119,8 @@ def _build_client(if orchestrator is not None:mocker.patch(f"{_PIPELINE_NS}.get_orchestrator_registry", return_value=OrchestratorRegistry({"direct": orchestrator}))app = FastAPI()- app.include_router(api_router, prefix="/v1")- register_exception_handlers(app, disclosure_mode=disclosure_mode)+ app.include_router(api_router, prefix="/v1", dependencies=[Depends(mark_operator_request)] if as_operator else [])+ register_exception_handlers(app)return TestClient(app)@@ -203,18 +206,20 @@ class TestVendoredMethodPackages:@pytest.mark.parametrize("broken", list(_UNPARSABLE_PROBE_BUNDLES))def test_a_shipped_bundle_that_does_not_parse_is_the_verdict(self, mocker: MockerFixture, tmp_path: Path, broken: str):"""The package is the caller's own content, so its parse failure is the verdict, located by address, never by host path."""- client = _build_client(mocker, tmp_path=tmp_path, disclosure_mode=DisclosureMode.STRICT)+ client = _build_client(mocker, tmp_path=tmp_path)files = {**VENDORED_PROBE_FILES, ".mthds/methods/probe/probe.mthds": _UNPARSABLE_PROBE_BUNDLES[broken]}response = _execute_vendored(client, files=files)assert response.status_code == 422, response.textbody = response.json()- assert body["error_type"] == "ValidateBundleError"- items = body["validation_errors"]+ assert body["code"] == CoreCode.METHOD_INVALID+ assert body["domain"] == "method"+ items = body["errors"]assert items, body- assert {item["source"] for item in items} == {f"{VENDORED_PROBE_ADDRESS}/probe.mthds"}- assert VENDORED_PROBE_ADDRESS in body["detail"]+ # Each fault is located in the package by its address, the way the caller's tree names it.+ assert {item["location"]["file"] for item in items} == {f"{VENDORED_PROBE_ADDRESS}/probe.mthds"}+ assert "diagnostics" not in bodydump = json.dumps(body)assert "pipelex-methods-" not in dumpfor temporary_root in (tempfile.gettempdir(), str(Path(tempfile.gettempdir()).resolve())):@@ -224,17 +229,20 @@ class TestVendoredMethodPackages:def test_a_shipped_structure_class_is_refused_unimported(self, mocker: MockerFixture, tmp_path: Path):sentinel = tmp_path / "structures-module-ran"orchestrator = _RecordingOrchestrator()- client = _build_client(mocker, tmp_path=tmp_path, orchestrator=orchestrator)+ client = _build_client(mocker, tmp_path=tmp_path, orchestrator=orchestrator, as_operator=True)files = {**VENDORED_PROBE_FILES, ".mthds/methods/probe/structures.py": _structures_py(sentinel=sentinel)}response = client.post("/v1/start", json={**_tree_body(files), "inputs": {"text": "hello"}})- assert response.status_code == 403, response.text+ assert response.status_code == 422, response.textbody = response.json()- assert body["error_type"] == "MethodStructuresRefusedError"+ assert body["code"] == PipelexErrorCode.DEPLOYMENT_PYTHON_STRUCTURES_REFUSED+ # The caller reads the file by the name its tree gives a shipped package's file: the address, then the path inside.+ assert body.get("params") == {"files": [f"{VENDORED_PROBE_ADDRESS}/structures.py"]}# Named as the fetched package's refusal is: by the package's address, and the file by its path inside it.- assert f"Method package '{VENDORED_PROBE_ADDRESS}'" in body["detail"]- assert "structures.py defines Invoice" in body["detail"]+ assert body["diagnostics"]["error_class"] == "MethodStructuresRefusedError"+ assert f"Method package '{VENDORED_PROBE_ADDRESS}'" in body["diagnostics"]["message"]+ assert "structures.py defines Invoice" in body["diagnostics"]["message"]assert not sentinel.exists(), "the structure module was imported"assert orchestrator.dispatches == []@@ -372,8 +380,8 @@ class TestVendoredMethodPackages:[item] = verdict["validation_errors"]assert item["error_type"] == "unresolved_package_dependency"assert item["source"] == "bundle.mthds"+ # The item quotes the refusal itself; the verdict's message is the sentence its code renders.assert f"{ADDRESS_DEPENDENCY_REFUSAL_MARKER} '{VENDORED_PROBE_ADDRESS}'" in item["message"]- assert ADDRESS_DEPENDENCY_REFUSAL_MARKER in verdict["message"]def test_validate_by_method_ref_resolves_the_dependency_it_ships(self, mocker: MockerFixture, tmp_path: Path, install_method_package: Callable[..., Path]diff --git a/api/tests/unit/test_webhook_recovery.py b/api/tests/unit/test_webhook_recovery.pyindex 37a3a9ecd..b009b5514 100644--- a/api/tests/unit/test_webhook_recovery.py+++ b/api/tests/unit/test_webhook_recovery.py@@ -1,193 +1,199 @@-"""Cross-path consistency regression for the API's two error surfaces.--The API surfaces a pipelex `ErrorReport` to clients along two paths:--1. The **synchronous HTTP path** — `POST /execute` (and every other- route that propagates a `PipelexError`) renders the report via- `build_problem_document(...)` → RFC 7807 `application/problem+json`.-2. The **asynchronous webhook path** — `POST /start` schedules a- Temporal workflow; on completion (success or `FAILED`), pipelex's- `DeliveryExecutor._notify_webhook(...)` posts a JSON payload to the- caller's callback URL. On `FAILED`, the payload carries- `error: <ErrorReport.to_dict(disclosure_mode=VERBOSE)>` — a flat dict, not- an RFC 7807 envelope (the receiver chooses how to render it).--This module pins the **T6 cross-path consistency** invariant: given the same-source `ErrorReport`, both renderings must surface the same classification-fields. A client that branches on `error_type` / `error_domain` /-`retryable` / `user_action` must not get one classification synchronously-and a different one over the webhook.--The webhook payload itself is composed entirely upstream in-`pipelex.pipe_run.delivery_executor`; the API never touches the bytes that-go over the wire. So this test exercises the two rendering helpers directly-and asserts the classification overlap is exact. Drift here would imply-either pipelex's `to_dict` / `to_problem_document` diverged in their field-selection, or the API's `build_problem_document` wrapper started shaping-the document.+"""Cross-path consistency of the API's two failure surfaces.++A failure reaches a client along two paths:++1. The **synchronous HTTP path**: `POST /execute`, and every other route that lets a `PipelexError`+ propagate, answers the error's problem through `problem_response`, in the view of whoever made+ the request (`pipelex_api.problem_view`).+2. The **asynchronous webhook path**: `POST /start` builds each completion webhook's target, and on+ a failed run pipelex's `DeliveryExecutor` posts the run's problem under `error`, in the view the+ target carries (`WebhookTarget.problem_view`).++A completion webhook is the same answer as the synchronous response, delivered later, so the start+route gives each target the view of its own request, and the payload's `error` is exactly the+synchronous body in that view, but for `status`, the HTTP envelope's member, which a webhook POST+does not have. A client branching on `code`, `retry` or `next_step` must not read one answer+synchronously and another over the webhook, and a caller must never receive over a webhook the+diagnostics its synchronous view withholds."""-from typing import Any+import asyncio+import os+from collections.abc import Callable+from typing import Any, castimport pytest+from fastapi import APIRouter, Depends, FastAPI+from fastapi.testclient import TestClientfrom mthds.protocol.problem.registry import CoreCode-from pipelex.base_exceptions import DisclosureMode, ErrorReport-from pipelex.cogt.inference.error_classification import ProviderErrorMetadata, UserAction, UserActionKind-from pipelex.cogt.inference.provider_name import ProviderName--from pipelex_api.problem_document import build_problem_document--# Classification fields that, when populated on the source `ErrorReport`,-# must appear with identical values in both renderings. Excluded from this-# list are: (a) `message` — present in both but under different keys-# (`message` in `to_dict`, `detail` in `to_problem_document`); checked-# separately. (b) the RFC 7807 standard slots `type`/`title`/`status` and-# the request-scoped extension members `instance`/`request_id` — those are-# rightfully envelope-only.-_CLASSIFICATION_FIELDS_PRESERVED = (- "code",- "error_type",- "error_domain",- "error_category",- "retryable",- "user_action",- "model",- "provider",- "provider_metadata",-)---def _fully_populated_llm_report() -> ErrorReport:- """A provider-429 report exercising every classification field at once.-- Provider/model/provider_metadata ride on `RUNTIME`-domain inference- failures, so an `LLMCompletionError` stand-in is the broadest single- fixture: it pins the parity contract on the maximum field set the API- ever surfaces.- """- report = ErrorReport.make_for_code(- code=CoreCode.PROVIDER_RATE_LIMITED,- error_type="LLMCompletionError",- message="OpenAI returned 429 (rate_limit_exceeded)",- user_action=UserAction(- kind=UserActionKind.WAIT_AND_RETRY,- detail="The provider is rate-limiting your account. Retry after the indicated delay.",- ),+from pipelex.base_exceptions import PipelexConfigError, PipelexError+from pipelex.errors.problem import ProblemView+from pipelex.pipe_run.delivery_assignment import DeliveryAssignment, DeliveryStatus+from pipelex.pipe_run.delivery_executor import DeliveryExecutor+from pipelex.pipe_run.pipe_job import PipeJob+from pipelex.plugins.orchestrator_registry import OrchestratorRegistry+from pipelex.runtime_bridge.payloads import PipelexPipeDispatchAck, PipelexPipeRunOutput+from pytest_mock import MockerFixture++from pipelex_api.api_config import ApiConfig+from pipelex_api.exception_handlers import register_exception_handlers+from pipelex_api.problem_view import mark_operator_request+from pipelex_api.routes import router as api_router+from tests.unit._constants import VALID_MTHDS+from tests.unit.test_data import ProblemTestData, rate_limited_failure++_PIPELINE_NS = "pipelex_api.routes.pipelex.pipeline"+_MODE = "temporal"+_RUN_ID = "run-webhook-view-1"+++def _config_failure() -> PipelexError:+ """An operator's fault, whose step differs between the views and whose message only the operator reads."""+ return PipelexConfigError("the gateway config is missing")+++# The failures the two paths are compared on, by id: the problem with the most members, and the operator's fault.+_FAILURES: dict[str, Callable[[], PipelexError]] = {+ "provider_rate_limit": rate_limited_failure,+ "operator_configuration": _config_failure,+}+++class _RecordingOrchestrator:+ """An async-capable orchestrator that records the delivery assignment of every run it is handed."""++ supports_fire_and_forget = True++ def __init__(self) -> None:+ self.delivery_assignments: list[DeliveryAssignment | None] = []++ async def execute(self, *, pipe_job: PipeJob, delivery_assignment: DeliveryAssignment | None) -> PipelexPipeRunOutput: # noqa: ARG002+ msg = "These tests dispatch through /start only."+ raise AssertionError(msg)++ async def start(self, *, pipe_job: PipeJob, delivery_assignment: DeliveryAssignment | None) -> PipelexPipeDispatchAck: # noqa: ARG002+ self.delivery_assignments.append(delivery_assignment)+ return PipelexPipeDispatchAck(pipeline_run_id=_RUN_ID, workflow_id="wf-webhook-view-1")+++def _router_dependencies(view: ProblemView) -> list[Any]:+ """What authentication leaves on a request of `view`: the operator's mark, or nothing for a caller."""+ match view:+ case ProblemView.OPERATOR:+ return [Depends(mark_operator_request)]+ case ProblemView.CALLER:+ return []+++def _start_with_a_callback(mocker: MockerFixture, *, view: ProblemView) -> DeliveryAssignment:+ """Start a run asking for a completion webhook, as a request of `view`, and return the assignment the run was handed."""+ mocker.patch.dict(os.environ, {"COMPLETION_CALLBACK_SECRET": ProblemTestData.SYNTHETIC_CALLBACK_SECRET})+ mocker.patch(f"{_PIPELINE_NS}.get_api_config", return_value=ApiConfig(orchestration_mode=_MODE, allow_request_orchestration_mode_override=False))+ orchestrator = _RecordingOrchestrator()+ mocker.patch(f"{_PIPELINE_NS}.get_orchestrator_registry", return_value=OrchestratorRegistry({_MODE: orchestrator}))+ app = FastAPI()+ app.include_router(api_router, prefix="/v1", dependencies=_router_dependencies(view))+ register_exception_handlers(app)++ response = TestClient(app).post(+ "/v1/start",+ json={+ "pipe_code": "echo",+ "mthds_contents": [VALID_MTHDS],+ "inputs": {"text": "hello"},+ "pipeline_run_id": _RUN_ID,+ "callback_urls": [ProblemTestData.CALLBACK_URL],+ },)- 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 `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 projection- keys its `message` passthrough on. Used here to verify that the parity- contract holds across both message-disclosure provenances.- """- return ErrorReport.make_for_code(- code=CoreCode.METHOD_SYNTAX,- error_type="MthdsParserError",- message="Your .mthds file has a syntax error on line 4",- caller_facing_message=True,- )---class TestWebhookRecoveryCrossPath:- @pytest.mark.parametrize(- ("label", "report_factory"),- [- ("llm_provider_429", _fully_populated_llm_report),- ("caller_facing_input", _caller_facing_input_report),- ],- )- def test_classification_fields_match_between_sync_and_webhook(self, label: str, report_factory: Any) -> None:- """T6 regression: webhook `error` and sync RFC 7807 body must agree.-- For every classification field that pipelex populates on the source- report, the value in `ErrorReport.to_dict(VERBOSE)` (what the webhook- carries under `error`) must be byte-identical to the value rendered- in the RFC 7807 problem document (what the sync handler returns).- """- report = report_factory()- webhook_payload = report.to_dict(disclosure_mode=DisclosureMode.VERBOSE)- problem_doc = build_problem_document(- report,- instance="/v1/execute",- request_id="REQ_T6",- disclosure_mode=DisclosureMode.VERBOSE,+ assert response.status_code == 202, response.text+ (delivery_assignment,) = orchestrator.delivery_assignments+ assert delivery_assignment is not None+ return delivery_assignment+++def _synchronous_body(*, failure: Callable[[], PipelexError], view: ProblemView) -> dict[str, Any]:+ """The body the synchronous path answers `failure` with, to a request of `view`."""+ router = APIRouter()++ async def fail() -> None:+ raise failure()++ router.add_api_route("/fail", fail, methods=["GET"])+ app = FastAPI()+ app.include_router(router, dependencies=_router_dependencies(view))+ register_exception_handlers(app)+ body = TestClient(app).get("/fail").json()+ return cast("dict[str, Any]", body)+++def _posted_failure(mocker: MockerFixture, *, delivery_assignment: DeliveryAssignment, failure: PipelexError) -> dict[str, Any]:+ """Deliver `failure` as the run's outcome to the assignment's webhooks, and return the one body the webhook received."""+ mock_client = mocker.AsyncMock()+ mock_response = mocker.MagicMock()+ mock_response.raise_for_status = mocker.Mock()+ mock_client.__aenter__ = mocker.AsyncMock(return_value=mock_client)+ mock_client.__aexit__ = mocker.AsyncMock(return_value=False)+ mock_client.post = mocker.AsyncMock(return_value=mock_response)+ mocker.patch("pipelex.pipe_run.delivery_executor.httpx.AsyncClient", return_value=mock_client)++ asyncio.run(+ DeliveryExecutor().execute(+ None,+ storage_scope="webhook-view-scope",+ pipeline_run_id=_RUN_ID,+ delivery_assignment=delivery_assignment,+ status=DeliveryStatus.FAILED,+ # A failed run's problem reaches the delivery in the operator's view; each webhook takes its own.+ problem=failure.to_problem(view=ProblemView.OPERATOR),)+ )- for field in _CLASSIFICATION_FIELDS_PRESERVED:- in_webhook = field in webhook_payload- in_problem = field in problem_doc- assert in_webhook == in_problem, f"{label}: field `{field}` presence mismatch (webhook={in_webhook}, problem={in_problem})"- if in_webhook:- assert webhook_payload[field] == problem_doc[field], f"{label}: field `{field}` value drift between paths"-- # `message` rides under different keys by design — pin the bridge.- assert problem_doc["detail"] == webhook_payload["message"], (- f"{label}: sync `detail` and webhook `message` must carry identical text under VERBOSE"- )+ mock_client.post.assert_awaited_once()+ post_call = mock_client.post.await_args+ assert post_call is not None+ assert post_call.args == (ProblemTestData.CALLBACK_URL,)+ payload = post_call.kwargs["json"]+ return cast("dict[str, Any]", payload)- def test_sync_only_envelope_members_are_isolated_to_problem_document(self) -> None:- """The RFC 7807 envelope is the sync path's contract, not the webhook's.-- `type` / `status` / `detail` / `instance` / `request_id` are the- envelope-only members: pipelex's `to_problem_document` maps them from- report fields (`type_uri` → `type`, `http_status` → `status`,- `message` → `detail`) or sources them from the caller (`instance`,- `request_id`). They never appear on the raw `to_dict` output the- webhook carries — the webhook is the structured-data layer (per- Phase 4b decision); receivers that want an envelope render one- themselves. Pin the asymmetry so a refactor of either path doesn't- quietly leak envelope members into the webhook payload or strip them- from the sync body. (`title` and `type_uri` ARE direct fields on- `ErrorReport`, so they appear in both — not envelope-only.)- """- report = _fully_populated_llm_report()- webhook_payload = report.to_dict(disclosure_mode=DisclosureMode.VERBOSE)- problem_doc = build_problem_document(- report,- instance="/v1/execute",- request_id="REQ_T6",- disclosure_mode=DisclosureMode.VERBOSE,- )- for envelope_member in ("type", "status", "detail", "instance", "request_id"):- assert envelope_member in problem_doc, f"sync path must carry RFC 7807 envelope member `{envelope_member}`"- assert envelope_member not in webhook_payload, (- f"webhook payload must NOT carry RFC 7807 envelope member `{envelope_member}` (use `to_problem_document` if you need an envelope)"- )-- def test_webhook_carries_raw_report_regardless_of_disclosure_mode(self) -> None:- """The webhook always renders the report VERBOSE, even when sync is STRICT.-- The receiver decides what to re-expose downstream — pipelex hardcodes- `DisclosureMode.VERBOSE` in `_notify_webhook` for exactly this reason.- Pin it here so a future refactor that introduces a `disclosure_mode`- knob on the webhook path is caught by this test.- """- report = _fully_populated_llm_report()- verbose_payload = report.to_dict(disclosure_mode=DisclosureMode.VERBOSE)- strict_payload = report.to_dict(disclosure_mode=DisclosureMode.STRICT)-- # The provider-identifying fields are the cheapest signal that the- # projection actually fired: VERBOSE keeps them, STRICT drops them.- assert verbose_payload.get("provider") == "openai"- assert verbose_payload.get("model") == "gpt-4o-mini"- assert "provider" not in strict_payload- assert "model" not in strict_payload+class TestWebhookRecoveryCrossPath:+ @pytest.mark.parametrize("view", [ProblemView.OPERATOR, ProblemView.CALLER])+ def test_the_webhook_target_takes_the_start_requests_view(self, mocker: MockerFixture, view: ProblemView) -> None:+ delivery_assignment = _start_with_a_callback(mocker, view=view)++ (webhook,) = delivery_assignment.webhooks+ assert webhook.url == ProblemTestData.CALLBACK_URL+ assert webhook.problem_view == view++ @pytest.mark.parametrize("view", [ProblemView.OPERATOR, ProblemView.CALLER])+ @pytest.mark.parametrize("failure_id", list(_FAILURES))+ def test_the_failure_payload_is_the_synchronous_answer_in_the_same_view(self, mocker: MockerFixture, view: ProblemView, failure_id: str) -> None:+ failure = _FAILURES[failure_id]+ delivery_assignment = _start_with_a_callback(mocker, view=view)++ payload = _posted_failure(mocker, delivery_assignment=delivery_assignment, failure=failure())++ assert payload["pipeline_run_id"] == _RUN_ID+ assert payload["state"] == DeliveryStatus.FAILED+ synchronous_body = _synchronous_body(failure=failure, view=view)+ # `status` is the HTTP envelope's member: the synchronous body carries it, the webhook's `error` does not.+ assert "status" not in payload["error"]+ assert payload["error"] == {member: value for member, value in synchronous_body.items() if member != "status"}+ match view:+ case ProblemView.OPERATOR:+ assert "diagnostics" in payload["error"]+ case ProblemView.CALLER:+ assert "diagnostics" not in payload["error"]++ def test_a_caller_never_receives_the_diagnostics_over_the_webhook(self, mocker: MockerFixture) -> None:+ """What the caller's synchronous view withholds, the provider's own answer included, its webhook withholds too."""+ delivery_assignment = _start_with_a_callback(mocker, view=ProblemView.CALLER)++ payload = _posted_failure(mocker, delivery_assignment=delivery_assignment, failure=rate_limited_failure())++ posted_error = payload["error"]+ assert posted_error["code"] == CoreCode.PROVIDER_RATE_LIMITED+ assert posted_error["detail"] == ProblemTestData.RATE_LIMIT_DETAIL+ for operator_only in (ProblemTestData.RATE_LIMIT_MESSAGE, ProblemTestData.RATE_LIMIT_PROVIDER_REQUEST_ID, "LLMCompletionError"):+ assert operator_only not in str(posted_error), operator_onlydiff --git a/docs/api-server/codegen.md b/docs/api-server/codegen.mdindex a31472ebd..256e2011b 100644--- a/docs/api-server/codegen.md+++ b/docs/api-server/codegen.md@@ -4,7 +4,7 @@ Resolve a library closure into its **normalized library crate**, and project thaBoth are **Pipelex API extensions**, not MTHDS Protocol routes: they are not tagged `x-mthds-protocol` in the [OpenAPI artifact](openapi/pipelex-api.openapi.yaml), and an MTHDS runner is not required to serve them. The *crate* is a different matter — its shape is the standard's [Library Crate Format](https://mthds.ai), so the wire fields are brand-neutral and any MTHDS tool can read one. What is ours is the HTTP surface that produces it, and the type projection on top (the standard specifies none).-Both endpoints speak the [`POST /v1/validate`](pipe-validate.md) verdict discipline: a **produced verdict is always a `200`** discriminated on `is_valid`; the invalid arm carries the structured `validation_errors[]` from pipelex's one shared builder — each item optionally carrying a [`suggested_fix`](error-responses.md#suggested-fixes). Non-2xx is reserved for *no verdict could be produced*: request-shape errors (an unknown projection `kind`/`target`, a malformed method selector) and a method tree that cannot be read are `422` RFC 7807 `application/problem+json`, the custom-Python policy is a `403`, a registry-form `method_ref` is `501`, an address-form `method_ref` that fails to resolve maps per the [`method_ref` error table](pipe-run.md#running-a-method-by-address-method_ref), auth is `401`/`403`, server faults are `5xx`.+Both endpoints speak the [`POST /v1/validate`](pipe-validate.md) verdict discipline: a **produced verdict is always a `200`** discriminated on `is_valid`; the invalid arm carries the structured `validation_errors[]` from pipelex's one shared builder — each item optionally carrying a [`suggested_fix`](error-responses.md#suggested-fixes). Non-2xx is reserved for *no verdict could be produced*: request-shape errors (an unknown projection `kind`/`target`, a malformed method selector) and a method tree that cannot be read are `422` RFC 9457 `application/problem+json`, the custom-Python policy is a `403` (the refusal of Python structure classes a `422`), a registry-form `method_ref` is `501`, an address-form `method_ref` that fails to resolve maps per the [`method_ref` error table](pipe-run.md#running-a-method-by-address-method_ref), auth is `401`/`403`, server faults are `5xx`.## Selecting the method@@ -21,7 +21,7 @@ Providing neither or both is a request-shape `422`. Beside `files`, the request**The tree's refusals produce no verdict**, exactly as on `/v1/validate`: a key or entry the tree's rule refuses is a `422 InvalidMethodFiles` with its `tree_refusal` member, a hash the runner does not hold a `422 MissingBlobs`, a tree past its limits a `422 MethodTreeTooLarge`, and a tree holding no `.mthds` bundle of its own a `422 InvalidBundle`. A `files` member that is not a map, such as a list, is an `InvalidMethodFiles` too.-**Python follows the run routes' policy.** A projection runs nothing, but loading a method's library on a deployment that is not sandbox-hosted imports each of its `.py` files that declares a structure class (a `StructuredContent` subclass), which runs that file's module-level code in the server's process. So there a tree, sent or fetched, that holds any `.py` file is refused with a `403 CustomCodeRequiresSandbox` before anything is written. On a sandbox-hosted deployment, a tree whose Python declares a structure class is refused with a `403 MethodStructuresRefusedError`, as on a [run](pipe-run.md#sending-a-method-as-a-tree).+**Python follows the run routes' policy.** A projection runs nothing, but loading a method's library on a deployment that is not sandbox-hosted imports each of its `.py` files that declares a structure class (a `StructuredContent` subclass), which runs that file's module-level code in the server's process. So there a tree, sent or fetched, that holds any `.py` file is refused with a `403 CustomCodeRequiresSandbox` before anything is written. On a sandbox-hosted deployment, a tree whose Python declares a structure class is refused with a `422` problem, `pipelex.deployment.python_structures_refused`, as on a [run](pipe-run.md#sending-a-method-as-a-tree).**A call by address resolves only from what was shipped.** A package the method calls by its address is loaded from the packages the request sends in `dependencies`, or that a fetched package ships under its `.mthds/methods/`, and from nowhere else: these routes never read a method installed on the runner and never fetch one. A call into a package nothing shipped is therefore the invalid verdict, one `unresolved_package_dependency` item per package, located on the pipe that calls it, whose message names it as `address-based dependency '<address>'`. The method is written out, loaded, projected and released in a worker thread, so a slow load never holds up the server's other requests.diff --git a/docs/api-server/error-responses.md b/docs/api-server/error-responses.mdindex ad4526f07..5ca6b3154 100644--- a/docs/api-server/error-responses.md+++ b/docs/api-server/error-responses.md@@ -1,55 +1,120 @@# Error Responses-Every error returned by the API uses the RFC 7807 `application/problem+json` envelope. The same shape applies across pipelex domain errors, validation errors, auth failures, payload-size limits, and the catch-all 500.+Every error returned by the API is an RFC 9457 `application/problem+json` document. A failure the Pipelex runtime raised, which is every domain error, every run failure and the catch-all, answers its **problem document**, named by a registry code and seen through the view the request's identity gives it. A refusal the API authors itself, such as a malformed body, a missing token or a payload over its limit, answers a problem document of its own, classified by an `error_type`.## Envelope-A failure response looks like this:+A failure the runtime raised looks like this, in the caller view:```json{"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/execute",+ "detail": "The method does not validate.","code": "method.invalid",- "error_type": "ValidateBundleError",- "error_domain": "input",- "retryable": false,+ "domain": "method",+ "retry": "no",+ "next_step": {+ "kind": "change_method",+ "detail": "Fix each fault the problem's errors list, then validate the method again."+ },+ "errors": [+ {+ "code": "method.input_undeclared",+ "detail": "Pipe 'summarize' reads names its inputs do not declare: tone.",+ "params": { "pipe": "summarize", "variables": ["tone"] },+ "location": { "pipe": "summarize", "file": "summaries.mthds" }+ }+ ],"request_id": "9f2c1ab3-…"}```-`Content-Type` is `application/problem+json` and `X-Request-ID` is always echoed in the response headers.+`Content-Type` is `application/problem+json` and `X-Request-ID` is always echoed in the response headers. No member is ever written as `null`: a member with no value is absent.++## Members-## Fields+**The RFC's members** — `type`, `title`, `status` and `detail` are always present:-**Standard RFC 7807 members** — `type`, `title`, `status`, `detail`, `instance`.+- `type` — the page of the error's `code`. See [The `type` URI](#the-type-uri).+- `title` — the code's title, the same for every occurrence of the code.+- `status` — the HTTP status the code declares, repeated in the body. See [Status codes](#status-codes).+- `detail` — the sentence stating this occurrence, rendered from the code's template with the problem's parameters. It is written for a person to read: a program branches on `code`, never on a sentence.-**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:+**The MTHDS standard's members** — `code`, `domain`, `retry` and `next_step` are always present, and the others appear when they hold a value:++- `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`, `status`, `domain`, `retry` and the sentences, so a consumer branches on it rather than on the class that raised the error, which a caller is never told.+- `domain` — who must act: `input` (the caller, by changing the request or its inputs), `method` (the method's author), `account` (the account's owner), `operator` (whoever runs this server) or `runtime` (nobody beforehand: wait, retry or report).+- `retry` — whether repeating the same request can succeed: `yes`, as for an inference provider's rate limit; `no`; or `outcome_unknown`, when the request may have taken effect. A client retries blindly only on `yes`.+- `retry_after` — on a code whose verdict is `yes`, the delay in seconds the provider asked for before a retry. A `429` also carries it as a `Retry-After` header, rounded up.+- `next_step` — what the reader does next: its `kind`, such as `change_input`, `change_method`, `change_model`, `wait`, `retry`, `fix_configuration` or `report`, and its `detail`, a sentence rendered from the code's template. The step is the reader's own, so the caller view and the operator view of one failure can give different steps.+- `params` — the facts the code's sentences name, by the registry's names, such as the failing `pipe` or the `model` a method named. A parameter only the operator may read never rides here.+- `location` — where the fault is: on a run failure the failing `pipe` and its `path` from the entry pipe, and elsewhere an `input`, a `field`, a batch `item`, an `attempt`, or a `file` with its `line` and `column`. See [Run failures](#run-failures-the-root-fault-located-at-the-failing-pipe).+- `errors` — one item per fault, for a refusal of several at once: each with its own `code`, `detail`, `params` and `location`, and on a method that does not validate the `suggestions` and `suggested_fix` of its validation item. See [Structured validation errors](#structured-validation-errors).+- `pipeline_run_id` — the run the problem belongs to.++**Pipelex's members:**-- `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.-- `model`, `provider`, `provider_metadata` — populated when the failure originated in an upstream inference call. **Stripped under STRICT disclosure** (see [Disclosure modes](#disclosure-modes)).+- `diagnostics` — present in the operator view alone. See [Views chosen by identity](#views-chosen-by-identity).++### API-authored errors++A refusal the API authors itself, before the runtime is asked anything, carries no `code` yet. It keeps the classification members it had before the problem document, beside the RFC's `type`, `title`, `status` and `detail`:++- `error_type` — the refusal's name, such as `ValidationError`, `InvalidJSON`, `Unauthenticated` or `PayloadTooLarge`, the member to branch on. See [Status codes](#status-codes).+- `error_domain` — `input` for a refusal the caller can fix, `config` for one the deployment must.+- `retryable` — always present, and `false`: every such refusal is a request to correct or a deployment to fix.+- `instance` — the request's path.+- `request_id` — as above.- `tree_refusal` — on a **422** `InvalidMethodFiles`, the MTHDS standard's refusal of a method tree the request sent: `{"code": "<refusal code>", "names": [...]}`, the code one of the standard's tree refusal codes, such as `invalid_tree_path`, `duplicate_key`, `excluded_name` or `malformed_entry`, and `names` the keys, paths or addresses it refuses. A name holding a code point UTF-8 cannot encode, such as a lone surrogate a JSON escape can carry, is written with that code point backslash-escaped. See [Pipe Run](pipe-run.md#sending-a-method-as-a-tree).- `missing_blobs` — on a **422** `MissingBlobs`, the SHA-256 hashes the request named by hash entries that this runner does not hold at their stated size, to upload through the blob routes before sending the request again. See [Sending files by hash](pipe-run.md#sending-files-by-hash).- `mismatched_blobs` — on a **422** `BlobMismatch` refusing a request's hash entries, each hash this runner holds at another size than its entry states, as `{"sha256": "…", "held_size": n}`: the entry's size is the one to correct, since uploading the bytes again would not change the size they are held at.-- `validation_errors` — structured per-error list carried by a `ValidateBundleError`. On the run routes (`/execute`, `/start`) it rides this 422 problem document; on the diagnostic routes (`/validate`, `/resolve`, `/codegen`, `/pipe-io`) it rides the **200 `is_valid: false`** body instead (see [Pipe Validate](pipe-validate.md)). See [Structured validation errors](#structured-validation-errors).++Its `detail` is the API's own sentence about what it checked, and it reads the same in every view.++## Views chosen by identity++A failure the runtime raised is one problem seen through a view, and the identity the request authenticated picks the view. No deployment setting picks it.++| How the request authenticated | View |+|-------------------------------|------|+| `AUTH_MODE=api_key`: the static API key is the operator's own credential | The operator view |+| `AUTH_MODE=none` with `TRUST_FORWARDED_IDENTITY_HEADERS=true`: the only party reaching this server is the trusted proxy in front of it, such as the hosted platform, which owes its own callers their caller view | The operator view |+| `AUTH_MODE=jwt`: a caller's token | The caller view |+| `AUTH_MODE=none` without the trusted proxy, or a request refused before any authentication ran | The caller view |++**The caller view** carries the code's sentences, rendered from the parameters a caller may read, and the step for the caller: for a code of the `operator` domain, whose actor is whoever runs this server, that is what the caller can do meanwhile, such as choosing another model. It never carries the error's own message, its class, a path on the host, a provider's answer or a foreign exception's text, whatever the failure. A problem this server relays with a code its own registries do not hold, such as one a newer worker built, reaches the caller with the generic step of its kind, and `report` for a code of the `operator` domain, since its recorded step was written for the operator.++**The operator view** adds the operator's step and `diagnostics`:++- `error_class` — the class of the error the problem was built from.+- `message` — that error's own message.+- `causes` — the errors along its cause chain, each with its class and the code it carries by itself.+- `params` — the parameters only an operator may read, such as the variable `pipelex.config.variable_missing` names, which also render into the operator's step.+- `model` — the model handle, when the failure is attributable to one.+- `provider` — what the inference provider answered: its `name` (the backend), `status`, `code`, `request_id` and `message`.+- `migration` — a pending configuration migration that explains the failure.+- `runtime_version` — the version of the Pipelex runtime that built the problem.+- `trace_id`, `span_id` — the OpenTelemetry span the failure happened in, when one was recording.++Every text in a problem that the runtime did not write itself, a message, a provider's answer or a parameter, is cut to a bounded length, keeping its head and ending with ` […]`.++The catch-all, a failure no more specific handler matched, answers `runtime.unexpected` with a **500** in both views: the caller reads that code's sentences, and the operator reads the exception's class and message in `diagnostics`. A traceback never reaches a response in either view.++The server's own record of a failure the runtime raised is built from the operator view, whichever view the response carries, so it names the error's class, its code and what the inference provider answered (see [Logging](logging.md)).## Structured validation errors-When a bundle fails validation, the `ValidateBundleError` carries a `validation_errors` array — the per-error diagnostics an editor maps to per-line problems. Where it surfaces depends on the endpoint: on the diagnostic routes (`/validate`, `/resolve`, `/codegen`, `/pipe-io`) it rides the **200 `is_valid: false`** body (the diagnostic-endpoint contract — see [Pipe Validate](pipe-validate.md)); on the run routes (`/execute`, `/start`) — where an invalid bundle means the run cannot proceed — it rides the **422** problem document alongside the single human-readable `detail`. Built by pipelex's one shared builder, the items are identical wherever they appear (and to the agent CLI's). Each item is one categorized validation failure:+When a bundle fails validation, the runtime builds one structured item per fault — the per-error diagnostics an editor maps to per-line problems — and where they surface depends on the endpoint. On the diagnostic routes (`/validate`, `/resolve`, `/codegen`, `/pipe-io`) an invalid bundle is the successful product of the call: a **200 `is_valid: false`** verdict carrying the items whole as `validation_errors` (see [Pipe Validate](pipe-validate.md)). On the run routes (`/execute`, `/start`), where an invalid bundle means the run cannot proceed, it is a **422** `method.invalid` problem carrying the same items as its `errors`, each with its own code. Built by pipelex's one shared builder, the items name the same faults at the same places wherever they appear, and the same as the agent CLI's.++Each `validation_errors` item of a verdict is one categorized validation failure:| Field | Meaning ||---|---|| `category` | The failure family — one of `blueprint_validation`, `pipe_factory`, `pipe_validation`, `dry_run`. |-| `message` | Human-readable description of this specific error. |+| `message` | Human-readable description of this specific error. On a `dry_run` item it names the pipe, then the sentence the failure's code renders for a caller, never the failure's own text. || `error_type` | Finer error subtype within the category, when the source error provides one. || `source` | The owning file of the error, when the runtime could attribute it to one: on `blueprint_validation` and `pipe_validation` items, and on a `dry_run` item, where it is the file of the pipe whose dry run failed. On the in-memory submit path it is the matching `mthds_sources[i]` (see [Sourcing submitted files](pipe-validate.md)), so it is absent when the caller sent no sources. Absent on `pipe_factory` items and on the parse-level residual described below. Beside a server's own library directories, an item never names one of their files, nor a template file one of their `PipeDocGen` steps names. || `pipe_code`, `concept_code`, `domain_code` | The pipe / concept / domain the error is about, when applicable. On a `dry_run` item they name the innermost pipe that failed, not the controller the failure passed through. |@@ -60,15 +125,17 @@ When a bundle fails validation, the `ValidateBundleError` carries a `validation_| `template_file`, `template_location` | On a `template_check_warning` item, which rides the valid verdict's `warnings` rather than `validation_errors`, the template file as the `PipeDocGen` step names it and the place in it the engine's finding names, in the engine's own words (a defined name, a Table, a cell, a shape, a tag); `template_location` is absent when the engine names no place. A step of the server's own library directories is named by its `pipe_code` and `domain_code` alone: its item carries no `template_file`, and its message reads `<host library file>` where it named the file. || `suggested_fix` | A structured, deterministic fix for this error — present only when the fix planner derived one. See [Suggested fixes](#suggested-fixes). |-Items carry only the fields that apply to their category — absent fields are omitted, not null. `validation_errors` is **retained under STRICT disclosure** (it describes the caller's own submitted bundle, not server internals). It is present only on `ValidateBundleError`; other error types omit it.+Items carry only the fields that apply to their category — absent fields are omitted, not null.-Every invalid verdict carries a **non-empty** `validation_errors` array — the structured-info invariant is total. A parse-level failure the runtime cannot attribute to a known pipe/concept/field — an empty blueprint, an elaborator failure — still becomes one `blueprint_validation` residual item carrying the failure message (no `source`, no `error_type` at this layer), so the array is never empty on an invalid verdict. A TOML syntax error is an item of the same category without an `error_type`, which carries the `line` and `column` the parser stopped at and the `source` when the caller sent one. A failing dry run is one `dry_run` item per failing pipe, located at the innermost pipe that failed. The richer, locator-bearing items appear only when the runtime could attribute the failure; the human-readable summary (the `detail` on a run-route 422, the `message` on a diagnostic-route 200 invalid verdict) stays available alongside, but a consumer can always read at least one structured item.+On a `422` problem, each item becomes one `errors` entry: its `code` is the code its `error_type` maps to (`method.input_undeclared` for a `missing_input_variable`, `model.unknown` for an `unknown_model`), a `dry_run` item's is its failure's own, and an item no stage classified takes `method.schema_violation` or the code of the refusal behind it; its `detail` is that code's sentence and its `params` the facts the item's locators give it; its `location` holds the item's `pipe`, `field`, `file`, `line` and `column`; and it keeps the item's `suggestions` and `suggested_fix`.-On the run routes, **every refusal of the bundle while it loads is this verdict**, and the load happens before any pipe runs: a misspelled concept, a wiring mismatch, an unknown model, a TOML fault or a refusal raised while a pipe is built all answer the same **422** carrying the same items validating the bundle gives. None of them reaches a run as a `500`. An entry pipe the bundle does not declare keeps its own `EntryPipeNotFoundError`, and a bare code matching pipes in several domains its own `EntryPipeAmbiguousError`.+Every invalid verdict carries a **non-empty** list of items — the structured-info invariant is total. A parse-level failure the runtime cannot attribute to a known pipe/concept/field — an empty blueprint, an elaborator failure — still becomes one `blueprint_validation` residual item carrying the failure message (no `source`, no `error_type` at this layer), so the list is never empty on an invalid verdict. A TOML syntax error is an item of the same category without an `error_type`, which carries the `line` and `column` the parser stopped at and the `source` when the caller sent one. A failing dry run is one `dry_run` item per failing pipe, located at the innermost pipe that failed. A dry run whose every failure belongs to someone other than the method's author, such as a storage outage, is no verdict about the method: it answers the failure's own code, with every failure riding its `errors`.++On the run routes, **every refusal of the bundle while it loads is this verdict**, and the load happens before any pipe runs: a misspelled concept, a wiring mismatch, an unknown model, a TOML fault or a refusal raised while a pipe is built all answer the same **422** `method.invalid` carrying the same items validating the bundle gives. None of them reaches a run as a `500`. An entry pipe the bundle does not declare answers `request.pipe_not_found`, and a bare code matching pipes in several domains `request.pipe_ambiguous`.## Suggested fixes-A validation error item may carry a `suggested_fix`: a deterministic repair the runtime's fix planner derived from the *typed* error data — never by parsing a message string. It is optional and additive. An item the planner has no rule for simply omits the field, and a client that ignores `suggested_fix` entirely behaves exactly as before.+A validation error item may carry a `suggested_fix`: a deterministic repair the runtime's fix planner derived from the *typed* error data — never by parsing a message string. It rides a verdict's `validation_errors` item and a problem's `errors` item as the same object. It is optional and additive. An item the planner has no rule for simply omits the field, and a client that ignores `suggested_fix` entirely behaves exactly as before.```json{@@ -120,11 +187,12 @@ For `ensure_table` and `delete_table`, `table_path` addresses the table itself r**The ops are the machine contract; any rendered diff is presentation.** Apply them with a style-preserving TOML editor rather than reconstructing the file from a diff: that is what keeps the caller's formatting, comments, and key order intact.+## Run failures: the root fault, located at the failing pipe-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.+When a run fails, the problem 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 every member is the root fault's — `code`, `type`, `title`, `domain`, `retry`, the HTTP status, the sentences and the parameters — and the wrappers add only where it happened, as the `location` members: `pipe`, the pipe that failed, and `path`, the pipe codes from the entry pipe down to it. A code that declares a `pipe` parameter names the failing pipe in its sentences too. A consumer reads the location from those members, never from a sentence.-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.+So a run the caller's own method or request refuses says what to change: 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 step saying what to change. A model the deck names but does not serve is `model.unavailable`, a **501** in the `operator` domain: the caller's step is to choose another model or ask whoever runs the server to serve it, and the operator's to configure a backend for it.```httpHTTP/1.1 422 Unprocessable Entity@@ -134,56 +202,65 @@ Content-Type: application/problem+json"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",+ "detail": "Pipe 'analyze_topic' produced an output of the multiplicity 'list', but its output 'ideas' is declared 'single'.","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[]'."+ "domain": "method",+ "retry": "no",+ "next_step": {+ "kind": "change_method",+ "detail": "Declare the output 'ideas' as 'list', or make pipe 'analyze_topic' produce 'single'."+ },+ "params": {+ "pipe": "analyze_topic",+ "output": "ideas",+ "produced": "list",+ "declared": "single"+ },+ "location": {+ "pipe": "analyze_topic",+ "path": ["review_topic", "analyze_topic"]},"request_id": "9f2c1ab3-…"}```-The failure of a `/start` run reaches its completion webhook as the same report, under the payload's `error` key (see [Async callbacks](#async-callbacks-webhook-payload)).+In the operator view the same failure adds `diagnostics`, whose `message` is the combine's own restatement, naming the branch whose result it could not combine and the setting to change. The failure of a `/start` run reaches its completion webhook as the same problem, under the payload's `error` key (see [Async callbacks](#async-callbacks-webhook-payload)).## Status codes-The HTTP status follows pipelex's `error_domain_to_http_status`:+The HTTP status of a failure the runtime raised is the one its code declares in the registry, the `status` member's value, and each code's page on [Error Codes](../errors/index.md) states it. A code the registries give none, which only a client's own failure has, answers **500**. Two codes of the same domain can answer different statuses, so a client reads `code`, `domain` and `retry`, never the status, to decide what to do. The statuses a run meets most:-- `error_domain = "input"` → **422** — the caller can fix it (bad `.mthds`, malformed arguments, validation failure).-- `error_domain = "config"` → **500** — the deployment needs a fix (missing env var, bad TOML override).-- `error_domain = "runtime"` → **500** — failure during execution (worker crash, upstream service failure).-- Unclassified / unknown → **500**.+- **422** — the caller's request or method: `method.invalid` and the method's other codes, `input.missing` and the input's other codes, `request.pipe_not_found`, `request.pipe_ambiguous`, `model.unknown`, `model.content_refused`.+- **429** — `provider.rate_limited`: an upstream inference provider rate-limited the run, a retry can succeed, and `Retry-After` is set when the provider gave a delay. Only `POST /v1/execute` runs inference, so only `/execute` can produce it.+- **500** — the operator's configuration, such as `pipelex.config.variable_missing` or `pipelex.config.invalid`, and the catch-all `runtime.unexpected`.+- **501** — something this deployment does not serve: `model.unavailable`, a model it serves no backend for; `runtime.unsupported`, async pipeline execution (`POST /v1/start`) on a deployment that does not provide it.+- **502** — an upstream service failed: `provider.unavailable`, `provider.failed`, `provider.quota_exhausted`, `provider.credential_refused`, `method.fetch_failed`. A **504** is `provider.timeout`.-A few specific statuses bypass the domain mapping:+A few runtime refusals worth knowing by their code:-- **400** — a well-formed request this deployment cannot serve. `error_type = "StartRequiresAsyncOrchestration"`: `POST /v1/start` is fire-and-forget by nature, and this deployment's orchestrator is blocking-only (the in-process `direct` default), so it refuses honestly rather than blocking and acking — use `POST /v1/execute` instead.-- **400** — `error_type = "BadRequest"`: the client disconnected before its request body was received in full. The client is gone before the answer, so this one is seen in the server's logs, at warning level.-- **401** — missing/invalid bearer token. `WWW-Authenticate: Bearer` is set. Only reachable when the deployment enables auth (`AUTH_MODE=api_key` or `AUTH_MODE=jwt`).-- **403** — authenticated but not authorized, or refused by deployment policy. The cases: a storage-ownership mismatch; `error_type = "ReadScopeForbidden"` — on a `jwt` deployment, the request sent a `read_scope` that does not lie under the caller's own `user_id`, which is the only scope its token may read (see [Pipe Run](pipe-run.md#host-supplied-run-context-storage_scope-and-analytics_groups)); `error_type = "OrchestrationModeOverrideForbidden"` — the request asked for an `orchestration_mode` this deployment does not allow overriding per request (`allow_request_orchestration_mode_override = false`); `error_type = "BlobUploadNotAuthorized"` — a `PUT /v1/blobs/{sha256}` without a valid upload target: its signature is missing, forged, expired, or signed for another hash or scope, so ask `POST /v1/blobs/missing` for a fresh target; `error_type = "CustomCodeRequiresSandbox"` — the method (a tree sent with the request, or a fetched `method_ref` package) holds custom Python `.py` files and this deployment is not sandbox-hosted, so running caller-supplied code in-process is refused; `error_type = "MethodStructuresRefusedError"` — a fetched `method_ref` package declares in-process Python structure classes (`StructuredContent` subclasses), which hosted execution always refuses, sandbox or not — express the types as MTHDS concepts with inline structures instead (see [Pipe Run](pipe-run.md#running-a-method-by-address-method_ref)).-- **404** — `error_type = "MethodPackageNotFoundError"`: the `method_ref` repository was fetched, but no package in it matches the requested address by manifest identity. The `detail` lists the package addresses the repository does contain, so the caller can correct the selector.-- **409** — `error_type = "PipelineManagerAlreadyExistsError"`: the submitted `pipeline_run_id` is already registered for a run that is still in flight on this server. Completed and failed runs free their id, so this only fires for genuinely concurrent duplicates — resubmit after the in-flight run finishes, or pick a fresh id. Only `POST /v1/start` accepts a client-supplied `pipeline_run_id`, so only `/start` can produce it.-- **413** — request body exceeds the configured size limit (`MAX_REQUEST_BODY_MIB`, 100 MiB by default), or a part of it exceeds its own: a `bundle_b64` archive over `MAX_BUNDLE_FILES` or `MAX_BUNDLE_TOTAL_KIB`, or `resources` over `MAX_RESOURCES_PER_REQUEST`, `MAX_RESOURCE_FILE_KIB` or `MAX_RESOURCES_TOTAL_KIB` (`error_type = "PayloadTooLarge"`).-- **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.+- **404** — `method.not_found`: the `method_ref` repository was fetched, but no package in it matches the requested address by manifest identity, or it holds no such tag. The problem's sentences name the reference.+- **409** — `pipelex.run.already_exists`: the submitted `pipeline_run_id` is already registered for a run that is still in flight on this server. Completed and failed runs free their id, so this only fires for genuinely concurrent duplicates — resubmit after the in-flight run finishes, or pick a fresh id. Only `POST /v1/start` accepts a client-supplied `pipeline_run_id`, so only `/start` can produce it.+- **422** — the `method_ref` resolution refusals the caller can fix: `request.invalid` for a reference that does not parse, `method.ambiguous`, and `method.package_invalid` for a package past its limits or carrying a symbolic link. `pipelex.deployment.python_structures_refused` is a **422** too: a method, fetched by `method_ref` or sent as a tree, declares in-process Python structure classes (`StructuredContent` subclasses), which hosted execution always refuses, sandbox or not — express the types as MTHDS concepts with inline structures instead (see [Pipe Run](pipe-run.md#running-a-method-by-address-method_ref)).-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.+The API's own refusals, which carry an `error_type` and no code, answer these statuses:++- **400** — `StartRequiresAsyncOrchestration`: `POST /v1/start` is fire-and-forget by nature, and this deployment's orchestrator is blocking-only (the in-process `direct` default), so it refuses honestly rather than blocking and acking — use `POST /v1/execute` instead. `BadRequest`: the client disconnected before its request body was received in full, which only the server's logs show, at warning level, since the client is gone before the answer; or a forwarded `X-User-Id` is not a single path-safe segment.+- **401** — `Unauthenticated`, `InvalidToken` or `TokenExpired`: a missing, invalid or expired bearer token, with `WWW-Authenticate: Bearer` set. Only reachable when the deployment enables auth (`AUTH_MODE=api_key` or `AUTH_MODE=jwt`), or trusts a proxy that forwarded no identity.+- **403** — `ReadScopeForbidden`: on a `jwt` deployment, the request sent a `read_scope` that does not lie under the caller's own `user_id`, which is the only scope its token may read (see [Pipe Run](pipe-run.md#host-supplied-run-context-storage_scope-and-analytics_groups)). `OrchestrationModeOverrideForbidden`: the request asked for an `orchestration_mode` this deployment does not allow overriding per request (`allow_request_orchestration_mode_override = false`). `BlobUploadNotAuthorized`: a `PUT /v1/blobs/{sha256}` without a valid upload target, its signature missing, forged, expired, or signed for another hash or scope, so ask `POST /v1/blobs/missing` for a fresh target. `CustomCodeRequiresSandbox`: the method (a tree sent with the request, or a fetched `method_ref` package) holds custom Python `.py` files and this deployment is not sandbox-hosted, so running caller-supplied code in-process is refused.+- **413** — `PayloadTooLarge`: the request body exceeds the configured size limit (`MAX_REQUEST_BODY_MIB`, 100 MiB by default), or a part of it exceeds its own: a `bundle_b64` archive over `MAX_BUNDLE_FILES` or `MAX_BUNDLE_TOTAL_KIB`, or `resources` over `MAX_RESOURCES_PER_REQUEST`, `MAX_RESOURCE_FILE_KIB` or `MAX_RESOURCES_TOTAL_KIB`.+- **501** — `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`. It is permanent under the current deployment — do not retry.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.The run routes read their body as plain JSON before anything else, and two refusals come from that step, both **422**. A body that is not valid UTF-8, not valid JSON, nested too deeply, or not a JSON object answers `InvalidJSON`. A body carrying, in any object at any depth, a key named `__class__` or `__module__`, or a key starting with `__kajson`, answers `ReservedObjectKey`, and the `detail` names the key, cut short when it is long. Those are the keys a kajson decoder reads as an order to import and instantiate a class, so the runner refuses them rather than carry them as data. Only keys are checked: a string value that mentions `__class__` is accepted.-A pipe selection the server cannot make is an input **422** named for its failure, never the generic `ValidationError`: `EntryPipeNotFoundError` when the selector names no pipe, and `EntryPipeAmbiguousError` when a bare code matches pipes in several domains. The run routes answer an unknown or ambiguous `pipe_code` that way. `POST /v1/pipe-io` answers every selection refusal that way, counting a request with no `pipe_ref` over a method that declares no `main_pipe` as `EntryPipeNotFoundError` and one over a method whose domains declare several as `EntryPipeAmbiguousError` (see [Pipe I/O](pipe-io.md#pipe-selection)).+A pipe selection the server cannot make is an input **422** named for its failure: `request.pipe_not_found` when the selector names no pipe, and `request.pipe_ambiguous` when a bare code, or a dependency's `alias->code`, matches pipes in several domains, naming the pipes it matched as its `candidates`. The run routes answer an unknown or ambiguous `pipe_code` that way. `POST /v1/pipe-io` answers every selection refusal that way, counting a request with no `pipe_ref` over a method that declares no `main_pipe`, or whose domains declare several, as `request.pipe_unspecified`, which names the declared ones as its `candidates`, and a manifest `main_pipe` the method lacks or declares in several domains as the method's own `method.pipe_unresolved` or `method.ref_ambiguous` (see [Pipe I/O](pipe-io.md#pipe-selection)).The run routes' extension fields are validated before any method is fetched or any library loaded, and a failure there is a **422** whose `error_type` names the field that failed: `InvalidCallbackUrls` for `callback_urls`, `InvalidStorageScope` for `storage_scope`, `InvalidReadScope` for `read_scope`, `InvalidAnalyticsGroups` for `analytics_groups` (see [Pipe Run](pipe-run.md#host-supplied-run-context-storage_scope-and-analytics_groups)). A storage scope that does not lie under the run's read scope, whether either was sent or defaulted, is an `InvalidReadScope` as well. A failure on another extension field, or on more than one at once, carries the generic `ValidationError`, and the `detail` names every field that failed. `POST /v1/validate` takes `analytics_groups` too and classifies it the same way: a body failing on that field alone answers `InvalidAnalyticsGroups`, and one failing on it and another field answers `ValidationError`.A method sent as a tree, in `files` or `bundle_b64`, is read under the MTHDS standard's tree rule before anything loads, on the run routes and `/validate` alike (see [Pipe Run](pipe-run.md#sending-a-method-as-a-tree)). A key or an entry the rule refuses, two shipped packages a reference could not tell apart, or `dependencies` that do not fit the request is a **422** `InvalidMethodFiles` carrying `tree_refusal` when the standard's reader refused it; a hash entry this runner does not hold is a **422** `MissingBlobs` carrying `missing_blobs`, and one it holds at another size than the entry states a **422** `BlobMismatch` carrying `mismatched_blobs`; a tree past `MAX_METHOD_TREE_FILES`, `MAX_METHOD_TREE_FILE_KIB` or `MAX_METHOD_TREE_TOTAL_KIB`, or a method past `MAX_METHOD_DEPENDENCIES` or `MAX_METHOD_REQUEST_TOTAL_KIB` across its trees, is a **422** `MethodTreeTooLarge`. The blob routes answer in the same vocabulary: a body whose SHA-256 is not the one its path names, or one hash listed with two sizes, is a **422** `BlobMismatch`, and a blob past the per-file limit a **422** `MethodTreeTooLarge`. Every one of these carries `retryable: false`. Bytes the blob store holds under a hash that do not hash to it, or an upload whose bytes hash to an object held at another size, are a **500** `BlobStoreCorrupted`: the deployment's storage is damaged, the runner never writes over a blob, and its operator removes the object for the blob to be uploaded again.-The files a request sends in `resources` are checked before the bundle loads and again once it is parsed (see [Pipe Validate](pipe-validate.md#sending-the-files-the-steps-read-resources)). A key that cannot name a file inside the bundle is a **422** `InvalidResourcePath`, a value that is not base64 a **400** `InvalidBase64`, a file none of the bundle's steps names a **422** `BundleResourceNotNamedError`, and files that cannot make one method tree, such as two keys equal once case-folded, a **422** `BundleResourcePathError`, on every route, the diagnostic ones included: both are the request's fault, not the bundle's, and every one of these refusals carries `retryable: false`, since the same request is refused again.+The files a request sends in `resources` are checked before the bundle loads and again once it is parsed (see [Pipe Validate](pipe-validate.md#sending-the-files-the-steps-read-resources)). A key that cannot name a file inside the bundle is a **422** `InvalidResourcePath` and a value that is not base64 a **400** `InvalidBase64`, both the API's own refusals; a file none of the bundle's steps names, and files that cannot make one method tree, such as two keys equal once case-folded, are **422** problems with the code `request.invalid`, or `security.input_path_refused` for a path the tree rule refuses, on every route, the diagnostic ones included: they are the request's fault, not the bundle's, and none invites a retry, since the same request is refused again.The HTTP status is the source of truth for success vs failure — there is no `success: true/false` field anywhere in the envelope.@@ -191,22 +268,6 @@ Which statuses a given route can actually produce is documented per operation in**What is *not* an error status:** an invalid `.mthds` bundle. On the diagnostic routes — `/validate`, `/resolve`, `/codegen`, and `/pipe-io` — a bundle that fails validation is the *successful product* of the call, so it rides a **200** discriminated on `is_valid: false`, carrying the same `validation_errors[]` described above. Non-2xx on those routes is reserved for *no verdict could be produced*. See [Pipe Validate](pipe-validate.md).-## Disclosure modes--The `ERROR_DISCLOSURE` env var controls how much of the originating error makes it onto the wire:--- `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 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.--Server logs are always verbose regardless of `ERROR_DISCLOSURE` — the operator sees the full picture, the caller sees what the error chose to disclose.--The mode governs **every** response, including the catch-all 500 (`error_category: "unknown"` — a failure that matched no more specific handler). Under `verbose` its `detail` is `"<ExceptionClass>: <message>"`; under `strict` it is the fixed `"An unexpected error occurred. The request id is included for support."`. A traceback never reaches the caller in either mode.--An unclassified failure is the one error a caller cannot diagnose from a request id alone, so it is exactly the one a `verbose` deployment must not turn into a dead end. If you want unclassified failures opaque, that is what `strict` is for — and note it redacts by message provenance, so a deployment wanting *nothing* leaked should set `strict` rather than rely on the catch-all to be silent.-## The `type` URI`type` is the page of the error's `code`:@@ -230,12 +291,13 @@ When opening an issue, include the `request_id` from the response (or response h## Examples-### 422 — input validation failure+### 422 — a method that does not validate```httpPOST /v1/execute{- "mthds_contents": ["domain = \"broken\"\nmain_pipe = \"Not A Valid Pipe Code!\"\n"]+ "mthds_contents": ["domain = \"summaries\"\nmain_pipe = \"summarize\"\n\n[pipe.summarize]\ntype = \"PipeLLM\"\ndescription = \"Summarize a text\"\ninputs = { text = \"Text\" }\noutput = \"Text\"\nprompt = \"Summarize $text in the style of $tone.\"\n"],+ "mthds_sources": ["summaries.mthds"]}```@@ -248,28 +310,27 @@ X-Request-ID: 9f2c1ab3-…"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",+ "detail": "The method does not validate.","code": "method.invalid",- "error_type": "ValidateBundleError",- "error_domain": "input",- "user_action": {- "kind": "change_input",- "detail": "Edit the bundle as each validation error says: apply its suggested fix where it has one, after confirming an unsafe one"+ "domain": "method",+ "retry": "no",+ "next_step": {+ "kind": "change_method",+ "detail": "Fix each fault the problem's errors list, then validate the method again."},- "request_id": "9f2c1ab3-…",- "validation_errors": [+ "errors": [{- "category": "blueprint_validation",- "message": "Value error, Invalid main pipe syntax 'Not A Valid Pipe Code!'. Must be in snake_case.",- "error_type": "invalid_pipe_code_syntax",- "domain_code": "broken"+ "code": "method.input_undeclared",+ "detail": "Pipe 'summarize' reads names its inputs do not declare: tone.",+ "params": { "pipe": "summarize", "variables": ["tone"] },+ "location": { "pipe": "summarize", "file": "summaries.mthds" }}- ]+ ],+ "request_id": "9f2c1ab3-…"}```-The single `detail` is the human summary; `validation_errors` is the machine-readable list a client maps to per-line diagnostics. Only the run routes answer an invalid bundle with this 422 — on the diagnostic routes the same bundle is a **200 `is_valid: false`** verdict, where per-file `source` attribution is also available — see [Structured validation errors](#structured-validation-errors) and [Sourcing submitted files](pipe-validate.md).+The `detail` is the human summary; `errors` is the machine-readable list a client maps to per-line diagnostics. Only the run routes answer an invalid bundle with this 422 — on the diagnostic routes the same bundle is a **200 `is_valid: false`** verdict carrying the items whole as `validation_errors` — see [Structured validation errors](#structured-validation-errors) and [Sourcing submitted files](pipe-validate.md).### 500 — deployment configuration fault@@ -282,19 +343,19 @@ X-Request-ID: 9f2c1ab3-…"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",+ "detail": "A variable the runtime's configuration refers to is not set.","code": "pipelex.config.variable_missing",- "error_type": "EnvVarNotFoundError",- "error_domain": "config",- "retryable": false,+ "domain": "operator",+ "retry": "no",+ "next_step": {+ "kind": "report",+ "detail": "Report this to whoever runs the runtime."+ },"request_id": "9f2c1ab3-…"}```-`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 `"An internal error occurred."` — the env var name lives in the server log only, and `code` still names the fault.+`pipelex.config.variable_missing` is a code in the `operator` domain: the deployment, not the caller, has to fix it, so the caller's step is to report it. The operator view of the same failure carries the `fix_configuration` step and `diagnostics`, whose `message` names the variable, `Missing required environment variable: COMPLETION_CALLBACK_SECRET`, which no caller reads.### 401 — missing bearer token@@ -310,15 +371,15 @@ X-Request-ID: 9f2c1ab3-…"status": 401,"detail": "Missing bearer token.","instance": "/v1/execute",+ "request_id": "9f2c1ab3-…","error_type": "Unauthenticated","error_domain": "input",- "retryable": false,- "request_id": "9f2c1ab3-…"+ "retryable": false}```## Async callbacks (webhook payload)-For [async pipeline runs](pipe-run.md) registering a `callback_url`, the failure payload delivered to the caller's webhook **does not** use this envelope. The webhook body carries the raw `ErrorReport` dict under an `error` key, alongside `pipeline_run_id` (the protocol field) plus the runtime's legacy `pipeline_run_id` / `status` keys — a non-HTTP receiver (queue, log shipper) does not necessarily want an RFC 7807 wrapper.+For [async pipeline runs](pipe-run.md) registering a `callback_url`, the payload delivered to the caller's webhook **does not** use this envelope: it is a completion notice carrying `pipeline_run_id`, the delivery `state` (also sent under the legacy `status` key) and, when results were stored, `result_url`. A failed run adds its problem under an `error` key, so a non-HTTP receiver such as a queue or a log shipper reads the same `code`, `domain`, `retry`, sentences and `location` as the synchronous answer, without an HTTP status.-The classification fields (`error_type`, `error_domain`, `retryable`, etc.) surface identically on both paths; only the envelope members (`type`, `status`, `detail`, `instance`, `request_id`) are sync-only. See [Pipe Run → Async Completion Callbacks](pipe-run.md) for the full webhook contract.+The problem rides in the view of whoever started the run, as the request that started it authenticated them: a `/start` request carrying the operator's credential, or forwarded by the trusted proxy, has its webhooks carry the operator view, `diagnostics` included, and any other request the caller view. A host that builds its own webhook targets picks the view with `WebhookTarget.problem_view`, which is the caller view when it names none. The problem is built only when the run has a webhook to deliver it to, and building it never changes how the run fails: a problem that cannot be built is logged as an error, and the webhooks receive `runtime.unexpected` while the run fails with its own error. See [Pipe Run → Async Completion Callbacks](pipe-run.md) for the full webhook contract.diff --git a/docs/api-server/index.md b/docs/api-server/index.mdindex d9510cd5d..e61d98583 100644--- a/docs/api-server/index.md+++ b/docs/api-server/index.md@@ -136,7 +136,7 @@ docker run --name pipelex-api -p 8081:8081 \## API Endpoints-Every failure is an RFC 7807 `application/problem+json` problem document — see **[Error Responses →](error-responses.md)**, and the [committed OpenAPI artifact](openapi/pipelex-api.openapi.yaml) for the statuses each route can produce.+Every failure is an RFC 9457 `application/problem+json` problem document — see **[Error Responses →](error-responses.md)**, and the [committed OpenAPI artifact](openapi/pipelex-api.openapi.yaml) for the statuses each route can produce.### Health & Versiondiff --git a/docs/api-server/logging.md b/docs/api-server/logging.mdindex f67743ed6..54423f16d 100644--- a/docs/api-server/logging.md+++ b/docs/api-server/logging.md@@ -12,7 +12,7 @@ An error response produces exactly one line. A caller mistake:A server fault looks the same at `ERROR`, and carries the traceback under an `exception` key.-The `message` is the same sentence on every error line, `A request ended in an error response`, whichever failure it reports, so it is the key a query or an alert selects this server's error stream by, following the [log-call conventions](../tools/logging.md#log-call-conventions). Everything about the failure, the HTTP status and the error type included, rides a field of its own, and nothing a caller supplied ever reaches the message: the caller-facing explanation rides the `detail` field instead, so a body crafted with newlines or quotes cannot break the line or forge a key. Two layers keep the `detail` value safe to write. Before any sink sees a record, the Pipelex runtime's redaction processor replaces a control character in a field's value with its printable escape, so a newline a caller sent reads as `\n` in `detail`, and replaces a credential it recognises, an `Authorization` header's token or an API key, with `[REDACTED]`. The sink then escapes what it writes, so a quote or an `=` stays inside its value. The processor is configured under `[runtime.log.redaction]` and is on by default.+The `message` is the same sentence on every error line, `A request ended in an error response`, whichever failure it reports, so it is the key a query or an alert selects this server's error stream by, following the [log-call conventions](../tools/logging.md#log-call-conventions). Everything about the failure, the HTTP status and the error type included, rides a field of its own, and nothing a caller supplied ever reaches the message: the API's explanation of a refusal rides the `detail` field instead, so a body crafted with newlines or quotes cannot break the line or forge a key. Two layers keep the `detail` value safe to write. Before any sink sees a record, the Pipelex runtime's redaction processor replaces a control character in a field's value with its printable escape, so a newline a caller sent reads as `\n` in `detail`, and replaces a credential it recognises, an `Authorization` header's token or an API key, with `[REDACTED]`. The sink then escapes what it writes, so a quote or an `=` stays inside its value. The processor is configured under `[runtime.log.redaction]` and is on by default.## The fields a line carries@@ -38,16 +38,17 @@ The remaining keys are what the error handlers attach to an error line. The ones| --- | --- || `url.path` | The request's URL path || `http.response.status_code` | The HTTP status actually sent, including any API-level override |-| `error.type` | The class or `ErrorType` name the response reports, which the response body carries as `error_type` |-| `error_domain` | `input`, `config`, `runtime`, … — who fixes it |-| `error_category` | A Pipelex classification, on the failures it classifies; `unknown` on the catch-all 500 |-| `retryable` | Whether a blind retry can help, when the failure says |-| `detail` | The operator-facing explanation, the same text the response body carries — on an API-authored failure only, see below |+| `error.code` | The code of the problem the response carries, on a failure the runtime raised: the body's `code` |+| `error.type` | On a failure the runtime raised, the class of the exception that escaped, which for an exception that is not a Pipelex error is that exception's own class; on an API-authored failure, the `ErrorType` name the body carries as `error_type` |+| `error_domain` | `input`, `config` or `runtime` — who fixes it. On a failure the runtime raised it is read from the problem's `domain`, the `input` and `method` domains reading `input`, and the `account` and `operator` domains `config` |+| `error_category` | The inference error category, on a failure the cause chain of which carries one |+| `retryable` | Whether a blind retry can help: the problem's `retry` is `yes`, or the API-authored body's `retryable` |+| `detail` | The API's own explanation, the same text the response body carries — on an API-authored failure only, see below || `user.id` | The authenticated caller, when auth bound one. An identity the server refused, a token's `user_id` claim or a forwarded `X-User-Id` that is not a path-safe segment, is never written under it: the warning about the refusal carries the claim's type as `claim_type`, and no value at all for the header || `pipe_code` | The pipe the request named, on a run route whose body parsed || `pipeline_run_id` | The run the request named, on a run route whose body parsed |-| `backend_name`, `model_handle` | The inference backend that served the model and the handle the pipe named it by, on a failure that reached one; the response body carries them as `provider` and `model`. `backend_name` is only ever the backend the error names, which a worker attributes its failure to: a failure no worker attributed carries none, even when the provider's own metadata names who answered, `openai` or `gateway`, since that is neither a backend's name nor an SDK's as the backends configuration spells them, and the record leaves it off rather than write it under `backend_name` or `sdk` |-| `provider_status_code`, `provider_request_id` | The inference provider's own status and request id, on a failure that reached one |+| `backend_name`, `model_handle` | The inference backend that served the model and the handle the pipe named it by, on a failure that reached one; the operator view's `diagnostics` carries them as `provider.name` and `model`. `backend_name` is only ever the backend the error names, which a worker attributes its failure to: a failure no worker attributed carries none, even when the provider's own metadata names who answered, `openai` or `gateway`, since that is neither a backend's name nor an SDK's as the backends configuration spells them, and the record leaves it off rather than write it under `backend_name` or `sdk` |+| `provider_status_code`, `provider_request_id` | The inference provider's own status and request id, on a failure that reached one: the operator view's `diagnostics.provider.status` and `diagnostics.provider.request_id` |A key whose value is not set for this request is **absent** from the line rather than written as `null`, so a query filtering on presence gets an honest answer.@@ -64,9 +65,9 @@ The record took these keys when the server's lines were brought to the log-call| `provider` | `backend_name` || `model` | `model_handle` |-The other keys, `error_domain`, `error_category`, `retryable`, `detail`, `pipe_code`, `pipeline_run_id`, `provider_status_code` and `provider_request_id`, kept their names.+The other keys, `error_domain`, `error_category`, `retryable`, `detail`, `pipe_code`, `pipeline_run_id`, `provider_status_code` and `provider_request_id`, kept their names. `error.code` came later, with the problem document.-`detail` is the one field whose absence follows the failure's origin rather than the request's shape, and it is worth knowing which way round. A failure this API authored itself — a validation error, an unknown model category — carries `detail` on the record. A failure that arrives as a Pipelex `ErrorReport`, which is most `5xx` and every domain error, does not: the response body still carries a `detail`, but the record does not, because the body's text has been through disclosure redaction and the cause has not. So a `4xx` from that path logs its `error.type` with no explanation and no traceback, and the response is where the explanation is. Build an operator query on `error.type` and `url.path`, which every line carries, rather than on `detail`.+`detail` and `error.code` are the two fields whose presence follows the failure's origin rather than the request's shape. A failure this API authored itself — a validation error, an unknown model category — carries `detail` on the record and no `error.code`. A failure the runtime raised, which is every domain error, every run failure and the catch-all, carries `error.code` and no `detail`: its record is built from the problem's operator view, whichever view the response carried, so `error.type` names the class of the error behind it, and the sentence the response carried is the code's, which `error.code` already names. A `5xx` from that path carries the traceback, and a `4xx` none. Build an operator query on `error.code` or `error.type`, with `url.path`, rather than on `detail`.Every field in that table is a **record attribute**, which is a different thing from the message. A structured sink — `json` here, and the OTLP sink — writes them beside the message as keys. The Rich console sink shows them after the message as a `key=value` suffix, each value on one line and cut short when long, a handled exception's `error.message` at a far more generous length, and leaves out the run identifiers (`request_id`, `pipeline_run_id`), which a person at a terminal does not need on every line, so `A request ended in an error response` is followed by the path, the status, the error type and the rest of the fields above. That rendering is for a person reading a terminal; keep `sink = "json"` wherever the lines are read by anything else.diff --git a/docs/api-server/mthds-tools.md b/docs/api-server/mthds-tools.mdindex fe443ab3d..508d28c16 100644--- a/docs/api-server/mthds-tools.md+++ b/docs/api-server/mthds-tools.md@@ -28,7 +28,7 @@ fetch schemas or read local catalog files.`/lint` is a diagnostic endpoint: malformed `.mthds` content returns HTTP 200with diagnostics in the body. Request-shape problems, such as missing `content`-or a file over the configured per-file limit, return RFC 7807 problem responses.+or a file over the configured per-file limit, return RFC 9457 problem responses.```json{@@ -77,7 +77,7 @@ An empty `diagnostics` array means the file is clean.Syntax errors return HTTP 200 with the original content unchanged and diagnosticsdescribing the blocking issue. Malformed formatter options, such as a non-numeric-`column_width`, are caller input errors and return RFC 7807 422 responses.+`column_width`, are caller input errors and return RFC 9457 422 responses.```json{diff --git a/docs/api-server/openapi/pipelex-api.openapi.yaml b/docs/api-server/openapi/pipelex-api.openapi.yamlindex 771b030cd..0c4559446 100644--- a/docs/api-server/openapi/pipelex-api.openapi.yaml+++ b/docs/api-server/openapi/pipelex-api.openapi.yaml@@ -67,8 +67,8 @@ paths:schema:$ref: '#/components/schemas/PipelexVersionInfo''500':- description: A `config`-domain or `runtime`-domain failure the caller cannot fix (a missing env var, a bad TOML- override, a backend fault), or an unclassified error sanitized by the catch-all handler. Report the `request_id`.+ description: A failure the caller cannot fix (a missing env var, a bad TOML override, a backend fault), or an unexpected+ error answered as `runtime.unexpected`. Report the `request_id`.content:application/problem+json:schema:@@ -153,16 +153,16 @@ paths:schema:$ref: '#/components/schemas/ProblemDocument''422':- description: 'The request could not be processed: a malformed body, a field failing validation, or an `input`-domain- pipelex error (a `.mthds` bundle the caller must fix). Note that on the diagnostic routes an *invalid bundle*- is a **200** verdict, not a 422 — see each route''s response contract.'+ description: 'The request could not be processed: a malformed body, a field failing validation, or a pipelex error+ whose code the caller fixes (a `.mthds` bundle that does not validate, a missing input). Note that on the diagnostic+ routes an *invalid bundle* is a **200** verdict, not a 422 — see each route''s response contract.'content:application/problem+json:schema:$ref: '#/components/schemas/ProblemDocument''500':- description: A `config`-domain or `runtime`-domain failure the caller cannot fix (a missing env var, a bad TOML- override, a backend fault), or an unclassified error sanitized by the catch-all handler. Report the `request_id`.+ description: A failure the caller cannot fix (a missing env var, a bad TOML override, a backend fault), or an unexpected+ error answered as `runtime.unexpected`. Report the `request_id`.content:application/problem+json:schema:@@ -449,16 +449,16 @@ paths:schema:$ref: '#/components/schemas/ProblemDocument''422':- description: 'The request could not be processed: a malformed body, a field failing validation, or an `input`-domain- pipelex error (a `.mthds` bundle the caller must fix). Note that on the diagnostic routes an *invalid bundle*- is a **200** verdict, not a 422 — see each route''s response contract.'+ description: 'The request could not be processed: a malformed body, a field failing validation, or a pipelex error+ whose code the caller fixes (a `.mthds` bundle that does not validate, a missing input). Note that on the diagnostic+ routes an *invalid bundle* is a **200** verdict, not a 422 — see each route''s response contract.'content:application/problem+json:schema:$ref: '#/components/schemas/ProblemDocument''500':- description: A `config`-domain or `runtime`-domain failure the caller cannot fix (a missing env var, a bad TOML- override, a backend fault), or an unclassified error sanitized by the catch-all handler. Report the `request_id`.+ description: A failure the caller cannot fix (a missing env var, a bad TOML override, a backend fault), or an unexpected+ error answered as `runtime.unexpected`. Report the `request_id`.content:application/problem+json:schema:@@ -467,18 +467,16 @@ paths:description: 'A deployment-policy refusal: `OrchestrationModeOverrideForbidden` — the request asked for an `orchestration_mode`this deployment does not allow overriding per request (`allow_request_orchestration_mode_override = false`); `CustomCodeRequiresSandbox`— the method (a bundle, or a fetched `method_ref` package) ships custom Python and this deployment is not sandbox-hosted;- or `MethodStructuresRefusedError` — the method''s Python declares structure classes (`StructuredContent` subclasses),- whether it arrived as a bundle (`files` or `bundle_b64`) or as a fetched `method_ref` package: a sandbox-hosted- deployment imports no caller Python into its own process, so it refuses them before loading anything (express- the types as MTHDS concepts instead); or `ReadScopeForbidden` — on a `jwt` deployment, the request sent a `read_scope`- that does not lie under the caller''s own `user_id`.'+ or `ReadScopeForbidden` — on a `jwt` deployment, the request sent a `read_scope` that does not lie under the caller''s+ own `user_id`. The refusal of a method whose Python declares structure classes, `pipelex.deployment.python_structures_refused`,+ is a 422 instead, since the method''s author changes it.'content:application/problem+json:schema:$ref: '#/components/schemas/ProblemDocument''404':- description: '`MethodPackageNotFoundError` — the `method_ref` repository was fetched, but no package in it matches- the requested address by manifest identity. The message lists the packages the repository does contain.'+ description: '`method.not_found` — the `method_ref` repository was fetched, but no package in it matches the requested+ address by manifest identity.'content:application/problem+json:schema:@@ -802,16 +800,16 @@ paths:schema:$ref: '#/components/schemas/ProblemDocument''422':- description: 'The request could not be processed: a malformed body, a field failing validation, or an `input`-domain- pipelex error (a `.mthds` bundle the caller must fix). Note that on the diagnostic routes an *invalid bundle*- is a **200** verdict, not a 422 — see each route''s response contract.'+ description: 'The request could not be processed: a malformed body, a field failing validation, or a pipelex error+ whose code the caller fixes (a `.mthds` bundle that does not validate, a missing input). Note that on the diagnostic+ routes an *invalid bundle* is a **200** verdict, not a 422 — see each route''s response contract.'content:application/problem+json:schema:$ref: '#/components/schemas/ProblemDocument''500':- description: A `config`-domain or `runtime`-domain failure the caller cannot fix (a missing env var, a bad TOML- override, a backend fault), or an unclassified error sanitized by the catch-all handler. Report the `request_id`.+ description: A failure the caller cannot fix (a missing env var, a bad TOML override, a backend fault), or an unexpected+ error answered as `runtime.unexpected`. Report the `request_id`.content:application/problem+json:schema:@@ -827,32 +825,30 @@ paths:description: 'A deployment-policy refusal: `OrchestrationModeOverrideForbidden` — the request asked for an `orchestration_mode`this deployment does not allow overriding per request (`allow_request_orchestration_mode_override = false`); `CustomCodeRequiresSandbox`— the method (a bundle, or a fetched `method_ref` package) ships custom Python and this deployment is not sandbox-hosted;- or `MethodStructuresRefusedError` — the method''s Python declares structure classes (`StructuredContent` subclasses),- whether it arrived as a bundle (`files` or `bundle_b64`) or as a fetched `method_ref` package: a sandbox-hosted- deployment imports no caller Python into its own process, so it refuses them before loading anything (express- the types as MTHDS concepts instead); or `ReadScopeForbidden` — on a `jwt` deployment, the request sent a `read_scope`- that does not lie under the caller''s own `user_id`.'+ or `ReadScopeForbidden` — on a `jwt` deployment, the request sent a `read_scope` that does not lie under the caller''s+ own `user_id`. The refusal of a method whose Python declares structure classes, `pipelex.deployment.python_structures_refused`,+ is a 422 instead, since the method''s author changes it.'content:application/problem+json:schema:$ref: '#/components/schemas/ProblemDocument''404':- description: '`MethodPackageNotFoundError` — the `method_ref` repository was fetched, but no package in it matches- the requested address by manifest identity. The message lists the packages the repository does contain.'+ description: '`method.not_found` — the `method_ref` repository was fetched, but no package in it matches the requested+ address by manifest identity.'content:application/problem+json:schema:$ref: '#/components/schemas/ProblemDocument''409':- description: '`PipelineManagerAlreadyExistsError` — the submitted `pipeline_run_id` is still registered for an in-flight+ description: '`pipelex.run.already_exists` — the submitted `pipeline_run_id` is still registered for an in-flightrun. Completed and failed runs free their id, so this only fires for genuinely concurrent duplicates.'content:application/problem+json:schema:$ref: '#/components/schemas/ProblemDocument''501':- description: '`AsyncExecutionNotEnabledError` — this deployment does not provide async pipeline execution. Permanent- under the current deployment; do not retry.'+ description: '`runtime.unsupported` — this deployment does not provide async pipeline execution. Permanent under+ the current deployment; do not retry.'content:application/problem+json:schema:@@ -884,17 +880,18 @@ paths:\ wants the output.\n- **Invalid verdict (200, `is_valid: false`):** the `InvalidReport` arm — `validation_errors[]`\n\\ (the structured per-error diagnostics, built by pipelex's one shared builder, incl. one\n located `dry_run` item\\ per pipe whose dry run failed) + `message`, with the structural artifacts absent. The runner\n returns this as\- \ a value (`ErrorReport` with `validation_errors`) regardless of backend — the\n in-process arm from the bundle's\- \ `ValidateBundleError`, the dispatched arm recovered from the\n worker — so the route maps it to a 200 by matching\- \ validation diagnostics, never by catching an\n exception. Returned `ErrorReport`s without validation diagnostics\- \ are backend/config/runtime\n faults and keep the global RFC 7807 problem response path.\n- **No verdict (non-2xx):**\- \ a malformed request body, an `mthds_sources` length mismatch, or\n both/neither of `mthds_contents` / `method_ref`\- \ is a request-shape **422**; a forbidden\n `orchestration_mode` override is a **403**; a host-wiring programmer\- \ error or a genuine\n orchestrator fault is a **5xx**; auth is **401/403**. A `method_ref` **resolution failure**\n\- \ is also a no-verdict condition — never an `is_valid: false`: a malformed reference or a\n failed fetch is a **422**,\- \ no matching package in the repository a **404**, and the\n custom-Python policy (the sandbox gate, the structures\- \ refusal) a **403**, each with the\n originating error class as `error_type`. All are RFC 7807 `application/problem+json`\n\- \ rendered by the global handler in `pipelex_api.exception_handlers` — routes never shape them."+ \ a value (a `BundleValidationFailure` with `validation_errors`) regardless of backend — the\n in-process arm from\+ \ the bundle's `ValidateBundleError`, the dispatched arm recovered from the\n worker — so the route maps it to a\+ \ 200 by matching validation diagnostics, never by catching an\n exception. A returned failure without validation\+ \ diagnostics is a backend, configuration or runtime\n fault, and its problem is answered as every raised failure's\+ \ is.\n- **No verdict (non-2xx):** a malformed request body, an `mthds_sources` length mismatch, or\n both/neither\+ \ of `mthds_contents` / `method_ref` is a request-shape **422**; a forbidden\n `orchestration_mode` override is a\+ \ **403**; a host-wiring programmer error or a genuine\n orchestrator fault is a **5xx**; auth is **401/403**. A\+ \ `method_ref` **resolution failure**\n is also a no-verdict condition — never an `is_valid: false`: each answers\+ \ the status its\n code declares, such as a **422** for a malformed reference, a **502** for a failed fetch, a\n\+ \ **404** for no matching package in the repository and a **422** for the method's Python\n structure classes, and\+ \ the custom-code sandbox gate a **403**. All are\n `application/problem+json` rendered by the global handlers in\n\+ \ `pipelex_api.exception_handlers` — routes never shape them."operationId: validate_mthds_v1_validate_postrequestBody:content:@@ -936,16 +933,16 @@ paths:schema:$ref: '#/components/schemas/ProblemDocument''422':- description: 'The request could not be processed: a malformed body, a field failing validation, or an `input`-domain- pipelex error (a `.mthds` bundle the caller must fix). Note that on the diagnostic routes an *invalid bundle*- is a **200** verdict, not a 422 — see each route''s response contract.'+ description: 'The request could not be processed: a malformed body, a field failing validation, or a pipelex error+ whose code the caller fixes (a `.mthds` bundle that does not validate, a missing input). Note that on the diagnostic+ routes an *invalid bundle* is a **200** verdict, not a 422 — see each route''s response contract.'content:application/problem+json:schema:$ref: '#/components/schemas/ProblemDocument''500':- description: A `config`-domain or `runtime`-domain failure the caller cannot fix (a missing env var, a bad TOML- override, a backend fault), or an unclassified error sanitized by the catch-all handler. Report the `request_id`.+ description: A failure the caller cannot fix (a missing env var, a bad TOML override, a backend fault), or an unexpected+ error answered as `runtime.unexpected`. Report the `request_id`.content:application/problem+json:schema:@@ -954,18 +951,16 @@ paths:description: 'A deployment-policy refusal: `OrchestrationModeOverrideForbidden` — the request asked for an `orchestration_mode`this deployment does not allow overriding per request (`allow_request_orchestration_mode_override = false`); `CustomCodeRequiresSandbox`— the method (a bundle, or a fetched `method_ref` package) ships custom Python and this deployment is not sandbox-hosted;- or `MethodStructuresRefusedError` — the method''s Python declares structure classes (`StructuredContent` subclasses),- whether it arrived as a bundle (`files` or `bundle_b64`) or as a fetched `method_ref` package: a sandbox-hosted- deployment imports no caller Python into its own process, so it refuses them before loading anything (express- the types as MTHDS concepts instead); or `ReadScopeForbidden` — on a `jwt` deployment, the request sent a `read_scope`- that does not lie under the caller''s own `user_id`.'+ or `ReadScopeForbidden` — on a `jwt` deployment, the request sent a `read_scope` that does not lie under the caller''s+ own `user_id`. The refusal of a method whose Python declares structure classes, `pipelex.deployment.python_structures_refused`,+ is a 422 instead, since the method''s author changes it.'content:application/problem+json:schema:$ref: '#/components/schemas/ProblemDocument''404':- description: '`MethodPackageNotFoundError` — the `method_ref` repository was fetched, but no package in it matches- the requested address by manifest identity. The message lists the packages the repository does contain.'+ description: '`method.not_found` — the `method_ref` repository was fetched, but no package in it matches the requested+ address by manifest identity.'content:application/problem+json:schema:@@ -1030,34 +1025,33 @@ paths:schema:$ref: '#/components/schemas/ProblemDocument''422':- description: 'The request could not be processed: a malformed body, a field failing validation, or an `input`-domain- pipelex error (a `.mthds` bundle the caller must fix). Note that on the diagnostic routes an *invalid bundle*- is a **200** verdict, not a 422 — see each route''s response contract.'+ description: 'The request could not be processed: a malformed body, a field failing validation, or a pipelex error+ whose code the caller fixes (a `.mthds` bundle that does not validate, a missing input). Note that on the diagnostic+ routes an *invalid bundle* is a **200** verdict, not a 422 — see each route''s response contract.'content:application/problem+json:schema:$ref: '#/components/schemas/ProblemDocument''500':- description: A `config`-domain or `runtime`-domain failure the caller cannot fix (a missing env var, a bad TOML- override, a backend fault), or an unclassified error sanitized by the catch-all handler. Report the `request_id`.+ description: A failure the caller cannot fix (a missing env var, a bad TOML override, a backend fault), or an unexpected+ error answered as `runtime.unexpected`. Report the `request_id`.content:application/problem+json:schema:$ref: '#/components/schemas/ProblemDocument''403':description: 'The run routes'' Python policy, applied to the method''s tree: `CustomCodeRequiresSandbox` — the method- (sent in `files`, or a fetched `method_ref` package) ships custom Python and this deployment is not sandbox-hosted;- or `MethodStructuresRefusedError` — the method''s Python declares structure classes (`StructuredContent` subclasses),- which a sandbox-hosted deployment never imports into its own process (express the types as MTHDS concepts instead).+ (sent in `files`, or a fetched `method_ref` package) ships custom Python and this deployment is not sandbox-hosted.Also `ReadScopeForbidden` — on a `jwt` deployment, the request sent a `read_scope` that does not lie under the- caller''s own `user_id`.'+ caller''s own `user_id`. The refusal of a method whose Python declares structure classes, `pipelex.deployment.python_structures_refused`,+ is a 422 instead, since the method''s author changes it.'content:application/problem+json:schema:$ref: '#/components/schemas/ProblemDocument''404':- description: '`MethodPackageNotFoundError` — the `method_ref` repository was fetched, but no package in it matches- the requested address by manifest identity. The message lists the packages the repository does contain.'+ description: '`method.not_found` — the `method_ref` repository was fetched, but no package in it matches the requested+ address by manifest identity.'content:application/problem+json:schema:@@ -1132,34 +1126,33 @@ paths:schema:$ref: '#/components/schemas/ProblemDocument''422':- description: 'The request could not be processed: a malformed body, a field failing validation, or an `input`-domain- pipelex error (a `.mthds` bundle the caller must fix). Note that on the diagnostic routes an *invalid bundle*- is a **200** verdict, not a 422 — see each route''s response contract.'+ description: 'The request could not be processed: a malformed body, a field failing validation, or a pipelex error+ whose code the caller fixes (a `.mthds` bundle that does not validate, a missing input). Note that on the diagnostic+ routes an *invalid bundle* is a **200** verdict, not a 422 — see each route''s response contract.'content:application/problem+json:schema:$ref: '#/components/schemas/ProblemDocument''500':- description: A `config`-domain or `runtime`-domain failure the caller cannot fix (a missing env var, a bad TOML- override, a backend fault), or an unclassified error sanitized by the catch-all handler. Report the `request_id`.+ description: A failure the caller cannot fix (a missing env var, a bad TOML override, a backend fault), or an unexpected+ error answered as `runtime.unexpected`. Report the `request_id`.content:application/problem+json:schema:$ref: '#/components/schemas/ProblemDocument''403':description: 'The run routes'' Python policy, applied to the method''s tree: `CustomCodeRequiresSandbox` — the method- (sent in `files`, or a fetched `method_ref` package) ships custom Python and this deployment is not sandbox-hosted;- or `MethodStructuresRefusedError` — the method''s Python declares structure classes (`StructuredContent` subclasses),- which a sandbox-hosted deployment never imports into its own process (express the types as MTHDS concepts instead).+ (sent in `files`, or a fetched `method_ref` package) ships custom Python and this deployment is not sandbox-hosted.Also `ReadScopeForbidden` — on a `jwt` deployment, the request sent a `read_scope` that does not lie under the- caller''s own `user_id`.'+ caller''s own `user_id`. The refusal of a method whose Python declares structure classes, `pipelex.deployment.python_structures_refused`,+ is a 422 instead, since the method''s author changes it.'content:application/problem+json:schema:$ref: '#/components/schemas/ProblemDocument''404':- description: '`MethodPackageNotFoundError` — the `method_ref` repository was fetched, but no package in it matches- the requested address by manifest identity. The message lists the packages the repository does contain.'+ description: '`method.not_found` — the `method_ref` repository was fetched, but no package in it matches the requested+ address by manifest identity.'content:application/problem+json:schema:@@ -1229,34 +1222,33 @@ paths:schema:$ref: '#/components/schemas/ProblemDocument''422':- description: 'The request could not be processed: a malformed body, a field failing validation, or an `input`-domain- pipelex error (a `.mthds` bundle the caller must fix). Note that on the diagnostic routes an *invalid bundle*- is a **200** verdict, not a 422 — see each route''s response contract.'+ description: 'The request could not be processed: a malformed body, a field failing validation, or a pipelex error+ whose code the caller fixes (a `.mthds` bundle that does not validate, a missing input). Note that on the diagnostic+ routes an *invalid bundle* is a **200** verdict, not a 422 — see each route''s response contract.'content:application/problem+json:schema:$ref: '#/components/schemas/ProblemDocument''500':- description: A `config`-domain or `runtime`-domain failure the caller cannot fix (a missing env var, a bad TOML- override, a backend fault), or an unclassified error sanitized by the catch-all handler. Report the `request_id`.+ description: A failure the caller cannot fix (a missing env var, a bad TOML override, a backend fault), or an unexpected+ error answered as `runtime.unexpected`. Report the `request_id`.content:application/problem+json:schema:$ref: '#/components/schemas/ProblemDocument''403':description: 'The run routes'' Python policy, applied to the method''s tree: `CustomCodeRequiresSandbox` — the method- (sent in `files`, or a fetched `method_ref` package) ships custom Python and this deployment is not sandbox-hosted;- or `MethodStructuresRefusedError` — the method''s Python declares structure classes (`StructuredContent` subclasses),- which a sandbox-hosted deployment never imports into its own process (express the types as MTHDS concepts instead).+ (sent in `files`, or a fetched `method_ref` package) ships custom Python and this deployment is not sandbox-hosted.Also `ReadScopeForbidden` — on a `jwt` deployment, the request sent a `read_scope` that does not lie under the- caller''s own `user_id`.'+ caller''s own `user_id`. The refusal of a method whose Python declares structure classes, `pipelex.deployment.python_structures_refused`,+ is a 422 instead, since the method''s author changes it.'content:application/problem+json:schema:$ref: '#/components/schemas/ProblemDocument''404':- description: '`MethodPackageNotFoundError` — the `method_ref` repository was fetched, but no package in it matches- the requested address by manifest identity. The message lists the packages the repository does contain.'+ description: '`method.not_found` — the `method_ref` repository was fetched, but no package in it matches the requested+ address by manifest identity.'content:application/problem+json:schema:@@ -1313,16 +1305,16 @@ paths:schema:$ref: '#/components/schemas/ProblemDocument''422':- description: 'The request could not be processed: a malformed body, a field failing validation, or an `input`-domain- pipelex error (a `.mthds` bundle the caller must fix). Note that on the diagnostic routes an *invalid bundle*- is a **200** verdict, not a 422 — see each route''s response contract.'+ description: 'The request could not be processed: a malformed body, a field failing validation, or a pipelex error+ whose code the caller fixes (a `.mthds` bundle that does not validate, a missing input). Note that on the diagnostic+ routes an *invalid bundle* is a **200** verdict, not a 422 — see each route''s response contract.'content:application/problem+json:schema:$ref: '#/components/schemas/ProblemDocument''500':- description: A `config`-domain or `runtime`-domain failure the caller cannot fix (a missing env var, a bad TOML- override, a backend fault), or an unclassified error sanitized by the catch-all handler. Report the `request_id`.+ description: A failure the caller cannot fix (a missing env var, a bad TOML override, a backend fault), or an unexpected+ error answered as `runtime.unexpected`. Report the `request_id`.content:application/problem+json:schema:@@ -1371,16 +1363,16 @@ paths:schema:$ref: '#/components/schemas/ProblemDocument''422':- description: 'The request could not be processed: a malformed body, a field failing validation, or an `input`-domain- pipelex error (a `.mthds` bundle the caller must fix). Note that on the diagnostic routes an *invalid bundle*- is a **200** verdict, not a 422 — see each route''s response contract.'+ description: 'The request could not be processed: a malformed body, a field failing validation, or a pipelex error+ whose code the caller fixes (a `.mthds` bundle that does not validate, a missing input). Note that on the diagnostic+ routes an *invalid bundle* is a **200** verdict, not a 422 — see each route''s response contract.'content:application/problem+json:schema:$ref: '#/components/schemas/ProblemDocument''500':- description: A `config`-domain or `runtime`-domain failure the caller cannot fix (a missing env var, a bad TOML- override, a backend fault), or an unclassified error sanitized by the catch-all handler. Report the `request_id`.+ description: A failure the caller cannot fix (a missing env var, a bad TOML override, a backend fault), or an unexpected+ error answered as `runtime.unexpected`. Report the `request_id`.content:application/problem+json:schema:@@ -1442,16 +1434,16 @@ paths:schema:$ref: '#/components/schemas/ProblemDocument''422':- description: 'The request could not be processed: a malformed body, a field failing validation, or an `input`-domain- pipelex error (a `.mthds` bundle the caller must fix). Note that on the diagnostic routes an *invalid bundle*- is a **200** verdict, not a 422 — see each route''s response contract.'+ description: 'The request could not be processed: a malformed body, a field failing validation, or a pipelex error+ whose code the caller fixes (a `.mthds` bundle that does not validate, a missing input). Note that on the diagnostic+ routes an *invalid bundle* is a **200** verdict, not a 422 — see each route''s response contract.'content:application/problem+json:schema:$ref: '#/components/schemas/ProblemDocument''500':- description: A `config`-domain or `runtime`-domain failure the caller cannot fix (a missing env var, a bad TOML- override, a backend fault), or an unclassified error sanitized by the catch-all handler. Report the `request_id`.+ description: A failure the caller cannot fix (a missing env var, a bad TOML override, a backend fault), or an unexpected+ error answered as `runtime.unexpected`. Report the `request_id`.content:application/problem+json:schema:@@ -1530,16 +1522,16 @@ paths:schema:$ref: '#/components/schemas/ProblemDocument''422':- description: 'The request could not be processed: a malformed body, a field failing validation, or an `input`-domain- pipelex error (a `.mthds` bundle the caller must fix). Note that on the diagnostic routes an *invalid bundle*- is a **200** verdict, not a 422 — see each route''s response contract.'+ description: 'The request could not be processed: a malformed body, a field failing validation, or a pipelex error+ whose code the caller fixes (a `.mthds` bundle that does not validate, a missing input). Note that on the diagnostic+ routes an *invalid bundle* is a **200** verdict, not a 422 — see each route''s response contract.'content:application/problem+json:schema:$ref: '#/components/schemas/ProblemDocument''500':- description: A `config`-domain or `runtime`-domain failure the caller cannot fix (a missing env var, a bad TOML- override, a backend fault), or an unclassified error sanitized by the catch-all handler. Report the `request_id`.+ description: A failure the caller cannot fix (a missing env var, a bad TOML override, a backend fault), or an unexpected+ error answered as `runtime.unexpected`. Report the `request_id`.content:application/problem+json:schema:@@ -1618,16 +1610,16 @@ paths:schema:$ref: '#/components/schemas/ProblemDocument''422':- description: 'The request could not be processed: a malformed body, a field failing validation, or an `input`-domain- pipelex error (a `.mthds` bundle the caller must fix). Note that on the diagnostic routes an *invalid bundle*- is a **200** verdict, not a 422 — see each route''s response contract.'+ description: 'The request could not be processed: a malformed body, a field failing validation, or a pipelex error+ whose code the caller fixes (a `.mthds` bundle that does not validate, a missing input). Note that on the diagnostic+ routes an *invalid bundle* is a **200** verdict, not a 422 — see each route''s response contract.'content:application/problem+json:schema:$ref: '#/components/schemas/ProblemDocument''500':- description: A `config`-domain or `runtime`-domain failure the caller cannot fix (a missing env var, a bad TOML- override, a backend fault), or an unclassified error sanitized by the catch-all handler. Report the `request_id`.+ description: A failure the caller cannot fix (a missing env var, a bad TOML override, a backend fault), or an unexpected+ error answered as `runtime.unexpected`. Report the `request_id`.content:application/problem+json:schema:@@ -1816,6 +1808,64 @@ components:- sizetitle: BlobRefdescription: A blob, named by its SHA-256 in lowercase hexadecimal and its length in bytes.+ BlockedEntry:+ properties:+ entry_id:+ type: string+ title: Entry Id+ to_schema_version:+ type: integer+ title: To Schema Version+ reason:+ $ref: '#/components/schemas/BlockedEntryReason'+ detail:+ type: string+ title: Detail+ guidance:+ anyOf:+ - type: string+ - type: 'null'+ title: Guidance+ applied_ops:+ items:+ oneOf:+ - $ref: '#/components/schemas/DeleteKeyOp'+ - $ref: '#/components/schemas/DeleteTableOp'+ - $ref: '#/components/schemas/RenameTableKeyOp'+ - $ref: '#/components/schemas/MoveKeyOp'+ - $ref: '#/components/schemas/RemapValueOp'+ discriminator:+ propertyName: kind+ mapping:+ delete_key: '#/components/schemas/DeleteKeyOp'+ delete_table: '#/components/schemas/DeleteTableOp'+ move_key: '#/components/schemas/MoveKeyOp'+ remap_value: '#/components/schemas/RemapValueOp'+ rename_table_key: '#/components/schemas/RenameTableKeyOp'+ type: array+ title: Applied Ops+ narrowed_paths:+ items:+ type: string+ type: array+ title: Narrowed Paths+ additionalProperties: false+ type: object+ required:+ - entry_id+ - to_schema_version+ - reason+ - detail+ title: BlockedEntry+ description: An entry that this file needs and the run would not apply.+ BlockedEntryReason:+ type: string+ enum:+ - unsafe+ - conflict+ - value_domain_narrowed+ title: BlockedEntryReason+ description: Why an entry could not be applied to this file.BooleanField:properties:title:@@ -2607,6 +2657,22 @@ components:- rangetitle: Diagnosticdescription: Structured lint/format diagnostic returned by `pipelex-tools-py`.+ DiagnosticCause:+ properties:+ error_class:+ type: string+ title: Error Class+ code:+ anyOf:+ - type: string+ - type: 'null'+ title: Code+ additionalProperties: true+ type: object+ required:+ - error_class+ title: DiagnosticCause+ description: One error of a failure's cause chain, by its class and the code it carries by itself.DocGenFormat:type: stringenum:@@ -3017,33 +3083,6 @@ components:- choicestitle: EnumItemdescription: '`enum` — one of a fixed set of values.'- ErrorSpec:- properties:- error_type:- type: string- title: Error Type- message:- type: string- title: Message- stack:- anyOf:- - type: string- - type: 'null'- title: Stack- caller_facing:- type: boolean- title: Caller Facing- default: false- additionalProperties: false- type: object- required:- - error_type- - message- title: ErrorSpec- description: 'Error information for failed nodes.--- Stack traces are automatically truncated to MAX_STACK_LENGTH.'ExtractSetting:properties:model:@@ -3071,6 +3110,25 @@ components:required:- modeltitle: ExtractSetting+ FileBlockedReason:+ type: string+ enum:+ - unreadable+ - unparseable+ - unsupported_schema_version+ - unwritable+ - changed_during_run+ - needs_a_hand_edit+ - state_uncertain+ title: FileBlockedReason+ description: 'Why a file could not be processed at all.+++ One member per *state the file is in*, because that is what decides what the user does next —++ not one per exception the run happened to catch. Every member but `STATE_UNCERTAIN` leaves the++ file exactly as it was found; that one does not, and it says so.'FixSafety:type: stringenum:@@ -4206,6 +4264,159 @@ components:server-side method-registry resolution exists. Either way the method is held to the run routes'' Python policy:custom `.py` only on a sandbox-hosted deployment, and no Python structure class at all.'+ MigrationErrorBlock:+ properties:+ remedy:+ type: string+ title: Remedy+ would_write:+ type: boolean+ title: Would Write+ needs_attention:+ type: boolean+ title: Needs Attention+ plans:+ items:+ $ref: '#/components/schemas/MigrationPlan'+ type: array+ title: Plans+ additionalProperties: false+ type: object+ required:+ - remedy+ - would_write+ - needs_attention+ - plans+ title: MigrationErrorBlock+ description: 'A pending configuration migration, reported alongside the error it explains.+++ The structured half of the answer to *why does my configuration not load*, carried by the operator''s++ ``diagnostics.migration`` and present only when a scan of this machine''s configuration directories found something++ to say. **Consumers branch on its presence**, never on the message text: an absent block means the failure is not++ staleness. It describes the host''s own configuration directories, so only an operator reads it.+++ ``plans`` is the same shape ``pipelex-agent migrate --dry-run --format json`` emits under its own ``plans`` key,++ deliberately: an agent that reads one has already parsed the other.+++ > **No value read from a user''s file is ever rendered** here either. The plans carry paths, operation kinds and++ > ledger-supplied values, and nothing else.'+ MigrationPlan:+ properties:+ surface_id:+ type: string+ title: Surface Id+ file_path:+ type: string+ format: path+ title: File Path+ blocked_reason:+ anyOf:+ - $ref: '#/components/schemas/FileBlockedReason'+ - type: 'null'+ blocked_detail:+ anyOf:+ - type: string+ - type: 'null'+ title: Blocked Detail+ steps:+ items:+ $ref: '#/components/schemas/MigrationStep'+ type: array+ title: Steps+ blocked:+ items:+ $ref: '#/components/schemas/BlockedEntry'+ type: array+ title: Blocked+ unexplained:+ items:+ $ref: '#/components/schemas/UnexplainedPath'+ type: array+ title: Unexplained+ backup_path:+ anyOf:+ - type: string+ format: path+ - type: 'null'+ title: Backup Path+ was_written:+ type: boolean+ title: Was Written+ default: false+ additionalProperties: false+ type: object+ required:+ - surface_id+ - file_path+ title: MigrationPlan+ description: What one file needs, and what this run did to it.+ MigrationSafety:+ type: string+ enum:+ - safe+ - unsafe+ title: MigrationSafety+ description: 'Whether the applier may act on an entry.+++ Independent of `guidance`, which any entry may carry whatever its safety.'+ MigrationStep:+ properties:+ entry_id:+ type: string+ title: Entry Id+ to_schema_version:+ type: integer+ title: To Schema Version+ title:+ type: string+ title: Title+ description:+ type: string+ title: Description+ breaking:+ type: boolean+ title: Breaking+ safety:+ $ref: '#/components/schemas/MigrationSafety'+ applied_ops:+ items:+ oneOf:+ - $ref: '#/components/schemas/DeleteKeyOp'+ - $ref: '#/components/schemas/DeleteTableOp'+ - $ref: '#/components/schemas/RenameTableKeyOp'+ - $ref: '#/components/schemas/MoveKeyOp'+ - $ref: '#/components/schemas/RemapValueOp'+ discriminator:+ propertyName: kind+ mapping:+ delete_key: '#/components/schemas/DeleteKeyOp'+ delete_table: '#/components/schemas/DeleteTableOp'+ move_key: '#/components/schemas/MoveKeyOp'+ remap_value: '#/components/schemas/RemapValueOp'+ rename_table_key: '#/components/schemas/RenameTableKeyOp'+ type: array+ title: Applied Ops+ additionalProperties: false+ type: object+ required:+ - entry_id+ - to_schema_version+ - title+ - description+ - breaking+ - safety+ - applied_ops+ title: MigrationStep+ description: One ledger entry that changed this file, and the operations of it that fired.MissingBlob:properties:sha256:@@ -4522,6 +4733,23 @@ components:is preserved within a parent and never across parents — see ``docs/migration-ledger.md``for the placement rule and for what happens to a moved table''s introducing comment.'+ NextStep:+ properties:+ kind:+ anyOf:+ - $ref: '#/components/schemas/StepKind'+ - type: string+ title: Kind+ detail:+ type: string+ title: Detail+ additionalProperties: true+ type: object+ required:+ - kind+ - detail+ title: NextStep+ description: 'What the reader should do next: a kind from the protocol''s closed list, and the step in one sentence.'NodeIOSpec:properties:inputs:@@ -4598,8 +4826,13 @@ components:$ref: '#/components/schemas/NodeIOSpec'error:anyOf:- - $ref: '#/components/schemas/ErrorSpec'+ - $ref: '#/components/schemas/PipelexProblem'+ - type: 'null'+ error_stack:+ anyOf:+ - type: string- type: 'null'+ title: Error Stacktags:additionalProperties:type: string@@ -6775,6 +7008,96 @@ components:(e.g. `default-small`) legitimately exists in several categories pointing atdifferent models, so a flat map would silently lose entries on collision.'+ PipelexProblem:+ properties:+ type:+ type: string+ title: Type+ title:+ type: string+ title: Title+ status:+ anyOf:+ - type: integer+ ge: 100+ le: 599+ - type: 'null'+ title: Status+ detail:+ type: string+ title: Detail+ code:+ type: string+ pattern: ^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,2}$+ title: Code+ domain:+ anyOf:+ - $ref: '#/components/schemas/ProblemDomain'+ - type: string+ title: Domain+ retry:+ anyOf:+ - $ref: '#/components/schemas/RetryVerdict'+ - type: string+ title: Retry+ retry_after:+ anyOf:+ - anyOf:+ - type: integer+ - type: number+ ge: 0+ - type: 'null'+ title: Retry After+ next_step:+ $ref: '#/components/schemas/NextStep'+ params:+ anyOf:+ - $ref: '#/components/schemas/ProblemParams'+ - type: 'null'+ location:+ anyOf:+ - $ref: '#/components/schemas/ProblemLocation'+ - type: 'null'+ errors:+ anyOf:+ - items:+ $ref: '#/components/schemas/ProblemItem'+ type: array+ minItems: 1+ - type: 'null'+ title: Errors+ pipeline_run_id:+ anyOf:+ - type: string+ - type: 'null'+ title: Pipeline Run Id+ request_id:+ anyOf:+ - type: string+ - type: 'null'+ title: Request Id+ run_error:+ anyOf:+ - $ref: '#/components/schemas/PipelexProblem'+ - type: 'null'+ diagnostics:+ anyOf:+ - $ref: '#/components/schemas/ProblemDiagnostics'+ - type: 'null'+ additionalProperties: true+ type: object+ required:+ - type+ - title+ - detail+ - code+ - domain+ - retry+ - next_step+ title: PipelexProblem+ description: "The MTHDS problem document with Pipelex's members.\n\nAttributes:\n request_id: The request that carried\+ \ the failure, when known.\n run_error: On a read of a failed run's results, the run's own problem.\n diagnostics:\+ \ What only an operator reads; present in the operator view alone."PipelexVersionInfo:properties:protocol_version:@@ -6884,127 +7207,571 @@ components:- descriptiontitle: PresetMatchdescription: What a preset reference is in one category.- ProblemDocument:+ ProblemDeleteKeyOp:properties:- type:- type: string- title: Type- 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:+ kind:type: string- title: Title- description: 'Short, human-readable summary: the title of the error''s `code`, or of its `error_type` when it carries- none.'- status:- type: integer- title: Status- description: HTTP status code, repeated in the body per RFC 7807.- detail:+ const: delete_key+ title: Kind+ table_path:+ items:+ type: string+ type: array+ title: Table Path+ key:type: string- title: Detail- description: Human-readable explanation of this specific failure. Redacted under `ERROR_DISCLOSURE=strict`.- instance:- anyOf:+ title: Key+ additionalProperties: true+ type: object+ required:+ - kind+ - table_path+ - key+ title: DeleteKeyOp+ description: Remove `key` from the table at `table_path`.+ ProblemDeleteTableOp:+ properties:+ kind:+ type: string+ const: delete_table+ title: Kind+ table_path:+ items:+ type: string+ type: array+ minItems: 1+ title: Table Path+ additionalProperties: true+ type: object+ required:+ - kind+ - table_path+ title: DeleteTableOp+ description: Remove the table at `table_path`, every part of it included.+ ProblemDiagnostics:+ properties:+ error_class:+ type: string+ title: Error Class+ message:+ type: string+ title: Message+ causes:+ anyOf:+ - items:+ $ref: '#/components/schemas/DiagnosticCause'+ type: array+ - type: 'null'+ title: Causes+ params:+ anyOf:+ - additionalProperties: true+ type: object+ - type: 'null'+ title: Params+ model:+ anyOf:- type: string- type: 'null'- title: Instance- description: Path of the request that failed.- request_id:+ title: Model+ provider:+ anyOf:+ - $ref: '#/components/schemas/ProviderDiagnostics'+ - type: 'null'+ migration:+ anyOf:+ - $ref: '#/components/schemas/MigrationErrorBlock'+ - type: 'null'+ runtime_version:anyOf:- type: string- type: 'null'- title: Request Id- description: Correlation id, echoed in the `X-Request-ID` response header.+ title: Runtime Version+ trace_id:+ anyOf:+ - type: string+ - type: 'null'+ title: Trace Id+ span_id:+ anyOf:+ - type: string+ - type: 'null'+ title: Span Id+ additionalProperties: true+ type: object+ required:+ - error_class+ - message+ title: ProblemDiagnostics+ description: "What only an operator reads of a problem: the operator view's ``diagnostics`` member.\n\nAttributes:\n\+ \ error_class: The class of the error the problem was built from, the identity ``error_type`` once was.\n message:\+ \ The error's own message, capped.\n causes: The errors below it on its cause chain, by class and code.\n params:\+ \ The parameters the code declares operator-only.\n model: The model a failed inference call addressed.\n provider:\+ \ What the provider said about the call.\n migration: A pending configuration migration that explains the failure.\n\+ \ runtime_version: The version of the Pipelex runtime that built the problem.\n trace_id: The trace of the Pipelex\+ \ span the failure happened in.\n span_id: That span."+ ProblemDocument:+ properties:+ type:+ type: string+ title: Type+ 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: string+ title: Title+ description: 'Short, human-readable summary: the title of the error''s `code`, or of its `error_type` when it carries+ none.'+ status:+ type: integer+ title: Status+ description: 'HTTP status code, repeated in the body per RFC 9457: the status its `code` declares.'+ detail:+ type: string+ title: Detail+ description: 'Human-readable explanation of this specific failure, rendered from its code''s template and parameters.+ Never parsed: a program branches on `code`.'code:anyOf:- type: string- type: 'null'title: Codedescription: '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.'+ or a Pipelex code (e.g. `pipelex.config.invalid`). Present on every error the runtime raises; absent on an API-authored+ error.'+ domain:+ anyOf:+ - type: string+ - type: 'null'+ title: Domain+ description: 'Who must act, the code''s domain: `input`, `method`, `account`, `operator` or `runtime`.'+ retry:+ anyOf:+ - type: string+ - type: 'null'+ title: Retry+ description: 'Whether repeating the request can succeed, the code''s verdict: `yes`, `no` or `outcome_unknown`.'+ retry_after:+ anyOf:+ - type: number+ - type: 'null'+ title: Retry After+ description: Seconds to wait before a retry, when known, on a code whose verdict is `yes`.+ next_step:+ anyOf:+ - $ref: '#/components/schemas/NextStep'+ - type: 'null'+ description: 'What the reader should do next: a kind and a sentence, aimed at the caller, or at the operator in+ the operator view.'+ params:+ anyOf:+ - $ref: '#/components/schemas/ProblemParams'+ - type: 'null'+ description: The code's typed parameters, the ones its templates are rendered with.+ location:+ anyOf:+ - $ref: '#/components/schemas/ProblemLocation'+ - type: 'null'+ description: 'Where the failure happened: the failing pipe and its path from the entry pipe, an input, a field,+ a file.'+ errors:+ anyOf:+ - items:+ $ref: '#/components/schemas/ProblemItem'+ type: array+ - type: 'null'+ title: Errors+ description: One item per fault, for a refusal with several, such as a method that does not validate. On `/validate`,+ `/resolve`, `/codegen` and `/pipe-io` an invalid bundle is a **200** verdict instead.+ pipeline_run_id:+ anyOf:+ - type: string+ - type: 'null'+ title: Pipeline Run Id+ description: The run the failure belongs to.+ request_id:+ anyOf:+ - type: string+ - type: 'null'+ title: Request Id+ description: Correlation id, echoed in the `X-Request-ID` response header.+ diagnostics:+ anyOf:+ - $ref: '#/components/schemas/ProblemDiagnostics'+ - type: 'null'+ description: 'What only the operator reads: the error''s class and message, its causes, the provider''s answer,+ the model. Present only when the request was authenticated as the operator''s (`AUTH_MODE=api_key`, or a trusted+ proxy).'+ instance:+ anyOf:+ - type: string+ - type: 'null'+ title: Instance+ description: Path of the request that failed, on an API-authored error.error_type:- type: string+ anyOf:+ - type: string+ - type: 'null'title: Error Type- description: Stable class name of the originating error (e.g. `ValidateBundleError`, `Unauthenticated`).+ description: Stable name of an API-authored error (e.g. `Unauthenticated`).error_domain:anyOf:- type: string- type: 'null'title: Error Domain- description: '`input` (caller can fix it → 422), `config` or `runtime` (deployment must fix it → 500). Absent for- domain-less errors.'+ description: 'On an API-authored error: `input` (caller can fix it → 4xx) or `config` (deployment must fix it →+ 5xx).'retryable:anyOf:- type: boolean- type: 'null'title: Retryable- 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:+ description: 'On an API-authored error: whether retrying the same request can plausibly succeed.'+ additionalProperties: true+ type: object+ required:+ - type+ - title+ - status+ - detail+ title: ProblemDocument+ description: 'An RFC 9457 `application/problem+json` error body — the shape of every failure response.+++ A pipelex error answers its problem document: the RFC''s members (`type`, `title`, `status`, `detail`), the MTHDS++ core''s (`code`, `domain`, `retry`, `next_step`, always present, and `retry_after`, `params`, `location`, `errors`,++ `pipeline_run_id` when they hold a value) and Pipelex''s (`request_id`, and `diagnostics` in the operator view++ alone). An API-authored error carries no `code` yet, and is classified by `error_type`, `error_domain` and++ `retryable` instead, with its request path as `instance`. No member is ever written as `null`: a member with no++ value is absent. `extra="allow"` mirrors RFC 9457''s open-ended extension-member rule.'+ ProblemDomain:+ type: string+ enum:+ - input+ - method+ - account+ - operator+ - runtime+ title: ProblemDomain+ description: 'Who must act: the protocol''s closed list of domains.'+ ProblemEnsureTableOp:+ properties:+ kind:+ type: string+ const: ensure_table+ title: Kind+ table_path:+ items:+ type: string+ type: array+ minItems: 1+ title: Table Path+ additionalProperties: true+ type: object+ required:+ - kind+ - table_path+ title: EnsureTableOp+ description: Create the table at `table_path` when it is absent.+ ProblemFixSafety:+ type: string+ enum:+ - safe+ - unsafe+ title: FixSafety+ description: Whether a suggested fix may be applied without asking anyone.+ ProblemItem:+ properties:+ code:+ type: string+ pattern: ^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,2}$+ title: Code+ detail:+ type: string+ title: Detail+ params:+ anyOf:+ - $ref: '#/components/schemas/ProblemParams'+ - type: 'null'+ location:+ anyOf:+ - $ref: '#/components/schemas/ProblemLocation'+ - type: 'null'+ suggestions:+ anyOf:+ - items:+ type: string+ type: array+ - type: 'null'+ title: Suggestions+ suggested_fix:+ anyOf:+ - $ref: '#/components/schemas/ProblemSuggestedFix'+ - type: 'null'+ additionalProperties: true+ type: object+ required:+ - code+ - detail+ title: ProblemItem+ description: 'One fault of a problem with several, and one finding of a `/validate` verdict.+++ An item carries its own code but no verdict; `effective_domain` reads its domain from its code,++ `code_spec` is the code''s registry entry and `params_as` reads the parameters as a model.'+ ProblemLocation:+ properties:+ pipe:anyOf:- type: string- type: 'null'- title: Error Category- description: Finer classification, when the originating error provides one (inference errors).- user_action:+ title: Pipe+ path:+ anyOf:+ - items:+ type: string+ type: array+ - type: 'null'+ title: Path+ input:anyOf:- - $ref: '#/components/schemas/UserAction'+ - type: string- type: 'null'- description: Structured suggestion of what the caller should do next, when available.- model:+ title: Input+ field:anyOf:- type: string- type: 'null'- title: Model- description: Inference model that failed. Stripped under `ERROR_DISCLOSURE=strict`.- provider:+ title: Field+ item:+ anyOf:+ - type: integer+ ge: 0+ - type: 'null'+ title: Item+ attempt:+ anyOf:+ - type: integer+ ge: 1+ - type: 'null'+ title: Attempt+ file:anyOf:- type: string- type: 'null'- title: Provider- description: Inference provider that failed. Stripped under `ERROR_DISCLOSURE=strict`.- provider_metadata:+ title: File+ line:anyOf:- - $ref: '#/components/schemas/ProviderErrorMetadata'+ - type: integer+ ge: 1- type: 'null'- description: Upstream provider error metadata. Stripped (bar a curated slice) under `ERROR_DISCLOSURE=strict`.- validation_errors:+ title: Line+ column:+ anyOf:+ - type: integer+ ge: 1+ - type: 'null'+ title: Column+ additionalProperties: true+ type: object+ title: ProblemLocation+ description: Where the error happened, in the method, the request or the run; every member is optional.+ ProblemMoveKeyOp:+ properties:+ kind:+ type: string+ const: move_key+ title: Kind+ table_path:+ items:+ type: string+ type: array+ title: Table Path+ key:+ type: string+ title: Key+ new_table_path:+ items:+ type: string+ type: array+ title: New Table Path+ new_key:+ type: string+ title: New Key+ additionalProperties: true+ type: object+ required:+ - kind+ - table_path+ - key+ - new_table_path+ - new_key+ title: MoveKeyOp+ description: Move `key` from the table at `table_path` into the table at `new_table_path` under `new_key`.+ ProblemParams:+ properties:+ missing_blobs:anyOf:- items:- $ref: '#/components/schemas/ValidationErrorItem'+ type: string+ pattern: ^[0-9a-f]{64}$type: array- type: 'null'- title: Validation Errors- description: Structured per-error diagnostics, carried by a `ValidateBundleError`. Each item may carry a `suggested_fix`.- Retained under `ERROR_DISCLOSURE=strict` — it describes the caller's own bundle, not server internals. On `/validate`,- `/resolve`, `/codegen` and `/pipe-io` an invalid bundle is a **200** verdict instead, so the items ride the response- body there rather than a problem document.+ title: Missing BlobsadditionalProperties: truetype: object- required:- - type- - title- - status- - detail- - error_type- title: ProblemDocument- description: 'An RFC 7807 `application/problem+json` error body — the shape of every failure response.+ title: ProblemParams+ description: 'The typed facts a problem''s sentences were written from.- Standard RFC 7807 members (`type`, `title`, `status`, `detail`, `instance`)+ Each code declares its own parameters, and the generated registry gives each core code a model of- plus the extension members pipelex''s classification adds. Only `type`,+ them (`CORE_CODE_SPECS[code].params_model`), which `Problem.params_as` validates into. This model- `title`, `status`, `detail`, and `error_type` are always present, and `code`+ types only the parameter the protocol types for every reader, `missing_blobs`; every other- 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.'+ parameter rides `model_extra` as received.'+ ProblemRemapValueOp:+ properties:+ kind:+ type: string+ const: remap_value+ title: Kind+ table_path:+ items:+ type: string+ type: array+ title: Table Path+ key:+ type: string+ title: Key+ mapping:+ additionalProperties:+ type: string+ type: object+ minProperties: 1+ title: Mapping+ additionalProperties: true+ type: object+ required:+ - kind+ - table_path+ - key+ - mapping+ title: RemapValueOp+ description: Rewrite the string value of `key` in the table at `table_path` through `mapping`.+ ProblemRenameTableKeyOp:+ properties:+ kind:+ type: string+ const: rename_table_key+ title: Kind+ table_path:+ items:+ type: string+ type: array+ title: Table Path+ key:+ type: string+ title: Key+ new_key:+ type: string+ title: New Key+ additionalProperties: true+ type: object+ required:+ - kind+ - table_path+ - key+ - new_key+ title: RenameTableKeyOp+ description: Rename `key` to `new_key` within the table at `table_path`.+ ProblemSetKeyOp:+ properties:+ kind:+ type: string+ const: set_key+ title: Kind+ table_path:+ items:+ type: string+ type: array+ title: Table Path+ key:+ type: string+ title: Key+ value:+ anyOf:+ - type: boolean+ - type: integer+ - type: number+ - type: string+ - additionalProperties:+ anyOf:+ - type: boolean+ - type: integer+ - type: number+ - type: string+ type: object+ title: Value+ additionalProperties: true+ type: object+ required:+ - kind+ - table_path+ - key+ - value+ title: SetKeyOp+ description: Write `key = value` in the table at `table_path`.+ ProblemSuggestedFix:+ properties:+ fix_code:+ type: string+ pattern: ^[a-z0-9]+(-[a-z0-9]+)*$+ title: Fix Code+ description:+ type: string+ title: Description+ safety:+ anyOf:+ - $ref: '#/components/schemas/ProblemFixSafety'+ - type: string+ title: Safety+ file:+ anyOf:+ - type: string+ - type: 'null'+ title: File+ ops:+ items:+ oneOf:+ - $ref: '#/components/schemas/ProblemSetKeyOp'+ - $ref: '#/components/schemas/ProblemEnsureTableOp'+ - $ref: '#/components/schemas/ProblemDeleteKeyOp'+ - $ref: '#/components/schemas/ProblemDeleteTableOp'+ - $ref: '#/components/schemas/ProblemRenameTableKeyOp'+ - $ref: '#/components/schemas/ProblemMoveKeyOp'+ - $ref: '#/components/schemas/ProblemRemapValueOp'+ - $ref: '#/components/schemas/UnknownFixOp'+ type: array+ minItems: 1+ title: Ops+ additionalProperties: true+ type: object+ required:+ - fix_code+ - description+ - safety+ - ops+ title: SuggestedFix+ description: 'A deterministic fix for one fault: operations over a bundle of the method, addressed by TOML key path.'PromptImageDetail:type: stringenum:@@ -7180,66 +7947,37 @@ components:- requiredtitle: ProseItemdescription: '`prose` — flowing free text.'- ProviderErrorMetadata:+ ProviderDiagnostics:properties:- provider:- $ref: '#/components/schemas/ProviderName'- sdk_exception_type:- type: string- title: Sdk Exception Type- message:- type: string- title: Message- default: ''- status_code:+ name:+ anyOf:+ - type: string+ - type: 'null'+ title: Name+ status:anyOf:- type: integer- type: 'null'- title: Status Code- request_id:+ title: Status+ code:anyOf:- type: string- type: 'null'- title: Request Id- retry_after_seconds:+ title: Code+ request_id:anyOf:- - type: number+ - type: string- type: 'null'- title: Retry After Seconds- provider_error_code:+ title: Request Id+ message:anyOf:- type: string- type: 'null'- title: Provider Error Code+ title: Message+ additionalProperties: truetype: object- required:- - provider- - sdk_exception_type- title: ProviderErrorMetadata- description: 'Structured SDK metadata attached to inference errors.--- Carries information downstream consumers (retry, temporal, CLI) need-- without having to scrape it back from the exception chain.'- ProviderName:- type: string- enum:- - openai- - anthropic- - mistral- - azure- - bedrock- - fal- - huggingface- - gateway- - linkup- - typesafe- - docling- - pypdfium2- title: ProviderName- description: Identifies the inference provider an SDK error originated from.+ title: ProviderDiagnostics+ description: What the inference provider said about a failed call, for an operator.Quality:type: stringenum:@@ -7390,6 +8128,14 @@ components:fingerprint computed from either surface agrees. Its `fingerprint` and `mthds_version` membersride inside the crate payload itself.'+ RetryVerdict:+ type: string+ enum:+ - 'no'+ - 'yes'+ - outcome_unknown+ title: RetryVerdict+ description: 'Whether repeating the operation can succeed: the protocol''s closed list of verdicts.'RunState:type: stringenum:@@ -7500,6 +8246,25 @@ components:- fail- continuetitle: SpecialOutcome+ StepKind:+ type: string+ enum:+ - retry+ - wait+ - read_run+ - refresh+ - change_input+ - change_method+ - change_model+ - check_credentials+ - request_access+ - check_account+ - fix_configuration+ - upgrade+ - contact_owner+ - report+ title: StepKind+ description: 'What the reader does next: the protocol''s closed list of step kinds.'StepRole:type: stringenum:@@ -7978,6 +8743,26 @@ components:``nb_tokens_by_category`` keys) are open sets on the wire, typed as plain strings —runtime enum churn is non-breaking for clients.'+ UnexplainedPath:+ properties:+ path:+ type: string+ title: Path+ note:+ type: string+ title: Note+ additionalProperties: false+ type: object+ required:+ - path+ - note+ title: UnexplainedPath+ description: 'A path the current schema does not know and no ledger entry removes.+++ Populated by the downgrade diagnosis, which lands with the commands: the file is either++ carrying a typo or was written by a newer pipelex than the one running.'UnknownField:properties:title:@@ -8044,6 +8829,18 @@ components:- nametitle: UnknownFielddescription: '`unknown` at a named position.'+ UnknownFixOp:+ properties:+ kind:+ type: string+ title: Kind+ additionalProperties: true+ type: object+ required:+ - kind+ title: UnknownFixOp+ description: 'The reader-side catch-all: an operation whose `kind` is none the protocol lists, which an applier never+ applies.'UnknownItem:properties:title:@@ -8135,41 +8932,6 @@ components:title: UploadTargetdescription: 'Where to upload one blob: send its bytes as the whole body of a request with this method to this URL,with exactly these headers.'- UserAction:- properties:- kind:- $ref: '#/components/schemas/UserActionKind'- detail:- type: string- title: Detail- type: object- required:- - kind- - detail- title: UserAction- description: 'Structured user-facing advice attached to an inference error.--- ``kind`` discriminates the type of action, ``detail`` is the free-form-- provider-specific advice (e.g. a billing URL, a retry hint).'- UserActionKind:- type: string- enum:- - wait_and_retry- - check_billing- - check_credentials- - change_input- - change_model- - contact_support- - unknown- title: UserActionKind- description: 'Discrete categories of advice we surface to the user/agent.--- Lets the CLI render consistent guidance and agent JSON stay typed across-- providers. The free-form ``detail`` string carries provider-specific text.'ValidReport:properties:is_valid:@@ -8615,10 +9377,12 @@ components:- category- messagetitle: ValidationErrorItem- description: 'One structured bundle-validation error, projected onto the error wire.+ description: 'One structured bundle-validation error, as the validation verdicts carry it.++ The typed item of an invalid verdict''s ``validation_errors``; the problem document of a refusal carries each as an- The typed wire item carried by :attr:`ErrorReport.validation_errors`. Its+ ``errors`` item instead (``pipelex.pipeline.validation_errors.problem_item_of``). Itsfields are the *union* across the three ``ValidateBundleError`` error-data@@ -8637,9 +9401,9 @@ components:CLI (``extract_validation_errors``) and the API path- (``ValidateBundleError.to_error_report``) call — so the CLI''s structured+ (``ValidateBundleError.validation_error_items``) call — so the CLI''s structured- output and the API''s 422 ``validation_errors`` can never drift. The same+ output and the API''s invalid verdict can never drift. The sameitem type also carries the report''s advisory ``warnings``, built by@@ -8652,13 +9416,11 @@ components:threads onto the in-memory load path — it hands a consumer the owning file- for cross-file diagnostics. Lives here, alongside :class:`ErrorReport`,-- rather than next to the source error-data models because ``ErrorReport``+ for cross-file diagnostics. Lives here rather than next to the source error-data- references it as a typed field and ``base_exceptions`` must not import the+ models because ``base_exceptions`` must not import the ``pipelex.core`` error- ``pipelex.core`` error modules (which import back into this module).'+ modules (which import back into this module).'ValidationResidualErrorType:type: stringenum:diff --git a/docs/api-server/pipe-io.md b/docs/api-server/pipe-io.mdindex a5b98fec1..f03b59536 100644--- a/docs/api-server/pipe-io.md+++ b/docs/api-server/pipe-io.md@@ -36,20 +36,23 @@ There is no `views` field, because the valid arm always carries all three artifa}```-The tree's refusals produce no verdict, as on `/v1/validate`: an `InvalidMethodFiles`, `MissingBlobs`, `MethodTreeTooLarge` or `InvalidBundle` `422`, and the custom-Python policy's `403`s (see [No verdict](#no-verdict)).+The tree's refusals produce no verdict, as on `/v1/validate`: an `InvalidMethodFiles`, `MissingBlobs`, `MethodTreeTooLarge` or `InvalidBundle` `422`, and the custom-Python policy's refusals (see [No verdict](#no-verdict)).## Pipe selection-The selection chain takes the request's `pipe_ref`; else the `main_pipe` of the `METHODS.toml` at the tree's root, whether the tree was fetched by `method_ref` or sent in `files`; else the closure's own `main_pipe` declaration, when exactly one domain declares one. A root `METHODS.toml` the route cannot read as a manifest, being no UTF-8 text or no valid manifest, is a `422 MethodEntryError` when the request names no pipe. A request naming its pipe in `pipe_ref` never reads the manifest to select it, so there a manifest the route cannot read refuses nothing and only leaves `default_pipe_ref` a stated `null`. The chain stops at the first link that is present, so a manifest `main_pipe` the closure does not declare, or declares in several domains, is a failed selection rather than a fall-through to the closure's declarations.+The selection chain takes the request's `pipe_ref`; else the `main_pipe` of the `METHODS.toml` at the tree's root, whether the tree was fetched by `method_ref` or sent in `files`; else the closure's own `main_pipe` declaration, when exactly one domain declares one. A root `METHODS.toml` the route cannot read as a manifest, being no UTF-8 text or no valid manifest, is a `422` problem coded `method.package_invalid` when the request names no pipe. A request naming its pipe in `pipe_ref` never reads the manifest to select it, so there a manifest the route cannot read refuses nothing and only leaves `default_pipe_ref` a stated `null`. The chain stops at the first link that is present, so a manifest `main_pipe` the closure does not declare, or declares in several domains, is a failed selection rather than a fall-through to the closure's declarations.-The closure is resolved first, so an invalid closure answers its invalid verdict whatever `pipe_ref` names. For a valid closure these selections are refused with an input `422` `problem+json`. Its `error_type` is the pipelex entry-lookup class that names the failure, never the `ValidationError` of a malformed request, so a client tells a selection refusal from a request-shape one by that field:+The closure is resolved first, so an invalid closure answers its invalid verdict whatever `pipe_ref` names. For a valid closure these selections are refused with a `422` problem whose `code` names the failure, never the `ValidationError` of a malformed request, so a client tells a selection refusal from a request-shape one by that member:-- `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.+- `request.pipe_not_found` for a `pipe_ref` that names no pipe of the closure, with the selection as its `pipe` parameter;+- `request.pipe_ambiguous` for a bare code that matches pipes in several domains, with the selection as its `pipe` parameter and the qualified refs to choose from as its `candidates`;+- `request.pipe_unspecified`, without `all_pipes`, for a request with no `pipe_ref` whose closure declares no `main_pipe`, or several, whose qualified refs are then its `candidates`;+- `method.pipe_unresolved` for a manifest `main_pipe` the closure does not declare, the method's own declaration to fix, with the declared selection as its `missing` parameter;+- `method.ref_ambiguous` for a manifest `main_pipe` that matches pipes in several domains of the closure, the method's own declaration to fix, with the declared selection as its `ref` parameter and the qualified refs it matches as its `candidates`.-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.+The problem's `type`, `title`, sentences and step are the code's: a request's selection asks the caller to select a pipe the method declares, and a manifest's asks the method's author to correct the declaration.-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.+An unknown or ambiguous `pipe_ref` answers the code 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.A bare `pipe_ref` that matches one pipe (`echo` where `smoke.echo` is meant) is still resolved today, and the valid arm reports the qualified ref.@@ -88,10 +91,10 @@ An invalid closure is the `200` crate verdict `/v1/resolve` gives: `is_valid: fa## No verdict-Every non-2xx is RFC 7807 `application/problem+json` (see [Error Responses](error-responses.md)):+Every non-2xx is RFC 9457 `application/problem+json` (see [Error Responses](error-responses.md)):-- **`422`** for a malformed body or neither or both method selectors, `ValidationError`; for a tree the runner cannot read, `InvalidMethodFiles`, `MissingBlobs`, `MethodTreeTooLarge` or `InvalidBundle`, as on [`/v1/resolve`](codegen.md#selecting-the-method); for an unreadable root manifest on a request naming no pipe, `MethodEntryError`; and for the selection refusals above, `EntryPipeNotFoundError` or `EntryPipeAmbiguousError`.-- **The `method_ref` fetch outcomes**, exactly as on `/v1/resolve`: `404` `MethodPackageNotFoundError` when no package in the fetched repository matches the address, `422` for a reference that does not parse or a fetch the server cannot accept, and `501` `MethodRefNotSupported` for a registry-form reference.-- **`403`** for the custom-Python policy of `/v1/validate` and the run routes, whose tree the route loads: `CustomCodeRequiresSandbox` for a tree holding a `.py` file on a deployment that is not sandbox-hosted, where loading the library would import each `.py` declaring a structure class and run its module-level code in the server's process, and `MethodStructuresRefusedError` for one whose Python declares a structure class.+- **`422`** for a malformed body or neither or both method selectors, `ValidationError`; for a tree the runner cannot read, `InvalidMethodFiles`, `MissingBlobs`, `MethodTreeTooLarge` or `InvalidBundle`, as on [`/v1/resolve`](codegen.md#selecting-the-method); for an unreadable root manifest on a request naming no pipe, `method.package_invalid`; and for the selection refusals above, by their codes.+- **The `method_ref` fetch outcomes**, exactly as on `/v1/resolve`: `404` `method.not_found` when no package in the fetched repository matches the address, `422` for a reference that does not parse (`request.invalid`) or a package the server cannot accept (`method.ambiguous`, `method.package_invalid`), `502` `method.fetch_failed` when the fetch itself failed, and `501` `MethodRefNotSupported` for a registry-form reference.+- **The custom-Python policy of `/v1/validate` and the run routes**, whose tree the route loads: a `403` `CustomCodeRequiresSandbox` for a tree holding a `.py` file on a deployment that is not sandbox-hosted, where loading the library would import each `.py` declaring a structure class and run its module-level code in the server's process, and a `422` `pipelex.deployment.python_structures_refused` for one whose Python declares a structure class.- **`401` / `403`** for authentication, and **`413`** for a body over the size limit.- **`500`** when an artifact cannot be derived: a pipe whose input or output JSON Schema cannot be rendered raises `PipeIOContractError`, which answers `500` as it does on `/v1/validate` — a fault of the tool, not a verdict about the method.diff --git a/docs/api-server/pipe-run.md b/docs/api-server/pipe-run.mdindex d3fd0dafd..5bb0217af 100644--- a/docs/api-server/pipe-run.md+++ b/docs/api-server/pipe-run.md@@ -84,7 +84,7 @@ Execute a Pipelex pipeline with flexible inputs and wait for completion.- `pipe_output.pipe_io_artifacts` (object | null): The I/O artifacts describing the graph's data, carried beside `graph_spec` so that wherever the graph travels its description travels with it. It groups the same artifacts `/validate` produces — `pipe_io_contracts`, `input_form` and `output_form` — each keyed by namespaced `pipe_ref`, over the **run library's own pipes**: a dependency package's pipes are keyed by alias in the library but by bare `pipe_ref` in the artifacts, where they would collide with the host's, so they are left out and a graph node contributed by a dependency has no entry here. Holding it with the graph is what lets a viewer show a data node's value rather than only its shape. It is built only when the run generated a graph **and** `interpreter.pipeline_execution.graph.graphs_inclusion.graphspec_json` is on (both default to `true`), and only when `graph_spec` itself came out non-null — so a run with `graphspec_json = false` returns a graph with no artifacts beside it and no error, which is the one case where the two fields disagree. `pipe_output.pipe_io_artifacts_error` (string | null) is non-null when the build ran and failed. See [Pipe Validate](pipe-validate.md) for the artifacts' own field reference.- `method_provenance` (object, only on `method_ref` runs): `{address, tag, commit_sha}` — the package's resolved full address, the requested tag (`null` for a bare address), and the commit SHA that was actually fetched. Absent for runs from inline source or a bundle. See [Running a method by address](#running-a-method-by-address-method_ref).-**Errors** are returned as [RFC 7807 `application/problem+json`](error-responses.md) bodies with HTTP 4xx/5xx status codes. The successful response body has no `status`/`error` field — the HTTP status code is the source of truth. An invalid bundle is refused before any pipe runs with a `422` carrying the same located `validation_errors` validating it gives ([Structured validation errors](error-responses.md#structured-validation-errors)), and a run that fails reports its root fault at the pipe that failed ([Run failures](error-responses.md#run-failures-the-root-fault-located-at-the-failing-pipe)).+**Errors** are returned as [RFC 9457 `application/problem+json`](error-responses.md) bodies with HTTP 4xx/5xx status codes. The successful response body has no `status`/`error` field — the HTTP status code is the source of truth. An invalid bundle is refused before any pipe runs with a `422` `method.invalid` problem whose `errors` are the same located items validating it gives ([Structured validation errors](error-responses.md#structured-validation-errors)), and a run that fails reports its root fault at the pipe that failed ([Run failures](error-responses.md#run-failures-the-root-fault-located-at-the-failing-pipe)).---@@ -169,7 +169,7 @@ Start a pipeline execution and get its `pipeline_run_id` back with a `202` ack.- `method_provenance` (object | null): `{address, tag, commit_sha}` for a `method_ref` run — see [Running a method by address](#running-a-method-by-address-method_ref); `null` for runs from inline source or a bundle.- `crate_fingerprint` (string | null): **Pipelex extension.** The fingerprint of the library crate the run's job was built from, as on the `/execute` result, known as soon as the run is queued, so a host records it from the acknowledgement.-**Errors** follow the same convention as `/execute`: HTTP 4xx/5xx with an [RFC 7807 `application/problem+json`](error-responses.md) body.+**Errors** follow the same convention as `/execute`: HTTP 4xx/5xx with an [RFC 9457 `application/problem+json`](error-responses.md) body.#### Async Completion Callbacks (optional)@@ -185,7 +185,7 @@ Start a pipeline execution and get its `pipeline_run_id` back with a `202` ack.When the pipeline completes, each URL in the list receives a POST carrying:-- A completion notice in the body, not the run's output: `pipeline_run_id`, the delivery `state` (`"COMPLETED"` or `"FAILED"`, also sent under the legacy `status` key), `result_url` (when results were stored: the storage key prefix under which the result files sit, not a fetchable URL) and `error` (the raw `ErrorReport` dict on failure). The receiver reads the results from storage under that prefix.+- A completion notice in the body, not the run's output: `pipeline_run_id`, the delivery `state` (`"COMPLETED"` or `"FAILED"`, also sent under the legacy `status` key), `result_url` (when results were stored: the storage key prefix under which the result files sit, not a fetchable URL) and `error` on failure, the run's problem document in the view of whoever started the run (see [Error Responses](error-responses.md#async-callbacks-webhook-payload)). The receiver reads the results from storage under that prefix.- An **`X-Completion-Signature`** header — `HMAC-SHA256(secret, pipeline_run_id)` rendered as a hex digest**Verifying the signature on the receiver side**@@ -246,7 +246,7 @@ The receiver-side secret must be the same value. In typical deployments both sid**Sandbox-hosted only for custom Python.** A tree that holds any `.py` file is honored **only on a sandbox-hosted deployment**, where the load reads the source without importing it and execution happens in an isolated sandbox. On a deployment that is not sandbox-hosted it is refused with `403 CustomCodeRequiresSandbox` before anything is written: running caller-supplied code in-process is never done implicitly. A tree without Python is accepted on any deployment.-**No Python structure classes.** A structure class (a `StructuredContent` subclass) can only be used by importing its module into the runner's own process, which a sandbox-hosted deployment never does, so a tree whose Python declares one is refused with a `403` (`MethodStructuresRefusedError`) naming each file and class, before anything is loaded. The rule is the same however the method arrives: sent as a tree, or fetched by `method_ref`. Declare the types as MTHDS concepts with inline structures instead; a PipeFunc returns them by importing the classes the sandbox generates from those concepts (`from structures import <domain>__<Concept>`). The `structures` module that `pipelex build structures` writes is accepted as long as it is left as generated, and it is not sent to the sandbox, which generates its own.+**No Python structure classes.** A structure class (a `StructuredContent` subclass) can only be used by importing its module into the runner's own process, which a sandbox-hosted deployment never does, so a tree whose Python declares one is refused with a `422` problem, `pipelex.deployment.python_structures_refused`, before anything is loaded; its operator view's message names each file and class. The rule is the same however the method arrives: sent as a tree, or fetched by `method_ref`. Declare the types as MTHDS concepts with inline structures instead; a PipeFunc returns them by importing the classes the sandbox generates from those concepts (`from structures import <domain>__<Concept>`). The `structures` module that `pipelex build structures` writes is accepted as long as it is left as generated, and it is not sent to the sandbox, which generates its own.**Requirements are checked against the sandbox.** A `requirements.txt` at the root of the tree declares the packages its Python imports, one PEP 508 requirement per line (see [Method Trees](../building-methods/method-trees.md#python-packages-requirementstxt)). Nothing is installed into a running sandbox: the packages the deployment states its PipeFunc sandbox offers for the method's requirements are the whole offer, a fixed package set or an environment the deployment builds for those requirements, and a method asking for a package the sandbox does not offer, or for a version it does not offer, is refused with a `422` (`MethodRequirementsNotMetError`) naming each requirement and the version offered, before the method loads and before anything is dispatched. A deployment that can build no environment holding the requirements refuses them with the same `422`, carrying its own explanation. The refusal names the file by its tree path, `requirements.txt`, and no path on the server. A line the standard refuses, such as `-r base.txt`, a URL or a comment after a requirement, is a `422` (`MethodRequirementsFileError`) naming the line. A deployment that states no package set for its sandbox refuses every method declaring requirements with a `500` (`PipeFuncPackageSetUnstatedError`), a fault of its configuration, and so does a method of the server's own library directories whose requirements are not met (`HostLibraryRequirementsError`), whose message is withheld from the caller. A `method_ref` package is checked the same way, on a run as on [`/validate`](pipe-validate.md), where the refusal is an `is_valid: false` verdict located on the requirement's line.@@ -287,7 +287,7 @@ bundle.mthds- **A reference finds the package by its manifest.** The package that answers is the one whose `METHODS.toml` declares the referenced address and name. A reference pinned with `@<tag>` is answered by the shipped copy too, and the server logs a warning when the copy's `version` is not that tag.- **The shipped copy comes first.** The server searches the shipped packages before the copies installed on it and before fetch-on-miss, so a shipped package wins over an installed copy of the same address, and it runs even where fetching is disabled or the address is not one the server can fetch. It serves this request alone: nothing is installed.- **It is a tree of its own.** Each package is written into a methods directory of its own, never into the method's tree, so its domains never merge with the method's, and a method whose only bundles are shipped ones is refused as holding no bundle of its own. Its keys are held to the tree's rule as the method's are.-- **Its Python never runs in the server's process.** A `.py` file in a shipped package counts for the sandbox gate like any other. On a sandbox-hosted deployment, a shipped package whose Python declares a structure class is refused with `403 MethodStructuresRefusedError` naming the package's address, as a package fetched by address is.+- **Its Python never runs in the server's process.** A `.py` file in a shipped package counts for the sandbox gate like any other. On a sandbox-hosted deployment, a shipped package whose Python declares a structure class is refused with the same `422` `pipelex.deployment.python_structures_refused`, as a package fetched by address is.- **A shipped bundle that does not parse refuses the run** with the `422` verdict, whose items name the file as `<address>/<path inside the package>`, never by a path on the server.Two shipped packages a reference could not tell apart, whose manifests declare the same address and name compared without regard to case, the name being the directory's when the manifest has none, are a `422 InvalidMethodFiles` naming the address, since nothing but their order would decide which one answers. In an archive, a package directory without a valid `METHODS.toml` is refused the same way, and any other entry under `.mthds/`, such as a file directly under `.mthds/methods/`, one under a directory whose name no package's directory can take, such as a dot directory, or a package's own `.mthds/` store, is refused by the tree's rule; a package fetched by `method_ref` holds its `.mthds/methods/` to the same rule, its other entries left out of its tree. A package whose manifest declares no name takes the last segment of its address, which must then be a name a directory can take: a dependency keyed by an address ending in `.` or `..` with a nameless manifest is a `422 InvalidMethodFiles`.@@ -315,19 +315,18 @@ Both `/execute` and `/start` accept **`method_ref`** — a globally resolvable a**Provenance.** The response carries `method_provenance = {address, tag, commit_sha, tree_digest}` — on `/execute` only for `method_ref` runs, on the `/start` ack as a nullable field. Tags can move; the recorded SHA is what keeps a run explainable after the fact, and `tree_digest` names the exact tree the run loaded.-**Custom Python follows the tree rules, plus one more.** What decides is *where the code would execute*: `.mthds` content is data, always acceptable. On a deployment that is **not** sandbox-hosted, a fetched package carrying any `.py` is refused with `403 CustomCodeRequiresSandbox`. On a sandbox-hosted deployment, PipeFunc `.py` is accepted (captured as text, executed in the isolated sandbox) — but a package declaring **Python structure classes** (`StructuredContent` subclasses) is refused with a `403` (`MethodStructuresRefusedError`), exactly as a tree sent with the request is: see [No Python structure classes](#sending-a-method-as-a-tree).+**Custom Python follows the tree rules, plus one more.** What decides is *where the code would execute*: `.mthds` content is data, always acceptable. On a deployment that is **not** sandbox-hosted, a fetched package carrying any `.py` is refused with `403 CustomCodeRequiresSandbox`. On a sandbox-hosted deployment, PipeFunc `.py` is accepted (captured as text, executed in the isolated sandbox) — but a package declaring **Python structure classes** (`StructuredContent` subclasses) is refused with a `422` (`pipelex.deployment.python_structures_refused`), exactly as a tree sent with the request is: see [No Python structure classes](#sending-a-method-as-a-tree).-**Errors.** Every resolution failure is a distinct RFC 7807 `problem+json` with the originating class as `error_type` (see [Error responses](error-responses.md)):+**Errors.** Every resolution failure is an RFC 9457 `problem+json` named by its code, or by its `error_type` for the one refusal the API authors itself (see [Error responses](error-responses.md)):-| Failure | Status | `error_type` |+| Failure | Status | `code` or `error_type` ||---|---|---|-| Reference does not match the grammar | 422 | `MethodRefParseError` |-| Repository could not be fetched, or `@<tag>` is not a tag | 422 | `MethodFetchError` |-| No package matches the address (message lists what the repo contains) | 404 | `MethodPackageNotFoundError` |-| More than one package matches | 422 | `MethodPackageAmbiguityError` |-| Package exceeds the fetched-package ceilings | 422 | `MethodPackageTooLargeError` |-| Package contains a symlink (file or directory) | 422 | `MethodPackageSymlinkError` |-| Package declares Python structure classes | 403 | `MethodStructuresRefusedError` |+| Reference does not match the grammar | 422 | `request.invalid` |+| Repository could not be fetched | 502 | `method.fetch_failed` |+| `@<tag>` is not a tag of the repository, or no package matches the address | 404 | `method.not_found` |+| More than one package matches | 422 | `method.ambiguous` |+| Package exceeds the fetched-package ceilings, or contains a symlink (file or directory) | 422 | `method.package_invalid` |+| Package declares Python structure classes | 422 | `pipelex.deployment.python_structures_refused` || Package ships `.py` on a non-sandbox deployment | 403 | `CustomCodeRequiresSandbox` |**The clone cache.** Fetched repositories are cached on local disk **keyed by resolved commit SHA** — never by tag. Each request first resolves the reference to its current SHA with a cheap `git ls-remote` (no clone); a cached SHA is reused, a new one (a moved tag, an advanced HEAD) triggers a fresh clone. The cache is per server instance and bounded by count, total bytes, and age, oldest first; a clone a request is still reading is never evicted, though it counts toward the bounds. That protection holds within one process, so a deployment running several worker processes gives each its own `METHOD_CACHE_DIR`.diff --git a/docs/api-server/pipe-validate.md b/docs/api-server/pipe-validate.mdindex 95c595591..92fd1083b 100644--- a/docs/api-server/pipe-validate.md+++ b/docs/api-server/pipe-validate.md@@ -116,7 +116,7 @@ The 200 body is one of two arms, discriminated on the mandatory `is_valid` field## What This Endpoint Does-The route wraps the runtime's protocol `validate`: parse → load → dry-run-sweep every pipe → build the per-pipe IO contracts → best-effort graph of the entry pipe → assemble the canonical report. The runner returns the verdict as a value — the canonical report on the valid arm, or a structured `ErrorReport` (a bundle the caller can fix) on the invalid arm — and the route maps the invalid verdict to the 200 invalid arm by matching the returned value, never by catching a transport error. A bundle that declares no `main_pipe`, when no manifest names one either, validates normally and simply carries `graph_spec: null` — there is no main-pipe precondition.+The route wraps the runtime's protocol `validate`: parse → load → dry-run-sweep every pipe → build the per-pipe IO contracts → best-effort graph of the entry pipe → assemble the canonical report. The runner returns the verdict as a value — the canonical report on the valid arm, or a `BundleValidationFailure` (the refusal's problem with its validation items, a bundle the caller can fix) on the invalid arm — and the route maps the invalid verdict to the 200 invalid arm by matching the returned value, never by catching a transport error. A bundle that declares no `main_pipe`, when no manifest names one either, validates normally and simply carries `graph_spec: null` — there is no main-pipe precondition.## The effective entry pipe@@ -181,7 +181,7 @@ A bundle sent as content has no directory, so a file one of its steps reads from- **Each key is the path a step names**, relative to the bundle and written with forward slashes, exactly as in its `template_file`. `.` segments and repeated slashes collapse, so `./templates/invoice.docx` names the same file; every bundle of the request is read as sitting in one directory. An empty or absolute path, a `..` segment, a backslash, a colon, or two keys naming the same file is a **422** `InvalidResourcePath`, refused before any value is decoded. A method sent as a tree may hold the file instead, beside the bundle whose step names it; beside a tree, each key of `resources` joins it at that path from the tree's root, and a file the tree already holds must have the same bytes (see [Pipe Run](pipe-run.md#sending-a-method-as-a-tree)).- **Each value is the file's bytes** in standard base64 (RFC 4648, with padding). A value that does not decode is a **400** `InvalidBase64`.-- **Beside inline contents, every file must be one a step names.** A file no step of the bundle reads is a **422** `BundleResourceNotNamedError`, whose `detail` lists the unnamed paths: a misspelled key fails loudly rather than leaving its step without its file. This is a request error, never an `is_valid: false` verdict. Beside a tree, a file no step names is kept like any other file of the tree.+- **Beside inline contents, every file must be one a step names.** A file no step of the bundle reads is a **422** problem with the code `request.invalid`, whose operator view's message lists the unnamed paths: a misspelled key fails loudly rather than leaving its step without its file. This is a request error, never an `is_valid: false` verdict. Beside a tree, a file no step names is kept like any other file of the tree.- **The sizes are bounded**: at most `MAX_RESOURCES_PER_REQUEST` files (32 by default), each at most `MAX_RESOURCE_FILE_KIB` once decoded (5 MiB by default), and at most `MAX_RESOURCES_TOTAL_KIB` across the request (10 MiB by default). A request over any of them is a **413** `PayloadTooLarge`, an oversized file refused on its encoded length before it is decoded. The whole body stays under `MAX_REQUEST_BODY_MIB` as well.- **The files make one method tree**, with the request's bundles at its root. A run names that tree by its digest, as it names the tree of a method loaded from a directory, and carries none of the files in its payloads, a remote orchestrator's included: the step that reads one reads it from the tree, through the deployment's method file store. Two files colliding in one tree, such as two keys equal once case-folded, are a **422** `BundleResourcePathError`.@@ -203,13 +203,13 @@ A validation is not a run, but it still emits telemetry: the sweep's `pipe_dry_r## No-verdict (non-2xx) responses-Only conditions where the endpoint could not produce a verdict are non-2xx, rendered as [RFC 7807 problem documents](error-responses.md):+Only conditions where the endpoint could not produce a verdict are non-2xx, rendered as [RFC 9457 problem documents](error-responses.md):- **422** — a malformed request body, an `mthds_sources` / `mthds_contents` length mismatch, more or fewer than one of `mthds_contents` / `files` / `method_ref`, or a malformed `analytics_groups` (`error_type` `InvalidAnalyticsGroups`) — request-shape errors caught before the runtime.- **422** on a method tree — a key or entry the tree's rule refuses (`InvalidMethodFiles`), a hash entry the runner does not hold (`MissingBlobs`), or a tree past its limits (`MethodTreeTooLarge`) — see [Validating a method tree](#validating-a-method-tree).-- **422**, **413** and **400** on `resources` — a path that cannot name a file inside the bundle (`InvalidResourcePath`), a file no step names (`BundleResourceNotNamedError`), files that cannot make one tree (`BundleResourcePathError`), a file or a request over its size limit (`PayloadTooLarge`), or a value that is not base64 (`InvalidBase64`) — see [Sending the files the steps read](#sending-the-files-the-steps-read-resources).+- **422**, **413** and **400** on `resources` — a path that cannot name a file inside the bundle (`InvalidResourcePath`), a file no step names (`request.invalid`), files that cannot make one tree (`request.invalid`, or `security.input_path_refused` for a path the tree rule refuses), a file or a request over its size limit (`PayloadTooLarge`), or a value that is not base64 (`InvalidBase64`) — see [Sending the files the steps read](#sending-the-files-the-steps-read-resources).- **401 / 403** — unauthenticated / forbidden (including a per-request `orchestration_mode` override the deployment does not allow).-- **`method_ref` resolution failures** — a selector that could not be resolved produced no verdict, so it is never rendered as `is_valid: false`: a malformed reference or a failed fetch is a **422**, no matching package in the repository a **404**, and the custom-Python policy (the sandbox gate, the structures refusal) a **403** — the same statuses and `error_type`s as on the run routes (see the [error table](pipe-run.md#running-a-method-by-address-method_ref)).-- **5xx** — a server fault (including a host-wiring programmer error, surfaced as `PipelexUnexpectedError`).+- **`method_ref` resolution failures** — a selector that could not be resolved produced no verdict, so it is never rendered as `is_valid: false`: a malformed reference is a **422** `request.invalid`, a failed fetch a **502** `method.fetch_failed`, no matching package in the repository a **404** `method.not_found`, the sandbox gate on custom Python a **403** `CustomCodeRequiresSandbox`, and the refusal of Python structure classes a **422** `pipelex.deployment.python_structures_refused` — the same statuses and codes as on the run routes (see the [error table](pipe-run.md#running-a-method-by-address-method_ref)).+- **5xx** — a server fault (including a host-wiring programmer error, surfaced as `runtime.unexpected`).Read it as one rule: a non-2xx on `/validate` always means "the endpoint could not produce a verdict," never "your bundle is bad."diff --git a/docs/building-methods/concepts/python-classes.md b/docs/building-methods/concepts/python-classes.mdindex 8b374149d..1039190c0 100644--- a/docs/building-methods/concepts/python-classes.md+++ b/docs/building-methods/concepts/python-classes.md@@ -45,7 +45,7 @@ Classes inheriting from `StructuredContent` are automatically discovered and reg**Best practice:** Keep your `StructuredContent` classes in dedicated modules (e.g., `*_struct.py` files) with minimal module-level code, or ensure module-level code is safe to execute during discovery.!!! warning "Not available on the hosted API"- Python structure classes are an open-source and self-hosted feature. Using one means importing its module, and the hosted API never imports a method's Python into its own process. It refuses any method whose Python declares a `StructuredContent` subclass, whether the method was sent inline, saved to the catalog or fetched by address. The refusal is a `MethodStructuresRefusedError` naming each file and class. Python that only holds PipeFuncs is accepted, because PipeFuncs run in an isolated sandbox.+ Python structure classes are an open-source and self-hosted feature. Using one means importing its module, and the hosted API never imports a method's Python into its own process. It refuses any method whose Python declares a `StructuredContent` subclass, whether the method was sent inline, saved to the catalog or fetched by address. The refusal is a problem with the code `pipelex.deployment.python_structures_refused`, whose operator view names each file and class. Python that only holds PipeFuncs is accepted, because PipeFuncs run in an isolated sandbox.To run such a method on the hosted API, declare its types as MTHDS concepts with [inline structures](inline-structures.md). A PipeFunc can still return them: in the sandbox, Pipelex generates a `structures` module from the method's concepts, so the function imports the class it returns with `from structures import <domain>__<Concept>`.diff --git a/docs/building-methods/pipes/pipe-controllers/PipeCondition.md b/docs/building-methods/pipes/pipe-controllers/PipeCondition.mdindex 8e69ea3bf..7ea04291e 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. `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.+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 message only the operator view of the problem carries.## Configuration@@ -150,7 +150,7 @@ Process this document of unknown type, classified as $classification...Beside pipe names, an outcome (or the `default_outcome`) can be one of two special outcomes:-- **`fail`**: the run fails loudly with an error naming the pipe. Use it to make "this should never happen" branches explicit. The failure is a refusal written into your method, so a hosted run answers it with HTTP 422 and keeps its message, with a next step, under STRICT disclosure. The message leaves out the value the expression rendered, which the run's execution graph keeps: that value can be text of a condition a host's library declared.+- **`fail`**: the run fails loudly with an error naming the pipe. Use it to make "this should never happen" branches explicit. The failure is a refusal of the run's inputs written into your method, with the code `pipe.condition_refused` in the `input` domain, so a hosted run answers it with HTTP 422, its sentences naming the pipe and its next step asking for inputs the method accepts. The message leaves out the value the expression rendered, which the run's execution graph keeps: that value can be text of a condition a host's library declared.- **`continue`**: the condition declares that it produced **no output**. The runtime records an absence for the declared output, whose reason names the condition and its `continue` outcome, and the run continues as a success — the rest of the working memory is unchanged. The reason leaves out the value the expression rendered, which the run's execution graph keeps, for the same reason a `fail` outcome's message does: a pipe that later requires the output quotes the reason to the caller.Because `continue` resolves the declared output as absent, a `continue`-reachable condition (any outcome mapped to `continue`, or `default_outcome = "continue"`) **must declare its output optional** — `output = "Constraint?"`. Validation enforces this statically (`optional_output_required`), so the no-output path is always visible to the type system. The same visibility rule applies at the condition's boundary: if a mapped outcome pipe declares an optional output, the condition must declare `?` too (`optional_not_handled`). So must a condition whose outcome pipe takes plainly an input the condition declares optional: when that input is absent, the chosen outcome is skipped and the condition's output resolves absent, along with every name the outcome would have stored in the caller's memory. A list output is the exception, since a skipped list output is an empty list. Validation does not read the expression, so a condition that chooses such an outcome only when the input is present, as `{{ 'with_flag' if flag is defined else 'no_flag' }}` does, is refused as well: declare the input forced on that outcome, `flag = "Text!"`, which says the outcome never runs without it and fails the run loudly if it ever does.diff --git a/docs/building-methods/pipes/pipe-controllers/PipeParallel.md b/docs/building-methods/pipes/pipe-controllers/PipeParallel.mdindex 1ea409563..ad03f8510 100644--- a/docs/building-methods/pipes/pipe-controllers/PipeParallel.md+++ b/docs/building-methods/pipes/pipe-controllers/PipeParallel.md@@ -34,7 +34,14 @@ A branch result may legitimately be **absent** at run time: the branch pipe decl### A branch and its field must agree on multiplicity-A branch that produces a list, such as a `PipeBatch` whose output is `Idea[]`, fills a field that holds a list, and a branch that produces one item fills a field that holds one item. When they disagree, the combine refuses the branch results, in the dry run of `pipelex validate` as in a run, and the refusal names the branch, its result and the field, and says which of the two to change; when the branch's multiplicity comes from its own `nb_output`, `multiple_output` or `batch_over` in `branches`, the refusal names that setting instead of the pipe's output. The advice is given only when the branch's concept fits the field, and whatever else the combine refused is reported beside it. The refusal is a fault in your method, so a hosted run answers it with HTTP 422 and keeps its message under STRICT disclosure, with the change to make as its next step:+A branch that produces a list, such as a `PipeBatch` whose output is `Idea[]`, fills a field that holds a list, and a branch that produces one item fills a field that holds one item. When they disagree, the combine refuses the branch results, in the dry run of `pipelex validate` as in a run, with the code `pipe.output_multiplicity`. The refusal is a fault in your method, so a hosted run answers it with HTTP 422, and its sentences, which the item of `pipelex validate` gives too, name the pipe, the result and the two multiplicities, with the change to make as the next step:++```text+Pipe 'analyze_topics' produced an output of the multiplicity 'list', but its output 'ideas' is declared 'single'.+Declare the output 'ideas' as 'list', or make pipe 'analyze_topics' produce 'single'.+```++The refusal's own message, which a local `pipelex run` prints and the operator view of a hosted run's problem carries, says more: it names the branch, its result and the field, and says which of the two to change; when the branch's multiplicity comes from its own `nb_output`, `multiple_output` or `batch_over` in `branches`, it names that setting instead of the pipe's output. The advice is given only when the branch's concept fits the field, and whatever else the combine refused is reported beside it:```textPipeParallel 'analyze_topics' cannot combine its branch results into its output 'TopicReview'. Branch 'draft_ideas' gives result 'ideas' as a list, 'Idea[]', but field 'ideas' of 'TopicReview' holds a single item. Declare the field as a list in the structure of 'TopicReview', with type 'list', item_type 'concept' and item_concept_ref 'Idea', or make branch 'draft_ideas' output a single 'Idea'.diff --git a/docs/building-methods/pipes/provide-inputs.md b/docs/building-methods/pipes/provide-inputs.mdindex 61e60826c..793d4c3d4 100644--- a/docs/building-methods/pipes/provide-inputs.md+++ b/docs/building-methods/pipes/provide-inputs.md@@ -223,6 +223,8 @@ When a value cannot be shaped against its declared concept, Pipelex raises a typ- **Incompatible explicit concept** — an envelope naming a concept that is not compatible with the declaration.- **Null value** — a top-level `null`; absence is expressed by *omitting* the key, not by providing `null`. (An input declared optional with `?` may simply be left out — see [Understanding Optionality](understanding-optionality.md).)+That message, with its expected shape, is what the CLIs print and what whoever runs the runtime reads. A caller of the API reads the refusal's [problem document](../../api-server/error-responses.md) instead, whose `params.input` and `location.input` name the input and whose code's sentence is rendered from what is wrong with it: the expected and provided counts of `input.wrong_multiplicity`, the declared and provided concepts of `input.wrong_concept`, the field at fault of `input.invalid` when the concept's structure names one, and the name of `input.unexpected`.+## Input files: JSON or TOMLAn inputs file is a dictionary of input names to values, accepted as **both JSON and TOML**, discriminated by file extension (`.toml` → TOML, everything else → JSON). Both produce the same dictionary, so every shape above applies to either. TOML's multi-line strings (`"""…"""`) make text-heavy inputs far easier to author, and a top-level TOML date/datetime literal (`hearing = 2026-09-01`) maps directly to the native [`Date`](../concepts/native-concepts.md) concept.diff --git a/docs/building-methods/pipes/running-on-the-hosted-api.md b/docs/building-methods/pipes/running-on-the-hosted-api.mdindex 0a980f749..558309cf6 100644--- a/docs/building-methods/pipes/running-on-the-hosted-api.md+++ b/docs/building-methods/pipes/running-on-the-hosted-api.md@@ -78,7 +78,7 @@ Two cases where `pipelex run --hosted` goes further than `prepare_inputs`:A failure is one of the SDK's typed errors, from `pipelex_sdk.errors`, all subclasses of the protocol's `PipelineRequestError`:- `ApiResponseError` is a refusal the hosted API answered: `status`, the reason in `server_message`, the next step in `user_action.detail` when the server advised one, and `validation_errors` locating the faults of a bundle it refused to load.-- `RunFailedError` is a run that started and failed; `error` holds its stored report, with the runner's `error_type`, `message`, `error_domain` and `user_action`.+- `RunFailedError` is a run that started and failed; `error` holds the error the hosted API stored for the run, with the runner's `error_type`, `message`, `error_domain` and `user_action`.- `RunTimeoutError` is a run that outlived the wait; it keeps running, and `run_id` reads its result later with `wait_for_result`.- `ApiUnreachableError` is a request that got no answer, on every route, `start` and `execute` included. Its `__cause__` is httpx's exception, and its `code` names the failure: `ABORT_TIMEOUT` for a read or a write that timed out, otherwise httpx's class name, such as `ConnectError`, `ConnectTimeout`, `ReadError` or `RemoteProtocolError`.- `InputPreparationError` and its subclasses are a local file that could not be read or uploaded.diff --git a/docs/configuration/config-technical/library-config.md b/docs/configuration/config-technical/library-config.mdindex d75a8335d..a25246fec 100644--- a/docs/configuration/config-technical/library-config.md+++ b/docs/configuration/config-technical/library-config.md@@ -287,7 +287,7 @@ 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.+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 only the operator view of the problem carries, 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 Organizationdiff --git a/docs/tools/cli/agent-cli.md b/docs/tools/cli/agent-cli.mdindex aacac40e3..d5516c2ca 100644--- a/docs/tools/cli/agent-cli.md+++ b/docs/tools/cli/agent-cli.md@@ -51,7 +51,7 @@ pipelex-agent run method <NAME> [OPTIONS]For `bundle` and `method`, use `--pipe` to target a specific pipe.-`run bundle` reads its method through its [method tree](../../building-methods/method-trees.md), as `pipelex run bundle` does. A folder is the method rooted at the nearest `METHODS.toml` at or above it, else at the folder itself, and with no `--pipe` the run starts at the manifest's `main_pipe`, or, with no manifest, at the one `main_pipe` its bundles declare; none or several is refused as a `ValidateBundleError` naming each bundle by its path in the tree. A bundle file named alone starts at its own `main_pipe`, and with no `METHODS.toml` at or above its folder its method is that one file, so a step naming a file beside it, such as a `template_file`, is refused with the advice to run the folder or to add a `METHODS.toml`. The run's output file (`live_run.json` or `dry_run.json`, in the run's output folder) carries `method_tree_digest`, the digest of the tree the run read, and so does the output under `--with-memory`.+`run bundle` reads its method through its [method tree](../../building-methods/method-trees.md), as `pipelex run bundle` does. A folder is the method rooted at the nearest `METHODS.toml` at or above it, else at the folder itself, and with no `--pipe` the run starts at the manifest's `main_pipe`, or, with no manifest, at the one `main_pipe` its bundles declare; none or several is refused as a `MethodEntryError` naming each bundle by its path in the tree, with the `error_code` `request.pipe_unspecified`, naming the declared ones as its `candidates` when there are several, and no `validation_errors`, since the method may be valid and only the pipe to start at is missing: pass `--pipe`. A bundle file named alone starts at its own `main_pipe`, and with no `METHODS.toml` at or above its folder its method is that one file, so a step naming a file beside it, such as a `template_file`, is refused with the advice to run the folder or to add a `METHODS.toml`. The run's output file (`live_run.json` or `dry_run.json`, in the run's output folder) carries `method_tree_digest`, the digest of the tree the run read, and so does the output under `--with-memory`.#### Running on the hosted API@@ -59,7 +59,7 @@ With `--runner hosted` (or `--hosted`, or `[run] execution = "hosted"`), the runThe success envelope has the shape of a local run's. Compact, it is the main output's content. With `--with-memory`, `main_stuff.json` is that content (the hosted API renders no Markdown, so the markdown output shows the JSON), `working_memory` is the whole working memory, `pipeline_run_id` names the run on the hosted API, and `uploads` lists the files uploaded for it. A hosted run writes nothing to disk.-A run refuses an invalid bundle while loading it, before any pipe runs, with exit code `1` and an error envelope whose `error_type` is `ValidateBundleError` and whose `validation_errors` array holds the items `validate` gives for that bundle, each with its pipe, its field and its suggested fix when it has one. A refusal found while loading a library directory you pass with `-L` (or the method's folder, for `run bundle <dir>`) is reported the same way, its items naming their file in `source`; a bundle file run on its own is loaded from its text, so the items of a refusal found while loading it carry no `source`, while a bundle that does not parse when `run bundle` looks for its `main_pipe` (no `--pipe`) names its file. In markdown, the items render as the same grouped prose `validate` prints.+A run refuses an invalid bundle while loading it, before any pipe runs, with exit code `1` and an error envelope whose `error_type` is `ValidateBundleError` and whose `validation_errors` array holds the items `validate` gives for that bundle, each with its pipe, its field and its suggested fix when it has one. A refusal found while loading a library directory you pass with `-L` (or the method's folder, for `run bundle <dir>`) is reported the same way, its items naming their file in `source`; a bundle file run on its own is loaded from its text, so the items of a refusal found while loading it carry no `source`, while a bundle that does not parse when `run bundle` looks for its `main_pipe` (no `--pipe`) names its file. In markdown, the items render as the same grouped prose `validate` prints. The items come from the verdict on the error's own chain of Pipelex errors: a failure of another kind raised while handling an earlier verdict, such as an unexpected error, lists none of that verdict's items.!!! note "Stdin inputs stay JSON"The agent CLI can also read inputs from stdin (a flat dict or a `working_memory` envelope). Stdin inputs are **JSON-only** — the extension-based TOML discrimination applies to `--inputs` file paths only. Like the main CLI, `run bundle <dir>` auto-detects `inputs.json` / `inputs.toml` when `--inputs` is omitted, erroring if both exist, and refuses one that is not a regular file, such as a symbolic link, which it never follows, under `"error_type": "AutoDetectedInputsFileError"`; a file named with `--inputs` is read as given, a link followed. In a `working_memory` envelope each stuff must name its concept as the ref string; anything else there — the full concept object an older runtime dumped, for instance — is refused under `"error_type": "StdinEnvelopeShapeError"`, which is the label for an envelope that parsed as JSON but does not hold the shape the contract asks for, as distinct from the `JSONDecodeError` that means the JSON itself did not parse.@@ -97,7 +97,7 @@ For `bundle`, additional options are available:On a successful run, the envelope also carries `pending_signatures` — the library-wide list of pipes still declared as `PipeSignature` (unimplemented forward declarations), each namespaced by `pipe_ref` (`domain.code`). In JSON it is a `pending_signatures` array, in markdown a "Pending signatures" section. A top-down build reads it to see exactly which headers remain to implement. The envelope also carries a derived `is_runnable` boolean (`true` ⇔ `pending_signatures` is empty), and the markdown states the runnability verdict in plain English — runnable when complete, NOT yet runnable above the "Pending signatures" section otherwise. `validate bundle`, `validate method`, and `validate pipe --all` carry them and gate on them: without `--allow-signatures`, the command exits non-zero when `is_runnable` is false. Bare `validate pipe <code>` omits them, and a `--pipe` slice surfaces them for information without gating.!!! note "Every refusal of the bundle is an invalid verdict"- A refusal of your input raised while the bundle is loaded or validated is answered with the invalid-verdict envelope — `is_valid: false` and a `validation_errors` array — and exit code `1`, never the no-verdict envelope and exit code `2`, which is kept for failures of the tool or its environment. A pipe whose dry run fails gives one `dry_run` item per failing pipe, with `error_type: DryRunError`, the `pipe_code`, `domain_code` and `source` of the innermost pipe that failed and is not allowed to fail (its `source` whenever the pipe is in your files; a validator of submitted content beside a host's library directories names only that content's files), and a message that keeps the failure's own text only when it is caller-facing, on `validate bundle`, `validate pipe <code>` and `validate pipe --all` alike; a controller that failed because a pipe it runs failed is reported once, at that pipe. Every error found while parsing is its own item, so a misspelled field is reported beside the categorized errors as an item without an `error_type`, carrying its `pipe_code`, `source` and `field_path`. A TOML syntax error's item carries its 1-based `line` and `column`, and an `unresolved_concept` item lists the concepts the validated bundle declares in its domain in `declared_concepts`. A pipe naming a model the model deck does not define gives one `pipe_validation` item with `error_type: unknown_model`, carrying `pipe_code`, `domain_code`, `source`, `field_path` (`pipe.<code>.model`), `model_reference` (the reference as written), `model_type` and `suggestions` (the deck's close matches), plus a `rename-model` `suggested_fix` when there is exactly one suggestion. That fix's `safety` is `unsafe`, because a close name can still be a different model: `fix bundle` never applies it, and the Markdown labels it `💡 Suggested fix (unsafe, confirm before applying):` where a safe fix reads `💡 Suggested fix:`. Any other refusal of your input with no code of its own gives one item without an `error_type`, located on its pipe when it was raised while that pipe was built. A pipe factory's refusal, such as a `PipeExtract` whose input is neither an image nor a document, is one of these items, located on its pipe. See [Error Model](../../under-the-hood/error-model.md#validation_errors-structured-bundle-validation-diagnostics).+ A refusal of your input raised while the bundle is loaded or validated is answered with the invalid-verdict envelope — `is_valid: false` and a `validation_errors` array — and exit code `1`, never the no-verdict envelope and exit code `2`, which is kept for failures of the tool or its environment. A pipe whose dry run fails gives one `dry_run` item per failing pipe, with `error_type: DryRunError`, the `pipe_code`, `domain_code` and `source` of the innermost pipe that failed and is not allowed to fail (its `source` whenever the pipe is in your files; a validator of submitted content beside a host's library directories names only that content's files), and a message naming the pipe and giving the sentence the failure's code renders for a caller, never the failure's own text, on `validate bundle`, `validate pipe <code>` and `validate pipe --all` alike; a controller that failed because a pipe it runs failed is reported once, at that pipe. Every error found while parsing is its own item, so a misspelled field is reported beside the categorized errors as an item without an `error_type`, carrying its `pipe_code`, `source` and `field_path`. A TOML syntax error's item carries its 1-based `line` and `column`, and an `unresolved_concept` item lists the concepts the validated bundle declares in its domain in `declared_concepts`. A pipe naming a model the model deck does not define gives one `pipe_validation` item with `error_type: unknown_model`, carrying `pipe_code`, `domain_code`, `source`, `field_path` (`pipe.<code>.model`), `model_reference` (the reference as written), `model_type` and `suggestions` (the deck's close matches), plus a `rename-model` `suggested_fix` when there is exactly one suggestion. That fix's `safety` is `unsafe`, because a close name can still be a different model: `fix bundle` never applies it, and the Markdown labels it `💡 Suggested fix (unsafe, confirm before applying):` where a safe fix reads `💡 Suggested fix:`. Any other refusal of your input with no code of its own gives one item without an `error_type`, located on its pipe when it was raised while that pipe was built. A pipe factory's refusal, such as a `PipeExtract` whose input is neither an image nor a document, is one of these items, located on its pipe. See [Error Model](../../under-the-hood/error-model.md#validation_errors-structured-bundle-validation-diagnostics).!!! note "Advisory warnings on validate"Whole-bundle and whole-library validate surfaces (`validate bundle`, `validate method`, `validate pipe --all`) also carry a `warnings` array — advisory findings on a VALID bundle that never flip the verdict or the exit code. Each entry has the **same shape as a validation error item** (`category`, `error_type`, `pipe_code`, `domain_code`, `variable_names`, `message`) — this is a different shape from the `init`/`doctor` setup `warnings` (`{type, message}`) documented under Output Contract below. Four families ride the array, always in this order: the useless-`!` lint (`optional_force_redundant`), a `!` (force) input whose slot is guaranteed present in every analyzed flow, so the assertion can never fire; the vacuous-presence lint (`input_presence_vacuous`), an entry-pipe input that must be supplied but whose concept declares no required field, so the empty object satisfies it and a caller cannot tell what to fill in (see [Understanding Optionality](../../building-methods/pipes/understanding-optionality.md)); the [intent-hint](../../building-methods/concepts/intent-hints.md) lints (`hint_unknown_key`, `hint_unknown_intent`, `hint_inapplicable_intent`); and the warnings of a [`PipeDocGen`](../../building-methods/pipes/pipe-operators/PipeDocGen.md#office-template-files) step's template check (`template_check_warning`), found by the engine in the step's office template file during the dry run, as a `dry_run` item that also carries `template_file` (the file as the step names it) and `template_location` (the place in it, in the engine's words, absent when the engine names none). Every whole-bundle validate channel — this CLI, the bare CLI and the protocol validation report — assembles them from one composition point, so which advisories you see does not depend on which command you typed. Hint findings are bounded per site: a site naming many undefined keys reports the first few and then how many more there were, and a long authored key or value is elided in the message. In markdown, warnings render as a "Warnings" section. The array is empty when there is nothing to report. `validate pipe <code>` carries the template-check warnings alone: one pipe has no flow context to lint in, but what its dry run found is about that pipe. `validate bundle`/`validate method` with `--pipe` keep it, and it stays bundle-wide there — the slice narrows the dry run, not the validation.@@ -215,13 +215,13 @@ 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.+`error_code` is the registry code of the error behind the failure, as its problem carries it, 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. On a Pipelex error the `hint` is the advice nearest the failure along its cause chain, else the command's own advice for its class, else the next step its code gives whoever runs the runtime, so an envelope with an `error_code` always carries a `hint`.**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 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`.+**A hosted run that started and failed** reports the error the hosted API stored for it: `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 stored error'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`.**`migration`** — a configuration error (`"error_domain": "config"`) carries an extra `migration` object when, and only when, a scan of this machine's configuration directories found something. Its presence says the migration history has something to report about these files; **`would_write` says whether a command repairs them.** The object holds `remedy` (the command that fixes what can be fixed), `would_write` (whether running it would rewrite any of these files), `needs_attention` (whether something there is a person's decision rather than the tool's), and `plans` — one per file, in the same shape [`pipelex-agent migrate`](migrate.md) emits under its own `plans` key. On `would_write: true` the loop is `pipelex-agent migrate --dry-run --format json`, show the user what would change, then `--yes`. On `would_write: false` there is nothing to run: the plans carry a path no ledger entry explains, or an entry blocked before anything applied, and the command would visit the files, write nothing and leave the same error standing — so read the plans and correct what they name. Never answer either one by re-initializing a configuration file — that discards every setting the migration would have kept.diff --git a/docs/tools/cli/run.md b/docs/tools/cli/run.mdindex bc9590574..f28cf54a0 100644--- a/docs/tools/cli/run.md+++ b/docs/tools/cli/run.md@@ -80,7 +80,7 @@ pipelex run pipe my_pipe -L ./pipelines --hosted --inputs data.jsonpipelex run bundle <PATH> [OPTIONS]```-Runs a method from a bundle file (`.mthds`) or a method's folder, read through its [method tree](../../building-methods/method-trees.md). A folder is the method rooted at the nearest `METHODS.toml` at or above it, else at the folder itself, and with no `--pipe` the run starts at the manifest's `main_pipe`, or, with no manifest, at the one `main_pipe` its bundles declare; none or several is refused, naming each bundle by its path in the tree. An inputs file (`inputs.json` or `inputs.toml`) in the folder is auto-detected when `--inputs` is not passed (see [Auto-detection and ambiguity](#auto-detection-and-ambiguity)). A bundle file named alone starts at its own `main_pipe`, and with no `METHODS.toml` at or above its folder its method is that one file, so a step naming a file beside it, such as a `template_file`, is refused: run the folder instead, or add a `METHODS.toml`.+Runs a method from a bundle file (`.mthds`) or a method's folder, read through its [method tree](../../building-methods/method-trees.md). A folder is the method rooted at the nearest `METHODS.toml` at or above it, else at the folder itself, and with no `--pipe` the run starts at the manifest's `main_pipe`, or, with no manifest, at the one `main_pipe` its bundles declare; none or several is refused with `Failed to run:` and a message naming each bundle by its path in the tree, which is no verdict on the method, since only the pipe to start at is missing: pass `--pipe`. An inputs file (`inputs.json` or `inputs.toml`) in the folder is auto-detected when `--inputs` is not passed (see [Auto-detection and ambiguity](#auto-detection-and-ambiguity)). A bundle file named alone starts at its own `main_pipe`, and with no `METHODS.toml` at or above its folder its method is that one file, so a step naming a file beside it, such as a `template_file`, is refused: run the folder instead, or add a `METHODS.toml`.The run prints the digest of the tree it read with its recap, and records the tree as `method_tree.json` in its output folder (see [The results directory](#the-results-directory)).diff --git a/docs/tools/logging.md b/docs/tools/logging.mdindex 0282aac36..691db39e9 100644--- a/docs/tools/logging.md+++ b/docs/tools/logging.md@@ -449,7 +449,7 @@ A message says what happened, and how it was handled when that matters, in one s- **One shape.** The subject comes first, then what happened to it, in the past tense or as a state: "A pipe of a dependency could not be loaded", "The routing profiles were read with override files merged over the base", "A stuff name starts with an underscore". A failure is "could not be", never "Failed to". The [summary events](#summary-events) and the pipe-run announcement keep their present-tense names, `Inference call ends`, `Pipe run ends` and `Pipe run starts`, which name events rather than tell what happened.- **Short.** At INFO and above a message holds at most 80 characters, so the line, its fields included, mostly stays on one line of a terminal. A consequence the reader needs goes in the sentence when it fits, "A model waterfall that leads back to itself resolves to no model", and the rest in fields; a second clause after "so" or ";" is a sign the sentence carries two things.-- **Advice in `user_action`.** What the reader should do rides in the `user_action` field, one imperative sentence written like a message, a command included as plain text: `fields={"user_action": "Run pipelex migrate to update it"}`. One event with several remedies is then one message with several `user_action` values, so a log store counts the event once whatever the cause. The console prints the advice on a line of its own under the record ([The advice under the line](#the-advice-under-the-line)), and every other sink writes it as a field. Pipelex's error reports carry their advice under the same name.+- **Advice in `user_action`.** What the reader should do rides in the `user_action` field, one imperative sentence written like a message, a command included as plain text: `fields={"user_action": "Run pipelex migrate to update it"}`. One event with several remedies is then one message with several `user_action` values, so a log store counts the event once whatever the cause. The console prints the advice on a line of its own under the record ([The advice under the line](#the-advice-under-the-line)), and every other sink writes it as a field. A Pipelex error carries its advice under the same name, which the local CLIs print as a tip.- **No identifier and no backtick.** A message is written for the person reading the log, not for the code: no snake_case name, no call, no `needs_inference=False`, no backticks. What the reader needs of an identifier is a field's value: an environment variable's name rides in `env_var`, a job's class in `inference_job_type`. A word of Pipelex's own vocabulary, a pipe type such as `PipeBatch` or a file such as `METHODS.toml`, is a word like any other.- **A capital, no period, no prefix.** A message starts with a capital letter and ends with no period and no `...`, and carries no subsystem tag such as `OTel:`, since the logger's name already says where a line comes from.- **DEBUG and VERBOSE follow the same wording**, beside the f-strings they may keep, and one thing has one verb: a client that is made is "Made" on every line, never "Init" on one and "Initializing" on the next.@@ -558,9 +558,9 @@ What varies goes in `fields`, named by the [naming convention](#naming-conventio| `auth_refusal_reason` | string | Why the API server refused a caller's own credentials: `missing_bearer_token`, `expired_token`, `invalid_token` or `api_key_mismatch` || `claim_type` | string | The type a token's claim was decoded as, by its Python name, where the claim is refused and its value is not logged: `str`, `int`, `dict` || `error.type`, `error.message` | string | A handled exception's class name and its text, as [Exceptions](#exceptions) describes |-| `error_domain` | string | Who fixes a failure, as an error report classifies it: `input`, `config`, `runtime` |-| `error_category` | string | A failure's Pipelex classification, as an error report carries it |-| `retryable` | boolean | Whether retrying the failed call as it was can help, as an error report says |+| `error_domain` | string | Who fixes a failure: `input`, `config`, `runtime`, read from the domain of the failure's code |+| `error_category` | string | An inference failure's Pipelex classification, as its error carries it |+| `retryable` | boolean | Whether retrying the failed call as it was can help, as the failure's code says || `detail` | string | The explanation an API error response gives its caller || `user_action` | string | What the reader of a line should do about it, one imperative sentence: `Run pipelex migrate to update it`. The console prints it on a line of its own under the record, as [The advice under the line](#the-advice-under-the-line) shows || `provider_status_code` | integer | The HTTP status an inference provider answered a failed call with |diff --git a/docs/under-the-hood/distributed-content-generation.md b/docs/under-the-hood/distributed-content-generation.mdindex 79c411e57..bd76c46dc 100644--- a/docs/under-the-hood/distributed-content-generation.md+++ b/docs/under-the-hood/distributed-content-generation.md@@ -184,7 +184,7 @@ 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 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 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`, 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; 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 a47177f2d..57a1a4e14 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. 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.+`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, `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 ff1ff9b17..8d41adbbd 100644--- a/docs/under-the-hood/error-model.md+++ b/docs/under-the-hood/error-model.md@@ -1,13 +1,13 @@---title: "Error Model"-description: "How Pipelex classifies, carries, and reports errors — the ErrorReport schema, inference error categories, error domains, the layer model, worker classification, and how classification survives a distributed worker boundary."+description: "How Pipelex classifies, carries, and reports errors — the problem document and its views, error codes, inference error categories, the layer model, worker classification, and how a problem survives a distributed worker boundary."---# Error ModelIn Pipelex, an error is **data**, not a control-flow accident. Every failure is classified once — at the layer that knows the most about it — and that classification travels intact to every consumer: the human reading a Rich panel, the agent parsing JSON, a distributed worker's retry engine, and the HTTP adapter picking a status code.-This page covers the contract that makes that possible: the `ErrorReport` schema, the classification enums, how inference workers classify SDK exceptions, how classification survives every wrapping layer, and how it survives serialization across a distributed worker boundary.+This page covers the contract that makes that possible: the problem document every error becomes and the views its readers see it through, the registry code that decides what the problem says, the classification enums, how inference workers classify SDK exceptions, how classification survives every wrapping layer, and how a problem survives serialization across a distributed worker boundary.---@@ -15,7 +15,7 @@ This page covers the contract that makes that possible: the `ErrorReport` schemaThree rules hold across the codebase, and everything else builds on them.-**Single-rooted hierarchy.** Every custom exception inherits from `PipelexError` (`pipelex/base_exceptions.py`). There is one root, so one `to_error_report()` contract covers the whole tree.+**Single-rooted hierarchy.** Every custom exception inherits from `PipelexError` (`pipelex/base_exceptions.py`). There is one root, so one `to_problem()` contract covers the whole tree.**Classify at the source, never lose it.** The layer that catches a third-party exception knows the most about it. It classifies there. Every layer above is a *wrapper* — it adds context (pipe code, stack) but inherits the classification rather than re-deriving or discarding it.@@ -39,43 +39,101 @@ 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 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.+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 Facts](#cause-chain-facts)). The worker's classification picks the code, and the code decides the domain, the retry verdict, the next step, the sentences a reader is told and the HTTP status, so a single Layer-1 decision settles them all.----## ErrorReport — the Serialization Schema+## The Problem Document-`ErrorReport` (`pipelex/base_exceptions.py`) is the single source of truth for error serialization. It is a frozen Pydantic model with `extra="forbid"`.+Every error becomes a **problem document**, `PipelexProblem` (`pipelex/errors/problem.py`): the MTHDS standard's problem, an RFC 9457 problem with the members the standard adds, extended with Pipelex's own. It is a frozen Pydantic model, and it is the single source of truth for what a failure says on every surface: the API's error responses, a failed run's completion webhook, a failed node of the execution graph, a distributed worker's packed failure and the agent CLI's error envelope.-| 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` | 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 |-| `provider_metadata` | `ProviderErrorMetadata \| None` | SDK metadata — status code, request id, `retry_after` |-| `validation_errors` | `list[ValidationErrorItem] \| None` | Structured per-error diagnostics on a bundle-validation failure (`ValidateBundleError` only) |+| Member | Meaning |+|--------|---------|+| `type` | The code's documentation page: `https://mthds.ai/errors/<code>` for a core code, `https://docs.pipelex.com/errors/<code>` for a Pipelex code |+| `title` | The code's title, the same for every occurrence of the code |+| `status` | The HTTP status the code declares, which only the HTTP response carrying the problem sets |+| `detail` | The sentence stating this occurrence, rendered from the code's template with the problem's parameters |+| `code` | 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) |+| `domain` | Who must act, the code's registry domain: `input`, `method`, `account`, `operator` or `runtime` |+| `retry` | The code's retry verdict: `yes`, `no` or `outcome_unknown` |+| `retry_after` | The delay in seconds a provider asked for before a retry, kept only on a code whose verdict is `yes` and only when it is finite and not negative |+| `next_step` | What the reader of this view does next: its `kind` and its `detail`, the step's sentence rendered from the code's template |+| `params` | The parameters the code declares that a caller may read, by the registry's names |+| `location` | Where the fault is: the failing `pipe` and its `path` from the entry pipe, an `input`, a `field`, a batch `item`, an `attempt`, or a `file` with its `line` and `column` |+| `errors` | One item per fault, for a refusal of several at once such as a method that does not validate: each with its own `code`, `detail`, `params` and `location`, and the `suggestions` and `suggested_fix` its validation item carries |+| `pipeline_run_id` | The run the problem belongs to |+| `request_id` | The request that carried the failure |+| `run_error` | On a read of a failed run's results, the run's own problem |+| `diagnostics` | What only an operator reads, present in the operator view alone: see [Diagnostics](#diagnostics) |-`PipelexError.to_error_report()` is the entry point. `to_dict()` serializes, dropping `None` fields; `from_dict()` is its strict inverse.+No declared member is ever written as `null`. The model's serializer drops every member a model declares that holds no value, at every depth and whoever dumps the problem, alone or nested in a model that holds one (a graph node, a trace event, a webhook's payload), so a reader validating against the standard's schema never refuses it. The protocol refuses `null` on a declared member and nowhere else, so a `null` an extension member holds, or one inside a free-form object, is a value: every write keeps it as it was read, the caller view included, so `{"extension": {"clear": null, "keep": 1}}` comes back whole. `to_wire()` gives the problem in JSON types, and so does `as_wire()`: both walk the model by hand, as the standard's own `Problem.as_wire()` does, rather than through Pydantic's serializer, which refuses a value nested a few hundred levels deep, so every problem a reader accepts, up to the standard's `MAX_BODY_NESTING`, can be written back, a recovered one with a deeply nested extension member included, and its caller view projected (`caller_view_of()`). A problem dumped inside another model goes through Pydantic's serializer and keeps its limit.++`PipelexError.to_problem(view=...)` is the entry point. `make_problem()` builds a problem from a code and `make_problem_item()` one item of a problem with several faults, both taking everything the code decides from the registries' generated tables.++### Views: who reads the problem++A problem is one document seen through a **view**, and who reads it picks the view, never a deployment setting. `ProblemView` has two members:++- **The caller view** (`ProblemView.CALLER`) is for whoever sent the request or wrote the method. It carries no `diagnostics`, and its step is the one the code gives the actor of its domain, except on a code of the `operator` domain: that actor is whoever runs the runtime, so the caller reads the code's other step instead, what it can do meanwhile, such as choosing another model.+- **The operator view** (`ProblemView.OPERATOR`) is for whoever runs the runtime. It adds the `diagnostics`, its step is always the actor's, and it renders into that step the parameters only an operator may read.++The operator view holds everything the caller view does, so a reader holding the operator's record serves its caller from it: `caller_view_of()` drops the diagnostics, renders the caller's step again from the problem's `params`, and projects a nested `run_error` the same way. It fails closed on a code neither registry of this process holds, such as one a newer worker or a stored record carries: that step cannot be rendered again and the operator's may name an operator-only parameter, so the caller reads the generic sentence of the step's kind, and the `report` step for a code of the `operator` domain. An item of such a code fails closed the same way: its parameters cannot be told apart, so the caller reads it with no `params` and with `UNKNOWN_CODE_ITEM_DETAIL` as its sentence, while the operator reads it as it came.++A third, narrower projection, `problem_metadata()`, gives a `ProblemMetadata`: what may leave a perimeter, such as a telemetry event. It holds the codes, the domain, the verdict, the step's kind, the shape of the location (the failing pipe's depth, the attempt and the batch index, naming nothing), the items' codes, the ids and the runtime version, and never a sentence, a parameter or a name a user wrote.++| Reader | View |+|--------|------|+| An API response | The view of the identity the request authenticated: the operator view for the operator's own credential and for the trusted proxy in front of the server, the caller view for anyone else (see the API server's [Error Responses](../api-server/error-responses.md#views-chosen-by-identity)) |+| A failed run's completion webhook | The view of whoever started the run, which `WebhookTarget.problem_view` carries, the caller view when the host that built the target names none |+| A failed node of the execution graph | The caller view, since whoever reads the run reads its graph |+| The human and agent CLIs, and the API's log record | The operator view, since their reader runs the runtime |+| A distributed worker's packed failure | The operator view, which the submitter projects to the view of its own reader |++### Sentences come from the code, never from the message++What a caller reads is written in the registry, not at the raise site. `detail` and the step's `detail` are rendered from the code's templates with the problem's parameters, and an error's own message, which its raise site writes for whoever debugs the runtime, rides only the operator view's `diagnostics.message`. A raise site can therefore put in its message anything that helps an operator, such as a path on the host, a configuration value, a foreign exception's text or a model's output, and no caller reads it; what a caller needs in order to act is given as parameters.++Rendering never fails. A template naming a parameter the problem does not hold makes `detail` fall back to the code's title, and the step to the generic sentence of its kind, such as `Correct the method as the problem describes, then validate it again.` The fallback is logged as a warning, `A problem's sentence could not be rendered from its template`, with the code and the reason as fields, so a raise site that forgot a parameter is found in the logs while the reader still reads a sentence.++### Parameters++A code declares its parameters in the registry, each typed, and its generated parameters model validates them. A problem's parameters come from the error whose code it reports:++- **The class's facts.** A subclass holding facts its codes declare overrides `problem_params()` and returns them by the registry's names. An input-shaping error (`InputShapingError`), for one, gives the input and what its factory found wrong with it, such as the counts of `input.wrong_multiplicity` or the concepts of `input.wrong_concept`, and locates itself at the input. A fact the resolved code does not declare is left out silently, since a class's codes declare different parameters.+- **The raise site.** `with_params(**params)` gives the parameters only the raise site knows, and overrides a fact of the same name: `raise PipeRunError(...).with_error_code(CoreCode.PIPE_CONDITION_UNMATCHED).with_params(pipe=self.code)`.+- **What the run found.** A declared parameter neither of them gave is filled from the run: a failure located at a pipe gives a `pipe` parameter the failing pipe, and the model and the provider found along the cause chain give the `model` and `provider` parameters.++A parameter the code does not declare, or one of the wrong type, is dropped when the problem is built and logged as a warning naming the code and the parameter, and a number JSON cannot write, an infinity or `NaN`, counts as one of the wrong type whatever the code's model says: it is a fault of the raise site, which must never turn the error it reports into another. So does a value that is neither a JSON scalar nor a built-in list, tuple or set of them, such as a collection of collections, a cyclic one, or a sequence of a class of its own whose items raise when read: it is never walked, so reading it cannot raise in place of the error. The parameters kept validate against the code's model and the problem's own `params` model whatever the raise site gave, so a refusal that names no parameter, such as a model-level one, drops them all rather than fail the problem's construction. A parameter the registry marks `operator_only`, such as the file and the setting of `pipelex.config.invalid` or the variable `pipelex.config.variable_missing` names, never rides `params`: it renders into the operator's step and rides `diagnostics.params`, so a caller is never told where the operator keeps a file. Nor does it ride an item's `params`: `make_problem()` and `caller_view_of()` take such a parameter out of every item a problem carries, in every view and whoever built the item, and render the item's sentence again without it (`item_in_view()`).++### Diagnostics++`ProblemDiagnostics` is what the operator view adds:++| Member | Meaning |+|--------|---------|+| `error_class` | The class of the error the problem was built from |+| `message` | That error's own message |+| `causes` | The errors along its cause chain, each with its class and the code it carries by itself |+| `params` | The parameters only an operator may read |+| `model` | The model handle, when the failure is attributable to one |+| `provider` | What the provider answered: its `name`, the backend's, its `status`, its `code`, its `request_id` and its `message` |+| `migration` | A pending configuration migration that explains the failure |+| `runtime_version` | The version of the Pipelex runtime that built the problem |+| `trace_id`, `span_id` | The OpenTelemetry span the failure happened in, when one was recording |++Every text a raise site, a provider or a caller wrote is bounded in a problem: `diagnostics.message`, the provider's message and every text parameter are cut to `MAX_PROBLEM_TEXT_LENGTH` characters by `cap_problem_text()`, which keeps the head of the text and appends ` […]`. The full text is left to the logs, so a provider's answer quoting a whole prompt cannot inflate a webhook, a stored run or a graph.### The identity, and why renaming an error class or changing its code is a wire break-`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.+`code` is the identity a problem carries, and a consumer branches on it. `title` and `type` follow from the code, so no class declares them. The class an error was raised as is no member of the caller's problem: it rides the operator view's `diagnostics.error_class`, the agent CLI's envelope as `error_type` and the API's log record as `error.type`.-`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.+Changing the code a class declares changes what every reader is told to do, and breaks a consumer branching on the old code *silently*: its build stays green and its branch simply stops matching, falling through to a generic error path. Renaming an error class breaks whoever reads its name the same way: an agent switching on the CLI envelope's `error_type`, or an operator's log query or alert on `error.type`.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-The MTHDS standard names every error a runner or a client can meet with a code, `input.missing` or `model.unavailable`, and publishes them as its core error registry: one entry per code, declaring its title, the domain whose actor must act, its retry verdict, its steps, its typed parameters and its HTTP status. A problem's `type` is the code's page, `https://mthds.ai/errors/<code>` for a core code. What the standard leaves to implementations, billing, organizations, the hosted catalog, Pipelex's storage, its configuration and plugins and the components it ships, Pipelex names with codes of its own under the `pipelex` extension prefix, which the core registry registers to Pipelex: `pipelex.billing.credit_exhausted`, `pipelex.config.variable_missing`.+The MTHDS standard names every error a runner or a client can meet with a code, `input.missing` or `model.unavailable`, and publishes them as its core error registry: one entry per code, declaring its title, the domain whose actor must act, its retry verdict, its steps, the templates of its sentences, its typed parameters and its HTTP status. A problem's `type` is the code's page, `https://mthds.ai/errors/<code>` for a core code. What the standard leaves to implementations, billing, organizations, the hosted catalog, Pipelex's storage, its configuration and plugins and the components it ships, Pipelex names with codes of its own under the `pipelex` extension prefix, which the core registry registers to Pipelex: `pipelex.billing.credit_exhausted`, `pipelex.config.variable_missing`.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.@@ -98,7 +156,7 @@ 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.+`make_problem()` builds every problem from its code: the title, the documentation page, the domain, the retry verdict, the steps, the sentences' templates, the parameters model and the HTTP status are the code's, read from the registries' generated tables (`error_code_spec()` in `pipelex/errors/error_codes.py`), so building a problem 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.@@ -112,7 +170,7 @@ Before every error carried a code, each class had a page at `errors/<kebab-class### `validation_errors` — structured bundle-validation diagnostics-A bundle-validation failure (`ValidateBundleError`) aggregates per-error data across stages and projects it onto `validation_errors` as a list of typed `ValidationErrorItem`s, so the structured error report an HTTP API surfaces carries machine-mappable diagnostics (not just a single `detail` string). Each item's `category` is one of the **closed** `ValidationErrorCategory` set:+A bundle-validation failure (`ValidateBundleError`) aggregates per-error data across stages and projects it onto a list of typed `ValidationErrorItem`s, which a validation verdict carries as `validation_errors` and the failure's problem as its `errors` items, so every surface carries machine-mappable diagnostics, not just a single `detail` string. Each item's `category` is one of the **closed** `ValidationErrorCategory` set:- `blueprint_validation` — interpreter / blueprint-validation faults. A blueprint-stage `PipeValidationError` raised *inside* a pydantic model validator (e.g. the PipeBatch `input_item_name` == `input_list_name` collision, or the SubPipe `batch_over` == `batch_as` collision — both `batch_item_name_collision`) is wrapped by pydantic as a `value_error`; the blueprint categorizer unwraps it (`ctx["error"]`) so the item keeps its structured `error_type` and `pipe_code` / `domain_code` locators. The item stays in `blueprint_validation` (not `pipe_validation`) because the fault genuinely surfaced at the parse boundary, before any pipe was instantiated — only the `error_type` is recovered, not the stage. This category also serves as the **last-resort residual**: a parse-level failure (an empty blueprint, a bundle-elaborator failure) is raised with only a message and no categorized data, so when *nothing else* produced an item the builder projects that message as one `blueprint_validation` item (no `error_type`, no `source` — the bundle could not become a blueprint at all). A TOML syntax error is its own item of this category, with no `error_type`, carrying the `source` and the 1-based `line` and `column` the parser stopped at.- `pipe_factory` — pipe-factory failures (e.g. a missing concept).@@ -121,25 +179,25 @@ A bundle-validation failure (`ValidateBundleError`) aggregates per-error data ac**Every error is an item, and none hides another.** Every pydantic error the parser meets becomes its own item: categorized when the blueprint categorizer knows it, and otherwise an uncategorized `blueprint_validation` item with no `error_type`, carrying its `source`, the `pipe_code` its location names and its `field_path`, the bundle-root path of the failing field with pydantic's own elements left out (`pipe.summarize.promtp`, not `pipe.summarize.PipeLLM.promtp`). A misspelled field beside an undeclared prompt variable therefore gives two items, where the typo used to vanish until the variable was fixed. The only error left out is the union-branch noise of a concept declared as `ConceptBlueprint | str`, whose table branch already reports the fault. The same holds inside every message `format_pydantic_validation_error` builds: the kinds it lists get their own heading, and every other kind is rendered under "Other validation errors", whatever else is present.-**A dry-run failure is one located item per failing pipe.** The dry-run sweep (`BundleValidator` in `pipelex/pipeline/bundle_validator.py`) runs each pipe through its own in-process router, which notes the first pipe each failure leaves: the innermost pipe that failed. A controller that failed because a pipe it runs failed is therefore reported at that pipe, and once, even when both were swept; validating the controller alone still reports the inner pipe. A pipe listed in `allowed_to_fail_pipes` is never where a failure is reported: a failure met there is reported at the innermost pipe around it that is not allowed to fail, the one whose failure is unexpected. When the bundle is validated from submitted content beside a host's library directories, as the hosted validator does, the item carries that pipe's `source` only when the pipe belongs to that content: a pipe loaded from the host's own library directories is named by its code and domain, never by its file on the host. A bundle validated from a file on the caller's own disk names every pipe's file, a sibling file of the same method included, and so does submitted content validated beside directories that are the caller's own (`library_dirs_are_callers`). The sweep raises one `DryRunError` whose `failures` hold one `DryRunFailureErrorData` per failing pipe, and the cascade turns each into its own `dry_run` item. The item's message names the pipe and carries the failure's own text only when the failure's root fault, the one a run failure reports (the innermost `PipelexError` on its cause chain, the walk stopping at the first exception that is not one, and of two errors of the same class the outer one, which restates the inner with a remedy), authored that text as caller-facing copy, and otherwise the fault's title, because the verdict is kept verbatim under STRICT disclosure and would otherwise carry a configuration or storage failure's internals to a hosted caller. A failure the runtime has not classified as the caller's therefore reads `Pipe '<code>' failed its dry run: <title>`, the fault's title in place of its message. The sweep reports every failing pipe this way, whatever raised the failure.+**A dry-run failure is one located item per failing pipe.** The dry-run sweep (`BundleValidator` in `pipelex/pipeline/bundle_validator.py`) runs each pipe through its own in-process router, which notes the first pipe each failure leaves: the innermost pipe that failed. A controller that failed because a pipe it runs failed is therefore reported at that pipe, and once, even when both were swept; validating the controller alone still reports the inner pipe. A pipe listed in `allowed_to_fail_pipes` is never where a failure is reported: a failure met there is reported at the innermost pipe around it that is not allowed to fail, the one whose failure is unexpected. When the bundle is validated from submitted content beside a host's library directories, as the hosted validator does, the item carries that pipe's `source` only when the pipe belongs to that content: a pipe loaded from the host's own library directories is named by its code and domain, never by its file on the host. A bundle validated from a file on the caller's own disk names every pipe's file, a sibling file of the same method included, and so does submitted content validated beside directories that are the caller's own (`library_dirs_are_callers`). The sweep raises one `DryRunError` whose `failures` hold one `DryRunFailureErrorData` per failing pipe, and the cascade turns each into its own `dry_run` item. Each failure carries the code of its root fault, the one a run failure reports (the first `PipelexError` down its cause chain that carries a code of its own, the walk stopping at the first exception that is not one, and of two errors of the same class the outer one, which restates the inner with a remedy), and its message names the pipe, then the sentence that code renders for a caller, never the fault's own message, because the caller reads the verdict: `Pipe '<code>' failed its dry run: <the code's detail>`. A failure with no Pipelex error on its chain is the dry run failing to mock a value, `method.mock_unsatisfiable`, and so is a pydantic `ValidationError` or a polyfactory `FactoryException` raised inside a routed pipe, which the router hands on as the `PipelexUnexpectedError` standing in for it, and which would otherwise read as a fault of ours with no verdict. The sweep reports every failing pipe this way, whatever raised the failure. The `DryRunError` it raises takes its code among its failures' (`first_fault_code()`), and its parameters and pipe from the failure that code is taken from, so its own sentence renders whole.The **structured-info invariant is total**: every invalid verdict carries a non-empty `validation_errors[]`, never a bare message. The builder emits the categorized items and the `dry_run` items, then the `blueprint_validation` fallback only when nothing else produced an item.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 (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.+**A verdict names no path on the host.** A caller reads the verdict, its items, their locators and its message, so none of them 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`). The withheld verdict is the same answer otherwise: it keeps the code its raise site chose, such as `request.invalid` for a request naming nothing to validate, and the parameters and items its raise site gave, withheld the same way. Every item of its problem is withheld whole, its sentence, each parameter and its locators, whichever channel each came from: an item no stage classified takes the parameters of the refusal the verdict was built from, its cause, whose `finding`, `file` or `path` the withholding never rewrote otherwise. 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 its code's 500, the host library's own text riding only the operator's diagnostics. 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 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.+**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 method's to fix, in the `method` domain, 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, and its message is the sentence the refusal's code renders for a caller (`refusal_detail()`), never the refusal's own message, which is the operator's. 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 another actor must fix, the caller's input, the account, the operator or the runtime, 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 method's. A dry run's failures and a pipe run failing outside the sweep become a verdict on the same rule: only when at least one failure is the method's. A dry run whose every failure belongs to another actor answers its own code, the first of its failures' codes by `first_fault_code()` (a verdict `no` before a retryable one, then the method's, the operator's, the account's, the input's and the runtime's, then the first given), with every failure riding its problem's `errors`, and never reads as an invalid method. 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 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. 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` 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.+**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`, so a hosted run route answers it with a 422 whose problem carries one `errors` item per validation item, 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`.)-**Host-wiring guards are programmer errors, not content verdicts.** `validate_bundle`'s "provide exactly one of `mthds_contents` / `mthds_file_path`" guard and `resolve_crate_from_contents`'s `mthds_sources`-length-mismatch guard raise `PipelexUnexpectedError` (→ 500, redacted under STRICT), not `ValidateBundleError` — a caller wiring bug must not be reported as if the submitted bundle were invalid. The empty-`mthds_contents` guard stays caller-facing (it can legitimately reflect an end user submitting no bundles).+**Host-wiring guards are programmer errors, not content verdicts.** `validate_bundle`'s "provide exactly one of `mthds_contents` / `mthds_file_path`" guard and `resolve_crate_from_contents`'s `mthds_sources`-length-mismatch guard raise `PipelexUnexpectedError` (`runtime.unexpected`, 500), not `ValidateBundleError` — a caller wiring bug must not be reported as if the submitted bundle were invalid. The empty-`mthds_contents` guard stays the caller's, `request.invalid` (it can legitimately reflect an end user submitting no bundles).-`ValidationErrorItem` and the builder are the single source of truth across surfaces: `build_validation_error_items()` (`pipelex/pipeline/validation_errors.py`) is reached through `ValidateBundleError.validation_error_items()`, which `ValidateBundleError.to_error_report()` (the API path), the agent CLI's `extract_validation_errors()` (the CLI JSON envelope) and `pipelex fix` all call, so the structured shapes cannot drift. `pipelex-agent validate pipe` and `validate --all` dry-run through the same cascade, so a failing dry run there is the same invalid verdict with the same items as on `validate bundle`. The item lives in `pipelex/base_exceptions.py` alongside `ErrorReport` — not next to the source error-data models — because `ErrorReport` references it as a typed field and the root exceptions module must not import the `pipelex.core` error modules.+`ValidationErrorItem` and the builder are the single source of truth across surfaces: `build_validation_error_items()` (`pipelex/pipeline/validation_errors.py`) is reached through `ValidateBundleError.validation_error_items()`, which `ValidateBundleError.problem_items()` (every problem of an invalid bundle), the validators' invalid arm, the agent CLI's `extract_validation_errors()` (the CLI JSON envelope) and `pipelex fix` all call, so the structured shapes cannot drift. `pipelex-agent validate pipe` and `validate --all` dry-run through the same cascade, so a failing dry run there is the same invalid verdict with the same items as on `validate bundle`. The item lives in `pipelex/base_exceptions.py`, not next to the source error-data models, because the root exceptions module must not import the `pipelex.core` error modules, which import back into it.#### The `error_type` registry — the closed vocabulary of faults@@ -151,17 +209,17 @@ Two spellings live in that one vocabulary, deliberately. The stage enums are snaMembership means a value is *reachable on the wire*, not that it is a useful thing to exercise. Several members are advisory-only — `optional_force_redundant`, `input_presence_vacuous`, the three `hint_*` lints and `template_check_warning` — riding `warnings` and never an invalid verdict, and the two `unknown_*` fallbacks fire on states no author can ask for. A consumer building coverage over the registry excludes those on its own side with a stated reason, rather than pruning them from the runtime truth here — which is what the [MTHDS Test Corpus](../contribute/mthds-test-corpus.md) vocabulary generator already does, excluding each with its reason as it generates the `error.*` namespace from this registry.-`validation_errors` is one of the fields kept under STRICT disclosure (it is in `_STRICT_KEPT_FIELDS`): the items describe the caller's *own* submitted bundle, not server internals, so redacting them would gut the hosted path's diagnostics.+On a problem, each validation item becomes one `errors` item (`problem_item_of()` in `pipelex/pipeline/validation_errors.py`). Its `code` is the code the item's `error_type` maps to (`validation_item_code()`), a dry-run item's is its failure's, and an item no stage classified takes the code of the refusal the verdict was built from when that refusal is the method's, else `method.schema_violation`. Its `detail` is that code's sentence, rendered from the parameters the item's locators give; its `location` holds the item's pipe, field, file, line and column; and its `suggestions` and `suggested_fix` are the item's.```python-report = exc.to_error_report()-report.to_dict() # {"error_type": "LLMCompletionError", "message": "...", ...}-ErrorReport.from_dict(d) # strict inverse — raises ValidationError on a malformed dict-report.http_status # 422 / 429 / 500 — for HTTP adapters+problem = exc.to_problem(view=ProblemView.CALLER)+problem.code # "method.invalid"+[item.code for item in problem.errors or []] # one code per validation item+exc.validation_error_items() # the typed items a verdict carries as validation_errors```-!!! warning "`ErrorReport` is `extra="forbid"`"- `from_dict()` rejects unknown keys, so it is the strict inverse of `to_dict()`. A report dict that crosses a serialization boundary and fails validation on the way back is an internal contract bug — the writer and the reader share the schema within one deploy. A cross-boundary recovery helper that rebuilds a report (e.g. a distributed-worker bridge) is expected to catch that `ValidationError` and synthesize a fallback report so failure-webhook delivery stays intact while keeping the contract bug visible; any other caller of `from_dict()` should treat the validation failure as a bug to fix.+!!! info "Two shapes of the same items"+ A validation verdict — the `200` `is_valid: false` answer of the API's diagnostic routes, the CLIs' validation output and a validator's invalid arm — carries the `ValidationErrorItem`s whole, as `validation_errors`. A problem — the `422` answer of a run refused before any pipe ran — carries them as `errors` items, each with its code. Both are built from the same items, so they name the same faults at the same places.### `suggested_fix` — structured deterministic fixes@@ -207,44 +265,33 @@ The category and the code are checked against each other. A classification whose### ErrorDomain-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:+Defined in `pipelex/base_exceptions.py`. A problem carries its code's own domain, one of the five the MTHDS core declares; `ErrorDomain` is a three-valued reading of it, derived through `ErrorDomain.from_problem_domain()`, which the CLIs' error envelopes, the usage statistics and the API's log records still carry as `error_domain`:-| 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 |+| Code's domain | `error_domain` | Who acts |+|---------------|----------------|----------|+| `input` | `INPUT` | The caller, by changing the request or its inputs |+| `method` | `INPUT` | The method's author, by changing the method |+| `account` | `CONFIG` | The account's owner |+| `operator` | `CONFIG` | Whoever runs the runtime |+| `runtime` | `RUNTIME` | Nobody beforehand: wait, retry or report |-`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.--No class declares a domain: a class whose raise sites need two readings declares two codes, and the raise site chooses.+It decides nothing. The HTTP status is the code's own, declared in its registry entry (`error_code_spec(code).status`), so two codes of one domain can answer different statuses: a provider's rate limit answers 429 and its unavailability 502, both in the `runtime` domain. 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-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.+The code says who must act and what the reader is told, so the raise site that knows which code applies, and holds the facts its sentences need, says so where it raises. A class whose raise sites need different readings declares a set, and each site chooses its code with `with_error_code()` and gives the parameters only it knows with `with_params()`:```pythonraise (- PipeRunInputsError(message=msg, run_mode=run_mode, pipe_code=pipe_code)+ PipeRunInputsError(message=msg, run_mode=run_mode, pipe_code=pipe_code, missing_inputs=missing_names).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."),- )+ .with_params(input=missing_inputs_str))```-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 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 |+A pipe checking that its required inputs are present tells the two cases apart by its stack: at the entry pipe, a missing input is one the request left out, `input.missing` with its `input` parameter; below it, it is one an earlier step of the method did not produce, `pipe.input_unresolved` with its `variable` parameter. The message, which also lists the inputs that may be omitted, is the operator's diagnostics; the caller reads `The request does not give the input 'name', which the method requires.` and the step `Add the input 'name' to the request, then send it again.`-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.+Because no caller reads a message, no raise site has to vouch for one: a model output that does not fit its structure, a `PipeFunc` crash, an input resource named by its path on the host and a template that fails to render all keep their whole text for the operator, while their caller reads the code's sentences. A raise site's only duty toward the caller is its parameters, which the caller view shows: it gives only the caller's own names and values (pipe codes, concept codes, variable names, the model as the method wrote it), and a fact only an operator may read is a parameter the registry marks `operator_only`.---@@ -285,8 +332,9 @@ Every raised inference error carries structured SDK metadata and typed advice.```pythonclass ProviderErrorMetadata(BaseModel):- provider: str+ provider: ProviderNamesdk_exception_type: str+ message: str = ""status_code: int | None = Nonerequest_id: str | None = Noneretry_after_seconds: float | None = None@@ -295,11 +343,11 @@ class ProviderErrorMetadata(BaseModel):```!!! warning "`body` is excluded from serialization"- The raw provider response `body` can carry account ids, billing details, or credential fragments. It is held in-process but `exclude`d from every serialized form — CLI JSON, agent output, and any serialized worker payload.+ The raw provider response `body` can carry account ids, billing details, or credential fragments. It is held in-process but `exclude`d from every serialized form — CLI JSON, agent output, and any serialized worker payload. The provider's `message`, the SDK exception's text, reaches only the operator's diagnostics, capped like every text a problem carries.-`UserAction` pairs a discrete `UserActionKind` (`WAIT_AND_RETRY`, `CHECK_BILLING`, `CHECK_CREDENTIALS`, `CHANGE_INPUT`, `CHANGE_MODEL`, `CONTACT_SUPPORT`, `UNKNOWN`) with a free-form `detail` string — so the CLI can render consistent guidance while keeping provider-specific text.+`UserAction` pairs a discrete `UserActionKind` (`WAIT_AND_RETRY`, `CHECK_BILLING`, `CHECK_CREDENTIALS`, `CHANGE_INPUT`, `CHANGE_MODEL`, `CONTACT_SUPPORT`, `UNKNOWN`) with a free-form `detail` string — so the local CLIs can print consistent guidance while keeping provider-specific text. It is advice for a local reader and never rides a problem, whose next step is the code's.-The `detail` is read on a failed run's report, once every automatic retry is spent, so it says what the reader can do next and never promises another attempt by the system: the `WAIT_AND_RETRY` advice says to wait, at least the provider's `Retry-After` delay when it gave one, then run it again.+The `detail` is read once a run has failed and every automatic retry is spent, so it says what the reader can do next and never promises another attempt by the system: the `WAIT_AND_RETRY` advice says to wait, at least the provider's `Retry-After` delay when it gave one, then run it again.### Service Error Codes@@ -315,17 +363,17 @@ 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.** 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.+- **It answers 501 on an HTTP surface.** It carries `model.unavailable`, a code in the operator's domain whose registry status is 501: it lands in server-error alerting, its verdict tells a client not to retry, since an outer retry earns an identical refusal, and its caller view's step tells the caller to choose another model while the operator's tells the operator to fix the configuration.### 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` with `model.output_schema_mismatch`, 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`, a `runtime` code whose verdict invites a retry and which answers its registry status, 502. A recovered exception the classifier does not recognize lands in `UNKNOWN`.One exception escapes the loop unwrapped. `instructor` reads the stop value of every structured answer it parses, and raises its `IncompleteOutputException` for one cut at the request's output limit: an OpenAI-shaped completion, Mistral's included, whose first choice finished on `length`, or an Anthropic message that stopped on `max_tokens`. It never re-asks such an answer, and it raises the exception as it is, carrying the cut answer as its `last_completion`, never inside an `InstructorRetryException`. The workers whose structuring mode can raise it, the Anthropic, OpenAI Chat Completions and Mistral workers, catch it and raise `LLMCompletionTruncatedError` from it through `LLMWorkerAbstract._incomplete_output_error`, which reads the answer's stop value and output tokens with `read_incomplete_output` (in `pipelex/cogt/llm/completion_stop.py`). A structured output cut at its limit therefore reads `model.output_truncated`, as a text cut at the same limit does, and names the same stop value, output tokens and `max_tokens`, the error's `output_kind` saying a structured output was cut rather than a text. When the Anthropic worker's structured-output timeout lowered the limit, the worker passes a `MaxTokensCeiling` naming the limit it was given and the timeout, and the error says the limit was lowered and to what, then gives as its next step, in its message and its `user_action`, a lower reasoning effort or a smaller output, since a higher `max_tokens` would be lowered the same way. The Gemini and Responses API structuring modes never raise it.### Model and Provider Attribution-Inference-failure leaf errors (`LLMCompletionError`, `ImgGenGenerationError`, …) are raised deep inside a plugin and do not know which model handle invoked them. Each worker family fills that in at its public-method chokepoint:+Inference-failure leaf errors (`LLMCompletionError`, `ImgGenGenerationError`, …) are raised deep inside a plugin and do not know which model handle invoked them. Each worker family fills that in at its public-method chokepoint, and the problem then gives the model and the backend as facts, in the operator's diagnostics and as the `model` and `provider` parameters of a code that declares them:```pythondef fill_model_and_provider(self, model_handle: str | None, *, backend_name: str | None) -> None:@@ -334,69 +382,62 @@ def fill_model_and_provider(self, model_handle: str | None, *, backend_name: str----## Cause-Chain Enrichment+## Cause-Chain Facts-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.+A wrapper exception — `PipeRunError` → `PipeRouterError` → `PipelineExecutionError` — carries no classification of its own, so the problem of an error is built from its whole cause chain, and the inference classification survives every wrapping layer:-```python-def _enrich_error_report_from_cause(self, report: ErrorReport) -> ErrorReport:- cause = self.__cause__- if not isinstance(cause, PipelexError):- return report- cause_report = cause.to_error_report()- 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 ...- }- )-```+| What | Taken from |+|------|------------|+| The code, and everything it decides | `resolve_error_code()`, which walked the `__cause__` chain (see [Every error declares its code](#every-error-declares-its-code)) |+| The parameters | The error whose code it is, `code_carrier()`: its `problem_params()` and the parameters its raise site gave; then, for a parameter it gives none of, the one the nearest wrapper between the error and it gave with `with_params()`, checked against its code like any other, so a parameter the code does not declare is dropped and logged |+| The location | Each error's `problem_location()` from the error down to the one whose code it is, merged member by member with the deeper error's winning, so a wrapper that takes its cause's code and knows the pipe, the field or the file its cause was met at locates a cause that does not; a code declaring a `pipe` parameter is given the location's pipe when its raise site gave none |+| The items | The first error at or below the one whose code it is whose `problem_items()` gives any, an error that refuses several faults at once, such as one whose raise site gave them with `with_items()`; then those each wrapper between the error and it refuses, the nearest the code's carrier first |+| The facts: `model`, `provider`, `migration` and `retry_after` | For each, the one nearest the error along the chain, from each error's `problem_facts()`, so a wrapper that knows a fact overrides its cause and one that does not inherits it; the provider's answer is merged member by member, so a wrapper naming the backend keeps the status and the request id its cause recorded |+| `diagnostics.error_class`, `message` and `causes` | The error itself, then each error along its chain with the code it carries by itself |-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).+A subclass contributes what it knows through those hooks, `problem_params()`, `problem_location()`, `problem_items()` and `problem_facts()`, and never overrides `to_problem()`, so the walk, the validation of the parameters and the views stay in one place. `CogtError` gives its model, its provider's answer and the delay the provider asked for as facts; `ValidateBundleError` gives one item per validation item. The only overrides of `to_problem()` are the two located wrappers of a run failure, which report their root fault instead of themselves (see [Run Failures: the Root Fault, Located](#run-failures-the-root-fault-located)). A host plugin's carrier of a problem recovered across a transport boundary does not override it: it overrides `recovered_problem()`, which returns that problem, in the operator's view, and is `None` on every other error, and the base `to_problem()` then reports it as it is (`recovered_problem_in_view()`), the location it is handed merged over its own, the request and the run filling the members it lacks, projected to the caller's view for a caller. Such a carrier reports a code its class does not resolve to, so a surface that reports a failure reads its code, its domain and its retry verdict off the problem it reports, as the agent CLI's error envelope and the usage statistics' error domain do, never off `resolve_error_code()` beside it. Every walk is the one cycle-guarded `iter_cause_chain()`, so a malformed chain can never turn error reporting into a hang or a `RecursionError`, and each walk that builds the problem stops at the first exception that is not a `PipelexError` (`iter_pipelex_cause_chain()`): a foreign exception raised from an earlier failure is a new failure, and nothing below it, neither a code, a fact, a location, an item nor a piece of advice, belongs to the error above it.-!!! 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`.+The advice an error carries, its `user_action`, is not a fact of its problem: the problem's step is the code's. `advised_action()` finds the advice nearest the error along its chain, and only the local CLIs print it, as a tip.---## 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`, 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.+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 problem built from `PipelineExecutionError` with a bridge's sentence for a message would tell the reader nothing. So the two located wrappers, `PipeRouterError` and `PipelineExecutionError`, which take their cause's code, answer the problem of 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 carries 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; when none carries one, the deepest error implying a code, else the innermost `PipelexError`. 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.+**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'`), which only an operator reads, 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 problem, the far side packs the root fault's own problem, never a located one: when it packs that problem 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 problem with `make_located()`, which the router raises untouched, so the problem 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.-**The report.** Both wrappers build the same report from the same root fault (`find_root_fault()`):+**The problem.** Both wrappers answer the same problem, the root fault's own (`located_root_fault()`), built as the wrapper reports it (`located_problem()`, over `PipelexError.problem_reported_by()`) with the location they hold:-| Field | Taken from |-|-------|------------|-| `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`, `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 |+| Member | Taken from |+|--------|------------|+| `code`, and what it decides: `type`, `title`, `domain`, `retry`, `next_step` and the HTTP status | The root fault |+| `detail` and `params` | The root fault's code and parameters, then those the wrappers above it gave for a parameter it gives none of, a code declaring a `pipe` parameter being given the failing pipe when no raise site gave one |+| `location` | The location the errors from the wrapper down to the root fault know, the root fault's winning, with `pipe`, the failing pipe, and `path`, the pipe codes from the entry pipe down to it (`failure_location_of()`) |+| `errors` | The first error along the root fault's chain that refuses several faults, then those each wrapper above it refuses |+| `diagnostics` | The root fault's class, message and causes, and the facts nearest the wrapper on its chain, so a model or a backend a worker attributed the failure to on a wrapper above the root fault is kept |-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`.+So a run failing at a nested pipe reads, in the caller view, `"location": {"pipe": "summarize", "path": ["two_steps", "summarize"]}` beside the code's own sentence about it, and the location is never parsed out of a sentence. The wrappers' own messages, which an operator meets in a traceback and the CLIs print, still read `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; `PipeRouterError` and `PipelineExecutionError` also carry the location structurally, as `pipe_code` and `pipe_stack`.-**A recovered report is taken as it is.** A distributed submitter receives a report that was already located on the worker. When it raises that report inside a `PipelexError` whose `to_error_report()` returns it, and no `PipeRouterError` sits on the submitter's own chain, the runner's `PipelineExecutionError` reports it verbatim: its `pipe_code` is the entry pipe, its `pipe_stack` is empty, and the message is not located a second time. A located report must never reach a router this way, since the router would locate it again: that is why a host router's transport packs the root fault's own report. A bridge's own sentence (`Pipe execution failed in DIRECT mode …`) appears in neither the report nor the message, so a run gives the same report whether it ran in process, through the in-process orchestrator or on a remote worker.+**A recovered problem is taken as it is.** A distributed submitter receives a problem that was already located on the worker. When it raises that problem inside a `PipelexError` whose `recovered_problem()` returns it, which its `to_problem()` then reports in the view asked for with the location it is handed, and no `PipeRouterError` sits on the submitter's own chain, the runner's `PipelineExecutionError` reports it unchanged: its `pipe_code` is the entry pipe, its `pipe_stack` is empty, and it adds no location of its own. A located problem must never reach a router this way, since the router would locate it again: that is why a host router's transport packs the root fault's own problem. Only that hook makes a root fault report its own problem as it is: an inner `PipeRouterError` standing for a foreign exception, under a wrapper that attributed the failure to a model, is reported as the runner's wrapper reports it, so the model and the backend reach the problem. A bridge's own sentence (`Pipe execution failed in DIRECT mode …`) appears nowhere in the problem, so a run gives the same problem whether it ran in process, through the in-process orchestrator or on a remote worker.-**Where the remedy goes.** A root fault's message states the fact and nothing else, because it reaches every surface, a hosted run's stored error included. Advice that only a local reader can act on belongs to the local CLI: `pipelex run` renders the model panel of a `PipeOperatorModelAvailabilityError` found anywhere on the chain, and the panel's tip is where the local model deck remedy lives.+**Where the remedy goes.** A problem's next step is its code's, the same on every surface, a hosted run's stored error included. Advice that only a local reader can act on belongs to the local CLI: `pipelex run` renders the model panel of a `PipeOperatorModelAvailabilityError` found anywhere on the chain, and the panel's tip is where the local model deck remedy lives.---## Crossing a Distributed Worker Boundary-The error model is built to survive serialization. Because `ErrorReport` round-trips through `to_dict()` / `from_dict()`, a failure that happens on a remote worker can reach the submitting process with its full classification intact — not just a message string.+The error model is built to survive serialization. A problem is a model with a published schema, so a failure that happens on a remote worker reaches the submitting process with its code, its parameters, its location and its diagnostics intact — not just a message string.The 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 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.+**Packing.** Convert a `PipelexError` into the transport's failure type and stash the root fault's problem, in the operator's view, in its details payload (`to_problem(view=ProblemView.OPERATOR).to_wire()`), 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.+**Recovering.** On the submitter side, walk the returned failure, pull the packed problem and validate it back into a `PipelexProblem`, carried by a `PipelexError` whose `recovered_problem()` returns it, which its `to_problem()` then reports in the view asked for. Recovery is **total**: when no problem is found — a non-Pipelex exception, a worker crash, a timeout — the plugin answers `runtime.unexpected`, so the recovery path always has a structured problem 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* `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.+**Net effect:** a pipe failing on a remote worker reaches the CLI and HTTP adapters with the *same* problem as the identical failure run locally — and a failure that escapes conversion fails loud and bounded instead of hanging. `pipelex.test_extras.problem_parity`, shipped in the package, holds the injected failures and their expected code, domain, verdict and operator step kind (`ProblemParityTestData`, `SearchProblemParityTestData` and `JudgeProblemParityTestData`), so this repository's local arm and a distributed plugin's arm check the same classification against the same data.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.@@ -432,18 +473,19 @@ Implementation: the agent CLI threads `exit_code` through `agent_error(...)` (`a### API-`pipelex` is a library — there is no API server in the package. Downstream HTTP repos consume the `ErrorReport`:+The `pipelex` library serves no HTTP itself; the API server, the repository's `api/` member, answers every failure with its problem (see the API server's [Error Responses](../api-server/error-responses.md)). Everything an HTTP adapter needs is the library's:-- `error_domain_to_http_status(error_domain)` — pure domain → status table.-- `ErrorReport.http_status` — full property, layering the provider-429 passthrough on top.+- `PipelexError.to_problem(view=ProblemView.OPERATOR, request_id=...)` builds the problem, which the adapter logs, then projects with `caller_view_of()` when the request's identity is not the operator's.+- The HTTP status is the code's, `error_code_spec(code).status`, with 500 for a code the registries give none.+- A `Retry-After` header rides only a 429, from the problem's `retry_after`, which only a code inviting a retry carries.-A downstream FastAPI exception handler calls `ErrorReport.http_status` and is a trivial adapter — it must not redefine the mapping.+An adapter is therefore a trivial renderer: it must not redefine a status, a domain or a sentence.### Inputs and Outputs-**Inputs.** `to_error_report()` takes a live `PipelexError`. `ErrorReport.from_dict()` takes a `to_dict()` payload — strictly, raising `ValidationError` on drift. (A distributed-worker bridge adds a cross-boundary recovery helper that walks a returned failure's `__cause__` chain and rebuilds the report; it lives in the host-runtime plugin, not core.)+**Inputs.** `to_problem()` takes a live `PipelexError` and the view of its reader. `PipelexProblem.model_validate()` takes a problem's wire form, which a distributed worker's bridge or a stored run hands back. (The cross-boundary recovery helper that walks a returned failure and rebuilds the problem lives in the host-runtime plugin, not core.)-**Outputs.** `to_error_report()` returns an `ErrorReport`; `to_dict()` returns a `None`-free `dict`. Side effects: telemetry events emitted on pipeline failure at Layer 3; the agent CLI writes to stderr and raises `typer.Exit(...)` — code 1 by default, or the validate surface's 0/1/2 policy (see [Validate exit-code policy](#validate-exit-code-policy-0-1-2)).+**Outputs.** `to_problem()` returns a `PipelexProblem`; `to_wire()` returns its JSON form with no declared member written as `null`. Side effects: a warning logged for a parameter the code does not declare or a sentence that could not be rendered; telemetry events emitted on pipeline failure at Layer 3, which carry the problem's metadata view; the agent CLI writes to stderr and raises `typer.Exit(...)` — code 1 by default, or the validate surface's 0/1/2 policy (see [Validate exit-code policy](#validate-exit-code-policy-0-1-2)).---@@ -454,25 +496,26 @@ flowchart TBSDK["Layer 0 — SDK exception<br/>(openai.RateLimitError)"]W["Layer 1 — Worker classifies<br/>is_quota_exhaustion_*() → CogtError<br/>+ InferenceErrorCategory + ProviderErrorMetadata"]WRAP["Layers 2-3 — Wrappers<br/>PipeRouterError → PipelineExecutionError<br/>(locate the root fault)"]- REPORT["ErrorReport<br/>via to_error_report() + cause-chain enrichment"]+ PROBLEM["PipelexProblem<br/>via to_problem(view=...) over the cause chain"]SDK -->|"raise ... from exc"| WW -->|"raise ... from exc"| WRAP- WRAP --> REPORT+ WRAP --> PROBLEM- REPORT --> RICH["Human CLI<br/>Rich panel"]- REPORT --> AGENT["Agent CLI<br/>JSON / Markdown"]- REPORT --> HTTP["HTTP adapters<br/>.http_status"]+ PROBLEM --> RICH["Human CLI<br/>Rich panel (operator view)"]+ PROBLEM --> AGENT["Agent CLI<br/>JSON / Markdown (operator view)"]+ PROBLEM --> HTTP["HTTP adapters<br/>view by identity, the code's status"]+ PROBLEM --> GRAPH["Execution graph<br/>failed node (caller view)"]- W -.->|"pack on worker"| TEMP["Distributed worker bridge (plugin)<br/>report packed into transport details"]- TEMP -.->|"recover on submitter"| REPORT+ W -.->|"pack on worker"| TEMP["Distributed worker bridge (plugin)<br/>operator-view problem packed into transport details"]+ TEMP -.->|"recover on submitter"| PROBLEMclassDef src fill:#fff3e0,stroke:#e65100,color:#000classDef cls fill:#e8eaf6,stroke:#3949ab,color:#000classDef out fill:#e8f5e9,stroke:#2e7d32,color:#000class SDK src- class W,WRAP,REPORT,TEMP cls- class RICH,AGENT,HTTP out+ class W,WRAP,PROBLEM,TEMP cls+ class RICH,AGENT,HTTP,GRAPH out```---@@ -481,23 +524,23 @@ flowchart TB### Class Hierarchy-`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.+`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, which overrides `problem_facts()` to give the model, the backend, the provider's answer and the delay the provider asked for, and `implied_error_code` to name its category's code for an error built with a category alone.```Exception-└── PipelexError base_exceptions.py — error_code, with_error_code(), resolve_error_code(), to_error_report()+└── PipelexError base_exceptions.py — error_code, with_error_code(), with_params(), resolve_error_code(), to_problem()├── PipelexUnexpectedError → runtime.unexpected- ├── PipelexConfigError → one of pipelex.config.invalid, .syntax, .file_missing+ ├── PipelexConfigError → one of pipelex.config.invalid, .syntax, .file_missing; gives its migration as a fact├── 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+ ├── CogtError cogt/exceptions.py — abstract; error_category, provider_metadata, problem_facts()│ ├── 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 and its code+ ├── PipelineExecutionError pipeline/exceptions.py — answers its located root fault's problem└── ... (one exceptions.py per package) ...```@@ -508,8 +551,8 @@ Exception| When | What carries metadata | How ||------|----------------------|-----|| **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()` |+| **Raise time** | The code chosen from the class's set, the parameters only the raise site knows, per-instance `error_category`, `user_action`, `provider_metadata` | `with_error_code()`, `with_params()` and constructor args — set by the raise site or the worker that classified the failure |+| **Problem time** | The resolved code and everything it decides; the parameters, location, items and facts along the chain; the view | `resolve_error_code()`, `code_carrier()` and the problem hooks; `fill_model_and_provider()` at the worker chokepoint; `make_problem()` |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.@@ -520,28 +563,33 @@ The "outcome" exceptions (`LLMCompletionError`, `ImgGenGenerationError`, `Extrac### Quick-Ref```python-# Produce a report from any PipelexError-report = exc.to_error_report() # enriched from the __cause__ chain-payload = report.to_dict() # None-free dict for serialization+# Build the problem of any PipelexError, in its reader's view+problem = exc.to_problem(view=ProblemView.CALLER) # code, sentences, step, params, location+operator_problem = exc.to_problem(view=ProblemView.OPERATOR, request_id=request_id) # adds the diagnostics+payload = problem.to_wire() # JSON types, no declared member written as null-# Declare a class's code, and choose one of its set where it is raised+# Declare a class's code; choose one of its set and give its parameters where it is raisedclass 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+raise SomeError(msg).with_error_code(CoreCode.INPUT_MISSING).with_params(input="topic")++# Consume a problem+problem.code # "input.missing" — the code decides everything below+problem.next_step.kind # "change_input"+problem.location # the failing pipe and its path, on a run failure+error_code_spec(exc.resolve_error_code()).status # 422 — the HTTP status-# Consume a report-report.code # "input.missing" — the code decides everything below-report.http_status # 422 / 429 / 500-report.user_action_detail() # free-form advice text, or None-report.error_category # "transient" / "capacity" / ...+# Project a problem built in the operator's view+caller_view_of(problem=operator_problem) # what a caller reads+problem_metadata(problem=operator_problem) # codes, verdicts and shapes, with no sentence or name# Round-trip across a boundary-ErrorReport.from_dict(payload) # strict inverse of to_dict()+PipelexProblem.model_validate(payload)-# Retry decision+# Retry decision within a runInferenceErrorCategory.TRANSIENT.is_retryable # True — only TRANSIENT```@@ -549,14 +597,18 @@ InferenceErrorCategory.TRANSIENT.is_retryable # True — only TRANSIENT| File | Purpose ||------|---------|-| `pipelex/base_exceptions.py` | `PipelexError`, `ErrorReport`, `ErrorDomain`, `ValidationErrorItem`, `error_domain_to_http_status()` |+| `pipelex/base_exceptions.py` | `PipelexError` and its problem hooks, `ErrorDomain`, `ValidationErrorItem` |+| `pipelex/errors/problem.py` | `PipelexProblem`, `ProblemView`, `ProblemDiagnostics`, `make_problem()`, `make_problem_item()`, `caller_view_of()`, `recovered_problem_in_view()`, `problem_metadata()`, `cap_problem_text()` || `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/error_codes.py` | `ErrorCode`, `error_code_spec()`: what the registries declare about each code, as generated tables, and `first_fault_code()` |+| `pipelex/errors/bundle_validation_failure.py` | `BundleValidationFailure`, a bundle validator's invalid arm: the refusal's problem and its validation items || `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 |+| `pipelex/pipe_run/located_failure.py` | `find_root_fault()`, `located_root_fault()`, `failure_location_of()`, `make_unexpected_failure()` |+| `pipelex/graph/node_problem.py` | `make_node_problem()`: the caller-view problem a failed node of the execution graph records |+| `pipelex/pipeline/validation_errors.py` | `build_validation_error_items()` — shared CLI/API structured bundle-validation builder — and `problem_item_of()` || `pipelex/validation_error_types.py` | The closed `error_type` registry — `VALIDATION_ERROR_TYPES`, `PipeValidationErrorType`, `PipeFactoryErrorType`, `ValidationResidualErrorType`, `HintLintErrorType` || `pipelex/cogt/exceptions.py` | `CogtError`, `InferenceErrorCategory` || `pipelex/cogt/inference/error_classification.py` | Extract — `ProviderErrorMetadata`, `SDKErrorEnvelope`, `UserAction`, `UserActionKind`, per-provider `extract_*_metadata` functions, pure discriminators |@@ -564,7 +616,8 @@ InferenceErrorCategory.TRANSIENT.is_retryable # True — only TRANSIENT| `pipelex/cogt/inference/error_render.py` | Render — `render_inference_error()`, `InferenceErrorFamily` || `pipelex/cogt/inference/provider_name.py` | `ProviderName` enum keying the extract-fn registry || `pipelex/providers/*/` | Per-provider inference workers — Layer 0 → 1 classification |-| `pipelex/pipeline/exceptions.py` | `PipelineExecutionError`, `PipeExecutionError` |+| `pipelex/pipeline/exceptions.py` | `PipelineExecutionError`, `PipeExecutionError`, `ValidateBundleError` |+| `pipelex/test_extras/problem_parity.py` | The failures and expected classifications the local and distributed parity tests share || `pipelex/cli/error_handlers.py` | Human CLI Rich panels — `display_error_panel()` || `pipelex/cli/agent_cli/commands/agent_output.py` | Agent CLI JSON / markdown delivery |@@ -572,38 +625,38 @@ InferenceErrorCategory.TRANSIENT.is_retryable # True — only TRANSIENT| Scenario | Behavior ||----------|----------|-| 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 |+| Rate limit hit | `TRANSIENT` → repeated within the run; `provider.rate_limited`, whose verdict invites a retry and which answers 429, with a `Retry-After` header when the provider gave a delay; transport retry honors `Retry-After` |+| Quota / billing exhausted | `CAPACITY` → not repeated; `UserAction(CHECK_BILLING)`; `provider.quota_exhausted`, the operator's → HTTP 502 |+| Bad API key | `CONFIGURATION` → not repeated; `provider.credential_refused`, the operator's → HTTP 502 || 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 |+| 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**, whose sentence names the reference and whose `suggestions` parameter carries the deck's close matches, 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 in its message for the operator, never the caller's `model.unknown`: `model.unavailable` → HTTP 501, with the reason `not_served`, for a bare handle no backend serves as the type the step needs, whose caller step offers another model, and `pipelex.config.invalid` → HTTP 500 for a preset, an alias or a waterfall the deck does not define; 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`, …) || A provider **HTTP 400**, or another 4xx such as the 422 or 413 a gateway may answer, saying the inputs are over what the model can read (OpenAI's `context_length_exceeded` code, which Azure OpenAI and OpenAI-compatible gateways relay, or a provider's own wording, read in the rendered message and in the body, where a raw `httpx` error such as Azure REST's keeps it: OpenAI's "maximum context length" and "exceeds the context window", Anthropic's "prompt is too long" and "exceed context limit", Bedrock's "Input is too long for requested model", Gemini's "exceeds the maximum number of tokens allowed") | `ProviderErrorMetadata.is_context_window_exceeded` → `CONTENT` / `CHANGE_INPUT`, not repeated; `model.context_exceeded`, the caller's → **HTTP 422**. The 400 arm and the other-4xx arm read it, ahead of the content-policy signal, for every family, and a 413 that carries no such signal keeps its payload-size reading, `input.too_large`. A language model's window holds the prompt and the output the request reserves with `max_tokens` together, and Anthropic's "exceed context limit" and OpenAI's "maximum context length" also refuse a request whose `max_tokens`, which may be the deck's default, pushes it over, so the language-model next step names both: shorten the input or lower `max_tokens`, or choose a model with a larger context window. The other families' next steps fit what their model reads: the prompt and its input images for an image model, the document for an extraction model, the inputs for a search or judgment model. Each phrase names the window or the inputs' length, so a 400 about a malformed request matches none of them || 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 context-window or a content-policy signal makes it the caller's, `model.context_exceeded` or `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 structured output cut at its output limit (`instructor`'s `IncompleteOutputException`, for an OpenAI or Mistral first choice finished on `length` or an Anthropic message stopped on `max_tokens`) | The Anthropic, OpenAI Chat Completions and Mistral workers raise `LLMCompletionTruncatedError` from it, at the output limit: `model.output_truncated` → **HTTP 422**, caller-facing under STRICT, with the same stop value, output tokens and `max_tokens` a cut text names (see [The `instructor` Unwrap](#the-instructor-unwrap)) |-| A Gemini image generation refused or stopped by a safety filter: a candidate whose `finish_reason` names a filter (`IMAGE_SAFETY`, `IMAGE_PROHIBITED_CONTENT`, `SAFETY` and their kin), or no candidate and a `prompt_feedback.block_reason` | The Google image worker reads the reason before it looks for an image, through `GoogleFactory.read_stop_signal`, which the Google text worker shares: the finish reason from Gemini's vocabulary with `classify_image_finish_reason`, and any block reason as a refusal. It raises `ImgGenGenerationError` → `CONTENT` / `CHANGE_INPUT`, not repeated; `model.content_refused` → **HTTP 422**, caller-facing under STRICT, naming the model's handle, the reason and what it says, so a recitation (`RECITATION`, `IMAGE_RECITATION`) or an unsupported language (`LANGUAGE`) is never called a safety filter's block. A candidate that holds no image for another reason (`NO_IMAGE`, `IMAGE_OTHER`) is still an unusable answer, `provider.response_invalid`, and a finish reason Gemini adds later is logged at warning level as an image generation's and taken as normal |-| A Gemini image generation its output token limit cut before the image: a candidate whose `finish_reason` is `MAX_TOKENS` and that holds no image | The Google image worker reads it with the refusals, before it looks for an image, and raises `ImgGenOutputTruncatedError`, a subclass of `ImgGenGenerationError` → `CONTENT` / `CHANGE_INPUT`, not repeated; `model.output_truncated` → **HTTP 422**, caller-facing under STRICT, naming the model's handle and the finish reason. The worker sends no output limit of its own, so the next step is a simpler prompt or another image model. An image the model finished before the limit is whole, and returned |+| 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`, the method's, at the output limit, which the method's `max_tokens` sets, and `model.context_exceeded`, the input's, at the context window, both → **HTTP 422**. The message, for the operator, names the model, the pipe, the stop value, the output tokens used and the `max_tokens` sent, never the partial text; the caller reads the code's sentence, with the model and the token counts as its parameters. The error's `truncation_limit` tells the output limit from the context window (`model_context_window_exceeded`, `model_length`), and so does its code's next step: a higher `max_tokens` for the first, a shorter input for the second. 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** |+| A structured output cut at its output limit (`instructor`'s `IncompleteOutputException`, for an OpenAI or Mistral first choice finished on `length` or an Anthropic message stopped on `max_tokens`) | The Anthropic, OpenAI Chat Completions and Mistral workers raise `LLMCompletionTruncatedError` from it, at the output limit: `model.output_truncated` → **HTTP 422**, whose message, for the operator, names the same stop value, output tokens and `max_tokens` a cut text names, and whose sentence the caller reads with the same parameters (see [The `instructor` Unwrap](#the-instructor-unwrap)) |+| A Gemini image generation refused or stopped by a safety filter: a candidate whose `finish_reason` names a filter (`IMAGE_SAFETY`, `IMAGE_PROHIBITED_CONTENT`, `SAFETY` and their kin), or no candidate and a `prompt_feedback.block_reason` | The Google image worker reads the reason before it looks for an image, through `GoogleFactory.read_stop_signal`, which the Google text worker shares: the finish reason from Gemini's vocabulary with `classify_image_finish_reason`, and any block reason as a refusal. It raises `ImgGenGenerationError` → `CONTENT` / `CHANGE_INPUT`, not repeated; `model.content_refused` → **HTTP 422**, whose sentence names the model's handle for the caller, and whose message, for the operator, names the reason and what it says, so a recitation (`RECITATION`, `IMAGE_RECITATION`) or an unsupported language (`LANGUAGE`) is never called a safety filter's block. A candidate that holds no image for another reason (`NO_IMAGE`, `IMAGE_OTHER`) is still an unusable answer, `provider.response_invalid`, and a finish reason Gemini adds later is logged at warning level as an image generation's and taken as normal |+| A Gemini image generation its output token limit cut before the image: a candidate whose `finish_reason` is `MAX_TOKENS` and that holds no image | The Google image worker reads it with the refusals, before it looks for an image, and raises `ImgGenOutputTruncatedError`, a subclass of `ImgGenGenerationError` → `CONTENT` / `CHANGE_INPUT`, not repeated; `model.output_truncated` → **HTTP 422**, whose message, for the operator, names the model's handle and the finish reason. The worker sends no output limit of its own, so its advice (`user_action`) is a simpler prompt or another image model. An image the model finished before the limit is whole, and returned || 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 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 structured output cut at the lowered limit is a truncation that says it was lowered and to what, and whose next step, in its message and its `user_action`, is a lower reasoning effort or a smaller output, never a higher `max_tokens`; 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`, `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 — `runtime.unexpected` |+| 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 once the re-asks are spent, or a timeout, keeps its class and category and its message ends with a sentence saying the limit was lowered and to what; a structured output cut at the lowered limit is a truncation whose message, for the operator, says it was lowered and to what, and whose advice, in its message and its `user_action`, is a lower reasoning effort or a smaller output, never a higher `max_tokens`; 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`, `model.output_schema_mismatch` → HTTP 502, whose verdict invites a retry |+| 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 501 |+| Connection dropped mid-request | `AMBIGUOUS` → not repeated within the run (outcome unknown); `provider.outcome_unknown` → HTTP 502, whose sentence says the work may exist and be billed, and whose step says to run the method again only if a repeat of the work is acceptable |+| 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 method's: **HTTP 422**, with a `change_model` step and a sentence 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 501, in the operator's domain, whose caller step offers another model |+| 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`, naming the first branch whose multiplicity differs from its field's, with one item per such branch when there are several, or `input.missing` at the entry pipe and `pipe.input_unresolved` below it → **HTTP 422**, each with its code's step, `change_method` for the method's codes and `change_input` for the input's |+| 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**. 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** 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 502; 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 the operator's alone; 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 parameters and facts from the chain |+| A pipe fails during a run | `PipeRouterError` → `PipelineExecutionError`, both answering the root fault's problem, its `location` naming the failing pipe and its path from the entry pipe; their own messages, for the operator, are the root fault's prefixed with `Pipe '<code>' failed (<path>): ` |+| A pipe raises a non-Pipelex exception | Located as a `PipelexUnexpectedError` whose message names the original class; `runtime.unexpected`, its message the operator's alone |+| Failure on a distributed worker | The problem recovered from the transport's serialized details — the same as local |+| Worker exception with no packed problem | A fallback problem — `runtime.unexpected` |---diff --git a/docs/under-the-hood/execution-graph-tracing.md b/docs/under-the-hood/execution-graph-tracing.mdindex 1d8f290ca..00b2a0d5d 100644--- a/docs/under-the-hood/execution-graph-tracing.md+++ b/docs/under-the-hood/execution-graph-tracing.md@@ -225,7 +225,7 @@ Every `EdgeSpec` also carries an `optional` boolean (default `false`). On a `DATA `SKIPPED` node also carries `skip_reason` (a human-readable sentence naming the absent input, e.g. `skipped because input 'source' is absent`). A lifted pipe with a plural output still writes a real empty-list value, so its node registers that output and downstream `DATA` edges resolve normally; a lifted singular output is a recorded absence with no output spec.-A failed node's `error` carries `caller_facing`, true when its `message` was written for the caller: the error report of the error the pipe raised says so in its `caller_facing_message`, as the run's own failure report does. A reader that shows failures to a caller under the strict disclosure shows the message only when it is true. Tracing never changes how a run fails: the report is built while the pipe's error is on its way to the caller (`pipelex/graph/traced_failure.py`), so when building it raises, the fault is logged as an error, the node records the error's text with `caller_facing` false, and the run fails with the pipe's own error.+A failed node's `error` is the [problem document](error-model.md#the-problem-document) of the error that ended it, in the caller view, since the graph is read by whoever reads the run: the code, its sentences rendered from the parameters a caller may read, and never the error's own message. Its `location` names the node's own pipe and that pipe's path from the entry pipe, whatever pipe below it the failure happened in, so each failed node of a nested failure is located at itself while all of them carry the root fault's code. An exception that is not a Pipelex error records `runtime.unexpected`. Beside it, `error_stack` holds the stack trace of the error when the graph's data inclusion asks for it, capped at `MAX_STACK_LENGTH` (`cap_error_stack()`) both on the node and on the `PipeEndErrorEvent` that every trace subscriber reads before any node is built. Tracing never changes how a run fails: the problem is built while the pipe's error is on its way to the caller (`pipelex/graph/node_problem.py`), so when building it raises, the fault is logged as an error under the message `The problem of a failed pipe could not be built for its trace`, the node records `runtime.unexpected`, and the run fails with the pipe's own error.### Node Paths@@ -329,7 +329,7 @@ The mode a trace states is the one the run's pipes run in, which is not always t|---|---|---|| `pipe_start` | A pipe starts | The node, its parent, the pipe's code, its `pipe_ref`, its domain-qualified reference (`null` for a binding step), its type, description and domain, its node kind and its inputs; a `PipeSequence` also states `step_count`, the number of steps its author wrote, and a `PipeParallel` states `branch_count`, the number of its branches, both `null` on every other pipe || `pipe_end_success` | A pipe ends with an output | The node, the pipe's `pipe_code`, `pipe_ref` and `pipe_type`, as its start states them, its end time, its output and its metrics |-| `pipe_end_error` | A pipe fails | The node, the pipe's code, reference and type, its end time and the error, whose `caller_facing` says whether its message was written for the caller |+| `pipe_end_error` | A pipe fails | The node, the pipe's code, reference and type, its end time, the error's problem in the caller view located at the pipe, and its stack trace when the data inclusion asks for it || `pipe_end_skipped` | A pipe is lifted because a plain input is absent | The node, the pipe's code, reference and type, its end time, the reason, and the empty list a plural output still writes || `edge` | The tracer draws an edge | Its source, target, kind, label and stuff digests || `controller_output` | A controller registers an output it produced | The node and the output |diff --git a/docs/under-the-hood/inference-backend-plugins.md b/docs/under-the-hood/inference-backend-plugins.mdindex ba7574263..ef00aa0d9 100644--- a/docs/under-the-hood/inference-backend-plugins.md+++ b/docs/under-the-hood/inference-backend-plugins.md@@ -64,7 +64,7 @@ registrar.add_inference_backend()```-`check_llm_request` is how validation learns what the worker refuses. Every LLM worker runs a `check_request` classmethod before each provider call, which refuses, from the model's spec and the job params alone, a request it would refuse anyway: a reasoning setting the model's `thinking_mode` refuses, a reasoning budget where it takes only an effort, a thinking budget the call's `max_tokens` cannot hold, or a structured output it cannot generate. When a method loads, every `PipeLLM` and `PipeStructure` resolves its model setting to the model the deck serves and calls the check its backend registered, so such a step is refused as an `llm_setting_refused_by_model` item before a run spends anything. The item is shown to whoever wrote the setting, even under strict error disclosure, so the refusal's text must name nothing your plugin keeps private: raise it as caller-facing copy, `LLMCapabilityError(msg).as_caller_fault()`, to have it shown as written, and any other refusal your check raises is named on the item by its title alone. A built-in backend's refusal is shown with the model named by its deck handle. The registered check is import-light like `make_worker`, called with `inference_model`, `job_params` and `is_structured` as keyword arguments, and delegates to the worker class's own check, which builds no SDK client:+`check_llm_request` is how validation learns what the worker refuses. Every LLM worker runs a `check_request` classmethod before each provider call, which refuses, from the model's spec and the job params alone, a request it would refuse anyway: a reasoning setting the model's `thinking_mode` refuses, a reasoning budget where it takes only an effort, a thinking budget the call's `max_tokens` cannot hold, or a structured output it cannot generate. When a method loads, every `PipeLLM` and `PipeStructure` resolves its model setting to the model the deck serves and calls the check its backend registered, so such a step is refused as an `llm_setting_refused_by_model` item before a run spends anything. The item is shown to whoever wrote the setting, in the caller view too, so the refusal's text must name nothing your plugin keeps private: raise an `LLMSettingRefusedError(msg)` (`pipelex.cogt.exceptions`), worded for whoever wrote the setting, to have it shown as written, and any other refusal your check raises is named on the item by its code's sentence alone, its text riding only the operator's diagnostics. A built-in backend's refusal is shown with the model named by its deck handle. The registered check is import-light like `make_worker`, called with `inference_model`, `job_params` and `is_structured` as keyword arguments, and delegates to the worker class's own check, which builds no SDK client:```pythondef _check_acme_request(*, inference_model: InferenceModelSpec, job_params: LLMJobParams, is_structured: bool) -> None:diff --git a/docs/under-the-hood/orchestrator-plugins.md b/docs/under-the-hood/orchestrator-plugins.mdindex 49afe4405..aed3cb53a 100644--- a/docs/under-the-hood/orchestrator-plugins.md+++ b/docs/under-the-hood/orchestrator-plugins.md@@ -58,7 +58,7 @@ Constructing the orchestrator instance must be **import-light** — it must not### A missing orchestrator is a generic, plugin-decoupled error-A token with no registered orchestrator (its plugin is not installed) raises `MissingOrchestratorError(mode=...)` (`pipelex/runtime_bridge/exceptions.py`). The message names the token but **no orchestrator** — *"No orchestrator is registered for orchestration mode '{mode}'; is its plugin installed?"* — so core stays fully decoupled from its plugins (it never spells out the Temporal or Mistral Workflows backend). The one special case is the core `"direct"` token: its orchestrator is always present, so a miss there reports a boot/discovery fault. The message survives STRICT error disclosure.+A token with no registered orchestrator (its plugin is not installed) raises `MissingOrchestratorError(mode=...)` (`pipelex/runtime_bridge/exceptions.py`). The message names the token but **no orchestrator** — *"No orchestrator is registered for orchestration mode '{mode}'; is its plugin installed?"* — so core stays fully decoupled from its plugins (it never spells out the Temporal or Mistral Workflows backend). The one special case is the core `"direct"` token: its orchestrator is always present, so a miss there reports a boot/discovery fault, `runtime.unexpected`. The message rides only the operator view; a caller reads the sentences of the error's code: `pipelex.plugin.not_found` for a mode the deployment configured, and `runtime.unsupported` for a mode the request named that this runtime does not offer.---@@ -91,7 +91,7 @@ The quoted annotations are forward references because `Mapping`, `Sequence` andTwo contract points distinguish it from `OrchestratorProtocol.execute`:- **No fire-and-forget arm.** Validation is inherently blocking, so — unlike orchestration's `execute`/`start` split — there is no `start` counterpart and no `supports_fire_and_forget` capability flag.-- **Verdict-as-value, not raise.** `validate_bundles` *returns* the verdict — `BundleValidationVerdict` is the union of the valid arm (a `ValidationReport`) and the invalid arm (an `ErrorReport` carrying `validation_errors`) — and raises only for a no-verdict infra fault, which a host runtime maps to a 5xx. This is the same valid/invalid pair the API maps onto its 200-always `/validate` wire, so the verdict contract is backend-independent.+- **Verdict-as-value, not raise.** `validate_bundles` *returns* the verdict — `BundleValidationVerdict` is the union of the valid arm (a `ValidationReport`) and the invalid arm (a `BundleValidationFailure`, `pipelex/errors/bundle_validation_failure.py`, carrying the refusal's problem in the operator view and its `validation_errors`) — and raises only for a no-verdict infra fault, which a host runtime maps to a 5xx. This is the same valid/invalid pair the API maps onto its 200-always `/validate` wire, so the verdict contract is backend-independent. The failure crosses process boundaries as a model, and the host that serves the verdict projects its problem to the view of whoever asked.The seam is deliberately typed at the MTHDS-protocol level (`ValidationReport` from `mthds.protocol`), not the concrete `PipelexValidationReport` envelope: the concrete report's module reaches the hub, so naming it from this hub-reachable seam would close an import cycle, and the seam is generic across orchestrators (language-standard altitude), so it speaks the protocol report — the Pipelex-runtime envelope is the concrete `ValidationReport` subtype the validators actually produce, and the API recovers that precise type at its edge. `library_dirs` is host context the in-process arm needs to load the method library; a worker-dispatched arm ignores it — its worker loads its own library.@@ -118,12 +118,14 @@ The failure modes mirror the orchestrator seam exactly: a duplicate token failsAn orchestrator's *runtime* (a Temporal client, a Mistral workflow runner) raises SDK-specific transport faults — a server unreachable, a workflow timeout — that a host runtime serving HTTP must turn into a proper error response, not a catch-all 500. But core names no web framework and the SDK lives only in the plugin, so the host (`pipelex-api`) cannot itself know how to classify `temporalio.TemporalError`.-The plugin bridges that gap by contributing a **framework-agnostic mapper** — a function from one exception type to a structured `ErrorReport` (`pipelex/base_exceptions.py`):+The plugin bridges that gap by contributing a **framework-agnostic mapper** — a function from one exception type to the `PipelexError` it stands for (`pipelex/base_exceptions.py`), whose code classifies it:```pythonregistrar.add_http_error_mapper(exc_type_provider=lambda: TemporalError, # SDK imported only when a host resolves the mappers, never at register- to_error_report=lambda exc: ErrorReport(...), # classified transient / RUNTIME+ to_pipelex_error=lambda exc: OrchestratorUnavailableError(...).with_error_code(+ CoreCode.RUNTIME_UNAVAILABLE+ ), # an error of the plugin's own, classified by its code)```@@ -131,9 +133,9 @@ The exc type is supplied as a **provider thunk**, not the bare class, on purposeThe contract is deliberately split so no layer overreaches:-- **The plugin** owns *classification* — which exception, transient or not, which error domain. It stays import-light: `register` only records the provider + closure; the SDK import happens when the provider runs at read time (and the `to_error_report` closure when the mapper is first invoked), never at registration.-- **Core** owns *transport* — `registrar.get_http_error_mappers()` runs every provider, builds the `{exc_type: mapper}` dict, and is fail-loud on a duplicate *resolved* exception type (naming both plugins). `ErrorReport` is a core type, so the seam carries **no** web-framework import.-- **The host runtime** owns *presentation* — at app construction it iterates the resolved mappers and wraps each into one framework error handler (FastAPI, …) that runs the mapper, then renders the `ErrorReport` through its own RFC 7807 + `DisclosureMode` path. FastAPI / Starlette stays only in the host; core and the plugin import neither.+- **The plugin** owns *classification* — which exception, and which code it carries, which decides its status, its domain and whether a retry can help. It stays import-light: `register` only records the provider + closure; the SDK import happens when the provider runs at read time (and the `to_pipelex_error` closure when the mapper is first invoked), never at registration.+- **Core** owns *transport* — `registrar.get_http_error_mappers()` runs every provider, builds the `{exc_type: mapper}` dict, and is fail-loud on a duplicate *resolved* exception type (naming both plugins). `PipelexError` is a core type, so the seam carries **no** web-framework import.+- **The host runtime** owns *presentation* — at app construction it iterates the resolved mappers and wraps each into one framework error handler (FastAPI, …) that runs the mapper, then renders the error's problem through its own RFC 9457 path, in the view the request's identity gives it (see [Error Responses](../api-server/error-responses.md#views-chosen-by-identity)). FastAPI / Starlette stays only in the host; core and the plugin import neither.This is what lets the public `pipelex-api` base be orchestrator-agnostic and still render a Temporal (or Mistral) transport fault correctly: install the flavor's plugin and its mapper rides in; install none and there is simply nothing to wrap. The capability is optional, contributing one method to the plugin contract.diff --git a/docs/under-the-hood/pipe-func-requirements.md b/docs/under-the-hood/pipe-func-requirements.mdindex b469811d3..1545a3dae 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`, 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)).+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, rides only the operator view's diagnostics, 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@@ -92,7 +92,7 @@ A mode with one fixed package set ignores the requirements and answers its packa- **`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 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 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 only the operator view carries, 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`).diff --git a/docs/under-the-hood/pipelex-kernel.md b/docs/under-the-hood/pipelex-kernel.mdindex 3cec653f0..a4e12c436 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 error with the code `security.input_url_refused` 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`, an 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,9 @@ 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.+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`, whose step asks the method's author for another model; 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.+`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 the validation item shows its message to whoever wrote the setting; its code, `model.capability_unsupported`, takes that handle as `model` and the capability the worker named as `capability`. An external plugin's refusal is raised as the plugin wrote it, and the item shows its message only when the plugin raised it as an `LLMSettingRefusedError`, and its code's sentence otherwise. 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`, 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.diff --git a/docs/under-the-hood/reasoning-controls.md b/docs/under-the-hood/reasoning-controls.mdindex 617620a5b..57a7dad27 100644--- a/docs/under-the-hood/reasoning-controls.md+++ b/docs/under-the-hood/reasoning-controls.md@@ -441,7 +441,7 @@ The behavior of `ReasoningEffort.NONE` varies by provider:## Checked When the Method Loads-Every refusal below is raised by a worker's `check_request` classmethod, which reads only the model's spec and the job params and builds no SDK client. The worker runs it before every call, on text and structured outputs alike, and bundle validation runs the same check: when a method loads, each `PipeLLM` and `PipeStructure` resolves the setting its output is generated with (`model` for a single text, or a single `Dynamic` output, which a run generates as text unless its caller names another concept; `model_to_structure`, else `model`, else the deck's override or default for structured outputs, for anything else, a declared list of any concept included) to the model the deck serves, applies the model's constraints to the job params as the worker does, and calls the check its backend registered beside its worker factory. A refusal is an `llm_setting_refused_by_model` validation error on the field holding the setting, naming the pipe, the setting and the worker's reason, with the model named by its deck handle and never by its SDK or backend (an external plugin's refusal is shown as written only when the plugin raised it as caller-facing copy, and by its title otherwise), so `pipelex validate`, the API's validate route and a run all refuse the method before any credit is spent, where it used to validate as runnable and fail at the first call. A model no backend serves on the boot, or whose backend's SDK is not installed, is left to the run. A backend that registers no check, an external plugin's for instance, is held to the rule every worker shares: a model whose spec declares `thinking_mode = "none"` takes no reasoning setting.+Every refusal below is raised by a worker's `check_request` classmethod, which reads only the model's spec and the job params and builds no SDK client. The worker runs it before every call, on text and structured outputs alike, and bundle validation runs the same check: when a method loads, each `PipeLLM` and `PipeStructure` resolves the setting its output is generated with (`model` for a single text, or a single `Dynamic` output, which a run generates as text unless its caller names another concept; `model_to_structure`, else `model`, else the deck's override or default for structured outputs, for anything else, a declared list of any concept included) to the model the deck serves, applies the model's constraints to the job params as the worker does, and calls the check its backend registered beside its worker factory. A refusal is an `llm_setting_refused_by_model` validation error on the field holding the setting, naming the pipe, the setting and the worker's reason, with the model named by its deck handle and never by its SDK or backend (an external plugin's refusal is shown as written only when the plugin raised it as an `LLMSettingRefusedError`, worded for whoever wrote the setting, and by its code's sentence otherwise), so `pipelex validate`, the API's validate route and a run all refuse the method before any credit is spent, where it used to validate as runnable and fail at the first call. A model no backend serves on the boot, or whose backend's SDK is not installed, is left to the run. A backend that registers no check, an external plugin's for instance, is held to the rule every worker shares: a model whose spec declares `thinking_mode = "none"` takes no reasoning setting.## Error Handlingdiff --git a/docs/under-the-hood/service-error-codes.md b/docs/under-the-hood/service-error-codes.mdindex 2f924b192..1d05c0da3 100644--- a/docs/under-the-hood/service-error-codes.md+++ b/docs/under-the-hood/service-error-codes.md@@ -56,9 +56,9 @@ Each entry says, about one code:|-------|---------|| `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 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 |+| `error_code` | the public registry code the rendered error carries, which decides its problem: its domain, the HTTP status it answers on a server, whether a retry can succeed, and the sentences and the step every reader of it gets. 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 the error's advice |+| `detail` | the advice itself: what the caller, or whoever operates the service, should do. The local CLIs print it as a tip beside the error; a problem never carries it, since its step is the code's. 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, and its `error_code` is then `model.unavailable` |## How the runtime reads themdiff --git a/docs/under-the-hood/template-sandbox.md b/docs/under-the-hood/template-sandbox.mdindex a09804a62..075e0db74 100644--- a/docs/under-the-hood/template-sandbox.md+++ b/docs/under-the-hood/template-sandbox.md@@ -48,7 +48,7 @@ What validation cannot see, because it depends on the values at run time (a methA 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.+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 the code's step for the method's author, which the caller view carries as well.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`.diff --git a/docs/under-the-hood/writing-an-inference-plugin.md b/docs/under-the-hood/writing-an-inference-plugin.mdindex 56cebd57b..c4ff674e4 100644--- a/docs/under-the-hood/writing-an-inference-plugin.md+++ b/docs/under-the-hood/writing-an-inference-plugin.md@@ -110,7 +110,7 @@ class HelloInferencePlugin:name = "hello_inference"# The plugin API version this plugin was written against, as a literal: never import the# runtime's PLUGIN_API_VERSION here, or the check that catches a breaking runtime upgrade always passes.- targets_api = 8+ targets_api = 9def register(self, registrar: PluginRegistrar) -> None:registrar.add_inference_backend(family=InferenceFamily.LLM, sdk="hello", make_worker=_make_hello_llm_worker)diff --git a/pipelex/base_exceptions.py b/pipelex/base_exceptions.pyindex c7548aa55..ee67fecf5 100644--- a/pipelex/base_exceptions.py+++ b/pipelex/base_exceptions.py@@ -1,12 +1,14 @@from collections.abc import Iteratorfrom enum import StrEnum-from typing import Any, ClassVar, Self+from typing import Any, ClassVar, NamedTuple, Self+from mthds.protocol.problem.models import ProblemItem, ProblemLocationfrom mthds.protocol.problem.registry import CoreCode, ProblemDomain+from opentelemetry import tracefrom pydantic import BaseModel, ConfigDict, Fieldfrom typing_extensions import override-from pipelex.cogt.inference.error_classification import ProviderErrorMetadata, UserAction+from pipelex.cogt.inference.error_classification import UserActionfrom pipelex.errors.error_code_declaration import (ABSTRACT_ERROR,AbstractError,@@ -17,9 +19,22 @@ from pipelex.errors.error_code_declaration import (describe_error_code_declaration,)from pipelex.errors.error_codes import ErrorCode, error_code_spec+from pipelex.errors.problem import (+ DiagnosticCause,+ MigrationErrorBlock,+ PipelexProblem,+ ProblemDiagnostics,+ ProblemView,+ ProviderDiagnostics,+ cap_problem_text,+ make_problem,+ merge_locations,+ recovered_problem_in_view,+ runtime_version,+)from pipelex.errors.registry.pipelex_codes import PipelexErrorCode-from pipelex.migration.plan import MigrationPlanfrom pipelex.suggested_fix import SuggestedFix+from pipelex.system.telemetry.current_span import current_span_context_for_logs, pipelex_span_context_for_logsfrom pipelex.validation_error_types import ValidationErrorType@@ -43,164 +58,28 @@ def iter_cause_chain(exc: BaseException) -> Iterator[BaseException]:node = node.__cause__-# Placeholder ``message`` substituted into a STRICT-mode serialization of a-# report whose ``message`` is not caller-facing copy. A report flagged-# ``caller_facing_message`` keeps its original ``message`` instead.-INTERNAL_ERROR_PLACEHOLDER = "An internal error occurred."--# Stable identifiers preserved verbatim on every STRICT envelope, regardless of-# the report's ``caller_facing_message`` flag. ``message`` and ``user_action``-# are intentionally absent and handled separately by the two STRICT branches:-# the caller-facing branch keeps both, the redacted branch replaces ``message``-# with ``INTERNAL_ERROR_PLACEHOLDER`` and drops ``user_action``.-# ``provider_metadata`` is also absent here — it is reattached on both branches-# as a curated subset (see ``_STRICT_PROVIDER_METADATA_KEPT_FIELDS``).-# Provider/model attribution (``provider``, ``model``) is unconditionally-# excluded: it never belongs on an external surface, whatever the report's-# ``error_domain``. The internal ``caller_facing_message`` flag is likewise-# excluded — it is redaction plumbing that rides only the VERBOSE round-trip-# format, never the lossy external projection.-#-# Single source of truth for both STRICT branches. Adding a new top-level-# ``ErrorReport`` field is one decision: include it here to surface it on both-# branches, or leave it out to keep both branches consistently silent.-#-# ``validation_errors`` IS surfaced: it describes the caller's own submitted-# bundle (per-error diagnostics on a ``ValidateBundleError``), not server-# internals, so redacting it would gut the hosted path's diagnostics. It only-# ever rides a ``ValidateBundleError`` report (a caller-facing INPUT error), but-# it is kept here — not by the caller-facing branch's bespoke logic — so the-# decision lives in this one allowlist.-#-# Caveat — ``validation_errors[].source``: on the *in-memory* validate and run-# paths ``source`` is the caller-supplied logical source (e.g. ``api://bundle-0.mthds``),-# which is the hosted/STRICT case and safe to surface; a bundle of an address-based-# dependency is named by the package's address and its path inside the package, and-# a file of the host's own library directories is withheld from the verdict, source-# and messages alike (``withholding_host_library_files``). On the *on-disk* path a-# ``source`` is a real server filesystem path, and STRICT does NOT redact it-# (consistent with ``DisclosureMode`` being a classification-projection, not a-# path-leak shield — see its docstring). A hosted surface that validates from disk-# should therefore use the in-memory path with logical sources rather than rely on-# STRICT to scrub the path.-#-# ``migration`` is NOT surfaced, and the contrast with ``validation_errors`` is-# the whole reason: a pending configuration migration describes the *host's* own-# configuration directories — server filesystem paths, and the shape of a-# 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(- {"code", "error_type", "title", "type_uri", "error_domain", "error_category", "retryable", "validation_errors"}-)--# The curated subset of ``ProviderErrorMetadata`` that survives STRICT-# projection. ``status_code`` and ``retry_after_seconds`` are actionable client-# hints (HTTP status mapping, ``Retry-After`` header) — they are not provider-# attribution. Every other ``ProviderErrorMetadata`` field carries either-# provider identity (``provider``, ``provider_error_code``, ``sdk_exception_type``)-# or internal correlation IDs / free-form text (``request_id``, ``message``) that-# the external surface has no business seeing.-_STRICT_PROVIDER_METADATA_KEPT_FIELDS: frozenset[str] = frozenset({"status_code", "retry_after_seconds"})-+def iter_pipelex_cause_chain(exc: BaseException) -> Iterator["PipelexError"]:+ """Yield ``exc`` and each Pipelex error below it along its ``__cause__`` chain, stopping at the first that is not one.-def _redact_provider_metadata_for_strict(metadata_payload: dict[str, Any]) -> dict[str, Any] | None:- """Project a ``ProviderErrorMetadata`` payload through STRICT's curated subset.-- Keeps only the fields in :data:`_STRICT_PROVIDER_METADATA_KEPT_FIELDS`- (``status_code`` / ``retry_after_seconds``). Returns ``None`` when no curated- field is present, so the caller can omit the key entirely rather than emit- an empty dict on the wire.- """- curated = {key: value for key, value in metadata_payload.items() if key in _STRICT_PROVIDER_METADATA_KEPT_FIELDS}- return curated or None---# Fields already mapped into RFC 7807 standard slots (``detail`` / ``title`` /-# ``type``) by ``to_problem_document`` — must NOT be echoed as extension-# members on the returned envelope.-_RFC7807_MAPPED_FIELDS: frozenset[str] = frozenset({"message", "title", "type_uri"})--# Fields ``to_problem_document`` must not surface as RFC 7807 extension members:-# the standard-slot mappings plus ``caller_facing_message``, which is internal-# redaction plumbing carried on the serialized report, not consumer-facing-# classification.-_PROBLEM_DOCUMENT_OMITTED_FIELDS: frozenset[str] = _RFC7807_MAPPED_FIELDS | frozenset({"caller_facing_message"})---class DisclosureMode(StrEnum):- """How much detail to include when serializing an ``ErrorReport`` for external surfaces.-- - ``VERBOSE``: all classification fields plus the original ``message``. Use for- internal-trust boundaries (webhook payloads, internal RPCs) where the receiver- decides what to expose further downstream. ``from_dict(to_dict(report, VERBOSE))``- reconstructs the original report exactly.-- - ``STRICT``: a lossy projection for untrusted external surfaces.- ``provider`` / ``model`` are dropped unconditionally — provider/model- attribution never belongs on an external surface. ``provider_metadata`` is- projected through a curated subset: only ``status_code`` and- ``retry_after_seconds`` survive (actionable HTTP client hints, not provider- attribution). The ``message`` is then projected by *provenance*:-- - A report flagged :attr:`ErrorReport.caller_facing_message` keeps its- ``message`` and ``user_action``. The flag is set by error classes whose- message is genuinely caller-facing copy — text describing the *caller's- own* input, e.g. ``MthdsParserError`` (a ``.mthds`` syntax error)- or ``ValidateBundleError`` (a failed bundle validation) — or, for a- class raised both for the caller's faults and for others, by the raise- site that knows, through :meth:`PipelexError.as_caller_fault`.- - Every other report has its ``message`` replaced with a generic- placeholder and its ``user_action`` dropped, keeping only the stable- identifiers (``error_type``, ``error_domain``, ``error_category``,- ``retryable``, ``title``, ``type_uri``).-- ``from_dict(to_dict(report, STRICT))`` does NOT reconstruct the original —- STRICT is lossy. Beyond the redacted message and dropped fields, a STRICT- payload that carries ``provider_metadata`` cannot be rehydrated at all:- the curated dict lacks the ``provider`` / ``sdk_exception_type`` fields- required by :class:`pipelex.cogt.inference.error_classification.ProviderErrorMetadata`,- so :meth:`ErrorReport.from_dict` raises :class:`pydantic.ValidationError`.- Consumers of a STRICT payload must read the dict directly (e.g. via- :meth:`ErrorReport.to_problem_document`) rather than rebuilding an- ``ErrorReport`` through ``from_dict``. Use VERBOSE on any surface that- needs round-trip semantics (webhook payloads, internal RPCs).-- STRICT keys the ``message`` decision on the *provenance of the message*,- not on ``error_domain``: ``error_domain`` is inherited up the ``__cause__``- chain, so a domain-less wrapper raised ``from`` an ``INPUT`` cause is- classified ``INPUT`` while still carrying its own internal ``message`` —- which STRICT must redact. ``caller_facing_message`` is not inherited, so it- tracks the wrapper's own message correctly. STRICT is a- *classification-projection*, **not a path-leak shield**: if a genuinely- caller-facing ``message`` could surface a server-resolved path or secret,- fix the upstream message — don't expand STRICT mode's scope.-- The curated ``provider_metadata`` subset, in contrast, IS inherited up the- ``__cause__`` chain via :meth:`PipelexError._enrich_error_report_from_cause`- and is preserved on both STRICT branches. A wrapper error (e.g.- ``PipelexUnexpectedError``) raised ``from`` a categorized ``CogtError``- therefore surfaces the cause's ``status_code`` / ``retry_after_seconds`` on- the STRICT envelope, even though the wrapper itself advertises no provider- relationship. This is deliberate, by the same reasoning as the previous- paragraph: the curated fields are HTTP client hints (status mapping,- ``Retry-After`` header), not provider attribution, and STRICT does not- hide internal failure topology.+ A foreign exception raised from an earlier failure is a new failure, raised by code of its own, so nothing below it+ belongs to the error above it: neither a code, a fact, a location, an item nor a piece of advice. Every walk that+ reads an error's chain for its problem reads it through this one, over the cycle-guarded :func:`iter_cause_chain`."""-- VERBOSE = "verbose"- STRICT = "strict"+ for node in iter_cause_chain(exc):+ if not isinstance(node, PipelexError):+ return+ yield nodeclass ErrorDomain(StrEnum):- """Classifies where an error originates, so consumers can route it.+ """The three-way reading of who acts that the CLIs' error output and the usage statistics still carry.- 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.+ The problem document carries the code's own domain, from the MTHDS core's closed list; this reading is derived+ from it through :meth:`from_problem_domain` for the surfaces that have not moved to it."""INPUT = "input"@@ -237,52 +116,12 @@ class ErrorDomain(StrEnum):return False-def error_domain_to_http_status(error_domain: ErrorDomain | str | None) -> int:- """Map an error domain to an HTTP status code.-- Domain-level building block for downstream HTTP APIs that render an- :class:`ErrorReport` as a response. When you have a full report, prefer- :attr:`ErrorReport.http_status` — it layers the provider 429 (rate-limit)- passthrough on top of this mapping. The library itself stays HTTP-agnostic —- no web-framework import lives here, only the mapping table.-- Accepts a raw ``str`` because ``ErrorReport.error_domain`` is serialized as- one. A value this version does not recognize (e.g. a report serialized by a- newer Pipelex) is treated as unclassified rather than crashing rendering.-- - ``INPUT`` -> 422: the caller sent something it can fix (bad input).- - ``CONFIG`` / ``RUNTIME`` -> 500: a server-side problem.- - unknown / ``None`` -> 500: unclassified, treated as a server-side problem.- """- if isinstance(error_domain, str):- try:- error_domain = ErrorDomain(error_domain)- except ValueError:- error_domain = None- match error_domain:- case ErrorDomain.INPUT:- return 422- case ErrorDomain.CONFIG | ErrorDomain.RUNTIME:- return 500- case None:- return 500--def error_domain_is_input(error_domain: ErrorDomain | str | None) -> bool:"""True when ``error_domain`` is the caller-fixable ``INPUT`` domain.- The serialized-form counterpart to :attr:`ErrorDomain.is_input`, mirroring- :func:`error_domain_to_http_status`: it accepts the raw ``str`` / ``None``- shape that :attr:`ErrorReport.error_domain` carries (and the value pulled out- of a serialized problem-document dict), so HTTP consumers can branch on- "is this the caller's mistake?" without re-implementing the coercion. Holds- a single source of truth — it delegates the per-value decision to- :attr:`ErrorDomain.is_input`.-- ``None`` or an unrecognized string (e.g. a report serialized by a newer- Pipelex) is treated as non-input — the conservative default those consumers- want, matching :func:`error_domain_to_http_status` which maps the same cases- to a server-side 500.+ The serialized-form counterpart to :attr:`ErrorDomain.is_input`: it accepts the raw ``str`` / ``None`` shape a+ CLI's JSON envelope carries, so a consumer can branch on "is this the caller's mistake?" without re-implementing+ the coercion. ``None`` or an unrecognized string is treated as non-input, the conservative default."""if error_domain is None:return False@@ -319,9 +158,10 @@ class ValidationErrorCategory(StrEnum):class ValidationErrorItem(BaseModel):- """One structured bundle-validation error, projected onto the error wire.+ """One structured bundle-validation error, as the validation verdicts carry it.- The typed wire item carried by :attr:`ErrorReport.validation_errors`. Its+ The typed item of an invalid verdict's ``validation_errors``; the problem document of a refusal carries each as an+ ``errors`` item instead (``pipelex.pipeline.validation_errors.problem_item_of``). Itsfields are the *union* across the three ``ValidateBundleError`` error-datamodels (``PipelexBundleBlueprintValidationErrorData``, ``PipeFactoryErrorData``,``PipesAndConceptValidationErrorData``); a given item only populates the@@ -331,18 +171,17 @@ class ValidationErrorItem(BaseModel):The error channel is built exclusively by``pipelex.pipeline.validation_errors.build_validation_error_items``, which both the agentCLI (``extract_validation_errors``) and the API path- (``ValidateBundleError.to_error_report``) call — so the CLI's structured- output and the API's 422 ``validation_errors`` can never drift. The same+ (``ValidateBundleError.validation_error_items``) call — so the CLI's structured+ output and the API's invalid verdict can never drift. The sameitem type also carries the report's advisory ``warnings``, built by``pipelex.pipeline.advisory_warnings``: a warning is the same shape ofdiagnostic, differing only in that it does not make the verdict invalid.``source`` is the declaring file path (CLI) or the per-content source the APIthreads onto the in-memory load path — it hands a consumer the owning file- for cross-file diagnostics. Lives here, alongside :class:`ErrorReport`,- rather than next to the source error-data models because ``ErrorReport``- references it as a typed field and ``base_exceptions`` must not import the- ``pipelex.core`` error modules (which import back into this module).+ for cross-file diagnostics. Lives here rather than next to the source error-data+ models because ``base_exceptions`` must not import the ``pipelex.core`` error+ modules (which import back into this module)."""model_config = ConfigDict(frozen=True, extra="forbid")@@ -388,316 +227,62 @@ class ValidationErrorItem(BaseModel):suggested_fix: SuggestedFix | None = None-class MigrationErrorBlock(BaseModel):- """A pending configuration migration, reported alongside the error it explains.-- The structured half of the answer to *why does my configuration not load* — carried by- :attr:`ErrorReport.migration`, and present only when a scan of this machine's configuration- directories found something to say. **Consumers branch on its presence**, never on the- message text: an absent block means the failure is not staleness.-- ``plans`` is the same shape ``pipelex-agent migrate --dry-run --format json`` emits under its- own ``plans`` key, deliberately — an agent that reads one has already parsed the other, and a- projection of its own here would be a second contract to keep in step with the first.-- Declared in this module rather than beside the migration engine for the same reason- :class:`ValidationErrorItem` is: :class:`ErrorReport` references it as a typed field, and- ``base_exceptions`` must not import the migration package's error modules, which import back- into this one. ``pipelex.migration.plan`` holds itself to stdlib + pydantic + low-level- siblings precisely so this import stays legal.-- > **No value read from a user's file is ever rendered** here either. The plans carry paths,- > operation kinds and ledger-supplied values, and nothing else — the same mechanical rule the- > migration report and the CLI output obey, on the third of the three channels it names.- """-- model_config = ConfigDict(frozen=True, extra="forbid")-- remedy: str- """The command that applies whatever can be applied without a decision."""-- would_write: bool- """Whether running ``remedy`` would actually rewrite any of these files.-- The block's *presence* says the migration history has something to report about this machine.- It does not say the remedy repairs it, and this field is what separates the two. A block whose- ``would_write`` is False carries a diagnosis and nothing to apply — a path no entry explains, a- file that could not be read, an entry blocked before any of its operations landed — so naming- ``remedy`` there would send a reader to a run that visits the files, writes nothing, and leaves- the same refusal standing. The dry run is what carries the answer on that side.-- Independent of :attr:`needs_attention`, and the pair is never both False: a file with nothing to- write and nothing for a person is clean, and clean files are not in ``plans``."""-- needs_attention: bool- """Whether something here is a person's to resolve rather than the tool's — a blocked file, a- blocked entry, or a path no ledger entry explains. When this is False, running ``remedy`` is- expected to be enough."""-- plans: list[MigrationPlan]- """One per configuration file the scan found something in. Files with nothing to say are left- out: unlike the ``migrate`` commands' report, which answers *what did the walk visit*, this- block answers *what is wrong with this machine's configuration*."""-+_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 ErrorReport(BaseModel):- """Structured error report — single source of truth for all error serialization.- Used by CLI JSON output, agent output, and Temporal error details.+class ProblemFacts(NamedTuple):+ """The facts an error knows that its problem's operator diagnostics and retry delay carry.- ``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.+ An error contributes the facts it holds (:meth:`PipelexError.problem_facts`), and a problem takes, for each, the+ one nearest the error it is built from along the cause chain, so that a wrapper that knows a fact overrides its+ cause and a wrapper that does not inherits it.- Frozen: wrappers must rebuild via :meth:`model_copy` rather than mutate, so- a cause-enrichment pass cannot accidentally overwrite an outer wrapper's- identity in-place.+ Attributes:+ model: The model a failed inference call addressed.+ provider: What the provider said about the call.+ migration: A pending configuration migration that explains the failure.+ retry_after: The delay the provider asked for before a retry, in seconds."""- model_config = ConfigDict(frozen=True, extra="forbid", arbitrary_types_allowed=True)-- code: str- error_type: str- message: str- title: str- type_uri: str- error_category: str | None = None- error_domain: str | None = None- retryable: bool | None = None- user_action: UserAction | None = Nonemodel: str | None = None- provider: str | None = None- provider_metadata: ProviderErrorMetadata | None = None- # True when ``message`` was authored as caller-facing copy — set at report- # construction from ``PipelexError._authors_caller_facing_message``, or from- # the raise site's :meth:`PipelexError.as_caller_fault`. STRICT- # disclosure keys its ``message`` passthrough on this flag (see- # :class:`DisclosureMode`). Defaults to False so an unflagged report — and- # any payload that predates the field — is redacted, never leaked.- caller_facing_message: bool = False- # Structured per-error diagnostics on a bundle-validation failure. Populated- # only by ``ValidateBundleError.to_error_report`` (None on every other- # report), so the 422 problem document carries the same machine-mappable- # items the agent CLI emits. Surfaced under STRICT disclosure (see- # ``_STRICT_KEPT_FIELDS``): these describe the caller's own submitted bundle,- # not server internals.- validation_errors: list[ValidationErrorItem] | None = None- # A pending configuration migration that explains this failure. Populated only by- # ``PipelexConfigError`` reports whose raiser ran a scan (see- # ``pipelex.core.validation.report_validation_error``); None on every other report, so a- # consumer branching on its presence is asking exactly "is my configuration stale?".- # Deliberately outside ``_STRICT_KEPT_FIELDS`` — it describes the host's own configuration- # directories, not the caller's submission.+ provider: ProviderDiagnostics | None = Nonemigration: MigrationErrorBlock | None = None+ retry_after: float | None = None- def to_dict(self, *, disclosure_mode: DisclosureMode = DisclosureMode.VERBOSE) -> dict[str, Any]:- """Return a dict with only non-None fields, projected through ``disclosure_mode``.-- ``VERBOSE`` is the strict inverse of :meth:`from_dict` — every populated- field round-trips. ``STRICT`` is a lossy projection (see- :class:`DisclosureMode`): ``provider`` / ``model`` are always dropped,- ``provider_metadata`` is projected through the curated subset (just- ``status_code`` and ``retry_after_seconds``), and unless the report is- flagged :attr:`caller_facing_message` its ``message`` is replaced with a- generic placeholder and ``user_action`` is dropped, leaving only the- stable identifiers plus the curated ``provider_metadata`` slice.- """- payload = self.model_dump(exclude_none=True)- if self.migration is not None:- # JSON mode for this field alone. ``MigrationPlan`` carries real ``Path`` values, and- # a payload holding one is not serializable by ``json.dumps`` — which is what the- # webhook delivery path hands this dict to. Dumping the whole report in JSON mode- # instead would re-serialize every other field too, so the narrow fix is the safe one.- # ``from_dict`` still round-trips: pydantic accepts a string for a ``Path`` field.- payload["migration"] = self.migration.model_dump(mode="json")- # ``caller_facing_message`` is redaction plumbing, not consumer-facing- # classification: emit it only when set, so the common (non-caller-facing)- # report serializes exactly as a report without the field would.- # ``from_dict`` defaults it back to False when absent, so the round-trip- # still holds.- if not self.caller_facing_message:- payload.pop("caller_facing_message", None)- match disclosure_mode:- case DisclosureMode.VERBOSE:- return payload- case DisclosureMode.STRICT:- # Both STRICT branches start from the same allowlist — single- # source of truth, so adding a new top-level ``ErrorReport``- # field is one decision (include / exclude), not two.- projected: dict[str, Any] = {key: payload[key] for key in _STRICT_KEPT_FIELDS if key in payload}- if self.caller_facing_message:- # The error class that authored this message designed it as- # caller-facing copy — reflect it (and ``user_action``) back- # on top of the shared allowlist.- projected["message"] = payload["message"]- if "user_action" in payload:- projected["user_action"] = payload["user_action"]- else:- projected["message"] = INTERNAL_ERROR_PLACEHOLDER- # Reattach a curated ``provider_metadata`` slice — even on the- # fully-redacted branch, ``status_code`` and ``retry_after_seconds``- # are actionable client hints (HTTP status mapping, ``Retry-After``- # header) that the HTTP adapter needs to emit a useful response.- if "provider_metadata" in payload:- curated_metadata = _redact_provider_metadata_for_strict(payload["provider_metadata"])- if curated_metadata is not None:- projected["provider_metadata"] = curated_metadata- return projected-- def to_problem_document(- self,- *,- instance: str | None = None,- request_id: str | None = None,- disclosure_mode: DisclosureMode = DisclosureMode.VERBOSE,- ) -> dict[str, Any]:- """Render this report as an RFC 7807 ``application/problem+json`` envelope.-- The runner stays HTTP-agnostic — this returns a plain ``dict`` that- downstream HTTP adapters serialize as JSON. The standard 7807 slots are- sourced from the report:-- - ``type`` from :attr:`type_uri`- - ``title`` from :attr:`title`- - ``status`` from :attr:`http_status`- - ``detail`` from :attr:`message` (subject to ``disclosure_mode`` redaction)- - ``instance`` from the ``instance`` arg (URN provided by the caller)-- Pipelex-native classification fields ride as extension members- (``error_type`` / ``error_domain`` / ``error_category`` / ``retryable`` /- ``user_action`` / ``model`` / ``provider`` / ``provider_metadata``).- ``type_uri`` and ``title`` are mapped — not duplicated — so the returned- dict has exactly one ``title`` key. The ``caller_facing_message`` flag is- internal redaction plumbing and is never echoed onto the envelope. When- the caller supplies a ``request_id``, it rides as an extension member too.- """- payload = self.to_dict(disclosure_mode=disclosure_mode)- document: dict[str, Any] = {- "type": self.type_uri,- "title": self.title,- "status": self.http_status,- "detail": payload["message"],- }- if instance is not None:- document["instance"] = instance- if request_id is not None:- document["request_id"] = request_id- for key, value in payload.items():- if key in _PROBLEM_DOCUMENT_OMITTED_FIELDS:- continue- document[key] = value- return document-- @classmethod- def from_dict(cls, data: dict[str, Any]) -> "ErrorReport":- """Rebuild an ``ErrorReport`` from a :meth:`to_dict` payload — the strict inverse of :meth:`to_dict` in ``VERBOSE`` mode.-- Used to recover a report that crossed a serialization boundary (e.g. a- Temporal ``ApplicationError.details`` payload) so it re-enters the- ``to_error_report()`` world. The nested ``UserAction`` /- ``ProviderErrorMetadata`` models round-trip through their dict form.-- Strict: ``ErrorReport`` is ``extra="forbid"``, so a malformed dict- raises :class:`pydantic.ValidationError`. Within a single deploy the- writer (activity bridge) and reader (submitter) share the schema, so a- validation failure is an internal contract bug. ``recover_error_report``- catches it to keep failure-webhook delivery intact; any other caller- should treat it as a bug to fix.- """- 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-- @property- def http_status(self) -> int:- """HTTP status code for this error, for downstream HTTP API adapters.-- A provider 429 (rate limit) takes precedence so the API can surface a- ``Retry-After`` header from ``provider_metadata.retry_after_seconds``;- otherwise the status follows ``error_domain`` (see- :func:`error_domain_to_http_status`, which also tolerates an- ``error_domain`` string this version does not recognize — e.g. a report- serialized by a newer Pipelex — rather than crashing response rendering).- """- if self.provider_metadata is not None and self.provider_metadata.status_code == 429:- return 429- return error_domain_to_http_status(self.error_domain)---_FALLBACK_ERROR_CODE: ErrorCode = CoreCode.RUNTIME_UNEXPECTED-"""The code of an error whose cause chain names none: the catch-all, ``runtime.unexpected``, step ``report``."""+def _merged_provider(*, nearer: ProviderDiagnostics | None, farther: ProviderDiagnostics | None) -> ProviderDiagnostics | None:+ """What two errors of one chain say about the provider, member by member, the nearer error's winning."""+ if nearer is None or farther is None:+ return nearer or farther+ return ProviderDiagnostics.model_validate({**farther.model_dump(exclude_none=True), **nearer.model_dump(exclude_none=True)})class PipelexError(Exception):- """The root of every error Pipelex raises, each carrying a registry code.+ """The root of every error Pipelex raises, each carrying a registry code, and each becoming a problem document.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.+ is an abstract base. The code decides the problem's title, documentation page, domain, retry verdict, step and+ sentences, 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.++ :meth:`to_problem` builds the error's problem document in the view of its reader. The error's own message is the+ operator's diagnostics, never a caller's sentence: the caller reads the code's templates, rendered from the+ parameters the raise site gives (:meth:`with_params`) or the class derives (:meth:`problem_params`)."""error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERROR+ # Advice a local reader of the error can act on, which the human and agent CLIs print as a tip. It never reaches a+ # problem document, whose step is the code's.user_action: UserAction | 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.- _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+ # The parameters the raise site gave with :meth:`with_params`.+ _given_params: dict[str, Any] | None = None+ # The items the raise site gave with :meth:`with_items`, one per fault of a refusal of several.+ _given_items: list[ProblemItem] | None = Nonedef __init_subclass__(cls, **kwargs: Any) -> None:super().__init_subclass__(**kwargs)@@ -739,6 +324,51 @@ class PipelexError(Exception):self._chosen_error_code = error_codereturn self+ def with_params(self, **params: Any) -> Self:+ """Give, where this error is raised, the parameters its code's sentences are rendered from.++ A raise site gives the facts its code declares, by the names the registry gives them, such as+ ``raise PipeRunError(...).with_error_code(CoreCode.PIPE_CONDITION_UNMATCHED).with_params(pipe=self.code)``. A+ parameter the code does not declare, or one of the wrong type, is dropped and logged when the problem is+ built, and a parameter given here overrides one the class derives.++ Args:+ **params: The parameters, by name.++ Returns:+ This error, so that the raise site reads ``raise SomeError(msg).with_params(name=value)``.+ """+ self._given_params = {**(self._given_params or {}), **params}+ return self++ def with_items(self, *, items: list[ProblemItem]) -> Self:+ """Give, where this error is raised, one item per fault when it refuses several at once.++ A raise site that finds several faults of one kind reports them all, each item rendered from its own+ parameters with :func:`pipelex.errors.problem.make_problem_item`, while the error's own code and parameters+ describe the first. A subclass that derives its items overrides :meth:`problem_items` instead.++ Args:+ items: The items, one per fault.++ Returns:+ This error, so that the raise site reads ``raise SomeError(msg).with_items(items=items)``.+ """+ self._given_items = list(items)+ return self++ def advised_action(self) -> UserAction | None:+ """The advice nearest this error along its cause chain, which a local CLI prints as a tip; never part of a problem."""+ for node in iter_pipelex_cause_chain(self):+ if node.user_action is not None:+ return node.user_action+ return None++ @property+ def given_params(self) -> dict[str, Any]:+ """The parameters the raise site gave with :meth:`with_params`."""+ return dict(self._given_params or {})+@propertydef own_error_code(self) -> ErrorCode | None:"""The code this error carries by itself, ``None`` when it takes its cause's.@@ -778,9 +408,7 @@ class PipelexError(Exception):"""implied_code: ErrorCode | None = Nonefallback: ErrorCode | None = None- for node in iter_cause_chain(self):- if not isinstance(node, PipelexError):- break+ for node in iter_pipelex_cause_chain(self):own_code = node.own_error_codeif own_code is not None:return own_code@@ -790,91 +418,236 @@ class PipelexError(Exception):fallback = declaration.fallbackreturn implied_code or fallback or _FALLBACK_ERROR_CODE- def as_caller_fault(self, *, user_action: UserAction | None = None) -> Self:- """Say, where this error is raised, that its message describes only the caller's own method or inputs.+ def resolve_domain(self) -> ProblemDomain:+ """Who must act on this error: the domain the registry gives the code it resolves to."""+ return error_code_spec(self.resolve_error_code()).domain- 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.+ def code_carrier(self) -> "PipelexError":+ """The error along the cause chain whose code this one reports, which gives the problem its facts about the fault.- 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- path, a secret, or the text of an exception that is not a Pipelex error.+ The first error that carries a code by itself, as :meth:`resolve_error_code` walks; else the deepest error that+ implies one; else this error, whose code is a fallback.+ """+ implied_node: PipelexError | None = None+ for node in iter_pipelex_cause_chain(self):+ if node.own_error_code is not None:+ return node+ if node.implied_error_code is not None:+ implied_node = node+ return implied_node or self++ def problem_params(self) -> dict[str, Any]:+ """The facts this error holds that its codes declare as parameters, by the registry's names.++ A subclass that holds such facts overrides it. A fact the resolved code does not declare is left out+ silently, since a class's codes declare different parameters, and a parameter its raise site gave+ (:meth:`with_params`) overrides a fact of the same name.+ """+ return {}++ def chain_items(self) -> list[ProblemItem] | None:+ """The items of the first error along the cause chain that refuses several faults at once."""+ for node in iter_pipelex_cause_chain(self):+ items = node.problem_items()+ if items:+ return items+ return None- Args:- user_action: The next step for the caller, when the raise site can name one.+ def chain_location(self, *, carrier: "PipelexError") -> ProblemLocation | None:+ """The location this error and the errors below it know, down to ``carrier``, the nearest the fault winning.- Returns:- This error, so that the raise site reads ``raise SomeError(msg).as_caller_fault()``.+ A wrapper that takes its cause's code often knows where its cause was met, the pipe, the field or the file, which+ the cause does not: each error's own location is merged over the ones above it, member by member, so a member+ the error whose code the problem reports knows wins, and the wrappers fill the members it lacks."""- self._raised_as_caller_fault = True- if user_action is not None:- self.user_action = user_action- return self+ location: ProblemLocation | None = None+ for node in iter_pipelex_cause_chain(self):+ node_location = node.problem_location()+ if node_location is not None:+ location = merge_locations(base=location, override=node_location)+ if node is carrier:+ break+ return location++ def problem_location(self) -> ProblemLocation | None:+ """Where this error happened, when it knows; a subclass that holds a place overrides it."""+ return None++ def problem_items(self) -> list[ProblemItem] | None:+ """One item per fault, for an error that refuses several at once: those its raise site gave with :meth:`with_items`.- def to_error_report(self) -> ErrorReport:- """Return a structured error report, enriched from the ``__cause__`` chain.+ A subclass that holds several faults of its own overrides it.+ """+ return list(self._given_items) if self._given_items else None++ def recovered_problem(self) -> PipelexProblem | None:+ """The problem this error carries from across a transport boundary, in the operator's view; ``None`` for any other error.++ A host plugin's carrier of a problem a far worker packed overrides it, and is the only kind of error that does:+ :meth:`to_problem` then reports that problem rather than one built from the carrier's class+ (:func:`pipelex.errors.problem.recovered_problem_in_view`), and a located wrapper above the carrier reports it as+ it is (``pipelex.pipe_run.located_failure``). Overriding :meth:`to_problem` for any other reason makes no carrier.+ """+ return None++ def errors_above(self, *, carrier: "PipelexError") -> list["PipelexError"]:+ """The errors from this one down to ``carrier``, ``carrier`` left out, this one first; empty when the chain never reaches it."""+ errors: list[PipelexError] = []+ for node in iter_pipelex_cause_chain(self):+ if node is carrier:+ return errors+ errors.append(node)+ return []- 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.+ def problem_facts(self) -> ProblemFacts:+ """The facts this error itself holds for its problem's diagnostics; a subclass that holds some overrides it."""+ return ProblemFacts()- 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.+ def chain_facts(self) -> ProblemFacts:+ """For each fact, the one nearest this error along its cause chain, which ends at the first foreign exception.++ The provider's answer is merged member by member, the nearest error's winning: a wrapper a worker attributed+ to its backend names the provider, while the cause it wraps keeps what the provider answered."""- report = ErrorReport.make_for_code(- code=self.resolve_error_code(),- error_type=type(self).__name__,- message=self.message,- user_action=self.user_action,- caller_facing_message=self._authors_caller_facing_message or self._raised_as_caller_fault,+ model: str | None = None+ provider: ProviderDiagnostics | None = None+ migration: MigrationErrorBlock | None = None+ retry_after: float | None = None+ for node in iter_pipelex_cause_chain(self):+ facts = node.problem_facts()+ model = model or facts.model+ provider = _merged_provider(nearer=provider, farther=facts.provider)+ migration = migration or facts.migration+ retry_after = retry_after if retry_after is not None else facts.retry_after+ return ProblemFacts(model=model, provider=provider, migration=migration, retry_after=retry_after)++ def _diagnostics(self, *, facts: ProblemFacts) -> ProblemDiagnostics:+ """The operator's diagnostics of this error: its class, its message capped, its causes and its facts."""+ causes: list[DiagnosticCause] = []+ for node in iter_cause_chain(self):+ if node is self:+ continue+ own_code = node.own_error_code if isinstance(node, PipelexError) else None+ causes.append(DiagnosticCause(error_class=type(node).__name__, code=own_code))+ span_context = pipelex_span_context_for_logs() or current_span_context_for_logs()+ return ProblemDiagnostics(+ error_class=type(self).__name__,+ message=cap_problem_text(text=self.message),+ causes=causes or None,+ model=facts.model,+ provider=facts.provider,+ migration=facts.migration,+ runtime_version=runtime_version(),+ trace_id=trace.format_trace_id(span_context.trace_id) if span_context is not None else None,+ span_id=trace.format_span_id(span_context.span_id) if span_context is not None else None,)- return self._enrich_error_report_from_cause(report)-- def _enrich_error_report_from_cause(self, report: ErrorReport) -> ErrorReport:- """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.++ def to_problem(+ self,+ *,+ view: ProblemView,+ request_id: str | None = None,+ pipeline_run_id: str | None = None,+ failure_location: ProblemLocation | None = None,+ ) -> PipelexProblem:+ """This error as a problem document, in the view of its reader.++ The code is :meth:`resolve_error_code`'s, and everything the code decides is the registry's. The rest is+ :meth:`problem_reported_by`'s, this error being its own reporter. An error carrying a problem recovered across a+ transport boundary (:meth:`recovered_problem`) reports that problem instead, in the view asked for.++ Args:+ view: The view of the reader the problem is built for, picked by the identity the boundary authenticated.+ request_id: The request that carried the failure, when known.+ pipeline_run_id: The run the failure belongs to, when one exists.+ failure_location: Where a run's failing pipe is, when the failure was located at a pipe.++ Returns:+ The problem."""- cause = self.__cause__- if not isinstance(cause, PipelexError):- return report- # Guard against a cyclic __cause__ chain: if self is reachable from cause, recursing- # into cause.to_error_report() would never terminate. Bail out with the enrichment- # gathered so far rather than raising a RecursionError from the error-reporting path.- if any(node is self for node in iter_cause_chain(cause)):- return report- cause_report = cause.to_error_report()- # 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``)- # discards the cause's actionable hints. Pinned by- # ``tests/unit/pipelex/cogt/test_cogt_provider_metadata_wrapper_wins.py``.- 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": report.model or cause_report.model,- "provider": report.provider or cause_report.provider,- "provider_metadata": report.provider_metadata or cause_report.provider_metadata,- }+ recovered = self.recovered_problem()+ if recovered is not None:+ return recovered_problem_in_view(+ problem=recovered, view=view, request_id=request_id, pipeline_run_id=pipeline_run_id, failure_location=failure_location+ )+ return self.problem_reported_by(+ reporter=self, view=view, request_id=request_id, pipeline_run_id=pipeline_run_id, failure_location=failure_location+ )++ def problem_reported_by(+ self,+ *,+ reporter: "PipelexError",+ view: ProblemView,+ request_id: str | None = None,+ pipeline_run_id: str | None = None,+ failure_location: ProblemLocation | None = None,+ ) -> PipelexProblem:+ """This error's problem as ``reporter`` reports it: this error itself, or a wrapper above it that located it.++ A run failure is reported as its root fault under the wrappers that located or carried it+ (``pipelex.pipe_run.located_failure``), and those wrappers may know what the root fault does not, so the problem+ is this error's, read along the reporter's chain:++ - the code is this error's (:meth:`resolve_error_code`), and the parameters are those of the error whose code it+ is (:meth:`code_carrier`): the facts it holds and the parameters its raise site gave, then, for a parameter it+ gives none of, the one the nearest error between the reporter and it gave with :meth:`with_params`, a+ parameter its code does not declare being dropped and logged;+ - the items are those of the first error at or below the error whose code it is that refuses several faults,+ then those each error between the reporter and it refuses, the nearest it first;+ - the location is assembled from the reporter down to the error whose code it is, each error's own location+ winning over those above it member by member, so a wrapper that knows the pipe, the field or the file a cause+ was met at locates a cause that does not; the location of the failing pipe a run found (``failure_location``)+ then takes precedence for the pipe and its path, and the pipe names the pipe parameter of a code that declares one;+ - the facts are the nearest the reporter along its chain, so a fact a wrapper above this error holds, such as+ the model and the backend a worker attributed it to, overrides its cause's;+ - the operator view's diagnostics name this error: its class, its message and its causes.++ Args:+ reporter: This error, or an error above it on whose cause chain it sits.+ view: The view of the reader the problem is built for, picked by the identity the boundary authenticated.+ request_id: The request that carried the failure, when known.+ pipeline_run_id: The run the failure belongs to, when one exists.+ failure_location: Where a run's failing pipe is, when the failure was located at a pipe.++ Returns:+ The problem.+ """+ code = self.resolve_error_code()+ carrier = self.code_carrier()+ # The wrappers between the reporter and the error whose code the problem reports, the reporter first.+ wrappers = reporter.errors_above(carrier=carrier)+ facts = reporter.chain_facts()+ spec = error_code_spec(code)+ params: dict[str, Any] = {}+ for wrapper in wrappers:+ # Given in order from the reporter down, so a wrapper nearer the carrier wins over one above it; checked+ # against the carrier's code when the problem is built, an undeclared one being dropped and logged.+ params.update(wrapper.given_params)+ params.update({name: value for name, value in carrier.problem_params().items() if name in spec.param_names})+ params.update(carrier.given_params)+ items = list(carrier.chain_items() or [])+ for wrapper in reversed(wrappers):+ items.extend(wrapper.problem_items() or [])+ location = reporter.chain_location(carrier=carrier)+ if failure_location is not None:+ location = merge_locations(base=location, override=failure_location)+ if location is not None and location.pipe is not None and "pipe" in spec.param_names:+ params.setdefault("pipe", location.pipe)+ if facts.model is not None and "model" in spec.param_names:+ params.setdefault("model", facts.model)+ if facts.provider is not None and facts.provider.name is not None and "provider" in spec.param_names:+ params.setdefault("provider", facts.provider.name)+ return make_problem(+ code=code,+ view=view,+ params=params,+ location=location,+ errors=items or None,+ retry_after=facts.retry_after,+ pipeline_run_id=pipeline_run_id,+ request_id=request_id,+ diagnostics=self._diagnostics(facts=facts) if view.shows_diagnostics else None,)@@ -897,11 +670,8 @@ class PipelexConfigError(PipelexError):self.migration = migration@override- def to_error_report(self) -> ErrorReport:- report = super().to_error_report()- if self.migration is None:- return report- return report.model_copy(update={"migration": self.migration})+ def problem_facts(self) -> ProblemFacts:+ return ProblemFacts(migration=self.migration)class PipelexSetupError(PipelexError):diff --git a/pipelex/cli/agent_cli/CLAUDE.md b/pipelex/cli/agent_cli/CLAUDE.mdindex d94b02c57..b2d8a8436 100644--- a/pipelex/cli/agent_cli/CLAUDE.md+++ b/pipelex/cli/agent_cli/CLAUDE.md@@ -99,14 +99,14 @@ 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 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).+- **Error classification**: Each error carries a domain (`input`, `config`, `runtime`), a hint string, and a `retryable` flag. `agent_error()` reads them **code-first**: a `PipelexError` cause's registry code wins, and every `PipelexError` carries one, which decides the envelope's domain (the code's own domain read through `ErrorDomain.from_problem_domain`) and its `retryable` verdict. The code, the domain and the verdict are all read off the cause's problem in the operator's view, never off `resolve_error_code()` beside it, so a cause that reports a problem it recovered across a transport boundary gives its classification together with its step. 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 hint is the advice nearest the cause along its chain (`PipelexError.advised_action()`), which only a local CLI prints and no problem carries, else the `AGENT_ERROR_HINTS` entry, else the code's next step in the operator's view, since whoever runs this CLI runs the runtime; the model, the provider and a pending migration come from the cause's problem in the operator's view (`to_problem(view=ProblemView.OPERATOR)`, its `diagnostics`), and `validation_errors` from the first `ValidateBundleError` on the chain. 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 cause's chain advises no action, 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 code-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 code, 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 class and message, found with `find_root_fault()`, never the router wrapper right under the run error); the code and the location come from the run error's problem, which is its root fault's. When the domain a class reports is wrong, the class needs another code, never a dict entry. An HTTP surface answers the problem's own status, the one its code declares in the registry — see [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()`.- **File convention**: Generated outputs go to `mthds-wip/` with incremental naming (`pipeline_01/`, `pipeline_02/`). A `run` writes into a new numbered folder, `results/<pipe_code>_output_<NN>/`, made by `make_run_output_folder` (`pipelex/cli/commands/run/_run_output_folder.py`) beside the bundle it ran, else under `mthds-wip/`; the folder holds a `.gitignore` of `*`, so a run's outputs never join the method tree and two runs read the same tree, with the same `method_tree_digest`. `run_pipeline_core`'s `output_dir_override` replaces the directory the folder is made under: `run method` on a fetched target (a method address or GitHub URL) passes `results/` under the caller's CWD, since the fetched clone is an ephemeral temp dir deleted at process exit, and `run bundle <folder> --pipe` passes the folder's `results/`, having no entry bundle to write beside.-- **Validate refusals are verdicts**: the `validate` commands run their library load inside `translate_to_validate_bundle_error` (`pipelex/pipeline/validate_bundle_translation.py`), so every input-domained refusal raised while loading a bundle, the unknown model (`PipeOperatorModelChoiceError`, an `unknown_model` item) included, reaches the command as a `ValidateBundleError` and leaves with the invalid-verdict envelope and exit 1. No `validate` command keeps an arm of its own for a model-choice error; exit 2 stays for a failure of the tool or its environment (config, runtime, security).-- **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.+- **Validate refusals of the method are verdicts**: the `validate` commands run their library load inside `translate_to_validate_bundle_error` (`pipelex/pipeline/validate_bundle_translation.py`), so every refusal raised while loading a bundle whose code is in the `method` domain, the unknown model (`PipeOperatorModelChoiceError`, an `unknown_model` item) included, reaches the command as a `ValidateBundleError` and leaves with the invalid-verdict envelope and exit 1. A refusal of another actor, the request's or the input's included, keeps its own class and code, and so does a dry run none of whose failures is the method's. No `validate` command keeps an arm of its own for a model-choice error; exit 2 stays for a failure of the tool or its environment (config, runtime, security).+- **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 into the envelope the `validation_errors` of the first verdict on the cause's chain of Pipelex errors (`_chain_validation_error_items`, over `iter_pipelex_cause_chain`), so a foreign exception raised while handling an earlier verdict lists none of its items. `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 tree past its limits or a symbolic link in the tree is a `ValidateBundleError` too, while a folder with no single `main_pipe` is the run's own refusal, a `MethodEntryError` coded `request.pipe_unspecified` or `request.pipe_ambiguous`, no verdict on a method that may be valid. 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 the `MethodEntryError` with exit 1 on both, coded `request.pipe_unspecified` or `request.pipe_ambiguous`, the message the same, and no verdict on a method that may be valid. 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`, 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.diff --git a/pipelex/cli/agent_cli/commands/agent_output.py b/pipelex/cli/agent_cli/commands/agent_output.pyindex bdc4f04b6..0e6c177a0 100644--- a/pipelex/cli/agent_cli/commands/agent_output.py+++ b/pipelex/cli/agent_cli/commands/agent_output.py@@ -29,7 +29,9 @@ import typerfrom pipelex_sdk.errors import ApiResponseErrorfrom pydantic import ValidationError-from pipelex.base_exceptions import PipelexError, ValidationErrorItem, iter_cause_chain+from pipelex.base_exceptions import ErrorDomain, PipelexError, ValidationErrorItem, iter_cause_chain, iter_pipelex_cause_chain+from pipelex.cogt.exceptions import find_inference_error_category_in_chain+from pipelex.errors.problem import ProblemViewfrom pipelex.hosted.error_rendering import hosted_refusal_message, hosted_refusal_next_step, sent_verdictfrom pipelex.pipe_run.located_failure import find_root_faultfrom pipelex.pipeline.exceptions import PipelineExecutionError, ValidateBundleError@@ -66,16 +68,16 @@ def get_agent_cli_error_format() -> CliOutputFormat:# Fallback error-classification lookups, keyed by error_type name.#-# 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() reads error_domain / retryable from a PipelexError cause's registry+# code first, and every PipelexError carries one, which decides its domain and its+# retry verdict, and its hint from the advice along the cause's chain. 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.+# still name a PipelexError subclass: a hint is read only when the cause's chain+# advises no action. 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 = (@@ -200,17 +202,17 @@ def _assemble_error_payload(message: str, *, error_type: str, cause: BaseExcepti"""Build the structured error payload shared by the JSON and markdown renderers.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 cannot+ ``model`` / ``provider`` from a ``PipelexError`` cause first: its code, its chain's advice and+ its problem in the operator's view, falling back to the lookup dicts for error types that cannotself-describe. ``extra`` is merged last and overrides everything.- ``migration`` comes from the report too, and it is the one field here that an agent is meant- to *act* on rather than classify by: its presence says the configuration is stale rather than- wrong, and the loop it opens is ``pipelex-agent migrate --dry-run --format json`` followed by- ``--yes``. Emitted only when the report carries one, so branching on its presence is the+ ``migration`` comes from the problem's diagnostics too, and it is the one field here that an agent+ is meant to *act* on rather than classify by: its presence says the configuration is stale rather+ than wrong, and the loop it opens is ``pipelex-agent migrate --dry-run --format json`` followed by+ ``--yes``. Emitted only when the error carries one, so branching on its presence is thewhole test.- ``validation_errors`` comes from the report as well, whenever it carries any: a command that+ ``validation_errors`` comes from the cause's chain as well, whenever a verdict on it carries any: a command thatrefuses an invalid bundle (a run refused before any pipe ran, for one) hands the agent the samelocated items ``validate`` gives, each with its pipe, its field and its fix, rather than only thesummary sentence. They are the items :func:`extract_validation_errors` projects, dumped the same way.@@ -221,8 +223,9 @@ def _assemble_error_payload(message: str, *, error_type: str, cause: BaseExcepti"message": message,}- # Extract structured data from PipelexError.to_error_report() when available+ # Extract structured data from a PipelexError cause when available: its code decides the domain and the verdictreport_hint: str | None = None+ report_next_step: str | None = Nonereport_retryable: bool | None = Nonereport_category: str | None = Nonereport_domain: str | None = None@@ -230,23 +233,30 @@ def _assemble_error_payload(message: str, *, error_type: str, cause: BaseExceptireport_extras: dict[str, Any] = {}if isinstance(cause, PipelexError):- report = cause.to_error_report()- report_hint = report.user_action_detail()- report_retryable = report.retryable- report_category = report.error_category- report_domain = report.error_domain- report_code = report.code- if report.model:- report_extras["model"] = report.model- if report.provider:- report_extras["provider"] = report.provider- if report.migration is not None:- report_extras["migration"] = report.migration.model_dump(mode="json")- if report.validation_errors:- report_extras["validation_errors"] = [item.model_dump(mode="json", exclude_none=True) for item in report.validation_errors]-- # hint: report-first, fallback to lookup dict- hint = report_hint or AGENT_ERROR_HINTS.get(error_type)+ # Every classification is read off the one problem, so a cause that reports a problem of its own, such as one+ # recovered across a transport boundary, gives its code, its domain and its verdict together with its step.+ problem = cause.to_problem(view=ProblemView.OPERATOR)+ advised_action = cause.advised_action()+ report_hint = advised_action.detail if advised_action is not None and advised_action.detail else None+ # The code's next step, as the operator reads it, which whoever runs this CLI is: the hint when nothing advises.+ report_next_step = problem.next_step.detail+ report_retryable = problem.is_retryable+ report_category = find_inference_error_category_in_chain(cause)+ report_domain = ErrorDomain.from_problem_domain(problem.effective_domain)+ report_code = problem.code+ diagnostics = problem.diagnostics+ if diagnostics is not None and diagnostics.model:+ report_extras["model"] = diagnostics.model+ if diagnostics is not None and diagnostics.provider is not None and diagnostics.provider.name:+ report_extras["provider"] = diagnostics.provider.name+ if diagnostics is not None and diagnostics.migration is not None:+ report_extras["migration"] = diagnostics.migration.model_dump(mode="json")+ chain_validation_errors = _chain_validation_error_items(error=cause)+ if chain_validation_errors:+ report_extras["validation_errors"] = [item.model_dump(mode="json", exclude_none=True) for item in chain_validation_errors]++ # hint: the chain's advice, else the lookup dict, else the code's next step+ hint = report_hint or AGENT_ERROR_HINTS.get(error_type) or report_next_stepif hint:error_json["hint"] = hint@@ -450,12 +460,23 @@ def run_failure_fields(*, error: PipelineExecutionError) -> dict[str, Any]:fields["cause_type"] = type(cause).__name__fields["cause_message"] = str(cause)else:- root_report = root_fault.to_error_report()- fields["cause_type"] = root_report.error_type- fields["cause_message"] = root_report.message+ fields["cause_type"] = type(root_fault).__name__+ fields["cause_message"] = root_fault.messagereturn fields+def _chain_validation_error_items(*, error: BaseException) -> list[ValidationErrorItem]:+ """The items of the first invalid verdict along ``error``'s cause chain, ``error`` itself included; empty when none.++ The walk stops at the first exception that is not a Pipelex error, as every walk reading a failure's chain does: a+ foreign exception raised from an earlier, handled verdict is a new failure, whose envelope lists none of its items.+ """+ for node in iter_pipelex_cause_chain(error):+ if isinstance(node, ValidateBundleError):+ return node.validation_error_items()+ return []++def _non_empty_string(*, value: Any) -> str | None:"""A problem member that is a non-empty string, else ``None``."""return value if isinstance(value, str) and value else None@@ -558,7 +579,7 @@ def extract_validation_errors(exc: ValidateBundleError) -> list[dict[str, Any]]:"""Project a ``ValidateBundleError`` into the CLI ``validation_errors`` JSON array.Thin adapter over ``ValidateBundleError.validation_error_items`` — the shared builder,- same one feeding the API 422's ``ErrorReport.validation_errors`` — so the CLI+ same one feeding the ``/validate`` verdict and the problem's items — so the CLIand API structured shapes can never drift. Each typed item is dumped to aplain dict with unset fields dropped (``exclude_none``), matching themachine-first agent-CLI envelope; the entries carry ``category``,@@ -645,7 +666,7 @@ def agent_error_validate_bundle(exit_code=1,)case CliOutputFormat.MARKDOWN:- items = list(exc.to_error_report().validation_errors or [])+ items = exc.validation_error_items()markdown = _render_validate_bundle_markdown(items, bundle_path=bundle_path, library_dirs=library_dirs, allow_signatures=allow_signatures)print(markdown, file=sys.stderr)raise typer.Exit(1) from excdiff --git a/pipelex/cli/agent_cli/commands/run/bundle_cmd.py b/pipelex/cli/agent_cli/commands/run/bundle_cmd.pyindex 6ee1041a4..81ce053d4 100644--- a/pipelex/cli/agent_cli/commands/run/bundle_cmd.py+++ b/pipelex/cli/agent_cli/commands/run/bundle_cmd.py@@ -39,7 +39,7 @@ from pipelex.mthds_parsing.helpers import is_pipelex_filefrom pipelex.mthds_parsing.parser import MthdsParserfrom pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityErrorfrom pipelex.pipelex import Pipelex-from pipelex.pipeline.exceptions import PipelineExecutionError, ValidateBundleError+from pipelex.pipeline.exceptions import MethodEntryError, PipelineExecutionError, ValidateBundleErrorfrom pipelex.pipeline.validate_bundle_translation import translate_to_validate_bundle_errorif TYPE_CHECKING:@@ -142,6 +142,9 @@ def run_bundle_cmd(folder_run = resolve_method_folder_run(directory=target_path, pipe_override=pipe)except ValidateBundleError as exc:agent_error(exc.message, error_type="ValidateBundleError", cause=exc)+ except MethodEntryError as exc:+ # No pipe to start at is the run's refusal and no verdict: its envelope carries its own code.+ agent_error(exc.message, error_type="MethodEntryError", cause=exc)except PipelexConfigError as exc:# Listing the tree reads its limits from the configuration, before the boot would.report_agent_init_failure(error=exc)diff --git a/pipelex/cli/bundle_target_resolution.py b/pipelex/cli/bundle_target_resolution.pyindex 0a8fb2b29..fd4c1da38 100644--- a/pipelex/cli/bundle_target_resolution.py+++ b/pipelex/cli/bundle_target_resolution.py@@ -111,11 +111,13 @@ def resolve_method_folder(*, directory: Path, pipe_override: str | None) -> Methdef resolve_method_folder_run(*, directory: Path, pipe_override: str | None) -> MethodFolderTarget:- """A method folder as `run bundle` reads it: every refusal, the method's lack of a single entry included, is the verdict.+ """A method folder as `run bundle` reads it: every refusal of the method is the verdict.Raises:- ValidateBundleError: The tree is refused or past this machine's limits, a bundle does not parse, or the method- has no single pipe to start at, each as the invalid verdict `validate` gives.+ ValidateBundleError: The tree is refused or past this machine's limits, or a bundle does not parse, each as the+ invalid verdict `validate` gives.+ MethodEntryError: The method has no single pipe to start at and `pipe_override` names none, which is no verdict+ on the method, coded as the refusal of a run that selects no pipe."""with translate_to_validate_bundle_error():return resolve_method_folder(directory=directory, pipe_override=pipe_override)diff --git a/pipelex/cli/commands/crate_loading.py b/pipelex/cli/commands/crate_loading.pyindex 3e02d4074..d7bc8e226 100644--- a/pipelex/cli/commands/crate_loading.py+++ b/pipelex/cli/commands/crate_loading.py@@ -18,7 +18,7 @@ import typerfrom mthds.package.manifest.schema import MTHDS_STANDARD_VERSIONfrom pipelex.cli.exceptions import BundleClosureEmptyError-from pipelex.interpreter_hub import get_library_manager+from pipelex.interpreter_hub import get_library_manager, resolve_library_dirsfrom pipelex.libraries.crate_normalization import normalize_cratefrom pipelex.libraries.exceptions import LibraryLoadingErrorfrom pipelex.libraries.library_crate import LibraryCrate@@ -40,7 +40,9 @@ def load_normalized_crate(*, library_dirs: list[Path] | None) -> LibraryCrate:crate = get_library_manager().get_crate(library_id)if crate is None:msg = "no .mthds bundles found in the closure."- raise BundleClosureEmptyError(msg)+ # The local command's own directories, which the person running it named or set as defaults.+ closure_dirs, _ = resolve_library_dirs(expanded_library_dirs)+ raise BundleClosureEmptyError(msg).with_params(method_ref=", ".join(str(closure_dir) for closure_dir in closure_dirs))# CrateNormalizationError (an internal invariant) is deliberately not caught — it must surface.return normalize_crate(crate, mthds_version=MTHDS_STANDARD_VERSION)diff --git a/pipelex/cli/commands/run/bundle_cmd.py b/pipelex/cli/commands/run/bundle_cmd.pyindex 50b6c6e1f..faff9a7cb 100644--- a/pipelex/cli/commands/run/bundle_cmd.py+++ b/pipelex/cli/commands/run/bundle_cmd.py@@ -16,7 +16,7 @@ from pipelex.cli.commands.run.exceptions import AmbiguousInputsFilesError, AutoDfrom pipelex.cli.error_handlers import handle_pre_boot_config_error, handle_validate_bundle_errorfrom pipelex.hosted.exceptions import HostedRunSourceErrorfrom pipelex.mthds_parsing.helpers import is_pipelex_file-from pipelex.pipeline.exceptions import ValidateBundleError+from pipelex.pipeline.exceptions import MethodEntryError, ValidateBundleErrorif TYPE_CHECKING:from mthds.method_tree.models import MethodTree@@ -160,6 +160,11 @@ def run_bundle_cmd(folder_run = resolve_method_folder_run(directory=target_path, pipe_override=pipe)except ValidateBundleError as exc:handle_validate_bundle_error(exc, library_dirs=[Path(one_dir) for one_dir in library_dir] if library_dir else None)+ except MethodEntryError as entry_exc:+ # No pipe to start at is no verdict on the method, which may be valid: the run names none, and the message+ # names the folder's bundles by their tree paths and what each declares.+ typer.secho(f"Failed to run: {entry_exc.message}", fg=typer.colors.RED, err=True)+ raise typer.Exit(1) from entry_excexcept PipelexConfigError as exc:# Listing the tree reads its limits from the configuration, before the boot would.handle_pre_boot_config_error(exc=exc, command=COMMAND, exit_code=1)diff --git a/pipelex/cli/commands/run/exceptions.py b/pipelex/cli/commands/run/exceptions.pyindex badc192d5..cebeb5950 100644--- a/pipelex/cli/commands/run/exceptions.py+++ b/pipelex/cli/commands/run/exceptions.py@@ -1,6 +1,9 @@"""Errors raised while loading pipeline-inputs files for the run CLI surfaces."""+from typing import Any+from mthds.protocol.problem.registry import CoreCode+from typing_extensions import overridefrom pipelex.base_exceptions import PipelexErrorfrom pipelex.cogt.inference.error_classification import UserAction, UserActionKind@@ -18,8 +21,10 @@ class AmbiguousInputsFilesError(PipelexError):kind=UserActionKind.CHANGE_INPUT,detail="Pass --inputs explicitly to choose which inputs file to use",)- # The message describes a fault in the caller's own bundle directory — caller-facing copy.- _authors_caller_facing_message = True++ @override+ def problem_params(self) -> dict[str, Any]:+ return {"field": "inputs"}class AutoDetectedInputsFileError(PipelexError):@@ -35,5 +40,7 @@ class AutoDetectedInputsFileError(PipelexError):kind=UserActionKind.CHANGE_INPUT,detail="Replace it with the file itself, or name the inputs file with --inputs <path>",)- # The message describes a fault in the caller's own bundle directory — caller-facing copy.- _authors_caller_facing_message = True++ @override+ def problem_params(self) -> dict[str, Any]:+ return {"field": "inputs"}diff --git a/pipelex/cli/dev_cli/commands/error_registry/codes_generator.py b/pipelex/cli/dev_cli/commands/error_registry/codes_generator.pyindex 14639681d..baa3d0805 100644--- a/pipelex/cli/dev_cli/commands/error_registry/codes_generator.py+++ b/pipelex/cli/dev_cli/commands/error_registry/codes_generator.py@@ -208,55 +208,90 @@ def _params_class(*, registry: ErrorRegistryDocument, entry: RegistryEntry, imporeturn lines+def _string_argument_lines(*, name: str, text: str, indent: str) -> list[str]:+ """A keyword argument holding a string, on one line when it fits, else as an implicit concatenation of word runs.++ ``ruff format`` keeps a parenthesized concatenation whose joined form does not fit on one line, and joins one+ that does, so the text is split only when its one-line form runs past the line length, which keeps the+ generated module as the formatter leaves it.+ """+ one_line = f"{indent}{name}={json.dumps(text)},"+ if len(one_line) <= _LINE_LENGTH:+ return [one_line]+ part_indent = f"{indent} "+ room = _LINE_LENGTH - len(part_indent) - 2+ parts: list[str] = []+ current = ""+ for word in text.split(" "):+ candidate = f"{current} {word}" if current else word+ if current and len(json.dumps(candidate + " ")) > room:+ parts.append(current + " ")+ current = word+ else:+ current = candidate+ parts.append(current)+ return [f"{indent}{name}=(", *(f"{part_indent}{json.dumps(part)}" for part in parts), f"{indent}),"]++def _entries_lines(*, registry: ErrorRegistryDocument) -> list[str]:- """The lines declaring ``PipelexErrorEntry`` and ``PIPELEX_ERROR_ENTRIES``, every code's title and verdict.+ """The lines declaring ``PipelexErrorEntry`` and ``PIPELEX_ERROR_ENTRIES``, every code's title, verdict and templates.- 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.+ The runtime reads a code's title, domain, retry verdict, status, step kinds and templates from this table+ rather than from the snapshot, so that classifying an error and rendering its problem 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.',+ ' """What the registry declares about a Pipelex code that classifying an error and rendering its problem need.',""," 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.",+ " detail: The template of the sentence that states one occurrence, naming parameters as ``{name}``."," actor_step: The kind of the step aimed at the domain's actor.",+ " actor_step_detail: The template of the sentence of the step aimed at the domain's actor."," other_step: The kind of the step aimed at any other reader.",+ " other_step_detail: The template of the sentence of the step aimed at any other reader.",' """',""," title: str"," domain: str"," retry: str"," status: int | None",+ " detail: str"," actor_step: str",+ " actor_step_detail: str"," other_step: str",+ " other_step_detail: str","","","PIPELEX_ERROR_ENTRIES: dict[PipelexErrorCode, PipelexErrorEntry] = {",]+ argument_indent = " "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.append(f" PipelexErrorCode.{member_name}: PipelexErrorEntry(")+ lines.extend(_string_argument_lines(name="title", text=title, indent=argument_indent))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))},",- " ),",+ f"{argument_indent}domain={json.dumps(str(entry.domain))},",+ f"{argument_indent}retry={json.dumps(str(entry.retry))},",+ f"{argument_indent}status={entry.status},",])+ lines.extend(_string_argument_lines(name="detail", text=entry.detail, indent=argument_indent))+ lines.append(f"{argument_indent}actor_step={json.dumps(str(entry.steps.actor.kind))},")+ lines.extend(_string_argument_lines(name="actor_step_detail", text=entry.steps.actor.detail, indent=argument_indent))+ lines.append(f"{argument_indent}other_step={json.dumps(str(entry.steps.other.kind))},")+ lines.extend(_string_argument_lines(name="other_step_detail", text=entry.steps.other.detail, indent=argument_indent))+ lines.append(" ),")lines.append("}")- lines.append('"""The title and verdict of every Pipelex code."""')+ lines.append('"""The title, verdict and templates of every Pipelex code."""')return linesdiff --git a/pipelex/cli/error_handlers.py b/pipelex/cli/error_handlers.pyindex bbe95242b..a54aba568 100644--- a/pipelex/cli/error_handlers.py+++ b/pipelex/cli/error_handlers.py@@ -9,7 +9,7 @@ from rich.console import Consolefrom rich.markup import escapefrom rich.traceback import Traceback-from pipelex.base_exceptions import PipelexConfigError, ValidationErrorCategory, ValidationErrorItem, error_domain_is_input, iter_cause_chain+from pipelex.base_exceptions import ErrorDomain, PipelexConfigError, PipelexError, ValidationErrorCategory, ValidationErrorItem, iter_cause_chainfrom pipelex.cogt.exceptions import ModelDeckPresetValidationErrorfrom pipelex.core.pipes.exceptions import PipeOperatorModelChoiceErrorfrom pipelex.migration.exceptions import FormerReleaseConfigError@@ -47,6 +47,14 @@ class ErrorContext(StrEnum):_traceback_requested: ContextVar[bool] = ContextVar("pipelex_cli_traceback_requested", default=False)+def _advice_detail(*, error: PipelexError) -> str | None:+ """The advice nearest the error along its cause chain, which a panel prints as its tip; ``None`` when none advises."""+ advised_action = error.advised_action()+ if advised_action is None or not advised_action.detail:+ return None+ return advised_action.detail++def set_traceback_requested(*, value: bool) -> None:"""Record whether --traceback was passed, independent of the Click context."""_traceback_requested.set(value)@@ -137,8 +145,7 @@ def handle_model_choice_error(exc: PipeOperatorModelChoiceError, *, context: Err"""console = get_console()print_traceback_if_requested(console=console)- report = exc.to_error_report()- tip = report.user_action_detail() or (+ tip = _advice_detail(error=exc) or (f"Check your model configuration in .pipelex/inference/ or specify a different model in the '{exc.pipe_code}' pipe.")display_error_panel(@@ -171,7 +178,6 @@ def handle_model_availability_error(exc: PipeOperatorModelAvailabilityError, *,"""console = get_console()print_traceback_if_requested(console=console)- report = exc.to_error_report()fields: list[tuple[str, str]] = [("Pipe", f"[yellow]'{escape(exc.pipe_code)}'[/yellow] [dim]({escape(exc.pipe_type)})[/dim]"),("Model", f"[yellow]'{escape(exc.model_handle or '')}'[/yellow]"),@@ -193,11 +199,11 @@ def handle_model_availability_error(exc: PipeOperatorModelAvailabilityError, *,"backend it routes to (see '.pipelex/inference/routing_profiles.toml') is enabled in '.pipelex/inference/backends.toml', ""and that you have the necessary credentials")- user_action_detail = report.user_action_detail()+ user_action_detail = _advice_detail(error=exc)tip: strif user_action_detail is None:tip = f"{local_deck_remedy}, or specify a different model in the '{exc.pipe_code}' pipe."- elif error_domain_is_input(report.error_domain):+ elif ErrorDomain.from_problem_domain(exc.resolve_domain()).is_input:# The method named a model no entry of the deck names, and the lookup's next step is to# change it. A local deck can also be what lacks that model, so the local remedy follows.tip = f"{user_action_detail}\n{local_deck_remedy}."@@ -241,7 +247,6 @@ def handle_model_deck_preset_error(exc: ModelDeckPresetValidationError, *, conte"""console = get_console()print_traceback_if_requested(console=console)- report = exc.to_error_report()model_handle = exc.model_handle or ""fields: list[tuple[str, str]] = [("Preset ID", f"[yellow]'{escape(exc.preset_id)}'[/yellow]"),@@ -252,7 +257,7 @@ def handle_model_deck_preset_error(exc: ModelDeckPresetValidationError, *, contebackends_str = ", ".join([f"[yellow]{escape(backend)}[/yellow]" for backend in sorted(exc.enabled_backends)])fields.append(("Enabled Backends", backends_str))- tip_detail = report.user_action_detail()+ tip_detail = _advice_detail(error=exc)if tip_detail is not None:tip = escape(tip_detail)else:@@ -380,8 +385,7 @@ def handle_validate_bundle_error(allow_signatures: Whether the invocation accepted PipeSignature placeholders; when true,the actionable fix command preserves the same leniency."""- report = exc.to_error_report()- items = list(report.validation_errors or [])+ items = exc.validation_error_items()console = get_console()print_traceback_if_requested(console=console)console.print("\n[bold red]❌ Bundle validation failed[/bold red]\n")@@ -401,7 +405,7 @@ def handle_validate_bundle_error(f"[bold green]💡 {fixable_count} of these errors can be fixed automatically[/bold green] — run: [cyan]{escape(fix_command)}[/cyan]")else:- tip = report.user_action_detail() or (+ tip = _advice_detail(error=exc) or ("Review the error messages above and check your pipeline configuration. ""Make sure all required fields are present and correctly formatted.")diff --git a/pipelex/codegen/check.py b/pipelex/codegen/check.pyindex e56cd0286..5f26fa5d2 100644--- a/pipelex/codegen/check.py+++ b/pipelex/codegen/check.py@@ -99,7 +99,7 @@ def run_codegen_check(*, root: Path) -> CodegenCheckReport:raiseexcept CodegenError as exc:msg = f"Unsafe codegen artifact tree at '{root}': {exc}"- raise CodegenLockError(msg) from exc+ raise CodegenLockError(msg).with_params(file=CODEGEN_LOCK_FILENAME) from excdef _check_locked_artifacts(*, root: Path, lock: CodegenLock) -> list[CodegenDrift]:diff --git a/pipelex/codegen/lock.py b/pipelex/codegen/lock.pyindex d79915649..abbb86896 100644--- a/pipelex/codegen/lock.py+++ b/pipelex/codegen/lock.py@@ -214,7 +214,7 @@ def load_lock(lock_path: Path) -> CodegenLock | None:# ValidationError on a shape mismatch (UnicodeDecodeError is a ValueError subclass);# OSError = the lock exists but cannot be read.msg = f"Malformed or unsafe codegen lock at '{lock_path}': {exc}"- raise CodegenLockError(msg) from exc+ raise CodegenLockError(msg).with_params(file=lock_path.name) from excdef _reject_unknown_lock_version(*, data: dict[str, Any], lock_path: Path) -> None:@@ -240,4 +240,7 @@ 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).with_error_code(PipelexErrorCode.CODEGEN_LOCK_UNSUPPORTED)+ unsupported = CodegenLockError(msg).with_error_code(PipelexErrorCode.CODEGEN_LOCK_UNSUPPORTED)+ if is_version_number:+ unsupported.with_params(lock_version=raw_version)+ raise unsupporteddiff --git a/pipelex/cogt/content_generation/doc_gen_generate.py b/pipelex/cogt/content_generation/doc_gen_generate.pyindex fc8b65803..b0245e917 100644--- a/pipelex/cogt/content_generation/doc_gen_generate.py+++ b/pipelex/cogt/content_generation/doc_gen_generate.py@@ -229,7 +229,11 @@ 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).with_error_code(PipelexErrorCode.DOCGEN_TEMPLATE_INVALID) from exc+ raise (+ DocGenRenderError(msg)+ .with_error_code(PipelexErrorCode.DOCGEN_TEMPLATE_INVALID)+ .with_params(template=template_file.name, reason="unreadable", finding="the file is not UTF-8 text")+ ) 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 3c8357656..d66405820 100644--- a/pipelex/cogt/content_generation/exceptions.py+++ b/pipelex/cogt/content_generation/exceptions.py@@ -17,7 +17,6 @@ class MockUsageOnLiveRunError(PipelexError, ValueError):"""error_code = CoreCode.REQUEST_INVALID- _authors_caller_facing_message = Trueclass UnsafeSchemaError(SecurityError):@@ -48,9 +47,6 @@ class DryRunObjectFidelityError(PipelexError):# 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@classmethoddef for_object_class(cls, object_class_name: str) -> "DryRunObjectFidelityError":@@ -80,9 +76,6 @@ class OutputStructureSchemaError(PipelexError):# 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@classmethoddef for_object_class(cls, *, object_class_name: str, reason: str) -> "OutputStructureSchemaError":@@ -112,9 +105,6 @@ class DryRunMockBuildError(PipelexError):# 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 = True@classmethoddef for_object_class(cls, object_class_name: str) -> "DryRunMockBuildError":diff --git a/pipelex/cogt/doc_gen/exceptions.py b/pipelex/cogt/doc_gen/exceptions.pyindex fcb930acf..59281dde5 100644--- a/pipelex/cogt/doc_gen/exceptions.py+++ b/pipelex/cogt/doc_gen/exceptions.py@@ -1,7 +1,9 @@from enum import StrEnum+from typing import Anyfrom mthds.method_tree.vocabulary import TreeRefusalCodefrom mthds.protocol.problem.registry import CoreCode+from typing_extensions import overridefrom pipelex.base_exceptions import PipelexErrorfrom pipelex.cogt.doc_gen.doc_gen_format import DocGenFormat, DocGenSource, doc_gen_choice_key@@ -36,6 +38,17 @@ class DocGenEngineGap(StrEnum):NOT_REGISTERED = "not_registered""""The engine's model is declared, and no installed plugin registers a worker for its sdk."""+ @property+ def desc(self) -> str:+ """What is missing, as the operator's step names it after the engine."""+ match self:+ case DocGenEngineGap.NO_DEFAULT:+ return "the model deck names no default engine for the format"+ case DocGenEngineGap.NOT_DECLARED:+ return "its model is not declared in this installation"+ case DocGenEngineGap.NOT_REGISTERED:+ return "no installed plugin registers a worker for it"+def _step_label(*, pipe_code: str | None) -> str:return f"PipeDocGen '{pipe_code}'" if pipe_code else "A PipeDocGen step"@@ -57,7 +70,6 @@ class DocGenEngineMissingError(PipelexError):"""error_code = PipelexErrorCode.DOCGEN_ENGINE_UNAVAILABLE- _authors_caller_facing_message = Truedef __init__(self,@@ -102,6 +114,12 @@ class DocGenEngineMissingError(PipelexError):message = f"{asks}, on the engine '{model}', which is not installed in this runtime. {comes_with_the_plugin}"super().__init__(message)+ @override+ def problem_params(self) -> dict[str, Any]:+ # The engine and the gap are the operator's own facts, operator-only parameters of the code.+ engine = self.model or f"default engine for {self.doc_gen_format.with_article} {self.source.desc}"+ return {"format": self.doc_gen_format, "engine": engine, "gap": self.gap.desc}+class DocGenModelCapabilityError(PipelexError):"""The document engine a `PipeDocGen` step names does not print the step's format from its source.@@ -111,7 +129,6 @@ class DocGenModelCapabilityError(PipelexError):"""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):self.doc_gen_format = doc_gen_format@@ -124,6 +141,10 @@ class DocGenModelCapabilityError(PipelexError):)super().__init__(message)+ @override+ def problem_params(self) -> dict[str, Any]:+ return {"model": self.model, "capability": f"printing {self.doc_gen_format.with_article} {self.source.desc}"}+class DocGenRenderError(PipelexError):"""A document engine could not print a render job.@@ -133,8 +154,8 @@ class DocGenRenderError(PipelexError):render 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;+ out (an element taller than a page, an image that is not one), whose raise site gives the code's ``reason`` and+ ``element`` parameters; ``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 notname; ``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,@@ -165,7 +186,6 @@ class MarkdownFormattingBudgetError(PipelexError):"""error_code = CoreCode.INPUT_TOO_LARGE- _authors_caller_facing_message = Trueclass TemplateUrlRefusedError(PipelexError):@@ -193,7 +213,6 @@ class TemplateUrlRefusedError(PipelexError):"""error_code = CoreCode.SECURITY_METHOD_PATH_REFUSED- _authors_caller_facing_message = Truedef __init__(self, message: str, *, refusal_code: TreeRefusalCode | None):super().__init__(message)diff --git a/pipelex/cogt/exceptions.py b/pipelex/cogt/exceptions.pyindex 8edfe6402..71ef8c767 100644--- a/pipelex/cogt/exceptions.py+++ b/pipelex/cogt/exceptions.py@@ -1,19 +1,20 @@from __future__ import annotationsfrom enum import StrEnum-from typing import TYPE_CHECKING, ClassVar, NamedTuple+from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple-from mthds.protocol.problem.registry import CoreCode+from mthds.protocol.problem.registry import CoreCode, ModelUnavailableReasonfrom typing_extensions import override-from pipelex.base_exceptions import ErrorReport, PipelexError, iter_cause_chain+from pipelex.base_exceptions import PipelexError, ProblemFacts, iter_cause_chainfrom pipelex.cogt.inference.error_classification import ProviderErrorMetadata, UserAction, UserActionKind+from pipelex.cogt.model_backends.model_type import ModelTypefrom pipelex.cogt.models.model_reference import ModelReferenceKindfrom pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeDeclaration, ErrorCodeSet, InheritsCause, declared_error_codes+from pipelex.errors.problem import ProviderDiagnostics, cap_problem_textfrom pipelex.errors.registry.pipelex_codes import PipelexErrorCodeif TYPE_CHECKING:- from pipelex.cogt.model_backends.model_type import ModelTypefrom pipelex.errors.error_codes import ErrorCode@@ -186,7 +187,7 @@ class CogtError(PipelexError):(``LLMCompletionError``, ``ImgGenGenerationError``, ...) carry no modelor provider of their own. Each worker family calls this at itspublic-method chokepoint — where model and provider are unambiguously- known — so the eventual ``ErrorReport`` can attribute the failure.+ known — so the eventual problem can attribute the failure.Never overwrites a value an inner error already set (e.g.``LLMModelNotFoundError`` setting its own ``model_handle``), and skips@@ -199,27 +200,36 @@ class CogtError(PipelexError):self.backend_name = backend_name@override- def to_error_report(self) -> ErrorReport:- # Start from the base report (which already runs cause-chain enrichment- # 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()- return base_report.model_copy(- update={- "error_category": self.error_category or base_report.error_category,- "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,- }+ def problem_params(self) -> dict[str, Any]:+ # The backend the failure was met on is the component an operator configures (`runtime.misconfigured`, operator-only).+ return {"component": self.backend_name} if self.backend_name is not None else {}++ @override+ def problem_facts(self) -> ProblemFacts:+ """The model and the provider this failure names, what the provider answered, and how long it asked to wait.++ Each fact is the nearest one set along the cause chain (``PipelexError.chain_facts``), so a wrapper that+ set a fact overrides its cause's, and one that did not leaves the cause's in place; the provider is merged+ member by member, so a wrapper naming the backend keeps the status its cause recorded. The provider's answer+ rides only the operator's diagnostics, its message capped, since it is the provider's text and may quote+ anything the request held.+ """+ provider: ProviderDiagnostics | None = None+ metadata = self.provider_metadata+ if metadata is not None:+ provider = ProviderDiagnostics(+ name=self.backend_name,+ status=metadata.status_code,+ code=metadata.provider_error_code,+ request_id=metadata.request_id,+ message=cap_problem_text(text=metadata.message) if metadata.message else None,+ )+ elif self.backend_name is not None:+ provider = ProviderDiagnostics(name=self.backend_name)+ return ProblemFacts(+ model=self.model_handle,+ provider=provider,+ retry_after=metadata.retry_after_seconds if metadata is not None else None,)@@ -280,11 +290,6 @@ class ModelChoiceNotFoundError(CogtError):error_code = ErrorCodeSet(default=CoreCode.MODEL_UNKNOWN, others=(CoreCode.MODEL_CAPABILITY_UNSUPPORTED,))error_category = InferenceErrorCategory.CONFIGURATION- # 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__(self,@@ -322,6 +327,11 @@ class ModelChoiceNotFoundError(CogtError):super().__init__(message=full_message)+ @override+ def problem_params(self) -> dict[str, Any]:+ suggestions = self.suggestions + self.cross_collection_suggestions+ return {**super().problem_params(), "model": self.model_choice, "model_type": self.model_type, "suggestions": suggestions or None}+class ModelDeckChoiceUnresolvedError(ModelChoiceNotFoundError):"""A model choice the model deck names itself, a default or an override, that the deck does not resolve.@@ -330,8 +340,8 @@ class ModelDeckChoiceUnresolvedError(ModelChoiceNotFoundError):reference reaches the deck's lookup as a method's own does: a step that names no model runs on the deck's defaultor 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+ with the reason ``not_served``, 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 theoperator, so it is not caller-facing.It is still a model choice the deck does not resolve, so a handler that skips an unresolvable choice, such as the@@ -340,7 +350,6 @@ class ModelDeckChoiceUnresolvedError(ModelChoiceNotFoundError):error_code = ErrorCodeSet(default=PipelexErrorCode.CONFIG_INVALID, others=(CoreCode.MODEL_UNAVAILABLE,))error_category = InferenceErrorCategory.CONFIGURATION- _authors_caller_facing_message = Falsedef __init__(self, *, deck_setting: str, unresolved: ModelChoiceNotFoundError):self.deck_setting = deck_setting@@ -366,6 +375,11 @@ class ModelDeckChoiceUnresolvedError(ModelChoiceNotFoundError):case ModelReferenceKind.PRESET | ModelReferenceKind.ALIAS | ModelReferenceKind.WATERFALL:pass+ @override+ def problem_params(self) -> dict[str, Any]:+ # The reason `model.unavailable` declares: no backend of this deployment serves the handle the deck names.+ return {**super().problem_params(), "reason": ModelUnavailableReason.NOT_SERVED}+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."""@@ -524,11 +538,10 @@ class LLMSettingRefusedError(LLMCapabilityError):"""A worker's refusal of an LLM setting, worded for the caller who wrote the setting.Its message names the model by its deck handle, never by the SDK, backend or provider model id a- worker's own refusal carries, so a validation verdict can show it under strict disclosure.+ worker's own refusal carries, so a validation verdict can show it to whoever wrote the setting."""error_code = CoreCode.MODEL_CAPABILITY_UNSUPPORTED- _authors_caller_facing_message = Trueclass LLMCompletionError(CogtError):@@ -598,7 +611,6 @@ class LLMCompletionTruncatedError(LLMCompletionError):error_code = ErrorCodeSet(default=CoreCode.MODEL_OUTPUT_TRUNCATED, others=(CoreCode.MODEL_CONTEXT_EXCEEDED,))error_category = InferenceErrorCategory.CONTENT- _authors_caller_facing_message = Truedef __init__(self,@@ -689,6 +701,16 @@ class LLMCompletionTruncatedError(LLMCompletionError):self.output_tokens = output_tokensself.max_tokens_ceiling = max_tokens_ceiling+ @override+ def problem_params(self) -> dict[str, Any]:+ return {+ **super().problem_params(),+ "pipe": self.pipe_code,+ "model": self.model_handle,+ "max_tokens": self.max_tokens,+ "output_tokens": self.output_tokens,+ }+class LLMCompletionRefusedError(LLMCompletionError):"""A text completion the model declined to write, or that a provider's safety filter stopped.@@ -703,7 +725,6 @@ class LLMCompletionRefusedError(LLMCompletionError):error_code = CoreCode.MODEL_CONTENT_REFUSEDerror_category = InferenceErrorCategory.CONTENT- _authors_caller_facing_message = Truedef __init__(self, *, model_handle: str, stop_reason: str, pipe_code: str | None = None):subject = f"the text of pipe '{pipe_code}'" if pipe_code else "its text"@@ -817,13 +838,12 @@ class ImgGenOutputTruncatedError(ImgGenGenerationError):holds no image (a Gemini candidate whose finish reason is `MAX_TOKENS`), instead of reading it as an empty answer.It is ``model.output_truncated``, and not retryable: the same request stops at the same limit. The worker sends nooutput limit of its own, so the limit is the model's, which the image and the model's thinking share, and the- next step is a simpler prompt or another model, never a setting of the pipe's. The message names only the model's- deck handle and the provider's stop value, so it is kept verbatim for the caller.+ advice its `user_action` gives is a simpler prompt or another model, never a setting of the pipe's. The message,+ for the operator, names only the model's deck handle and the provider's stop value."""error_code = CoreCode.MODEL_OUTPUT_TRUNCATEDerror_category = InferenceErrorCategory.CONTENT- _authors_caller_facing_message = Truedef __init__(self, *, model_handle: str, stop_reason: str):next_step = "Simplify the image prompt, or choose another image model."@@ -927,7 +947,6 @@ class JudgmentRefusedError(CogtError):error_code = CoreCode.MODEL_CONTENT_REFUSEDerror_category = InferenceErrorCategory.CONTENT- _authors_caller_facing_message = Truedef __init__(self, *, pipe_code: str | None, model_handle: str, question_name: str | None = None):step = f"PipeJudge '{pipe_code}'" if pipe_code else "This judgment"@@ -968,7 +987,6 @@ class JudgmentModelMissingError(PipelexError):"""error_code = CoreCode.MODEL_UNSPECIFIED- _authors_caller_facing_message = Truedef __init__(self, *, pipe_code: str | None = None):self.pipe_code = pipe_code@@ -979,6 +997,10 @@ class JudgmentModelMissingError(PipelexError):)super().__init__(message)+ @override+ def problem_params(self) -> dict[str, Any]:+ return {"pipe": self.pipe_code, "model_type": ModelType.JUDGMENT}+class RoutingProfileLibraryNotFoundError(CogtError):error_code = PipelexErrorCode.CONFIG_INVALID@@ -1065,6 +1087,11 @@ class InferenceBackendCredentialsError(CogtError):case InferenceBackendCredentialsErrorType.NOT_RESOLVED_ON_KEYLESS_BOOT:self.with_error_code(CoreCode.RUNTIME_MISCONFIGURED)+ @override+ def problem_params(self) -> dict[str, Any]:+ # Operator-only parameters of its codes: they reach the operator's step and diagnostics alone.+ return {"variable": self.key_name, "backend": self.backend_name, "component": self.backend_name}+class InferenceBackendLibraryError(CogtError):"""A backend the library cannot load.diff --git a/pipelex/cogt/llm/llm_worker_abstract.py b/pipelex/cogt/llm/llm_worker_abstract.pyindex 390ba5462..af4c19dab 100644--- a/pipelex/cogt/llm/llm_worker_abstract.py+++ b/pipelex/cogt/llm/llm_worker_abstract.py@@ -4,7 +4,7 @@ import sysfrom abc import ABC, abstractmethodfrom typing import TYPE_CHECKING, Any-from mthds.protocol.problem.registry import CoreCode+from mthds.protocol.problem.registry import CoreCode, ModelContextExceededLimitfrom opentelemetry import tracefrom opentelemetry.trace import NonRecordingSpan, Span, SpanContext, SpanKind, Status, StatusCode, TraceFlagsfrom typing_extensions import override@@ -99,7 +99,7 @@ class LLMWorkerAbstract(InferenceWorkerAbstract, ABC):returnif job_params.reasoning_effort is not None or job_params.reasoning_budget is not None:msg = f"Model '{inference_model.desc}' does not support reasoning (thinking_mode=none)"- raise LLMCapabilityError(msg)+ raise LLMCapabilityError(msg).with_params(capability="reasoning")@classmethoddef constrained_job_params(cls, *, inference_model: InferenceModelSpec, job_params: LLMJobParams) -> LLMJobParams | None:@@ -566,13 +566,17 @@ class LLMWorkerAbstract(InferenceWorkerAbstract, ABC):if llm_job.llm_prompt.user_images:if not self.inference_model.is_vision_supported:msg = f"LLM Engine '{self.inference_model.tag}' does not support vision."- raise LLMCapabilityError(msg)+ raise LLMCapabilityError(msg).with_params(capability="images")nb_images = len(llm_job.llm_prompt.user_images)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).with_error_code(CoreCode.MODEL_CONTEXT_EXCEEDED)+ raise (+ LLMCapabilityError(msg)+ .with_error_code(CoreCode.MODEL_CONTEXT_EXCEEDED)+ .with_params(limit=ModelContextExceededLimit.PROMPT_IMAGES, count=nb_images, max=max_prompt_images)+ )check_prompt_images_are_images(model_name=self.inference_model.name, prompt_images=llm_job.llm_prompt.user_images)@@ -582,7 +586,7 @@ class LLMWorkerAbstract(InferenceWorkerAbstract, ABC):if not self.inference_model.is_document_supported:msg = f"LLM Engine '{self.inference_model.tag}' does not support documents."- raise LLMCapabilityError(msg)+ raise LLMCapabilityError(msg).with_params(capability="documents")check_prompt_documents_are_read(model_name=self.inference_model.name,diff --git a/pipelex/cogt/llm/thinking_budget.py b/pipelex/cogt/llm/thinking_budget.pyindex 571bb1f6a..a74f5445c 100644--- a/pipelex/cogt/llm/thinking_budget.py+++ b/pipelex/cogt/llm/thinking_budget.py@@ -44,7 +44,7 @@ def fit_thinking_budget(*, budget: int, max_tokens: int | None, min_budget: intf"{ceiling} remain for thinking, below the smallest thinking budget of {smallest_budget}. "f"Raise max_tokens or remove the reasoning setting.")- raise LLMCapabilityError(msg)+ raise LLMCapabilityError(msg).with_params(capability="reasoning within the step's max_tokens")fitted_budget = min(fitted_budget, ceiling)if min_budget is not None:fitted_budget = max(fitted_budget, min_budget)diff --git a/pipelex/cogt/models/model_deck.py b/pipelex/cogt/models/model_deck.pyindex 4ef993f0e..6ceb7c3c4 100644--- a/pipelex/cogt/models/model_deck.py+++ b/pipelex/cogt/models/model_deck.py@@ -2,7 +2,7 @@ from collections.abc import Callable, Container, Mappingfrom functools import partialfrom typing import NoReturn, Self, TypeVar-from mthds.protocol.problem.registry import CoreCode+from mthds.protocol.problem.registry import CoreCode, ModelUnavailableReasonfrom pydantic import Field, PrivateAttr, field_validator, model_validatorfrom pipelex import log@@ -65,7 +65,7 @@ def resolve_deck_choice(*, deck_setting: str, resolve: Callable[[], 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+ method's: ``model.unknown``. A step that names no model reaches the same lookups with the deck'sown choice, and the caller can change nothing about that, so the miss is raised again as a``ModelDeckChoiceUnresolvedError`` naming the deck's setting.@@ -1094,7 +1094,9 @@ class ModelDeck(ConfigModel):f"You must enable model fallback in your .pipelex/pipelex.toml file to permit the following fallbacks, "f"or enable a backend that supports '{ideal_model_handle}'. ")- raise ModelNotFoundError(message=msg, model_handle=waterfall_name)+ raise ModelNotFoundError(message=msg, model_handle=waterfall_name).with_params(+ model=waterfall_name, model_type=model_type, reason=ModelUnavailableReason.FALLBACK_DISABLED+ )try:inference_model = self._get_optional_inference_model(model_handle=fallback,@@ -1384,17 +1386,19 @@ class ModelDeck(ConfigModel):# 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, `model.unavailable`, and stays# redacted, with no next step.+ # The advice is the local CLI's tip; a problem's reader gets the code's own next step.+ change_model = UserAction(+ kind=UserActionKind.CHANGE_MODEL,+ detail=f"Change the model '{model_handle}' to {model_type.indefinite_description} the model deck serves.",+ )raise (- ModelNotFoundError(message=msg, model_handle=model_handle)+ ModelNotFoundError(message=msg, model_handle=model_handle, user_action=change_model).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.",- )- )+ .with_params(model=model_handle, model_type=model_type))- raise ModelNotFoundError(message=msg, model_handle=model_handle)+ raise ModelNotFoundError(message=msg, model_handle=model_handle).with_params(+ model=model_handle, model_type=model_type, reason=ModelUnavailableReason.NOT_SERVED+ )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/core/bundle_resources/bundle_resource.py b/pipelex/core/bundle_resources/bundle_resource.pyindex bc2426a89..1845685df 100644--- a/pipelex/core/bundle_resources/bundle_resource.py+++ b/pipelex/core/bundle_resources/bundle_resource.py@@ -78,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).with_error_code(CoreCode.REQUEST_INVALID)+ raise BundleResourcePathError(msg).with_error_code(CoreCode.REQUEST_INVALID).with_params(field="resources")canonical_files[canonical_path] = contentreturn canonical_filesdiff --git a/pipelex/core/bundle_resources/exceptions.py b/pipelex/core/bundle_resources/exceptions.pyindex c03c63e6c..5ac796307 100644--- a/pipelex/core/bundle_resources/exceptions.py+++ b/pipelex/core/bundle_resources/exceptions.py@@ -17,7 +17,6 @@ class BundleResourcePathError(PipelexError):"""error_code = ErrorCodeSet(default=CoreCode.SECURITY_INPUT_PATH_REFUSED, others=(CoreCode.REQUEST_INVALID,))- _authors_caller_facing_message = Trueclass BundleResourceNotNamedError(PipelexError):@@ -29,4 +28,3 @@ class BundleResourceNotNamedError(PipelexError):"""error_code = CoreCode.REQUEST_INVALID- _authors_caller_facing_message = Truediff --git a/pipelex/core/exceptions.py b/pipelex/core/exceptions.pyindex 20499d66a..5eaa3f872 100644--- a/pipelex/core/exceptions.py+++ b/pipelex/core/exceptions.py@@ -1,5 +1,8 @@+from typing import Any+from pydantic import BaseModel, Field+from pipelex.errors.error_codes import ErrorCodefrom pipelex.validation_error_types import PipeFactoryErrorType, PipeValidationErrorType@@ -164,12 +167,16 @@ class DryRunFailureErrorData(BaseModel):The dry-run sweep records one per failing pipe, located at the innermost pipe that failed: afailure that makes an enclosing controller fail for the same cause is kept once, at the pipe- where it happened. ``message`` is built from that pipe's own failure under the disclosure rule- for an item built from a raised error: the failure's own message when it is caller-facing, its- title otherwise, because the verdict that carries it is caller-facing as a whole.+ where it happened. ``code`` is the failure's own code, which decides whether the failure is the+ method's (an invalid verdict) or a fault no verdict may carry. ``message`` names the pipe and gives+ the sentence the code renders for a caller, never the failure's own message, because the verdict+ that carries it is read by the caller, and ``params`` holds the parameters that sentence was rendered+ from, so that the verdict's item renders it again whole."""+ code: ErrorCode = Field(description="The code of the pipe's failure")pipe_code: str | None = Field(default=None, description="Bare code of the pipe whose dry run failed")domain_code: str | None = Field(default=None, description="Domain of the pipe whose dry run failed")source: str | None = Field(default=None, description="Source file of the pipe, when the library knows it")- message: str = Field(description="The pipe's own failure, as the disclosure rule allows it")+ message: str = Field(description="The pipe's failure, in the sentence its code renders for a caller")+ params: dict[str, Any] | None = Field(default=None, description="The parameters the code's sentences are rendered from, those a caller may read")diff --git a/pipelex/core/memory/exceptions.py b/pipelex/core/memory/exceptions.pyindex a27d6fea6..f66bd3e44 100644--- a/pipelex/core/memory/exceptions.py+++ b/pipelex/core/memory/exceptions.py@@ -1,10 +1,13 @@-from typing import ClassVar+from typing import Any, ClassVar-from mthds.protocol.problem.registry import CoreCode+from mthds.protocol.problem.models import ProblemLocation+from mthds.protocol.problem.registry import CoreCode, InputWrongMultiplicityExpected+from typing_extensions import overridefrom pipelex.base_exceptions import PipelexErrorfrom pipelex.cogt.inference.error_classification import UserAction, UserActionKindfrom pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeDeclaration, ErrorCodeSet+from pipelex.errors.problem import make_locationfrom pipelex.tools.misc.exceptions import ContextProviderError@@ -53,22 +56,40 @@ 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. 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).+ signature. Each subclass carries an ``input.`` code (the caller can fix it).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.++ The message is the operator's diagnostics, so what the caller needs in order to act rides the problem: the input+ as the ``input`` parameter and ``location.input``, and the facts each factory knows as the parameters its code's+ template declares, such as the counts of ``input.wrong_multiplicity`` or the concepts of ``input.wrong_concept``."""error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERROR- _authors_caller_facing_message = True- def __init__(self, message: str, *, variable_name: str, user_action: UserAction | None = None):+ def __init__(+ self,+ message: str,+ *,+ variable_name: str,+ user_action: UserAction | None = None,+ shaping_params: dict[str, Any] | None = None,+ ):self.variable_name = variable_name+ self.shaping_params = dict(shaping_params or {})if user_action is not None:self.user_action = user_actionsuper().__init__(message)+ @override+ def problem_params(self) -> dict[str, Any]:+ return {"input": self.variable_name, **self.shaping_params}++ @override+ def problem_location(self) -> ProblemLocation | None:+ return make_location(input_name=self.variable_name)+class WrongScalarKindError(InputShapingError):"""A provided bare value has the wrong JSON kind for the declared concept (D5).@@ -109,6 +130,7 @@ class ListWhereSingularError(InputShapingError):variable_name: str,declared_concept_ref: str,provided_description: str,+ provided_count: int,expected_shape: str,) -> "ListWhereSingularError":message = (@@ -119,7 +141,8 @@ class ListWhereSingularError(InputShapingError):kind=UserActionKind.CHANGE_INPUT,detail=f"Provide a single value for input '{variable_name}', or declare it as a list ('{declared_concept_ref}[]') in the method.",)- return cls(message, variable_name=variable_name, user_action=user_action)+ shaping_params = {"expected": InputWrongMultiplicityExpected.SINGLE, "provided_count": provided_count}+ return cls(message, variable_name=variable_name, user_action=user_action, shaping_params=shaping_params)class MultiplicityCountMismatchError(InputShapingError):@@ -145,7 +168,8 @@ class MultiplicityCountMismatchError(InputShapingError):kind=UserActionKind.CHANGE_INPUT,detail=f"Provide exactly {expected_count} items for input '{variable_name}'.",)- return cls(message, variable_name=variable_name, user_action=user_action)+ shaping_params = {"expected": InputWrongMultiplicityExpected.COUNT, "expected_count": expected_count, "provided_count": provided_count}+ return cls(message, variable_name=variable_name, user_action=user_action, shaping_params=shaping_params)class StructureValidationError(InputShapingError):@@ -172,13 +196,19 @@ class StructureValidationError(InputShapingError):declared_concept_ref: str,reason: str,expected_shape: str,+ field: str | None = None,) -> "StructureValidationError":+ """The refusal for a value of the right kind that does not build into the declared concept.++ ``field`` is the dotted path, inside the value, of the first field the build refused, when the build names one,+ which the caller reads as the problem's ``field`` parameter.+ """message = f"Input '{variable_name}' could not be built as '{declared_concept_ref}': {reason}\nExpected shape:\n{expected_shape}"user_action = UserAction(kind=UserActionKind.CHANGE_INPUT,detail=f"Fix input '{variable_name}' so it matches the expected shape for '{declared_concept_ref}'.",)- return cls(message, variable_name=variable_name, user_action=user_action)+ return cls(message, variable_name=variable_name, user_action=user_action, shaping_params={"field": field})@classmethoddef make_for_unreadable_bare_value(@@ -292,7 +322,10 @@ 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).with_error_code(CoreCode.INPUT_WRONG_CONCEPT)+ shaping_params = {"expected": declared_concept_ref, "provided": built_concept_ref}+ return cls(message, variable_name=variable_name, user_action=user_action, shaping_params=shaping_params).with_error_code(+ CoreCode.INPUT_WRONG_CONCEPT+ )class ExplicitConceptIncompatibleError(InputShapingError):@@ -321,7 +354,8 @@ class ExplicitConceptIncompatibleError(InputShapingError):kind=UserActionKind.CHANGE_INPUT,detail=f"Provide a '{declared_concept_ref}' (or a concept that refines it) for input '{variable_name}'.",)- return cls(message, variable_name=variable_name, user_action=user_action)+ shaping_params = {"expected": declared_concept_ref, "provided": provided_concept_ref}+ return cls(message, variable_name=variable_name, user_action=user_action, shaping_params=shaping_params)class UnknownInputNameError(InputShapingError):diff --git a/pipelex/core/memory/input_shaper.py b/pipelex/core/memory/input_shaper.pyindex 57592bf7f..a4d469526 100644--- a/pipelex/core/memory/input_shaper.py+++ b/pipelex/core/memory/input_shaper.py@@ -127,6 +127,14 @@ class InputKind(StrEnum):return False+def _first_refused_field(*, validation_error: ValidationError) -> str | None:+ """The dotted path, inside the value, of the first field a structure's validation refused; ``None`` when it names none."""+ errors = validation_error.errors(include_url=False, include_input=False)+ if not errors or not errors[0]["loc"]:+ return None+ return ".".join(str(segment) for segment in errors[0]["loc"])++class InputShaper:"""Turn a caller's provided inputs into a ``WorkingMemory``, interpreted against the signature."""@@ -426,6 +434,7 @@ class InputShaper:variable_name=variable_name,declared_concept_ref=stuff_spec.concept.concept_ref,provided_description=cls._describe_value(value),+ provided_count=len(cast("list[Any]", value)),expected_shape=cls._render_expected_shape(concept_provider=concept_provider, stuff_spec=stuff_spec),)return cls._build_item_content(@@ -814,6 +823,7 @@ class InputShaper:declared_concept_ref=stuff_spec.concept.concept_ref,reason=str(exc),expected_shape=cls._render_expected_shape(concept_provider=concept_provider, stuff_spec=stuff_spec),+ field=_first_refused_field(validation_error=exc) if isinstance(exc, ValidationError) else None,) from exc@classmethod@@ -990,6 +1000,7 @@ class InputShaper:variable_name=variable_name,declared_concept_ref=stuff_spec.concept.concept_ref,provided_description=f"a list of {len(list_content.items)} item(s)",+ provided_count=len(list_content.items),expected_shape=cls._render_expected_shape(concept_provider=concept_provider, stuff_spec=stuff_spec),)if fixed_count is not None and len(list_content.items) != fixed_count:diff --git a/pipelex/core/method_trees/exceptions.py b/pipelex/core/method_trees/exceptions.pyindex a47e8a9f1..666845ffd 100644--- a/pipelex/core/method_trees/exceptions.py+++ b/pipelex/core/method_trees/exceptions.py@@ -37,11 +37,10 @@ class TreeModuleShadowingError(TreePythonError):With the tree's root first on `sys.path`, the tree's module would replace the other one for the whole process,and the failure would show up far from its cause. The message names the module, the tree file and what it- would shadow; it describes the caller's own method, so it is kept under STRICT disclosure.+ would shadow; it describes the caller's own method."""error_code = CoreCode.METHOD_NAME_CONFLICT- _authors_caller_facing_message = Trueclass TreeModuleExcludedError(ImportError):diff --git a/pipelex/core/pipes/exceptions.py b/pipelex/core/pipes/exceptions.pyindex 624f0591b..ce1b44ee7 100644--- a/pipelex/core/pipes/exceptions.py+++ b/pipelex/core/pipes/exceptions.py@@ -1,12 +1,15 @@-from typing import ClassVar+from typing import Any, ClassVar+from mthds.protocol.problem.models import ProblemLocationfrom mthds.protocol.problem.registry import CoreCode+from typing_extensions import overridefrom pipelex.base_exceptions import PipelexErrorfrom pipelex.cogt.exceptions import ModelChoiceNotFoundErrorfrom pipelex.cogt.model_backends.model_type import ModelTypefrom pipelex.errors.error_code_declaration import ErrorCodeDeclaration, ErrorCodeSet, InheritsCausefrom pipelex.errors.error_codes import ErrorCode+from pipelex.errors.problem import PipelexProblem, ProblemView, make_locationfrom pipelex.system.pipe_run_mode import PipeRunModefrom pipelex.validation_error_types import PipeFactoryErrorType, PipeValidationErrorType@@ -99,6 +102,14 @@ class PipeRunError(PipelexError):self.pipe_code = pipe_codesuper().__init__(message)+ @override+ def problem_params(self) -> dict[str, Any]:+ return {"pipe": self.pipe_code}++ @override+ def problem_location(self) -> ProblemLocation | None:+ return make_location(pipe=self.pipe_code)+class PipeOperatorModelChoiceError(PipelexError):"""Raised by a pipe operator (``PipeLLM``, ``PipeStructure``, ``PipeImgGen``, ``PipeExtract``, ``PipeSearch``, ``PipeJudge``)@@ -112,9 +123,9 @@ class PipeOperatorModelChoiceError(PipelexError):``PipeLLM``), and the library load adds the file the pipe is declared in. Every pipe type that namesa model raises this same error, so every one of them gives the same verdict item.- 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 public- handles, and it must reach a hosted caller under STRICT disclosure.+ The message names the pipe and the field, then keeps the deck check's sentence and its suggestions; the+ problem gives the reference as written, the model type and the suggestions as parameters, and the pipe and+ the field as its location.It takes the code of the deck check's refusal it locates: ``model.unknown`` for a reference the deckdoes not define, ``model.capability_unsupported`` for a bare handle the deck serves only as another@@ -122,7 +133,6 @@ class PipeOperatorModelChoiceError(PipelexError):"""error_code = InheritsCause(fallback=CoreCode.MODEL_UNKNOWN)- _authors_caller_facing_message = Truedef __init__(self,@@ -151,6 +161,14 @@ class PipeOperatorModelChoiceError(PipelexError):self.source = sourcesuper().__init__(message)+ @override+ def problem_params(self) -> dict[str, Any]:+ return {"model": self.model_choice, "model_type": self.model_type, "suggestions": self.suggestions, "pipe": self.pipe_code}++ @override+ def problem_location(self) -> ProblemLocation | None:+ return make_location(pipe=self.pipe_code, field=self.field_name, file=self.source)+@classmethoddef make_from_model_choice_not_found(cls,@@ -185,13 +203,11 @@ class PipeLoadRefusalError(PipelexError):``error_type``, since the refusal has no closed code. Only an ``input``-domained refusal is wrapped: afault of the configuration or of the runtime keeps its own identity and stays a no-verdict fault.- Its message is built only from caller-facing material, the caller's own pipe code and either the- refusal's message, when that message is caller-facing, or the refusal's title, so it is kept under- STRICT disclosure. It takes the code of the refusal it wraps.+ Its message names the pipe and gives the refusal's own message, for the operator; the caller reads the+ sentence the refusal's code renders. It takes the code of the refusal it wraps."""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):self.pipe_code = pipe_code@@ -199,24 +215,43 @@ class PipeLoadRefusalError(PipelexError):self.source = sourcesuper().__init__(message)+ @override+ def problem_params(self) -> dict[str, Any]:+ # Its own code is its fallback, taken only when the refusal it wraps carries none: the pipe's whole declaration.+ return {"pipe": self.pipe_code, "field_path": f"pipe.{self.pipe_code}", "finding": "the pipe could not be built from its declaration"}++ @override+ def problem_location(self) -> ProblemLocation | None:+ return make_location(pipe=self.pipe_code, file=self.source)+@classmethoddef make_from_refusal(cls, *, refusal: PipelexError, pipe_code: str, domain_code: str, source: str | None) -> "PipeLoadRefusalError":- """Locate a refusal on the pipe being built, keeping its message only when it is caller-facing."""- message = f"Pipe '{pipe_code}' could not be loaded: {caller_facing_refusal_text(refusal=refusal)}"+ """Locate a refusal on the pipe being built."""+ message = f"Pipe '{pipe_code}' could not be loaded: {refusal.message}"return cls(message, pipe_code=pipe_code, domain_code=domain_code, source=source)-def caller_facing_refusal_text(*, refusal: PipelexError) -> str:- """The refusal's message when it was authored as caller-facing copy, otherwise its title.+def caller_refusal(*, refusal: PipelexError, pipe_code: str | None = None) -> PipelexProblem:+ """The problem a refusal makes for a caller, located at the pipe that met it when the refusal does not name it.++ Args:+ refusal: The refusal.+ pipe_code: The pipe that met the refusal, which names the pipe parameter of a code that declares one.++ Returns:+ The refusal's problem in the caller's view.+ """+ return refusal.to_problem(view=ProblemView.CALLER, failure_location=make_location(pipe=pipe_code))+++def refusal_detail(*, refusal: PipelexError, pipe_code: str | None = None) -> str:+ """The sentence a refusal's code renders for a caller, the text an item of a verdict built from a raised refusal carries.- A validation verdict is caller-facing as a whole — ``ValidateBundleError`` keeps its message under- STRICT disclosure — so text taken from a refusal onto a verdict item must be caller-facing too: a- refusal whose message is internal is named by its title, which is always public.+ A verdict is read by the caller, so an item taken from a refusal never carries the refusal's own message,+ which is the operator's diagnostics: it carries the code's ``detail``, rendered from the parameters a caller+ may read, the pipe that met the refusal included when it is given."""- report = refusal.to_error_report()- if report.caller_facing_message:- return report.message- return report.title+ return caller_refusal(refusal=refusal, pipe_code=pipe_code).detaildef pipe_validation_error_code(*, error_type: PipeValidationErrorType | None) -> ErrorCode:diff --git a/pipelex/core/pipes/inputs/exceptions.py b/pipelex/core/pipes/inputs/exceptions.pyindex babee76d4..0871eb832 100644--- a/pipelex/core/pipes/inputs/exceptions.py+++ b/pipelex/core/pipes/inputs/exceptions.py@@ -1,6 +1,7 @@-from typing import ClassVar+from typing import Any, ClassVarfrom mthds.protocol.problem.registry import CoreCode+from typing_extensions import overridefrom pipelex.base_exceptions import PipelexErrorfrom pipelex.cogt.inference.error_classification import UserAction, UserActionKind@@ -64,13 +65,9 @@ class OptionalValueAbsentError(PipeRunError):``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- method and data (pipe codes, variable names, ledger reasons — no server internals), and the- caller is the only one who can act on them; they must survive STRICT disclosure."""error_code = CoreCode.PIPE_FORCED_INPUT_ABSENT- _authors_caller_facing_message = Truedef __init__(self,@@ -123,6 +120,10 @@ class OptionalValueAbsentError(PipeRunError):absence_record=absence_record,)+ @override+ def problem_params(self) -> dict[str, Any]:+ return {**super().problem_params(), "variable": self.variable_name}+class NoInputsRequiredError(PipelexError):"""Raised when a pipe has no inputs.diff --git a/pipelex/core/stuffs/exceptions.py b/pipelex/core/stuffs/exceptions.pyindex 00b8a5986..49a13a920 100644--- a/pipelex/core/stuffs/exceptions.py+++ b/pipelex/core/stuffs/exceptions.py@@ -50,9 +50,6 @@ class DateContentError(StuffError):"""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 = Trueclass StuffContentValidationError(StuffError):diff --git a/pipelex/core/stuffs/stuff_factory.py b/pipelex/core/stuffs/stuff_factory.pyindex 9c1afaee9..11197cf92 100644--- a/pipelex/core/stuffs/stuff_factory.py+++ b/pipelex/core/stuffs/stuff_factory.py@@ -235,9 +235,9 @@ class StuffFactory:# base64/pipelex-storage url is a non-local ResolvedUri; an `s3://`/`gs://`-style scheme slips# through as a ResolvedLocalPath but keeps `://` in its path, so reject those too.if not isinstance(resolved, ResolvedLocalPath) or "://" in resolved.path:- # Strip query/fragment/userinfo before echoing the url: CsvError is caller-facing and- # survives STRICT disclosure, so a signed/token-bearing url (e.g. an S3 presigned link)- # must not leak its credentials into the message. Keep scheme/host/path to identify it.+ # Strip query/fragment/userinfo before echoing the url: the message reaches the operator's+ # diagnostics and every log line, so a signed/token-bearing url (e.g. an S3 presigned link)+ # must not leak its credentials into it. Keep scheme/host/path to identify it.safe_netloc = url_parts.hostname or ""try:safe_port = url_parts.portdiff --git a/pipelex/errors/bundle_validation_failure.py b/pipelex/errors/bundle_validation_failure.pynew file mode 100644index 000000000..0eba3280d--- /dev/null+++ b/pipelex/errors/bundle_validation_failure.py@@ -0,0 +1,25 @@+"""The invalid verdict a bundle validator returns: the refusal's problem, and the items the verdict lists."""++from pydantic import BaseModel, ConfigDict, Field++from pipelex.base_exceptions import ValidationErrorItem+from pipelex.errors.problem import PipelexProblem+from pipelex.tools.typing.pydantic_utils import empty_list_factory_of+++class BundleValidationFailure(BaseModel):+ """A bundle refused by validation, as a value: its problem in the operator's view, and its validation items.++ A validator returns it rather than raising, since an invalid bundle is a verdict and not a fault, and the host that+ serves the verdict projects the problem to the view of whoever asked (``pipelex.errors.problem.caller_view_of``).+ It crosses process boundaries, a worker-dispatched validator's included, so it is a model.++ Attributes:+ problem: The refusal's problem, in the operator's view.+ validation_errors: One item per refusal, in the order the validation stages found them, which the verdict lists.+ """++ model_config = ConfigDict(frozen=True, extra="forbid")++ problem: PipelexProblem+ validation_errors: list[ValidationErrorItem] = Field(default_factory=empty_list_factory_of(ValidationErrorItem))diff --git a/pipelex/errors/error_code_sites.py b/pipelex/errors/error_code_sites.pyindex f186558bd..ddad4b751 100644--- a/pipelex/errors/error_code_sites.py+++ b/pipelex/errors/error_code_sites.py@@ -38,7 +38,7 @@ class ChosenCodeSite(NamedTuple):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()``+ ``SomeError(msg)``, ``module.SomeError(msg)`` and ``SomeError(msg).with_error_code(code).with_params(name=value)``all construct ``SomeError``; a bare name, such as a re-raised variable, constructs nothing."""current: ast.expr = nodediff --git a/pipelex/errors/error_codes.py b/pipelex/errors/error_codes.pyindex aae54744d..da78307ca 100644--- a/pipelex/errors/error_codes.py+++ b/pipelex/errors/error_codes.py@@ -20,7 +20,7 @@ from typing import TypeAliasfrom mthds.protocol.problem.registry import CORE_BASE_URL, CORE_CODE_SPECS, EXTENSION_PREFIXES, CoreCode, ProblemDomain, RetryVerdict, StepKindfrom pydantic import BaseModel, ConfigDict-from pipelex.errors.registry.pipelex_codes import PIPELEX_ERROR_ENTRIES, PipelexErrorCode+from pipelex.errors.registry.pipelex_codes import PIPELEX_ERROR_ENTRIES, PIPELEX_ERROR_PARAMS, PipelexErrorCodeErrorCode: TypeAlias = CoreCode | PipelexErrorCode"""A registered code: a core code of the MTHDS standard, or a Pipelex code."""@@ -39,9 +39,16 @@ class ErrorCodeSpec(BaseModel):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 clientraises itself or one that only rides a warning.+ detail: The template of the sentence stating one occurrence, naming parameters as ``{name}``.actor_step: The kind of the next step for the domain's actor.+ actor_step_detail: The template of the actor's step sentence.other_step: The kind of the next step for any other reader.+ other_step_detail: The template of the other reader's step sentence.type_uri: The code's documentation page: its registry's base URL, a slash, then the code.+ params_model: The generated model of the code's parameters.+ param_names: Every parameter the code declares.+ operator_only_params: The parameters only whoever runs the runtime may read: they render into the+ operator's step and ride the operator's diagnostics, never a problem's ``params``."""model_config = ConfigDict(frozen=True, extra="forbid")@@ -51,9 +58,15 @@ class ErrorCodeSpec(BaseModel):domain: ProblemDomainretry: RetryVerdictstatus: int | None+ detail: stractor_step: StepKind+ actor_step_detail: strother_step: StepKind+ other_step_detail: strtype_uri: str+ params_model: type[BaseModel]+ param_names: frozenset[str]+ operator_only_params: frozenset[str]@propertydef invites_retry(self) -> bool:@@ -75,21 +88,34 @@ def _build_specs() -> dict[str, ErrorCodeSpec]:domain=core_spec.domain,retry=core_spec.retry,status=core_spec.status,+ detail=core_spec.detail,actor_step=core_spec.actor_step.kind,+ actor_step_detail=core_spec.actor_step.detail,other_step=core_spec.other_step.kind,+ other_step_detail=core_spec.other_step.detail,type_uri=f"{CORE_BASE_URL}/{core_code}",+ params_model=core_spec.params_model,+ param_names=frozenset(param.name for param in core_spec.params),+ operator_only_params=frozenset(param.name for param in core_spec.params if param.operator_only),)for pipelex_code in PipelexErrorCode:entry = PIPELEX_ERROR_ENTRIES[pipelex_code]+ params_model = PIPELEX_ERROR_PARAMS[pipelex_code]specs[pipelex_code] = ErrorCodeSpec(code=pipelex_code,title=entry.title,domain=ProblemDomain(entry.domain),retry=RetryVerdict(entry.retry),status=entry.status,+ detail=entry.detail,actor_step=StepKind(entry.actor_step),+ actor_step_detail=entry.actor_step_detail,other_step=StepKind(entry.other_step),+ other_step_detail=entry.other_step_detail,type_uri=f"{PIPELEX_ERROR_BASE_URL}/{pipelex_code}",+ params_model=params_model,+ param_names=frozenset(params_model.model_fields),+ operator_only_params=params_model.operator_only_params,)return specs@@ -104,7 +130,7 @@ def error_code_spec(code: ErrorCode) -> ErrorCodeSpec:code: A core code or a Pipelex code.Returns:- The code's title, domain, retry verdict, status, step kinds and type URI.+ The code's title, domain, retry verdict, status, templates, step kinds, parameters and type URI."""return _ERROR_CODE_SPECS[code]@@ -127,3 +153,58 @@ def parse_error_code(value: str) -> ErrorCode | None:return PipelexErrorCode(value)except ValueError:return None+++def _retry_rank(*, retry: RetryVerdict) -> int:+ # A verdict that someone must fix comes before one a repeat may cure, so that no client retries what must be fixed.+ match retry:+ case RetryVerdict.NO:+ return 0+ case RetryVerdict.OUTCOME_UNKNOWN:+ return 1+ case RetryVerdict.YES:+ return 2+++def _domain_rank(*, domain: ProblemDomain) -> int:+ match domain:+ case ProblemDomain.METHOD:+ return 0+ case ProblemDomain.OPERATOR:+ return 1+ case ProblemDomain.ACCOUNT:+ return 2+ case ProblemDomain.INPUT:+ return 3+ case ProblemDomain.RUNTIME:+ return 4+++def first_fault_code(*, codes: list[ErrorCode]) -> ErrorCode | None:+ """The code an answer takes among the codes of several faults it reports at once, ``None`` for no codes.++ A code whose verdict is ``no`` comes before a retryable one, so that no client retries what someone must fix;+ then the method's, the operator's, the account's, the input's and the runtime's, in that order; then the first+ given. Every fault still rides the answer as an item with its own code.++ Args:+ codes: The codes of the faults, in the order they were found.++ Returns:+ The code the answer takes.+ """+ if not codes:+ return None+ return min(+ codes,+ key=lambda code: (_retry_rank(retry=error_code_spec(code).retry), _domain_rank(domain=error_code_spec(code).domain)),+ )+++def code_is_method_domain(*, code: ErrorCode) -> bool:+ """Whether the method's author must act on a code: its registry domain is ``method``."""+ match error_code_spec(code).domain:+ case ProblemDomain.METHOD:+ return True+ case ProblemDomain.INPUT | ProblemDomain.ACCOUNT | ProblemDomain.OPERATOR | ProblemDomain.RUNTIME:+ return Falsediff --git a/pipelex/errors/error_identity_snapshot.py b/pipelex/errors/error_identity_snapshot.pyindex e7c96ec3a..f62c173ac 100644--- a/pipelex/errors/error_identity_snapshot.py+++ b/pipelex/errors/error_identity_snapshot.py@@ -1,10 +1,9 @@"""Snapshot of the wire-visible identity of every ``PipelexError`` subclass: its name and its code.-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 stops-matching, falling through to a generic error path.+Every problem carries the registry ``code`` its error resolved to, and the operator's view carries the Python+class name verbatim as ``diagnostics.error_class``, which operators' tooling may branch on. Renaming an error class+therefore breaks it *silently*, and so does changing the code a class raises: its build stays green and the branch+simply stops matching, falling through to a generic error path.This module closes that gap the cheap way: it renders every class's name and code declaration (the code, theset its raise sites choose from, the cause it takes its code from, or that it is abstract, asdiff --git a/pipelex/errors/problem.py b/pipelex/errors/problem.pynew file mode 100644index 000000000..a55548db7--- /dev/null+++ b/pipelex/errors/problem.py@@ -0,0 +1,924 @@+"""The problem document every Pipelex error becomes, and the views its readers see it through.++A failure, on any wire or at rest, is one problem document: the MTHDS core's :class:`~mthds.protocol.problem.models.Problem`,+an RFC 9457 document carrying a registry code, the code's domain, retry verdict and next step, the code's typed+parameters, the location and the itemized errors, extended by Pipelex with the request id, the problem of a failed+run nested in the problem of a read of its results (``run_error``), and the diagnostics only an operator reads.++**The views.** Who reads a problem decides what of it they see, and the identity a boundary authenticates picks the+view, never a deployment's mode:++- The caller view is the problem without ``diagnostics``, with the step aimed at the caller: the code's actor step,+ except for a code of the ``operator`` domain, whose actor is whoever runs the runtime, where it is the step aimed at+ any other reader.+- The operator view adds ``diagnostics`` and gives the actor's step for every code, rendered with the parameters only+ an operator may read as well.+- The metadata view (:class:`ProblemMetadata`) holds codes, domains, verdicts, step kinds, the shape of the location,+ ids and versions, and no sentence, no parameter and no name a user wrote.++**The sentences.** ``detail`` and the step's ``detail`` are rendered from the code's templates and its parameters, and+a raise site never writes them: the exception's own message rides ``diagnostics.message``. Rendering is total: a+template that cannot be rendered, because a parameter it names was not given, falls back to the code's title for+``detail`` and to a generic sentence of the step's kind for the step, and the failure is logged so that the raise site+can be given the parameter.++**The parameters.** A problem's ``params`` hold the parameters the code declares and the raise site gave, validated+against the code's generated model: an undeclared parameter, or one of the wrong type, is dropped and logged. A+parameter the registry declares operator-only never rides ``params`` in any view; it renders into the operator's step+and rides ``diagnostics.params``.++**The bound.** Every text a raise site, a provider or a caller wrote is capped at :data:`MAX_PROBLEM_TEXT_LENGTH`+characters, keeping its head, which names the fault: an exception's message, a provider's message and every text+parameter. The full text is left to the logs.++**No null declared member.** A problem is written without a member a model declares whose value is ``null``, since the+protocol leaves a member with no value out and a strict reader refuses a declared member written as ``null``+(:meth:`PipelexProblem.to_wire`). A ``null`` an undeclared member holds, or one inside a free-form object, is a value,+and is written as it was read.+"""++from __future__ import annotations++import functools+import logging+import math+from enum import Enum, StrEnum+from pathlib import Path+from typing import TYPE_CHECKING, Any, cast++from mthds.protocol.problem.client_problems import render_template+from mthds.protocol.problem.models import NextStep, Problem, ProblemItem, ProblemLocation, ProblemParams+from mthds.protocol.problem.registry import ProblemDomain, StepKind+from pydantic import BaseModel, ConfigDict, SerializerFunctionWrapHandler, ValidationError, model_serializer+from pydantic_core import to_jsonable_python+from typing_extensions import override++from pipelex.errors.error_codes import ErrorCode, ErrorCodeSpec, error_code_spec, parse_error_code+from pipelex.migration.plan import MigrationPlan+from pipelex.tools.log.log_context import get_log_context+from pipelex.tools.log.log_fields import attach_log_record_extra, build_log_record_extra+from pipelex.tools.misc.package_utils import get_package_version++if TYPE_CHECKING:+ from collections.abc import Mapping, Sequence++MAX_PROBLEM_TEXT_LENGTH = 2000+"""The most characters a text written by a raise site, a provider or a caller keeps on a problem.++It bounds an exception's message on ``diagnostics.message``, a provider's message on ``diagnostics.provider.message``+and every text parameter. A structured output's validation failure can run to hundreds of thousands of characters,+every completion an output parser retried included, and none of it may travel whole into a stored run report, a+response or a client. A capped text keeps its head, which names the fault, and ends with :data:`TRUNCATION_MARKER`.+"""++TRUNCATION_MARKER = " […]"+"""What a capped text ends with, so that its reader knows the rest was cut."""+++def cap_problem_text(*, text: str) -> str:+ """A text bounded to :data:`MAX_PROBLEM_TEXT_LENGTH` characters, its head kept and the cut marked.++ Args:+ text: A text a raise site, a provider or a caller wrote.++ Returns:+ The text itself when it fits, else its head followed by :data:`TRUNCATION_MARKER`, the two within the bound.+ """+ if len(text) <= MAX_PROBLEM_TEXT_LENGTH:+ return text+ return text[: MAX_PROBLEM_TEXT_LENGTH - len(TRUNCATION_MARKER)] + TRUNCATION_MARKER+++class ProblemView(StrEnum):+ """The view of a problem document a reader sees, picked by the identity a boundary authenticates.++ The third view, the metadata channel's, is no problem document: :class:`ProblemMetadata`.+ """++ CALLER = "caller"+ OPERATOR = "operator"++ @property+ def shows_diagnostics(self) -> bool:+ """Whether the view carries ``diagnostics``: only the operator's."""+ match self:+ case ProblemView.OPERATOR:+ return True+ case ProblemView.CALLER:+ return False+++class MigrationErrorBlock(BaseModel):+ """A pending configuration migration, reported alongside the error it explains.++ The structured half of the answer to *why does my configuration not load*, carried by the operator's+ ``diagnostics.migration`` and present only when a scan of this machine's configuration directories found something+ to say. **Consumers branch on its presence**, never on the message text: an absent block means the failure is not+ staleness. It describes the host's own configuration directories, so only an operator reads it.++ ``plans`` is the same shape ``pipelex-agent migrate --dry-run --format json`` emits under its own ``plans`` key,+ deliberately: an agent that reads one has already parsed the other.++ > **No value read from a user's file is ever rendered** here either. The plans carry paths, operation kinds and+ > ledger-supplied values, and nothing else.+ """++ model_config = ConfigDict(frozen=True, extra="forbid")++ remedy: str+ """The command that applies whatever can be applied without a decision."""++ would_write: bool+ """Whether running ``remedy`` would actually rewrite any of these files.++ The block's *presence* says the migration history has something to report about this machine. It does not say the+ remedy repairs it, and this field is what separates the two. A block whose ``would_write`` is False carries a+ diagnosis and nothing to apply. Independent of :attr:`needs_attention`, and the pair is never both False."""++ needs_attention: bool+ """Whether something here is a person's to resolve rather than the tool's: a blocked file, a blocked entry, or a+ path no ledger entry explains. When this is False, running ``remedy`` is expected to be enough."""++ plans: list[MigrationPlan]+ """One per configuration file the scan found something in. Files with nothing to say are left out."""+++class DiagnosticCause(BaseModel):+ """One error of a failure's cause chain, by its class and the code it carries by itself."""++ model_config = ConfigDict(frozen=True, extra="allow")++ error_class: str+ code: str | None = None+++class ProviderDiagnostics(BaseModel):+ """What the inference provider said about a failed call, for an operator."""++ model_config = ConfigDict(frozen=True, extra="allow")++ name: str | None = None+ status: int | None = None+ code: str | None = None+ request_id: str | None = None+ message: str | None = None+++class ProblemDiagnostics(BaseModel):+ """What only an operator reads of a problem: the operator view's ``diagnostics`` member.++ Attributes:+ error_class: The class of the error the problem was built from, the identity ``error_type`` once was.+ message: The error's own message, capped.+ causes: The errors below it on its cause chain, by class and code.+ params: The parameters the code declares operator-only.+ model: The model a failed inference call addressed.+ provider: What the provider said about the call.+ migration: A pending configuration migration that explains the failure.+ runtime_version: The version of the Pipelex runtime that built the problem.+ trace_id: The trace of the Pipelex span the failure happened in.+ span_id: That span.+ """++ model_config = ConfigDict(frozen=True, extra="allow")++ error_class: str+ message: str+ causes: list[DiagnosticCause] | None = None+ params: dict[str, Any] | None = None+ model: str | None = None+ provider: ProviderDiagnostics | None = None+ migration: MigrationErrorBlock | None = None+ runtime_version: str | None = None+ trace_id: str | None = None+ span_id: str | None = None+++class PipelexProblem(Problem):+ """The MTHDS problem document with Pipelex's members.++ Attributes:+ request_id: The request that carried the failure, when known.+ run_error: On a read of a failed run's results, the run's own problem.+ diagnostics: What only an operator reads; present in the operator view alone.+ """++ request_id: str | None = None+ run_error: PipelexProblem | None = None+ diagnostics: ProblemDiagnostics | None = None++ @model_serializer(mode="wrap")+ def _drop_null_members(self, handler: SerializerFunctionWrapHandler):+ # Unannotated on purpose: a return annotation would replace the model's published serialization schema.+ # Whoever dumps a problem, alone or nested in a model that holds one (a graph node, a trace event, a webhook's+ # payload), gets it with no declared member written as `null`, which a strict reader refuses, and every `null`+ # an extension member or a free-form object holds as it was read. This path is pydantic's, which refuses a+ # value nested past its own depth limit; every write of a problem by itself goes through `to_wire`, which has none.+ return _without_null_declared_members(model=self, dumped=handler(self))++ def to_wire(self) -> dict[str, Any]:+ """The problem in JSON types, with no declared member written as ``null``.++ The members are written by walking the model by hand, as the standard's ``Problem.as_wire`` does, rather than+ through pydantic's serializer, which refuses a value nested past its own depth limit of a few hundred levels as+ a circular reference: a reader accepts a body nested up to ``mthds.protocol.problem.answers.MAX_BODY_NESTING``,+ so every problem a reader accepts, a recovered one with a deep extension member included, can be written back.+ A member a model declares is left out when it holds no value; an undeclared member, and every member of a+ free-form object, is written with the value it holds, ``null`` included, as the standard writes it.++ Returns:+ The members of the problem that hold a value, nested ones included.+ """+ return _model_wire(model=self)++ @override+ def as_wire(self) -> dict[str, Any]:+ return self.to_wire()+++def _without_null_declared_members(*, model: BaseModel, dumped: Any) -> Any:+ """``dumped``, pydantic's dump of ``model``, without a member a model declares dumped as ``null``, at any depth.++ The protocol refuses ``null`` on a member a model declares, and on nothing else: a ``null`` an undeclared member+ holds, or one inside a free-form object, is the value it was read with, and is kept. The dump is walked beside the+ model it was dumped from, so that each object of it is known for a model's members or a free-form object.+ """+ if not isinstance(dumped, dict):+ return dumped+ declared_names = type(model).model_fields+ extras = model.model_extra or {}+ kept: dict[str, Any] = {}+ for name, dumped_value in cast("dict[str, Any]", dumped).items():+ if name in declared_names:+ if dumped_value is None:+ continue+ kept[name] = _without_null_declared_members_in(value=getattr(model, name), dumped=dumped_value)+ else:+ kept[name] = _without_null_declared_members_in(value=extras.get(name), dumped=dumped_value)+ return kept+++def _without_null_declared_members_in(*, value: Any, dumped: Any) -> Any:+ """``dumped``, the dump of ``value``, without a declared member written as ``null`` in any model ``value`` holds."""+ if isinstance(value, PipelexProblem):+ # A nested problem was dumped through its own serializer, which already left its declared members out.+ return dumped+ if isinstance(value, BaseModel):+ return _without_null_declared_members(model=value, dumped=dumped)+ if isinstance(value, dict) and isinstance(dumped, dict):+ value_members = cast("dict[Any, Any]", value)+ return {+ key: _without_null_declared_members_in(value=value_members.get(key), dumped=dumped_item)+ for key, dumped_item in cast("dict[str, Any]", dumped).items()+ }+ if isinstance(value, list | tuple) and isinstance(dumped, list):+ value_items = cast("list[Any] | tuple[Any, ...]", value)+ dumped_items = cast("list[Any]", dumped)+ if len(value_items) != len(dumped_items):+ return dumped_items+ return [+ _without_null_declared_members_in(value=item, dumped=dumped_item) for item, dumped_item in zip(value_items, dumped_items, strict=True)+ ]+ return dumped+++def _model_wire(*, model: BaseModel) -> dict[str, Any]:+ """A model's members in JSON types, each declared one that holds a value in the order the model declares it, then each undeclared one.++ A model open to undeclared members, which any problem model is, is walked by hand, one level per call, so that no+ depth limit but the interpreter's applies; a closed one, such as a migration block, holds only the members it+ types and is dumped by pydantic. A declared member that holds no value is left out, and an undeclared one is+ written with the value it holds, ``null`` included.+ """+ if model.model_config.get("extra") != "allow":+ return cast("dict[str, Any]", _without_null_declared_members(model=model, dumped=model.model_dump(mode="json")))+ wire: dict[str, Any] = {}+ for name in type(model).model_fields:+ member = _wire_member(value=getattr(model, name))+ if member is not None:+ wire[name] = member+ for name, value in (model.model_extra or {}).items():+ wire[name] = _wire_member(value=value)+ return wire+++def _wire_member(*, value: Any) -> Any:+ """A member's value in JSON types, with no declared member written as ``null``; a container is walked one level per call.++ The loops are written out rather than as comprehensions, which cost a frame of their own per level on Python 3.11.+ A number JSON cannot hold, an infinity or ``NaN``, reads as ``null``, as pydantic's JSON serialization writes it.+ A free-form object keeps every member, one whose value is ``null`` included: the protocol refuses ``null`` only on+ a member a model declares.+ """+ if isinstance(value, BaseModel):+ return _model_wire(model=value)+ if isinstance(value, dict):+ wire_object: dict[str, Any] = {}+ for key, item in cast("dict[str, Any]", value).items():+ wire_object[key] = _wire_member(value=item)+ return wire_object+ if isinstance(value, list | tuple):+ wire_array: list[Any] = []+ for item in cast("list[Any] | tuple[Any, ...]", value):+ wire_array.append(_wire_member(value=item))+ return wire_array+ if isinstance(value, Enum):+ return _wire_member(value=value.value)+ if isinstance(value, float):+ return value if math.isfinite(value) else None+ # A string, an integer, a boolean or null is already a JSON value.+ if value is None or isinstance(value, str | int):+ return value+ return to_jsonable_python(value)+++# The sentence of a step whose template could not be rendered: one per kind, naming no parameter.+_GENERIC_STEP_SENTENCES: dict[StepKind, str] = {+ StepKind.RETRY: "Send the request again.",+ StepKind.WAIT: "Wait, then send the request again.",+ StepKind.READ_RUN: "Read the run to learn its outcome before sending the request again.",+ StepKind.REFRESH: "Fetch the latest state, then apply the change again.",+ StepKind.CHANGE_INPUT: "Correct the request or its inputs as the problem describes, then send it again.",+ StepKind.CHANGE_METHOD: "Correct the method as the problem describes, then validate it again.",+ StepKind.CHANGE_MODEL: "Choose another model, then send the request again.",+ StepKind.CHECK_CREDENTIALS: "Check the credential the request carries, then send it again.",+ StepKind.REQUEST_ACCESS: "Ask for the access this operation needs, then send the request again.",+ StepKind.CHECK_ACCOUNT: "Check the account's plan, credit and quotas.",+ StepKind.FIX_CONFIGURATION: "Correct the runtime's configuration, then restart it.",+ StepKind.UPGRADE: "Upgrade the client or the runtime so that both implement the same protocol version.",+ StepKind.CONTACT_OWNER: "Ask the owner of the method or of the account to act on this problem.",+ StepKind.REPORT: "Report this problem with its request id.",+}+++# The logger of the faults of a raise site this module finds while it builds a problem. This module sits under the+# import chain of `pipelex.log` itself, whose configuration loads the error classes that build problems, so it cannot+# import the log, and emits its records on this stdlib logger instead, with the same attached fields, through the+# handlers the log configured, as `pipelex.system.exceptions` does.+_problem_logger = logging.getLogger(__name__)+++def _warn(*, message: str, fields: Mapping[str, Any]) -> None:+ """Emit a warning record about a raise site's fault, its values attached as fields, never in the message."""+ if not _problem_logger.isEnabledFor(logging.WARNING):+ return+ record = _problem_logger.makeRecord(+ name=_problem_logger.name,+ level=logging.WARNING,+ fn=__file__,+ lno=0,+ msg=message,+ args=(),+ exc_info=None,+ )+ attach_log_record_extra(record=record, extra=build_log_record_extra(context=get_log_context(), fields=fields, data=None))+ _problem_logger.handle(record)+++def _render_sentence(*, template: str, params: Mapping[str, Any], code: str, part: str) -> str | None:+ """A template rendered with the parameters, or ``None``, logged, when it names a parameter not given."""+ try:+ return render_template(template, params=params)+ except ValueError as exc:+ _warn(+ message="A problem's sentence could not be rendered from its template",+ fields={"error.code": code, "template_part": part, "reason": str(exc)},+ )+ return None+++class _NotAParamValue:+ """The mark of a raise site's value that is neither a JSON scalar nor a built-in collection of them."""+++_NOT_A_PARAM_VALUE = _NotAParamValue()+++def _param_scalar(*, value: Any) -> Any:+ """A scalar parameter value in JSON types: a text capped, an enum as its value; :data:`_NOT_A_PARAM_VALUE` for anything else."""+ if isinstance(value, StrEnum):+ return cap_problem_text(text=str(value))+ if isinstance(value, Enum):+ value = value.value+ if isinstance(value, str):+ return cap_problem_text(text=value)+ if isinstance(value, Path):+ return cap_problem_text(text=str(value))+ if isinstance(value, bool | int | float):+ return value+ return _NOT_A_PARAM_VALUE+++def _param_value(*, value: Any) -> Any:+ """A parameter's value in the JSON types its model validates, :data:`_NOT_A_PARAM_VALUE` when it cannot be one.++ Every parameter a registry declares is a scalar or a list of scalars, so a value is read as one of those and nothing+ else: a scalar, or a built-in list, tuple or set of scalars, made a list. Anything else, a collection of+ collections, a cyclic one or an object of a class of its own whose iteration runs code the raise site wrote, is no+ parameter value, and is never walked, so that reading it cannot raise in place of the error it reports.+ """+ if isinstance(value, list | tuple | set | frozenset):+ items: list[Any] = []+ for item in cast("list[Any] | tuple[Any, ...] | set[Any] | frozenset[Any]", value):+ item_value = _param_scalar(value=item)+ if item_value is _NOT_A_PARAM_VALUE:+ return _NOT_A_PARAM_VALUE+ items.append(item_value)+ return items+ return _param_scalar(value=value)+++def _holds_only_finite_numbers(*, value: Any) -> bool:+ """Whether every number ``value`` holds, itself or as an item, is one JSON can write: never an infinity or ``NaN``."""+ if isinstance(value, float):+ return math.isfinite(value)+ if isinstance(value, list):+ return all(_holds_only_finite_numbers(value=item) for item in cast("list[Any]", value))+ return True+++def accepted_params(*, code: ErrorCode, params: Mapping[str, Any]) -> dict[str, Any]:+ """The parameters of ``params`` the code declares, each of the type its model requires.++ A parameter the code does not declare, or one of the wrong type, is dropped and logged: it is a fault of the+ raise site, which must never turn the error it reports into another. A parameter given as ``None`` is left out,+ and a number JSON cannot write, an infinity or ``NaN``, is of the wrong type whatever the code's model says, since+ it would render into a sentence and then vanish from the wire. So is a value that is neither a JSON scalar nor a+ built-in list, tuple or set of them, which is never walked, so that a cyclic collection, or one whose iteration+ raises, is dropped rather than raise in place of the error. The result validates against the code's model and+ against the problem's own ``params`` model, whatever the raise site gave: a refusal that names no parameter, such+ as a model-level one, drops every parameter rather than let one the models refuse reach the problem, where it would+ fail the problem's construction.++ Args:+ code: The code the parameters are given for.+ params: The parameters the raise site gave, by name.++ Returns:+ The accepted parameters, in JSON types, texts capped.+ """+ spec = error_code_spec(code)+ accepted: dict[str, Any] = {}+ for name, value in params.items():+ if value is None:+ continue+ if name not in spec.param_names:+ _warn(message="An error gives a parameter its code does not declare", fields={"error.code": code, "param": name})+ continue+ param_value = _param_value(value=value)+ if param_value is _NOT_A_PARAM_VALUE:+ _warn(+ message="An error gives a parameter of the wrong type for its code",+ fields={"error.code": code, "param": name, "reason": "not_a_json_value"},+ )+ continue+ if not _holds_only_finite_numbers(value=param_value):+ _warn(+ message="An error gives a parameter of the wrong type for its code",+ fields={"error.code": code, "param": name, "reason": "non_finite_number"},+ )+ continue+ accepted[name] = param_value+ # The code's own model, then the wire's, which types a parameter every reader reads the same way.+ for params_model in (spec.params_model, ProblemParams):+ _drop_refused_params(accepted=accepted, params_model=params_model, code=code)+ return accepted+++def _drop_refused_params(*, accepted: dict[str, Any], params_model: type[BaseModel], code: ErrorCode) -> None:+ """Drop from ``accepted`` every parameter ``params_model`` refuses, and all of them when a refusal names none.++ A missing parameter is no refusal: the code's sentences that name it fall back when they are rendered.+ """+ try:+ params_model.model_validate(accepted)+ except ValidationError as validation_error:+ unattributed_reasons: list[str] = []+ for error in validation_error.errors(include_url=False, include_input=False):+ if error["type"] == "missing":+ continue+ if not error["loc"]:+ unattributed_reasons.append(error["type"])+ continue+ refused_name = str(error["loc"][0])+ if accepted.pop(refused_name, None) is not None:+ _warn(+ message="An error gives a parameter of the wrong type for its code",+ fields={"error.code": code, "param": refused_name, "reason": error["type"]},+ )+ if unattributed_reasons and accepted:+ _warn(+ message="An error gives parameters its code refuses as a whole",+ fields={"error.code": code, "params": sorted(accepted), "reason": ", ".join(unattributed_reasons)},+ )+ accepted.clear()+++def _caller_step_is_actor_step(*, domain: ProblemDomain) -> bool:+ """Whether the caller reads the actor's step: for every domain but ``operator``, whose actor is whoever runs the runtime."""+ match domain:+ case ProblemDomain.INPUT | ProblemDomain.METHOD | ProblemDomain.ACCOUNT | ProblemDomain.RUNTIME:+ return True+ case ProblemDomain.OPERATOR:+ return False+++def _next_step(*, spec: ErrorCodeSpec, view: ProblemView, params: Mapping[str, Any]) -> NextStep:+ """The step of a view, rendered with the parameters the view may read, a generic sentence of its kind when it cannot be."""+ kind: StepKind+ template: str+ match view:+ case ProblemView.OPERATOR:+ kind, template = spec.actor_step, spec.actor_step_detail+ case ProblemView.CALLER:+ if _caller_step_is_actor_step(domain=spec.domain):+ kind, template = spec.actor_step, spec.actor_step_detail+ else:+ kind, template = spec.other_step, spec.other_step_detail+ detail = _render_sentence(template=template, params=params, code=spec.code, part=f"step.{kind}")+ return NextStep(kind=kind, detail=detail or _GENERIC_STEP_SENTENCES[kind])+++def _is_usable_delay(*, seconds: float | None) -> bool:+ """Whether a delay before a retry can ride a problem: a finite, non-negative number of seconds."""+ return seconds is not None and math.isfinite(seconds) and seconds >= 0+++def _members(**members: Any) -> dict[str, Any]:+ """The members that hold a value, so that no declared member is built as ``null``."""+ return {name: value for name, value in members.items() if value is not None}+++def make_problem(+ *,+ code: ErrorCode,+ view: ProblemView,+ params: Mapping[str, Any] | None = None,+ location: ProblemLocation | None = None,+ errors: list[ProblemItem] | None = None,+ retry_after: float | None = None,+ pipeline_run_id: str | None = None,+ request_id: str | None = None,+ diagnostics: ProblemDiagnostics | None = None,+) -> PipelexProblem:+ """Build a problem in a view, reading from the registry everything its code decides.++ Args:+ code: The registry code.+ view: The view of the reader the problem is built for.+ params: The parameters the raise site gave, operator-only ones included; they are validated by+ :func:`accepted_params`.+ location: Where the error happened.+ errors: One item per fault, for a refusal with several; a parameter an item's code declares operator-only is+ taken out of it in every view, and the caller's view of an item whose code neither registry of this process+ holds carries no parameter (:func:`item_in_view`).+ retry_after: The delay before a retry, kept only when the code's verdict is ``yes`` and the delay is a finite,+ non-negative number of seconds: a provider can send any value, ``inf`` included, and the wire takes none of those.+ pipeline_run_id: The run the error belongs to.+ request_id: The request that carried it.+ diagnostics: What only an operator reads; kept in the operator view alone, with the operator-only parameters.++ Returns:+ The problem, without a ``status``, which the HTTP response that carries it adds.+ """+ spec = error_code_spec(code)+ given = accepted_params(code=code, params=params or {})+ caller_params = {name: value for name, value in given.items() if name not in spec.operator_only_params}+ operator_params = {name: value for name, value in given.items() if name in spec.operator_only_params}+ detail = _render_sentence(template=spec.detail, params=caller_params, code=code, part="detail") or spec.title+ step_params = given if view.shows_diagnostics else caller_params+ view_diagnostics: ProblemDiagnostics | None = None+ if view.shows_diagnostics and diagnostics is not None:+ view_diagnostics = diagnostics.model_copy(update={"params": operator_params or None}) if operator_params else diagnostics+ invites_retry = spec.invites_retry+ return PipelexProblem.model_validate(+ _members(+ type=spec.type_uri,+ title=spec.title,+ detail=detail,+ code=spec.code,+ domain=spec.domain,+ retry=spec.retry,+ retry_after=retry_after if invites_retry and _is_usable_delay(seconds=retry_after) else None,+ next_step=_next_step(spec=spec, view=view, params=step_params),+ params=ProblemParams.model_validate(caller_params) if caller_params else None,+ location=location,+ errors=[item_in_view(item=item, view=view) for item in errors] if errors else None,+ pipeline_run_id=pipeline_run_id,+ request_id=request_id,+ diagnostics=view_diagnostics,+ )+ )+++def make_problem_item(+ *,+ code: ErrorCode,+ params: Mapping[str, Any] | None = None,+ location: ProblemLocation | None = None,+ suggestions: list[str] | None = None,+ suggested_fix: Mapping[str, Any] | None = None,+) -> ProblemItem:+ """Build one item of a problem with several faults, its sentence rendered from its code's template.++ An item is the same in every view: its parameters are the caller's, a parameter its code declares operator-only+ being left out, and its sentence falls back on the code's title when the template cannot be rendered.++ Args:+ code: The item's registry code.+ params: The parameters the raise site gave.+ location: Where the fault is.+ suggestions: The names a near miss most likely meant.+ suggested_fix: The deterministic fix of the fault, in its wire form.++ Returns:+ The item.+ """+ spec = error_code_spec(code)+ given = accepted_params(code=code, params=params or {})+ caller_params = {name: value for name, value in given.items() if name not in spec.operator_only_params}+ detail = _render_sentence(template=spec.detail, params=caller_params, code=code, part="detail") or spec.title+ return ProblemItem.model_validate(+ _members(+ code=spec.code,+ detail=detail,+ params=ProblemParams.model_validate(caller_params) if caller_params else None,+ location=location,+ suggestions=suggestions or None,+ suggested_fix=dict(suggested_fix) if suggested_fix is not None else None,+ )+ )+++UNKNOWN_CODE_ITEM_DETAIL = "A fault of a kind this runtime cannot describe; its code names it."+"""The sentence the caller reads of an item whose code neither registry of this process holds (:func:`item_in_view`)."""+++def item_in_view(*, item: ProblemItem, view: ProblemView) -> ProblemItem:+ """An item as a view reads it: without a parameter its code declares operator-only, in every view.++ :func:`make_problem_item` builds every item so, but an item may come from elsewhere: a raise site that built it by+ hand, a plugin, or a stored record read back. When a parameter is taken out, the item's sentence, which may quote+ it, is rendered again from the parameters left, falling back on the code's title.++ An item whose code neither registry of this process holds, such as one a newer worker or a stored record carries,+ fails closed for the caller, as :func:`caller_view_of` does for such a problem's step: its parameters cannot be told+ apart, and its sentence may quote an operator-only one, so the caller's view of it carries no parameter and reads+ :data:`UNKNOWN_CODE_ITEM_DETAIL`. The operator's view keeps it as it is.++ Args:+ item: An item of a problem.+ view: The view of the reader the item is projected for.++ Returns:+ The item, or a copy of it without what the view may not read.+ """+ code = parse_error_code(item.code)+ if code is None:+ match view:+ case ProblemView.OPERATOR:+ return item+ case ProblemView.CALLER:+ unknown_members = item.as_wire()+ unknown_members.pop("params", None)+ unknown_members["detail"] = UNKNOWN_CODE_ITEM_DETAIL+ return ProblemItem.model_validate(unknown_members)+ if item.params is None:+ return item+ spec = error_code_spec(code)+ params = item.params.as_wire()+ if not any(name in spec.operator_only_params for name in params):+ return item+ caller_params = {name: value for name, value in params.items() if name not in spec.operator_only_params}+ members = item.as_wire()+ members["detail"] = _render_sentence(template=spec.detail, params=caller_params, code=code, part="detail") or spec.title+ members.pop("params")+ if caller_params:+ members["params"] = caller_params+ return ProblemItem.model_validate(members)+++def make_location(+ *,+ pipe: str | None = None,+ path: Sequence[str] | None = None,+ input_name: str | None = None,+ field: str | None = None,+ item: int | None = None,+ attempt: int | None = None,+ file: str | None = None,+ line: int | None = None,+ column: int | None = None,+) -> ProblemLocation | None:+ """A location holding the members given, ``None`` when none is.++ Args:+ pipe: The failing pipe's code.+ path: The pipe codes from the run's main pipe down to the failing one.+ input_name: An input's name.+ field: A dotted path inside an input or a request body.+ item: An index in a batch.+ attempt: The attempt, from 1.+ file: The method's source file.+ line: The line in it, from 1.+ column: The column in it, from 1.++ Returns:+ The location, or ``None`` when it would be empty.+ """+ members = _members(+ pipe=pipe,+ path=list(path) if path else None,+ input=input_name,+ field=field,+ item=item,+ attempt=attempt,+ file=file,+ line=line,+ column=column,+ )+ if not members:+ return None+ return ProblemLocation.model_validate(members)+++def merge_locations(*, base: ProblemLocation | None, override: ProblemLocation) -> ProblemLocation:+ """A location holding the members of both, ``override``'s winning where both hold one.++ Args:+ base: The location an error knows about itself, such as the input or the field at fault.+ override: The location found around it, such as the failing pipe and its path.++ Returns:+ The merged location.+ """+ base_members = base.as_wire() if base is not None else {}+ return ProblemLocation.model_validate({**base_members, **override.as_wire()})+++def caller_view_of(*, problem: PipelexProblem) -> PipelexProblem:+ """The caller's view of a problem built in the operator's: ``diagnostics`` dropped, the step re-aimed at the caller.++ The operator view holds everything the caller view does, so a reader holding the operator's record, such as the+ hosted plane's stored run report, serves its caller from it. The step is rendered again from the problem's+ ``params``, which never hold an operator-only parameter, since the operator's step may have been rendered with one.++ The projection fails closed for a code neither registry of this process holds, such as one a newer worker or a+ stored record carries: its step cannot be rendered again, and the operator's may quote an operator-only parameter,+ so the caller reads the generic sentence of the step's kind, and ``report`` for a code of the ``operator`` domain,+ whose actor's step is not the caller's. A nested ``run_error`` is projected the same way, and each item loses a+ parameter its code declares operator-only, and every parameter and its sentence when its code is unknown+ (:func:`item_in_view`), since a stored record's items may not have been built by :func:`make_problem`.++ Args:+ problem: A problem in any view.++ Returns:+ The caller view.+ """+ members = problem.to_wire()+ members.pop("diagnostics", None)+ if problem.run_error is not None:+ members["run_error"] = caller_view_of(problem=problem.run_error).to_wire()+ if problem.errors:+ members["errors"] = [item_in_view(item=item, view=ProblemView.CALLER).as_wire() for item in problem.errors]+ code = parse_error_code(problem.code)+ if code is None:+ members["next_step"] = _unknown_code_caller_step(problem=problem).as_wire()+ else:+ params = problem.params.as_wire() if problem.params is not None else {}+ members["next_step"] = _next_step(spec=error_code_spec(code), view=ProblemView.CALLER, params=params).as_wire()+ return PipelexProblem.model_validate(members)+++def recovered_problem_in_view(+ *,+ problem: PipelexProblem,+ view: ProblemView,+ request_id: str | None = None,+ pipeline_run_id: str | None = None,+ failure_location: ProblemLocation | None = None,+) -> PipelexProblem:+ """A problem recovered across a transport boundary, as the error carrying it reports it in a view.++ The problem was built on the far side, in the operator's view, so it is taken as it is: the location a run found+ for it is merged over its own, the run's failing pipe and path winning; the request and the run fill the members+ it does not hold; and a caller reads its caller view (:func:`caller_view_of`).++ Args:+ problem: The recovered problem, in the operator's view.+ view: The view of the reader the problem is reported to.+ request_id: The request that carried the failure, when known.+ pipeline_run_id: The run the failure belongs to, when one exists.+ failure_location: Where a run's failing pipe is, when the failure was located at a pipe.++ Returns:+ The problem in the view asked for.+ """+ update: dict[str, Any] = {}+ if failure_location is not None:+ update["location"] = merge_locations(base=problem.location, override=failure_location)+ if request_id is not None and problem.request_id is None:+ update["request_id"] = request_id+ if pipeline_run_id is not None and problem.pipeline_run_id is None:+ update["pipeline_run_id"] = pipeline_run_id+ reported = problem.model_copy(update=update) if update else problem+ match view:+ case ProblemView.OPERATOR:+ return reported+ case ProblemView.CALLER:+ return caller_view_of(problem=reported)+++def _unknown_code_caller_step(*, problem: PipelexProblem) -> NextStep:+ """The caller's step of a problem whose code this process's registries do not hold, naming no parameter.++ The kind is the problem's own, read the way a reader reads a kind it does not know, except for a code of the+ ``operator`` domain, whose step is the actor's in the operator's record, and whose caller reports the problem.+ """+ kind: StepKind+ if _caller_step_is_actor_step(domain=problem.effective_domain):+ kind = problem.effective_step_kind+ else:+ kind = StepKind.REPORT+ return NextStep(kind=kind, detail=_GENERIC_STEP_SENTENCES[kind])+++class LocationShape(BaseModel):+ """The shape of a problem's location, naming nothing: how deep the failing pipe is, the attempt and the batch index."""++ model_config = ConfigDict(frozen=True, extra="forbid")++ depth: int | None = None+ attempt: int | None = None+ item: int | None = None+++class ProblemMetadata(BaseModel):+ """The metadata view of a problem: what may leave a perimeter, with no sentence, parameter or name a user wrote.++ Attributes:+ code: The registry code.+ domain: Who must act.+ retry: The retry verdict.+ next_step_kind: The kind of the problem's step.+ location: The shape of the location, when the problem has one.+ item_codes: The codes of the problem's items, in order.+ pipeline_run_id: The run the problem belongs to.+ request_id: The request that carried it.+ runtime_version: The version of the Pipelex runtime that built it.+ run_error: The metadata of a nested run problem.+ """++ model_config = ConfigDict(frozen=True, extra="forbid")++ code: str+ domain: str+ retry: str+ next_step_kind: str+ location: LocationShape | None = None+ item_codes: list[str] | None = None+ pipeline_run_id: str | None = None+ request_id: str | None = None+ runtime_version: str | None = None+ run_error: ProblemMetadata | None = None++ def to_wire(self) -> dict[str, Any]:+ """The metadata in JSON types, with no member written as ``null``."""+ return self.model_dump(mode="json", exclude_none=True)+++def problem_metadata(*, problem: PipelexProblem) -> ProblemMetadata:+ """The metadata view of a problem built in any view.++ Args:+ problem: The problem.++ Returns:+ Its codes, domain, verdict, step kind, location shape, ids and versions.+ """+ location_shape: LocationShape | None = None+ if problem.location is not None:+ location_shape = LocationShape(+ depth=len(problem.location.path) if problem.location.path else None,+ attempt=problem.location.attempt,+ item=problem.location.item,+ )+ return ProblemMetadata(+ code=problem.code,+ domain=str(problem.domain),+ retry=str(problem.retry),+ next_step_kind=str(problem.next_step.kind),+ location=location_shape,+ item_codes=[item.code for item in problem.errors] if problem.errors else None,+ pipeline_run_id=problem.pipeline_run_id,+ request_id=problem.request_id,+ runtime_version=problem.diagnostics.runtime_version if problem.diagnostics is not None else None,+ run_error=problem_metadata(problem=problem.run_error) if problem.run_error is not None else None,+ )+++def runtime_version() -> str:+ """The version of the installed Pipelex runtime, which an operator's diagnostics name."""+ return get_package_version()diff --git a/pipelex/errors/registry/pipelex_codes.py b/pipelex/errors/registry/pipelex_codes.pyindex ab52bf25e..51c88709f 100644--- a/pipelex/errors/registry/pipelex_codes.py+++ b/pipelex/errors/registry/pipelex_codes.py@@ -1017,23 +1017,29 @@ PIPELEX_ERROR_PARAMS: dict[PipelexErrorCode, type[PipelexErrorParams]] = {class PipelexErrorEntry(NamedTuple):- """What the registry declares about a Pipelex code that classifying an error needs.+ """What the registry declares about a Pipelex code that classifying an error and rendering its problem need.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.+ detail: The template of the sentence that states one occurrence, naming parameters as ``{name}``.actor_step: The kind of the step aimed at the domain's actor.+ actor_step_detail: The template of the sentence of the step aimed at the domain's actor.other_step: The kind of the step aimed at any other reader.+ other_step_detail: The template of the sentence of the step aimed at any other reader."""title: strdomain: strretry: strstatus: int | None+ detail: stractor_step: str+ actor_step_detail: strother_step: str+ other_step_detail: strPIPELEX_ERROR_ENTRIES: dict[PipelexErrorCode, PipelexErrorEntry] = {@@ -1042,464 +1048,644 @@ PIPELEX_ERROR_ENTRIES: dict[PipelexErrorCode, PipelexErrorEntry] = {domain="account",retry="no",status=409,+ detail="The account's plan allows at most {value} for '{limit}', and the account already holds that many.",actor_step="check_account",+ actor_step_detail="Check the account's plan, then free some of '{limit}' or move to a plan that allows more.",other_step="contact_owner",+ other_step_detail="Ask the account's owner to move to a plan that allows more than {value} for '{limit}'.",),PipelexErrorCode.BILLING_CREDIT_EXHAUSTED: PipelexErrorEntry(title="The organization is out of credit",domain="account",retry="no",status=402,+ detail="The organization has no credit left, so the operation was refused.",actor_step="check_account",+ actor_step_detail="Add credit to the organization, or move it to a plan that includes more, then try again.",other_step="contact_owner",+ other_step_detail="Ask the account's owner to add credit to the organization.",),PipelexErrorCode.BILLING_SUBSCRIPTION_CONFLICT: PipelexErrorEntry(title="The subscription's state does not allow this",domain="account",retry="no",status=409,+ detail="This billing action is not possible while the organization's subscription is '{subscription}'.",actor_step="check_account",+ actor_step_detail="Check the organization's subscription, then take the billing action its state allows.",other_step="contact_owner",+ other_step_detail="Ask the account's owner to check the organization's subscription.",),PipelexErrorCode.BILLING_PLAN_REFUSED: PipelexErrorEntry(title="The plan's rules refuse this change",domain="input",retry="no",status=409,+ detail="The rules of the organization's plan refuse this change (reason: {reason}).",actor_step="change_input",+ actor_step_detail="Request a change the organization's plan allows, then send the request again.",other_step="change_input",+ other_step_detail="Pass this to the caller, whose plan change the plan's rules refuse.",),PipelexErrorCode.ORG_REQUIRED: PipelexErrorEntry(title="An organization is required",domain="account",retry="no",status=403,+ detail="This operation acts on an organization, and the request acts for none.",actor_step="check_account",+ actor_step_detail="Act for an organization, by joining or creating one, then send the request again.",other_step="contact_owner",+ other_step_detail="Ask the account's owner to add you to an organization.",),PipelexErrorCode.ORG_MISMATCH: PipelexErrorEntry(title="The reference belongs to another organization",domain="input",retry="no",status=403,+ detail="The request's {reference} belongs to an organization other than the caller's.",actor_step="change_input",+ actor_step_detail="Use a {reference} of the organization the request acts for, then send the request again.",other_step="change_input",+ other_step_detail="Pass this to the caller, whose {reference} belongs to another organization.",),PipelexErrorCode.ORG_NOT_FOUND: PipelexErrorEntry(title="The organization's resource does not exist",domain="input",retry="no",status=404,+ detail="The {resource} the request names does not exist.",actor_step="change_input",+ actor_step_detail="Name a {resource} that exists, then send the request again.",other_step="change_input",+ other_step_detail="Pass this to the caller, whose request names a {resource} that does not exist.",),PipelexErrorCode.ORG_NOT_MANAGEABLE: PipelexErrorEntry(title="The resource cannot be changed this way in its state",domain="input",retry="no",status=409,+ detail="The resource cannot be changed this way in its current state (reason: {reason}).",actor_step="change_input",+ actor_step_detail="Change the resource another way, or bring it into a state that allows this change first.",other_step="change_input",+ other_step_detail="Pass this to the caller, whose change the resource's state does not allow.",),PipelexErrorCode.ORG_ALREADY_EXISTS: PipelexErrorEntry(title="The organization's resource already exists",domain="input",retry="no",status=409,+ detail="The {resource} the request would create already exists.",actor_step="change_input",+ actor_step_detail="Use the {resource} that exists, or choose another, then send the request again.",other_step="change_input",+ other_step_detail="Pass this to the caller, whose {resource} already exists.",),PipelexErrorCode.ORG_PROMO_INVALID: PipelexErrorEntry(title="The promo code cannot be redeemed",domain="input",retry="no",status=422,+ detail="The promo code cannot be redeemed.",actor_step="change_input",+ actor_step_detail="Check the promo code, then redeem one that is valid.",other_step="change_input",+ other_step_detail="Pass this to the caller, whose promo code cannot be redeemed.",),PipelexErrorCode.ORG_PROMO_CREDIT_PENDING: PipelexErrorEntry(title="The promo credit is pending",domain="runtime",retry="no",status=502,+ detail="The promo code was redeemed, and its credit has not been applied yet.",actor_step="wait",+ actor_step_detail="Wait for the credit to reach the organization, without redeeming the code again.",other_step="wait",+ other_step_detail="Wait for the credit to reach the organization, without redeeming the code again.",),PipelexErrorCode.CATALOG_NOT_FOUND: PipelexErrorEntry(title="The saved method does not exist",domain="input",retry="no",status=404,+ detail="The organization's catalog holds no {resource} matching the request for the method '{method_id}'.",actor_step="change_input",+ actor_step_detail="List the organization's catalog to find the {resource}, then send the request again with one that exists.",other_step="change_input",+ other_step_detail="Pass this to the caller, whose request names a {resource} the catalog does not hold.",),PipelexErrorCode.CATALOG_NOT_PUBLISHED: PipelexErrorEntry(title="The saved method has no published version",domain="input",retry="no",status=409,+ detail="The method '{method_id}' has no published version.",actor_step="change_input",+ actor_step_detail="Publish a version of the method '{method_id}', or name its draft as '{method_id}@draft', then send the request again.",other_step="change_input",+ other_step_detail="Pass this to the caller, who names the latest published version of the method '{method_id}', which has none.",),PipelexErrorCode.CATALOG_BEING_DELETED: PipelexErrorEntry(title="The saved method is being deleted",domain="input",retry="no",status=409,+ detail="The method '{method_id}' is being deleted.",actor_step="change_input",+ actor_step_detail="Use another method, since the method '{method_id}' is being deleted.",other_step="change_input",+ other_step_detail="Pass this to the caller, whose request names the method '{method_id}', which is being deleted.",),PipelexErrorCode.CATALOG_DELETION_FAILED: PipelexErrorEntry(title="The saved method's deletion failed",domain="runtime",retry="yes",status=503,+ detail="The deletion of the method '{method_id}' did not complete.",actor_step="retry",+ actor_step_detail="Delete the method '{method_id}' again.",other_step="retry",+ other_step_detail="Delete the method '{method_id}' again.",),PipelexErrorCode.CATALOG_UPDATE_CONFLICT: PipelexErrorEntry(title="The saved method changed since it was read",domain="input",retry="no",status=409,+ detail="The method '{method_id}' changed after it was read, so the update was not applied.",actor_step="refresh",+ actor_step_detail="Read the method '{method_id}' again, then apply the change to its current content.",other_step="refresh",+ other_step_detail="Read the method '{method_id}' again, then apply the change to its current content.",),PipelexErrorCode.CATALOG_SELECTOR_INVALID: PipelexErrorEntry(title="The catalog selector is malformed",domain="input",retry="no",status=422,+ detail="The catalog selector cannot be parsed (reason: {reason}).",actor_step="change_input",+ actor_step_detail=(+ "Write the selector as a catalog id, alone or followed by '@' and a version number or 'draft', then send the request again."+ ),other_step="change_input",+ other_step_detail="Pass this to the caller, whose catalog selector cannot be parsed.",),PipelexErrorCode.CATALOG_LINK_CONFLICT: PipelexErrorEntry(title="The directory is linked to another method",domain="input",retry="no",status=None,+ detail="The method link of the directory '{path}' stops this save to the method '{method_id}'.",actor_step="change_input",+ actor_step_detail="Save the directory to the method its link names, or save these files from a directory of their own.",other_step="change_input",+ other_step_detail="Pass this to the caller, whose directory '{path}' is linked in a way that stops this save.",),PipelexErrorCode.RUN_ALREADY_EXISTS: PipelexErrorEntry(title="A run with this id already exists",domain="input",retry="no",status=409,+ detail="A run with the id '{pipeline_run_id}' already exists.",actor_step="change_input",+ actor_step_detail="Start the run with another id, or with none so that the runner assigns one.",other_step="change_input",+ other_step_detail="Pass this to the caller, who chose the run id '{pipeline_run_id}', which is already taken.",),PipelexErrorCode.STORAGE_URI_INVALID: PipelexErrorEntry(title="The storage address is malformed",domain="input",retry="no",status=422,+ detail="A storage address in the request cannot be parsed.",actor_step="change_input",+ actor_step_detail="Send the storage address exactly as storage returned it, then send the request again.",other_step="change_input",+ other_step_detail="Pass this to the caller, whose request holds a storage address that cannot be parsed.",),PipelexErrorCode.STORAGE_NOT_FOUND: PipelexErrorEntry(title="A stored file is gone",domain="runtime",retry="no",status=500,+ detail="A file the runtime stored is no longer in its {scheme} storage.",actor_step="report",+ actor_step_detail="Report this to whoever runs the runtime.",other_step="report",+ other_step_detail="Report this to whoever runs the runtime.",),PipelexErrorCode.STORAGE_UNAVAILABLE: PipelexErrorEntry(title="Storage is unavailable",domain="runtime",retry="yes",status=503,+ detail="The {scheme} storage failed a read or a write.",actor_step="retry",+ actor_step_detail="Send the request again after a while.",other_step="wait",+ other_step_detail="Wait, then send the request again.",),PipelexErrorCode.STORAGE_NOT_CONFIGURED: PipelexErrorEntry(title="This deployment serves no storage for that address",domain="operator",retry="no",status=500,+ detail="This deployment serves no storage for the scheme '{scheme}'.",actor_step="fix_configuration",+ actor_step_detail="Configure a storage for the scheme '{scheme}' on this deployment, then restart the runtime.",other_step="report",+ other_step_detail="Report this to whoever runs the runtime.",),PipelexErrorCode.STORAGE_GRANT_UNUSABLE: PipelexErrorEntry(title="The upload grant is spent or expired",domain="runtime",retry="yes",status=403,+ detail="The upload grant has expired, or has already written its file.",actor_step="retry",+ actor_step_detail="Ask for a new upload grant, then upload the file with it.",other_step="retry",+ other_step_detail="Ask for a new upload grant, then upload the file with it.",),PipelexErrorCode.STORAGE_GRANT_MISMATCH: PipelexErrorEntry(title="The upload differs from its grant",domain="runtime",retry="no",status=403,+ detail="The upload differs from what its grant signed, so storage refused it.",actor_step="report",+ actor_step_detail="Report this to whoever runs the runtime.",other_step="report",+ other_step_detail="Report this to whoever runs the runtime.",),PipelexErrorCode.STORAGE_UPLOAD_REFUSED: PipelexErrorEntry(title="Storage refused the upload",domain="runtime",retry="no",status=403,+ detail="Storage refused the upload with the status {status}.",actor_step="report",+ actor_step_detail="Report this to whoever runs the runtime.",other_step="report",+ other_step_detail="Report this to whoever runs the runtime.",),PipelexErrorCode.SECURITY_RESERVED_KEY: PipelexErrorEntry(title="The request carries a reserved key",domain="input",retry="no",status=422,+ detail="The request carries object keys that Pipelex's decoder reserves for its own markers.",actor_step="change_input",+ actor_step_detail="Rename or remove the reserved keys in the request, then send it again.",other_step="change_input",+ other_step_detail="Pass this to the caller, whose request carries reserved keys.",),PipelexErrorCode.SECURITY_RESULT_OUTSIDE_SCOPE: PipelexErrorEntry(title="A result location lies outside the run",domain="runtime",retry="no",status=500,+ detail="A result location lies outside the run's storage scope, so the runtime refused it.",actor_step="report",+ actor_step_detail="Report this to whoever runs the runtime.",other_step="report",+ other_step_detail="Report this to whoever runs the runtime.",),PipelexErrorCode.CONFIG_INVALID: PipelexErrorEntry(title="The runtime's configuration is invalid",domain="operator",retry="no",status=500,+ detail="The runtime's configuration is invalid, so it cannot serve this request.",actor_step="fix_configuration",+ actor_step_detail="Correct the setting '{setting}' in the file '{file}' of the {surface} configuration, then restart the runtime.",other_step="report",+ other_step_detail="Report this to whoever runs the runtime.",),PipelexErrorCode.CONFIG_SYNTAX: PipelexErrorEntry(title="A configuration file does not parse",domain="operator",retry="no",status=500,+ detail="A configuration file of the runtime does not parse.",actor_step="fix_configuration",+ actor_step_detail=(+ "Fix the TOML of the file '{file}' of the {surface} configuration at line {line}, column {column}, then restart the runtime."+ ),other_step="report",+ other_step_detail="Report this to whoever runs the runtime.",),PipelexErrorCode.CONFIG_FILE_MISSING: PipelexErrorEntry(title="A configuration file is missing",domain="operator",retry="no",status=500,+ detail="A configuration file the runtime needs is missing.",actor_step="fix_configuration",+ actor_step_detail="Create or restore the file '{file}' of the {surface} configuration, then restart the runtime.",other_step="report",+ other_step_detail="Report this to whoever runs the runtime.",),PipelexErrorCode.CONFIG_VARIABLE_MISSING: PipelexErrorEntry(title="A configuration variable is not set",domain="operator",retry="no",status=500,+ detail="A variable the runtime's configuration refers to is not set.",actor_step="fix_configuration",+ actor_step_detail="Set the {source} variable '{variable}', then restart the runtime.",other_step="report",+ other_step_detail="Report this to whoever runs the runtime.",),PipelexErrorCode.CONFIG_CREDENTIAL_MISSING: PipelexErrorEntry(title="An inference backend has no credential",domain="operator",retry="no",status=500,+ detail="An inference backend of the runtime has no credential.",actor_step="check_credentials",+ actor_step_detail="Set the credential '{variable}' of the backend '{backend}', then restart the runtime.",other_step="report",+ other_step_detail="Report this to whoever runs the runtime.",),PipelexErrorCode.CONFIG_CREDENTIAL_REFUSED: PipelexErrorEntry(title="A service refused the configured credential",domain="operator",retry="no",status=500,+ detail="A service the runtime depends on refused the credential it is configured with.",actor_step="check_credentials",+ actor_step_detail="Check the credential the {surface} configuration holds for the service '{service}'.",other_step="report",+ other_step_detail="Report this to whoever runs the runtime.",),PipelexErrorCode.CONFIG_DEPENDENCY_MISSING: PipelexErrorEntry(title="An optional dependency is not installed",domain="operator",retry="no",status=500,+ detail="An optional dependency that the runtime's configuration needs is not installed.",actor_step="fix_configuration",+ actor_step_detail="Install '{dependency}', which the extra '{extra}' provides, then restart the runtime.",other_step="report",+ other_step_detail="Report this to whoever runs the runtime.",),PipelexErrorCode.PLUGIN_NOT_FOUND: PipelexErrorEntry(title="No plugin provides the configured choice",domain="operator",retry="no",status=500,+ detail="No installed plugin provides a choice the runtime's configuration makes.",actor_step="fix_configuration",+ actor_step_detail="Install a plugin that provides '{value}' for the setting '{setting}', or choose a value an installed plugin provides.",other_step="report",+ other_step_detail="Report this to whoever runs the runtime.",),PipelexErrorCode.PLUGIN_BROKEN: PipelexErrorEntry(title="A plugin failed to load",domain="operator",retry="no",status=500,+ detail="An installed plugin failed to load.",actor_step="fix_configuration",+ actor_step_detail="Fix or uninstall the plugin '{plugin}' ({reason}), then restart the runtime.",other_step="report",+ other_step_detail="Report this to whoever runs the runtime.",),PipelexErrorCode.PLUGIN_CONFLICT: PipelexErrorEntry(title="Two plugins claim the same slot",domain="operator",retry="no",status=500,+ detail="Two installed plugins claim the same slot.",actor_step="fix_configuration",+ actor_step_detail="Uninstall '{plugin}' or '{other_plugin}', which both claim '{slot}', then restart the runtime.",other_step="report",+ other_step_detail="Report this to whoever runs the runtime.",),PipelexErrorCode.PLUGIN_API_MISMATCH: PipelexErrorEntry(title="A plugin targets another plugin API",domain="operator",retry="no",status=500,+ detail="An installed plugin targets a plugin API this runtime does not support.",actor_step="upgrade",+ actor_step_detail=(+ "Upgrade the plugin '{plugin}', built for the plugin API {targets_api}, or Pipelex, which supports the plugin API {supported_api}."+ ),other_step="report",+ other_step_detail="Report this to whoever runs the runtime.",),PipelexErrorCode.DEPLOYMENT_ORCHESTRATION_OVERRIDE_FORBIDDEN: PipelexErrorEntry(title="This deployment does not allow choosing the orchestration mode",domain="input",retry="no",status=422,+ detail="This deployment does not let a request choose its orchestration mode, and this one asks for '{requested_mode}'.",actor_step="change_input",+ actor_step_detail="Send the request without choosing an orchestration mode.",other_step="change_input",+ other_step_detail="Pass this to the caller, whose request chooses an orchestration mode this deployment fixes.",),PipelexErrorCode.DEPLOYMENT_CUSTOM_CODE_REQUIRES_SANDBOX: PipelexErrorEntry(title="Custom code needs a sandbox-hosted deployment",domain="operator",retry="no",status=501,+ detail="The method ships Python code in its {origin}, and this deployment runs none outside the Daytona sandbox.",actor_step="fix_configuration",+ actor_step_detail="Configure the Daytona sandbox on this deployment, so that it can run the method's own code.",other_step="report",+ other_step_detail="Report this to whoever runs the runtime.",),PipelexErrorCode.DEPLOYMENT_PYTHON_STRUCTURES_REFUSED: PipelexErrorEntry(title="Python structure classes are not allowed here",domain="method",retry="no",status=422,+ detail="The method declares structures as Python classes, which this runner does not import.",actor_step="change_method",+ actor_step_detail="Declare the structures as concepts in the method in place of Python classes, then run it again.",other_step="contact_owner",+ other_step_detail="Ask the method's owner to declare its structures as concepts in the method.",),PipelexErrorCode.DEPLOYMENT_TOKEN_CLAIMS_INVALID: PipelexErrorEntry(title="The token's claims cannot be used",domain="operator",retry="no",status=500,+ detail="The request's verified token carries claims this runner cannot use.",actor_step="fix_configuration",+ actor_step_detail="Correct the claim '{claim}' ({reason}) that the token issuer writes, then send the request again.",other_step="report",+ other_step_detail="Report this to whoever runs the runtime.",),PipelexErrorCode.DOCGEN_ENGINE_UNAVAILABLE: PipelexErrorEntry(title="No document engine prints this here",domain="operator",retry="no",status=501,+ detail="No document engine prints the format '{format}' in this runtime.",actor_step="fix_configuration",+ actor_step_detail="Install or enable the engine '{engine}' ({gap}), then restart the runtime.",other_step="report",+ other_step_detail="Report this to whoever runs the runtime.",),PipelexErrorCode.DOCGEN_TEMPLATE_INVALID: PipelexErrorEntry(title="The document template cannot be used",domain="method",retry="no",status=422,+ detail="The document template '{template}' cannot be used (reason: {reason}): {finding}",actor_step="change_method",+ actor_step_detail="Fix the template '{template}', then run the method again.",other_step="contact_owner",+ other_step_detail="Ask the method's owner to fix the template '{template}'.",),PipelexErrorCode.DOCGEN_RESOURCE_REFUSED: PipelexErrorEntry(title="The document names a file it may not read",domain="method",retry="no",status=422,+ detail="The document names a file the print engine may not read (reason: {reason}).",actor_step="change_method",+ actor_step_detail="Name the file by an absolute https URL or embed it, then run the method again.",other_step="contact_owner",+ other_step_detail="Ask the method's owner to fix the file its document names.",),PipelexErrorCode.DOCGEN_CONTENT_UNPRINTABLE: PipelexErrorEntry(title="The document's content cannot be printed",domain="input",retry="no",status=422,+ detail="The run's data holds something the print engine cannot lay out (reason: {reason}, in '{element}').",actor_step="change_input",+ actor_step_detail="Change the input that fills '{element}', then run the method again.",other_step="change_input",+ other_step_detail="Pass this to the caller, whose inputs hold something the document cannot print.",),PipelexErrorCode.DOCGEN_PRINT_TIMEOUT: PipelexErrorEntry(title="Printing the document took too long",domain="runtime",retry="yes",status=504,+ detail="Printing the document ran past its limit of {limit} seconds and was stopped.",actor_step="retry",+ actor_step_detail="Run the method again, since the print may finish within its limit.",other_step="retry",+ other_step_detail="Run the method again, since the print may finish within its limit.",),PipelexErrorCode.DOCGEN_TEMPLATE_WARNING: PipelexErrorEntry(title="The document template may be faulty",domain="method",retry="no",status=None,+ detail="The document template '{template}' may be faulty: {finding}",actor_step="change_method",+ actor_step_detail="Check the template '{template}', and fix it if the finding is right.",other_step="contact_owner",+ other_step_detail="Ask the method's owner to check the template '{template}'.",),PipelexErrorCode.SANDBOX_UNAVAILABLE: PipelexErrorEntry(title="The Daytona sandbox could not be started",domain="runtime",retry="yes",status=503,+ detail="The Daytona sandbox that runs the method's code could not be started (backend: {backend}), so the code never ran.",actor_step="retry",+ actor_step_detail="Run the method again after a while.",other_step="retry",+ other_step_detail="Run the method again after a while.",),PipelexErrorCode.CODEGEN_OUTPUT_CONFLICT: PipelexErrorEntry(title="Codegen will not write there",domain="input",retry="no",status=409,+ detail="Codegen will not write to '{path}' (reason: {reason}).",actor_step="change_input",+ actor_step_detail="Generate into a directory codegen owns, or move what sits at '{path}' out of the way.",other_step="change_input",+ other_step_detail="Pass this to the caller, whose codegen target '{path}' holds something codegen will not overwrite.",),PipelexErrorCode.CODEGEN_LOCK_INVALID: PipelexErrorEntry(title="The codegen lock is unreadable",domain="input",retry="no",status=422,+ detail="The codegen lock '{file}' cannot be read.",actor_step="change_input",+ actor_step_detail="Restore the lock '{file}' from version control, or generate the code again to rewrite it.",other_step="change_input",+ other_step_detail="Pass this to the caller, whose codegen lock '{file}' cannot be read.",),PipelexErrorCode.CODEGEN_LOCK_UNSUPPORTED: PipelexErrorEntry(title="The codegen lock needs a newer Pipelex",domain="operator",retry="no",status=500,+ detail="The codegen lock was written in the format version {lock_version}, which this Pipelex does not read.",actor_step="upgrade",+ actor_step_detail="Upgrade Pipelex to a version that reads the codegen lock format {lock_version}.",other_step="report",+ other_step_detail="Report this to whoever runs the runtime.",),PipelexErrorCode.CODEGEN_LOCK_NOT_FOUND: PipelexErrorEntry(title="No codegen lock in this directory",domain="input",retry="no",status=404,+ detail="The directory '{path}' holds no codegen lock.",actor_step="change_input",+ actor_step_detail="Check the directory codegen wrote, or generate the code into '{path}' first.",other_step="change_input",+ other_step_detail="Pass this to the caller, whose directory '{path}' holds no codegen lock.",),PipelexErrorCode.CODEGEN_DRIFTED: PipelexErrorEntry(title="The generated code has drifted from its method",domain="input",retry="no",status=409,+ detail="The generated code no longer matches its method.",actor_step="change_input",+ actor_step_detail="Generate the code again from the method, then check it again.",other_step="change_input",+ other_step_detail="Pass this to the caller, whose generated code no longer matches its method.",),PipelexErrorCode.CONNECTOR_TOOL_NOT_IN_TOOLSET: PipelexErrorEntry(title="The tool is not in the connector's toolset",domain="method",retry="no",status=422,+ detail="A model asked for the tool '{tool}', which the method's toolset does not hold.",actor_step="change_method",+ actor_step_detail="Add the tool '{tool}' to the method's toolset, or steer the prompt away from it, then run the method again.",other_step="contact_owner",+ other_step_detail="Ask the method's owner to add the tool '{tool}' to its toolset.",),PipelexErrorCode.ERASURE_INCOMPLETE: PipelexErrorEntry(title="The erasure left data behind",domain="runtime",retry="yes",status=503,+ detail="The erasure of the {resource} '{id}' did not complete, and some of its data remains.",actor_step="retry",+ actor_step_detail="Request the erasure of the {resource} '{id}' again.",other_step="report",+ other_step_detail="Report this to whoever runs the runtime.",),PipelexErrorCode.WEBHOOK_DELIVERY_FAILED: PipelexErrorEntry(title="A webhook was not delivered",domain="input",retry="yes",status=502,+ detail="The webhook was not delivered to its receiver (reason: {reason}).",actor_step="change_input",+ actor_step_detail="Check that the webhook's receiver is reachable and answers with a success status.",other_step="change_input",+ other_step_detail="Pass this to the caller, whose webhook receiver refused the delivery or could not be reached.",),}-"""The title and verdict of every Pipelex code."""+"""The title, verdict and templates of every Pipelex code."""diff --git a/pipelex/errors/unsupported_reasons.py b/pipelex/errors/unsupported_reasons.pynew file mode 100644index 000000000..10f454578--- /dev/null+++ b/pipelex/errors/unsupported_reasons.py@@ -0,0 +1,10 @@+"""The reasons the runtime gives `request.unsupported` that a client tells one refusal apart by.++A reason rides the problem's `params.reason`, so a client branches on the code and the reason together, never on+the problem's text. This module imports nothing, so a client of the hosted API reads it without loading the+interpreter.+"""++#: Contents-only resolution, the core of `POST /v1/pipe-io`, met a method calling another one by its address, which it+#: cannot fetch. A hosted run tells this refusal apart by it, since the run route fetches such a dependency.+ADDRESS_DEPENDENCY_UNSUPPORTED_REASON = "address_based_dependency"diff --git a/pipelex/graph/graph_tracer.py b/pipelex/graph/graph_tracer.pyindex 13820ddab..4a652e56f 100644--- a/pipelex/graph/graph_tracer.py+++ b/pipelex/graph/graph_tracer.py@@ -6,12 +6,12 @@ from typing import Anyfrom typing_extensions import overridefrom pipelex import log+from pipelex.errors.problem import PipelexProblemfrom pipelex.graph.condition_output_merge import ConditionOutputMerge, apply_condition_output_mergesfrom pipelex.graph.graph_tracer_protocol import GraphTracerProtocol, invocation_path_of_startfrom pipelex.graph.graphspec import (EdgeKind,EdgeSpec,- ErrorSpec,GraphSpec,IOSpec,NodeIOSpec,@@ -103,7 +103,8 @@ class _MutableNodeData:self.skip_reason: str | None = Noneself.output_preview: str | None = Noneself.metrics: dict[str, float] = {}- self.error: ErrorSpec | None = None+ self.error: PipelexProblem | None = None+ self.error_stack: str | None = Noneself.input_specs: list[IOSpec] = input_specs or []self.output_specs: list[IOSpec] = []self.execution_data: dict[str, Any] = {}@@ -138,6 +139,7 @@ class _MutableNodeData:timing=timing,node_io=node_io,error=self.error,+ error_stack=self.error_stack,metrics=self.metrics,execution_data=self.execution_data,)@@ -1110,10 +1112,8 @@ class GraphTracer(GraphTracerProtocol):node_id: str,*,ended_at: datetime,- error_type: str,- error_message: str,+ problem: PipelexProblem,error_stack: str | None = None,- caller_facing: bool = False,) -> None:"""Record failed completion of a pipe execution."""if not self._is_active:@@ -1125,13 +1125,8 @@ class GraphTracer(GraphTracerProtocol):node_data.ended_at = ended_atnode_data.status = NodeStatus.FAILED- error = ErrorSpec(- error_type=error_type,- message=error_message,- stack=error_stack,- caller_facing=caller_facing,- )- node_data.error = error+ node_data.error = problem+ node_data.error_stack = error_stack# Emit PipeEndErrorEventif self._event_log is not None:@@ -1151,7 +1146,8 @@ class GraphTracer(GraphTracerProtocol):pipe_ref=node_data.pipe_ref,pipe_type=node_data.pipe_type,ended_at=ended_at,- error=error,+ error=problem,+ error_stack=error_stack,))diff --git a/pipelex/graph/graph_tracer_manager.py b/pipelex/graph/graph_tracer_manager.pyindex 9d3e838ce..bc9e1034f 100644--- a/pipelex/graph/graph_tracer_manager.py+++ b/pipelex/graph/graph_tracer_manager.py@@ -4,6 +4,7 @@ from datetime import datetimefrom typing import TYPE_CHECKING, Anyfrom pipelex import log+from pipelex.errors.problem import PipelexProblemfrom pipelex.graph.condition_output_merge import ConditionOutputMergefrom pipelex.graph.graph_tracer import GraphTracerfrom pipelex.graph.graph_tracer_protocol import GraphTracerProtocol@@ -421,10 +422,8 @@ class GraphTracerManager(metaclass=ABCSingletonMeta):lookup_key: str,node_id: str | None,ended_at: datetime,- error_type: str,- error_message: str,+ problem: PipelexProblem,error_stack: str | None = None,- caller_facing: bool = False,) -> None:"""Record failed completion of a pipe execution.@@ -432,11 +431,8 @@ class GraphTracerManager(metaclass=ABCSingletonMeta):lookup_key: The tracer lookup key.node_id: The node ID returned from on_pipe_start.ended_at: When the pipe failed.- error_type: The exception type name.- error_message: The error message.+ problem: The problem that ended the node, in the caller's view, located at the node's pipe.error_stack: Optional stack trace.- caller_facing: Whether the message was written for the caller, as the error report of the error the- pipe raised says in its `caller_facing_message`."""if node_id is None:return@@ -448,10 +444,8 @@ class GraphTracerManager(metaclass=ABCSingletonMeta):tracer.on_pipe_end_error(node_id=node_id,ended_at=ended_at,- error_type=error_type,- error_message=error_message,+ problem=problem,error_stack=error_stack,- caller_facing=caller_facing,)def register_controller_output(diff --git a/pipelex/graph/graph_tracer_protocol.py b/pipelex/graph/graph_tracer_protocol.pyindex 1598092d2..7a0ca7754 100644--- a/pipelex/graph/graph_tracer_protocol.py+++ b/pipelex/graph/graph_tracer_protocol.py@@ -3,6 +3,7 @@ from typing import Any, Protocolfrom typing_extensions import override+from pipelex.errors.problem import PipelexProblemfrom pipelex.graph.condition_output_merge import ConditionOutputMergefrom pipelex.graph.graphspec import EdgeKind, GraphSpec, IOSpec, NodeKindfrom pipelex.system.data_inclusion_config import DataInclusionConfig@@ -160,21 +161,16 @@ class GraphTracerProtocol(Protocol):node_id: str,*,ended_at: datetime,- error_type: str,- error_message: str,+ problem: PipelexProblem,error_stack: str | None = None,- caller_facing: bool = False,) -> None:"""Record failed completion of a pipe execution.Args:node_id: The node ID returned from on_pipe_start.ended_at: When the pipe failed.- error_type: The exception type name.- error_message: The error message.+ problem: The problem that ended the node, in the caller's view, located at the node's pipe.error_stack: Optional stack trace.- caller_facing: Whether the message was written for the caller, as an error report's- `caller_facing_message` says."""...@@ -460,10 +456,8 @@ class GraphTracerNoOp(GraphTracerProtocol):node_id: str,*,ended_at: datetime,- error_type: str,- error_message: str,+ problem: PipelexProblem,error_stack: str | None = None,- caller_facing: bool = False,) -> None:passdiff --git a/pipelex/graph/graphspec.py b/pipelex/graph/graphspec.pyindex 2ab0a2c79..67d095dc0 100644--- a/pipelex/graph/graphspec.py+++ b/pipelex/graph/graphspec.py@@ -11,6 +11,7 @@ from typing import Annotated, Any, Selffrom pydantic import BaseModel, ConfigDict, Field, computed_field, field_validator, model_validator+from pipelex.errors.problem import PipelexProblemfrom pipelex.tools.typing.pydantic_utils import empty_list_factory_of# Redaction limits@@ -162,6 +163,11 @@ def _truncate_string(value: str | None, *, max_length: int) -> str | None:return value[: max_length - 3] + "..."+def cap_error_stack(*, stack: str | None) -> str | None:+ """A failed pipe's stack trace, capped at MAX_STACK_LENGTH, as every record of it carries it: the node and its event."""+ return _truncate_string(stack, max_length=MAX_STACK_LENGTH)++class PipelineRef(BaseModel):"""Reference to the pipeline that was executed."""@@ -277,29 +283,6 @@ class NodeIOSpec(BaseModel):outputs: list[IOSpec] = Field(default_factory=empty_list_factory_of(IOSpec))-class ErrorSpec(BaseModel):- """Error information for failed nodes.-- Stack traces are automatically truncated to MAX_STACK_LENGTH.- """-- model_config = ConfigDict(extra="forbid", strict=True)-- error_type: str- message: str- stack: str | None = None- # Whether `message` was written for the caller, as the `caller_facing_message` of the error report of the error the- # pipe raised says: a reader that discloses failures to the caller under the strict disclosure shows the message- # only when this is true.- caller_facing: bool = False-- @field_validator("stack", mode="after")- @classmethod- def truncate_stack(cls, value: str | None) -> str | None:- """Truncate stack trace to MAX_STACK_LENGTH."""- return _truncate_string(value, max_length=MAX_STACK_LENGTH)--class ModelUsageSpec(BaseModel):"""What one inference model actually did for a node.@@ -455,13 +438,24 @@ class NodeSpec(BaseModel):validation_alias="io",serialization_alias="io",)- error: ErrorSpec | None = None+ # The problem that ended a failed node, in the caller's view, located at the node's own pipe; None for every other+ # status.+ error: PipelexProblem | None = None+ # The stack trace of the error that ended a failed node, when the graph's data inclusion asks for it, truncated to+ # MAX_STACK_LENGTH.+ error_stack: str | None = Nonetags: dict[str, str] = Field(default_factory=dict)metrics: dict[str, float] = Field(default_factory=dict)# Inference usage attributed to this node; None under NodeUsageSpec invariant 1.usage: NodeUsageSpec | None = Noneexecution_data: dict[str, Any] = Field(default_factory=dict)+ @field_validator("error_stack", mode="after")+ @classmethod+ def truncate_error_stack(cls, value: str | None) -> str | None:+ """Truncate the stack trace to MAX_STACK_LENGTH."""+ return cap_error_stack(stack=value)+class EdgeSpec(BaseModel):"""Specification for an edge in the execution graph."""diff --git a/pipelex/graph/node_problem.py b/pipelex/graph/node_problem.pynew file mode 100644index 000000000..a8575d701--- /dev/null+++ b/pipelex/graph/node_problem.py@@ -0,0 +1,46 @@+"""What the execution graph records of the error that ended a node: its problem, in the caller's view."""++from mthds.protocol.problem.registry import CoreCode++from pipelex import log+from pipelex.base_exceptions import PipelexError+from pipelex.errors.problem import PipelexProblem, ProblemView, make_location, make_problem+from pipelex.tools.log.error_fields import error_fields++NODE_PROBLEM_FAULT_MESSAGE = "The problem of a failed pipe could not be built for its trace"+"""The error logged when a failed pipe's problem raises while its node's failure is traced."""+++def make_node_problem(*, error: BaseException, pipe_code: str, pipe_path: list[str]) -> PipelexProblem:+ """The problem a node ended by `error` records, located at the node's own pipe.++ The graph is read by whoever reads the run, so the problem is the caller's view: the code's sentences, rendered from+ the parameters a caller may read, and never the error's own message. Its location names the node's pipe and its+ path from the entry pipe, whatever pipe below it the failure happened in. An exception that is not a Pipelex error+ is a fault of ours, `runtime.unexpected`.++ Tracing never changes how a run fails. This runs while the pipe's own error is being handled, on its way to the+ caller, so building the problem must not raise in its place: a problem that cannot be built is logged as an error,+ and the node records `runtime.unexpected`.++ Args:+ error: The error that ended the node.+ pipe_code: The node's pipe.+ pipe_path: The pipe codes from the entry pipe down to the node's pipe, which ends it.++ Returns:+ The node's problem.+ """+ location = make_location(pipe=pipe_code, path=pipe_path or [pipe_code])+ if isinstance(error, PipelexError):+ try:+ return error.to_problem(view=ProblemView.CALLER, failure_location=location)+ except Exception as problem_fault: # ruff: ignore[blind-except]+ # Unbounded code: `to_problem` reads hooks overridden across the whole error hierarchy, the errors plugins+ # define included, and walks the error's cause chain, so what it raises cannot be enumerated. The pipe's own+ # error is the one the run fails with, so the fault is logged and the node records a fault of ours.+ log.error(+ NODE_PROBLEM_FAULT_MESSAGE,+ fields={"failed_error_type": type(error).__name__, **error_fields(exc=problem_fault)},+ )+ return make_problem(code=CoreCode.RUNTIME_UNEXPECTED, view=ProblemView.CALLER, location=location)diff --git a/pipelex/graph/traced_failure.py b/pipelex/graph/traced_failure.pydeleted file mode 100644index 6b36b9b4c..000000000--- a/pipelex/graph/traced_failure.py+++ /dev/null@@ -1,44 +0,0 @@-"""What the execution graph records of the error that ended a node: its message, and whether it was written for the caller."""--from typing import NamedTuple--from pipelex import log-from pipelex.base_exceptions import PipelexError-from pipelex.tools.log.error_fields import error_fields--ERROR_REPORT_FAULT_MESSAGE = "The error report of a failed pipe could not be built for its trace"-"""The error logged when a failed pipe's error report raises while its node's failure is traced."""---class TracedFailure(NamedTuple):- """The message a failed node records, and whether that message was written for the caller."""-- message: str- caller_facing: bool---def make_traced_failure(*, error: BaseException) -> TracedFailure:- """What a node ended by `error` records of it.-- Whether the message was written for the caller is the error report's to say, as it says it of the run's own failure:- a Pipelex error records its report's message and `caller_facing_message`, and any other exception records its text,- which is never written for the caller.-- Tracing never changes how a run fails. This runs while the pipe's own error is being handled, on its way to the- caller, so building the report must not raise in its place: a report that cannot be built is logged as an error,- and the node records the error's text, as for any other exception.- """- if isinstance(error, PipelexError):- try:- error_report = error.to_error_report()- except Exception as report_fault: # ruff: ignore[blind-except]- # Unbounded code: `to_error_report` is overridden across the whole error hierarchy, the errors plugins- # define included, and walks the error's cause chain, so what it raises cannot be enumerated. The pipe's own- # error is the one the run fails with, so the fault is logged and the node records the error's text.- log.error(- ERROR_REPORT_FAULT_MESSAGE,- fields={"failed_error_type": type(error).__name__, **error_fields(exc=report_fault)},- )- return TracedFailure(message=str(error), caller_facing=False)- return TracedFailure(message=error_report.message, caller_facing=error_report.caller_facing_message)- return TracedFailure(message=str(error), caller_facing=False)diff --git a/pipelex/hosted/client_factory.py b/pipelex/hosted/client_factory.pyindex 5eca71e6d..97690e746 100644--- a/pipelex/hosted/client_factory.py+++ b/pipelex/hosted/client_factory.py@@ -85,4 +85,4 @@ def make_hosted_client(*, base_url: str | None = None, api_key: str | None = Non"Give scheme://host[:port], with http or https and no path, query or credentials, such as https://api.pipelex.com.")# Not chained: the SDK's message quotes the rejected value whole, credentials included, and a traceback prints it.- raise HostedBaseUrlError(msg) from None+ raise HostedBaseUrlError(msg).with_params(setting=source) from Nonediff --git a/pipelex/hosted/error_rendering.py b/pipelex/hosted/error_rendering.pyindex 22c5331c4..b6a2f3394 100644--- a/pipelex/hosted/error_rendering.py+++ b/pipelex/hosted/error_rendering.py@@ -30,6 +30,7 @@ from pipelex_sdk.errors import (from pipelex_sdk.validation_models import ValidationErrorItemfrom pipelex.base_exceptions import ErrorDomain+from pipelex.errors.error_codes import error_code_specfrom pipelex.hosted.client_factory import HOSTED_API_DEFAULT_BASE_URL, PIPELEX_API_KEY_ENV_KEY, PIPELEX_BASE_URL_ENV_KEYfrom pipelex.hosted.exceptions import HostedMethodInvalidError, HostedRunError, HostedRunInterruptedError, HostedRunPollingError@@ -167,10 +168,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"- # 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.retryable+ # Who acts and whether a retry can succeed are the error's code's.+ hosted_code_spec = error_code_spec(error.resolve_error_code())+ error_domain = ErrorDomain.from_problem_domain(hosted_code_spec.domain)+ retryable = hosted_code_spec.invites_retryif 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 9f9f3d111..1e071b39c 100644--- a/pipelex/hosted/exceptions.py+++ b/pipelex/hosted/exceptions.py@@ -1,7 +1,8 @@-from typing import ClassVar+from typing import Any, ClassVarfrom mthds.protocol.problem.registry import CoreCodefrom pipelex_sdk.validation_models import ValidationErrorItem+from typing_extensions import overridefrom pipelex.base_exceptions import PipelexErrorfrom pipelex.cogt.inference.error_classification import UserAction, UserActionKind@@ -32,7 +33,6 @@ class HostedBaseUrlError(HostedRunError):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",)- _authors_caller_facing_message: ClassVar[bool] = Trueclass HostedRunSourceError(HostedRunError):@@ -44,7 +44,6 @@ class HostedRunSourceError(HostedRunError):"""error_code = CoreCode.CLIENT_ARGUMENT_INVALID- _authors_caller_facing_message: ClassVar[bool] = Trueclass HostedMethodInvalidError(HostedRunError):@@ -57,7 +56,6 @@ class HostedMethodInvalidError(HostedRunError):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] = Truedef __init__(self, message: str, *, validation_errors: list[ValidationErrorItem]):super().__init__(message)@@ -85,6 +83,10 @@ class HostedRunPollingError(HostedRunError):),)+ @override+ def problem_params(self) -> dict[str, Any]:+ return {"pipeline_run_id": self.pipeline_run_id}+class HostedRunOutcomeUnknownError(HostedRunError):"""The request that runs the method was sent, and the connection failed before its answer came back.@@ -116,7 +118,6 @@ class HostedRunInterruptedError(HostedRunError):"""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):if pipeline_run_id is None:@@ -138,6 +139,10 @@ class HostedRunInterruptedError(HostedRunError):if pipeline_run_id is not None:self.with_error_code(CoreCode.CLIENT_FOLLOW_FAILED)+ @override+ def problem_params(self) -> dict[str, Any]:+ return {"pipeline_run_id": self.pipeline_run_id}+class HostedLocalFileUploadUnavailableError(HostedRunError):"""A hosted run's inputs name a local file, and its method calls another method by its address.@@ -152,4 +157,3 @@ class HostedLocalFileUploadUnavailableError(HostedRunError):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",)- _authors_caller_facing_message: ClassVar[bool] = Truediff --git a/pipelex/hosted/hosted_inputs.py b/pipelex/hosted/hosted_inputs.pyindex 5618108c0..f3a598ab1 100644--- a/pipelex/hosted/hosted_inputs.py+++ b/pipelex/hosted/hosted_inputs.py@@ -33,10 +33,13 @@ from mthds.protocol.input_form import (TextItem,UnknownItem,)+from mthds.protocol.problem.registry import CoreCodefrom pipelex_sdk.client import PipelexAPIClientfrom pipelex_sdk.crate_models import CrateInvalidReport, MthdsFileItem, PipeIORequest+from pipelex_sdk.errors import ApiResponseErrorfrom pipelex_sdk.upload import UploadRecord+from pipelex.errors.unsupported_reasons import ADDRESS_DEPENDENCY_UNSUPPORTED_REASONfrom pipelex.hosted.exceptions import HostedLocalFileUploadUnavailableError, HostedMethodInvalidErrorfrom pipelex.methods.address_dependencies import ADDRESS_DEPENDENCY_REFUSAL_MARKERfrom pipelex.tools.uri.resolved_uri import ResolvedLocalPath@@ -50,6 +53,10 @@ _HTTP_URL_PATTERN = re.compile(r"^https?://", re.IGNORECASE)_NOT_LOCAL_PREFIXES: tuple[str, ...] = ("pipelex-storage://", "data:")#: A `file://` URI, which a local run reads as the local path it names._FILE_URI_PREFIX = "file://"+#: The code of the refusal an in-memory resolution answers a method calling another one by its address with, carrying+#: the reason `ADDRESS_DEPENDENCY_UNSUPPORTED_REASON` (`resolve_crate_from_contents` in `pipelex/pipeline/resolve_bundle.py`).+#: The run route fetches such a dependency.+_ADDRESS_DEPENDENCY_REFUSAL_CODES: frozenset[str] = frozenset({CoreCode.REQUEST_UNSUPPORTED})#: The dependency's address, as the refusal of `POST /v1/pipe-io` quotes it when the method calls a package by its#: address that the request did not ship (`ADDRESS_DEPENDENCY_REFUSAL_MARKER`). The run route fetches such a dependency;#: pipe-io never fetches.@@ -246,11 +253,36 @@ def _with_storage_uris(*, anchored: AnchoredInputs, descriptor: PipeInputFormDesreturn _walk_inputs(inputs=anchored.inputs, descriptor=descriptor, at_file_position=_rewrite)-def _address_dependency_refusal(*, report: CrateInvalidReport) -> HostedLocalFileUploadUnavailableError | None:+def _address_dependency_refusal(*, refusal: ApiResponseError) -> HostedLocalFileUploadUnavailableError | None:"""The error to raise when pipe-io refused the method for calling another one by its address, else `None`.- The run route fetches such a dependency, so the method is not at fault. The refusal's own advice, to send the- dependency's contents, is meant for the API's callers, so the error names the dependency and leaves the advice out.+ An in-memory resolution answers that refusal with its problem, coded `request.unsupported` and giving the reason+ `ADDRESS_DEPENDENCY_UNSUPPORTED_REASON`: the request is what it cannot serve, not the method, which the run route+ fetches the dependency of. The tree resolution behind pipe-io answers a call into a package nothing shipped with its+ invalid verdict instead (`_unshipped_dependency_refusal`). The refusal's own advice, to send the dependency's contents, is meant for the API's+ callers, so the error leaves it out.++ The error does not name the dependency, because the problem does not carry it: `request.unsupported` declares only+ `field` and `reason`, and the sentence naming the dependency's address is the server's message, which reaches its+ operator alone. Naming it would need a parameter of the error registry for the address.+ """+ if refusal.code not in _ADDRESS_DEPENDENCY_REFUSAL_CODES:+ return None+ params = (refusal.problem_document or {}).get("params")+ if not isinstance(params, dict) or cast("dict[str, Any]", params).get("reason") != ADDRESS_DEPENDENCY_UNSUPPORTED_REASON:+ return None+ msg = "Local file upload is not available yet for methods with address-based dependencies, and the inputs name a local file"+ return HostedLocalFileUploadUnavailableError(msg)+++def _unshipped_dependency_refusal(*, report: CrateInvalidReport) -> HostedLocalFileUploadUnavailableError | None:+ """The error to raise when pipe-io's invalid verdict refuses the method for calling a package by its address, else `None`.++ pipe-io resolves the method's tree with only the packages the request ships, and answers a call into a package+ nothing shipped with its invalid verdict, whose item quotes the dependency's address after+ `ADDRESS_DEPENDENCY_REFUSAL_MARKER`. The run route fetches such a dependency, so the method is not at fault. The+ refusal's own advice, to send the dependency's contents, is meant for the API's callers, so the error names the+ dependency and leaves the advice out."""messages = [report.message, *(item.message for item in report.validation_errors)]refusal = next((message for message in messages if ADDRESS_DEPENDENCY_REFUSAL_MARKER in message), None)@@ -283,7 +315,8 @@ async def prepare_hosted_inputs(Raises:HostedLocalFileUploadUnavailableError: If pipe-io cannot load the method because it calls another method by- its address: the run route would, so the file has to reach it as a URL.+ its address, refusing the request or answering its verdict: the run route would, so the file has to reach+ it as a URL.HostedMethodInvalidError: If the method does not load, with the hosted API's labelled validation items.ApiResponseError: If the hosted API refuses the pipe-io request (an unknown method, a key it refuses).InputPreparationError: If an upload fails, or a local file cannot be read.@@ -291,10 +324,15 @@ async def prepare_hosted_inputs(if not inputs or not inputs_name_a_local_file(inputs=inputs, base_dir=inputs_base_dir):return PreparedHostedInputs(inputs=inputs, uploads=[], pipe_ref=None)- report = await client.pipe_io(PipeIORequest(files=mthds_files, method_ref=method_ref, method_id=method_id, pipe_ref=pipe_code))+ try:+ report = await client.pipe_io(PipeIORequest(files=mthds_files, method_ref=method_ref, method_id=method_id, pipe_ref=pipe_code))+ except ApiResponseError as refusal:+ if (address_dependency_refusal := _address_dependency_refusal(refusal=refusal)) is not None:+ raise address_dependency_refusal from refusal+ raiseif isinstance(report, CrateInvalidReport):- if (address_dependency_refusal := _address_dependency_refusal(report=report)) is not None:- raise address_dependency_refusal+ if (unshipped_dependency_refusal := _unshipped_dependency_refusal(report=report)) is not None:+ raise unshipped_dependency_refusalmsg = f"The hosted API cannot load the method: {report.message}"raise HostedMethodInvalidError(msg, validation_errors=report.validation_errors)selected_pipe_ref = report.pipe_refdiff --git a/pipelex/kernel/llm_ops.py b/pipelex/kernel/llm_ops.pyindex ce23b49ee..730c08068 100644--- a/pipelex/kernel/llm_ops.py+++ b/pipelex/kernel/llm_ops.py@@ -144,12 +144,14 @@ def check_llm_setting_with_served_model(*, llm_setting: LLMSetting, is_structure)except LLMCapabilityError as refusal:if registered_check and not registered_check.is_builtin:- # An external plugin's text may carry what it keeps private: it reaches the caller only if the plugin vouched for it+ # An external plugin's text may carry what it keeps private: it rides only the operator's diagnosticsraise# A built-in worker names the model by its description, which carries the SDK, the backend and the# provider's model id: the caller who wrote the setting knows the model by its deck handle alone.msg = str(refusal).replace(inference_model.desc, inference_model.name)- raise LLMSettingRefusedError(msg) from refusal+ # The model by its handle, and the capability the worker's refusal named, which a caller reads alike.+ capability = refusal.given_params.get("capability")+ raise LLMSettingRefusedError(msg).with_params(model=inference_model.name, capability=capability) from refusal# A resolution chain is at most a handful of hops (preset -> alias -> handle); this onlydiff --git a/pipelex/libraries/bundle_resources.py b/pipelex/libraries/bundle_resources.pyindex f5b75d31a..f49a27f61 100644--- a/pipelex/libraries/bundle_resources.py+++ b/pipelex/libraries/bundle_resources.py@@ -45,4 +45,4 @@ def check_submitted_files(*, blueprints: Iterable[PipelexBundleBlueprint], submif"The bundle was submitted with files none of its steps names: {listed}. Submit only the files a step reads, ""each keyed by the path the step names, such as a PipeDocGen step's 'template_file', relative to the bundle.")- raise BundleResourceNotNamedError(msg)+ raise BundleResourceNotNamedError(msg).with_params(field="resources")diff --git a/pipelex/libraries/exceptions.py b/pipelex/libraries/exceptions.pyindex 30ccb6b5c..94f1979c0 100644--- a/pipelex/libraries/exceptions.py+++ b/pipelex/libraries/exceptions.py@@ -92,7 +92,6 @@ class MethodTreeLoadError(LibraryLoadingError):"""error_code = CoreCode.METHOD_PACKAGE_INVALID- _authors_caller_facing_message = Trueclass EmptyMethodTreeError(MethodTreeLoadError):@@ -129,7 +128,6 @@ class MethodRequirementsError(LibraryLoadingError):"""error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERROR- _authors_caller_facing_message = Truedef __init__(self, message: str, *, items: list[PipelexBundleBlueprintValidationErrorData]):super().__init__(message, blueprint_validation_errors=items)diff --git a/pipelex/libraries/library_manager.py b/pipelex/libraries/library_manager.pyindex 67884e950..1c1328b81 100644--- a/pipelex/libraries/library_manager.py+++ b/pipelex/libraries/library_manager.py@@ -18,7 +18,7 @@ from pydantic import BaseModel, PydanticUserError, ValidationErrorfrom typing_extensions import overridefrom pipelex import log-from pipelex.base_exceptions import PipelexError, SecurityError, error_domain_is_input, iter_cause_chain+from pipelex.base_exceptions import ErrorDomain, PipelexError, SecurityError, iter_cause_chainfrom pipelex.cogt.exceptions import ModelChoiceNotFoundErrorfrom pipelex.config import is_pipe_func_sandbox_hostedfrom pipelex.core.bundle_resources.bundle_resource import canonical_submitted_files@@ -163,8 +163,10 @@ 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)]).with_error_code(- CoreCode.METHOD_DEPENDENCY_INVALID+ raise (+ MthdsParserError(msg, validation_errors=[PipelexBundleBlueprintValidationErrorData(source=bundle_source, message=msg)])+ .with_error_code(CoreCode.METHOD_DEPENDENCY_INVALID)+ .with_params(package=package_address, finding=f"its bundle '{bundle_source}' is not UTF-8 text")) from exctry:return MthdsParser.make_pipelex_bundle_blueprint(mthds_content=mthds_content, mthds_source=bundle_source)@@ -174,9 +176,11 @@ def _parse_dependency_bundle(*, mthds_path: Path, bundle_source: str, package_adcontext = f"Bundle '{bundle_source}' of method package '{package_address}' does not parse"items = [item.model_copy(update={"source": bundle_source, "message": f"{context}: {item.message}"}) for item in exc.validation_errors]msg = f"{context}: {exc.message}"- raise MthdsParserError(- msg, validation_errors=items or [PipelexBundleBlueprintValidationErrorData(source=bundle_source, message=msg)]- ).with_error_code(CoreCode.METHOD_DEPENDENCY_INVALID) from exc+ raise (+ MthdsParserError(msg, validation_errors=items or [PipelexBundleBlueprintValidationErrorData(source=bundle_source, message=msg)])+ .with_error_code(CoreCode.METHOD_DEPENDENCY_INVALID)+ .with_params(package=package_address, finding=f"its bundle '{bundle_source}' does not parse")+ ) from excdef _public_dependency_pipe_refs(*, resolved_dep: ResolvedDependency, blueprints: list[PipelexBundleBlueprint]) -> set[str] | None:@@ -327,7 +331,7 @@ def _locating_pipe_build_refusals(except (SecurityError, LibraryError, PipeValidationError):raiseexcept PipelexError as refusal:- if not error_domain_is_input(refusal.to_error_report().error_domain):+ if not ErrorDomain.from_problem_domain(refusal.resolve_domain()).is_input:raiseauthored_pipe_code = elaboration.parent_pipe_code if elaboration is not None else pipe_coderaise PipeLoadRefusalError.make_from_refusal(@@ -642,13 +646,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).with_error_code(CoreCode.REQUEST_INVALID)+ raise BundleResourcePathError(msg).with_error_code(CoreCode.REQUEST_INVALID).with_params(field="resources")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).with_error_code(CoreCode.REQUEST_INVALID)+ raise BundleResourcePathError(msg).with_error_code(CoreCode.REQUEST_INVALID).with_params(field="resources")return joineddef _submitted_tree(self, *, library_id: str) -> MethodTree | None:@@ -1868,7 +1872,7 @@ class LibraryManager(LibraryManagerAbstract):address_dependency_sources=address_dependency_sources,)except (MethodFetchDisabledError, MethodDependencyFetchError, MethodDependencyNotShippedError) as exc:- # The item carries the caller-facing text; the host's log keeps the whole cause chain, git's raw output+ # The item carries the sentence its code renders; the host's log keeps the whole cause chain, git's raw output# included, since a cause on the host (git missing, an unwritable clone directory) becomes an item too.causes = " <- ".join(f"{type(cause).__name__}: {cause}" for cause in iter_cause_chain(exc))log.warning("A method package could not be resolved", fields={"package_address": full_address, **error_fields(exc=exc, text=causes)})diff --git a/pipelex/libraries/pipe/exceptions.py b/pipelex/libraries/pipe/exceptions.pyindex 6818e96f5..da9576e8a 100644--- a/pipelex/libraries/pipe/exceptions.py+++ b/pipelex/libraries/pipe/exceptions.py@@ -38,9 +38,8 @@ class EntryPipeNotFoundError(PipeNotFoundError):``request.pipe_unspecified`` where the caller named no pipe and the method declares no entry pipe. An entry pipethe 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 disclosure- keeps 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.+ The message names only the caller's own `pipe_code`, and each raise site owes that invariant: a+ message here may name what the caller typed and nothing from the loaded library."""error_code = ErrorCodeSet(@@ -58,7 +57,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.",)- _authors_caller_facing_message = Trueclass EntryPipeAmbiguousError(PipeLibraryError):@@ -66,19 +64,20 @@ 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- — ``request.pipe_ambiguous``, same reasoning as :class:`EntryPipeNotFoundError`; several entry pipes the method- itself declares choose ``method.pipe_unresolved``.+ — ``request.pipe_ambiguous``, same reasoning as :class:`EntryPipeNotFoundError`. A request naming no pipe of a+ method declaring several entry pipes chooses ``request.pipe_unspecified`` with those pipes as its candidates, and+ an entry pipe the method itself declares that matches pipes in several domains chooses ``method.ref_ambiguous``.- Caller-facing copy: the message names the caller's own `pipe_code` and the qualified `pipe_ref`s- of bundles they loaded themselves, so it survives STRICT disclosure intact — and it has to, since- the candidates are the only thing that makes the error actionable. That holds because the entry+ The message names the caller's own `pipe_code` and the qualified `pipe_ref`s of bundles they+ loaded themselves, the candidates being the only thing that makes the error actionable, and a raise+ site gives them as the code's `candidates` parameter, which the caller reads. That holds because the entrylibrary carries only the caller's own bundles: the runner passes no `library_dirs` and nodeployment sets `PIPELEXPATH`, so no host-private `.mthds` is merged into it. It is a property ofhow the runner is deployed, not a rule this class enforces — a deployment that did merge a hostlibrary would put host `pipe_ref`s in this message."""- error_code = ErrorCodeSet(default=CoreCode.REQUEST_PIPE_AMBIGUOUS, others=(CoreCode.METHOD_PIPE_UNRESOLVED,))+ error_code = ErrorCodeSet(default=CoreCode.REQUEST_PIPE_AMBIGUOUS, others=(CoreCode.REQUEST_PIPE_UNSPECIFIED, CoreCode.METHOD_REF_AMBIGUOUS))user_action = UserAction(kind=UserActionKind.CHANGE_INPUT,# Both spellings, because both raise sites reach this one detail: the bare-code arm is fixed by@@ -86,4 +85,3 @@ 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.",)- _authors_caller_facing_message = Truediff --git a/pipelex/libraries/pipe/pipe_library.py b/pipelex/libraries/pipe/pipe_library.pyindex 599dfa648..1626fcba7 100644--- a/pipelex/libraries/pipe/pipe_library.py+++ b/pipelex/libraries/pipe/pipe_library.py@@ -120,8 +120,10 @@ class PipeLibrary(RootModel[PipeLibraryRoot], PipeLibraryAbstract):return matches[0]if len(matches) > 1:domains = [match.domain_code for match in matches]+ # The aliased keys the matches are loaded under, the spellings that name each one unambiguously.+ candidates = sorted(f"{alias}->{match.pipe_ref}" for match in matches)msg = f"Ambiguous cross-package pipe code '{pipe_code}' found in domains: {domains}. Use domain-qualified ref."- raise PipeLibraryError(msg).with_error_code(CoreCode.METHOD_REF_AMBIGUOUS)+ raise PipeLibraryError(msg).with_error_code(CoreCode.METHOD_REF_AMBIGUOUS).with_params(ref=pipe_code, candidates=candidates)return Nonereturn None@@ -158,7 +160,8 @@ class PipeLibrary(RootModel[PipeLibraryRoot], PipeLibraryAbstract):# asserting the opposite — and handed a `user_action` naming candidates that never existed.raiseexcept PipeLibraryError as exc:- raise EntryPipeAmbiguousError(str(exc)) from exc+ # The candidates the lookup found, which the refusal's code names to the caller and a selection reads back.+ raise EntryPipeAmbiguousError(str(exc)).with_params(pipe=pipe_code, candidates=exc.given_params.get("candidates")) from excif pipe is not None:return pipe@@ -173,7 +176,7 @@ class PipeLibrary(RootModel[PipeLibraryRoot], PipeLibraryAbstract):if len(matches) > 1:candidates = sorted(match.pipe_ref for match in matches)msg = f"Pipe code '{pipe_code}' is ambiguous — it is declared by {candidates}. Name one of them explicitly, as 'domain.pipe_code'."- raise EntryPipeAmbiguousError(msg)+ raise EntryPipeAmbiguousError(msg).with_params(pipe=pipe_code, candidates=candidates)return None@override@@ -184,7 +187,7 @@ class PipeLibrary(RootModel[PipeLibraryRoot], PipeLibraryAbstract):f"Pipe '{pipe_code}' could not be resolved. Check for typos and make sure its bundle is loaded. ""A bare code only matches this library's own domains — a pipe from a dependency package must be named 'alias->pipe_code'.")- raise EntryPipeNotFoundError(msg)+ raise EntryPipeNotFoundError(msg).with_params(pipe=pipe_code)return the_pipedef add_dependency_pipe(self, *, alias: str, pipe: PipeAbstract, is_exported: bool) -> None:diff --git a/pipelex/methods/exceptions.py b/pipelex/methods/exceptions.pyindex 5853bf536..b813d15f9 100644--- a/pipelex/methods/exceptions.py+++ b/pipelex/methods/exceptions.py@@ -1,6 +1,7 @@-from typing import ClassVar+from typing import Any, ClassVar, Selffrom mthds.protocol.problem.registry import CoreCode+from typing_extensions import overridefrom pipelex.base_exceptions import PipelexErrorfrom pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeDeclaration, ErrorCodeSet@@ -10,12 +11,10 @@ from pipelex.errors.registry.pipelex_codes import PipelexErrorCodeclass MethodRefError(PipelexError):"""Base class for errors while resolving a method reference (`<address>[@<tag>]`).- Every subclass describes the caller's own reference or the package it points at,- so the messages are caller-facing by design.+ Every subclass describes the caller's own reference or the package it points at."""error_code: ClassVar[ErrorCodeDeclaration] = ABSTRACT_ERROR- _authors_caller_facing_message: ClassVar[bool] = Trueclass MethodRefParseError(MethodRefError):@@ -23,6 +22,11 @@ class MethodRefParseError(MethodRefError):error_code = ErrorCodeSet(default=CoreCode.REQUEST_INVALID, others=(CoreCode.REQUEST_UNSUPPORTED,))+ @override+ def problem_params(self) -> dict[str, Any]:+ # The reference is the request's `method_ref`; an address it does not fetch is one off GitHub.+ return {"field": "method_ref", "reason": "address_not_on_github"}+class MethodFetchError(MethodRefError):"""Fetching the repository behind a method reference failed (clone, tag verification, or commit resolution).@@ -38,6 +42,17 @@ class MethodFetchError(MethodRefError):others=(PipelexErrorCode.CONFIG_DEPENDENCY_MISSING, CoreCode.METHOD_NOT_FOUND, CoreCode.METHOD_PACKAGE_INVALID),)+ method_ref: str | None = None++ def for_method_ref(self, *, method_ref: str) -> Self:+ """Name the method reference whose fetch failed, which the codes' sentences name; returns this error."""+ self.method_ref = method_ref+ return self++ @override+ def problem_params(self) -> dict[str, Any]:+ return {"method_ref": self.method_ref}+class MethodPackageNotFoundError(MethodRefError):"""No package inside the fetched repository matches the requested address by manifest identity."""diff --git a/pipelex/methods/fetching.py b/pipelex/methods/fetching.pyindex f8685f83e..ab4acff1d 100644--- a/pipelex/methods/fetching.py+++ b/pipelex/methods/fetching.py@@ -232,12 +232,15 @@ def fetch_method_package(clone_default_branch(clone_url=effective_clone_url, destination=dest_dir)except VCSFetchError as exc:msg = f"Failed to fetch method '{ref.ref_str}': {_without_host_directory(text=exc.message, directory=dest_dir)}"- raise MethodFetchError(msg) from exc-- if ref.tag:- ensure_cloned_at_tag(clone_dir=dest_dir, ref=ref)+ raise MethodFetchError(msg).for_method_ref(method_ref=ref.ref_str) from exc- commit_sha = resolve_head_commit_sha(clone_dir=dest_dir)+ try:+ if ref.tag:+ ensure_cloned_at_tag(clone_dir=dest_dir, ref=ref)+ commit_sha = resolve_head_commit_sha(clone_dir=dest_dir)+ except MethodFetchError as fetch_error:+ # The steps after the clone know the clone, not the reference the caller sent, which the sentences name.+ raise fetch_error.for_method_ref(method_ref=ref.ref_str) # ruff: ignore[raise-without-from-inside-except]located = locate_package_in_clone(clone_root=dest_dir, requested_address=ref.address)ensure_package_within_bounds(package_dir=located.package_dir, package_address=located.full_address)if refuse_structures:diff --git a/pipelex/methods/package_locator.py b/pipelex/methods/package_locator.pyindex 7ec24060b..edb678587 100644--- a/pipelex/methods/package_locator.py+++ b/pipelex/methods/package_locator.py@@ -190,11 +190,13 @@ def locate_package_in_clone(*, clone_root: Path, requested_address: str) -> Packif scan.skipped_manifests:details = "; ".join(scan.skipped_manifests)msg = f"{msg} Manifests skipped: {details}"- raise MethodPackageNotFoundError(msg)+ raise MethodPackageNotFoundError(msg).with_params(method_ref=requested_address)matched = ", ".join(sorted(f"{candidate.full_address} ({candidate.package_dir.name}/)" for candidate in matches))msg = (f"Ambiguous method address '{requested_address}': it matches more than one package in the fetched repository: {matched}. "f"Use the package's full address (address + '/' + name) to disambiguate.")- raise MethodPackageAmbiguityError(msg)+ raise MethodPackageAmbiguityError(msg).with_params(+ method_ref=requested_address, candidates=sorted(candidate.full_address for candidate in matches)+ )diff --git a/pipelex/methods/structures_check.py b/pipelex/methods/structures_check.pyindex 7e02e7dd5..5e91aa767 100644--- a/pipelex/methods/structures_check.py+++ b/pipelex/methods/structures_check.py@@ -222,7 +222,8 @@ def ensure_no_structured_content_python(*, package_dir: Path, package_address: sf"Method package '{package_address}' declares Python structure classes ({details}), which would be imported "f"into the runner's own process. Refused: {STRUCTURES_REFUSAL_RULE}. {STRUCTURES_REFUSAL_REMEDY}")- raise MethodStructuresRefusedError(msg)+ # A package's files are named by the package's address, as the caller names the package.+ raise MethodStructuresRefusedError(msg).with_params(files=[f"{package_address}/{violation.relative_path}" for violation in violations])def ensure_no_structured_content_in_library_sources(*, sources_by_dir: Mapping[Path, Mapping[str, str]]) -> None:@@ -253,4 +254,4 @@ def ensure_no_structured_content_in_library_sources(*, sources_by_dir: Mapping[Pf"This method declares Python structure classes ({details}), which would be imported into the runner's "f"own process. Refused: {STRUCTURES_REFUSAL_RULE}. {STRUCTURES_REFUSAL_REMEDY}")- raise MethodStructuresRefusedError(msg)+ raise MethodStructuresRefusedError(msg).with_params(files=[violation.relative_path for violation in violations])diff --git a/pipelex/mthds_parsing/exceptions.py b/pipelex/mthds_parsing/exceptions.pyindex a46af6035..981c2e8bd 100644--- a/pipelex/mthds_parsing/exceptions.py+++ b/pipelex/mthds_parsing/exceptions.py@@ -50,8 +50,7 @@ class MthdsParserError(PipelexError):Covers every way the caller's ``.mthds`` source can be rejected — TOML thatdoes not parse, and TOML that parses but fails blueprint validation. The- message is always caller-facing copy describing a fault in the caller's own- input.+ message always describes a fault in the caller's own input.The default ``method.invalid`` is the umbrella refusal whose items carry their own codes. A raise site thatfinds one fault chooses its code: ``method.syntax`` for a source that does not parse, ``method.schema_violation``@@ -71,9 +70,6 @@ class MthdsParserError(PipelexError):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 = Truedef __init__(self,diff --git a/pipelex/pipe_controllers/binding/binding_step.py b/pipelex/pipe_controllers/binding/binding_step.pyindex 6f51fe705..7ae2a1c79 100644--- a/pipelex/pipe_controllers/binding/binding_step.py+++ b/pipelex/pipe_controllers/binding/binding_step.py@@ -18,6 +18,7 @@ from typing import Anyfrom pydantic import BaseModel, ConfigDictfrom pipelex import log+from pipelex.base_exceptions import PipelexUnexpectedErrorfrom pipelex.core.concepts.concept import Conceptfrom pipelex.core.memory.absence import AbsenceKind, AbsenceRecordfrom pipelex.core.memory.working_memory import PRIVATE_BINDING_NAME_PREFIX, WorkingMemory@@ -28,8 +29,8 @@ from pipelex.core.stuffs.stuff_content import StuffContentfrom pipelex.core.stuffs.stuff_factory import StuffFactoryfrom pipelex.graph.graph_tracer_manager import GraphTracerManagerfrom pipelex.graph.graphspec import NodeKind+from pipelex.graph.node_problem import make_node_problemfrom pipelex.graph.stuff_io_spec import make_stuff_io_spec-from pipelex.graph.traced_failure import make_traced_failurefrom pipelex.pipe_controllers.binding.binding_derivation import BindingDerivationfrom pipelex.pipe_controllers.binding.binding_value import FoundNothing, bind_contentfrom pipelex.system.job_metadata import JobMetadata@@ -288,23 +289,11 @@ class BindingStep(BaseModel):tracer_manager = GraphTracerManager.get_instance()if tracer_manager is None:return- error_type: str- error_message: str- caller_facing: bool- if error is None:- error_type = "UnknownError"- error_message = "the binding step stopped without binding a value"- caller_facing = False- else:- traced_failure = make_traced_failure(error=error)- error_type = type(error).__name__- error_message = traced_failure.message- caller_facing = traced_failure.caller_facing+ # A binding step runs no pipe: its node's pipe code is the path it binds from, and its problem is located there.+ stopping_error = error or PipelexUnexpectedError("The binding step stopped without binding a value")tracer_manager.on_pipe_end_error(lookup_key=trace_context.lookup_key,node_id=node_id,ended_at=datetime.now(UTC),- error_type=error_type,- error_message=error_message,- caller_facing=caller_facing,+ problem=make_node_problem(error=stopping_error, pipe_code=self.from_path, pipe_path=[]),)diff --git a/pipelex/pipe_controllers/binding/binding_value.py b/pipelex/pipe_controllers/binding/binding_value.pyindex d00fd2e99..5ff96f385 100644--- a/pipelex/pipe_controllers/binding/binding_value.py+++ b/pipelex/pipe_controllers/binding/binding_value.py@@ -75,7 +75,7 @@ def bind_content(*, root_content: StuffContent, derivation: BindingDerivation) -f"Binding '{derivation.path}' cannot read '{segment.name}' at '{reached_path}': the value there, a "f"'{type(value).__name__}', has no such field, although the declared structure has one.")- raise BindingStepRunError(msg)+ raise BindingStepRunError(msg).with_params(binding=derivation.path, segment=segment.name)field_value = getattr(value, segment.name)if field_value is None:if empty_path is None:@@ -112,14 +112,22 @@ 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).with_error_code(CoreCode.PIPE_OUTPUT_MULTIPLICITY)+ raise (+ BindingStepRunError(msg)+ .with_error_code(CoreCode.PIPE_OUTPUT_MULTIPLICITY)+ .with_params(output=derivation.root_name, produced="list", declared="single")+ )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).with_error_code(CoreCode.PIPE_OUTPUT_MULTIPLICITY)+ raise (+ BindingStepRunError(msg)+ .with_error_code(CoreCode.PIPE_OUTPUT_MULTIPLICITY)+ .with_params(output=derivation.root_name, produced="single", declared="list")+ )def _list_items(*, value: Any, reached_path: str, path: str) -> list[Any]:@@ -128,7 +136,7 @@ def _list_items(*, value: Any, reached_path: str, path: str) -> list[Any]:if isinstance(value, list):return list(cast("list[Any]", value))msg = f"Binding '{path}' expected a list at '{reached_path}', as its declared structure says, but found a '{type(value).__name__}'."- raise BindingStepRunError(msg)+ raise BindingStepRunError(msg).with_params(binding=path, segment=reached_path.rsplit(".", 1)[-1])def _store_value(*, value: Any, leaf_kind: BindingValueKind, path: str) -> StuffContent:diff --git a/pipelex/pipe_controllers/condition/exceptions.py b/pipelex/pipe_controllers/condition/exceptions.pyindex 15b9031a1..7a1758c51 100644--- a/pipelex/pipe_controllers/condition/exceptions.py+++ b/pipelex/pipe_controllers/condition/exceptions.py@@ -8,9 +8,8 @@ class PipeConditionFactoryError(PipelexError):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.+ name only the author's own pipe, concepts and template text; like every message, they reach the operator's+ diagnostics alone, the caller reading the sentences the code renders."""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 ec3ace7f2..181ba11b8 100644--- a/pipelex/pipe_controllers/condition/pipe_condition.py+++ b/pipelex/pipe_controllers/condition/pipe_condition.py@@ -4,7 +4,6 @@ from mthds.protocol.problem.registry import CoreCodefrom pydantic import BaseModel, ConfigDictfrom typing_extensions import override-from pipelex.cogt.inference.error_classification import UserAction, UserActionKindfrom pipelex.cogt.templating.template_rendering import render_templatefrom pipelex.core.concepts.native.concept_native import NativeConceptCodefrom pipelex.core.memory.absence import AbsenceKind, AbsenceRecord@@ -415,17 +414,7 @@ class PipeCondition(PipeController):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."- ),- )- )+ ).with_error_code(CoreCode.PIPE_CONDITION_UNMATCHED))@override@@ -457,12 +446,7 @@ class PipeCondition(PipeController):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}",- )- )+ .with_params(template="expression", finding=exc.fault)) from excasync def _evaluate_expression(@@ -513,9 +497,9 @@ class PipeCondition(PipeController):# downstream); it no longer passes through as this pipe's output.if SpecialOutcome.is_continue(outcome):self._record_resolution(job_metadata=job_metadata, evaluated_expression=evaluated_expression, outcome=outcome)- # The reason names only the pipe and the outcome: a pipe that force-unwraps this output quotes it to the caller- # under STRICT disclosure, and the value the expression rendered can be literal text of a condition a host- # library declared. The execution data above keeps that value.+ # The reason names only the pipe and the outcome: a pipe that force-unwraps this output quotes it in its+ # failure, and the value the expression rendered can be literal text of a condition a host library+ # declared. The execution data above keeps that value.self._record_declared_absent_output(working_memory=working_memory,output_name=output_name,@@ -532,15 +516,7 @@ class PipeCondition(PipeController):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'."- ),- )- )+ .with_params(outcome=outcome))chosen_pipe = get_required_pipe(pipe_code=outcome)@@ -568,12 +544,7 @@ class PipeCondition(PipeController):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}.",- )- )+ .with_params(variable=missing_names_str))# Recorded only now: a choice whose pipe cannot run is a failure of the condition, never an outcome it took.@@ -685,12 +656,7 @@ class PipeCondition(PipeController):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.",- )- )+ .with_params(template="expression", finding=describe_expression_parse_failure(error=exc))) from exc.__cause__# Validate that all values in the outcomes map (appart from special outcomes) do exist as pipe codes@@ -708,14 +674,7 @@ class PipeCondition(PipeController):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."- ),- )- )+ .with_params(missing=missing_pipes_str))# A dry run cannot know which outcome a live run takes, so the pipe of every outcome group@@ -772,12 +731,7 @@ class PipeCondition(PipeController):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'.",- )- )+ .with_params(field_path=f"pipe.{self.code}.outcomes", finding="every outcome and the default map to 'fail'"))self._record_declared_absent_output(working_memory=working_memory,diff --git a/pipelex/pipe_controllers/condition/pipe_condition_blueprint.py b/pipelex/pipe_controllers/condition/pipe_condition_blueprint.pyindex 34716206c..33afb596e 100644--- a/pipelex/pipe_controllers/condition/pipe_condition_blueprint.py+++ b/pipelex/pipe_controllers/condition/pipe_condition_blueprint.py@@ -84,7 +84,7 @@ class PipeConditionBlueprint(PipeBlueprint):# a conditional only when it renders, so a wrong name there compiles and is left to the run, as it must be:# refusing it here would refuse an expression whose run never reaches it.# The message 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 the condition may be a host library's.+ # the verdict's item shows it to the caller, and the condition may be a host library's.if not has_exactly_one_among_attributes_from_list(self, attributes_list=["expression_template", "expression"]):# Both fields or neither: the validator of the pair refuses that and says why, where a refusal of the# parse of one of them, which runs first, would hide it.diff --git a/pipelex/pipe_controllers/parallel/exceptions.py b/pipelex/pipe_controllers/parallel/exceptions.pyindex b9dd581bd..a44306174 100644--- a/pipelex/pipe_controllers/parallel/exceptions.py+++ b/pipelex/pipe_controllers/parallel/exceptions.py@@ -8,9 +8,8 @@ class PipeParallelFactoryError(PipelexError):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.+ name only the author's own pipe, concepts and template text; like every message, they reach the operator's+ diagnostics alone, the caller reading the sentences the code renders."""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 9e824ca20..690d6b423 100644--- a/pipelex/pipe_controllers/parallel/pipe_parallel.py+++ b/pipelex/pipe_controllers/parallel/pipe_parallel.py@@ -7,7 +7,6 @@ from pydantic import ValidationError, field_validatorfrom typing_extensions import overridefrom pipelex import log-from pipelex.cogt.inference.error_classification import UserAction, UserActionKindfrom pipelex.core.concepts.annotation_shapes import list_item_annotation, strip_optionalfrom pipelex.core.concepts.concept import Conceptfrom pipelex.core.concepts.exceptions import ConceptValueError@@ -25,6 +24,7 @@ from pipelex.core.stuffs.exceptions import StuffFactoryErrorfrom pipelex.core.stuffs.list_content import ListContentfrom pipelex.core.stuffs.stuff_content import StuffContentfrom pipelex.core.stuffs.stuff_factory import StuffFactory+from pipelex.errors.problem import make_problem_itemfrom pipelex.graph.graph_tracer_manager import GraphTracerManagerfrom pipelex.graph.stuff_io_spec import make_stuff_io_specfrom pipelex.interpreter_hub import get_concept_library, get_optional_pipe, get_required_pipe@@ -567,37 +567,50 @@ class PipeParallel(PipeController):# the combined fields' validation errors.# The output concept as the author writes it in this bundle, in the next step as in the restatement below.output_concept_ref = self._concept_ref_for_message(concept=self.output.concept, package_alias=None)- method_next_step = (- f"Change the method so that each branch of PipeParallel '{self.code}' produces what the field of "- f"'{output_concept_ref}' it feeds expects, a list only where that field is a list, "- "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: an output that does not fit its concept.+ # any other refusal leaves as it came, coded as 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.with_error_code(CoreCode.PIPE_OUTPUT_INVALID).as_caller_fault(- user_action=UserAction(kind=UserActionKind.CHANGE_INPUT, detail=method_next_step)+ # The combine's own message can quote a structure class's validator, which a deployment may have+ # written: it stays the operator's, and the caller reads the code's sentence over the refused fields.+ # A refusal of the whole structure, such as a model validator's, names no field: the caller reads the+ # fields the branches fed, which the refusal is about together.+ refused_field_names = _refused_field_names(exc=exc)+ exc.with_error_code(CoreCode.PIPE_OUTPUT_INVALID).with_params(+ output_concept=output_concept_ref,+ fields=sorted(refused_field_names if refused_field_names is not None else output_stuff_contents),)raiselead = f"PipeParallel '{self.code}' cannot combine its branch results into its output '{output_concept_ref}'."message_parts = [lead, *next_steps.values()]- next_step_parts = list(next_steps.values())# Keep what the combine said about every other field it refused, so a second fault is not hidden- # behind the multiplicity one, and keep the general next step for it.+ # behind the multiplicity one.refused_fields = _refused_field_names(exc=exc)if refused_fields is None or refused_fields - next_steps.keys():message_parts.append(f"The combine also reported: {exc.message}")- next_step_parts.append(method_next_step)# A StuffFactoryError raised from the combine's own: a run failure is reported as its root fault, and# 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 (+ # It is the method's fault like the refusal it restates: its sentence names the first branch to change, and+ # when several branches differ from their fields, its items name each one, so no branch to change is hidden.+ multiplicity_params = {result_name: self._multiplicity_params(result_stuff=output_stuffs[result_name]) for result_name in next_steps}+ first_result_name = next(iter(next_steps))+ multiplicity_refusal = (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 exc+ .with_params(output=first_result_name, **multiplicity_params[first_result_name])+ )+ if len(next_steps) > 1:+ multiplicity_refusal.with_items(+ items=[+ make_problem_item(+ code=CoreCode.PIPE_OUTPUT_MULTIPLICITY,+ params={"pipe": self.code, "output": result_name, **branch_params},+ )+ for result_name, branch_params in multiplicity_params.items()+ ]+ )+ raise multiplicity_refusal from excworking_memory.set_new_main_stuff(stuff=combined_output_stuff,name=output_name,@@ -667,6 +680,13 @@ class PipeParallel(PipeController):library_crate=library_crate,)+ @staticmethod+ def _multiplicity_params(*, result_stuff: "Stuff") -> dict[str, str]:+ """The multiplicity a branch result produced, and the one its field declares, which differs from it."""+ if result_stuff.is_list:+ return {"declared": "single", "produced": "list"}+ return {"declared": "list", "produced": "single"}+def _multiplicity_next_steps(self, *, structure_class: builtins.type[StuffContent], output_stuffs: "dict[str, Stuff]") -> dict[str, str]:"""Say, for each branch whose result and field differ only in multiplicity, which one to change.diff --git a/pipelex/pipe_machinery/pipe_abstract.py b/pipelex/pipe_machinery/pipe_abstract.pyindex 676ca3451..df16b118c 100644--- a/pipelex/pipe_machinery/pipe_abstract.py+++ b/pipelex/pipe_machinery/pipe_abstract.py@@ -11,7 +11,6 @@ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validafrom typing_extensions import overridefrom pipelex import log-from pipelex.cogt.inference.error_classification import UserAction, UserActionKindfrom pipelex.core.concepts.concept import Conceptfrom pipelex.core.concepts.native.concept_native import NativeConceptCodefrom pipelex.core.memory.absence import AbsenceKind, AbsenceRecord@@ -26,8 +25,8 @@ from pipelex.core.stuffs.list_content import ListContentfrom pipelex.core.stuffs.stuff import Stufffrom pipelex.core.stuffs.stuff_content import StuffContentfrom pipelex.graph.graph_tracer_manager import GraphTracerManager, IOSpec, NodeKind+from pipelex.graph.node_problem import make_node_problemfrom pipelex.graph.stuff_io_spec import make_stuff_io_spec-from pipelex.graph.traced_failure import make_traced_failurefrom pipelex.libraries.library_crate import LibraryCratefrom pipelex.pipe_machinery.memory_writes import MemoryWritefrom pipelex.pipe_machinery.pipe_blueprint import PipeCategory, PipeType, valid_pipe_type_tags@@ -605,13 +604,13 @@ class PipeAbstract(ABC, BaseModel):# 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+ missing_inputs_params: dict[str, 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}."+ missing_inputs_params = {"input": 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}."+ missing_inputs_params = {"variable": missing_inputs_str}raise (PipeRunInputsError(message=msg,@@ -620,7 +619,7 @@ class PipeAbstract(ABC, BaseModel):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))+ .with_params(**missing_inputs_params))# The pipe is about to be lifted (skipped): per-pipe validation and resource checks are@@ -642,9 +641,9 @@ class PipeAbstract(ABC, BaseModel):try:stuff.content.validate_resources()except ValueError as exc:- # Not classified as the caller's fault, although the resource is the- # caller's: the check's message names the path as resolved on this host,- # which STRICT disclosure must not show, as `PipelineInputContentError`'s.+ # No parameter repeats the check's message, although the resource is the+ # caller's: it names the path as resolved on this host, which only the+ # operator's diagnostics may show, as `PipelineInputContentError`'s.msg = f"Input '{variable_name}' of pipe '{self.code}' references an invalid resource: {exc}"raise PipeRunInputsError(message=msg,@@ -897,15 +896,12 @@ class PipeAbstract(ABC, BaseModel):error_stack: str | None = Noneif parent_trace_context.data_inclusion.error_stack_traces:error_stack = traceback.format_exc()- traced_failure = make_traced_failure(error=exc)tracer_manager.on_pipe_end_error(lookup_key=parent_trace_context.lookup_key,node_id=graph_node_id,ended_at=datetime.now(UTC),- error_type=type(exc).__name__,- error_message=traced_failure.message,+ problem=make_node_problem(error=exc, pipe_code=self.code, pipe_path=list(pipe_run_params.pipe_stack)),error_stack=error_stack,- caller_facing=traced_failure.caller_facing,)raisediff --git a/pipelex/pipe_machinery/rendering/exceptions.py b/pipelex/pipe_machinery/rendering/exceptions.pyindex 4c3f3d487..eef7bb6f5 100644--- a/pipelex/pipe_machinery/rendering/exceptions.py+++ b/pipelex/pipe_machinery/rendering/exceptions.py@@ -11,4 +11,3 @@ class OutputShapeUnavailableError(PipelexError, ValueError):"""error_code = CoreCode.REQUEST_UNSUPPORTED- _authors_caller_facing_message = Truediff --git a/pipelex/pipe_operators/compose/exceptions.py b/pipelex/pipe_operators/compose/exceptions.pyindex 2a05cb028..23883b193 100644--- a/pipelex/pipe_operators/compose/exceptions.py+++ b/pipelex/pipe_operators/compose/exceptions.py@@ -18,12 +18,11 @@ class PipeComposeFactoryError(PipeComposeError):Raised only while the pipe is built from its blueprint, about that blueprint, so it is the method's to fix andbundle 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.+ ``method.schema_violation``. Its messages name only the author's own pipe, concepts and template text; like every+ message, they reach the operator's diagnostics alone, the caller reading the sentences the code renders."""error_code = ErrorCodeSet(default=CoreCode.METHOD_TEMPLATE_INVALID, others=(CoreCode.METHOD_SCHEMA_VIOLATION,))- _authors_caller_facing_message = Trueclass ConstructFieldBlueprintTypeError(PipeComposeError, TypeError):@@ -41,9 +40,9 @@ class ConstructFieldBlueprintValueError(PipeComposeError, ValueError):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.+ Its message carries the parser's diagnosis, which can quote the template, so it reaches the operator alone, as+ every message does, and no parameter repeats it: 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_INVALIDdiff --git a/pipelex/pipe_operators/doc_gen/doc_gen_rendering.py b/pipelex/pipe_operators/doc_gen/doc_gen_rendering.pyindex faccb5dd7..4e8b4b834 100644--- a/pipelex/pipe_operators/doc_gen/doc_gen_rendering.py+++ b/pipelex/pipe_operators/doc_gen/doc_gen_rendering.py@@ -6,6 +6,7 @@ print stage renders an HTML template file, which it reads through the method filBoth raise the same errors, worded the same way."""+import refrom typing import Anyfrom jinja2.exceptions import UndefinedError@@ -17,6 +18,16 @@ from pipelex.tools.jinja2.exceptions import Jinja2TemplateInvalidError, Jinja2Tefrom pipelex.tools.jinja2.template_category import TemplateCategoryfrom pipelex.tools.templating.templating_style import TemplatingStyle+# The name a strict undefined's message says is missing: Jinja2 words it "'name' is undefined", "... has no attribute+# 'name'" or "... has no element 'name'", where what comes before the name can quote an object's class, never a caller's.+_UNDEFINED_NAME_PATTERN = re.compile(r"(?:has no (?:attribute|element) |^)'([^']+)'(?: is undefined)?$")+++def undefined_name(*, undefined_error: UndefinedError) -> str | None:+ """The name a strict undefined's error says is missing, or ``None`` when its message is not one Jinja2 words."""+ match = _UNDEFINED_NAME_PATTERN.search(undefined_error.message or "")+ return match.group(1) if match else None+async def render_doc_gen_template(*,@@ -47,17 +58,21 @@ async def render_doc_gen_template(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 exc+ raise (+ PipeDocGenRunError(msg).with_error_code(CoreCode.METHOD_TEMPLATE_INVALID).with_params(pipe=pipe_code, template=label, finding=exc.fault)+ ) from excexcept Jinja2TemplateRenderError as exc:undefined_error = exc.__cause__if isinstance(undefined_error, UndefinedError):# Raised from Jinja's own error rather than from the tools-layer wrapper, whose message quotes the- # template and is not caller-facing, so that this is the root fault a verdict or a run report names.+ # template, so that this is the root fault a verdict or a run's problem names.msg = (f"PipeDocGen '{pipe_code}' could not render its {label}: {undefined_error.message}. ""Every value a document's template reads must exist: check the name against the input's concept, ""or test an optional value first with {% if ... %}.")- raise PipeDocGenUndefinedValueError(msg) from undefined_error+ raise PipeDocGenUndefinedValueError(msg).with_params(+ pipe=pipe_code, variable=undefined_name(undefined_error=undefined_error)+ ) from undefined_errormsg = f"PipeDocGen '{pipe_code}' could not render its {label}: {exc}"raise PipeDocGenRunError(msg) from excdiff --git a/pipelex/pipe_operators/doc_gen/exceptions.py b/pipelex/pipe_operators/doc_gen/exceptions.pyindex 37f0a169d..3a15ca778 100644--- a/pipelex/pipe_operators/doc_gen/exceptions.py+++ b/pipelex/pipe_operators/doc_gen/exceptions.py@@ -1,4 +1,7 @@+from typing import Any+from mthds.protocol.problem.registry import CoreCode+from typing_extensions import overridefrom pipelex.base_exceptions import PipelexErrorfrom pipelex.errors.error_code_declaration import ErrorCodeSet, InheritsCause@@ -25,7 +28,19 @@ class PipeDocGenFactoryError(PipelexError):CoreCode.METHOD_FIELD_PATH_UNRESOLVED,),)- _authors_caller_facing_message = True++ def __init__(self, message: str, *, facts: dict[str, Any] | None = None):+ """The refusal, and the facts its raise site knows, by the parameter names its codes give them.++ Each raise site chooses one of several codes declaring different parameters, so it gives every fact it holds,+ and the problem keeps the ones its code declares, where :meth:`with_params` would log the others.+ """+ super().__init__(message)+ self.facts = facts or {}++ @override+ def problem_params(self) -> dict[str, Any]:+ return dict(self.facts)class PipeDocGenRunError(PipelexError):@@ -50,7 +65,6 @@ class PipeDocGenUndefinedValueError(PipelexError):"""error_code = CoreCode.PIPE_TEMPLATE_RENDER_FAILED- _authors_caller_facing_message = Trueclass PipeDocGenTemplateCheckError(PipelexError):@@ -62,7 +76,6 @@ class PipeDocGenTemplateCheckError(PipelexError):"""error_code = PipelexErrorCode.DOCGEN_TEMPLATE_INVALID- _authors_caller_facing_message = Trueclass PipeDocGenTemplateFileUncheckedError(PipelexError):diff --git a/pipelex/pipe_operators/doc_gen/pipe_doc_gen_factory.py b/pipelex/pipe_operators/doc_gen/pipe_doc_gen_factory.pyindex 36004949e..2755b8f65 100644--- a/pipelex/pipe_operators/doc_gen/pipe_doc_gen_factory.py+++ b/pipelex/pipe_operators/doc_gen/pipe_doc_gen_factory.py@@ -43,7 +43,8 @@ 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).with_error_code(CoreCode.METHOD_OUTPUT_CONCEPT_MISMATCH)+ facts = {"pipe": pipe_code, "pipe_type": pipe_type, "declared": output.concept.concept_ref, "expected": [document_concept.concept_ref]}+ raise PipeDocGenFactoryError(msg, facts=facts).with_error_code(CoreCode.METHOD_OUTPUT_CONCEPT_MISMATCH)template_file_ref: MethodFileRef | None = Nonetemplate_bundle_ref: TreeBundleRef | None = None@@ -85,11 +86,14 @@ 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).with_error_code(_template_file_refusal_code(refusal_error=exc)) from exc+ raise PipeDocGenFactoryError(msg, facts=_file_facts(pipe_code=pipe_code, file=template_file)).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:msg = cls._unsubmitted_template_file_message(pipe_code=pipe_code, template_file=template_file)- raise PipeDocGenFactoryError(msg).with_error_code(CoreCode.METHOD_RESOURCE_MISSING)+ facts = _file_facts(pipe_code=pipe_code, file=template_file)+ raise PipeDocGenFactoryError(msg, facts=facts).with_error_code(CoreCode.METHOD_RESOURCE_MISSING)pipe_doc_gen = PipeDocGen(domain_code=domain_code,@@ -142,7 +146,9 @@ 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).with_error_code(CoreCode.METHOD_RESOURCE_MISSING)+ raise PipeDocGenFactoryError(msg, facts=_file_facts(pipe_code=pipe_code, file=url)).with_error_code(+ CoreCode.METHOD_RESOURCE_MISSING+ )return None, False@classmethod@@ -162,7 +168,8 @@ 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).with_error_code(CoreCode.METHOD_RESOURCE_MISSING)+ facts = _file_facts(pipe_code=pipe_code, file=refusal.reference)+ raise PipeDocGenFactoryError(msg, facts=facts).with_error_code(CoreCode.METHOD_RESOURCE_MISSING)@classmethoddef _resolve_template_file(cls, *, pipe_code: str, template_file: str, tree_bundle: TreeBundle) -> str:@@ -180,10 +187,13 @@ 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).with_error_code(CoreCode.METHOD_RESOURCE_MISSING) from exc+ facts = _file_facts(pipe_code=pipe_code, file=template_file)+ raise PipeDocGenFactoryError(msg, facts=facts).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).with_error_code(_template_file_refusal_code(refusal_error=exc)) from exc+ raise PipeDocGenFactoryError(msg, facts=_file_facts(pipe_code=pipe_code, file=template_file)).with_error_code(+ _template_file_refusal_code(refusal_error=exc)+ ) from exc@staticmethoddef _unsubmitted_template_file_message(*, pipe_code: str, template_file: str) -> str:@@ -212,12 +222,15 @@ 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).with_error_code(CoreCode.METHOD_RESOURCE_MISSING)+ raise PipeDocGenFactoryError(msg, facts=_file_facts(pipe_code=pipe_code, file=template_file)).with_error_code(+ CoreCode.METHOD_RESOURCE_MISSING+ )try:return data.decode("utf-8")except UnicodeError as exc:msg = f"PipeDocGen '{pipe_code}' could not read the template file '{template_file}' as UTF-8 text."- raise PipeDocGenFactoryError(msg) from exc+ facts = {"pipe": pipe_code, "template": template_file, "finding": "the file is not UTF-8 text"}+ raise PipeDocGenFactoryError(msg, facts=facts) from exc@classmethoddef _check_html_template_file(cls, *, pipe_code: str, template: str, inputs: InputStuffSpecs, template_file: str) -> None:@@ -232,10 +245,19 @@ class PipeDocGenFactory(PipeFactoryProtocol[PipeDocGenBlueprint, PipeDocGen]):)except ValueError as exc:msg = f"PipeDocGen '{pipe_code}': {exc}"- raise PipeDocGenFactoryError(msg) from exc+ raise PipeDocGenFactoryError(msg, facts={"pipe": pipe_code, "template": template_file, "finding": str(exc)}) 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).with_error_code(CoreCode.METHOD_INPUT_UNDECLARED)+ raise PipeDocGenFactoryError(msg, facts={"pipe": pipe_code, "variables": [root]}).with_error_code(CoreCode.METHOD_INPUT_UNDECLARED)+++def _file_facts(*, pipe_code: str, file: str) -> dict[str, Any]:+ """The facts of a refusal of a file the step names, for whichever of its codes the raise site chooses.++ A file the method's tree does not hold is the reason a `method.resource_missing` gives here, where a path its+ tree refuses as a security matter takes `security.method_path_refused`, which declares no reason.+ """+ return {"pipe": pipe_code, "file": file, "reason": "not_in_tree"}def _template_file_refusal_code(*, refusal_error: MethodTreeRefusedError) -> CoreCode:diff --git a/pipelex/pipe_operators/doc_gen/template_field_check.py b/pipelex/pipe_operators/doc_gen/template_field_check.pyindex dce5cb46b..47834acf9 100644--- a/pipelex/pipe_operators/doc_gen/template_field_check.py+++ b/pipelex/pipe_operators/doc_gen/template_field_check.py@@ -122,7 +122,8 @@ 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).with_error_code(CoreCode.METHOD_FIELD_PATH_UNRESOLVED)+ facts = {"pipe": pipe_code, "path": path.written, "segment": missing_field, "available_fields": list(model_class.model_fields)}+ raise PipeDocGenFactoryError(msg, facts=facts).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 429fc5c64..f914581b7 100644--- a/pipelex/pipe_operators/doc_gen/template_file_stage.py+++ b/pipelex/pipe_operators/doc_gen/template_file_stage.py@@ -183,7 +183,8 @@ class DocGenTemplateFileStage(TemplateFileStageProtocol):if errors:listed = "\n".join(f"- {finding.message}" + (f" ({finding.location})" if finding.location else "") for finding in errors)msg = f"PipeDocGen '{pipe_code}': the template file '{template_file.name}' does not fit the step's inputs:\n{listed}"- raise PipeDocGenTemplateCheckError(msg)+ findings_text = "; ".join(finding.message for finding in errors)+ raise PipeDocGenTemplateCheckError(msg).with_params(template=template_file.name, reason="does_not_fit", finding=findings_text)def _report_template_warning(*, domain_code: str | None, pipe_code: str, template_file: str, finding: TemplateFinding) -> None:diff --git a/pipelex/pipe_operators/extract/exceptions.py b/pipelex/pipe_operators/extract/exceptions.pyindex d94ae1359..456ba0553 100644--- a/pipelex/pipe_operators/extract/exceptions.py+++ b/pipelex/pipe_operators/extract/exceptions.py@@ -8,9 +8,8 @@ class PipeExtractFactoryError(PipelexError):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.+ name only the author's own pipe, concepts and template text; like every message, they reach the operator's+ diagnostics alone, the caller reading the sentences the code renders."""error_code = CoreCode.METHOD_SCHEMA_VIOLATION- _authors_caller_facing_message = Truediff --git a/pipelex/pipe_operators/extract/pipe_extract_factory.py b/pipelex/pipe_operators/extract/pipe_extract_factory.pyindex 5ff2f6195..f727771d0 100644--- a/pipelex/pipe_operators/extract/pipe_extract_factory.py+++ b/pipelex/pipe_operators/extract/pipe_extract_factory.py@@ -54,7 +54,8 @@ class PipeExtractFactory(PipeFactoryProtocol[PipeExtractBlueprint, PipeExtract])f"{get_native_concept(native_concept=NativeConceptCode.DOCUMENT).concept_ref}. ""Declare this input as an Image or a Document, or as a concept that refines one of them.")- raise PipeExtractFactoryError(msg)+ finding = f"the input '{input_name}' is a {input_requirement.concept.concept_ref}, neither an Image nor a Document"+ raise PipeExtractFactoryError(msg).with_params(field_path=f"pipe.{pipe_code}.inputs.{input_name}", finding=finding)return PipeExtract(domain_code=domain_code,diff --git a/pipelex/pipe_operators/func/direct_pipe_func_executor.py b/pipelex/pipe_operators/func/direct_pipe_func_executor.pyindex bbaa464d2..6d2706e4f 100644--- a/pipelex/pipe_operators/func/direct_pipe_func_executor.py+++ b/pipelex/pipe_operators/func/direct_pipe_func_executor.py@@ -87,7 +87,7 @@ class DirectPipeFuncExecutor(PipeFuncExecutorProtocol):# 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+ raise PipeFuncRaisedError(msg).with_params(function=function_name) 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)diff --git a/pipelex/pipe_operators/func/exceptions.py b/pipelex/pipe_operators/func/exceptions.pyindex 32de965d0..4f1807440 100644--- a/pipelex/pipe_operators/func/exceptions.py+++ b/pipelex/pipe_operators/func/exceptions.py@@ -33,7 +33,8 @@ class PipeFuncRaisedError(PipelexError):Raised by the in-process executor from whatever the function's own code raised, so that the step tells a failureof its function from a failure of the seam that runs it: it is ``pipe.function_raised`` whatever the functionraised, 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.+ function's exception, which can carry whatever the process holds, so it reaches the operator alone, as every+ message does, and no parameter of its code repeats it."""error_code = CoreCode.PIPE_FUNCTION_RAISED@@ -45,8 +46,7 @@ class PipeFuncFunctionError(PipelexError):Raised when the module the import path names is not found, when the function is not a top-level `def` or`async def` of that module carrying the `@pipe_func()` marker, or, once the module is imported, when the functiondoes not follow the calling convention. The message names the step and the function, and describes the- caller's own method, so it is kept under STRICT disclosure.+ caller's own method."""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 97099b9fb..dfd7d88db 100644--- a/pipelex/pipe_operators/func/pipe_func.py+++ b/pipelex/pipe_operators/func/pipe_func.py@@ -130,7 +130,7 @@ class PipeFunc(PipeOperator[PipeFuncOutput]):domain_code=self.domain_code,pipe_code=self.code,field_name="function_name",- ) from exc+ ).with_params(pipe=self.code, function=self.function_name, finding=exc.message) from excself._is_function_proven = True@override@@ -361,9 +361,9 @@ class PipeFunc(PipeOperator[PipeFuncOutput]):msg = (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. The wrapper takes its cause's code. What the function raised reads+ # No parameter carries the function's own exception text, which can carry whatever the+ # process holds (a path, a setting, a secret): it rides the operator's diagnostics alone.+ # 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)@@ -489,6 +489,9 @@ class PipeFunc(PipeOperator[PipeFuncOutput]):try:return self.bind_function()except (PipeFuncFunctionError, TreePythonError) as exc:+ if isinstance(exc, PipeFuncFunctionError):+ # The refusal's code is the run failure's, and its sentences name the function and what is wrong with it.+ exc.with_params(function=self.function_name, finding=exc.message)msg = f"PipeFunc '{self.code}' cannot call its function '{self.function_name}': {exc.message}"raise PipeRunError(message=msg, run_mode=pipe_run_params.run_mode, pipe_code=self.code) from excexcept Exception as exc:@@ -496,8 +499,10 @@ 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).with_error_code(- CoreCode.METHOD_FUNCTION_INVALID+ raise (+ PipeRunError(message=msg, run_mode=pipe_run_params.run_mode, pipe_code=self.code)+ .with_error_code(CoreCode.METHOD_FUNCTION_INVALID)+ .with_params(function=self.function_name, finding=f"importing its module raised {type(exc).__name__}")) from exc@overridediff --git a/pipelex/pipe_operators/judge/exceptions.py b/pipelex/pipe_operators/judge/exceptions.pyindex d2c0ea48a..9f0880e45 100644--- a/pipelex/pipe_operators/judge/exceptions.py+++ b/pipelex/pipe_operators/judge/exceptions.py@@ -1,6 +1,7 @@-from typing import ClassVar+from typing import Any, ClassVarfrom mthds.protocol.problem.registry import CoreCode+from typing_extensions import overridefrom pipelex.base_exceptions import PipelexErrorfrom pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeDeclaration@@ -22,7 +23,6 @@ class PipeJudgeInputCapabilityError(PipeJudgeError):"""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]):self.pipe_code = pipe_code@@ -37,6 +37,10 @@ class PipeJudgeInputCapabilityError(PipeJudgeError):)super().__init__(message)+ @override+ def problem_params(self) -> dict[str, Any]:+ return {"pipe": self.pipe_code, "model": self.model_name, "capability": f"{self.file_kind} inputs"}+def _with_article(*, noun: str) -> str:return f"an {noun}" if noun[0] in "aeiou" else f"a {noun}"diff --git a/pipelex/pipe_operators/llm/exceptions.py b/pipelex/pipe_operators/llm/exceptions.pyindex 1bd64a1ca..8e2cfe857 100644--- a/pipelex/pipe_operators/llm/exceptions.py+++ b/pipelex/pipe_operators/llm/exceptions.py@@ -8,9 +8,8 @@ class PipeLLMFactoryError(PipelexError):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.+ name only the author's own pipe, concepts and template text; like every message, they reach the operator's+ diagnostics alone, the caller reading the sentences the code renders."""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 74e98cf7d..cf9cd4dad 100644--- a/pipelex/pipe_operators/llm/pipe_llm.py+++ b/pipelex/pipe_operators/llm/pipe_llm.py@@ -6,7 +6,6 @@ from 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@@ -437,12 +436,7 @@ class PipeLLM(PipeOperator[PipeLLMOutput]):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}",- )- )+ .with_params(template=where, finding=fault))def _format_error_location(self, pipe_run_params: PipeRunParams) -> str:diff --git a/pipelex/pipe_operators/llm/pipe_llm_factory.py b/pipelex/pipe_operators/llm/pipe_llm_factory.pyindex 811c953da..161793e06 100644--- a/pipelex/pipe_operators/llm/pipe_llm_factory.py+++ b/pipelex/pipe_operators/llm/pipe_llm_factory.py@@ -23,7 +23,8 @@ from pipelex.tools.templating.templating_style import TagStyle, TemplatingStyledef _describe_template_syntax_error(*, validation_error: ValidationError) -> str:"""Say where a prompt fails to parse, in words that owe nothing to the prompt.- A ``PipeLLMFactoryError`` is caller-facing, and the prompt it is about may not be the caller's: a pipe+ The description is the ``finding`` parameter of a ``PipeLLMFactoryError``'s problem, which reaches the caller, and+ the prompt it is about may not be the caller's: a pipewith no system prompt of its own inherits its domain's, which a host's library may have declared.Every layer between Jinja2 and this factory appends the template source to its message, and Jinja2'sown diagnosis quotes the token it stopped at (an unknown tag's name, an unexpected word), so no text@@ -67,11 +68,9 @@ class PipeLLMFactory(PipeFactoryProtocol[PipeLLMBlueprint, PipeLLM]):except ValidationError as exc:# The system prompt is the pipe's own, or else its domain's: name the one that failed.prompt_owner = "system prompt" if blueprint.system_prompt else f"system prompt of domain '{domain_code}', which it inherits,"- error_msg = (- f"Template syntax error in the {prompt_owner} for pipe '{pipe_code}' "- f"in domain '{domain_code}': {_describe_template_syntax_error(validation_error=exc)}."- )- raise PipeLLMFactoryError(error_msg) from exc+ diagnosis = _describe_template_syntax_error(validation_error=exc)+ error_msg = f"Template syntax error in the {prompt_owner} for pipe '{pipe_code}' in domain '{domain_code}': {diagnosis}."+ raise PipeLLMFactoryError(error_msg).with_params(pipe=pipe_code, template="system_prompt", finding=diagnosis) from excuser_text_jinja2_blueprint: TemplateBlueprint | None = Noneif blueprint.prompt:@@ -84,7 +83,7 @@ class PipeLLMFactory(PipeFactoryProtocol[PipeLLMBlueprint, PipeLLM]):# `TemplateBlueprint` reports a template that does not parse as a pydantic validation error.diagnosis = _describe_template_syntax_error(validation_error=exc)error_msg = f"Template syntax error in the prompt for pipe '{pipe_code}' in domain '{domain_code}': {diagnosis}."- raise PipeLLMFactoryError(error_msg) from exc+ raise PipeLLMFactoryError(error_msg).with_params(pipe=pipe_code, template="prompt", finding=diagnosis) from exc# Template analyzers read the slot grammar only, so they get the concept-spec projection.blueprint_input_specs = blueprint.inputs_concept_specs or {}diff --git a/pipelex/pipe_operators/shared/llm_setting_check.py b/pipelex/pipe_operators/shared/llm_setting_check.pyindex aaad83ca9..2d347ae5d 100644--- a/pipelex/pipe_operators/shared/llm_setting_check.py+++ b/pipelex/pipe_operators/shared/llm_setting_check.py@@ -1,9 +1,9 @@"""The load-time refusal of an LLM setting the model it resolves to refuses, shared by the operators that generate with one."""-from pipelex.cogt.exceptions import LLMCapabilityError+from pipelex.cogt.exceptions import LLMCapabilityError, LLMSettingRefusedErrorfrom pipelex.cogt.llm.llm_setting import LLMModelChoice, LLMSettingfrom pipelex.cogt.models.model_reference import ensure_model_reference-from pipelex.core.pipes.exceptions import PipeValidationError, caller_facing_refusal_text+from pipelex.core.pipes.exceptions import PipeValidationError, refusal_detailfrom pipelex.kernel.llm_ops import check_llm_setting_with_served_modelfrom pipelex.runtime_hub import get_model_deckfrom pipelex.validation_error_types import PipeValidationErrorType@@ -59,7 +59,10 @@ def refuse_llm_setting_its_model_refuses(model_reference = ensure_model_reference(llm_choice).rawsetting_desc = f"the model setting `{model_reference}` its `{field_name}` names"remedy = f"Name another setting in `{field_name}`, or one whose model takes it."- reason = caller_facing_refusal_text(refusal=refusal).rstrip(".")+ # A built-in worker's refusal is worded for whoever wrote the setting; an external plugin's may carry what the+ # plugin keeps private, so the verdict gives its code's sentence instead.+ reason_text = refusal.message if isinstance(refusal, LLMSettingRefusedError) else refusal_detail(refusal=refusal)+ reason = reason_text.rstrip(".")msg = f"{pipe_type} '{pipe_code}' generates {output_desc} with {setting_desc}, which the model it resolves to refuses: {reason}. {remedy}"raise PipeValidationError(message=msg,diff --git a/pipelex/pipe_run/delivery_assignment.py b/pipelex/pipe_run/delivery_assignment.pyindex 05443ce86..1cb049dc4 100644--- a/pipelex/pipe_run/delivery_assignment.py+++ b/pipelex/pipe_run/delivery_assignment.py@@ -5,6 +5,7 @@ from typing import Anyfrom pydantic import BaseModel, Field, field_validator+from pipelex.errors.problem import ProblemViewfrom pipelex.tools.typing.pydantic_utils import empty_list_factory_of@@ -21,11 +22,17 @@ _RESERVED_WEBHOOK_PAYLOAD_KEYS: frozenset[str] = frozenset({"state", "pipeline_rclass WebhookTarget(BaseModel):- """A webhook endpoint to notify on delivery."""+ """A webhook endpoint to notify on delivery.++ ``problem_view`` is the view the failed run's problem reaches the webhook in, the view of whoever asked for it: the+ host that builds the target picks it from the identity its boundary authenticated, and a target built with none+ receives the caller's view, which carries no diagnostics.+ """url: strheaders: dict[str, str] = Field(default_factory=dict)payload: dict[str, Any] = Field(default_factory=dict)+ problem_view: ProblemView = Field(default=ProblemView.CALLER, strict=False)@field_validator("payload", mode="after")@classmethoddiff --git a/pipelex/pipe_run/delivery_executor.py b/pipelex/pipe_run/delivery_executor.pyindex ea08d3369..86f162316 100644--- a/pipelex/pipe_run/delivery_executor.py+++ b/pipelex/pipe_run/delivery_executor.py@@ -9,7 +9,6 @@ from kajson.exceptions import KajsonExceptionfrom pydantic import ValidationErrorfrom pipelex import log-from pipelex.base_exceptions import DisclosureMode, ErrorReportfrom pipelex.config import get_configfrom pipelex.core.concepts.concept_factory import ConceptFactoryfrom pipelex.core.concepts.exceptions import ConceptLibraryConceptNotFoundError, ConceptRefAmbiguousError@@ -23,6 +22,7 @@ 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_viewer+from pipelex.errors.problem import PipelexProblem, ProblemView, caller_view_offrom pipelex.graph.graph_factory import generate_graph_outputsfrom pipelex.interpreter_hub import get_concept_library, get_current_library_id_or_nonefrom pipelex.libraries.exceptions import LibraryError@@ -48,6 +48,27 @@ class ResultFile(NamedTuple):content_type: str+def _problem_wires_by_view(*, problem: PipelexProblem | None, webhooks: list[WebhookTarget]) -> dict[ProblemView, dict[str, Any]]:+ """A failed run's problem in the wire form of each view the webhooks read it in, each view built once.++ ``problem`` is in the operator's view, which an operator's webhook receives as it is, and a caller's webhook+ receives its caller view, projected once for every caller webhook rather than once per webhook.+ """+ wires: dict[ProblemView, dict[str, Any]] = {}+ if problem is None:+ return wires+ for webhook in webhooks:+ view = webhook.problem_view+ if view in wires:+ continue+ match view:+ case ProblemView.OPERATOR:+ wires[view] = problem.to_wire()+ case ProblemView.CALLER:+ wires[view] = caller_view_of(problem=problem).to_wire()+ return wires++class DeliveryExecutor:"""Handles the full delivery lifecycle: generate result files, store them, notify webhooks."""@@ -59,11 +80,13 @@ class DeliveryExecutor:pipeline_run_id: str,delivery_assignment: DeliveryAssignment,status: DeliveryStatus,- error_report: ErrorReport | None = None,+ problem: PipelexProblem | None = None,request_id: str | None = None,) -> None:"""Execute a full delivery: generate result files, store them, then notify webhooks.+ ``problem`` is a failed run's problem in the operator's view, which each webhook receives in its own view.+``request_id`` is the originating API request id (when set). The delivery binds itwith ``pipeline_run_id`` onto the log context, so every record the delivery emits,its storage and webhook completion lines included, carries both and correlates@@ -82,13 +105,14 @@ class DeliveryExecutor:)# Step 2: Notify webhooks with status + result_url (always, even on failure)+ problem_wires = _problem_wires_by_view(problem=problem, webhooks=delivery_assignment.webhooks)for webhook in delivery_assignment.webhooks:await self._notify_webhook(pipeline_run_id=pipeline_run_id,status=status,result_url=result_url,webhook=webhook,- error_report=error_report,+ problem_wire=problem_wires.get(webhook.problem_view),)# ---- Result file generation ----@@ -458,12 +482,13 @@ class DeliveryExecutor:status: DeliveryStatus,result_url: str | None,webhook: WebhookTarget,- error_report: ErrorReport | None = None,+ problem_wire: dict[str, Any] | None = None,) -> None:- """POST status, optional result_url, and optional VERBOSE error report to a webhook URL.+ """POST status, optional result_url, and a failed run's problem to a webhook URL.- VERBOSE on the wire is deliberate: the receiver decides what to re-expose- downstream (it can render STRICT via :meth:`ErrorReport.to_problem_document`).+ ``problem_wire`` is the problem in the webhook's own view (``WebhookTarget.problem_view``),+ already in its wire form: an operator's webhook, such as a hosted plane's completion+ callback, receives the diagnostics, and a caller's receives the problem without them.The HTTP client uses :class:`SsrfGuardedTransport`, which re-resolves thecallback host at connect time and refuses private/loopback/metadata@@ -485,8 +510,8 @@ class DeliveryExecutor:payload["status"] = statusif result_url is not None:payload["result_url"] = result_url- if error_report is not None:- payload["error"] = error_report.to_dict(disclosure_mode=DisclosureMode.VERBOSE)+ if problem_wire is not None:+ payload["error"] = problem_wireasync with httpx.AsyncClient(transport=SsrfGuardedTransport()) as client:response = await client.post(diff --git a/pipelex/pipe_run/exceptions.py b/pipelex/pipe_run/exceptions.pyindex e3e418a88..7721400fd 100644--- a/pipelex/pipe_run/exceptions.py+++ b/pipelex/pipe_run/exceptions.py@@ -1,13 +1,16 @@-from typing import ClassVar, Self+from typing import Any, ClassVar, Self+from mthds.protocol.problem.models import ProblemItem, ProblemLocationfrom mthds.protocol.problem.registry import CoreCodefrom typing_extensions import override-from pipelex.base_exceptions import ErrorReport, PipelexError, iter_cause_chain+from pipelex.base_exceptions import PipelexError, iter_cause_chainfrom pipelex.core.exceptions import DryRunFailureErrorDatafrom pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeDeclaration, InheritsCause+from pipelex.errors.error_codes import ErrorCode, error_code_spec, first_fault_code+from pipelex.errors.problem import PipelexProblem, ProblemView, make_location, make_problem_itemfrom pipelex.errors.registry.pipelex_codes import PipelexErrorCode-from pipelex.pipe_run.located_failure import build_located_failure_report, locate_failure_message+from pipelex.pipe_run.located_failure import failure_location_of, locate_failure_message, located_problem, located_root_faultfrom pipelex.system.pipe_run_mode import PipeRunMode@@ -46,6 +49,10 @@ class AsyncExecutionNotEnabledError(PipelexError):"""return cls(cls.DEFAULT_MESSAGE)+ @override+ def problem_params(self) -> dict[str, Any]:+ return {"capability": "asynchronous execution"}+class PipeRunParamsError(PipelexError):"""A pipe's declaration and the run's params cannot settle a value the pipe needs, such as an image count."""@@ -84,13 +91,14 @@ class StorageDeliveryError(DeliveryError):class DryRunError(PipelexError):"""Raised when a dry run fails. The validation sweep raises it with one failure per pipe whose dry runfailed, located at the innermost failing pipe that is not allowed to fail, so a controller that failed- because a pipe it runs failed is reported once, at that pipe. Bundle validation reports each failure as its own ``dry_run``- item, with the error type ``DryRunError``, the pipe's code, domain and source, and a message that- keeps the failure's own text only when that text is caller-facing and otherwise names the failure's- title.-- 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.+ because a pipe it runs failed is reported once, at that pipe. Each failure carries its own code, and bundle+ validation reports each as its own ``dry_run`` item, with the error type ``DryRunError``, the pipe's code,+ domain and source, and the sentence the failure's code renders for a caller.++ With failures, its code is the one the answer takes among theirs (``first_fault_code``), its parameters are those of+ the failure that code is taken from, its pipe included, so that the problem's sentence renders whole, and its problem+ carries one item per failure; a validation answers it as an invalid verdict only when one of them is the method's.+ Raised elsewhere it may carry no failures, and then it takes the code of its cause, the failure it reports."""error_code: ClassVar[ErrorCodeDeclaration] = InheritsCause(fallback=CoreCode.RUNTIME_UNEXPECTED)@@ -99,6 +107,42 @@ class DryRunError(PipelexError):self.failures = failures or []super().__init__(message)+ def _code_failure(self) -> DryRunFailureErrorData | None:+ """The failure whose code this error carries: the first of those whose code ``first_fault_code`` takes."""+ code = first_fault_code(codes=[failure.code for failure in self.failures])+ for failure in self.failures:+ if failure.code == code:+ return failure+ return None++ @property+ @override+ def own_error_code(self) -> ErrorCode | None:+ code_failure = self._code_failure()+ return code_failure.code if code_failure is not None else super().own_error_code++ @override+ def problem_params(self) -> dict[str, Any]:+ code_failure = self._code_failure()+ if code_failure is None:+ return {}+ params = dict(code_failure.params or {})+ if code_failure.pipe_code is not None:+ params.setdefault("pipe", code_failure.pipe_code)+ return params++ @override+ def problem_items(self) -> list[ProblemItem] | None:+ items: list[ProblemItem] = []+ for failure in self.failures:+ spec = error_code_spec(failure.code)+ params = dict(failure.params or {})+ if failure.pipe_code is not None and "pipe" in spec.param_names:+ params.setdefault("pipe", failure.pipe_code)+ location = make_location(pipe=failure.pipe_code, file=failure.source)+ items.append(make_problem_item(code=failure.code, params=params or None, location=location))+ return items or None+class DryRunGraphNotProducedError(DryRunError):"""Raised when a graph-producing dry run completes but no ``GraphSpec`` was assembled onto the pipe output.@@ -120,10 +164,10 @@ class PipeRouterError(PipelexError):The pipe router raises it around every failure of the pipe it runs, chained to the failure,with the pipe's code and a snapshot of its stack taken where it failed. A failure that alreadycarries one keeps it as it rises through the routers of the controllers above, so the innermost- location is the one reported. Its report is its root fault's, located (see+ location is the one reported. Its problem 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`, and its code- is the root fault's.+ `StuffFactoryError`'s code and diagnostics, with a location naming the pipe and its path, never+ `PipeRouterError`."""error_code = InheritsCause(fallback=CoreCode.RUNTIME_UNEXPECTED)@@ -164,12 +208,20 @@ class PipeRouterError(PipelexError):)@override- def to_error_report(self) -> ErrorReport:- return build_located_failure_report(- wrapper=self,- own_report=super().to_error_report(),- pipe_code=self.pipe_code,- pipe_stack=self.pipe_stack,+ def to_problem(+ self,+ *,+ view: ProblemView,+ request_id: str | None = None,+ pipeline_run_id: str | None = None,+ failure_location: ProblemLocation | None = None,+ ) -> PipelexProblem:+ location = failure_location or failure_location_of(pipe_code=self.pipe_code, pipe_stack=self.pipe_stack)+ root_fault = located_root_fault(wrapper=self)+ if root_fault is None:+ return super().to_problem(view=view, request_id=request_id, pipeline_run_id=pipeline_run_id, failure_location=location)+ return located_problem(+ wrapper=self, root_fault=root_fault, view=view, request_id=request_id, pipeline_run_id=pipeline_run_id, failure_location=location)diff --git a/pipelex/pipe_run/located_failure.py b/pipelex/pipe_run/located_failure.pyindex 0542a1338..1349e92c6 100644--- a/pipelex/pipe_run/located_failure.py+++ b/pipelex/pipe_run/located_failure.py@@ -3,34 +3,30 @@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, and each takes its cause's code. The report of such a failure is therefore built from its+wrong, and each takes its cause's code. The problem 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, thesame walk `PipelexError.resolve_error_code` makes, so a wrapper that adds the fact deciding the codeis the root fault over a coded cause; when none carries one, it is the innermost `PipelexError`. Thewalk 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's- own message unaltered. Pipe codes are the caller's own names, so the message is caller-facing- exactly when the root fault's is;-- 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 contract-gives it one. A root fault whose report was recovered across a transport boundary (a report-carried by a `PipelexError`, the way a distributed worker's submitter carries it) is taken as it is:-at the runner, with no location on the chain, it is reported unchanged, and a host router packs-the root fault's own report with its location rather than a located report (see-`PipeRouterProtocol._as_pipelex_failure`), so nothing is located twice.+- the problem is the root fault's, its code, parameters and diagnostics included;+- its `location` names the failing pipe and its path from the entry pipe, as members rather than a prefix of+ any sentence, and a code that declares a `pipe` parameter is given the failing pipe.++A root fault whose problem was recovered across a transport boundary (a problem carried by a `PipelexError` whose+`recovered_problem()` returns it, the way a distributed worker's submitter carries it) is taken as it is: at the+runner, with no location on the chain, it is reported unchanged, and a host router packs the root fault's own problem+with its location rather than a located problem (see `PipeRouterProtocol._as_pipelex_failure`), so nothing is located+twice. Any other root fault, a located wrapper standing for a foreign exception included, is reported as the outer+wrapper reports it, so the facts and locations of the errors between the two reach the problem."""+from mthds.protocol.problem.models import ProblemLocationfrom pydantic import ValidationError-from pipelex.base_exceptions import ErrorReport, PipelexError, PipelexUnexpectedError, iter_cause_chain-from pipelex.cogt.inference.error_classification import UserAction, UserActionKind+from pipelex.base_exceptions import PipelexError, PipelexUnexpectedError, iter_cause_chain+from pipelex.errors.problem import PipelexProblem, ProblemView, make_locationfrom pipelex.tools.typing.pydantic_utils import format_pydantic_validation_error# Joins the pipe codes of a failure's path from the entry pipe down to the pipe that failed.@@ -96,18 +92,28 @@ def compose_located_message(*, pipe_code: str, pipe_stack: list[str], message: sdef locate_failure_message(*, failure: PipelexError, pipe_code: str, pipe_stack: list[str]) -> str:- """The message a located wrapper of `failure` carries: its root fault's own message, located."""+ """The message a located wrapper of `failure` carries, for its logs and its operator: its root fault's own message, located."""root_fault = find_root_fault(error=failure) or failure- return compose_located_message(pipe_code=pipe_code, pipe_stack=pipe_stack, message=root_fault.to_error_report().message)+ return compose_located_message(pipe_code=pipe_code, pipe_stack=pipe_stack, message=root_fault.message)+++def failure_location_of(*, pipe_code: str, pipe_stack: list[str]) -> ProblemLocation | None:+ """The location of a failure at `pipe_code`, whose path from the entry pipe is `pipe_stack`.++ `None` when the stack is empty, since the location is then unknown.+ """+ if not pipe_stack:+ return None+ return make_location(pipe=pipe_code, path=pipe_stack)def make_unexpected_failure(*, error: Exception) -> PipelexUnexpectedError:"""Stand a `PipelexUnexpectedError` in for an exception that is not a `PipelexError`.Its message names the original class, and it is chained to the original so its traceback- survives. It is never caller-facing: a foreign exception's text can carry anything, a server- path or a secret included. A pydantic `ValidationError` keeps the readable rendering the runner- gives one.+ survives. Its message only ever reaches an operator, since a foreign exception's text can carry+ anything, a server path or a secret included. A pydantic `ValidationError` keeps the readable+ rendering the runner gives one."""detail = format_pydantic_validation_error(error) if isinstance(error, ValidationError) else (str(error) or repr(error))unexpected_error = PipelexUnexpectedError(f"{type(error).__name__}: {detail}")@@ -116,58 +122,60 @@ def make_unexpected_failure(*, error: Exception) -> PipelexUnexpectedError:return unexpected_error-def _fallback_user_action(*, pipe_code: str, pipe_stack: list[str]) -> UserAction:- if pipe_stack:- detail = f"The run failed in pipe '{pipe_code}': the message gives the cause."- else:- detail = f"The run of '{pipe_code}' failed: the message gives the cause."- return UserAction(kind=UserActionKind.UNKNOWN, detail=detail)--def _find_root_fault_below(*, wrapper: PipelexError) -> PipelexError | None:"""The root fault under `wrapper`, or `None` when it wraps no `PipelexError` or its chain loops back to it."""cause = wrapper.__cause__if cause is None:return None- # A cyclic chain that reaches the wrapper again would make the root fault's report recurse- # into the wrapper's: report the wrapper as itself instead, as the base enrichment does.+ # A cyclic chain that reaches the wrapper again would make the root fault's problem recurse+ # into the wrapper's: report the wrapper as itself instead.if any(node is wrapper for node in iter_cause_chain(cause)):return Nonereturn find_root_fault(error=cause)-def build_located_failure_report(+def located_root_fault(*, wrapper: PipelexError) -> PipelexError | None:+ """The root fault a located wrapper reports.++ `None` when the wrapper is its own root fault: it chose its code, wraps no `PipelexError`, or loops back to itself.+ """+ # A wrapper whose raise site chose its code is the root fault itself, as `resolve_error_code` reads it.+ if wrapper.own_error_code is not None:+ return None+ return _find_root_fault_below(wrapper=wrapper)+++def located_problem(*,wrapper: PipelexError,- own_report: ErrorReport,- pipe_code: str,- pipe_stack: list[str],-) -> ErrorReport:- """Build the report of a located run failure from its root fault.+ root_fault: PipelexError,+ view: ProblemView,+ request_id: str | None,+ pipeline_run_id: str | None,+ failure_location: ProblemLocation | None,+) -> PipelexProblem:+ """The problem a located wrapper reports: its root fault's, located at the failing pipe.++ A root fault carrying a problem recovered across a transport boundary (`PipelexError.recovered_problem`) reports+ that problem as it is, located at `failure_location`. Any other root fault's problem is built as the wrapper+ reports it (`PipelexError.problem_reported_by`), so the facts and the location the errors between the two hold,+ such as the model and the backend a worker attributed a failure to on a wrapper that takes its cause's code, reach+ the problem. That holds for a root fault that overrides `to_problem` for another reason too, such as an inner+ `PipeRouterError` standing for a foreign exception under the runner's `PipelineExecutionError`.Args:- 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 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 is- unknown, in which case the message is the root fault's, unlocated.+ wrapper: The located wrapper, a `PipeRouterError` or a `PipelineExecutionError`.+ root_fault: The root fault below it (`located_root_fault`).+ view: The view of the reader the problem is built for.+ request_id: The request that carried the failure, when known.+ pipeline_run_id: The run the failure belongs to, when one exists.+ failure_location: Where the failing pipe is, when the failure was located at a pipe.Returns:- The root fault's report, carrying its code and what the code decides, with the located message and- the chain's diagnostics.+ The problem."""- # 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_report- return 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,- "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,- "provider_metadata": own_report.provider_metadata,- }+ if root_fault.recovered_problem() is not None:+ return root_fault.to_problem(view=view, request_id=request_id, pipeline_run_id=pipeline_run_id, failure_location=failure_location)+ return root_fault.problem_reported_by(+ reporter=wrapper, view=view, request_id=request_id, pipeline_run_id=pipeline_run_id, failure_location=failure_location)diff --git a/pipelex/pipe_run/pipe_router_protocol.py b/pipelex/pipe_run/pipe_router_protocol.pyindex a0e735e41..fc8ae3623 100644--- a/pipelex/pipe_run/pipe_router_protocol.py+++ b/pipelex/pipe_run/pipe_router_protocol.py@@ -93,23 +93,27 @@ class PipeRouterProtocol(Protocol):def _as_pipelex_failure(self, *, error: Exception) -> PipelexError | None:"""Return the `PipelexError` this router locates for `error`, or `None` to let `error` through untouched.- A `PipelexError` stands for itself, and that includes one carrying a report recovered- across a transport boundary, whose report then becomes the located failure's root fault.+ A `PipelexError` stands for itself, and that includes one carrying a problem recovered+ across a transport boundary, whose problem then becomes the located failure's root fault.Any other exception is foreign to Pipelex: it is wrapped into a `PipelexUnexpectedError`- that names its class and is never caller-facing, so it no longer escapes the runner raw.+ that names its class, whose message only an operator reads, so it no longer escapes the runner raw.A host router overrides this for the exceptions its own transport raises, and returns `None`for a control-flow exception its runtime must see unchanged, such as a cancellation. A- transport failure carrying a recovered report is converted according to what the far side- packed, which must never be a report that is already located, since this router would+ transport failure carrying a recovered problem is converted according to what the far side+ packed, which must never be a problem that is already located, since this router wouldlocate it again:- - the root fault's own report alone (`find_root_fault(...).to_error_report()`): return a+ - the root fault's own problem alone (`find_root_fault(...).to_problem(view=ProblemView.OPERATOR)`): return a`PipelexError` carrying it, and this router locates it at the pipe it ran;- - that report together with the location the far side found (`find_failure_location(...)`,+ - that problem together with the location the far side found (`find_failure_location(...)`,its `pipe_code` and `pipe_stack`): return `PipeRouterError.make_located(...)` over a- `PipelexError` carrying the report, chained to it. It already names its pipe, so this- router raises it untouched, and the report reads exactly as the local run's.+ `PipelexError` carrying the problem, chained to it. It already names its pipe, so this+ router raises it untouched, and the problem reads exactly as the local run's.++ A `PipelexError` carrying a recovered problem overrides `recovered_problem()` to return it, and its `to_problem`+ reports it projected to the view asked for (`pipelex.errors.problem.recovered_problem_in_view`), with the+ location it is given."""if isinstance(error, PipelexError):return errordiff --git a/pipelex/pipe_run/pipe_run.py b/pipelex/pipe_run/pipe_run.pyindex 56007752a..c3b3afc45 100644--- a/pipelex/pipe_run/pipe_run.py+++ b/pipelex/pipe_run/pipe_run.py@@ -3,15 +3,18 @@ from __future__ import annotationsimport timefrom typing import TYPE_CHECKING+from mthds.protocol.problem.registry import CoreCodefrom typing_extensions import overridefrom pipelex import log-from pipelex.base_exceptions import ErrorReport, PipelexError, PipelexUnexpectedError+from pipelex.base_exceptions import PipelexError+from pipelex.errors.problem import PipelexProblem, ProblemView, make_problemfrom pipelex.graph.graph_tracer_manager import GraphTracerManagerfrom pipelex.interpreter_hub import get_concept_library, get_own_pipesfrom pipelex.pipe_run.delivery_assignment import DeliveryAssignment, DeliveryStatusfrom pipelex.pipe_run.delivery_executor import DeliveryExecutorfrom pipelex.pipe_run.exceptions import DeliveryError+from pipelex.pipe_run.located_failure import make_unexpected_failurefrom pipelex.pipe_run.pipe_run_protocol import PipeRunProtocolfrom pipelex.pipe_run.tracing_assembly import RunTraceEvents, assemble_tracing_on_output, read_run_trace_eventsfrom pipelex.pipeline.build_pipe_io_artifacts import build_pipe_io_artifacts@@ -28,6 +31,32 @@ if TYPE_CHECKING:from pipelex.pipe_run.pipe_router_protocol import PipeRouterProtocol+WEBHOOK_PROBLEM_FAULT_MESSAGE = "The problem of a failed run could not be built for its webhooks"+"""The error logged when a failed run's problem raises while it is built for the run's webhooks."""+++def _webhook_problem(*, error: Exception, pipeline_run_id: str, request_id: str | None) -> PipelexProblem:+ """The problem of a failed run that its webhooks receive, in the operator's view, which each webhook projects to its own.++ A Pipelex error carries its own code, and a bare exception stands as a fault of ours, so a webhook still receives+ an ``error`` object. Delivery never changes how a run fails: this runs while the run's own error is on its way to+ the caller, so building the problem must not raise in its place. A problem that cannot be built is logged as an+ error, and the webhooks receive ``runtime.unexpected``, as a traced node does (``make_node_problem``).+ """+ failure = error if isinstance(error, PipelexError) else make_unexpected_failure(error=error)+ try:+ return failure.to_problem(view=ProblemView.OPERATOR, pipeline_run_id=pipeline_run_id, request_id=request_id)+ except Exception as problem_fault: # ruff: ignore[blind-except]+ # Unbounded code: `to_problem` reads hooks overridden across the whole error hierarchy, the errors plugins+ # define included, and walks the error's cause chain, so what it raises cannot be enumerated. The run's own+ # error is the one it fails with, so the fault is logged and the webhooks receive a fault of ours.+ log.error(+ WEBHOOK_PROBLEM_FAULT_MESSAGE,+ fields={"failed_error_type": type(error).__name__, **error_fields(exc=problem_fault)},+ )+ return make_problem(code=CoreCode.RUNTIME_UNEXPECTED, view=ProblemView.OPERATOR, pipeline_run_id=pipeline_run_id, request_id=request_id)++class PipeRun(PipeRunProtocol):"""Direct-mode PipeRun: executes the pipe inline, then delivers results."""@@ -66,7 +95,7 @@ class PipeRun(PipeRunProtocol):status: DeliveryStatus = DeliveryStatus.COMPLETEDpipe_output: PipeOutput | None = Noneexecution_error: Exception | None = None- error_report: ErrorReport | None = None+ problem: PipelexProblem | None = Noneclosed_graph: GraphSpec | None = None# The run's statistics: its inputs are read before the run adds its own outputs to its working memory.usage_tally = RunInferenceTally() if self._reports_usage_stats and usage_stats_are_enabled() else None@@ -85,14 +114,13 @@ class PipeRun(PipeRunProtocol):# Observe-and-reraise: records FAILED status so the finally delivery sees it, then re-raises the original error below.status = DeliveryStatus.FAILEDexecution_error = exc- # Always build a report for the FAILED webhook: Pipelex errors carry their own- # classification; a bare exception is wrapped in PipelexUnexpectedError so the- # webhook still receives an `error` object — matching Temporal mode, where- # recover_error_report() is total.- if isinstance(exc, PipelexError):- error_report = exc.to_error_report()- else:- error_report = PipelexUnexpectedError(str(exc) or repr(exc)).to_error_report()+ # The problem a FAILED webhook receives, built only when a webhook is there to receive it.+ if delivery_assignment is not None and delivery_assignment.webhooks:+ problem = _webhook_problem(+ error=exc,+ pipeline_run_id=pipeline_run_id,+ request_id=pipe_job.job_metadata.run_metadata.request_id,+ )# The error rides as fields and no traceback: the exception is re-raised below, and its traceback# belongs to whoever catches it, the CLI or the API's handler, which would otherwise print it twice.# `pipe_code` is the bare code `Pipe run starts` carries for the same pipe, so one query finds both lines.@@ -170,7 +198,7 @@ class PipeRun(PipeRunProtocol):pipeline_run_id=pipeline_run_id,delivery_assignment=delivery_assignment,status=status,- error_report=error_report,+ problem=problem,request_id=pipe_job.job_metadata.run_metadata.request_id,)except DeliveryError as delivery_error:diff --git a/pipelex/pipeline/bundle_validator.py b/pipelex/pipeline/bundle_validator.pyindex b5e923f71..f8fb2f24d 100644--- a/pipelex/pipeline/bundle_validator.py+++ b/pipelex/pipeline/bundle_validator.py@@ -30,8 +30,9 @@ import timefrom contextlib import AbstractContextManager, nullcontextfrom contextvars import ContextVarfrom enum import StrEnum-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Any, NamedTuple+from mthds.protocol.problem.registry import CoreCodefrom polyfactory.exceptions import FactoryExceptionfrom pydantic import BaseModel, Field, ValidationErrorfrom typing_extensions import override@@ -41,8 +42,9 @@ from pipelex.base_exceptions import PipelexError, ValidationErrorItemfrom pipelex.cogt.content_generation.content_generator import ContentGeneratorfrom pipelex.config import get_configfrom pipelex.core.exceptions import DryRunFailureErrorData-from pipelex.core.pipes.exceptions import caller_facing_refusal_text+from pipelex.core.pipes.exceptions import caller_refusalfrom pipelex.core.pipes.pipe_output import PipeOutput+from pipelex.errors.error_codes import ErrorCodefrom pipelex.interpreter_hub import (clear_current_library,get_current_library,@@ -109,8 +111,7 @@ class DryRunOutput(BaseModel):status: DryRunStatuserror_message: str | None = None# On a FAILURE, the failure located at the innermost pipe that failed and is not allowed to fail,- # which is this pipe or one- # it runs, with a message the disclosure rule allows onto a verdict item.+ # which is this pipe or one it runs, with its code and the sentence its code renders for a caller.failure: DryRunFailureErrorData | None = None# What the pipe's dry run found without failing, each item located at the pipe that found it, which is this# pipe or one it runs: today, the warnings of a PipeDocGen step's template check. The composition point of the@@ -119,8 +120,8 @@ class DryRunOutput(BaseModel):warnings: list[ValidationErrorItem] = Field(default_factory=empty_list_factory_of(ValidationErrorItem))-# The foreign shapes a dry run can fail with (pydantic and polyfactory, while mock data is built) carry no-# caller-facing flag, so their item names what failed rather than repeating their text.+# The foreign shapes a dry run can fail with (pydantic and polyfactory, while mock data is built) carry no code, so+# their item names what failed rather than repeating their text._MOCK_DATA_FAILURE_TEXT = "The dry run could not generate mock data for this pipe"@@ -188,20 +189,32 @@ class _DryRunSweepRouter(PipeRouter):raise-def _dry_run_failure_text(*, error: Exception) -> str:- """The text a dry-run failure puts on its verdict item: the failure's own message only when it is caller-facing.+class _DryRunFailureFacts(NamedTuple):+ """The code of a dry-run failure, the sentence its verdict item carries, and the parameters it was rendered from."""- The text is its root fault's, the innermost ``PipelexError`` on the cause chain, since a wrapper- around it neither knows more nor authors caller-facing copy of its own; of two faults of the same- class the outer one, which restates the inner with more context, is the root, as a run failure's- report takes it (see ``find_root_fault``). A message that is not- caller-facing is replaced by the fault's title, because the verdict is caller-facing as a whole- and would otherwise carry a configuration or storage failure's internals past STRICT disclosure.+ code: ErrorCode+ text: str+ params: dict[str, Any] | None+++def _dry_run_failure_facts(*, error: Exception, pipe_code: str) -> _DryRunFailureFacts:+ """The code a dry-run failure carries, the sentence its verdict item puts after the pipe's name, and its parameters.++ All are its root fault's, the error whose code the failure resolves to, since a wrapper around it neither knows+ more nor holds a code of its own; of two faults of the same class the outer one, which restates the inner with more+ context, is the root, as a run failure's problem takes it (see ``find_root_fault``). The sentence is the one the+ code renders for a caller, the failing pipe ``pipe_code`` naming its pipe parameter, never the fault's own message,+ because the verdict is read by the caller. A failure with no Pipelex error on its chain is the dry run failing to+ mock a value: ``method.mock_unsatisfiable``. So is a pydantic ``ValidationError`` or a polyfactory+ ``FactoryException`` raised inside a routed pipe, which reaches the sweep as the ``PipelexUnexpectedError`` the+ router stands in for it (``find_foreign_fault``), and which would otherwise read as a fault of ours."""root_fault = find_root_fault(error=error)- if root_fault is None:- return _MOCK_DATA_FAILURE_TEXT- return caller_facing_refusal_text(refusal=root_fault)+ if root_fault is None or isinstance(find_foreign_fault(error=error), (ValidationError, FactoryException)):+ return _DryRunFailureFacts(code=CoreCode.METHOD_MOCK_UNSATISFIABLE, text=_MOCK_DATA_FAILURE_TEXT, params=None)+ problem = caller_refusal(refusal=root_fault, pipe_code=pipe_code)+ params = problem.params.as_wire() if problem.params is not None else None+ return _DryRunFailureFacts(code=root_fault.resolve_error_code(), text=problem.detail, params=params or None)def _disclosed_warnings(*, warnings: list[ValidationErrorItem], source_pipe_refs: frozenset[str] | None) -> list[ValidationErrorItem]:@@ -581,13 +594,16 @@ class BundleValidator:failing_pipe_source: str | None = Noneif source_pipe_refs is None or failing_pipe.pipe_ref in source_pipe_refs:failing_pipe_source = get_library_manager().get_pipe_source(failing_pipe.pipe_ref)+ failure_facts = _dry_run_failure_facts(error=exc, pipe_code=failing_pipe.code)failure = DryRunFailureErrorData(+ code=failure_facts.code,pipe_code=failing_pipe.code,domain_code=failing_pipe.domain_code,# Compatibility boundary: injected managers written against the previous protocol may still# return ``Path``. Normalize before assigning to the string-only model.source=str(failing_pipe_source) if failing_pipe_source is not None else None,- message=f"Pipe '{failing_pipe.code}' failed its dry run: {_dry_run_failure_text(error=exc)}",+ message=f"Pipe '{failing_pipe.code}' failed its dry run: {failure_facts.text}",+ params=failure_facts.params,)return DryRunOutput(pipe_code=pipe.code, pipe_ref=pipe.pipe_ref, status=DryRunStatus.FAILURE, error_message=error_message, failure=failure@@ -628,7 +644,10 @@ class BundleValidator:)if unexpected_failures:failures = cls._located_failures(unexpected_failures=unexpected_failures)- details = "\n".join(f"- {failure.message}" for failure in failures)+ # The message is the operator's diagnostics, so it gives each failure as the dry run met it, such as a+ # combine's restatement naming the branch to change, which the failures' caller sentences leave out.+ met_texts = {id(output.failure): output.error_message for output in unexpected_failures.values() if output.failure is not None}+ details = "\n".join(f"- {met_texts.get(id(failure)) or failure.message}" for failure in failures)msg = f"Dry run failed for {len(failures)} pipe(s):\n{details}"raise DryRunError(msg, failures=failures)return results@@ -647,6 +666,7 @@ class BundleValidator:failures_by_pipe_ref: dict[str, DryRunFailureErrorData] = {}for swept_pipe_ref, dry_run_output in unexpected_failures.items():failure = dry_run_output.failure or DryRunFailureErrorData(+ code=CoreCode.RUNTIME_UNEXPECTED,pipe_code=dry_run_output.pipe_code,message=f"Pipe '{dry_run_output.pipe_code}' failed its dry run",)diff --git a/pipelex/pipeline/direct_bundle_validator.py b/pipelex/pipeline/direct_bundle_validator.pyindex ad44c011b..b4c8dce5f 100644--- a/pipelex/pipeline/direct_bundle_validator.py+++ b/pipelex/pipeline/direct_bundle_validator.py@@ -2,8 +2,8 @@Validates MTHDS bundles in-process via ``validate_bundles_in_process``, the same sweepthe local protocol runtime uses. Returns the verdict as a value (decision A): the canonical-``PipelexValidationReport`` on success, or the structured ``ErrorReport`` an invalid bundle's-``ValidateBundleError`` projects. Any other exception propagates as a no-verdict infra fault.+``PipelexValidationReport`` on success, or the ``BundleValidationFailure`` of an invalid bundle's+``ValidateBundleError``. Any other exception propagates as a no-verdict fault.Registered unconditionally by the core ``direct`` plugin alongside ``DirectOrchestrator``, sothe agnostic base gets in-process ``/validate`` "for free" through the same seam the Temporal@@ -14,6 +14,8 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING+from pipelex.errors.bundle_validation_failure import BundleValidationFailure+from pipelex.errors.problem import ProblemViewfrom pipelex.pipeline.exceptions import ValidateBundleErrorfrom pipelex.pipeline.validate_in_process import validate_bundles_in_process@@ -21,7 +23,6 @@ if TYPE_CHECKING:from collections.abc import Mapping, Sequencefrom pathlib import Path- from pipelex.base_exceptions import ErrorReportfrom pipelex.pipeline.validation_report import PipelexValidationReportfrom pipelex.system.caller_identity import CallerIdentity@@ -50,7 +51,7 @@ class DirectBundleValidator:# The in-process arm reads every file of the method in this process, from the trees its libraries hold, and# reads no blob store, so the scope a dispatched arm hands its worker the trees through has no use here.read_scope: str | None, # ruff: ignore[unused-method-argument]- ) -> PipelexValidationReport | ErrorReport:+ ) -> PipelexValidationReport | BundleValidationFailure:try:return await validate_bundles_in_process(mthds_contents=mthds_contents,@@ -65,6 +66,6 @@ class DirectBundleValidator:methods_dirs=methods_dirs,)except ValidateBundleError as exc:- # An invalid bundle is a produced verdict, not a fault: surface its structured- # report as the invalid arm. Any other exception (genuine infra fault) propagates.- return exc.to_error_report()+ # An invalid bundle is a produced verdict, not a fault: surface its problem and its items+ # as the invalid arm. Any other exception (a fault with no verdict) propagates.+ return BundleValidationFailure(problem=exc.to_problem(view=ProblemView.OPERATOR), validation_errors=exc.validation_error_items())diff --git a/pipelex/pipeline/exceptions.py b/pipelex/pipeline/exceptions.pyindex 497488002..bd0f0c31b 100644--- a/pipelex/pipeline/exceptions.py+++ b/pipelex/pipeline/exceptions.py@@ -1,11 +1,12 @@import refrom collections.abc import Collection-from typing import ClassVar, NamedTuple, Self, TypeVar+from typing import Any, ClassVar, NamedTuple, Self, TypeVar, cast+from mthds.protocol.problem.models import ProblemItem, ProblemLocationfrom mthds.protocol.problem.registry import CoreCodefrom typing_extensions import override-from pipelex.base_exceptions import ErrorReport, PipelexError, ValidationErrorItem+from pipelex.base_exceptions import PipelexError, ValidationErrorItemfrom pipelex.cogt.inference.error_classification import UserAction, UserActionKindfrom pipelex.core.exceptions import (DryRunFailureErrorData,@@ -14,10 +15,12 @@ from pipelex.core.exceptions import (PipesAndConceptValidationErrorData,)from pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeDeclaration, ErrorCodeSet, InheritsCause+from pipelex.errors.error_codes import ErrorCode, code_is_method_domain+from pipelex.errors.problem import PipelexProblem, ProblemViewfrom pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.pipe_run.exceptions import find_failure_location-from pipelex.pipe_run.located_failure import build_located_failure_report, locate_failure_message-from pipelex.pipeline.validation_errors import build_validation_error_items+from pipelex.pipe_run.located_failure import failure_location_of, locate_failure_message, located_problem, located_root_fault+from pipelex.pipeline.validation_errors import build_validation_error_items, problem_item_of, validation_item_codefrom pipelex.system.pipe_run_mode import PipeRunMode@@ -37,14 +40,10 @@ 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. 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 are- inherited from the cause chain (so a categorized ``CogtError`` keeps its ``WAIT_AND_RETRY`` /- ``CHECK_BILLING`` action) and, when nothing on the chain advises an action, a fallback names the- failing pipe. See ``pipelex.pipe_run.located_failure``.+ Its problem is not its own. It takes its cause's code, and ``to_problem()`` is the root fault's, the first+ ``PipelexError`` on the cause chain that carries a code of its own, or the problem such an error recovered across+ a transport boundary, with a ``location`` naming the failing pipe and its path. See+ ``pipelex.pipe_run.located_failure``."""error_code = InheritsCause(fallback=CoreCode.RUNTIME_UNEXPECTED)@@ -95,12 +94,20 @@ class PipelineExecutionError(PipelexError):)@override- def to_error_report(self) -> ErrorReport:- return build_located_failure_report(- wrapper=self,- own_report=super().to_error_report(),- pipe_code=self.pipe_code,- pipe_stack=self.pipe_stack,+ def to_problem(+ self,+ *,+ view: ProblemView,+ request_id: str | None = None,+ pipeline_run_id: str | None = None,+ failure_location: ProblemLocation | None = None,+ ) -> PipelexProblem:+ location = failure_location or failure_location_of(pipe_code=self.pipe_code, pipe_stack=self.pipe_stack)+ root_fault = located_root_fault(wrapper=self)+ if root_fault is None:+ return super().to_problem(view=view, request_id=request_id, pipeline_run_id=pipeline_run_id, failure_location=location)+ return located_problem(+ wrapper=self, root_fault=root_fault, view=view, request_id=request_id, pipeline_run_id=pipeline_run_id, failure_location=location)@@ -114,6 +121,10 @@ class PipeStackOverflowError(PipelexError):self.pipe_stack = list(pipe_stack) # snapshot: the live stack unwinds after this error is raisedsuper().__init__(message)+ @override+ def problem_params(self) -> dict[str, Any]:+ return {"limit": self.limit}+class PipelineManagerNotFoundError(PipelexError):"""The pipeline manager holds no run under an id it was asked for: an internal lookup of ours."""@@ -198,22 +209,44 @@ class _FileWithholding(NamedTuple):return self.pattern.sub(lambda _match: self.placeholder, text)def withheld_errors(self, *, errors: list[_SourcedErrorData]) -> list[_SourcedErrorData]:- """The error data without a withheld name as its ``source``, its ``field_path`` or in its ``message``.+ """The error data without a withheld name as its ``source``, its ``field_path``, in its ``message`` or its ``params``.A pipe-validation error located from the pipe-source map carries its file as its ``field_path`` too- (``categorize_pipe_validation_with_libraries_error``), so a withheld file leaves that field empty.+ (``categorize_pipe_validation_with_libraries_error``), so a withheld file leaves that field empty. A dry-run+ failure's parameters render its item's sentence, so a text among them, such as the template file a host's step+ names, reads the placeholder too."""withheld: list[_SourcedErrorData] = []for error in errors:- update: dict[str, str | None] = {+ update: dict[str, Any] = {"source": None if error.source in self.names else error.source,"message": self.withheld_text(text=error.message),}if isinstance(error, PipesAndConceptValidationErrorData) and error.field_path in self.names:update["field_path"] = ""+ if isinstance(error, DryRunFailureErrorData) and error.params:+ update["params"] = self.withheld_params(params=error.params)withheld.append(error.model_copy(update=update))return withheld+ def withheld_params(self, *, params: dict[str, Any]) -> dict[str, Any]:+ """Parameters reading the placeholder where a text of them named a withheld file."""+ return {name: self._withheld_value(value=value) for name, value in params.items()}++ def withheld_item(self, *, item: ProblemItem) -> ProblemItem:+ """A problem item reading the placeholder where a text of it, its sentence, a parameter or a locator, named a withheld file."""+ return ProblemItem.model_validate(self._withheld_value(value=item.as_wire()))++ def _withheld_value(self, *, value: Any) -> Any:+ """A value reading the placeholder where a text of it, at any depth, named a withheld file."""+ if isinstance(value, str):+ return self.withheld_text(text=value)+ if isinstance(value, list):+ return [self._withheld_value(value=item) for item in cast("list[Any]", value)]+ if isinstance(value, dict):+ return {key: self._withheld_value(value=item) for key, item in cast("dict[str, Any]", value).items()}+ return value+def withhold_names_in_text(*, text: str, names: Collection[str], placeholder: str) -> str:"""``text`` reading ``placeholder`` where it named one of ``names`` standing on its own, never inside a longer name.@@ -224,6 +257,10 @@ def withhold_names_in_text(*, text: str, names: Collection[str], placeholder: streturn _FileWithholding.make_from_names(names=names, placeholder=placeholder).withheld_text(text=text)+# The code of a verdict itself, which no item of it takes: its sentence says nothing of any one fault.+_VERDICT_UMBRELLA_CODES: frozenset[ErrorCode] = frozenset({CoreCode.METHOD_INVALID})++class ValidateBundleError(PipelexError):"""Raised when a bundle is refused while it is loaded or validated: the invalid verdict, carrying onestructured item per refusal in ``validation_errors``. Every refusal of the bundle itself becomes one —@@ -248,8 +285,11 @@ class ValidateBundleError(PipelexError):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.+ Its code is ``method.invalid``, each item keeping its own code on the problem's ``errors``; a request that names+ nothing to validate, such as an empty set of bundle contents, is ``request.invalid``, chosen at its raise site.+ The validation translation builds one only when at least one item is the method's+ (``pipelex.pipeline.validate_bundle_translation``): a refusal whose every item is a fault of another actor answers+ that fault, never an invalid verdict."""error_code = ErrorCodeSet(default=CoreCode.METHOD_INVALID, others=(CoreCode.REQUEST_INVALID,))@@ -259,9 +299,6 @@ class ValidateBundleError(PipelexError):# suggested fix when one can be derived, so the top level says to follow them rather than to go read them.detail="Edit the bundle as each validation error says: apply its suggested fix where it has one, after confirming an unsafe one",)- # Bundle-validation messages describe faults in the caller's own bundle —- # caller-facing copy, kept verbatim under STRICT disclosure.- _authors_caller_facing_message = Truedef __init__(self,@@ -283,13 +320,16 @@ class ValidateBundleError(PipelexError):# One located failure per pipe whose dry run failed (see ``BundleValidator``).self.dry_run_failures = dry_run_failures or []+ # The files a withheld verdict must not name (``withholding_files``), withheld again from every problem item it+ # builds, since an item reads parameters from beyond the verdict's own channels, its cause's among them.+ self._file_withholding: _FileWithholding | None = None+# Disease C: the top-line ``message`` is often a leaky ``str(pydantic ValidationError)``# (``Value errors: '<field>': Value error, …``). Replace it at the source with a clean- # summary derived from the already-clean per-error item messages, so EVERY surface that- # shows the top-line — the agent JSON ``message`` and the API report — benefits (one- # engine), not just the CLI markdown. The raw ``message`` still rides ``to_error_report``'s- # ``fallback_message`` residual, which only fires when there is no categorized data (the- # summary is the raw message in that same case, so the two stay consistent).+ # summary derived from the already-clean per-error item messages, so every surface that+ # shows the top-line benefits (one engine), not just the CLI markdown. The raw ``message``+ # still rides the ``fallback_message`` residual, which only fires when there is no categorized+ # data (the summary is the raw message in that same case, so the two stay consistent).super().__init__(_summarize_bundle_validation_message(blueprint_errors=self.pipelex_bundle_blueprint_validation_errors,@@ -308,9 +348,13 @@ class ValidateBundleError(PipelexError):items' and the verdict's own, reads ``placeholder`` where it named one of them standing on its own,never inside a longer name. Everything else is kept, the items' locators included, so it is the sameanswer about the same bundle. Every channel the constructor takes is carried here: a channel added to- it must be added here too, which ``test_validate_bundle_error_withholding`` pins. A validator of- submitted content uses it to keep the files of the host's own library directories, paths on the host,- out of a verdict that STRICT disclosure hands the caller verbatim.+ it must be added here too, which ``test_validate_bundle_error_withholding`` pins. So is what the raise site chose+ after building it: the code it chose (:meth:`with_error_code`), and the parameters and items it gave+ (:meth:`with_params`, :meth:`with_items`), withheld as the messages are. The new verdict keeps the withholding,+ and every problem item it builds (:meth:`problem_items`) is withheld too, its sentence, every parameter and its+ locators: an item no stage classified takes the parameters of the refusal the verdict was built from, its+ cause, which the withholding never rewrote. A validator of submitted content uses it to keep the files of the+ host's own library directories, paths on the host, out of a verdict the caller reads.Args:withheld_files: Every spelling of every file the verdict must not name.@@ -320,7 +364,7 @@ class ValidateBundleError(PipelexError):A new verdict; this one is left as it is."""withholding = _FileWithholding.make_from_names(names=withheld_files, placeholder=placeholder)- return ValidateBundleError(+ withheld = ValidateBundleError(message=withholding.withheld_text(text=self.message),pipelex_bundle_blueprint_validation_errors=withholding.withheld_errors(errors=self.pipelex_bundle_blueprint_validation_errors),pipe_factory_errors=[@@ -330,6 +374,14 @@ class ValidateBundleError(PipelexError):pipe_concept_instantiation_errors=withholding.withheld_errors(errors=self.pipe_concept_instantiation_errors),dry_run_failures=withholding.withheld_errors(errors=self.dry_run_failures),)+ if self._chosen_error_code is not None:+ withheld.with_error_code(self._chosen_error_code)+ if self.given_params:+ withheld.with_params(**withholding.withheld_params(params=self.given_params))+ if self._given_items:+ withheld.with_items(items=[withholding.withheld_item(item=item) for item in self._given_items])+ withheld._file_withholding = withholding+ return withheld@propertydef pipe_validation_error_data(self) -> list[PipesAndConceptValidationErrorData]:@@ -343,8 +395,8 @@ class ValidateBundleError(PipelexError):def validation_error_items(self) -> list[ValidationErrorItem]:"""Project every channel this verdict carries into typed wire items, via the shared builder.- The one projection behind the API report (:meth:`to_error_report`), the agent CLI's- ``validation_errors`` array and ``pipelex fix``, so no surface can drop a channel another+ The one projection behind the problem's items (:meth:`problem_items`), the ``/validate`` verdict, the agent+ CLI's ``validation_errors`` array and ``pipelex fix``, so no surface can drop a channel anotherkeeps. The pipe-validation arm uses :attr:`pipe_validation_error_data` (pipe validation**plus** pipe/concept instantiation errors) so the instantiation category is not silentlydropped. Each dry-run failure becomes its own located ``dry_run`` item. Finally@@ -363,19 +415,43 @@ class ValidateBundleError(PipelexError):)@override- def to_error_report(self) -> ErrorReport:- """Attach the structured ``validation_errors`` list onto the base report.-- ``super().to_error_report()`` builds the report and enriches it from the- ``__cause__`` chain; this override then attaches the per-error structured- list from :meth:`validation_error_items` — the same items the agent CLI- emits — so the API problem document carries machine-mappable diagnostics.- The list is set to ``None`` when empty so it drops out of the- ``exclude_none`` wire projection (and the round-trip stays identical to a- plain report).+ def problem_items(self) -> list[ProblemItem] | None:+ """One problem item per validation item, each with its own code: a dry run's the failure's, any other its type's.++ An item no stage classified takes the code of the refusal this verdict was built from when that refusal is+ the method's, and ``method.schema_violation`` otherwise, or when that code is ``method.invalid``: the verdict's+ own umbrella, whose sentence says nothing of the item. On a withheld verdict (:meth:`withholding_files`), every+ item is withheld whole, its sentence, its parameters and its locators, whichever channel each came from."""- report = super().to_error_report()- return report.model_copy(update={"validation_errors": self.validation_error_items() or None})+ residual_code: ErrorCode = CoreCode.METHOD_SCHEMA_VIOLATION+ # The parameters the refusal's code renders from, as a caller reads them, which an item taking its code keeps.+ residual_params: dict[str, Any] | None = None+ cause = self.__cause__+ if isinstance(cause, PipelexError):+ cause_code = cause.resolve_error_code()+ if code_is_method_domain(code=cause_code) and cause_code not in _VERDICT_UMBRELLA_CODES:+ residual_code = cause_code+ cause_params = cause.to_problem(view=ProblemView.CALLER).params+ residual_params = cause_params.as_wire() if cause_params is not None else None+ dry_run_failures = iter(self.dry_run_failures)+ items: list[ProblemItem] = []+ for item in self.validation_error_items():+ item_code: ErrorCode+ item_params: dict[str, Any] | None = None+ if item.category.is_dry_run:+ dry_run_failure = next(dry_run_failures, None)+ item_code = dry_run_failure.code if dry_run_failure is not None else CoreCode.RUNTIME_UNEXPECTED+ item_params = dry_run_failure.params if dry_run_failure is not None else None+ elif item.error_type is None:+ item_code = residual_code+ item_params = residual_params+ else:+ item_code = validation_item_code(item=item, residual_code=residual_code)+ items.append(problem_item_of(item=item, code=item_code, params=item_params))+ if self._file_withholding is not None:+ file_withholding = self._file_withholding+ items = [file_withholding.withheld_item(item=item) for item in items]+ return items or Noneclass HostLibraryLoadRefusalError(PipelexError):@@ -386,9 +462,9 @@ class HostLibraryLoadRefusalError(PipelexError):refuses in any other way the caller's own content would be refused, is the deployment's configuration failing tovalidate: `pipelex.config.invalid`, the code the registry gives the libraries among the runtime's ownconfiguration, 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.+ directories. Its message names the method's refusal, which only the operator reads, and the caller reads the+ code's sentence, which quotes 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@@ -416,14 +492,12 @@ class PipelineInputContentError(PipelexError):caller supplied the value — INPUT domain, so API servers answer 422, nevera sanitized 500 (a blank url used to surface as IsADirectoryError('.') → 500).- Deliberately NOT caller-facing: the message names the resolved path and the- ``OSError`` subclass that rejected it, or the storage provider's reason for- refusing a key, which are server-side storage facts. Surviving STRICT disclosure would turn the report into an- existence/permission oracle over the runner's filesystem for any- authenticated caller — ``PermissionError`` on a path that exists reads- differently from ``FileNotFoundError`` on one that does not. The- caller-facing half of this family is ``PipelineInputUrlMissingError``,- whose message carries nothing but the accepted schemes.+ The message names the resolved path and the ``OSError`` subclass that+ rejected it, or the storage provider's reason for refusing a key, which are+ server-side storage facts: it rides only the operator's diagnostics, since a+ caller reading it could probe the runner's filesystem — ``PermissionError``+ on a path that exists reads differently from ``FileNotFoundError`` on one+ that does not. The caller reads the code's sentence.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@@ -446,14 +520,13 @@ class PipelineInputContentError(PipelexError):class PipelineInputUrlInvalidError(PipelineInputContentError):"""An Image/Document input carries an http(s) url that does not parse as one.- Caller-facing on purpose: the message repeats the url the caller supplied and- what is wrong with its shape, both of which are the caller's own facts. Whether+ The message repeats the url the caller supplied and what is wrong with its+ shape, both of which are the caller's own facts. Whetherthe resource behind a well-formed url exists is not decided here — the operatorthat 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,detail="Provide a well-formed http(s) URL: a scheme, a host, and no whitespace.",@@ -464,14 +537,12 @@ class PipelineInputFormatError(PipelineInputContentError):"""A file input's format is one its input slot, or the pipe that consumes it, cannot take.Raised at run setup, after the setup established each file input's format from its bytes, so the- run is refused before any pipe spends anything on it. Caller-facing on purpose, and the flag spans- every child and every raise site: a message in this family carries only facts the caller supplied- (the input's path in the inputs, the file's identified type) or the method declares (a pipe, a- model, the formats that model reads), never a url, a storage key or a server-side reason.+ run is refused before any pipe spends anything on it. A message in this family carries only facts the+ caller supplied (the input's path in the inputs, the file's identified type) or the method declares (a+ pipe, a 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,detail="Give the input a file in a format the method can read.",@@ -513,17 +584,9 @@ class PipelineInputFormatUnsupportedError(PipelineInputFormatError):class PipelineInputUrlMissingError(PipelineInputContentError):- """An Image/Document input carries a blank url.-- The message states only the accepted schemes — no path, no server-side fact- — so it is caller-facing copy and survives STRICT disclosure intact, where- the placeholder would leave the caller with nothing to act on.- (``caller_facing_message`` is the *report* field; the class-level flag that- sets it is ``_authors_caller_facing_message``.)- """+ """An Image/Document input carries a blank url."""error_code = CoreCode.INPUT_INVALID- _authors_caller_facing_message = Trueclass MethodEntryError(PipelexError):@@ -538,10 +601,12 @@ class MethodEntryError(PipelexError):`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``+ Its code defaults to ``request.pipe_unspecified``, a run naming no pipe of a method that declares no single+ ``main_pipe``, which names the bundles' ``main_pipe``s as its candidates when they declare several; the raise site+ chooses ``request.pipe_not_found`` when no bundle of the method defines the pipe the caller named,+ ``request.pipe_ambiguous`` when the caller named a pipe by a bare code that bundles of several domains define,+ ``method.pipe_unresolved`` when the manifest names a pipe no bundle defines, ``method.ref_ambiguous`` when+ several bundles define the pipe the manifest names, ``method.package_invalid``when the manifest cannot be read, ``method.syntax`` when a bundle is not text, and ``method.invalid`` whenthe method holds no bundle at all."""@@ -549,6 +614,7 @@ class MethodEntryError(PipelexError):error_code = ErrorCodeSet(default=CoreCode.REQUEST_PIPE_UNSPECIFIED,others=(+ CoreCode.METHOD_REF_AMBIGUOUS,CoreCode.REQUEST_PIPE_AMBIGUOUS,CoreCode.REQUEST_PIPE_NOT_FOUND,CoreCode.METHOD_PIPE_UNRESOLVED,@@ -561,4 +627,3 @@ class MethodEntryError(PipelexError):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",)- _authors_caller_facing_message = Truediff --git a/pipelex/pipeline/file_input_consumers.py b/pipelex/pipeline/file_input_consumers.pyindex 4ebc6e97a..6141689fa 100644--- a/pipelex/pipeline/file_input_consumers.py+++ b/pipelex/pipeline/file_input_consumers.py@@ -222,6 +222,8 @@ def check_file_inputs_against_consumers(*, entry_pipe: PipeAbstract, file_inputsreturnconsumers_by_slot = collect_file_input_consumers(entry_pipe)violations: list[str] = []+ # The code's parameters name one violation, the first, which the message lists among the others.+ first_violation_params: dict[str, str | None] | None = Nonefor file_input in known_file_inputs:format_key = file_input.format_keyif format_key is None:@@ -239,9 +241,11 @@ def check_file_inputs_against_consumers(*, entry_pipe: PipeAbstract, file_inputsf"pipe '{consumer.pipe_code}' {consumer.verb_phrase} model '{consumer.model}', "f"which reads {describe_format_keys(format_keys=consumer.listed_formats)}.")+ if first_violation_params is None:+ first_violation_params = {"input": file_input.display_path, "format": format_key, "model": consumer.model}if violations:msg = " ".join([*violations, "Give a file in a format its model reads, or use a model that reads this format."])- raise PipelineInputFormatUnsupportedError(msg)+ raise PipelineInputFormatUnsupportedError(msg).with_params(**(first_violation_params or {}))def _is_http_url(*, uri_kind: UriKind) -> bool:diff --git a/pipelex/pipeline/fixes/fix_loop.py b/pipelex/pipeline/fixes/fix_loop.pyindex 4051b6fb8..8383c7f69 100644--- a/pipelex/pipeline/fixes/fix_loop.py+++ b/pipelex/pipeline/fixes/fix_loop.py@@ -108,7 +108,7 @@ def _fix_fingerprint(fix: SuggestedFix) -> str:def _validation_error_items(exc: ValidateBundleError) -> list[ValidationErrorItem]:- """Project the error's categorized lists into wire items — same channels as ``to_error_report``."""+ """Project the error's categorized lists into wire items — the same channels as its problem's items."""return exc.validation_error_items()diff --git a/pipelex/pipeline/input_normalizer.py b/pipelex/pipeline/input_normalizer.pyindex e1aa4a4d4..22c9fe7b6 100644--- a/pipelex/pipeline/input_normalizer.py+++ b/pipelex/pipeline/input_normalizer.py@@ -571,7 +571,8 @@ def _identify_file_input(f"Input '{input_name}' expects an image, but the file is {describe_file_format(format_key=format_key, mime_type=mime_type_to_describe)}. ""Give an image file such as PNG, JPEG or WebP.")- raise PipelineInputNotAnImageError(msg)+ # No model reads the input yet, so the code's sentence, which names one, falls back to its title.+ raise PipelineInputNotAnImageError(msg).with_params(input=input_name, format=format_key)async def _load_local_head(local_path: Path) -> bytes:diff --git a/pipelex/pipeline/method_entry.py b/pipelex/pipeline/method_entry.pyindex 5454ce564..63c1b10c5 100644--- a/pipelex/pipeline/method_entry.py+++ b/pipelex/pipeline/method_entry.py@@ -201,7 +201,10 @@ 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).with_error_code(CoreCode.REQUEST_PIPE_AMBIGUOUS)+ # The run names no pipe, so there is no selector for `request.pipe_ambiguous` to name: the pipes it may name are+ # the candidates of the default code, `request.pipe_unspecified`.+ declared_refs = sorted(f"{candidate.domain}.{candidate.main_pipe}" for candidate in declaring)+ raise MethodEntryError(msg).with_params(candidates=declared_refs)entry_candidate = declaring[0]main_pipe = entry_candidate.main_pipeif main_pipe is None:@@ -232,14 +235,16 @@ 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).with_error_code(CoreCode.METHOD_PIPE_UNRESOLVED)+ raise MethodEntryError(msg).with_error_code(CoreCode.METHOD_PIPE_UNRESOLVED).with_params(missing=main_pipe)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).with_error_code(CoreCode.REQUEST_PIPE_AMBIGUOUS)+ # The manifest's own declaration matches several pipes, which its author resolves: never a pipe that does not exist.+ defined_refs = sorted(f"{candidate.domain}.{main_pipe}" for candidate in defining)+ raise MethodEntryError(msg).with_error_code(CoreCode.METHOD_REF_AMBIGUOUS).with_params(ref=main_pipe, candidates=defined_refs)return _entry_of(candidate=defining[0], pipe_code=main_pipe)@@ -272,12 +277,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).with_error_code(CoreCode.REQUEST_PIPE_NOT_FOUND)+ raise MethodEntryError(msg).with_error_code(CoreCode.REQUEST_PIPE_NOT_FOUND).with_params(pipe=pipe_ref)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).with_error_code(CoreCode.REQUEST_PIPE_NOT_FOUND) from exc+ raise MethodEntryError(msg).with_error_code(CoreCode.REQUEST_PIPE_NOT_FOUND).with_params(pipe=pipe_ref) from excdefining = [candidatefor candidate in candidates@@ -285,9 +290,10 @@ 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).with_error_code(CoreCode.REQUEST_PIPE_NOT_FOUND)+ raise MethodEntryError(msg).with_error_code(CoreCode.REQUEST_PIPE_NOT_FOUND).with_params(pipe=pipe_ref)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).with_error_code(CoreCode.REQUEST_PIPE_AMBIGUOUS)+ defined_refs = sorted(f"{candidate.domain}.{qualified_ref.local_code}" for candidate in defining)+ raise MethodEntryError(msg).with_error_code(CoreCode.REQUEST_PIPE_AMBIGUOUS).with_params(pipe=pipe_ref, candidates=defined_refs)return _entry_of(candidate=defining[0], pipe_code=qualified_ref.local_code)diff --git a/pipelex/pipeline/pipeline_manager.py b/pipelex/pipeline/pipeline_manager.pyindex 7587a48b4..885d4fbd4 100644--- a/pipelex/pipeline/pipeline_manager.py+++ b/pipelex/pipeline/pipeline_manager.py@@ -40,7 +40,7 @@ class PipelineManager(PipelineManagerAbstract, RootModel[PipelineManagerRoot]):def add_new_pipeline(self, *, pipe_code: str | None, pipeline_run_id: str | None = None) -> Pipeline:if pipeline_run_id is not None and pipeline_run_id in self.root:msg = f"Pipeline {pipeline_run_id} already exists"- raise PipelineManagerAlreadyExistsError(msg)+ raise PipelineManagerAlreadyExistsError(msg).with_params(pipeline_run_id=pipeline_run_id)pipeline = PipelineFactory.make_pipeline(pipeline_run_id=pipeline_run_id)self._set_pipeline(pipeline_run_id=pipeline.pipeline_run_id, pipeline=pipeline)return pipelinediff --git a/pipelex/pipeline/pipeline_run_setup.py b/pipelex/pipeline/pipeline_run_setup.pyindex 58704568b..7f2dcbf22 100644--- a/pipelex/pipeline/pipeline_run_setup.py+++ b/pipelex/pipeline/pipeline_run_setup.py@@ -171,7 +171,7 @@ async def pipeline_run_setup(request_id:Optional inbound ``X-Request-ID`` from the dispatcher (the value theexternal HTTP caller can use to correlate every log line and every- ``ErrorReport`` back to its originating request). Threaded onto+ problem back to its originating request). Threaded onto:attr:`pipelex.system.job_metadata.RunMetadata.request_id` so itcrosses the Temporal serialization boundary intact.inputs_base_dir:@@ -224,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 PipeExecutionError(message=msg).with_error_code(CoreCode.REQUEST_PIPE_UNSPECIFIED).as_caller_fault()+ raise PipeExecutionError(message=msg).with_error_code(CoreCode.REQUEST_PIPE_UNSPECIFIED)# Validate the extras HERE, before this function causes anything observable.#@@ -355,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).with_error_code(CoreCode.REQUEST_PIPE_UNSPECIFIED).as_caller_fault()+ raise PipeExecutionError(message=msg).with_error_code(CoreCode.REQUEST_PIPE_UNSPECIFIED)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.pyindex f4beebfba..9a6875a19 100644--- a/pipelex/pipeline/request_exceptions.py+++ b/pipelex/pipeline/request_exceptions.py@@ -26,8 +26,6 @@ class PipelexRequestError(PipelineRequestError, PipelexError):"""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 = Truedef __init__(self, message: str, *, field: str, unsupported_reason: str | None = None) -> None:"""Build the refusal of one request field.@@ -51,4 +49,4 @@ class PipelexRequestError(PipelineRequestError, PipelexError):# is the refusal alone, since the report states its next step on its own.self.message = messageself.field = field- self.with_error_code(code)+ self.with_error_code(code).with_params(**params)diff --git a/pipelex/pipeline/resolve_bundle.py b/pipelex/pipeline/resolve_bundle.pyindex ba35e21ec..62157c2b8 100644--- a/pipelex/pipeline/resolve_bundle.py+++ b/pipelex/pipeline/resolve_bundle.py@@ -33,6 +33,7 @@ from mthds.protocol.problem.registry import CoreCodefrom pipelex.base_exceptions import PipelexUnexpectedErrorfrom pipelex.core.method_trees.file_references import BundleFileOriginfrom pipelex.core.qualified_ref import QualifiedRef+from pipelex.errors.unsupported_reasons import ADDRESS_DEPENDENCY_UNSUPPORTED_REASONfrom pipelex.interpreter_hub import clear_current_library, get_current_library_id_or_none, get_library_manager, set_current_libraryfrom pipelex.libraries.bundle_resources import check_submitted_filesfrom pipelex.libraries.crate_normalization import normalize_crate@@ -106,7 +107,7 @@ def resolve_crate_from_contents(crate = library_manager.get_crate(library_id)if crate is None:# Unreachable with non-empty contents (load_from_blueprints accumulated them), so a- # None crate is an internal invariant break, not a caller-facing verdict.+ # None crate is an internal invariant break, not a verdict on the caller's method.msg = "library crate unavailable after a successful bundle load"raise PipelexUnexpectedError(msg)return normalize_crate(crate, mthds_version=MTHDS_STANDARD_VERSION)@@ -192,4 +193,8 @@ 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).with_error_code(CoreCode.REQUEST_UNSUPPORTED)+ raise (+ PipeLibraryError(msg)+ .with_error_code(CoreCode.REQUEST_UNSUPPORTED)+ .with_params(field="files", reason=ADDRESS_DEPENDENCY_UNSUPPORTED_REASON)+ )diff --git a/pipelex/pipeline/validate_bundle.py b/pipelex/pipeline/validate_bundle.pyindex 3cc135c92..907e9d34e 100644--- a/pipelex/pipeline/validate_bundle.py+++ b/pipelex/pipeline/validate_bundle.py@@ -120,10 +120,8 @@ def _pipes_to_dry_run(loaded_pipes: list[PipeAbstract], *, dry_run_pipe_codes: lif missing:missing_str = ", ".join(f"'{code}'" for code in sorted(missing))msg = f"Pipe(s) {missing_str} not found in the bundle. Check for typos and make sure they are declared in the bundle."- # The bundle-scoped wording stays the raise site's own — more precise here than the class's- # library-lookup message — and is safe under ``_authors_caller_facing_message``: it names only- # the caller's own selector codes (derived from ``wanted``), nothing from the loaded library.- raise EntryPipeNotFoundError(msg)+ # The bundle-scoped wording stays the raise site's own, more precise here than the class's library-lookup message.+ raise EntryPipeNotFoundError(msg).with_params(pipe=", ".join(sorted(missing)))return selected@@ -182,7 +180,7 @@ async def validate_bundle(if provided_params == 0:# Programmer error: a caller (the HTTP request layer, a builder op) must wire exactly one# input. It is not a content verdict the end user can fix → PipelexUnexpectedError (→ 500,- # redacted under STRICT), matching the mthds_sources-mismatch guard below — never a+ # runtime.unexpected), matching the mthds_sources-mismatch guard below — never a# ValidateBundleError, which would 200/422 a host-wiring bug as if the bundle were invalid.msg = "One of mthds_contents, mthds_file_path or method_dir must be provided to validate_bundle"raise PipelexUnexpectedError(msg)@@ -206,9 +204,9 @@ async def validate_bundle(# threads each bundle's source onto the in-memory load path so its diagnostics carry a# real ``source``). It is never supplied by the end caller, so a missing-alongside /# length-mismatch is a host wiring bug, not bad user input: raise an internal error- # (→ 500, redacted under STRICT) rather than ``ValidateBundleError`` (→ caller-facing- # 422). Contrast the empty-``mthds_contents`` guard above, which can legitimately- # reflect an end user submitting no bundles and so stays a caller-facing input error.+ # (→ 500, runtime.unexpected) rather than ``ValidateBundleError`` (→ 422). Contrast the+ # empty-``mthds_contents`` guard above, which can legitimately reflect an end user+ # submitting no bundles and so stays the caller's input error.msg = "mthds_sources, when provided, must be a per-item source list matching mthds_contents in length"raise PipelexUnexpectedError(msg)diff --git a/pipelex/pipeline/validate_bundle_translation.py b/pipelex/pipeline/validate_bundle_translation.pyindex c0d57fee3..4eac1a3c9 100644--- a/pipelex/pipeline/validate_bundle_translation.py+++ b/pipelex/pipeline/validate_bundle_translation.py@@ -17,7 +17,7 @@ from typing import NamedTuple, castfrom pydantic import ValidationError-from pipelex.base_exceptions import PipelexError, SecurityError, error_domain_is_input+from pipelex.base_exceptions import ErrorDomain, PipelexError, SecurityErrorfrom pipelex.config import get_configfrom pipelex.core.bundle_resources.exceptions import BundleResourceNotNamedError, BundleResourcePathErrorfrom pipelex.core.exceptions import DryRunFailureErrorData, PipelexBundleBlueprintValidationErrorData, PipesAndConceptValidationErrorData@@ -27,9 +27,11 @@ from pipelex.core.pipes.exceptions import (PipeOperatorModelChoiceError,PipeRunError,PipeValidationError,- caller_facing_refusal_text,+ caller_refusal,+ refusal_detail,)from pipelex.core.validation import report_validation_error+from pipelex.errors.error_codes import code_is_method_domainfrom 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@@ -90,12 +92,15 @@ def translate_to_validate_bundle_error() -> Generator[None, None, None]:factory error, etc. Sharing one source of truth means a new handler onlyneeds to be added once.- **Every refusal of the bundle is a verdict.** After the class-specific arms, a final arm turns any- other ``PipelexError`` whose report is ``input``-domained (the caller's fault) into a verdict with one- item, so a refusal nobody wrote an arm for still reaches the author as an invalid bundle rather than- as a crash or a no-verdict fault. Only a failure of the tool or its environment — a ``config`` or- ``runtime`` fault, an unclassified one, anything that is not a ``PipelexError`` — propagates as- no verdict, along with the refusals that must keep their own class: ``PipeNotFoundError`` (its+ **Every refusal of the method is a verdict, and only a refusal of the method.** After the class-specific+ arms, a final arm turns any other ``PipelexError`` whose code is the method's (its registry domain is+ ``method``) into a verdict with one item, so a refusal nobody wrote an arm for still reaches the author+ as an invalid bundle rather than as a crash or a no-verdict fault. A dry run's failures, and a library's+ refusal, become a verdict only when at least one of them is the method's: a failure whose every fault+ belongs to another actor, the runtime's own included, answers its own code, never that the method is+ invalid. A failure of the tool or its environment, a refusal of another actor than the method's author,+ anything that is not a ``PipelexError``, propagates as no verdict, along with the refusals that must+ keep their own class: ``PipeNotFoundError`` (itsdedicated not-found handler), a ``SecurityError`` (never absorbed by a domain handler), a``ValidateBundleError`` already produced (never re-wrapped), and a ``BundleResourceNotNamedError`` or a``BundleResourcePathError``, which refuse the files submitted with the bundle rather than the bundle.@@ -150,10 +155,10 @@ 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):+ # A library error that is not the method's, such as an invariant of the library manager+ # (`runtime.unexpected`) or library directories configured wrongly (`pipelex.config.invalid`), is no+ # verdict about the bundle, and propagates as it is.+ if not code_is_method_domain(code=library_error.resolve_error_code()):raiseif isinstance(library_error, LibraryLoadingError):blueprint_validation_errors = library_error.blueprint_validation_errors@@ -167,15 +172,22 @@ def translate_to_validate_bundle_error() -> Generator[None, None, None]:pipe_validation_errors=pipe_concept_validation_errors,) from library_errorexcept PipeRunError as pipe_run_error:- # A pipe run failing outside the sweep's per-pipe classification: one dry-run item on its pipe,- # whose text follows the disclosure rule, since the verdict carries it past STRICT disclosure.- failure_text = caller_facing_refusal_text(refusal=pipe_run_error)+ # A pipe run failing outside the sweep's per-pipe classification: one dry-run item on its pipe when+ # its fault is the method's, whose text is the sentence its code renders for the caller who reads the+ # verdict, and otherwise the fault itself, which no verdict carries.+ failure_code = pipe_run_error.resolve_error_code()+ if not code_is_method_domain(code=failure_code):+ raise+ failure_problem = caller_refusal(refusal=pipe_run_error, pipe_code=pipe_run_error.pipe_code)+ failure_params = failure_problem.params.as_wire() if failure_problem.params is not None else Noneraise ValidateBundleError(- message=failure_text,+ message=pipe_run_error.message,dry_run_failures=[DryRunFailureErrorData(+ code=failure_code,pipe_code=pipe_run_error.pipe_code,- message=f"Pipe '{pipe_run_error.pipe_code}' failed its dry run: {failure_text}",+ message=f"Pipe '{pipe_run_error.pipe_code}' failed its dry run: {failure_problem.detail}",+ params=failure_params or None,)],) from pipe_run_error@@ -184,10 +196,17 @@ def translate_to_validate_bundle_error() -> Generator[None, None, None]: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.+ # DryRunError raised elsewhere carries none, and stands for one failure, its own. They are a verdict+ # only when one of them is the method's; otherwise the dry run's fault answers its own code, every+ # failure riding its items, and never reads as an invalid method.+ dry_run_failures = dry_run_error.failures or [+ DryRunFailureErrorData(code=dry_run_error.resolve_error_code(), message=refusal_detail(refusal=dry_run_error))+ ]+ if not any(code_is_method_domain(code=failure.code) for failure in dry_run_failures):+ raiseraise ValidateBundleError(message=dry_run_error.message,- dry_run_failures=dry_run_error.failures or [DryRunFailureErrorData(message=caller_facing_refusal_text(refusal=dry_run_error))],+ dry_run_failures=dry_run_failures,) from dry_run_errorexcept PipeOperatorModelChoiceError as model_choice_error:# A pipe names a model its deck does not define: the operator located it on the pipe and the@@ -237,7 +256,7 @@ def reporting_host_library_faults() -> Generator[None, None, None]: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_errorexcept PipelexError as refusal:- if not error_domain_is_input(refusal.to_error_report().error_domain):+ if not ErrorDomain.from_problem_domain(refusal.resolve_domain()).is_input:raisemsg = f"A method in a library directory of this host refuses to load ({type(refusal).__name__}): {refusal.message}"raise HostLibraryLoadRefusalError(msg) from refusal@@ -246,20 +265,19 @@ def reporting_host_library_faults() -> Generator[None, None, None]: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``.- ``None`` — no verdict — unless the refusal's report is ``input``-domained: a ``config`` or ``runtime``- fault, or an unclassified one, is a failure of the tool or its environment, which the validator must- not report as the bundle's fault. The item is ``pipe_validation`` when the library load located the+ ``None`` — no verdict — unless the refusal's code is the method's: a refusal another actor must act on,+ the caller's input, the account, the operator or the runtime, is never the bundle's fault, and keeps+ its own code. The item is ``pipe_validation`` when the library load located therefusal on the pipe it was building (``PipeLoadRefusalError``, with the pipe's code, domain and file),and ``blueprint_validation`` otherwise. It carries no ``error_type``: a refusal with a closed codehas its own arm above, and naming one here would claim a diagnosis the refusal does not make.- The item's text is the refusal's message only when that message was authored as caller-facing copy,- and otherwise its title: the verdict is caller-facing as a whole and is kept verbatim under STRICT- disclosure, so internal text must not ride it past the redaction it would otherwise get.+ The item's text is the sentence the refusal's code renders for a caller, never the refusal's own message:+ the verdict is read by the caller, and the message is the operator's diagnostics."""- if not error_domain_is_input(refusal.to_error_report().error_domain):+ if not code_is_method_domain(code=refusal.resolve_error_code()):return None- message = caller_facing_refusal_text(refusal=refusal)+ message = refusal_detail(refusal=refusal)if isinstance(refusal, PipeLoadRefusalError):return ValidateBundleError(message=message,@@ -285,8 +303,8 @@ def withholding_host_library_files() -> Generator[None, None, None]:"""Keep the files of a host's own library directories out of the verdict the block raises.- A verdict is caller-facing as a whole, and STRICT disclosure hands its message and its items to the caller- verbatim, so it must not name a path on the host. When submitted content is validated or run, the library+ A verdict is read by the caller, its items' messages and locators included, so it must not name a path on the+ host. When submitted content is validated or run, the librarydirectories loaded beside it are the host's (installed libraries, the defaults, ``PIPELEXPATH``), and an itemlocated in one of their files would name that file, as would a message about it, such as a duplicatedeclaration, a load that failed, or two ``@pipe_func`` functions of the same name, which the registry names bydiff --git a/pipelex/pipeline/validation_errors.py b/pipelex/pipeline/validation_errors.pyindex cad41828c..50242bc89 100644--- a/pipelex/pipeline/validation_errors.py+++ b/pipelex/pipeline/validation_errors.py@@ -1,20 +1,31 @@-"""Shared builder that flattens bundle-validation error data into typed wire items.+"""Shared builder that flattens bundle-validation error data into typed wire items, and those into problem items.-``build_validation_error_items`` is the single source of truth behind both-structured-error surfaces:+``build_validation_error_items`` is the single source of truth behind every+structured-error surface:- the agent CLI's ``validation_errors`` JSON array (via- ``pipelex.cli.agent_cli.commands.agent_output.extract_validation_errors``), and-- the API report's ``ErrorReport.validation_errors`` (via- ``ValidateBundleError.to_error_report``).+ ``pipelex.cli.agent_cli.commands.agent_output.extract_validation_errors``),+- the ``/validate`` route's invalid verdict, and+- the problem's ``errors`` (via ``ValidateBundleError.problem_items``, which+ turns each item into a problem item with :func:`problem_item_of`).-Both reach it through ``ValidateBundleError.validation_error_items``, so the CLI+All of them reach it through ``ValidateBundleError.validation_error_items``, so the CLIand API structured shapes cannot drift. It takes the error-data lists directlyrather than a ``ValidateBundleError`` instance — that keeps the dependency one-directional(``pipelex.pipeline.exceptions`` imports this module, never the reverse) so thereis no import cycle."""+from typing import Any++from mthds.protocol.problem.models import ProblemItem+from mthds.protocol.problem.registry import (+ CoreCode,+ MethodDependencyMissingKind,+ MethodDependencyMissingReason,+ MethodIdentifierInvalidIdentifierKind,+)+from pipelex.base_exceptions import ValidationErrorCategory, ValidationErrorItemfrom pipelex.core.exceptions import (DryRunFailureErrorData,@@ -22,8 +33,12 @@ from pipelex.core.exceptions import (PipelexBundleBlueprintValidationErrorData,PipesAndConceptValidationErrorData,)+from pipelex.core.pipes.exceptions import pipe_validation_error_code+from pipelex.core.qualified_ref import QualifiedRef+from pipelex.errors.error_codes import ErrorCode, error_code_spec+from pipelex.errors.problem import make_location, make_problem_itemfrom pipelex.pipeline.fixes.planner import plan_fix_for_blueprint_validation_error, plan_fix_for_pipe_validation_error-from pipelex.validation_error_types import ValidationResidualErrorType+from pipelex.validation_error_types import PipeFactoryErrorType, PipeValidationErrorType, ValidationResidualErrorTypedef build_validation_error_items(@@ -62,7 +77,7 @@ def build_validation_error_items(factory_errors: Pipe-factory error data (e.g. a missing concept).pipe_validation_errors: Pipe/concept validation error data.dry_run_failures: One located failure per pipe whose dry run failed.- fallback_message: The error's caller-facing message, used as the+ fallback_message: The error's message, used as thelast-resort residual. Only projected as a ``blueprint_validation``item when no other channel produced one.@@ -128,7 +143,7 @@ def build_validation_error_items()# One located item per failing pipe: the sweep already reduced a failure that made enclosing- # controllers fail to the innermost pipe, and built each message under the disclosure rule.+ # controllers fail to the innermost pipe, and gave each failure the sentence its code renders for a caller.for dry_run_failure in dry_run_failures or []:items.append(ValidationErrorItem(@@ -157,3 +172,136 @@ def build_validation_error_items()return items+++def validation_item_code(*, item: ValidationErrorItem, residual_code: ErrorCode) -> ErrorCode:+ """The code of a validation item that is not a dry run's: its ``error_type``'s, or ``residual_code`` for an item with none.++ Args:+ item: The item.+ residual_code: The code of the refusal the verdict was built from, which an item no stage classified takes.++ Returns:+ The item's code.+ """+ error_type = item.error_type+ if error_type is None:+ return residual_code+ if isinstance(error_type, PipeValidationErrorType):+ return pipe_validation_error_code(error_type=error_type)+ if isinstance(error_type, PipeFactoryErrorType):+ match error_type:+ case PipeFactoryErrorType.UNKNOWN_CONCEPT:+ return CoreCode.METHOD_CONCEPT_UNRESOLVED+ case PipeFactoryErrorType.UNKNOWN_FACTORY_ERROR:+ return CoreCode.METHOD_SCHEMA_VIOLATION+ # The dry-run residual, whose items take their failure's own code, and the advisory types, which only ride warnings.+ return residual_code+++# The identifier an item of these types is about, and where the item holds it: an input name among its variable names, a pipe+# code as its pipe. A main_pipe the item does not name, or a pipe code only its message quotes, gives no identifier facts.+_IDENTIFIER_KINDS: dict[PipeValidationErrorType, MethodIdentifierInvalidIdentifierKind] = {+ PipeValidationErrorType.INVALID_INPUT_NAME: MethodIdentifierInvalidIdentifierKind.INPUT_NAME,+ PipeValidationErrorType.INVALID_PIPE_CODE_SYNTAX: MethodIdentifierInvalidIdentifierKind.PIPE_CODE,+}+++def _identifier_facts(*, item: ValidationErrorItem) -> dict[str, Any]:+ """The name an identifier item is about and what the name is, when the item holds the name."""+ if not isinstance(item.error_type, PipeValidationErrorType):+ return {}+ identifier_kind = _IDENTIFIER_KINDS.get(item.error_type)+ if identifier_kind is None:+ return {}+ match identifier_kind:+ case MethodIdentifierInvalidIdentifierKind.INPUT_NAME:+ name = item.variable_names[0] if item.variable_names else None+ case MethodIdentifierInvalidIdentifierKind.PIPE_CODE | MethodIdentifierInvalidIdentifierKind.MAIN_PIPE:+ name = item.pipe_code+ if name is None:+ return {}+ return {"identifier_kind": identifier_kind, "name": name}+++def _dependency_facts(*, item: ValidationErrorItem) -> dict[str, Any]:+ """The package an unresolved package reference names, the prefix of its ``->`` reference, as a missing dependency."""+ if item.error_type not in _PACKAGE_DEPENDENCY_TYPES or not item.missing_pipe_code:+ return {}+ reference = item.missing_pipe_code+ package = QualifiedRef.split_cross_package_ref(reference).alias if QualifiedRef.has_cross_package_prefix(reference) else reference+ return {+ "kind": MethodDependencyMissingKind.PACKAGE,+ "name": package,+ "reason": MethodDependencyMissingReason.NOT_FOUND,+ "package": package,+ }+++# The item types about a package the method depends on that could not be resolved.+_PACKAGE_DEPENDENCY_TYPES: frozenset[PipeValidationErrorType] = frozenset({PipeValidationErrorType.UNRESOLVED_PACKAGE_DEPENDENCY})+++def _item_facts(*, item: ValidationErrorItem) -> dict[str, Any]:+ """The facts a validation item holds, by the names the registry gives the parameters that carry them."""+ facts: dict[str, Any] = {+ **_identifier_facts(item=item),+ **_dependency_facts(item=item),+ "pipe": item.pipe_code,+ "concept": item.missing_concept_code or item.concept_code,+ "variables": item.variable_names,+ "model": item.model_reference,+ "model_type": item.model_type,+ "suggestions": item.suggestions,+ "field_path": item.field_path or _declaration_path(item=item),+ "missing": item.missing_pipe_code,+ "finding": item.message,+ }+ return {name: value for name, value in facts.items() if value is not None}+++def _declaration_path(*, item: ValidationErrorItem) -> str | None:+ """The bundle-root dot path of the declaration an item is about when it names no field path: its pipe's, or its concept's."""+ if item.pipe_code is not None:+ return f"pipe.{item.pipe_code}.{item.field_name}" if item.field_name else f"pipe.{item.pipe_code}"+ if item.concept_code is not None:+ return f"concept.{item.concept_code}"+ return None+++def problem_item_of(*, item: ValidationErrorItem, code: ErrorCode, params: dict[str, Any] | None = None) -> ProblemItem:+ """The problem item of a validation item: its code, the parameters its locators give that code, and its location.++ Args:+ item: The validation item.+ code: Its code: :func:`validation_item_code`'s, or the dry-run failure's own.+ params: Parameters known beside the item, such as those a dry-run failure was rendered from, which take+ precedence over the item's own.++ Returns:+ The problem item, its sentence rendered from the code's template.+ """+ spec = error_code_spec(code)+ facts = {**_item_facts(item=item), **(params or {})}+ item_params = {name: value for name, value in facts.items() if name in spec.param_names}+ line = item.line if item.line is not None and item.line >= 1 else None+ column = item.column if item.column is not None and item.column >= 1 else None+ location = make_location(pipe=item.pipe_code, field=item.field_name or item.field_path or None, file=item.source, line=line, column=column)+ return make_problem_item(+ code=code,+ params=item_params,+ location=location,+ suggestions=item.suggestions,+ suggested_fix=_problem_fix(item=item),+ )+++def _problem_fix(*, item: ValidationErrorItem) -> dict[str, Any] | None:+ """An item's suggested fix in the standard's wire form, where the file it edits is ``file``, not ``source``."""+ if item.suggested_fix is None:+ return None+ fix = item.suggested_fix.model_dump(mode="json", exclude_none=True)+ source = fix.pop("source", None)+ if source is not None:+ fix["file"] = source+ return fixdiff --git a/pipelex/plugins/bundle_validator_registry.py b/pipelex/plugins/bundle_validator_registry.pyindex 23733427f..c4bbcf629 100644--- a/pipelex/plugins/bundle_validator_registry.py+++ b/pipelex/plugins/bundle_validator_registry.py@@ -7,9 +7,9 @@ external orchestrator plugin can contribute a worker-dispatched validator undermode token — which core never names.Verdict-as-value (not raise): ``validate_bundles`` *returns* the verdict — the valid-report (a ``ValidationReport``) or the invalid ``ErrorReport`` (carrying-``validation_errors``) — and raises only for a no-verdict infra fault (which a host-runtime maps to a 5xx). This is the same valid/invalid pair the API maps to its+report (a ``ValidationReport``) or the invalid ``BundleValidationFailure`` (the refusal's+problem in the operator's view, with its ``validation_errors``) — and raises only for a+no-verdict fault, which a host runtime answers with that fault's problem. This is the same valid/invalid pair the API maps to its200-always ``/validate`` wire, so the verdict contract is backend-independent.Seam typed at the MTHDS-protocol level (``ValidationReport``), not the concrete@@ -28,7 +28,7 @@ from typing import TYPE_CHECKING, Any, Protocol, TypeAlias, runtime_checkablefrom mthds.protocol.models import ValidationReport-from pipelex.base_exceptions import ErrorReport+from pipelex.errors.bundle_validation_failure import BundleValidationFailurefrom pipelex.runtime_bridge.orchestration_mode import OrchestrationModefrom pipelex.system.caller_identity import CallerIdentity@@ -37,11 +37,11 @@ if TYPE_CHECKING:from pathlib import Path# The verdict a validator returns: valid arm = the protocol validation report (at runtime-# always the canonical PipelexValidationReport subtype), invalid arm = the structured-# ErrorReport. Bound at runtime (not just under TYPE_CHECKING) so an external validator+# always the canonical PipelexValidationReport subtype), invalid arm = the refusal's+# BundleValidationFailure. 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[Any] | ErrorReport+BundleValidationVerdict: TypeAlias = ValidationReport[Any] | BundleValidationFailure@runtime_checkablediff --git a/pipelex/plugins/contract.py b/pipelex/plugins/contract.pyindex 1cd12bc8d..6660d2993 100644--- a/pipelex/plugins/contract.py+++ b/pipelex/plugins/contract.py@@ -9,8 +9,7 @@ if TYPE_CHECKING:# registrar menu or the plugin contract.## v2 added the optional ``add_http_error_mapper`` capability (a framework-agnostic-# transport-fault → ``ErrorReport`` mapping a host runtime renders into its own-# HTTP error response).+# mapping of a transport fault a host runtime renders into its own HTTP error response).## v3 added ``add_storage_provider`` and ``add_secrets_provider`` — two config-selected,# process-global provider registries (``runtime.storage.method`` / ``runtime.secrets.method`` pick@@ -86,7 +85,14 @@ if TYPE_CHECKING:# ``PipeFuncPackageOfferFactoryFn`` receives a ``PipeFuncPackageOfferRequest``, the pipe_func config and the requirements# of the one method being judged, where it received the config alone, and may answer a ``PipeFuncPackageRefusal``# beside an offer or ``None``. A factory written against v7 would read the request as the config it expected.-PLUGIN_API_VERSION: int = 8+#+# v9 changed what crosses the plugin contract for a failure, now that every failure is a problem document seen through+# the view of its reader. An HTTP-error mapper (``add_http_error_mapper``) returns the ``PipelexError`` a transport+# exception stands for, whose problem the host builds in the view of whoever asked, where it returned a report; and a+# bundle validator's ``validate_bundles`` returns a ``BundleValidationFailure`` as its invalid arm, the refusal's+# problem in the operator's view with its validation items, where it returned a report. A plugin written against v8+# would hand back a type that is gone; the bump turns that into a discovery-time mismatch naming the plugin.+PLUGIN_API_VERSION: int = 9@runtime_checkablediff --git a/pipelex/plugins/exceptions.py b/pipelex/plugins/exceptions.pyindex 956a50d85..1b21f7014 100644--- a/pipelex/plugins/exceptions.py+++ b/pipelex/plugins/exceptions.py@@ -342,10 +342,6 @@ class RetiredPluginEntryPointGroupError(PluginError):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-def __init__(self, *, plugin_names: list[str], retired_group: str, groups: list[str]):self.plugin_names = plugin_namesself.retired_group = retired_group@@ -379,9 +375,6 @@ class PluginDeclaredInMultipleGroupsError(PluginError):error_code = PipelexErrorCode.PLUGIN_BROKEN- # The message names the caller's own installed distribution and the exact fix.- _authors_caller_facing_message = True-def __init__(self, *, plugin_name: str, groups: list[str]):self.plugin_name = plugin_nameself.groups = groups@@ -423,10 +416,6 @@ class UnknownBootOrchestratorError(PluginError):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-def __init__(self, *, requested: str):self.requested = requestedmessage = (@@ -449,10 +438,6 @@ class UnknownStorageMethodError(PluginError):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-def __init__(self, *, method: str, registered_methods: list[str]):self.method = methodself.registered_methods = registered_methods@@ -477,10 +462,6 @@ class UnknownPipeFuncExecutionModeError(PluginError):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-def __init__(self, *, mode: str, registered_modes: list[str]):self.mode = modeself.registered_modes = registered_modes@@ -504,10 +485,6 @@ class UnknownSecretsMethodError(PluginError):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-def __init__(self, *, method: str, registered_methods: list[str]):self.method = methodself.registered_methods = registered_methods@@ -531,10 +508,6 @@ class UnknownLogSinkError(PluginError):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-def __init__(self, *, method: str, registered_methods: list[str]):self.method = methodself.registered_methods = registered_methodsdiff --git a/pipelex/plugins/inference_backend_registry.py b/pipelex/plugins/inference_backend_registry.pyindex 220bbe8ee..2e33bb1bf 100644--- a/pipelex/plugins/inference_backend_registry.py+++ b/pipelex/plugins/inference_backend_registry.py@@ -46,9 +46,8 @@ class CheckLLMRequestFn(Protocol):A refusal is an ``LLMCapabilityError``, and a validation verdict shows it to whoever wrote the setting.A built-in backend's refusal is shown with the model named by its deck handle, since this library writes- those messages. An external plugin's refusal is shown as written only when the plugin raises it as- caller-facing copy (``as_caller_fault()``), vouching that it names nothing the plugin keeps private;- any other is named by its title alone.+ those messages. An external plugin's refusal is shown by the sentence its code renders, since its own+ message may name what the plugin keeps private; that message rides the operator's diagnostics alone."""def __call__(self, *, inference_model: "InferenceModelSpec", job_params: "LLMJobParams", is_structured: bool) -> None: ...diff --git a/pipelex/plugins/registrar.py b/pipelex/plugins/registrar.pyindex b85890291..29ea3d5c7 100644--- a/pipelex/plugins/registrar.py+++ b/pipelex/plugins/registrar.py@@ -5,7 +5,7 @@ from typing import TYPE_CHECKING, Any, NamedTuple, TypeVarfrom pydantic import BaseModel, Field-from pipelex.base_exceptions import ErrorReport+from pipelex.base_exceptions import PipelexErrorfrom 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@@ -52,11 +52,11 @@ if TYPE_CHECKING:_RegistryKeyT = TypeVar("_RegistryKeyT")_RegistryValueT = TypeVar("_RegistryValueT")-# A plugin's framework-agnostic mapping from one transport/runtime exception to a-# structured ``ErrorReport``. A host runtime (``pipelex-api``) renders the report-# into its own HTTP error response (RFC 7807 + disclosure) — so core and the plugin-# name no web framework.-HttpErrorMapperFn = Callable[[Exception], ErrorReport]+# A plugin's framework-agnostic mapping from one transport/runtime exception to the+# ``PipelexError`` it stands for. A host runtime (``pipelex-api``) builds that error's+# problem in the view of whoever asked and renders it into its own HTTP error response+# — so core and the plugin name no web framework.+HttpErrorMapperFn = Callable[[Exception], PipelexError]# A thunk returning the concrete exception class a mapper applies to. The mapper is# registered with this *provider* rather than the bare type so a plugin whose@@ -77,7 +77,7 @@ class _HttpErrorMapperContribution(NamedTuple):"""exc_type_provider: HttpErrorTypeProviderFn- to_error_report: HttpErrorMapperFn+ to_pipelex_error: HttpErrorMapperFnsource_plugin: str@@ -506,8 +506,8 @@ class PluginRegistrar:),)- def add_http_error_mapper(self, *, exc_type_provider: HttpErrorTypeProviderFn, to_error_report: HttpErrorMapperFn) -> None:- """Contribute a mapping from a transport/runtime exception to a structured ``ErrorReport``.+ def add_http_error_mapper(self, *, exc_type_provider: HttpErrorTypeProviderFn, to_pipelex_error: HttpErrorMapperFn) -> None:+ """Contribute a mapping from a transport/runtime exception to the ``PipelexError`` it stands for.``exc_type_provider`` is a thunk returning the concrete exception class themapper applies to. It is resolved *lazily* by ``get_http_error_mappers`` (at a@@ -515,16 +515,16 @@ class PluginRegistrar:plugin's ``register`` import-light: a plugin whose exception type lives in aheavy orchestrator SDK (``temporalio``) passes ``lambda: TemporalError`` and theSDK import is deferred until a host runtime actually consumes the mappers. The- ``to_error_report`` closure is likewise uninvoked until an error is rendered.+ ``to_pipelex_error`` closure is likewise uninvoked until an error is rendered.A host runtime (``pipelex-api``) iterates the resolved mappers at app- construction and wraps each into one framework error handler (FastAPI, …) using- its own RFC 7807 + disclosure rendering — so core and the plugin name no web- framework. Duplicate-by-type detection is deferred to ``get_http_error_mappers``+ construction and wraps each into one framework error handler (FastAPI, …) that+ renders the error's problem in the view of whoever asked — so core and the plugin+ name no web framework. Duplicate-by-type detection is deferred to ``get_http_error_mappers``(the providers must run first); it stays fail-loud and names both plugins."""self.http_error_mappers.append(- _HttpErrorMapperContribution(exc_type_provider=exc_type_provider, to_error_report=to_error_report, source_plugin=self._active.name)+ _HttpErrorMapperContribution(exc_type_provider=exc_type_provider, to_pipelex_error=to_pipelex_error, source_plugin=self._active.name))self._active.contributions.append("http error mapper")@@ -612,7 +612,7 @@ class PluginRegistrar:raise DuplicateHttpErrorMapperError(exc_type=exc_type.__qualname__, first_plugin=sources[exc_type], second_plugin=contribution.source_plugin)- resolved[exc_type] = contribution.to_error_report+ resolved[exc_type] = contribution.to_pipelex_errorsources[exc_type] = contribution.source_pluginreturn resolveddiff --git a/pipelex/providers/anthropic/anthropic_llm_worker.py b/pipelex/providers/anthropic/anthropic_llm_worker.pyindex 2133da8ad..4cdddbce1 100644--- a/pipelex/providers/anthropic/anthropic_llm_worker.py+++ b/pipelex/providers/anthropic/anthropic_llm_worker.py@@ -306,7 +306,7 @@ class AnthropicLLMWorker(LLMWorkerAbstract):)case ThinkingMode.NONE:msg = f"Model '{inference_model.desc}' does not support reasoning (thinking_mode=none)"- raise LLMCapabilityError(msg)+ raise LLMCapabilityError(msg).with_params(capability="reasoning")@classmethoddef _build_thinking_params_for_budget(@@ -323,7 +323,7 @@ class AnthropicLLMWorker(LLMWorkerAbstract):f"Model '{inference_model.desc}' uses adaptive thinking which does not support reasoning_budget. "f"Use reasoning_effort instead (e.g. reasoning_effort='high')")- raise LLMCapabilityError(msg)+ raise LLMCapabilityError(msg).with_params(capability="a reasoning budget")case ThinkingMode.MANUAL:safe_budget = fit_thinking_budget(budget=budget,@@ -340,7 +340,7 @@ class AnthropicLLMWorker(LLMWorkerAbstract):)case ThinkingMode.NONE:msg = f"Model '{inference_model.desc}' does not support reasoning (thinking_mode=none)"- raise LLMCapabilityError(msg)+ raise LLMCapabilityError(msg).with_params(capability="reasoning")@overrideasync def _gen_text(diff --git a/pipelex/providers/bedrock/bedrock_factory.py b/pipelex/providers/bedrock/bedrock_factory.pyindex 480566cf0..4b29e1c5a 100644--- a/pipelex/providers/bedrock/bedrock_factory.py+++ b/pipelex/providers/bedrock/bedrock_factory.py@@ -65,6 +65,6 @@ class BedrockFactory:message.content.append(BedrockContentItem(text=user_text))if llm_job.llm_prompt.user_images:msg = "BedrockFactory does not support images. Skipping images."- raise LLMCapabilityError(msg)+ raise LLMCapabilityError(msg).with_params(capability="images")return messagediff --git a/pipelex/providers/bedrock/bedrock_llm_worker.py b/pipelex/providers/bedrock/bedrock_llm_worker.pyindex 4ea7d76a4..39694cf73 100644--- a/pipelex/providers/bedrock/bedrock_llm_worker.py+++ b/pipelex/providers/bedrock/bedrock_llm_worker.py@@ -52,9 +52,9 @@ class BedrockLLMWorker(LLMWorkerAbstract):f"Model '{inference_model.desc}' does not support reasoning parameters; ""Bedrock native models do not support reasoning_effort or reasoning_budget")- raise LLMCapabilityError(msg)+ raise LLMCapabilityError(msg).with_params(capability="reasoning")if is_structured:- raise LLMCapabilityError(cls._structured_output_refusal(inference_model=inference_model))+ raise LLMCapabilityError(cls._structured_output_refusal(inference_model=inference_model)).with_params(capability="structured output")@classmethoddef _structured_output_refusal(cls, *, inference_model: InferenceModelSpec) -> str:@@ -112,4 +112,4 @@ class BedrockLLMWorker(LLMWorkerAbstract):schema: type[BaseModelTypeVar],) -> BaseModelTypeVar:# Refused by check_request before this is reached. TODO: try with the newest instructor release- raise LLMCapabilityError(self._structured_output_refusal(inference_model=self.inference_model))+ raise LLMCapabilityError(self._structured_output_refusal(inference_model=self.inference_model)).with_params(capability="structured output")diff --git a/pipelex/providers/google/google_img_gen_worker.py b/pipelex/providers/google/google_img_gen_worker.pyindex 7255d13b3..9dafd1f58 100644--- a/pipelex/providers/google/google_img_gen_worker.py+++ b/pipelex/providers/google/google_img_gen_worker.py@@ -282,11 +282,12 @@ class GoogleImgGenWorker(ImgGenWorkerAbstract):cause = _IMAGE_REFUSAL_CAUSES.get(refusal_reason.upper())next_step = "Revise the image prompt or its input images."msg = f"{what_happened}: {cause}. {next_step}" if cause else f"{what_happened}. {next_step}"- raise (- ImgGenGenerationError(msg, error_category=InferenceErrorCategory.CONTENT, provider_metadata=None)- .with_error_code(CoreCode.MODEL_CONTENT_REFUSED)- .as_caller_fault(user_action=UserAction(kind=UserActionKind.CHANGE_INPUT, detail=next_step))- )+ raise ImgGenGenerationError(+ msg,+ error_category=InferenceErrorCategory.CONTENT,+ user_action=UserAction(kind=UserActionKind.CHANGE_INPUT, detail=next_step),+ provider_metadata=None,+ ).with_error_code(CoreCode.MODEL_CONTENT_REFUSED)@overrideasync def _gen_image_list(diff --git a/pipelex/providers/google/google_llm_worker.py b/pipelex/providers/google/google_llm_worker.pyindex 342420f37..1e9ea70d0 100644--- a/pipelex/providers/google/google_llm_worker.py+++ b/pipelex/providers/google/google_llm_worker.py@@ -174,7 +174,7 @@ class GoogleLLMWorker(LLMWorkerAbstract):return genai_types.ThinkingConfig(thinking_level=thinking_level)case ThinkingMode.NONE:msg = f"Model '{inference_model.desc}' does not support reasoning (thinking_mode=none)"- raise LLMCapabilityError(msg)+ raise LLMCapabilityError(msg).with_params(capability="reasoning")@classmethoddef _thinking_off_config(cls, *, inference_model: InferenceModelSpec) -> genai_types.ThinkingConfig:@@ -184,7 +184,7 @@ class GoogleLLMWorker(LLMWorkerAbstract):f"Model '{inference_model.desc}' cannot turn thinking off, so it cannot take reasoning_effort 'none': "f"set another reasoning effort, or remove the reasoning setting")- raise LLMCapabilityError(msg)+ raise LLMCapabilityError(msg).with_params(capability="turning its reasoning off")return genai_types.ThinkingConfig(thinking_budget=0)@classmethod@@ -215,7 +215,7 @@ class GoogleLLMWorker(LLMWorkerAbstract):return genai_types.ThinkingConfig(thinking_budget=budget)case ThinkingMode.NONE:msg = f"Model '{inference_model.desc}' does not support reasoning (thinking_mode=none)"- raise LLMCapabilityError(msg)+ raise LLMCapabilityError(msg).with_params(capability="reasoning")#########################################################diff --git a/pipelex/providers/mistral/mistral_llm_worker.py b/pipelex/providers/mistral/mistral_llm_worker.pyindex cdaa790c9..c5e7fb08f 100644--- a/pipelex/providers/mistral/mistral_llm_worker.py+++ b/pipelex/providers/mistral/mistral_llm_worker.py@@ -84,7 +84,7 @@ class MistralLLMWorker(LLMWorkerAbstract):f"Model '{inference_model.desc}' cannot reason on a structured output with structure method "f"'{inference_model.structure_method}': use 'instructor/mistral_tools', or remove the reasoning setting")- raise LLMCapabilityError(msg)+ raise LLMCapabilityError(msg).with_params(capability="reasoning on a structured output")@classmethoddef _instructor_mode(cls, *, inference_model: InferenceModelSpec) -> "InstructorMode":@@ -115,13 +115,13 @@ class MistralLLMWorker(LLMWorkerAbstract):match thinking_mode:case ThinkingMode.MANUAL:msg = f"Model '{inference_model.desc}' does not support reasoning_budget; Mistral uses reasoning_effort instead"- raise LLMCapabilityError(msg)+ raise LLMCapabilityError(msg).with_params(capability="a reasoning budget")case ThinkingMode.ADAPTIVE:msg = f"Model '{inference_model.desc}' has thinking_mode=adaptive which is not supported for Mistral models"- raise LLMCapabilityError(msg)+ raise LLMCapabilityError(msg).with_params(capability="adaptive reasoning through this provider's API")case ThinkingMode.NONE:msg = f"Model '{inference_model.desc}' does not support reasoning (thinking_mode=none)"- raise LLMCapabilityError(msg)+ raise LLMCapabilityError(msg).with_params(capability="reasoning")if job_params.reasoning_effort is not None:effort = job_params.reasoning_effort@@ -131,10 +131,10 @@ class MistralLLMWorker(LLMWorkerAbstract):return UNSET if mistral_effort is None else mistral_effortcase ThinkingMode.ADAPTIVE:msg = f"Model '{inference_model.desc}' has thinking_mode=adaptive which is not supported for Mistral models"- raise LLMCapabilityError(msg)+ raise LLMCapabilityError(msg).with_params(capability="adaptive reasoning through this provider's API")case ThinkingMode.NONE:msg = f"Model '{inference_model.desc}' does not support reasoning (thinking_mode=none)"- raise LLMCapabilityError(msg)+ raise LLMCapabilityError(msg).with_params(capability="reasoning")return UNSETdiff --git a/pipelex/providers/openai/openai_completions_llm_worker.py b/pipelex/providers/openai/openai_completions_llm_worker.pyindex e5670a4bc..122502bb7 100644--- a/pipelex/providers/openai/openai_completions_llm_worker.py+++ b/pipelex/providers/openai/openai_completions_llm_worker.py@@ -110,22 +110,22 @@ class OpenAICompletionsLLMWorker(LLMWorkerAbstract):return get_config().inference.llm.openai.get_reasoning_level(effort=effort)case ThinkingMode.ADAPTIVE:msg = f"Model '{inference_model.desc}' has thinking_mode=adaptive which is not supported by the OpenAI Chat Completions API"- raise LLMCapabilityError(msg)+ raise LLMCapabilityError(msg).with_params(capability="adaptive reasoning through this provider's API")case ThinkingMode.NONE:msg = f"Model '{inference_model.desc}' does not support reasoning (thinking_mode=none)"- raise LLMCapabilityError(msg)+ raise LLMCapabilityError(msg).with_params(capability="reasoning")if job_params.reasoning_budget is not None:match thinking_mode:case ThinkingMode.MANUAL:msg = f"Model '{inference_model.desc}' does not support reasoning_budget; OpenAI uses reasoning_effort instead"- raise LLMCapabilityError(msg)+ raise LLMCapabilityError(msg).with_params(capability="a reasoning budget")case ThinkingMode.ADAPTIVE:msg = f"Model '{inference_model.desc}' has thinking_mode=adaptive which is not supported by the OpenAI Chat Completions API"- raise LLMCapabilityError(msg)+ raise LLMCapabilityError(msg).with_params(capability="adaptive reasoning through this provider's API")case ThinkingMode.NONE:msg = f"Model '{inference_model.desc}' does not support reasoning (thinking_mode=none)"- raise LLMCapabilityError(msg)+ raise LLMCapabilityError(msg).with_params(capability="reasoning")return Nonediff --git a/pipelex/providers/openai/openai_responses_llm_worker.py b/pipelex/providers/openai/openai_responses_llm_worker.pyindex 8203af61e..f8f22ff34 100644--- a/pipelex/providers/openai/openai_responses_llm_worker.py+++ b/pipelex/providers/openai/openai_responses_llm_worker.py@@ -120,22 +120,22 @@ class OpenAIResponsesLLMWorker(LLMWorkerAbstract):return Reasoning(effort=openai_effort)case ThinkingMode.ADAPTIVE:msg = f"Model '{inference_model.desc}' has thinking_mode=adaptive which is not supported by the OpenAI Responses API"- raise LLMCapabilityError(msg)+ raise LLMCapabilityError(msg).with_params(capability="adaptive reasoning through this provider's API")case ThinkingMode.NONE:msg = f"Model '{inference_model.desc}' does not support reasoning (thinking_mode=none)"- raise LLMCapabilityError(msg)+ raise LLMCapabilityError(msg).with_params(capability="reasoning")if job_params.reasoning_budget is not None:match thinking_mode:case ThinkingMode.MANUAL:msg = f"Model '{inference_model.desc}' does not support reasoning_budget; OpenAI uses reasoning_effort instead"- raise LLMCapabilityError(msg)+ raise LLMCapabilityError(msg).with_params(capability="a reasoning budget")case ThinkingMode.ADAPTIVE:msg = f"Model '{inference_model.desc}' has thinking_mode=adaptive which is not supported by the OpenAI Responses API"- raise LLMCapabilityError(msg)+ raise LLMCapabilityError(msg).with_params(capability="adaptive reasoning through this provider's API")case ThinkingMode.NONE:msg = f"Model '{inference_model.desc}' does not support reasoning (thinking_mode=none)"- raise LLMCapabilityError(msg)+ raise LLMCapabilityError(msg).with_params(capability="reasoning")return Nonediff --git a/pipelex/providers/reportlab/reportlab_pdf_renderer.py b/pipelex/providers/reportlab/reportlab_pdf_renderer.pyindex ad7390441..875521596 100644--- a/pipelex/providers/reportlab/reportlab_pdf_renderer.py+++ b/pipelex/providers/reportlab/reportlab_pdf_renderer.py@@ -148,7 +148,11 @@ 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).with_error_code(PipelexErrorCode.DOCGEN_CONTENT_UNPRINTABLE).as_caller_fault() from exc+ raise (+ DocGenRenderError(msg)+ .with_error_code(PipelexErrorCode.DOCGEN_CONTENT_UNPRINTABLE)+ .with_params(reason="too_tall_for_page", element=where)+ ) from excreturn _BuiltPass(data=buffer.getvalue(), page_count=doc_template.page)@@ -217,10 +221,14 @@ 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).with_error_code(PipelexErrorCode.DOCGEN_CONTENT_UNPRINTABLE).as_caller_fault() from exc+ raise (+ DocGenRenderError(msg)+ .with_error_code(PipelexErrorCode.DOCGEN_CONTENT_UNPRINTABLE)+ .with_params(reason="image_unreadable", element=position)+ ) from excif width_px <= 0 or height_px <= 0:msg = f"The PDF engine cannot print {position}: the image is empty."- raise DocGenRenderError(msg).with_error_code(PipelexErrorCode.DOCGEN_CONTENT_UNPRINTABLE).as_caller_fault()+ raise DocGenRenderError(msg).with_error_code(PipelexErrorCode.DOCGEN_CONTENT_UNPRINTABLE).with_params(reason="image_empty", element=position)return _LoadedImage(url=url, data=data, width_px=width_px, height_px=height_px)diff --git a/pipelex/runtime_bridge/exceptions.py b/pipelex/runtime_bridge/exceptions.pyindex 4ddc84e9a..15a331bc6 100644--- a/pipelex/runtime_bridge/exceptions.py+++ b/pipelex/runtime_bridge/exceptions.py@@ -1,6 +1,7 @@-from typing import ClassVar+from typing import Any, ClassVarfrom mthds.protocol.problem.registry import CoreCode+from typing_extensions import overridefrom pipelex.base_exceptions import PipelexErrorfrom pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeDeclaration, ErrorCodeSet, InheritsCause@@ -34,14 +35,15 @@ class MissingOrchestratorError(PipelexRuntimeBridgeError):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 = True-def __init__(self, *, mode: OrchestrationMode):self.mode = modesuper().__init__(_build_missing_message(noun="orchestrator", mode=mode))_code_a_missing_direct_mode(error=self, mode=mode)+ @override+ def problem_params(self) -> dict[str, Any]:+ return _missing_mode_params(mode=self.mode)+class MissingBundleValidatorError(PipelexRuntimeBridgeError):"""Raised when no bundle validator is registered for a requested orchestration mode.@@ -58,14 +60,20 @@ class MissingBundleValidatorError(PipelexRuntimeBridgeError):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 = True-def __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)+ @override+ def problem_params(self) -> dict[str, Any]:+ return _missing_mode_params(mode=self.mode)+++def _missing_mode_params(*, mode: OrchestrationMode) -> dict[str, Any]:+ """The facts both Missing* errors give their codes: the setting and the mode, as the deployment's or the caller's choice."""+ return {"setting": "orchestration_mode", "value": mode, "capability": f"the orchestration mode '{mode}'"}+def _build_missing_message(*, noun: str, mode: OrchestrationMode) -> str:"""Generic, plugin-decoupled message shared by both Missing* errors.diff --git a/pipelex/runtime_bridge/serialization.py b/pipelex/runtime_bridge/serialization.pyindex a0761c5dd..949913c05 100644--- a/pipelex/runtime_bridge/serialization.py+++ b/pipelex/runtime_bridge/serialization.py@@ -26,9 +26,9 @@ if TYPE_CHECKING:# Pipe-execution failures an orchestrator converts into PipelexBridgeDispatchError so a host can catch a# single error type regardless of execution mode. Distributed orchestrators additionally catch their-# own workflow-level execution errors; wrapping with ``from exc`` loses no signal — the structured-# ErrorReport stays reachable via ``__cause__`` and is surfaced by-# PipelexBridgeDispatchError.to_error_report()'s cause-chain enrichment.+# own workflow-level execution errors; wrapping with ``from exc`` loses no signal — the root fault+# stays reachable via ``__cause__``, and PipelexBridgeDispatchError, which takes its cause's code,+# reports its problem.PIPE_DISPATCH_ERRORS: tuple[type[PipelexError], ...] = (PipeRunError,PipeJobError,diff --git a/pipelex/system/environment.py b/pipelex/system/environment.pyindex 16db3e36f..11abcc7fe 100644--- a/pipelex/system/environment.py+++ b/pipelex/system/environment.py@@ -66,7 +66,7 @@ def get_required_env(key: str) -> str:value = os.getenv(key)if not value:msg = f"Environment variable '{key}' is required but not set"- raise EnvVarNotFoundError(msg)+ raise EnvVarNotFoundError(msg).with_params(variable=key, source="env")return valuediff --git a/pipelex/system/job_metadata.py b/pipelex/system/job_metadata.pyindex 3214515ce..be6bb6dd7 100644--- a/pipelex/system/job_metadata.py+++ b/pipelex/system/job_metadata.py@@ -164,14 +164,14 @@ class RunMetadata(BaseModel):# The API-inbound ``X-Request-ID`` (set by the dispatcher when an external# HTTP request enters Pipelex). Rides here so it crosses the Temporal# serialization boundary — every activity / workflow can correlate logs and- # the resulting ``ErrorReport`` back to the originating request. Distinct+ # the resulting problem back to the originating request. Distinct# from :class:`pipelex.cogt.inference.error_classification.ProviderErrorMetadata.request_id`,# which is the *provider*-side request id (OpenAI ``x-request-id`` etc.) —# both can appear together when the API surfaces a provider failure.# Constrained at the wire-format boundary by `validate_request_id` (printable# ASCII only, max 128 chars) so an unsanitized upstream value cannot inject- # newlines or control characters into the log lines or ``ErrorReport``- # envelopes that quote it.+ # newlines or control characters into the log lines or the problem+ # documents that quote it.request_id: str | None = None# The opaque labels the host attaches to this run. Never read by name;diff --git a/pipelex/system/usage_stats/usage_stats_runs.py b/pipelex/system/usage_stats/usage_stats_runs.pyindex 8894d4304..720c26c23 100644--- a/pipelex/system/usage_stats/usage_stats_runs.py+++ b/pipelex/system/usage_stats/usage_stats_runs.py@@ -16,6 +16,7 @@ from contextlib import contextmanagerfrom contextvars import ContextVarfrom pipelex.base_exceptions import ErrorDomain, PipelexError+from pipelex.errors.problem import ProblemViewfrom pipelex.system.usage_stats.usage_stats_contract import UsageStatsErrorDomain, UsageStatsMethodSource#: The failure categories a `model_used` event counts, the runtime's own `InferenceErrorCategory` values.@@ -104,10 +105,14 @@ def tallying_inference_calls(*, tally: RunInferenceTally | None) -> Generator[Nodef usage_stats_error_domain(*, error: BaseException | None) -> UsageStatsErrorDomain:- """Who can fix a failure, by the runtime's own error report: `input`, `config`, `runtime`, or `other` when it cannot say."""+ """Who can fix a failure, by the domain of the runtime's own code: `input`, `config`, `runtime`, or `other` when it cannot say.++ The domain is the failure's problem's, which a cause reporting a problem of its own, such as one recovered across a+ transport boundary, decides, as every other surface reads it.+ """if not isinstance(error, PipelexError):return UsageStatsErrorDomain.OTHER- return usage_stats_error_domain_of(domain=error.to_error_report().error_domain)+ return usage_stats_error_domain_of(domain=ErrorDomain.from_problem_domain(error.to_problem(view=ProblemView.CALLER).effective_domain))def usage_stats_error_domain_of(*, domain: ErrorDomain | str | None) -> UsageStatsErrorDomain:diff --git a/pipelex/test_extras/error_report_parity.py b/pipelex/test_extras/problem_parity.pysimilarity index 70%rename from pipelex/test_extras/error_report_parity.pyrename to pipelex/test_extras/problem_parity.pyindex ef7bb5b9e..fb90fbdd4 100644--- a/pipelex/test_extras/error_report_parity.py+++ b/pipelex/test_extras/problem_parity.py@@ -1,14 +1,14 @@-"""Single source of truth for the local / Temporal ``ErrorReport`` parity contract.+"""Single source of truth for the local / Temporal problem parity contract.This module is **shipped in the open-core wheel on purpose**. The parity contract spans two-repos: open core asserts that a failing pipe surfaces a fully classified ``ErrorReport`` on the+repos: open core asserts that a failing pipe surfaces a fully classified problem on thelocal execution path, and our Temporal plugin asserts the *same*-classification survives the activity -> workflow -> submitter boundary. Both arms import the+problem survives the activity -> workflow -> submitter boundary. Both arms import thefixtures below, so the classification a failing pipe surfaces cannot silently diverge between thetwo execution paths — there is one definition, not two hand-synced copies.Shipping it from core also gives third-party orchestrator-plugin authors a ready-made fixture to-prove their own backend preserves the ``ErrorReport`` across its boundary.+prove their own backend preserves the problem across its boundary.The only genuinely per-repo bit — the ``.mthds`` bundle each repo ships to drive the failing pipe— is deliberately NOT here. Each arm subclasses these classes and adds its own ``BUNDLE_FILE``.@@ -16,16 +16,18 @@ The only genuinely per-repo bit — the ``.mthds`` bundle each repo ships to drifrom typing import ClassVar+from mthds.protocol.problem.registry import CoreCode, ProblemDomain, StepKind+from pipelex.cogt.exceptions import InferenceErrorCategory, JudgmentJobFailureError, LLMCompletionError, SearchJobFailureErrorfrom pipelex.cogt.inference.error_classification import UserAction, UserActionKind-class ErrorReportParityTestData:- """Constants + factory driving both arms of the local / Temporal ``ErrorReport`` parity test.+class ProblemParityTestData:+ """Constants + factory driving both arms of the local / Temporal problem parity test.A single deliberately-failing ``PipeLLM`` call is the source of truth for both arms: each runsthe ``native_text_sequence`` pipe with the LLM call mocked to raise ``make_failing_llm_error()``,- then asserts the resulting ``ErrorReport`` against the same ``EXPECTED_*`` classification.+ then asserts the resulting problem against the same ``EXPECTED_*`` classification."""PIPE_CODE: ClassVar[str] = "native_text_sequence"@@ -39,9 +41,14 @@ class ErrorReportParityTestData:FAILURE_CATEGORY: ClassVar[InferenceErrorCategory] = InferenceErrorCategory.CONFIGURATIONFAILURE_USER_ACTION_DETAIL: ClassVar[str] = "Verify the API key configured for this provider."- # The classification both arms must surface on the recovered ErrorReport.+ # The classification both arms must surface on the recovered problem: the code the category names, its domain, its+ # verdict and its step, and the model and the provider on the operator's diagnostics.+ EXPECTED_CODE: ClassVar[CoreCode] = CoreCode.RUNTIME_MISCONFIGURED+ EXPECTED_DOMAIN: ClassVar[ProblemDomain] = ProblemDomain.OPERATOREXPECTED_RETRYABLE: ClassVar[bool] = False- EXPECTED_USER_ACTION_KIND: ClassVar[UserActionKind] = UserActionKind.CHECK_CREDENTIALS+ EXPECTED_OPERATOR_STEP_KIND: ClassVar[StepKind] = StepKind.FIX_CONFIGURATION+ # The advice the failure carries, which a local CLI prints as its tip and no problem carries.+ FAILURE_USER_ACTION_KIND: ClassVar[UserActionKind] = UserActionKind.CHECK_CREDENTIALS@classmethoddef make_failing_llm_error(cls) -> LLMCompletionError:@@ -53,7 +60,7 @@ class ErrorReportParityTestData:error = LLMCompletionError(cls.FAILURE_MESSAGE,error_category=cls.FAILURE_CATEGORY,- user_action=UserAction(kind=cls.EXPECTED_USER_ACTION_KIND, detail=cls.FAILURE_USER_ACTION_DETAIL),+ user_action=UserAction(kind=cls.FAILURE_USER_ACTION_KIND, detail=cls.FAILURE_USER_ACTION_DETAIL),)# model_handle / backend_name are declared on CogtError; a real worker fills them# at its public-method chokepoint. This test mocks above the worker, so set them@@ -63,10 +70,10 @@ class ErrorReportParityTestData:return error-class SearchErrorReportParityTestData:- """Constants + factory driving both arms of the local / Temporal ``ErrorReport`` parity test for web search.+class SearchProblemParityTestData:+ """Constants + factory driving both arms of the local / Temporal problem parity test for web search.- The search counterpart of :class:`ErrorReportParityTestData`. A single deliberately-failing+ The search counterpart of :class:`ProblemParityTestData`. A single deliberately-failing``PipeSearch`` leaf is the source of truth for both arms: the local arm runs the ``native_search``pipe through the direct ``ContentGenerator`` with ``make_search_sourced_answer`` mocked to fail; theTemporal arm runs the same pipe through ``WfPipeRouter`` with the activity-side ``search_gen_sourced_answer``@@ -83,9 +90,14 @@ class SearchErrorReportParityTestData:FAILURE_CATEGORY: ClassVar[InferenceErrorCategory] = InferenceErrorCategory.CONFIGURATIONFAILURE_USER_ACTION_DETAIL: ClassVar[str] = "Verify the API key configured for this search provider."- # The classification both arms must surface on the recovered ErrorReport.+ # The classification both arms must surface on the recovered problem: the code the category names, its domain, its+ # verdict and its step, and the model and the provider on the operator's diagnostics.+ EXPECTED_CODE: ClassVar[CoreCode] = CoreCode.RUNTIME_MISCONFIGURED+ EXPECTED_DOMAIN: ClassVar[ProblemDomain] = ProblemDomain.OPERATOREXPECTED_RETRYABLE: ClassVar[bool] = False- EXPECTED_USER_ACTION_KIND: ClassVar[UserActionKind] = UserActionKind.CHECK_CREDENTIALS+ EXPECTED_OPERATOR_STEP_KIND: ClassVar[StepKind] = StepKind.FIX_CONFIGURATION+ # The advice the failure carries, which a local CLI prints as its tip and no problem carries.+ FAILURE_USER_ACTION_KIND: ClassVar[UserActionKind] = UserActionKind.CHECK_CREDENTIALS@classmethoddef make_failing_search_error(cls) -> SearchJobFailureError:@@ -97,7 +109,7 @@ class SearchErrorReportParityTestData:error = SearchJobFailureError(cls.FAILURE_MESSAGE,error_category=cls.FAILURE_CATEGORY,- user_action=UserAction(kind=cls.EXPECTED_USER_ACTION_KIND, detail=cls.FAILURE_USER_ACTION_DETAIL),+ user_action=UserAction(kind=cls.FAILURE_USER_ACTION_KIND, detail=cls.FAILURE_USER_ACTION_DETAIL),)# model_handle / backend_name are declared on CogtError; a real search worker fills them at its# public-method chokepoint. This test mocks above the worker, so set them directly.@@ -106,10 +118,10 @@ class SearchErrorReportParityTestData:return error-class JudgeErrorReportParityTestData:- """Constants + factory driving both arms of the local / Temporal ``ErrorReport`` parity test for judgment.+class JudgeProblemParityTestData:+ """Constants + factory driving both arms of the local / Temporal problem parity test for judgment.- The judgment counterpart of :class:`SearchErrorReportParityTestData`. A single deliberately-failing+ The judgment counterpart of :class:`SearchProblemParityTestData`. A single deliberately-failing``PipeJudge`` leaf is the source of truth for both arms: the local arm runs the ``native_judge`` pipethrough the direct ``ContentGenerator`` with ``make_judgment_answers`` mocked to fail; a distributedarm runs the same pipe with its activity-side leaf mocked to fail. Both assert the same ``EXPECTED_*``@@ -126,9 +138,14 @@ class JudgeErrorReportParityTestData:FAILURE_CATEGORY: ClassVar[InferenceErrorCategory] = InferenceErrorCategory.CONFIGURATIONFAILURE_USER_ACTION_DETAIL: ClassVar[str] = "Verify the API key configured for this judgment provider."- # The classification both arms must surface on the recovered ErrorReport.+ # The classification both arms must surface on the recovered problem: the code the category names, its domain, its+ # verdict and its step, and the model and the provider on the operator's diagnostics.+ EXPECTED_CODE: ClassVar[CoreCode] = CoreCode.RUNTIME_MISCONFIGURED+ EXPECTED_DOMAIN: ClassVar[ProblemDomain] = ProblemDomain.OPERATOREXPECTED_RETRYABLE: ClassVar[bool] = False- EXPECTED_USER_ACTION_KIND: ClassVar[UserActionKind] = UserActionKind.CHECK_CREDENTIALS+ EXPECTED_OPERATOR_STEP_KIND: ClassVar[StepKind] = StepKind.FIX_CONFIGURATION+ # The advice the failure carries, which a local CLI prints as its tip and no problem carries.+ FAILURE_USER_ACTION_KIND: ClassVar[UserActionKind] = UserActionKind.CHECK_CREDENTIALS@classmethoddef make_failing_judgment_error(cls) -> JudgmentJobFailureError:@@ -140,7 +157,7 @@ class JudgeErrorReportParityTestData:error = JudgmentJobFailureError(cls.FAILURE_MESSAGE,error_category=cls.FAILURE_CATEGORY,- user_action=UserAction(kind=cls.EXPECTED_USER_ACTION_KIND, detail=cls.FAILURE_USER_ACTION_DETAIL),+ user_action=UserAction(kind=cls.FAILURE_USER_ACTION_KIND, detail=cls.FAILURE_USER_ACTION_DETAIL),)# model_handle / backend_name are declared on CogtError; a real judgment worker fills them at its# public-method chokepoint. This test mocks above the worker, so set them directly.diff --git a/pipelex/tools/jinja2/exceptions.py b/pipelex/tools/jinja2/exceptions.pyindex f80afcb8c..c0d102e68 100644--- a/pipelex/tools/jinja2/exceptions.py+++ b/pipelex/tools/jinja2/exceptions.py@@ -74,11 +74,10 @@ class Jinja2TemplateBudgetError(ToolError):Its template repeated, padded, joined, looped or recursed past what one render may allocate or compute. On amethod's template that is the method's to fix, `pipe.template_budget_exceeded`, the default; a Pipelex templateonly 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.+ the operation and its size, never the template source or a value."""error_code = ErrorCodeSet(default=CoreCode.PIPE_TEMPLATE_BUDGET_EXCEEDED, others=(CoreCode.INPUT_TOO_LARGE,))- _authors_caller_facing_message = Trueclass Jinja2StuffError(ToolError):diff --git a/pipelex/tools/jinja2/jinja2_rendering.py b/pipelex/tools/jinja2/jinja2_rendering.pyindex 55502185f..9f0a3edda 100644--- a/pipelex/tools/jinja2/jinja2_rendering.py+++ b/pipelex/tools/jinja2/jinja2_rendering.py@@ -161,7 +161,7 @@ def _make_invalid_template_error(*, template_error: TemplateError, template_owneIts message gives Jinja2's own finding (`TemplateError.message`, which names the filter, test or template thetemplate 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.+ template it can be the ``finding`` parameter its problem shows the caller."""if isinstance(template_error, TemplateNotFound):# A template without a loader (every method template) has nothing to include or extend.@@ -171,8 +171,8 @@ def _make_invalid_template_error(*, template_error: TemplateError, template_ownemsg = 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()+ # The fault names the construct Jinja2 refused and never the source, so the method's author reads it as the finding.+ invalid_error.with_params(finding=fault)return invalid_errordiff --git a/pipelex/tools/misc/exceptions.py b/pipelex/tools/misc/exceptions.pyindex 997c6b641..676fb0399 100644--- a/pipelex/tools/misc/exceptions.py+++ b/pipelex/tools/misc/exceptions.py@@ -1,7 +1,8 @@-from typing import ClassVar, Self+from typing import Any, ClassVar, Selfimport tomlifrom mthds.protocol.problem.registry import CoreCode+from typing_extensions import overridefrom pipelex.cogt.inference.error_classification import UserAction, UserActionKindfrom pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeDeclaration, ErrorCodeSet@@ -63,6 +64,11 @@ class TomlError(ToolError):self.lineno = linenoself.colno = colno+ @override+ def problem_params(self) -> dict[str, Any]:+ # The parser's own words, which name a position in the document and never its text.+ return {"reason": self.message, "finding": self.message, "line": self.lineno, "column": self.colno}+@classmethoddef from_tomli_error(cls, exc: tomli.TOMLDecodeError) -> Self:return cls(message=exc.msg, doc=exc.doc, pos=exc.pos, lineno=exc.lineno, colno=exc.colno)@@ -72,9 +78,10 @@ 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 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 message names the URL and what+ the server or the network said (an HTTP status, a refused connection, a timeout), and never+ a resolved address; it reaches the operator's diagnostics, the caller reading the sentence+ its code renders.A server that answered but would not serve the file is ``input.file_unreadable`` (thedefault); a timeout or a refused connection, which a retry may get past, is@@ -86,7 +93,6 @@ class RemoteFileFetchError(ToolError):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.",diff --git a/pipelex/tools/network/exceptions.py b/pipelex/tools/network/exceptions.pyindex 5058d192f..566b88eb5 100644--- a/pipelex/tools/network/exceptions.py+++ b/pipelex/tools/network/exceptions.py@@ -29,15 +29,13 @@ class SsrfBlockedError(SecurityError):and the caller fixes it by providing a public URL. A raise or catch site thatknows the method named the URL chooses ``security.method_url_refused``, and onethat knows a provider's answer named it ``security.provider_url_refused``.- ``_authors_caller_facing_message`` lets the message survive STRICT- disclosure — it deliberately names only the requested hostname, never the- resolved private IP, so it never reveals an internal address to a probing- client. That a name resolves to a private address at all stays observable,- since the refusal is told apart from a host that cannot be reached.+ The message deliberately names only the requested hostname, never the+ resolved private IP, so it never reveals an internal address. That a name+ resolves to a private address at all stays observable, since the refusal is+ told apart from a host that cannot be reached."""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/secrets/env_secrets_provider.py b/pipelex/tools/secrets/env_secrets_provider.pyindex 3e9e47712..283f4e33e 100644--- a/pipelex/tools/secrets/env_secrets_provider.py+++ b/pipelex/tools/secrets/env_secrets_provider.py@@ -13,7 +13,7 @@ class EnvSecretsProvider(SecretsProviderAbstract):return get_required_env(key=secret_id)except EnvVarNotFoundError as exc:msg = f"Secret '{secret_id}' not found"- raise SecretNotFoundError(msg) from exc+ raise SecretNotFoundError(msg).with_params(variable=secret_id, source="env") from exc@overridedef get_optional_secret(self, secret_id: str) -> str | None:diff --git a/pipelex/tools/secrets/secrets_utils.py b/pipelex/tools/secrets/secrets_utils.pyindex cd0acc4d6..4be3080a7 100644--- a/pipelex/tools/secrets/secrets_utils.py+++ b/pipelex/tools/secrets/secrets_utils.py@@ -168,7 +168,7 @@ def _get_env_var(var_name: str) -> str:return get_required_env(var_name)except EnvVarNotFoundError as exc:msg = f"Could not get variable '{var_name}': {exc!s}"- raise VarNotFoundError(message=msg, var_name=var_name) from exc+ raise VarNotFoundError(message=msg, var_name=var_name).with_params(variable=var_name, source="env") from excdef _get_secret(secret_name: str, *, secrets_provider: SecretsProviderAbstract) -> str:@@ -177,4 +177,4 @@ def _get_secret(secret_name: str, *, secrets_provider: SecretsProviderAbstract)return secrets_provider.get_secret(secret_id=secret_name)except SecretNotFoundError as exc:msg = f"Could not get variable '{secret_name}': {exc!s}"- raise VarNotFoundError(message=msg, var_name=secret_name) from exc+ raise VarNotFoundError(message=msg, var_name=secret_name).with_params(variable=secret_name, source="secret") from excdiff --git a/pipelex/tools/tabular/csv_codec.py b/pipelex/tools/tabular/csv_codec.pyindex e44d4cf88..cae7df839 100644--- a/pipelex/tools/tabular/csv_codec.py+++ b/pipelex/tools/tabular/csv_codec.py@@ -375,8 +375,8 @@ def list_content_from_csv(error_fields = sorted({_validation_error_label(error) for error in exc.errors()})fields_label = ", ".join(error_fields) or "?"# Use pydantic's per-error `msg` (e.g. "Input should be a valid integer"), NOT str(exc):- # str(exc) appends `input_value=<raw cell>`, which would leak the cell content into this- # caller-facing message (CsvError survives STRICT disclosure). Row/field identifiers suffice.+ # str(exc) appends `input_value=<raw cell>`, which would put the cell content, a run's input, into+ # the operator's diagnostics and every log line carrying the message. Row/field identifiers suffice.reasons = "; ".join(sorted({str(error.get("msg", "")) for error in exc.errors()})) or "invalid value"msg = f"Could not coerce CSV row {row_number} of {path} for concept {row_model.__name__!r}: field(s) {fields_label} — {reasons}"raise CsvCoercionError(msg) from excdiff --git a/pipelex/tools/tabular/exceptions.py b/pipelex/tools/tabular/exceptions.pyindex 6e827e5e8..3f975520d 100644--- a/pipelex/tools/tabular/exceptions.py+++ b/pipelex/tools/tabular/exceptions.py@@ -19,10 +19,6 @@ class CsvError(ToolError):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.- _authors_caller_facing_message = Trueclass CsvReadError(CsvError):diff --git a/pipelex/tools/uri/exceptions.py b/pipelex/tools/uri/exceptions.pyindex 669bd7fbd..9781edebb 100644--- a/pipelex/tools/uri/exceptions.py+++ b/pipelex/tools/uri/exceptions.py@@ -1,6 +1,8 @@from enum import StrEnum+from typing import Anyfrom mthds.protocol.problem.registry import CoreCode+from typing_extensions import overridefrom pipelex.base_exceptions import SecurityErrorfrom pipelex.errors.error_code_declaration import ErrorCodeSet@@ -20,6 +22,15 @@ class UriReadRefusalReason(StrEnum):case UriReadRefusalReason.LOCAL_PATH:return "it names a file on the server's own disk, or a URL in a scheme this runtime does not read, and a hosted run reads neither"+ @property+ def target_class(self) -> str:+ """The kind of target the refused URL points at, as the refusal's sentence names it."""+ match self:+ case UriReadRefusalReason.FOREIGN_STORAGE_KEY:+ return "foreign storage"+ case UriReadRefusalReason.LOCAL_PATH:+ return "local"+class UriReadRefusedError(SecurityError):"""Raised when a run asks to read a URL outside what its host lets it read.@@ -33,16 +44,18 @@ class UriReadRefusedError(SecurityError):A :class:`SecurityError`, so that a domain-level ``except`` around a read cannot swallow it.The default is ``security.input_url_refused``, answered as a 422: an input asked for the readand 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 is- caller-facing and keeps its text under STRICT disclosure: it names where the URL sat (an- image of a pipe's prompt, an input) and why it was refused, and quotes neither the URL nor the- read scope. The refusal happens before any IO, so it says nothing about whether the file+ knows the method named the URL chooses ``security.method_url_refused``. The message names+ where the URL sat (an image of a pipe's prompt, an input) and why it was refused, and quotes+ neither the URL nor the read scope. The refusal happens before any IO, so it says nothing about whether the fileexists."""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):super().__init__(message)self.reason = reason++ @override+ def problem_params(self) -> dict[str, Any]:+ return {"reason": self.reason.desc, "target_class": self.reason.target_class}diff --git a/pipelex/tracing/graphspec_assembler.py b/pipelex/tracing/graphspec_assembler.pyindex 4e688bee5..79e1676ea 100644--- a/pipelex/tracing/graphspec_assembler.py+++ b/pipelex/tracing/graphspec_assembler.py@@ -15,14 +15,13 @@ one its latest attempt ran, and never a failed node beside a succeeded one.from collections.abc import Sequencefrom datetime import UTC, datetime-from typing import Any+from typing import TYPE_CHECKING, Anyfrom pipelex import logfrom pipelex.graph.condition_output_merge import ConditionOutputMerge, apply_condition_output_mergesfrom pipelex.graph.graphspec import (EdgeKind,EdgeSpec,- ErrorSpec,GraphSpec,GraphSpecMode,GraphUsageSpec,@@ -60,6 +59,9 @@ from pipelex.tracing.trace_events import ()from pipelex.tracing.usage_attribution import NodeUsages, attribute_usage, make_self_contained_spec+if TYPE_CHECKING:+ from pipelex.errors.problem import PipelexProblem+class _AssemblerNodeData:"""Internal mutable data structure for building a node from events.@@ -94,7 +96,8 @@ class _AssemblerNodeData:self.skip_reason: str | None = Noneself.metrics: dict[str, float] = {}self.usage_spec: NodeUsageSpec | None = None- self.error: ErrorSpec | None = None+ self.error: PipelexProblem | None = None+ self.error_stack: str | None = Noneself.input_specs: list[IOSpec] = input_specs or []self.output_specs: list[IOSpec] = []self.execution_data: dict[str, Any] = {}@@ -126,6 +129,7 @@ class _AssemblerNodeData:timing=timing,node_io=node_io,error=self.error,+ error_stack=self.error_stack,metrics=self.metrics,usage=self.usage_spec,execution_data=self.execution_data,@@ -400,6 +404,7 @@ class _AssemblerState:node_data.ended_at = event.ended_atnode_data.status = NodeStatus.FAILEDnode_data.error = event.error+ node_data.error_stack = event.error_stackdef _handle_pipe_end_skipped(self, event: PipeEndSkippedEvent) -> None:node_data = self._nodes.get(event.node_id)diff --git a/pipelex/tracing/trace_events.py b/pipelex/tracing/trace_events.pyindex cf447a3e4..7e1f302b2 100644--- a/pipelex/tracing/trace_events.py+++ b/pipelex/tracing/trace_events.py@@ -11,11 +11,12 @@ from enum import StrEnumfrom functools import cached_propertyfrom typing import Annotated, Any, Literal, Self-from pydantic import BaseModel, ConfigDict, Field, ValidationError+from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validatorfrom typing_extensions import override+from pipelex.errors.problem import PipelexProblemfrom pipelex.graph.condition_output_merge import ConditionOutputMerge-from pipelex.graph.graphspec import EdgeKind, ErrorSpec, IOSpec, NodeKind+from pipelex.graph.graphspec import EdgeKind, IOSpec, NodeKind, cap_error_stackfrom pipelex.reporting.reporting_types import AnyTokensUsagefrom pipelex.system.execution_chain import ExecutionAttempt, execution_chain_keyfrom pipelex.system.pipe_run_mode import PipeRunMode@@ -168,8 +169,9 @@ class PipeEndSuccessEvent(TraceEvent):class PipeEndErrorEvent(TraceEvent):"""Emitted when a pipe fails.- Its `error` gives the progress contract's `failure`: `message`, and `caller_facing`, true when that message was- written for the caller.+ Its `error` is the problem that ended the pipe, in the caller's view, located at the pipe; `error_stack` is the+ stack trace of the error, when the graph's data inclusion asks for it, capped as the graph's node caps it, since+ the event reaches every trace subscriber before any node is built from it."""event_kind: Literal[TraceEventKind.PIPE_END_ERROR] = TraceEventKind.PIPE_END_ERROR@@ -178,7 +180,13 @@ class PipeEndErrorEvent(TraceEvent):pipe_ref: str | Nonepipe_type: strended_at: datetime- error: ErrorSpec+ error: PipelexProblem+ error_stack: str | None = None++ @field_validator("error_stack", mode="after")+ @classmethod+ def cap_stack(cls, value: str | None) -> str | None:+ return cap_error_stack(stack=value)class PipeEndSkippedEvent(TraceEvent):@@ -298,7 +306,7 @@ class ConditionResolvedEvent(TraceEvent):"""The PipeCondition's own node."""rendered_value: str"""The value the condition's expression rendered. It may quote text of the method, or of a library the method- depends on, so it is kept for whoever reads the trace and never reaches a caller-facing summary."""+ depends on, so it is kept for whoever reads the trace and never reaches a problem's parameters."""selected_outcome: str | None"""The key of the outcome map the rendered value matched, or None when it matched none and the condition took itsdefault outcome: `"default"` can itself be a key of an outcome map, so it cannot stand for the default."""diff --git a/subject_grants.toml b/subject_grants.tomlindex 91a4d7a24..8b6320fba 100644--- a/subject_grants.toml+++ b/subject_grants.toml@@ -4,34 +4,22 @@ version = 1param = "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."--["pipelex/base_exceptions.py::PipelexError._enrich_error_report_from_cause"]-param = "report"-rationale = "Verb-object: enriches the report; 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"-rationale = "Transforms the metadata payload; single operand."-["pipelex/base_exceptions.py::error_domain_is_input"]param = "error_domain"rationale = "Predicate on the error domain; single operand."-["pipelex/base_exceptions.py::error_domain_to_http_status"]-param = "error_domain"-rationale = "Conversion: maps the error domain to a status; single operand."-["pipelex/base_exceptions.py::iter_cause_chain"]param = "exc"rationale = "Verb-object: iterates the exception's cause chain; single operand."+["pipelex/base_exceptions.py::iter_pipelex_cause_chain"]+param = "exc"+rationale = "Verb-object: iterates the Pipelex part of the exception's cause chain; single operand, as iter_cause_chain."+["pipelex/cli/agent_cli/commands/agent_output.py::_agent_error_json"]param = "message"rationale = "Builds the error JSON around the message; single operand."diff --git a/tests/data/errors/error_identity.txt b/tests/data/errors/error_identity.txtindex da981ea16..f0931ce9e 100644--- a/tests/data/errors/error_identity.txt+++ b/tests/data/errors/error_identity.txt@@ -92,7 +92,7 @@ DuplicateSecretsProviderError | pipelex.plugin.conflictDuplicateServiceErrorCodeError | pipelex.plugin.conflictDuplicateStorageProviderError | pipelex.plugin.conflictEmptyMethodTreeError | method.invalid-EntryPipeAmbiguousError | one of request.pipe_ambiguous, method.pipe_unresolved+EntryPipeAmbiguousError | one of request.pipe_ambiguous, request.pipe_unspecified, method.ref_ambiguousEntryPipeNotFoundError | one of request.pipe_not_found, request.pipe_unspecified, method.pipe_unresolvedEnvVarNotFoundError | pipelex.config.variable_missingErrorRegistryError | runtime.unexpected@@ -197,7 +197,7 @@ MarkdownFormattingBudgetError | input.too_largeMarkdownParserDependencyError | pipelex.config.dependency_missingMethodDependencyFetchError | method.dependency_missingMethodDependencyNotShippedError | 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+MethodEntryError | one of request.pipe_unspecified, method.ref_ambiguous, request.pipe_ambiguous, request.pipe_not_found, method.pipe_unresolved, method.package_invalid, method.syntax, method.invalidMethodFetchDisabledError | method.dependency_missingMethodFetchError | one of method.fetch_failed, pipelex.config.dependency_missing, method.not_found, method.package_invalidMethodFileUnavailableError | one of runtime.unexpected, method.resource_missingdiff --git a/tests/data/errors/foreign_raises.txt b/tests/data/errors/foreign_raises.txtindex 5ae991f65..d106ba666 100644--- a/tests/data/errors/foreign_raises.txt+++ b/tests/data/errors/foreign_raises.txt@@ -15,6 +15,7 @@## 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/openapi_schema.py | name_shared_fix_schemas | ValueError | invariantapi/pipelex_api/schemas/models.py | _ensure_mthds_file_within_bytes_limit | ValueError | validatorpipelex/base_exceptions.py | PipelexError.__init_subclass__ | TypeError | invariantpipelex/base_exceptions.py | PipelexError.with_error_code | ValueError | invariantdiff --git a/tests/e2e/pipelex/pipes/optionals/test_guarded_condition_mthds.py b/tests/e2e/pipelex/pipes/optionals/test_guarded_condition_mthds.pyindex b899cb8bf..e2fa0eb86 100644--- a/tests/e2e/pipelex/pipes/optionals/test_guarded_condition_mthds.py+++ b/tests/e2e/pipelex/pipes/optionals/test_guarded_condition_mthds.py@@ -64,7 +64,7 @@ class TestGuardedConditionExpression:# The load-time guard lint (OPTIONAL_INPUT_UNGUARDED) is raised inside a pydantic validator, and# the run refuses the bundle with the verdict validating it gives: its item names the lint, so# the missing-function error (the wrong reason this control used to pass for) cannot pass it.- items = exc_info.value.to_error_report().validation_errors or []+ items = exc_info.value.validation_error_items() or []unguarded_items = [item for item in items if item.error_type == PipeValidationErrorType.OPTIONAL_INPUT_UNGUARDED]assert unguarded_items, f"expected an optional_input_unguarded item, got {items!r}"assert "'flag'" in unguarded_items[0].messagediff --git a/tests/e2e/test_signature_validation_mthds.py b/tests/e2e/test_signature_validation_mthds.pyindex 8134ae33b..65633dece 100644--- a/tests/e2e/test_signature_validation_mthds.py+++ b/tests/e2e/test_signature_validation_mthds.py@@ -5,6 +5,7 @@ from pathlib import Pathimport pytestfrom pipelex.core.stuffs.text_content import TextContent+from pipelex.errors.problem import ProblemViewfrom pipelex.pipe_run.located_failure import find_root_faultfrom pipelex.pipe_signature.exceptions import PipeSignatureNotExecutableErrorfrom pipelex.pipeline.bundle_validator import DryRunStatus@@ -89,4 +90,6 @@ class TestSignatureValidationE2E:root_fault = find_root_fault(error=exc_info.value)assert isinstance(root_fault, PipeSignatureNotExecutableError)assert root_fault.pipe_ref.endswith("summarize_doc")- assert exc_info.value.to_error_report().error_type == "PipeSignatureNotExecutableError"+ diagnostics = exc_info.value.to_problem(view=ProblemView.OPERATOR).diagnostics+ assert diagnostics is not None+ assert diagnostics.error_class == "PipeSignatureNotExecutableError"diff --git a/tests/helpers/error_report.py b/tests/helpers/error_report.pydeleted file mode 100644index 62cc31cfe..000000000--- a/tests/helpers/error_report.py+++ /dev/null@@ -1,55 +0,0 @@-"""Test helper for building ``ErrorReport`` instances with sensible defaults.--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 annotations--from typing import TYPE_CHECKING--from mthds.protocol.problem.registry import CoreCode--from pipelex.base_exceptions import ErrorReport--if TYPE_CHECKING:- from pipelex.cogt.inference.error_classification import ProviderErrorMetadata, UserAction--_DEFAULT_TITLE = "Test error"-_DEFAULT_TYPE_URI = "https://test.pipelex.dev/errors/test-error/"---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,- error_domain: str | None = None,- retryable: bool | None = None,- user_action: UserAction | None = None,- model: str | None = None,- provider: str | None = None,- provider_metadata: ProviderErrorMetadata | None = None,-) -> ErrorReport:- """Build an ``ErrorReport`` with test-friendly defaults for ``code`` / ``title`` / ``type_uri``."""- return ErrorReport(- code=code,- error_type=error_type,- message=message,- title=title,- type_uri=type_uri,- error_category=error_category,- error_domain=error_domain,- retryable=retryable,- user_action=user_action,- model=model,- provider=provider,- provider_metadata=provider_metadata,- )diff --git a/tests/helpers/recovered_problem.py b/tests/helpers/recovered_problem.pynew file mode 100644index 000000000..af02594af--- /dev/null+++ b/tests/helpers/recovered_problem.py@@ -0,0 +1,35 @@+"""An error carrying a problem recovered across a transport boundary, as a distributed submitter raises one.++Its class declares the catch-all code, as a host plugin's carrier does, while the problem it reports carries the code the+far side found: a surface that reads the class's code instead of the problem's tells the two apart, which is what the+tests using it check.+"""++from typing import ClassVar++from mthds.protocol.problem.registry import CoreCode+from typing_extensions import override++from pipelex.base_exceptions import PipelexError+from pipelex.errors.error_code_declaration import ErrorCodeDeclaration+from pipelex.errors.problem import PipelexProblem, ProblemView, make_problem+++class RecoveredProblemError(PipelexError):+ """Carries a problem in the operator's view, which its `to_problem` reports projected to the view asked for."""++ error_code: ClassVar[ErrorCodeDeclaration] = CoreCode.RUNTIME_UNEXPECTED++ def __init__(self, message: str, *, problem: PipelexProblem):+ super().__init__(message)+ self.carried_problem = problem++ @override+ def recovered_problem(self) -> PipelexProblem | None:+ return self.carried_problem+++def make_recovered_url_refusal() -> RecoveredProblemError:+ """A recovered refusal of an input URL: an `input` problem a retry can clear, unlike the carrier's own code."""+ problem = make_problem(code=CoreCode.INPUT_URL_UNREACHABLE, view=ProblemView.OPERATOR, params={"input": "document", "host": "example.com"})+ return RecoveredProblemError("a worker could not reach the document's URL", problem=problem)diff --git a/tests/integration/pipelex/cli/agent_cli/test_run_error_chain.py b/tests/integration/pipelex/cli/agent_cli/test_run_error_chain.pyindex d9fa0812f..fd9ef9eb8 100644--- a/tests/integration/pipelex/cli/agent_cli/test_run_error_chain.py+++ b/tests/integration/pipelex/cli/agent_cli/test_run_error_chain.py@@ -25,6 +25,7 @@ from pipelex.cli.agent_cli.commands.run.pipe_cmd import run_pipe_cmdfrom pipelex.cli.agent_cli.commands.run.stdin_resolver import ParsedCliInputsfrom pipelex.cogt.content_generation.content_generator import ContentGeneratorfrom pipelex.cogt.exceptions import InferenceErrorCategory, LLMCompletionError+from pipelex.cogt.inference.error_classification import UserAction, UserActionKindif TYPE_CHECKING:from pytest_mock import MockerFixture@@ -34,6 +35,7 @@ ERROR_CHAIN_LIBRARY_DIR = Path("tests/integration/pipelex/cli/agent_cli")WORKER_ERROR_MESSAGE = "LLM provider connection reset"WORKER_MODEL = "gpt-4o-mini"WORKER_PROVIDER = "openai"+WORKER_ADVICE = "Wait a moment and retry"class TestRunErrorChain:@@ -48,7 +50,12 @@ class TestRunErrorChain:mocker.patch(f"{RUN_PIPE_MODULE}.resolve_pipe_from_exports", return_value=[])mocker.patch(f"{RUN_PIPE_MODULE}.parse_cli_inputs", return_value=ParsedCliInputs(pipeline_inputs=None, inputs_base_dir=None))- transient_error = LLMCompletionError(WORKER_ERROR_MESSAGE, error_category=InferenceErrorCategory.TRANSIENT)+ # The advice a worker's classification attaches to a transient failure, which every wrapper lets through as the hint.+ transient_error = LLMCompletionError(+ WORKER_ERROR_MESSAGE,+ error_category=InferenceErrorCategory.TRANSIENT,+ user_action=UserAction(kind=UserActionKind.WAIT_AND_RETRY, detail=WORKER_ADVICE),+ )# model_handle / backend_name are declared on CogtError; a real worker fills them at# its public-method chokepoint. This test mocks above the worker, so set them directly.transient_error.model_handle = WORKER_MODEL@@ -83,6 +90,7 @@ class TestRunErrorChain:# LLMCompletionError and must survive every wrapping layer.assert payload["error_category"] == "transient"assert payload["retryable"] is True+ assert payload["hint"] == WORKER_ADVICEassert payload["error_domain"] == "runtime"assert payload["model"] == WORKER_MODELassert payload["provider"] == WORKER_PROVIDER@@ -124,6 +132,7 @@ class TestRunErrorChain:assert markdown.startswith("# Error: PipelineExecutionError")assert WORKER_ERROR_MESSAGE in markdownassert "💡" in markdown # hint callout+ assert WORKER_ADVICE in markdownassert "error_category" in markdownassert "transient" in markdown# The whole stack-trace section is gone. The stack-frame format fromdiff --git a/tests/integration/pipelex/cli/test_agent_validate_pipe_in_bundle.py b/tests/integration/pipelex/cli/test_agent_validate_pipe_in_bundle.pyindex af070d024..e67e4e5a2 100644--- a/tests/integration/pipelex/cli/test_agent_validate_pipe_in_bundle.py+++ b/tests/integration/pipelex/cli/test_agent_validate_pipe_in_bundle.py@@ -6,12 +6,14 @@ from pathlib import Pathfrom typing import TYPE_CHECKINGimport pytest+from mthds.protocol.problem.registry import CoreCode, ProblemDomain-from pipelex.base_exceptions import INTERNAL_ERROR_PLACEHOLDER, DisclosureMode, ErrorDomainfrom pipelex.cli.agent_cli.commands.validate._validate_core import (validate_bundle_core,validate_pipe_in_bundle_core,)+from pipelex.errors.error_codes import error_code_spec+from pipelex.errors.problem import ProblemViewfrom pipelex.libraries.pipe.exceptions import EntryPipeNotFoundErrorif TYPE_CHECKING:@@ -182,8 +184,8 @@ class TestAgentValidatePipeInBundle:) -> None:# Selecting a pipe that is not defined in the bundle is an error, not a vacuous success. The# `--pipe` / `pipe_ref` selector is entry-shaped input the caller typed, so the miss must be- # the INPUT-domained EntryPipeNotFoundError — not the undomained base, which every- # presentation would render as a 500 server fault for a mistake only the caller can fix.+ # the input-domained EntryPipeNotFoundError — not the method's in-body miss, nor a server fault,+ # for a mistake only the caller can fix.with pytest.raises(EntryPipeNotFoundError) as exc_info:asyncio.run(validate_pipe_in_bundle_core(@@ -192,20 +194,17 @@ class TestAgentValidatePipeInBundle:library_dirs=[implemented_plus_signature_dir],))- report = exc_info.value.to_error_report()- assert report.error_domain == ErrorDomain.INPUT- assert report.http_status == 422- # The raise site keeps its own bundle-scoped wording, which names the caller's own code.- assert "does_not_exist" in report.message- # `to_error_report()` never redacts, so the assertion above cannot prove the class-level- # `_authors_caller_facing_message` invariant this raise site inherits. Project through the- # STRICT serialization — the untrusted-surface one — where a message that is NOT declared- # caller-facing is replaced by the placeholder. This is what pins the promise the class- # docstring makes of every raise site: the wording may name what the caller typed, so it- # survives verbatim, and nothing from the loaded library rides along with it.- strict_payload = report.to_dict(disclosure_mode=DisclosureMode.STRICT)- assert strict_payload["message"] != INTERNAL_ERROR_PLACEHOLDER- assert "does_not_exist" in strict_payload["message"]+ caller = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert caller.code == CoreCode.REQUEST_PIPE_NOT_FOUND+ assert caller.domain == ProblemDomain.INPUT+ assert error_code_spec(CoreCode.REQUEST_PIPE_NOT_FOUND).status == 422+ # The caller reads the code's sentence, which names the code it typed and nothing from the loaded library.+ assert caller.detail == "The method declares no pipe 'does_not_exist'."+ assert caller.diagnostics is None+ # The raise site keeps its own bundle-scoped wording, which the operator reads.+ operator = exc_info.value.to_problem(view=ProblemView.OPERATOR)+ assert operator.diagnostics is not None+ assert "does_not_exist" in operator.diagnostics.messagedef test_pipe_slice_cross_package_controller_reports_skipped_not_success(self,diff --git a/tests/integration/pipelex/cli/test_validate_parallel_multiplicity_next_step.py b/tests/integration/pipelex/cli/test_validate_parallel_multiplicity_next_step.pyindex a5bd12e34..683873807 100644--- a/tests/integration/pipelex/cli/test_validate_parallel_multiplicity_next_step.py+++ b/tests/integration/pipelex/cli/test_validate_parallel_multiplicity_next_step.py@@ -1,9 +1,11 @@-"""Pin: a `PipeParallel` whose branch and field differ in multiplicity is refused with its next step.+"""Pin: a `PipeParallel` whose branch and field differ in multiplicity is refused as the method's fault, located at the parallel.The combine of the branch results is the existing check, reached in the dry run of validate; it stays as-it is. What these tests pin is what the refusal carries: the branch, the result, the field and which of-the two multiplicities to change, on ``pipelex validate bundle`` and in ``pipelex-agent validate bundle``'s-JSON, and a top-level next step that sends the reader to the items instead of to "the array".+it is. What these tests pin is what the verdict carries for the caller: one item coded+``pipe.output_multiplicity``, rendered from the result, the declared and the produced multiplicities, on+``pipelex validate bundle`` and in ``pipelex-agent validate bundle``'s JSON, and a top-level next step that+sends the reader to the items instead of to "the array". The combine's own restatement, which names the+branch to change, is the operator's: no caller reads it."""from __future__ import annotations@@ -14,11 +16,13 @@ from typing import TYPE_CHECKINGimport pytestimport typer+from mthds.protocol.problem.registry import CoreCode, StepKindfrom rich.console import Consolefrom pipelex.cli.agent_cli.commands.agent_output import CliOutputFormat, set_agent_cli_error_formatfrom pipelex.cli.agent_cli.commands.validate.bundle_cmd import validate_bundle_cmd as agent_validate_bundle_cmdfrom pipelex.cli.commands.validate._validate_core import _validate_pipe_or_bundle # pyright: ignore[reportPrivateUsage]+from pipelex.errors.problem import PipelexProblem, ProblemViewfrom pipelex.pipeline.exceptions import ValidateBundleErrorfrom pipelex.pipeline.validate_bundle import validate_bundle@@ -132,21 +136,15 @@ template = "One idea.""""# The list comes from the branch itself: `draft_idea` declares one `Idea`, but the branch batches it over-# the topics, so the next step names that branch setting rather than the pipe's declared output.+# the topics, so the parallel receives a list for its single field all the same._BATCHED_BRANCH_INTO_SINGLE_FIELD = _LIST_BRANCH_INTO_SINGLE_FIELD.replace('{ pipe = "draft_ideas", result = "ideas" }','{ pipe = "draft_idea", result = "ideas", batch_over = "topics", batch_as = "topic" }',)-_BATCHED_INTO_SINGLE_NEXT_STEP = (- "Branch 'draft_idea' gives result 'ideas' as a list, 'Idea[]', but field 'ideas' of 'TopicReview' holds a single item. "- "Declare the field as a list in the structure of 'TopicReview', with type 'list', item_type 'concept' and item_concept_ref 'Idea', "- "or change the nb_output, multiple_output or batch_over that branch 'draft_idea' sets in the parallel's branches."-)-# Two faults in one combine: the ideas are a multiplicity mismatch, while the overview field receives a-# list of `Idea`, a concept that does not fit `Overview` whatever its multiplicity. Only the first gets a-# multiplicity next step, and the combine's own report is kept for the second.+# list of `Idea`, a concept that does not fit `Overview` whatever its multiplicity. Only the first is a+# multiplicity fault, which the verdict's item reports._TWO_FAULTS_IN_ONE_COMBINE = _LIST_BRANCH_INTO_SINGLE_FIELD.replace('{ pipe = "write_overview", result = "overview" }','{ pipe = "draft_ideas", result = "overview" }',@@ -154,7 +152,7 @@ _TWO_FAULTS_IN_ONE_COMBINE = _LIST_BRANCH_INTO_SINGLE_FIELD.replace(# No advice where a multiplicity change would not make the branch fit: a single `Text` into a list of# plain strings, whose items are not concept contents, and an `Anything[]` branch, whose concept has no-# structure class to compare. The combine's own refusal reaches the verdict instead.+# structure class to compare. The verdict's item reports an output that does not fit its concept instead._TEXT_INTO_PRIMITIVE_LIST_FIELD = _SINGLE_BRANCH_INTO_LIST_FIELD.replace('ideas = { type = "list", item_type = "concept", item_concept_ref = "Idea", description = "The ideas", required = true }','ideas = { type = "list", item_type = "text", description = "The ideas", required = true }',@@ -162,17 +160,9 @@ _TEXT_INTO_PRIMITIVE_LIST_FIELD = _SINGLE_BRANCH_INTO_LIST_FIELD.replace(_ANYTHING_LIST_INTO_SINGLE_FIELD = _LIST_BRANCH_INTO_SINGLE_FIELD.replace('output = "Idea[]"', 'output = "Anything[]"')-_LIST_INTO_SINGLE_NEXT_STEP = (- "Branch 'draft_ideas' gives result 'ideas' as a list, 'Idea[]', but field 'ideas' of 'TopicReview' holds a single item. "- "Declare the field as a list in the structure of 'TopicReview', with type 'list', item_type 'concept' and item_concept_ref 'Idea', "- "or make branch 'draft_ideas' output a single 'Idea'."-)+_LIST_INTO_SINGLE_SENTENCE = "Pipe 'analyze_topics' produced an output of the multiplicity 'list', but its output 'ideas' is declared 'single'."-_SINGLE_INTO_LIST_NEXT_STEP = (- "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[]'."-)+_SINGLE_INTO_LIST_SENTENCE = "Pipe 'analyze_topic' produced an output of the multiplicity 'single', but its output 'ideas' is declared 'list'."_TOP_LEVEL_NEXT_STEP = "Edit the bundle as each validation error says"@@ -191,18 +181,25 @@ def console(mocker: MockerFixture) -> Console:return recorded_console+def _verdict_problem(*, bundle_path: Path) -> PipelexProblem:+ """The caller's view of the invalid verdict validate gives the bundle."""+ with pytest.raises(ValidateBundleError) as raised:+ asyncio.run(validate_bundle(mthds_file_path=bundle_path, library_dirs=[bundle_path.parent]))+ return raised.value.to_problem(view=ProblemView.CALLER)++class TestValidateParallelMultiplicityNextStep:@pytest.mark.parametrize(- ("bundle_content", "expected_next_step"),+ ("bundle_content", "expected_item"),[- (_LIST_BRANCH_INTO_SINGLE_FIELD, _LIST_INTO_SINGLE_NEXT_STEP),- (_SINGLE_BRANCH_INTO_LIST_FIELD, _SINGLE_INTO_LIST_NEXT_STEP),- (_BATCHED_BRANCH_INTO_SINGLE_FIELD, _BATCHED_INTO_SINGLE_NEXT_STEP),+ (_LIST_BRANCH_INTO_SINGLE_FIELD, f"Pipe 'analyze_topics' failed its dry run: {_LIST_INTO_SINGLE_SENTENCE}"),+ (_SINGLE_BRANCH_INTO_LIST_FIELD, f"Pipe 'analyze_topic' failed its dry run: {_SINGLE_INTO_LIST_SENTENCE}"),+ (_BATCHED_BRANCH_INTO_SINGLE_FIELD, f"Pipe 'analyze_topics' failed its dry run: {_LIST_INTO_SINGLE_SENTENCE}"),],ids=["list_branch_into_single_field", "single_branch_into_list_field", "batched_branch_into_single_field"],)def test_bare_validate_bundle_names_the_multiplicity_to_change(- self, console: Console, tmp_path: Path, bundle_content: str, expected_next_step: str+ self, console: Console, tmp_path: Path, bundle_content: str, expected_item: str) -> None:bundle_path = _write_bundle(directory=tmp_path, content=bundle_content)@@ -213,38 +210,41 @@ class TestValidateParallelMultiplicityNextStep:# The console wraps long lines; the words, not the line breaks, are what the reader gets.output = " ".join(console.export_text().split())assert "Bundle validation failed" in output- assert expected_next_step in output+ assert expected_item in outputassert f"💡 Tip: {_TOP_LEVEL_NEXT_STEP}" in outputassert "Check the validation_errors array" not in outputassert "Traceback" not in output- def test_a_concept_mismatch_keeps_the_combine_report(self, tmp_path: Path) -> None:- """A branch whose concept does not fit its field gets no multiplicity advice, and its refusal is not hidden."""- bundle_path = _write_bundle(directory=tmp_path, content=_TWO_FAULTS_IN_ONE_COMBINE)-- with pytest.raises(ValidateBundleError) as raised:- asyncio.run(validate_bundle(mthds_file_path=bundle_path, library_dirs=[bundle_path.parent]))+ def test_a_concept_mismatch_beside_a_multiplicity_one_reports_the_multiplicity(self, tmp_path: Path) -> None:+ """Of two faults in one combine, the caller's item is the multiplicity one, rendered from its own parameters."""+ problem = _verdict_problem(bundle_path=_write_bundle(directory=tmp_path, content=_TWO_FAULTS_IN_ONE_COMBINE))- (item,) = raised.value.to_error_report().validation_errors or []- assert _LIST_INTO_SINGLE_NEXT_STEP in item.message- assert "gives result 'overview'" not in item.message- assert "The combine also reported: Error combining stuffs for concept TopicReview" in item.message+ assert problem.errors is not None+ (item,) = problem.errors+ assert item.code == CoreCode.PIPE_OUTPUT_MULTIPLICITY+ assert item.params is not None+ assert item.params.as_wire() == {"pipe": "analyze_topics", "output": "ideas", "declared": "single", "produced": "list"}+ assert item.detail == _LIST_INTO_SINGLE_SENTENCE+ # The combine's own text quotes the structure's validation, which is the operator's alone.+ assert "Error combining stuffs" not in str(problem.to_wire())@pytest.mark.parametrize(- "bundle_content",- [_TEXT_INTO_PRIMITIVE_LIST_FIELD, _ANYTHING_LIST_INTO_SINGLE_FIELD],+ ("bundle_content", "pipe_code"),+ [(_TEXT_INTO_PRIMITIVE_LIST_FIELD, "analyze_topic"), (_ANYTHING_LIST_INTO_SINGLE_FIELD, "analyze_topics")],ids=["text_into_primitive_list_field", "anything_list_into_single_field"],)- def test_no_multiplicity_advice_where_it_would_not_help(self, tmp_path: Path, bundle_content: str) -> None:- """The verdict carries the combine's own refusal, never a multiplicity change that could not make it combine."""- bundle_path = _write_bundle(directory=tmp_path, content=bundle_content)-- with pytest.raises(ValidateBundleError) as raised:- asyncio.run(validate_bundle(mthds_file_path=bundle_path, library_dirs=[bundle_path.parent]))-- (item,) = raised.value.to_error_report().validation_errors or []- assert "Error combining stuffs for concept TopicReview" in item.message- assert "cannot combine its branch results" not in item.message+ def test_no_multiplicity_advice_where_it_would_not_help(self, tmp_path: Path, bundle_content: str, pipe_code: str) -> None:+ """The verdict reports an output that does not fit its concept, never a multiplicity change that could not make it combine."""+ problem = _verdict_problem(bundle_path=_write_bundle(directory=tmp_path, content=bundle_content))++ assert problem.errors is not None+ (item,) = problem.errors+ assert item.code == CoreCode.PIPE_OUTPUT_INVALID+ assert item.params is not None+ assert item.params.as_wire() == {"pipe": pipe_code, "output_concept": "TopicReview", "fields": ["ideas"]}+ assert item.detail == f"Pipe '{pipe_code}' produced an output that does not fit the concept 'TopicReview', at the fields ideas."+ assert "Error combining stuffs" not in str(problem.to_wire())+ assert "cannot combine its branch results" not in str(problem.to_wire())def test_agent_validate_bundle_json_carries_the_next_step(self,@@ -269,20 +269,30 @@ class TestValidateParallelMultiplicityNextStep:envelope = json.loads(capsys.readouterr().err)assert envelope["is_valid"] is Falseassert envelope["error_domain"] == "input"+ assert envelope["error_code"] == CoreCode.METHOD_INVALIDassert envelope["hint"].startswith(_TOP_LEVEL_NEXT_STEP)(item,) = envelope["validation_errors"]assert item["category"] == "dry_run"- assert "PipeParallel 'analyze_topics' cannot combine its branch results into its output 'TopicReview'." in item["message"]- assert _LIST_INTO_SINGLE_NEXT_STEP in item["message"]+ assert item["pipe_code"] == "analyze_topics"+ assert item["message"] == f"Pipe 'analyze_topics' failed its dry run: {_LIST_INTO_SINGLE_SENTENCE}"- def test_the_verdict_report_carries_both_next_steps(self, tmp_path: Path) -> None:- """The report every surface draws from: the item names the fix, the top level points at the items."""+ def test_the_verdict_problem_carries_both_next_steps(self, tmp_path: Path) -> None:+ """The problem every surface draws from: the item names the fault, the top level points at the items."""bundle_path = _write_bundle(directory=tmp_path, content=_LIST_BRANCH_INTO_SINGLE_FIELD)with pytest.raises(ValidateBundleError) as raised:asyncio.run(validate_bundle(mthds_file_path=bundle_path, library_dirs=[bundle_path.parent]))- report = raised.value.to_error_report()- assert (report.user_action_detail() or "").startswith(_TOP_LEVEL_NEXT_STEP)- (item,) = report.validation_errors or []- assert _LIST_INTO_SINGLE_NEXT_STEP in item.message+ verdict = raised.value+ advice = verdict.advised_action()+ assert advice is not None+ assert (advice.detail or "").startswith(_TOP_LEVEL_NEXT_STEP)+ problem = verdict.to_problem(view=ProblemView.CALLER)+ assert problem.code == CoreCode.METHOD_INVALID+ assert problem.next_step.kind == StepKind.CHANGE_METHOD+ assert problem.errors is not None+ (item,) = problem.errors+ assert item.code == CoreCode.PIPE_OUTPUT_MULTIPLICITY+ assert item.detail == _LIST_INTO_SINGLE_SENTENCE+ assert item.location is not None+ assert item.location.pipe == "analyze_topics"diff --git a/tests/integration/pipelex/cogt/test_handle_per_model_type_end_to_end.py b/tests/integration/pipelex/cogt/test_handle_per_model_type_end_to_end.pyindex 6dc03e818..51bc4e33b 100644--- a/tests/integration/pipelex/cogt/test_handle_per_model_type_end_to_end.py+++ b/tests/integration/pipelex/cogt/test_handle_per_model_type_end_to_end.py@@ -11,12 +11,14 @@ import shutilfrom pathlib import Pathimport pytest+from mthds.protocol.problem.registry import CoreCodefrom pytest_mock import MockerFixturefrom pipelex.cogt.model_backends.model_spec import InferenceModelSpecfrom pipelex.cogt.model_backends.model_type import ModelTypefrom pipelex.cogt.models.model_deck import ModelDeckfrom pipelex.cogt.models.model_manager import ModelManager+from pipelex.errors.problem import ProblemViewfrom pipelex.kit.paths import get_kit_configs_dirfrom pipelex.pipeline.exceptions import ValidateBundleErrorfrom pipelex.pipeline.validate_bundle import validate_bundle@@ -163,7 +165,13 @@ class TestHandlePerModelTypeEndToEnd:with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_contents=[judging_the_llm_only_model])- report = str(exc_info.value.to_error_report().model_dump())- assert LLM_ONLY_HANDLE in report- assert "'unknown_model'" in report- assert "'model_type': 'judgment'" in report+ caller = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert caller.code == CoreCode.METHOD_INVALID+ assert caller.errors is not None+ (item,) = caller.errors+ assert item.code == CoreCode.MODEL_UNKNOWN+ assert item.params is not None+ assert item.params.as_wire()["model"] == LLM_ONLY_HANDLE+ assert item.params.as_wire()["model_type"] == ModelType.JUDGMENT+ assert item.location is not None+ assert item.location.pipe == "judge_it"diff --git a/tests/integration/pipelex/error_handling/test_data.py b/tests/integration/pipelex/error_handling/test_data.pyindex 3954d3ed6..95b992ee0 100644--- a/tests/integration/pipelex/error_handling/test_data.py+++ b/tests/integration/pipelex/error_handling/test_data.py@@ -1,7 +1,7 @@-"""Per-repo bundle paths for the local / Temporal ``ErrorReport`` parity pair.+"""Per-repo bundle paths for the local / Temporal problem parity pair.The parity-invariant fixtures (the injected failure + its expected classification) and the error-factories are the single shared source of truth in ``pipelex.test_extras.error_report_parity`` —+factories are the single shared source of truth in ``pipelex.test_extras.problem_parity`` —shipped in the open-core wheel so this repo's local arm and our Temporal plugin's distributedarm import the *same* data and cannot silently diverge. Only the ``.mthds`` bundle each repoships is genuinely per-repo, so that is all these subclasses add.@@ -9,24 +9,24 @@ ships is genuinely per-repo, so that is all these subclasses add.from typing import ClassVar-from pipelex.test_extras.error_report_parity import ErrorReportParityTestData as SharedErrorReportParityTestData-from pipelex.test_extras.error_report_parity import JudgeErrorReportParityTestData as SharedJudgeErrorReportParityTestData-from pipelex.test_extras.error_report_parity import SearchErrorReportParityTestData as SharedSearchErrorReportParityTestData+from pipelex.test_extras.problem_parity import JudgeProblemParityTestData as SharedJudgeProblemParityTestData+from pipelex.test_extras.problem_parity import ProblemParityTestData as SharedProblemParityTestData+from pipelex.test_extras.problem_parity import SearchProblemParityTestData as SharedSearchProblemParityTestData-class ErrorReportParityTestData(SharedErrorReportParityTestData):+class ProblemParityTestData(SharedProblemParityTestData):"""Local-arm view of the parity fixtures, pointing at this repo's ``native_text_sequence`` bundle."""BUNDLE_FILE: ClassVar[str] = "tests/integration/pipelex/error_handling/bundles/native_text_sequence.mthds"-class SearchErrorReportParityTestData(SharedSearchErrorReportParityTestData):+class SearchProblemParityTestData(SharedSearchProblemParityTestData):"""Local-arm view of the search parity fixtures, pointing at this repo's ``native_search`` bundle."""BUNDLE_FILE: ClassVar[str] = "tests/integration/pipelex/error_handling/bundles/native_search.mthds"-class JudgeErrorReportParityTestData(SharedJudgeErrorReportParityTestData):+class JudgeProblemParityTestData(SharedJudgeProblemParityTestData):"""Local-arm view of the judgment parity fixtures, pointing at this repo's ``native_judge`` bundle."""BUNDLE_FILE: ClassVar[str] = "tests/integration/pipelex/error_handling/bundles/native_judge.mthds"diff --git a/tests/integration/pipelex/error_handling/test_error_report_local_full_chain.py b/tests/integration/pipelex/error_handling/test_error_report_local_full_chain.pydeleted file mode 100644index 41986adee..000000000--- a/tests/integration/pipelex/error_handling/test_error_report_local_full_chain.py+++ /dev/null@@ -1,68 +0,0 @@-"""Local arm of the local / Temporal ``ErrorReport`` parity pair.--Runs the ``native_text_sequence`` pipe through the local (non-Temporal)-``PipeRouter`` with the LLM call mocked to fail, and asserts the resulting-``ErrorReport`` carries the full classification — ``error_category`` /-``retryable`` / ``model`` / ``provider`` / ``user_action``.--This is the baseline the Temporal full-chain test-(``tests/integration/pipelex/temporal/test_workflow_error_report_full_chain.py``)-must match. Both arms assert the same ``ErrorReportParityTestData`` constants, so-local / Temporal parity holds by construction. They live in separate modules on-purpose: the Temporal arm needs ``temporal.is_enabled = True`` and the temporal-``boot_temporal`` fixture, this one must stay on default config — separate-modules avoid any in-test config swapping.-"""--from collections.abc import Generator--import pytest-from pytest_mock import MockerFixture--from pipelex.cogt.content_generation.content_generator import ContentGenerator-from pipelex.interpreter_hub import get_pipe_router-from pipelex.pipe_run.exceptions import PipeRouterError-from pipelex.pipe_run.pipe_job import PipeJob-from pipelex.system.pipe_run_mode import PipeRunMode-from tests.integration.pipelex.error_handling.test_data import ErrorReportParityTestData-from tests.integration.pipelex.fixtures.pipe_job_helpers import pipe_job_from_bundle--[email protected](loop_scope="class")-class TestErrorReportLocalFullChain:- """A failing pipe run locally yields a fully classified ``ErrorReport``."""-- @pytest.fixture- def failing_pipe_job_local(self) -> Generator[PipeJob, None, None]:- """A PipeJob for the failing pipe, in LIVE mode so the LLM call actually fires."""- yield from pipe_job_from_bundle(- bundle_file=ErrorReportParityTestData.BUNDLE_FILE,- pipe_code=ErrorReportParityTestData.PIPE_CODE,- pipe_run_mode=PipeRunMode.LIVE,- )-- async def test_error_report_from_local_execution(- self,- mocker: MockerFixture,- failing_pipe_job_local: PipeJob,- ) -> None:- """Local execution surfaces the worker failure as a classified ``PipeRouterError``."""- mocker.patch.object(- ContentGenerator,- "make_llm_text",- side_effect=ErrorReportParityTestData.make_failing_llm_error(),- )-- with pytest.raises(PipeRouterError) as exc_info:- await get_pipe_router().run(pipe_job=failing_pipe_job_local)-- # The classification fields — the parity target. error_type / message- # are not part of this pair (the local report names the root fault,- # located at the failing pipe), so they are not asserted here.- report = exc_info.value.to_error_report()- assert report.error_category == ErrorReportParityTestData.FAILURE_CATEGORY- assert report.retryable == ErrorReportParityTestData.EXPECTED_RETRYABLE- assert report.model == ErrorReportParityTestData.FAILURE_MODEL- assert report.provider == ErrorReportParityTestData.FAILURE_PROVIDER- assert report.user_action is not None- assert report.user_action.kind == ErrorReportParityTestData.EXPECTED_USER_ACTION_KINDdiff --git a/tests/integration/pipelex/error_handling/test_judge_error_report_local_full_chain.py b/tests/integration/pipelex/error_handling/test_judge_error_report_local_full_chain.pydeleted file mode 100644index 76f1a4c8f..000000000--- a/tests/integration/pipelex/error_handling/test_judge_error_report_local_full_chain.py+++ /dev/null@@ -1,65 +0,0 @@-"""Local arm of the local / Temporal ``ErrorReport`` parity pair for judgment.--Runs the ``native_judge`` pipe through the local (non-Temporal) ``PipeRouter`` with the judgment call-mocked to fail, and asserts the resulting ``ErrorReport`` carries the full classification —-``error_category`` / ``retryable`` / ``model`` / ``provider`` / ``user_action``.--This is the baseline a distributed arm must match, asserting the same ``JudgeErrorReportParityTestData``-constants so local / distributed parity holds by construction. The judgment operator does not wrap the-leaf error (unlike PipeLLM), so the ``PipeRouter`` locates the raw ``JudgmentJobFailureError`` (a-``CogtError``) itself, and the report carries its identity.-"""--from collections.abc import Generator--import pytest-from pytest_mock import MockerFixture--from pipelex.cogt.content_generation.content_generator import ContentGenerator-from pipelex.cogt.exceptions import JudgmentJobFailureError-from pipelex.interpreter_hub import get_pipe_router-from pipelex.pipe_run.exceptions import PipeRouterError-from pipelex.pipe_run.pipe_job import PipeJob-from pipelex.system.pipe_run_mode import PipeRunMode-from tests.integration.pipelex.error_handling.test_data import JudgeErrorReportParityTestData-from tests.integration.pipelex.fixtures.pipe_job_helpers import pipe_job_from_bundle--[email protected](loop_scope="class")-class TestJudgeErrorReportLocalFullChain:- """A failing judgment pipe run locally yields a fully classified ``ErrorReport``."""-- @pytest.fixture- def failing_judge_pipe_job_local(self) -> Generator[PipeJob, None, None]:- """A PipeJob for the judgment pipe, in LIVE mode so the judgment call actually fires."""- yield from pipe_job_from_bundle(- bundle_file=JudgeErrorReportParityTestData.BUNDLE_FILE,- pipe_code=JudgeErrorReportParityTestData.PIPE_CODE,- pipe_run_mode=PipeRunMode.LIVE,- )-- async def test_error_report_from_local_execution(- self,- mocker: MockerFixture,- failing_judge_pipe_job_local: PipeJob,- ) -> None:- """Local execution surfaces the worker failure, located, with the ``JudgmentJobFailureError``'s classification."""- mocker.patch.object(- ContentGenerator,- "make_judgment_answers",- side_effect=JudgeErrorReportParityTestData.make_failing_judgment_error(),- )-- with pytest.raises(PipeRouterError) as exc_info:- await get_pipe_router().run(pipe_job=failing_judge_pipe_job_local)- assert isinstance(exc_info.value.__cause__, JudgmentJobFailureError)-- # The classification fields — the parity target.- report = exc_info.value.to_error_report()- assert report.error_type == "JudgmentJobFailureError"- assert report.error_category == JudgeErrorReportParityTestData.FAILURE_CATEGORY- assert report.retryable == JudgeErrorReportParityTestData.EXPECTED_RETRYABLE- assert report.model == JudgeErrorReportParityTestData.FAILURE_MODEL- assert report.provider == JudgeErrorReportParityTestData.FAILURE_PROVIDER- assert report.user_action is not None- assert report.user_action.kind == JudgeErrorReportParityTestData.EXPECTED_USER_ACTION_KINDdiff --git a/tests/integration/pipelex/error_handling/test_judge_problem_local_full_chain.py b/tests/integration/pipelex/error_handling/test_judge_problem_local_full_chain.pynew file mode 100644index 000000000..856329cbb--- /dev/null+++ b/tests/integration/pipelex/error_handling/test_judge_problem_local_full_chain.py@@ -0,0 +1,75 @@+"""Local arm of the local / Temporal problem parity pair for judgment.++Runs the ``native_judge`` pipe through the local (non-Temporal) ``PipeRouter`` with the judgment call+mocked to fail, and asserts the resulting problem carries the full classification —+its code, domain, verdict and step, and the model and the provider in the operator's diagnostics.++This is the baseline a distributed arm must match, asserting the same ``JudgeProblemParityTestData``+constants so local / distributed parity holds by construction. The judgment operator does not wrap the+leaf error (unlike PipeLLM), so the ``PipeRouter`` locates the raw ``JudgmentJobFailureError`` (a+``CogtError``) itself, and the problem's diagnostics carry its identity.+"""++from collections.abc import Generator++import pytest+from pytest_mock import MockerFixture++from pipelex.cogt.content_generation.content_generator import ContentGenerator+from pipelex.cogt.exceptions import JudgmentJobFailureError, find_inference_error_category_in_chain+from pipelex.errors.problem import ProblemView+from pipelex.interpreter_hub import get_pipe_router+from pipelex.pipe_run.exceptions import PipeRouterError+from pipelex.pipe_run.pipe_job import PipeJob+from pipelex.system.pipe_run_mode import PipeRunMode+from tests.integration.pipelex.error_handling.test_data import JudgeProblemParityTestData+from tests.integration.pipelex.fixtures.pipe_job_helpers import pipe_job_from_bundle++[email protected](loop_scope="class")+class TestJudgeProblemLocalFullChain:+ """A failing judgment pipe run locally yields a fully classified problem."""++ @pytest.fixture+ def failing_judge_pipe_job_local(self) -> Generator[PipeJob, None, None]:+ """A PipeJob for the judgment pipe, in LIVE mode so the judgment call actually fires."""+ yield from pipe_job_from_bundle(+ bundle_file=JudgeProblemParityTestData.BUNDLE_FILE,+ pipe_code=JudgeProblemParityTestData.PIPE_CODE,+ pipe_run_mode=PipeRunMode.LIVE,+ )++ async def test_problem_from_local_execution(+ self,+ mocker: MockerFixture,+ failing_judge_pipe_job_local: PipeJob,+ ) -> None:+ """Local execution surfaces the worker failure, located, with the ``JudgmentJobFailureError``'s classification."""+ mocker.patch.object(+ ContentGenerator,+ "make_judgment_answers",+ side_effect=JudgeProblemParityTestData.make_failing_judgment_error(),+ )++ with pytest.raises(PipeRouterError) as exc_info:+ await get_pipe_router().run(pipe_job=failing_judge_pipe_job_local)+ assert isinstance(exc_info.value.__cause__, JudgmentJobFailureError)++ # The classification the problem carries — the parity target.+ error = exc_info.value+ problem = error.to_problem(view=ProblemView.OPERATOR)+ assert problem.code == JudgeProblemParityTestData.EXPECTED_CODE+ assert problem.domain == JudgeProblemParityTestData.EXPECTED_DOMAIN+ assert problem.is_retryable is JudgeProblemParityTestData.EXPECTED_RETRYABLE+ assert problem.next_step.kind == JudgeProblemParityTestData.EXPECTED_OPERATOR_STEP_KIND+ assert problem.diagnostics is not None+ assert problem.diagnostics.error_class == "JudgmentJobFailureError"+ assert problem.diagnostics.model == JudgeProblemParityTestData.FAILURE_MODEL+ assert problem.diagnostics.provider is not None+ assert problem.diagnostics.provider.name == JudgeProblemParityTestData.FAILURE_PROVIDER+ assert find_inference_error_category_in_chain(error) == JudgeProblemParityTestData.FAILURE_CATEGORY+ # The advice stays the local CLI's tip: the caller's view carries the code's step, never the advice.+ advice = error.advised_action()+ assert advice is not None+ assert advice.kind == JudgeProblemParityTestData.FAILURE_USER_ACTION_KIND+ assert JudgeProblemParityTestData.FAILURE_USER_ACTION_DETAIL not in str(error.to_problem(view=ProblemView.CALLER).to_wire())diff --git a/tests/integration/pipelex/error_handling/test_problem_local_full_chain.py b/tests/integration/pipelex/error_handling/test_problem_local_full_chain.pynew file mode 100644index 000000000..582b59ae1--- /dev/null+++ b/tests/integration/pipelex/error_handling/test_problem_local_full_chain.py@@ -0,0 +1,77 @@+"""Local arm of the local / Temporal problem parity pair.++Runs the ``native_text_sequence`` pipe through the local (non-Temporal)+``PipeRouter`` with the LLM call mocked to fail, and asserts the resulting+problem carries the full classification — its code, domain,+verdict and step, and the model and the provider in the operator's diagnostics.++This is the baseline the Temporal full-chain test+(``tests/integration/pipelex/temporal/test_workflow_problem_full_chain.py``)+must match. Both arms assert the same ``ProblemParityTestData`` constants, so+local / Temporal parity holds by construction. They live in separate modules on+purpose: the Temporal arm needs ``temporal.is_enabled = True`` and the temporal+``boot_temporal`` fixture, this one must stay on default config — separate+modules avoid any in-test config swapping.+"""++from collections.abc import Generator++import pytest+from pytest_mock import MockerFixture++from pipelex.cogt.content_generation.content_generator import ContentGenerator+from pipelex.cogt.exceptions import find_inference_error_category_in_chain+from pipelex.errors.problem import ProblemView+from pipelex.interpreter_hub import get_pipe_router+from pipelex.pipe_run.exceptions import PipeRouterError+from pipelex.pipe_run.pipe_job import PipeJob+from pipelex.system.pipe_run_mode import PipeRunMode+from tests.integration.pipelex.error_handling.test_data import ProblemParityTestData+from tests.integration.pipelex.fixtures.pipe_job_helpers import pipe_job_from_bundle++[email protected](loop_scope="class")+class TestProblemLocalFullChain:+ """A failing pipe run locally yields a fully classified problem."""++ @pytest.fixture+ def failing_pipe_job_local(self) -> Generator[PipeJob, None, None]:+ """A PipeJob for the failing pipe, in LIVE mode so the LLM call actually fires."""+ yield from pipe_job_from_bundle(+ bundle_file=ProblemParityTestData.BUNDLE_FILE,+ pipe_code=ProblemParityTestData.PIPE_CODE,+ pipe_run_mode=PipeRunMode.LIVE,+ )++ async def test_problem_from_local_execution(+ self,+ mocker: MockerFixture,+ failing_pipe_job_local: PipeJob,+ ) -> None:+ """Local execution surfaces the worker failure as a classified ``PipeRouterError``."""+ mocker.patch.object(+ ContentGenerator,+ "make_llm_text",+ side_effect=ProblemParityTestData.make_failing_llm_error(),+ )++ with pytest.raises(PipeRouterError) as exc_info:+ await get_pipe_router().run(pipe_job=failing_pipe_job_local)++ # The classification the problem carries — the parity target.+ error = exc_info.value+ problem = error.to_problem(view=ProblemView.OPERATOR)+ assert problem.code == ProblemParityTestData.EXPECTED_CODE+ assert problem.domain == ProblemParityTestData.EXPECTED_DOMAIN+ assert problem.is_retryable is ProblemParityTestData.EXPECTED_RETRYABLE+ assert problem.next_step.kind == ProblemParityTestData.EXPECTED_OPERATOR_STEP_KIND+ assert problem.diagnostics is not None+ assert problem.diagnostics.model == ProblemParityTestData.FAILURE_MODEL+ assert problem.diagnostics.provider is not None+ assert problem.diagnostics.provider.name == ProblemParityTestData.FAILURE_PROVIDER+ assert find_inference_error_category_in_chain(error) == ProblemParityTestData.FAILURE_CATEGORY+ # The advice stays the local CLI's tip: the caller's view carries the code's step, never the advice.+ advice = error.advised_action()+ assert advice is not None+ assert advice.kind == ProblemParityTestData.FAILURE_USER_ACTION_KIND+ assert ProblemParityTestData.FAILURE_USER_ACTION_DETAIL not in str(error.to_problem(view=ProblemView.CALLER).to_wire())diff --git a/tests/integration/pipelex/error_handling/test_search_error_report_local_full_chain.py b/tests/integration/pipelex/error_handling/test_search_error_report_local_full_chain.pydeleted file mode 100644index 6736de4a4..000000000--- a/tests/integration/pipelex/error_handling/test_search_error_report_local_full_chain.py+++ /dev/null@@ -1,67 +0,0 @@-"""Local arm of the local / Temporal ``ErrorReport`` parity pair for web search.--Runs the ``native_search`` pipe through the local (non-Temporal) ``PipeRouter`` with the search call-mocked to fail, and asserts the resulting ``ErrorReport`` carries the full classification —-``error_category`` / ``retryable`` / ``model`` / ``provider`` / ``user_action``.--This is the baseline the Temporal full-chain test-(``tests/integration/pipelex/temporal/test_workflow_search_error_report_full_chain.py``) must match.-Both arms assert the same ``SearchErrorReportParityTestData`` constants, so local / Temporal parity holds-by construction. The search operator does not wrap the leaf error (unlike PipeLLM), so the-``PipeRouter`` locates the raw ``SearchJobFailureError`` (a ``CogtError``) itself, and the report-carries its identity.-"""--from collections.abc import Generator--import pytest-from pytest_mock import MockerFixture--from pipelex.cogt.content_generation.content_generator import ContentGenerator-from pipelex.cogt.exceptions import SearchJobFailureError-from pipelex.interpreter_hub import get_pipe_router-from pipelex.pipe_run.exceptions import PipeRouterError-from pipelex.pipe_run.pipe_job import PipeJob-from pipelex.system.pipe_run_mode import PipeRunMode-from tests.integration.pipelex.error_handling.test_data import SearchErrorReportParityTestData-from tests.integration.pipelex.fixtures.pipe_job_helpers import pipe_job_from_bundle--[email protected](loop_scope="class")-class TestSearchErrorReportLocalFullChain:- """A failing search pipe run locally yields a fully classified ``ErrorReport``."""-- @pytest.fixture- def failing_search_pipe_job_local(self) -> Generator[PipeJob, None, None]:- """A PipeJob for the search pipe, in LIVE mode so the search call actually fires."""- yield from pipe_job_from_bundle(- bundle_file=SearchErrorReportParityTestData.BUNDLE_FILE,- pipe_code=SearchErrorReportParityTestData.PIPE_CODE,- pipe_run_mode=PipeRunMode.LIVE,- )-- async def test_error_report_from_local_execution(- self,- mocker: MockerFixture,- failing_search_pipe_job_local: PipeJob,- ) -> None:- """Local execution surfaces the worker failure, located, with the ``SearchJobFailureError``'s classification."""- mocker.patch.object(- ContentGenerator,- "make_search_sourced_answer",- side_effect=SearchErrorReportParityTestData.make_failing_search_error(),- )-- with pytest.raises(PipeRouterError) as exc_info:- await get_pipe_router().run(pipe_job=failing_search_pipe_job_local)- assert isinstance(exc_info.value.__cause__, SearchJobFailureError)-- # The classification fields — the parity target.- report = exc_info.value.to_error_report()- assert report.error_type == "SearchJobFailureError"- assert report.error_category == SearchErrorReportParityTestData.FAILURE_CATEGORY- assert report.retryable == SearchErrorReportParityTestData.EXPECTED_RETRYABLE- assert report.model == SearchErrorReportParityTestData.FAILURE_MODEL- assert report.provider == SearchErrorReportParityTestData.FAILURE_PROVIDER- assert report.user_action is not None- assert report.user_action.kind == SearchErrorReportParityTestData.EXPECTED_USER_ACTION_KINDdiff --git a/tests/integration/pipelex/error_handling/test_search_problem_local_full_chain.py b/tests/integration/pipelex/error_handling/test_search_problem_local_full_chain.pynew file mode 100644index 000000000..7834911c9--- /dev/null+++ b/tests/integration/pipelex/error_handling/test_search_problem_local_full_chain.py@@ -0,0 +1,77 @@+"""Local arm of the local / Temporal problem parity pair for web search.++Runs the ``native_search`` pipe through the local (non-Temporal) ``PipeRouter`` with the search call+mocked to fail, and asserts the resulting problem carries the full classification —+its code, domain, verdict and step, and the model and the provider in the operator's diagnostics.++This is the baseline the Temporal full-chain test+(``tests/integration/pipelex/temporal/test_workflow_search_problem_full_chain.py``) must match.+Both arms assert the same ``SearchProblemParityTestData`` constants, so local / Temporal parity holds+by construction. The search operator does not wrap the leaf error (unlike PipeLLM), so the+``PipeRouter`` locates the raw ``SearchJobFailureError`` (a ``CogtError``) itself, and the problem's+diagnostics carry its identity.+"""++from collections.abc import Generator++import pytest+from pytest_mock import MockerFixture++from pipelex.cogt.content_generation.content_generator import ContentGenerator+from pipelex.cogt.exceptions import SearchJobFailureError, find_inference_error_category_in_chain+from pipelex.errors.problem import ProblemView+from pipelex.interpreter_hub import get_pipe_router+from pipelex.pipe_run.exceptions import PipeRouterError+from pipelex.pipe_run.pipe_job import PipeJob+from pipelex.system.pipe_run_mode import PipeRunMode+from tests.integration.pipelex.error_handling.test_data import SearchProblemParityTestData+from tests.integration.pipelex.fixtures.pipe_job_helpers import pipe_job_from_bundle++[email protected](loop_scope="class")+class TestSearchProblemLocalFullChain:+ """A failing search pipe run locally yields a fully classified problem."""++ @pytest.fixture+ def failing_search_pipe_job_local(self) -> Generator[PipeJob, None, None]:+ """A PipeJob for the search pipe, in LIVE mode so the search call actually fires."""+ yield from pipe_job_from_bundle(+ bundle_file=SearchProblemParityTestData.BUNDLE_FILE,+ pipe_code=SearchProblemParityTestData.PIPE_CODE,+ pipe_run_mode=PipeRunMode.LIVE,+ )++ async def test_problem_from_local_execution(+ self,+ mocker: MockerFixture,+ failing_search_pipe_job_local: PipeJob,+ ) -> None:+ """Local execution surfaces the worker failure, located, with the ``SearchJobFailureError``'s classification."""+ mocker.patch.object(+ ContentGenerator,+ "make_search_sourced_answer",+ side_effect=SearchProblemParityTestData.make_failing_search_error(),+ )++ with pytest.raises(PipeRouterError) as exc_info:+ await get_pipe_router().run(pipe_job=failing_search_pipe_job_local)+ assert isinstance(exc_info.value.__cause__, SearchJobFailureError)++ # The classification the problem carries — the parity target.+ error = exc_info.value+ problem = error.to_problem(view=ProblemView.OPERATOR)+ assert problem.code == SearchProblemParityTestData.EXPECTED_CODE+ assert problem.domain == SearchProblemParityTestData.EXPECTED_DOMAIN+ assert problem.is_retryable is SearchProblemParityTestData.EXPECTED_RETRYABLE+ assert problem.next_step.kind == SearchProblemParityTestData.EXPECTED_OPERATOR_STEP_KIND+ assert problem.diagnostics is not None+ assert problem.diagnostics.error_class == "SearchJobFailureError"+ assert problem.diagnostics.model == SearchProblemParityTestData.FAILURE_MODEL+ assert problem.diagnostics.provider is not None+ assert problem.diagnostics.provider.name == SearchProblemParityTestData.FAILURE_PROVIDER+ assert find_inference_error_category_in_chain(error) == SearchProblemParityTestData.FAILURE_CATEGORY+ # The advice stays the local CLI's tip: the caller's view carries the code's step, never the advice.+ advice = error.advised_action()+ assert advice is not None+ assert advice.kind == SearchProblemParityTestData.FAILURE_USER_ACTION_KIND+ assert SearchProblemParityTestData.FAILURE_USER_ACTION_DETAIL not in str(error.to_problem(view=ProblemView.CALLER).to_wire())diff --git a/tests/integration/pipelex/libraries/test_unparsable_dependency_bundle.py b/tests/integration/pipelex/libraries/test_unparsable_dependency_bundle.pyindex 12de3c0f0..57fd680c1 100644--- a/tests/integration/pipelex/libraries/test_unparsable_dependency_bundle.py+++ b/tests/integration/pipelex/libraries/test_unparsable_dependency_bundle.py@@ -14,7 +14,7 @@ from pathlib import Pathimport pytestfrom pytest_mock import MockerFixture-from pipelex.base_exceptions import DisclosureMode+from pipelex.errors.problem import ProblemViewfrom pipelex.pipeline.exceptions import ValidateBundleErrorfrom pipelex.pipeline.execution_seams import acquire_libraryfrom pipelex.pipeline.validate_bundle import validate_bundle@@ -33,9 +33,10 @@ UNPARSABLE_BUNDLES: dict[str, str] = {def _assert_names_no_host_path(*, verdict: ValidateBundleError, tmp_path: Path) -> None:- strict_dump = json.dumps(verdict.to_error_report().to_dict(disclosure_mode=DisclosureMode.STRICT))+ items = [item.model_dump(mode="json", exclude_none=True) for item in verdict.validation_error_items()]+ caller_dump = json.dumps({"problem": verdict.to_problem(view=ProblemView.CALLER).to_wire(), "validation_errors": items})for host_path in (str(tmp_path), str(tmp_path.resolve())):- assert host_path not in strict_dump+ assert host_path not in caller_dumpclass TestUnparsableDependencyBundle:@@ -48,7 +49,7 @@ class TestUnparsableDependencyBundle:acquire_library(library_id="", mthds_contents=[ProbePackageTestData.CONSUMER_BUNDLE], methods_dirs=[methods_dir])verdict = exc_info.value- items = verdict.to_error_report().validation_errors or []+ items = verdict.validation_error_items() or []assert items, verdict.messageassert {item.source for item in items} == {f"{PROBE_ALIAS}/probe_dep.mthds"}assert PROBE_ALIAS in verdict.message@@ -64,6 +65,6 @@ class TestUnparsableDependencyBundle:await validate_bundle(mthds_contents=[ProbePackageTestData.CONSUMER_BUNDLE])verdict = exc_info.value- items = verdict.to_error_report().validation_errors or []+ items = verdict.validation_error_items() or []assert [(item.source, item.line) for item in items] == [(f"{PROBE_ALIAS}/probe_dep.mthds", 3)]_assert_names_no_host_path(verdict=verdict, tmp_path=tmp_path)diff --git a/tests/integration/pipelex/libraries/test_unresolved_package_dependency.py b/tests/integration/pipelex/libraries/test_unresolved_package_dependency.pyindex 4790291b0..56c93ce18 100644--- a/tests/integration/pipelex/libraries/test_unresolved_package_dependency.py+++ b/tests/integration/pipelex/libraries/test_unresolved_package_dependency.py@@ -15,9 +15,11 @@ from pathlib import Pathimport pytestfrom mthds.package.exceptions import VCSFetchErrorfrom mthds.package.manifest.parser import parse_methods_toml+from mthds.protocol.problem.registry import ProblemDomainfrom pytest_mock import MockerFixture-from pipelex.base_exceptions import DisclosureMode, ErrorDomain, ValidationErrorCategory, ValidationErrorItem+from pipelex.base_exceptions import ValidationErrorCategory, ValidationErrorItem+from pipelex.errors.problem import ProblemViewfrom pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.interpreter_hub import get_library_managerfrom pipelex.libraries.exceptions import LibraryLoadingError@@ -69,14 +71,16 @@ async def _verdict_for(*, mthds_content: str) -> ValidateBundleError:def _package_items(verdict: ValidateBundleError) -> list[ValidationErrorItem]:- items = verdict.to_error_report().validation_errors or []+ items = verdict.validation_error_items() or []package_items = [item for item in items if item.error_type == PipeValidationErrorType.UNRESOLVED_PACKAGE_DEPENDENCY]assert len(package_items) == len(items), f"Only package items were expected, got {[(item.category, item.error_type) for item in items]}"return package_items-def _strict_dump(verdict: ValidateBundleError) -> str:- return json.dumps(verdict.to_error_report().to_dict(disclosure_mode=DisclosureMode.STRICT))+def _caller_dump(verdict: ValidateBundleError) -> str:+ """What a caller reads of a verdict: its problem in the caller's view and its validation items."""+ items = [item.model_dump(mode="json", exclude_none=True) for item in verdict.validation_error_items()]+ return json.dumps({"problem": verdict.to_problem(view=ProblemView.CALLER).to_wire(), "validation_errors": items})def _assert_located_on_go(item: ValidationErrorItem, *, reference: str) -> None:@@ -144,10 +148,10 @@ class TestUnresolvedPackageDependency:_assert_located_on_go(item, reference=PROBE_REFERENCE)# Git's own explanation stays; its progress line naming the runner's clone directory does not.assert "does not appear to be a git repository" in item.message- strict_dump = _strict_dump(verdict)- assert "does not appear to be a git repository" in strict_dump- assert "Cloning into" not in strict_dump- assert "mthds_fetch_on_miss_" not in strict_dump+ caller_dump = _caller_dump(verdict)+ assert "does not appear to be a git repository" in caller_dump+ assert "Cloning into" not in caller_dump+ assert "mthds_fetch_on_miss_" not in caller_dumpasync def test_the_host_log_keeps_what_caused_the_item(self, tmp_path: Path, mocker: MockerFixture, caplog: pytest.LogCaptureFixture) -> None:"""The item carries the caller-facing text; the host's own log keeps the whole cause chain, git's raw output included."""@@ -231,6 +235,7 @@ class TestUnresolvedPackageDependency:# 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.INPUT+ caller = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert caller.code == PipelexErrorCode.CONFIG_INVALID+ assert caller.domain == ProblemDomain.OPERATOR+ assert caller.errors is Nonediff --git a/tests/integration/pipelex/pipeline/test_condition_expression_parse_refusal.py b/tests/integration/pipelex/pipeline/test_condition_expression_parse_refusal.pyindex c417b2666..48ce62d24 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. A condition declared in a host's library directories is no-verdict at all but the deployment's fault, whose text STRICT redacts.+verdict is the caller's to read. A condition declared in a host's library directories is no verdict at all but+the deployment's fault, whose text is the operator's diagnostics alone."""import json@@ -15,8 +15,11 @@ from pathlib import Pathfrom typing import Anyimport pytest+from mthds.protocol.problem.registry import CoreCode, StepKind-from pipelex.base_exceptions import DisclosureMode, ValidationErrorCategory, ValidationErrorItem+from pipelex.base_exceptions import ValidationErrorCategory, ValidationErrorItem+from pipelex.errors.error_codes import error_code_spec+from pipelex.errors.problem import ProblemViewfrom pipelex.pipeline.exceptions import HostLibraryLoadRefusalError, ValidateBundleErrorfrom pipelex.pipeline.runner import PipelexMTHDSProtocolfrom pipelex.pipeline.validate_bundle import validate_bundle@@ -74,25 +77,40 @@ def _assert_is_the_refusal(*, item: ValidationErrorItem, reason: str, expressionassert expression_text not in item.message-def _strict_item_messages(payload: dict[str, Any]) -> list[str]:- return [item["message"] for item in payload["validation_errors"]]+def _caller_payload(verdict: ValidateBundleError) -> dict[str, Any]:+ """What a caller reads of a verdict: its problem in the caller's view and its validation items."""+ return {+ "problem": verdict.to_problem(view=ProblemView.CALLER).to_wire(),+ "validation_errors": [item.model_dump(mode="json", exclude_none=True) for item in verdict.validation_error_items()],+ }+++def _assert_the_caller_reads_one_item(*, verdict: ValidateBundleError, reason: str, expression_text: str) -> None:+ payload = _caller_payload(verdict)+ assert [item["message"] for item in payload["validation_errors"]] == [reason]+ problem = verdict.to_problem(view=ProblemView.CALLER)+ assert problem.code == CoreCode.METHOD_INVALID+ (problem_item,) = problem.errors or []+ # An item carries its own fault's code, never the verdict's umbrella, whose sentence says nothing of the condition.+ assert problem_item.code != CoreCode.METHOD_INVALID+ assert problem_item.location is not None+ assert problem_item.location.pipe == "route_parcel"+ assert expression_text not in json.dumps(payload)@pytest.mark.asyncio(loop_scope="class")class TestConditionExpressionParseRefusal:@_CASESasync def test_validation_refuses_it_as_an_item_on_the_condition(self, bundle: str, reason: str, expression_text: str) -> None:- """The verdict carries one item on the condition, the same locally and in the STRICT payload."""+ """The verdict carries one item on the condition, the same in the validation items and in the caller's problem."""with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_contents=[bundle])verdict = exc_info.value- (item,) = verdict.to_error_report().validation_errors or []+ (item,) = verdict.validation_error_items() or []_assert_is_the_refusal(item=item, reason=reason, expression_text=expression_text)- strict_payload = verdict.to_error_report().to_dict(disclosure_mode=DisclosureMode.STRICT)- assert _strict_item_messages(strict_payload) == [reason]- assert expression_text not in json.dumps(strict_payload)+ _assert_the_caller_reads_one_item(verdict=verdict, reason=reason, expression_text=expression_text)@_CASESasync def test_a_run_answers_422_with_the_item(self, bundle: str, reason: str, expression_text: str) -> None:@@ -103,19 +121,14 @@ class TestConditionExpressionParseRefusal:)verdict = exc_info.value- (item,) = verdict.to_error_report().validation_errors or []+ (item,) = verdict.validation_error_items() or []_assert_is_the_refusal(item=item, reason=reason, expression_text=expression_text)- document = verdict.to_error_report().to_problem_document(disclosure_mode=DisclosureMode.STRICT)- assert document["status"] == 422- assert document["error_domain"] == "input"- assert document["error_type"] == "ValidateBundleError"- assert document["detail"] == reason- assert _strict_item_messages(document) == [reason]- assert document["user_action"]["kind"] == "change_input"- assert expression_text not in json.dumps(document)+ _assert_the_caller_reads_one_item(verdict=verdict, reason=reason, expression_text=expression_text)+ assert error_code_spec(CoreCode.METHOD_INVALID).status == 422+ assert verdict.to_problem(view=ProblemView.CALLER).next_step.kind == StepKind.CHANGE_METHOD- async def test_a_host_library_condition_puts_none_of_its_text_in_the_strict_payload(self, tmp_path: Path) -> None:+ async def test_a_host_library_condition_puts_none_of_its_text_in_what_the_caller_reads(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)@@ -124,9 +137,9 @@ class TestConditionExpressionParseRefusal: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 "validation_errors" not in strict_payload- serialized_payload = json.dumps(strict_payload)+ caller = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert caller.errors is None+ serialized_payload = json.dumps(caller.to_wire())assert "frobnicate_the_parcel" not in serialized_payloadassert "lane ==" not in serialized_payloadassert str(tmp_path) not in serialized_payloaddiff --git a/tests/integration/pipelex/pipeline/test_condition_method_faults.py b/tests/integration/pipelex/pipeline/test_condition_method_faults.pyindex f03e9031d..cdabd9a40 100644--- a/tests/integration/pipelex/pipeline/test_condition_method_faults.py+++ b/tests/integration/pipelex/pipeline/test_condition_method_faults.py@@ -1,9 +1,9 @@-"""Pin: a `PipeCondition`'s own refusals are the caller's faults, and their reason reaches every surface.+"""Pin: a `PipeCondition`'s own refusals are the method's faults, and their sentence reaches every surface.The condition's expression and outcomes are the caller's own method, so when it refuses a run, the refusal-is the caller's to fix: its message names the pipe and the reason, locally and under STRICT disclosure, where-it used to be an unclassified `PipeRunError` that a validation verdict named by its title, "Pipe run", and a-hosted run answered with `An internal error occurred.`.+is the method's to fix: the caller reads the sentence of its code, naming the pipe, and the operator its reason,+where it used to be an unclassified `PipeRunError` that a validation verdict named by its title, "Pipe run", and+a hosted run answered with `An internal error occurred.`."""from __future__ import annotations@@ -12,22 +12,20 @@ import jsonfrom typing import Anyimport pytest+from mthds.protocol.problem.registry import CoreCode, ProblemDomain-from pipelex.base_exceptions import INTERNAL_ERROR_PLACEHOLDER, DisclosureMode, ValidationErrorCategory+from pipelex.base_exceptions import ValidationErrorCategory+from pipelex.errors.error_codes import error_code_spec+from pipelex.errors.problem import ProblemViewfrom pipelex.pipeline.exceptions import PipelineExecutionError, ValidateBundleErrorfrom pipelex.pipeline.runner import PipelexMTHDSProtocolfrom pipelex.pipeline.validate_bundle import validate_bundlefrom tests.integration.pipelex.pipeline.test_data import ConditionMethodFaultsTestData_EMPTY_EXPRESSION_REASON = "PipeCondition 'route_parcel': Conditional expression returned no result"-_EMPTY_EXPRESSION_NEXT_STEP = (- "Change the expression of PipeCondition 'route_parcel' so that it always renders a value: "- "the name of one of its outcomes, or any other value, which takes the default outcome."-)-_ALL_FAIL_REASON = (- "PipeCondition 'route_parcel' maps every outcome (and the default) to 'fail': every live run of this pipe raises. "- "Map at least one outcome to a pipe or to 'continue'."-)+# The sentences the condition's refusals render for a caller, naming the pipe and no text of the expression.+_UNMATCHED_SENTENCE = "The condition of pipe 'route_parcel' rendered a value that no outcome maps."+_ALL_FAIL_SENTENCE = "The declaration at 'pipe.route_parcel.outcomes' breaks a rule of the language (every outcome and the default map to 'fail')."def _routing_bundle(*, inputs: str, expression: str, outcomes: str, default_outcome: str) -> str:@@ -71,58 +69,69 @@ async def _failed_run(*, bundle: str, inputs: dict[str, Any]) -> PipelineExecutireturn exc_info.value+def _assert_the_condition_s_refusal(*, error: PipelineExecutionError, code: CoreCode, domain: ProblemDomain, detail: str, message: str) -> None:+ """The caller reads the code's sentence at the condition, a 422 of its domain; the condition's own reason is the operator's."""+ caller = error.to_problem(view=ProblemView.CALLER)+ assert caller.code == code, caller.to_wire()+ assert caller.domain == domain+ assert caller.detail == detail, caller.to_wire()+ assert caller.location is not None+ assert caller.location.pipe == "route_parcel"+ assert error_code_spec(code).status == 422+ operator = error.to_problem(view=ProblemView.OPERATOR)+ assert operator.diagnostics is not None+ assert operator.diagnostics.message == message++@pytest.mark.asyncio(loop_scope="class")class TestConditionMethodFaults:@pytest.mark.parametrize(- ("bundle", "reason"),+ ("bundle", "code", "sentence"),[- (_EMPTY_EXPRESSION_BUNDLE, _EMPTY_EXPRESSION_REASON),- (_ALL_FAIL_BUNDLE, _ALL_FAIL_REASON),+ (_EMPTY_EXPRESSION_BUNDLE, CoreCode.PIPE_CONDITION_UNMATCHED, _UNMATCHED_SENTENCE),+ (_ALL_FAIL_BUNDLE, CoreCode.METHOD_SCHEMA_VIOLATION, _ALL_FAIL_SENTENCE),],ids=["expression_renders_nothing", "every_outcome_fails"],)- async def test_a_dry_run_refusal_is_an_item_with_its_reason(self, bundle: str, reason: str) -> None:- """The verdict item names the pipe and the reason, locally and in the STRICT payload, never the title "Pipe run"."""+ async def test_a_dry_run_refusal_is_an_item_with_its_code_s_sentence(self, bundle: str, code: CoreCode, sentence: str) -> None:+ """The verdict item names the pipe and reads the sentence of the refusal's code, never the title "Pipe run"."""verdict = await _verdict(bundle=bundle)- (item,) = verdict.to_error_report().validation_errors or []+ (item,) = verdict.validation_error_items() or []assert item.category == ValidationErrorCategory.DRY_RUNassert item.pipe_code == "route_parcel"- assert item.message == f"Pipe 'route_parcel' failed its dry run: {reason}"-- strict_payload = verdict.to_error_report().to_dict(disclosure_mode=DisclosureMode.STRICT)- (strict_item,) = strict_payload["validation_errors"]- assert strict_item["message"] == f"Pipe 'route_parcel' failed its dry run: {reason}"-- async def test_an_expression_that_renders_nothing_is_the_callers_fault_under_strict(self) -> None:- """A run whose condition expression renders nothing: HTTP 422, the reason at the condition, and the next step."""+ assert item.message == f"Pipe 'route_parcel' failed its dry run: {sentence}"+ problem = verdict.to_problem(view=ProblemView.CALLER)+ (problem_item,) = problem.errors or []+ assert problem_item.code == code+ assert problem_item.detail == sentence++ async def test_an_expression_that_renders_nothing_is_the_methods_fault(self) -> None:+ """A run whose condition expression renders nothing: HTTP 422, the code's sentence at the condition."""error = await _failed_run(bundle=_EMPTY_EXPRESSION_BUNDLE, inputs={"parcel": "a box of books"})- document = error.to_error_report().to_problem_document(disclosure_mode=DisclosureMode.STRICT)- assert document["status"] == 422- assert document["error_domain"] == "input"- assert document["error_type"] == "PipeRunError"- assert document["detail"] == f"Pipe 'route_parcel' failed: {_EMPTY_EXPRESSION_REASON}"- assert document["user_action"] == {"kind": "change_input", "detail": _EMPTY_EXPRESSION_NEXT_STEP}+ _assert_the_condition_s_refusal(+ error=error,+ code=CoreCode.PIPE_CONDITION_UNMATCHED,+ domain=ProblemDomain.METHOD,+ detail=_UNMATCHED_SENTENCE,+ message=_EMPTY_EXPRESSION_REASON,+ )- async def test_a_fail_outcome_is_the_callers_fault_under_strict(self) -> None:- """A run whose lane the method maps to 'fail': HTTP 422, naming the pipe, never the value its expression rendered."""+ async def test_a_fail_outcome_refuses_the_inputs(self) -> None:+ """A run whose lane the method maps to 'fail': a refusal of these inputs, naming the pipe, never the value its expression rendered."""error = await _failed_run(bundle=_LANE_BUNDLE, inputs={"parcel": "a box of books", "lane": "reject"})- document = error.to_error_report().to_problem_document(disclosure_mode=DisclosureMode.STRICT)- assert document["status"] == 422- assert document["error_domain"] == "input"- assert document["error_type"] == "PipeRunError"- assert document["detail"] != INTERNAL_ERROR_PLACEHOLDER- # The rendered value can be text of a condition a host library declared, so no message carries it.- assert document["detail"] == "Pipe 'route_parcel' failed: PipeCondition 'route_parcel' failed with outcome: fail."- assert document["user_action"] == {- "kind": "change_input",- "detail": (- "PipeCondition 'route_parcel' 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'."- ),- }+ # The rendered value can be text of a condition a host library declared, so no reader's text carries it.+ _assert_the_condition_s_refusal(+ error=error,+ code=CoreCode.PIPE_CONDITION_REFUSED,+ domain=ProblemDomain.INPUT,+ detail="Pipe 'route_parcel' chose the outcome 'fail', which the method maps to a refusal of these inputs.",+ message="PipeCondition 'route_parcel' failed with outcome: fail.",+ )+ for view in (ProblemView.CALLER, ProblemView.OPERATOR):+ assert "reject" not in json.dumps(error.to_problem(view=view).to_wire())async def test_a_continue_outcome_leaves_its_rendered_value_out_of_the_absence_reason(self) -> None:"""A step force-unwrapping a result the condition resolved to 'continue' fails naming the condition, never the value it rendered."""@@ -132,16 +141,17 @@ class TestConditionMethodFaults:mthds_contents=[ConditionMethodFaultsTestData.CONTINUE_THEN_FORCE_MTHDS],inputs={"parcel": "a box of books", "lane": "hold"},)- report = exc_info.value.to_error_report()+ error = exc_info.value- assert report.error_type == "OptionalValueAbsentError"+ operator = error.to_problem(view=ProblemView.OPERATOR)+ assert operator.diagnostics is not None+ assert operator.diagnostics.error_class == "OptionalValueAbsentError"assert ("Absence origin: pipe 'route_parcel' produced no value — \"PipeCondition 'route_parcel' resolved to its 'continue' outcome\""- in report.message+ in operator.diagnostics.message)- assert ConditionMethodFaultsTestData.HELD_LANE_LITERAL not in report.message-- # The message is caller-facing, so STRICT disclosure keeps it, and nothing in the STRICT answer quotes the expression.- document = report.to_problem_document(disclosure_mode=DisclosureMode.STRICT)- assert document["detail"] == report.message- assert ConditionMethodFaultsTestData.HELD_LANE_LITERAL not in json.dumps(document)+ caller = error.to_problem(view=ProblemView.CALLER)+ assert caller.code == CoreCode.PIPE_FORCED_INPUT_ABSENT+ # Neither reader's text quotes the expression's rendered value.+ for text in (error.message, json.dumps(caller.to_wire()), json.dumps(operator.to_wire())):+ assert ConditionMethodFaultsTestData.HELD_LANE_LITERAL not in textdiff --git a/tests/integration/pipelex/pipeline/test_data.py b/tests/integration/pipelex/pipeline/test_data.pyindex 569d610e4..b78c132d1 100644--- a/tests/integration/pipelex/pipeline/test_data.py+++ b/tests/integration/pipelex/pipeline/test_data.py@@ -97,6 +97,9 @@ output = "Summary"prompt = "Summarize $topic""""+ # Both branches of the parallel give a list to a single field: two multiplicity faults in one combine.+ PARALLEL_TWO_MULTIPLICITIES_MTHDS: ClassVar[str] = PARALLEL_MTHDS.replace('output = "Summary"', 'output = "Summary[]"')+# A step force-unwraps ('!') an optional input the caller left out: a caller-facing failure.FORCE_MTHDS: ClassVar[str] = """domain = "located_failure_force"@@ -118,7 +121,7 @@ template = "Clause: {{ clause }}""""-class StrictMethodFaultsTestData:+class RunFaultViewsTestData:"""Bundles whose runs fail on a fault in the caller's own method, and on faults that are not the caller's."""# A sequence whose first step needs an input the caller may leave out of the request.@@ -192,6 +195,50 @@ type = "PipeCompose"description = "Write a one-line overview"output = "Overview"template = "One idea."+"""++ # The text a deployment's own structure class writes when its validator refuses a combination, which only the+ # operator may read: it is the deployment's code talking, not the caller's method.+ DEPLOYMENT_VALIDATOR_TEXT: ClassVar[str] = "Deployment rule DR-7 refused this review: internal threshold 0.83 not met"++ # A parallel whose output concept takes the structure class a deployment loaded from its own library, the class+ # named after the concept, whose model validator refuses every combination.+ DEPLOYMENT_VALIDATOR_MTHDS: ClassVar[str] = """+domain = "run_fault_views_deployment"+description = "A parallel whose output's structure class is the deployment's own"++[concept.RunFaultViewsValidatedReview]+description = "An idea and an overview, validated by the deployment's own structure class"++[pipe.flow]+type = "PipeSequence"+description = "Review the topic"+inputs = { topic = "Text" }+output = "RunFaultViewsValidatedReview"+steps = [{ pipe = "analyze", result = "review" }]++[pipe.analyze]+type = "PipeParallel"+description = "Draft an idea and an overview at the same time"+inputs = { topic = "Text" }+output = "RunFaultViewsValidatedReview"+branches = [+ { pipe = "draft_idea", result = "idea" },+ { pipe = "write_overview", result = "overview" },+]++[pipe.draft_idea]+type = "PipeCompose"+description = "Draft one idea about the topic"+inputs = { topic = "Text" }+output = "Text"+template = "An idea about $topic"++[pipe.write_overview]+type = "PipeCompose"+description = "Write a one-line overview"+output = "Text"+template = "One idea.""""DECK_PRESET: ClassVar[str] = "strict-faults-deck-preset"diff --git a/tests/integration/pipelex/pipeline/test_execute_request_id.py b/tests/integration/pipelex/pipeline/test_execute_request_id.pyindex 6fcf56b4c..1877d12c1 100644--- a/tests/integration/pipelex/pipeline/test_execute_request_id.py+++ b/tests/integration/pipelex/pipeline/test_execute_request_id.py@@ -6,6 +6,7 @@ import pytestfrom mthds.protocol.problem.registry import CoreCodefrom typing_extensions import override+from pipelex.errors.problem import ProblemViewfrom pipelex.interpreter_hub import get_pipe_runfrom pipelex.pipe_run.pipe_run_protocol import PipeRunProtocolfrom pipelex.pipeline.runner import PipelexMTHDSProtocol@@ -71,5 +72,5 @@ class TestExecuteRequestId:)assert type(exc_info.value) is RunParameterError- assert exc_info.value.to_error_report().code == CoreCode.REQUEST_INVALID+ assert exc_info.value.to_problem(view=ProblemView.CALLER).code == CoreCode.REQUEST_INVALIDassert pipe_run.pipe_jobs == []diff --git a/tests/integration/pipelex/pipeline/test_factory_refusal_verdicts.py b/tests/integration/pipelex/pipeline/test_factory_refusal_verdicts.pyindex 5c7d99e3f..996ff79b1 100644--- a/tests/integration/pipelex/pipeline/test_factory_refusal_verdicts.py+++ b/tests/integration/pipelex/pipeline/test_factory_refusal_verdicts.py@@ -2,19 +2,24 @@A pipe factory refuses a blueprint it cannot build, such as a ``PipeExtract`` whose input is neither animage nor a document. Its error classes declared no domain, so the validation translation did not-recognise them and they escaped every validator raw. They are now the author's input, caller-facing, so-the refusal validates to one item located on the pipe and its file, carrying the next step. The agent+recognise them and they escaped every validator raw. They are now the method's fault, so the refusal+validates to one item located on the pipe and its file, which reads the sentence its code renders; the+refusal's own message, naming the input and the next step, stays on the verdict's cause chain. The agentCLI's ``validate_all_core`` translated its load only after the failed library was torn down, so its itemslost their file; they keep it now."""+import jsonfrom pathlib import Pathimport pytest+from mthds.protocol.problem.registry import CoreCode, ProblemDomain, StepKind-from pipelex.base_exceptions import DisclosureMode, ErrorDomain, PipelexError, ValidationErrorCategory, ValidationErrorItem+from pipelex.base_exceptions import PipelexError, ValidationErrorCategory, ValidationErrorItemfrom pipelex.cli.agent_cli.commands.validate._validate_core import validate_all_corefrom pipelex.core.pipes.exceptions import PipeLoadRefusalError+from pipelex.errors.error_codes import error_code_spec+from pipelex.errors.problem import ProblemViewfrom pipelex.pipe_controllers.condition.exceptions import PipeConditionFactoryErrorfrom pipelex.pipe_controllers.parallel.exceptions import PipeParallelFactoryErrorfrom pipelex.pipe_operators.compose.exceptions import PipeComposeFactoryError@@ -93,19 +98,25 @@ def _assert_located_extract_item(*, items: list[ValidationErrorItem], bundle_patassert item.pipe_code == "read_almanac_pages"assert item.domain_code == _DOMAINassert item.source == str(bundle_path)- assert "The input 'almanac_text' of PipeExtract 'read_almanac_pages' is a native.Text" in item.message- assert _NEXT_STEP in item.message+ # The code's sentence names the refused input: the parameters the raise site gives.+ assert "almanac_text" in item.message+++def _caller_payload(error: ValidateBundleError) -> str:+ """What a caller reads of a verdict: its problem in the caller's view and its validation items."""+ items = [item.model_dump(mode="json", exclude_none=True) for item in error.validation_error_items()]+ return json.dumps({"problem": error.to_problem(view=ProblemView.CALLER).to_wire(), "validation_errors": items})@pytest.mark.asyncio(loop_scope="class")class TestFactoryRefusalVerdicts:@pytest.mark.parametrize("error_class", _FACTORY_REFUSAL_CLASSES, ids=[error_class.__name__ for error_class in _FACTORY_REFUSAL_CLASSES])- async def test_factory_refusal_is_the_authors_caller_facing_input(self, error_class: type[PipelexError]) -> None:- report = error_class("The pipe cannot be built from this blueprint.").to_error_report()+ async def test_factory_refusal_is_the_method_s_fault(self, error_class: type[PipelexError]) -> None:+ problem = error_class("The pipe cannot be built from this blueprint.").to_problem(view=ProblemView.CALLER)- assert report.error_domain == ErrorDomain.INPUT- assert report.caller_facing_message- assert report.http_status == 422+ assert problem.domain == ProblemDomain.METHOD+ assert problem.next_step.kind == StepKind.CHANGE_METHOD+ assert error_code_spec(CoreCode(problem.code)).status == 422async def test_validate_bundle_locates_the_extract_refusal_with_its_next_step(self, tmp_path: Path) -> None:bundle_path = _write_bundle(directory=tmp_path)@@ -115,10 +126,15 @@ class TestFactoryRefusalVerdicts:assert isinstance(raised.value.__cause__, PipeLoadRefusalError)assert isinstance(raised.value.__cause__.__cause__, PipeExtractFactoryError)- report = raised.value.to_error_report()- _assert_located_extract_item(items=report.validation_errors or [], bundle_path=bundle_path)- (strict_item,) = report.to_dict(disclosure_mode=DisclosureMode.STRICT)["validation_errors"]- assert _NEXT_STEP in strict_item["message"]+ _assert_located_extract_item(items=raised.value.validation_error_items(), bundle_path=bundle_path)+ problem = raised.value.to_problem(view=ProblemView.CALLER)+ assert problem.code == CoreCode.METHOD_INVALID+ (problem_item,) = problem.errors or []+ assert problem_item.code == CoreCode.METHOD_SCHEMA_VIOLATION+ # The factory's own message, naming the input and the next step, is on the chain for the operator.+ refusal_message = str(raised.value.__cause__.__cause__)+ assert "The input 'almanac_text' of PipeExtract 'read_almanac_pages' is a native.Text" in refusal_message+ assert _NEXT_STEP in refusal_messageasync def test_agent_validate_all_locates_a_wiring_refusal_on_its_file(self, tmp_path: Path) -> None:bundle_path = _write_bundle(directory=tmp_path, content=_SEQUENCE_OUTPUT_MISMATCH_BUNDLE)@@ -126,7 +142,7 @@ class TestFactoryRefusalVerdicts:with pytest.raises(ValidateBundleError) as raised:await validate_all_core(library_dirs=[tmp_path])- (item,) = raised.value.to_error_report().validation_errors or []+ (item,) = raised.value.validation_error_items() or []assert item.pipe_code == "summarize_almanac"assert item.source == str(bundle_path)@@ -138,8 +154,7 @@ class TestFactoryRefusalVerdicts:await validate_bundle(mthds_file_path=bundle_path, library_dirs=[tmp_path])# Jinja2's diagnosis names the unknown tag; the verdict must not.- strict_report = raised.value.to_error_report().to_dict(disclosure_mode=DisclosureMode.STRICT)- assert "quay_ledger" not in str(strict_report)+ assert "quay_ledger" not in _caller_payload(raised.value)async def test_an_inherited_system_prompt_refusal_names_the_domain(self, tmp_path: Path) -> None:bundle_path = _write_bundle(directory=tmp_path, content=_INHERITED_SYSTEM_PROMPT_BUNDLE)@@ -147,11 +162,14 @@ class TestFactoryRefusalVerdicts:with pytest.raises(ValidateBundleError) as raised:await validate_bundle(mthds_file_path=bundle_path, library_dirs=[tmp_path])- (item,) = raised.value.to_error_report().validation_errors or []+ (item,) = raised.value.validation_error_items() or []assert item.pipe_code == "write_note"assert item.source == str(bundle_path)- assert "system prompt of domain 'almanac_notes', which it inherits, for pipe 'write_note' in domain" in item.message- assert item.message.endswith("it does not parse at line 1 of that prompt.")- # The inherited prompt may be a host's, so its text never rides the caller-facing verdict.- strict_report = raised.value.to_error_report().to_dict(disclosure_mode=DisclosureMode.STRICT)- assert "harbour users" not in str(strict_report)+ # The item reads the code's sentence over the pipe and the parse failure; the refusal names the domain for the operator.+ assert "'write_note'" in item.message+ assert "line 1" in item.message+ refusal_message = str(raised.value.__cause__.__cause__ if raised.value.__cause__ else None)+ assert "system prompt of domain 'almanac_notes', which it inherits, for pipe 'write_note' in domain" in refusal_message+ assert refusal_message.endswith("it does not parse at line 1 of that prompt.")+ # The inherited prompt may be a host's, so its text never rides the verdict the caller reads.+ assert "harbour users" not in _caller_payload(raised.value)diff --git a/tests/integration/pipelex/pipeline/test_host_library_load_refusals.py b/tests/integration/pipelex/pipeline/test_host_library_load_refusals.pyindex f8b65f807..540241de7 100644--- a/tests/integration/pipelex/pipeline/test_host_library_load_refusals.py+++ b/tests/integration/pipelex/pipeline/test_host_library_load_refusals.py@@ -3,22 +3,25 @@A server loads its library directories beside a request's bundles, and those directories are the deployment's, not thecaller's (`library_dirs_are_callers` False). A pipe there that its factory refuses, or that names a model the deck doesnot 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.+`pipelex.config.invalid`, an operator fault, whose message is the operator's diagnostics alone. The same refusal in the+caller's own content stays the caller's: a 422 verdict with one item."""import jsonfrom pathlib import Pathimport pytest+from mthds.protocol.problem.registry import CoreCode, ProblemDomain-from pipelex.base_exceptions import INTERNAL_ERROR_PLACEHOLDER, DisclosureMode, ErrorDomain, PipelexError+from pipelex.base_exceptions import PipelexError+from pipelex.errors.error_codes import error_code_spec+from pipelex.errors.problem import ProblemViewfrom pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.pipeline.exceptions import HostLibraryLoadRefusalError, ValidateBundleErrorfrom pipelex.pipeline.runner import PipelexMTHDSProtocolfrom pipelex.pipeline.validate_bundle import validate_bundle-# Text of the host library's bundles that no STRICT answer may carry.+# Text of the host library's bundles that no caller's answer may carry._HOST_TEXT = "almanac"# A factory refusal: a PipeExtract whose input is neither an image nor a document.@@ -76,18 +79,16 @@ def _host_library_dir(*, directory: Path, refusing_bundle: str) -> Path: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)+ caller = error.to_problem(view=ProblemView.CALLER)+ assert caller.code == PipelexErrorCode.CONFIG_INVALID+ assert caller.domain == ProblemDomain.OPERATOR+ assert caller.errors is None+ assert error_code_spec(PipelexErrorCode.CONFIG_INVALID).status == 500+ # The operator reads which method refused; the caller reads none of the host library's text.+ operator = error.to_problem(view=ProblemView.OPERATOR)+ assert operator.diagnostics is not None+ assert _HOST_TEXT in operator.diagnostics.message+ assert _HOST_TEXT not in json.dumps(caller.to_wire())@pytest.mark.asyncio(loop_scope="class")@@ -121,10 +122,12 @@ class TestHostLibraryLoadRefusals: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+ problem = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert problem.code == CoreCode.METHOD_INVALID+ assert problem.domain == ProblemDomain.METHOD+ assert error_code_spec(CoreCode.METHOD_INVALID).status == 422+ assert len(problem.errors or []) == 1+ assert len(exc_info.value.validation_error_items()) == 1@_REFUSING_BUNDLESasync def test_a_refusal_in_the_callers_own_library_dirs_stays_the_callers(self, tmp_path: Path, refusing_bundle: str) -> None:@@ -136,4 +139,4 @@ class TestHostLibraryLoadRefusals:pipe_code="greet", mthds_contents=[_CALLER_BUNDLE], inputs={"name": "Ada"})- assert exc_info.value.to_error_report().error_domain == ErrorDomain.INPUT+ assert exc_info.value.to_problem(view=ProblemView.CALLER).code == CoreCode.METHOD_INVALIDdiff --git a/tests/integration/pipelex/pipeline/test_located_run_failure.py b/tests/integration/pipelex/pipeline/test_located_run_failure.pyindex c1a9bf939..eb9212005 100644--- a/tests/integration/pipelex/pipeline/test_located_run_failure.py+++ b/tests/integration/pipelex/pipeline/test_located_run_failure.py@@ -3,13 +3,14 @@ from __future__ import annotationsfrom typing import TYPE_CHECKINGimport pytest-from mthds.protocol.problem.registry import CoreCode+from mthds.protocol.problem.registry import CoreCode, StepKindfrom typing_extensions import override-from pipelex.base_exceptions import INTERNAL_ERROR_PLACEHOLDER, DisclosureMode, ErrorReport, PipelexError+from pipelex.base_exceptions import PipelexErrorfrom pipelex.cogt.inference.error_classification import UserAction, UserActionKindfrom pipelex.config import get_configfrom pipelex.errors.error_codes import error_code_spec+from pipelex.errors.problem import PipelexProblem, ProblemViewfrom pipelex.pipe_run.exceptions import PipeRouterError, find_failure_locationfrom pipelex.pipe_run.pipe_router import PipeRouterfrom pipelex.pipe_run.pipe_run import PipeRun@@ -45,27 +46,28 @@ class _DirectOrchestratorPipeRun(PipeRunProtocol):raise AssertionError(msg)-class _RecoveredReportError(PipelexError):- """Carries a report recovered across a transport boundary, as a distributed submitter does."""+class _RecoveredProblemError(PipelexError):+ """Carries a problem recovered across a transport boundary, as a distributed submitter does."""- def __init__(self, message: str, *, error_report: ErrorReport):+ def __init__(self, message: str, *, recovered_problem: PipelexProblem):super().__init__(message)- self.error_report = error_report+ self.carried_problem = recovered_problem@override- def to_error_report(self) -> ErrorReport:- return self.error_report+ def recovered_problem(self) -> PipelexProblem | None:+ return self.carried_problem-class _RecoveredReportPipeRun(PipeRunProtocol):- """Fail the way a distributed orchestrator does: its bridge sentence around a recovered report."""+class _RecoveredProblemPipeRun(PipeRunProtocol):+ """Fail the way a distributed orchestrator does: its bridge sentence around a recovered problem."""- def __init__(self, *, recovered_report: ErrorReport):- self._recovered_report = recovered_report+ def __init__(self, *, recovered_problem: PipelexProblem):+ self._recovered_problem = recovered_problem@overrideasync def run(self, pipe_job: PipeJob, *, delivery_assignment: DeliveryAssignment | None = None) -> PipeOutput:- recovered = _RecoveredReportError(self._recovered_report.message, error_report=self._recovered_report)+ recovered_message = self._recovered_problem.diagnostics.message if self._recovered_problem.diagnostics else self._recovered_problem.detail+ recovered = _RecoveredProblemError(recovered_message, recovered_problem=self._recovered_problem)msg = f"Pipe execution failed in temporal blocking delivery for pipe '{pipe_job.pipe.code}': {recovered}"raise PipelexBridgeDispatchError(msg) from recovered@@ -88,7 +90,7 @@ class TestLocatedRunFailure:return exc_info.valueasync def test_unserved_model_is_reported_at_the_failing_step(self) -> None:- """The model example: the failing step, its path and the model error's own identity and sentence."""+ """The model example: the failing step, its path and the model error's own identity, code and sentence."""runner = PipelexMTHDSProtocol()with pytest.raises(PipelineExecutionError) as exc_info:await runner.execute(pipe_code="two_steps", mthds_contents=[LocatedRunFailureTestData.MODEL_MTHDS], inputs={"topic": "cats"})@@ -97,34 +99,32 @@ class TestLocatedRunFailure:assert error.pipe_code == "summarize"assert error.pipe_stack == ["two_steps", "summarize"]- report = error.to_error_report()- assert report.error_type == "ModelNotFoundError"- 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_HANDLE- assert 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.- assert ".pipelex/inference" not in report.message- assert "pipelex init" not in report.message- assert report.model == LocatedRunFailureTestData.UNSERVED_MODEL_HANDLE- # The model lookup advises changing the model the step names, so no fallback is needed.- assert report.user_action == UserAction(+ caller = error.to_problem(view=ProblemView.CALLER)+ assert caller.code == CoreCode.MODEL_UNKNOWN+ assert caller.title == error_code_spec(CoreCode.MODEL_UNKNOWN).title+ assert caller.type == error_code_spec(CoreCode.MODEL_UNKNOWN).type_uri+ assert caller.location is not None+ assert (caller.location.pipe, caller.location.path) == ("summarize", ["two_steps", "summarize"])+ assert caller.detail == f"The method names the llm model '{unserved_handle}', which no catalog knows."+ assert caller.diagnostics is None++ operator = error.to_problem(view=ProblemView.OPERATOR)+ assert operator.diagnostics is not None+ assert operator.diagnostics.error_class == "ModelNotFoundError"+ assert operator.diagnostics.message == f"Model handle '{unserved_handle}' was not found in the model deck."+ assert operator.diagnostics.model == unserved_handle+ assert error.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: neither reader's text names it.+ for text in (error.message, str(caller.to_wire()), str(operator.to_wire())):+ assert ".pipelex/inference" not in text+ assert "pipelex init" not in text+ # The model lookup advises changing the model the step names, a local tip that rides no problem.+ assert error.advised_action() == UserAction(kind=UserActionKind.CHANGE_MODEL,detail=f"Change the model '{unserved_handle}' to an LLM the model deck serves.",)- # The step names the model in an inline setting, and no entry of the deck names it: the- # caller's own fault, whose message STRICT disclosure keeps.- strict_payload = report.to_dict(disclosure_mode=DisclosureMode.STRICT)- assert strict_payload["message"] == report.message- assert strict_payload["error_domain"] == "input"- assert strict_payload["error_type"] == "ModelNotFoundError"- assert strict_payload["user_action"] == {- "kind": "change_model",- "detail": f"Change the model '{unserved_handle}' to an LLM the model deck serves.",- }-async def test_parallel_combine_failure_is_reported_at_the_nested_parallel(self) -> None:"""The multiplicity example: the parallel nested in the sequence, with the combine's own identity and message."""error = await self._run_parallel_failure()@@ -132,20 +132,46 @@ class TestLocatedRunFailure:assert error.pipe_code == "analyze"assert error.pipe_stack == ["flow", "analyze"]- report = error.to_error_report()- assert report.error_type == "StuffFactoryError"# The combine's refusal restated with its multiplicity remedy, a StuffFactoryError raised from the# combine's own, is the root fault: of two faults of the same class, the outer one.- assert report.message.startswith(+ operator = error.to_problem(view=ProblemView.OPERATOR)+ assert operator.diagnostics is not None+ assert operator.diagnostics.error_class == "StuffFactoryError"+ assert operator.diagnostics.message.startswith("PipeParallel 'analyze' cannot combine its branch results into its output 'Report'.")+ assert error.message.startswith("Pipe 'analyze' failed (flow → analyze): PipeParallel 'analyze' cannot combine its branch results into its output 'Report'.")- assert "Branch 'gen_ideas' gives result 'ideas' as a list, 'Idea[]', but field 'ideas' of 'Report' holds a single item." in report.message- # The multiplicity next step, since a mismatched combine is the caller's to fix.- assert report.user_action is not None- assert report.user_action.detail.startswith("Branch 'gen_ideas' gives result 'ideas' as a list")-- async def test_caller_facing_root_keeps_its_message_under_strict(self) -> None:- """A caller-facing root fault keeps its own message, located, under STRICT."""+ assert "Branch 'gen_ideas' gives result 'ideas' as a list, 'Idea[]', but field 'ideas' of 'Report' holds a single item." in error.message+ caller = error.to_problem(view=ProblemView.CALLER)+ assert caller.code == CoreCode.PIPE_OUTPUT_MULTIPLICITY+ assert caller.detail == ("Pipe 'analyze' produced an output of the multiplicity 'list', but its output 'ideas' is declared 'single'.")+ # A mismatched combine is the caller's to fix: the caller's step is the code's, the branch to change the operator's message.+ assert caller.next_step.kind == StepKind.CHANGE_METHOD+ assert "Branch 'gen_ideas'" not in str(caller.to_wire())++ async def test_every_branch_whose_multiplicity_differs_is_an_item(self) -> None:+ """Two branches give a list to a single field: the problem names the first, and one item names each."""+ runner = PipelexMTHDSProtocol(pipe_run_mode=PipeRunMode.DRY, execution_config=_dry_mock_config())+ with pytest.raises(PipelineExecutionError) as exc_info:+ await runner.execute(pipe_code="flow", mthds_contents=[LocatedRunFailureTestData.PARALLEL_TWO_MULTIPLICITIES_MTHDS])++ caller = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert caller.code == CoreCode.PIPE_OUTPUT_MULTIPLICITY+ assert caller.detail == "Pipe 'analyze' produced an output of the multiplicity 'list', but its output 'ideas' is declared 'single'."+ assert caller.errors is not None+ assert [(item.code, item.detail) for item in caller.errors] == [+ (+ CoreCode.PIPE_OUTPUT_MULTIPLICITY,+ "Pipe 'analyze' produced an output of the multiplicity 'list', but its output 'ideas' is declared 'single'.",+ ),+ (+ CoreCode.PIPE_OUTPUT_MULTIPLICITY,+ "Pipe 'analyze' produced an output of the multiplicity 'list', but its output 'summary' is declared 'single'.",+ ),+ ]++ async def test_a_method_fault_at_the_root_reads_its_code_s_sentence_located(self) -> None:+ """A root fault of the caller's own method reads its code's sentence, located at the failing pipe."""runner = PipelexMTHDSProtocol()with pytest.raises(PipelineExecutionError) as exc_info:await runner.execute(pipe_code="force_flow", mthds_contents=[LocatedRunFailureTestData.FORCE_MTHDS], inputs={})@@ -153,17 +179,20 @@ class TestLocatedRunFailure:assert error.pipe_code == "force_echo"assert error.pipe_stack == ["force_flow", "force_echo"]-- report = error.to_error_report()- assert report.error_type == "OptionalValueAbsentError"- assert report.caller_facing_message is True- strict_payload = report.to_dict(disclosure_mode=DisclosureMode.STRICT)- assert strict_payload["message"] == report.message- assert strict_payload["message"].startswith("Pipe 'force_echo' failed (force_flow → force_echo): ")- assert "clause" in strict_payload["message"]+ assert error.message.startswith("Pipe 'force_echo' failed (force_flow → force_echo): ")+ assert "clause" in error.message++ caller = error.to_problem(view=ProblemView.CALLER)+ assert caller.code == CoreCode.PIPE_FORCED_INPUT_ABSENT+ assert caller.detail == "Pipe 'force_echo' forces 'clause' with '!', and it was absent in this run."+ assert caller.location is not None+ assert (caller.location.pipe, caller.location.path) == ("force_echo", ["force_flow", "force_echo"])+ operator = error.to_problem(view=ProblemView.OPERATOR)+ assert operator.diagnostics is not None+ assert operator.diagnostics.error_class == "OptionalValueAbsentError"async def test_in_process_orchestrator_adds_nothing(self) -> None:- """Through the in-process bridge, the report and the location are the direct run's; the bridge's sentence is in neither."""+ """Through the in-process bridge, the problem and the location are the direct run's; the bridge's sentence is in neither."""direct_error = await self._run_parallel_failure()bridged_error = await self._run_parallel_failure(pipe_run=_DirectOrchestratorPipeRun())@@ -171,21 +200,23 @@ class TestLocatedRunFailure:assert bridged_error.pipe_code == direct_error.pipe_codeassert bridged_error.pipe_stack == direct_error.pipe_stackassert bridged_error.message == direct_error.message- assert bridged_error.to_error_report() == direct_error.to_error_report()- assert "DIRECT mode" not in bridged_error.to_error_report().message+ for view in (ProblemView.CALLER, ProblemView.OPERATOR):+ assert bridged_error.to_problem(view=view) == direct_error.to_problem(view=view)+ assert "DIRECT mode" not in str(bridged_error.to_problem(view=ProblemView.OPERATOR).to_wire())- async def test_recovered_report_adds_nothing(self) -> None:- """A report recovered across a transport boundary, as the hosted run stores it, reads as the direct run's."""+ async def test_recovered_problem_adds_nothing(self) -> None:+ """A problem recovered across a transport boundary, as the hosted run stores it, reads as the direct run's."""direct_error = await self._run_parallel_failure()location = find_failure_location(error=direct_error)assert isinstance(location, PipeRouterError)- # What a distributed worker's run root stores: the located router error's report.- recovered_report = location.to_error_report()+ # What a distributed worker's run root stores: the located router error's problem, in the operator's view.+ recovered_problem = location.to_problem(view=ProblemView.OPERATOR)- bridged_error = await self._run_parallel_failure(pipe_run=_RecoveredReportPipeRun(recovered_report=recovered_report))+ bridged_error = await self._run_parallel_failure(pipe_run=_RecoveredProblemPipeRun(recovered_problem=recovered_problem))- assert bridged_error.to_error_report() == direct_error.to_error_report()- assert "temporal blocking delivery" not in bridged_error.to_error_report().message+ for view in (ProblemView.CALLER, ProblemView.OPERATOR):+ assert bridged_error.to_problem(view=view) == direct_error.to_problem(view=view)+ assert "temporal blocking delivery" not in str(bridged_error.to_problem(view=ProblemView.OPERATOR).to_wire())assert "temporal blocking delivery" not in bridged_error.messageasync def test_foreign_exception_is_located_as_unexpected_error(self) -> None:@@ -194,8 +225,13 @@ class TestLocatedRunFailure:assert error.pipe_code == "flow"assert error.pipe_stack == ["flow"]- report = error.to_error_report()- assert report.error_type == "PipelexUnexpectedError"- assert report.message == "Pipe 'flow' failed: KeyError: 'boom from a pipe'"- assert report.caller_facing_message is False- assert report.to_dict(disclosure_mode=DisclosureMode.STRICT)["message"] == INTERNAL_ERROR_PLACEHOLDER+ assert error.message == "Pipe 'flow' failed: KeyError: 'boom from a pipe'"+ operator = error.to_problem(view=ProblemView.OPERATOR)+ assert operator.code == CoreCode.RUNTIME_UNEXPECTED+ assert operator.diagnostics is not None+ assert operator.diagnostics.error_class == "PipelexUnexpectedError"+ assert "boom from a pipe" in operator.diagnostics.message+ caller = error.to_problem(view=ProblemView.CALLER)+ assert caller.code == CoreCode.RUNTIME_UNEXPECTED+ assert "boom from a pipe" not in str(caller.to_wire())+ assert "KeyError" not in str(caller.to_wire())diff --git a/tests/integration/pipelex/pipeline/test_pipeline_run_setup_consumer_check.py b/tests/integration/pipelex/pipeline/test_pipeline_run_setup_consumer_check.pyindex 49189b356..bdda01851 100644--- a/tests/integration/pipelex/pipeline/test_pipeline_run_setup_consumer_check.py+++ b/tests/integration/pipelex/pipeline/test_pipeline_run_setup_consumer_check.py@@ -12,11 +12,13 @@ import zipfilefrom pathlib import Pathimport pytest+from mthds.protocol.problem.registry import CoreCode, ProblemDomain-from pipelex.base_exceptions import DisclosureMode, ErrorDomainfrom pipelex.cogt.exceptions import ExtractInputFormatErrorfrom pipelex.config import get_configfrom pipelex.core.stuffs.text_content import TextContent+from pipelex.errors.error_codes import error_code_spec+from pipelex.errors.problem import ProblemViewfrom pipelex.interpreter_hub import get_pipe_routerfrom pipelex.pipe_run.exceptions import PipeRouterErrorfrom pipelex.pipeline.exceptions import PipelineInputFormatUnsupportedError@@ -167,10 +169,12 @@ class TestPipelineRunSetupConsumerCheck:inputs={"transcripts": {"concept": "native.Document", "content": [{"url": docx_url}, {"url": docx_url}, {"url": docx_url}]}},)- report = exc_info.value.to_error_report()- assert report.error_domain == ErrorDomain.INPUT- assert report.http_status == 422- message = exc_info.value.to_error_report().to_dict(disclosure_mode=DisclosureMode.STRICT)["message"]+ problem = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert problem.code == CoreCode.INPUT_FILE_TYPE_UNSUPPORTED+ assert problem.domain == ProblemDomain.INPUT+ assert error_code_spec(CoreCode.INPUT_FILE_TYPE_UNSUPPORTED).status == 422+ assert problem.to_wire().get("params", {}).get("input") == "transcripts[0]", problem.to_wire()+ message = exc_info.value.messagefor index in range(3):assert (f"Input 'transcripts[{index}]' is a Word document (.docx): pipe 'extract_transcript' extracts it "diff --git a/tests/integration/pipelex/pipeline/test_pipeline_run_setup_image_format.py b/tests/integration/pipelex/pipeline/test_pipeline_run_setup_image_format.pyindex bb89ccac7..82f6215dc 100644--- a/tests/integration/pipelex/pipeline/test_pipeline_run_setup_image_format.py+++ b/tests/integration/pipelex/pipeline/test_pipeline_run_setup_image_format.py@@ -10,9 +10,11 @@ import base64from pathlib import Pathimport pytest+from mthds.protocol.problem.registry import CoreCode, ProblemDomain-from pipelex.base_exceptions import ErrorDomain, error_domain_to_http_statusfrom pipelex.config import get_config+from pipelex.errors.error_codes import error_code_spec+from pipelex.errors.problem import ProblemViewfrom pipelex.pipeline.exceptions import PipelineInputNotAnImageErrorfrom pipelex.pipeline.pipeline_run_setup import pipeline_run_setup@@ -67,11 +69,12 @@ class TestPipelineRunSetupImageFormat:},)- report = exc_info.value.to_error_report()- assert report.error_domain == ErrorDomain.INPUT- assert error_domain_to_http_status(report.error_domain) == 422- assert report.http_status == 422- assert f"Input '{refused_input}' expects an image, but the file is a PDF document (.pdf)" in report.message+ problem = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert problem.code == CoreCode.INPUT_FILE_TYPE_UNSUPPORTED+ assert problem.domain == ProblemDomain.INPUT+ assert error_code_spec(CoreCode.INPUT_FILE_TYPE_UNSUPPORTED).status == 422+ assert problem.to_wire().get("params", {}).get("input") == refused_input, problem.to_wire()+ assert f"Input '{refused_input}' expects an image, but the file is a PDF document (.pdf)" in exc_info.value.messageasync def test_images_pass_setup(self):execution_config = get_config().interpreter.pipeline_execution.with_execution_overrides(generate_graph=False)diff --git a/tests/integration/pipelex/pipeline/test_render_time_template_refusals.py b/tests/integration/pipelex/pipeline/test_render_time_template_refusals.pyindex 4988b4e21..c6c5aea88 100644--- a/tests/integration/pipelex/pipeline/test_render_time_template_refusals.py+++ b/tests/integration/pipelex/pipeline/test_render_time_template_refusals.py@@ -4,7 +4,8 @@ Jinja2 compiles a filter or a test inside a branch to a lookup that only fails wonly 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 answered500 "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.+template's field and the filter Jinja2 refused for the operator, and the code's sentence for the caller, which never quotes+the template's text."""from __future__ import annotations@@ -13,10 +14,11 @@ import jsonfrom typing import TYPE_CHECKING, Anyimport pytest-from mthds.protocol.problem.registry import CoreCode+from mthds.protocol.problem.registry import CoreCode, StepKind-from pipelex.base_exceptions import INTERNAL_ERROR_PLACEHOLDER, DisclosureModefrom pipelex.config import get_config+from pipelex.errors.error_codes import error_code_spec+from pipelex.errors.problem import ProblemViewfrom pipelex.pipeline.exceptions import PipelineExecutionErrorfrom pipelex.pipeline.runner import PipelexMTHDSProtocolfrom pipelex.system.pipe_run_mode import PipeRunMode@@ -41,23 +43,22 @@ async def _failed_run(*, pipe_code: str, bundle: str, inputs: dict[str, Any], pireturn 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+def _assert_is_the_refusal(*, error: PipelineExecutionError, message: str, detail: str, pipe_code: str) -> None:+ """The caller reads the code's sentence, located on the pipe; the refusal's own message is the operator's diagnostics."""+ caller = error.to_problem(view=ProblemView.CALLER)+ assert caller.code == CoreCode.METHOD_TEMPLATE_INVALID, caller.to_wire()+ assert caller.detail == detail, caller.to_wire()+ assert caller.location is not None+ assert caller.location.pipe == pipe_code+ assert caller.next_step.kind == StepKind.CHANGE_METHOD+ assert error_code_spec(CoreCode.METHOD_TEMPLATE_INVALID).status == 422+ operator = error.to_problem(view=ProblemView.OPERATOR)+ assert operator.diagnostics is not None+ assert operator.diagnostics.message == message# 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)+ caller_wire = json.dumps(caller.to_wire())+ assert RenderTimeTemplateTestData.TEMPLATE_TEXT not in caller_wire+ assert "{%" not in caller_wire@pytest.mark.asyncio(loop_scope="class")@@ -73,8 +74,9 @@ class TestRenderTimeTemplateRefusals:_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}",+ message=f"PipeCondition 'route_parcel': its expression cannot render: {_UNKNOWN_FILTER_FAULT}",+ detail=f"The template 'expression' of pipe 'route_parcel' is invalid ({_UNKNOWN_FILTER_FAULT}).",+ pipe_code="route_parcel",)@pytest.mark.parametrize("prompt_field", ["prompt", "system_prompt"])@@ -89,12 +91,13 @@ class TestRenderTimeTemplateRefusals:_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}",+ message=f"PipeLLM 'summarize': its {prompt_field} cannot render: {_UNKNOWN_FILTER_FAULT}",+ detail=f"The template '{prompt_field}' of pipe 'summarize' is invalid ({_UNKNOWN_FILTER_FAULT}).",+ pipe_code="summarize",)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."""+ """The structure prompt is the deployment's template, rendered in the step: `runtime.unexpected`, a 500 whose message is the operator's."""mocker.patch.dict(get_config().inference.llm.generic_templates,{"output_structure_prompt": RenderTimeTemplateTestData.BROKEN_STRUCTURE_PROMPT},@@ -107,11 +110,13 @@ class TestRenderTimeTemplateRefusals: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+ caller = error.to_problem(view=ProblemView.CALLER)+ assert caller.code == CoreCode.RUNTIME_UNEXPECTED+ assert caller.diagnostics is None+ assert error_code_spec(CoreCode.RUNTIME_UNEXPECTED).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)+ assert RenderTimeTemplateTestData.UNKNOWN_STRUCTURE_FILTER not in json.dumps(caller.to_wire())+ operator = error.to_problem(view=ProblemView.OPERATOR)+ assert operator.diagnostics is not None+ diagnosed_classes = {operator.diagnostics.error_class, *(cause.error_class for cause in operator.diagnostics.causes or [])}+ assert "Jinja2TemplateInvalidError" in diagnosed_classesdiff --git a/tests/integration/pipelex/pipeline/test_resolve_bundle.py b/tests/integration/pipelex/pipeline/test_resolve_bundle.pyindex 5bf1d710c..b869ffaa7 100644--- a/tests/integration/pipelex/pipeline/test_resolve_bundle.py+++ b/tests/integration/pipelex/pipeline/test_resolve_bundle.py@@ -10,10 +10,14 @@ from collections.abc import Callableimport pytestfrom mthds.package.manifest.schema import MTHDS_STANDARD_VERSION+from mthds.protocol.problem.registry import CoreCodefrom pytest_mock import MockerFixturefrom pipelex.base_exceptions import PipelexUnexpectedError+from pipelex.errors.problem import ProblemView+from pipelex.errors.unsupported_reasons import ADDRESS_DEPENDENCY_UNSUPPORTED_REASONfrom pipelex.interpreter_hub import clear_current_library, get_current_library_id_or_none, get_library_manager+from pipelex.libraries.pipe.exceptions import PipeLibraryErrorfrom pipelex.methods.address_dependencies import ADDRESS_DEPENDENCY_REFUSAL_MARKERfrom pipelex.pipeline.exceptions import ValidateBundleErrorfrom pipelex.pipeline.resolve_bundle import resolve_crate_from_contents@@ -69,8 +73,7 @@ class TestResolveCrateFromContents:with pytest.raises(ValidateBundleError) as exc_info:resolve_crate_from_contents(mthds_contents=[INVALID_MTHDS], mthds_sources=["broken.mthds"])- error_report = exc_info.value.to_error_report()- assert error_report.validation_errors, "the shared builder must produce structured validation-error items"+ assert exc_info.value.validation_error_items(), "the shared builder must produce structured validation-error items"assert teardown_spy.call_count == teardown_calls_before + 1opened_library_id, _ = open_library_spy.spy_return@@ -92,10 +95,15 @@ class TestResolveCrateFromContents:side_effect=AssertionError("in-memory resolve must not discover installed methods or fetch by address"),)- with pytest.raises(ValidateBundleError, match=ADDRESS_DEPENDENCY_REFUSAL_MARKER) as exc_info:+ with pytest.raises(PipeLibraryError) as exc_info:resolve_crate_from_contents(mthds_contents=[ADDRESS_DEPENDENCY_MTHDS], mthds_sources=["host.mthds"])discovery.assert_not_called()- # The verdict's items carry the marker a hosted run tells this refusal apart by, on a server answering it.- validation_errors = exc_info.value.to_error_report().validation_errors or []- assert any(ADDRESS_DEPENDENCY_REFUSAL_MARKER in item.message for item in validation_errors)+ # The request is what pipe-io cannot serve, not the method, so the refusal is no verdict: its problem carries the+ # code and the reason a hosted run tells this refusal apart by.+ assert not isinstance(exc_info.value, ValidateBundleError)+ problem = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert problem.code == CoreCode.REQUEST_UNSUPPORTED+ assert problem.to_wire().get("params") == {"field": "files", "reason": ADDRESS_DEPENDENCY_UNSUPPORTED_REASON}+ # The operator's message quotes the dependency after the marker the tree resolution's verdict items carry too.+ assert f"{ADDRESS_DEPENDENCY_REFUSAL_MARKER} 'github.com/org/pkg'" in exc_info.value.messagediff --git a/tests/integration/pipelex/pipeline/test_resolve_crate_from_method_dir.py b/tests/integration/pipelex/pipeline/test_resolve_crate_from_method_dir.pyindex 1b1554421..e1112cb4e 100644--- a/tests/integration/pipelex/pipeline/test_resolve_crate_from_method_dir.py+++ b/tests/integration/pipelex/pipeline/test_resolve_crate_from_method_dir.py@@ -15,6 +15,7 @@ from mthds.method_tree.digest import digest_of_contentsfrom mthds.package.manifest.schema import MTHDS_STANDARD_VERSIONfrom pytest_mock import MockerFixture+from pipelex.errors.problem import ProblemViewfrom pipelex.interpreter_hub import clear_current_library, get_current_library_id_or_none, get_library_managerfrom pipelex.libraries.written_trees import WRITTEN_METHOD_TREES, write_method_treefrom pipelex.methods.address_dependencies import ADDRESS_DEPENDENCY_REFUSAL_MARKER@@ -85,11 +86,11 @@ class TestResolveCrateFromMethodDir:resolve_crate_from_method_dir(method_dir=method_dir)if expects_items:- validation_errors = exc_info.value.to_error_report().validation_errors or []+ validation_errors = exc_info.value.validation_error_items()assert validation_errors, "the shared builder must produce structured validation-error items"assert validation_errors[0].source == "broken.mthds"- # Nothing of the verdict names the directory the host wrote the tree to, the report's own message included.- report_text = exc_info.value.to_error_report().model_dump_json()+ # Nothing of the verdict names the directory the host wrote the tree to, the operator's diagnostics included.+ report_text = str(exc_info.value.to_problem(view=ProblemView.OPERATOR).to_wire())assert str(tmp_path) not in report_textassert str(tmp_path.resolve()) not in report_textelse:@@ -105,9 +106,8 @@ class TestResolveCrateFromMethodDir:with _written_tree(destination=tmp_path / "method", files=files) as method_dir, pytest.raises(ValidateBundleError) as exc_info:resolve_crate_from_method_dir(method_dir=method_dir)- report = exc_info.value.to_error_report()- assert "['first.mthds', 'second.mthds']" in report.message- report_text = report.model_dump_json()+ assert "['first.mthds', 'second.mthds']" in exc_info.value.message+ report_text = str(exc_info.value.to_problem(view=ProblemView.OPERATOR).to_wire())assert str(tmp_path) not in report_textassert str(tmp_path.resolve()) not in report_text@@ -130,7 +130,7 @@ class TestResolveCrateFromMethodDir:discovery.assert_not_called()# The unresolved dependency `/v1/validate` reports, located on the pipe calling it, in the words of the contents# core's refusal, whose marker a hosted run tells it apart by.- validation_errors = exc_info.value.to_error_report().validation_errors or []+ validation_errors = exc_info.value.validation_error_items()assert len(validation_errors) == 1, validation_errorsitem = validation_errors[0]assert item.error_type == PipeValidationErrorType.UNRESOLVED_PACKAGE_DEPENDENCYdiff --git a/tests/integration/pipelex/pipeline/test_run_fault_views.py b/tests/integration/pipelex/pipeline/test_run_fault_views.pynew file mode 100644index 000000000..75ca7f489--- /dev/null+++ b/tests/integration/pipelex/pipeline/test_run_fault_views.py@@ -0,0 +1,224 @@+from __future__ import annotations++from typing import TYPE_CHECKING, Any++import pytest+from kajson.kajson_manager import KajsonManager+from mthds.protocol.problem.registry import CoreCode, ProblemDomain, StepKind+from pydantic import model_validator++from pipelex.cogt.exceptions import InferenceErrorCategory, LLMCompletionError+from pipelex.cogt.llm.llm_setting import LLMSetting+from pipelex.config import get_config+from pipelex.core.stuffs.structured_content import StructuredContent+from pipelex.core.stuffs.text_content import TextContent+from pipelex.errors.error_codes import error_code_spec+from pipelex.errors.problem import PipelexProblem, ProblemView+from pipelex.pipeline.exceptions import PipelineExecutionError+from pipelex.pipeline.runner import PipelexMTHDSProtocol+from pipelex.runtime_hub import get_model_deck+from pipelex.system.pipe_run_mode import PipeRunMode+from tests.integration.pipelex.pipeline.test_data import LocatedRunFailureTestData, RunFaultViewsTestData++if TYPE_CHECKING:+ from pytest_mock import MockerFixture+ from typing_extensions import Self+++class RunFaultViewsValidatedReview(StructuredContent):+ """Stands in for a structure class a deployment loads from its own library, whose validator writes its own text."""++ idea: TextContent+ overview: TextContent++ @model_validator(mode="after")+ def refuse_by_deployment_rule(self) -> Self:+ msg = RunFaultViewsTestData.DEPLOYMENT_VALIDATOR_TEXT+ raise ValueError(msg)+++def _views(error: PipelineExecutionError) -> tuple[PipelexProblem, PipelexProblem]:+ """The run failure's problem as a caller reads it, then as the operator does."""+ return error.to_problem(view=ProblemView.CALLER), error.to_problem(view=ProblemView.OPERATOR)+++async def _run_failing(+ *,+ pipe_code: str,+ mthds_content: str,+ inputs: dict[str, Any],+ pipe_run_mode: PipeRunMode = PipeRunMode.LIVE,+) -> PipelineExecutionError:+ if pipe_run_mode.is_dry:+ execution_config = get_config().interpreter.pipeline_execution.with_execution_overrides(generate_graph=False, mock_inputs=True)+ runner = PipelexMTHDSProtocol(pipe_run_mode=pipe_run_mode, execution_config=execution_config)+ else:+ runner = PipelexMTHDSProtocol()+ with pytest.raises(PipelineExecutionError) as exc_info:+ await runner.execute(pipe_code=pipe_code, mthds_contents=[mthds_content], inputs=inputs)+ return exc_info.value++[email protected](loop_scope="class")+class TestRunFaultViews:+ async def test_parallel_combine_mismatch_is_the_methods_fault(self) -> None:+ """A branch declared `Idea[]` feeding a single field: the method's fault, located at `analyze`, with its remedy."""+ error = await _run_failing(+ pipe_code="flow",+ mthds_content=LocatedRunFailureTestData.PARALLEL_MTHDS,+ inputs={},+ pipe_run_mode=PipeRunMode.DRY,+ )++ caller, operator = _views(error)+ assert caller.code == CoreCode.PIPE_OUTPUT_MULTIPLICITY+ assert caller.domain == ProblemDomain.METHOD+ assert error_code_spec(CoreCode.PIPE_OUTPUT_MULTIPLICITY).status == 422+ assert caller.detail == "Pipe 'analyze' produced an output of the multiplicity 'list', but its output 'ideas' is declared 'single'."+ assert caller.next_step.kind == StepKind.CHANGE_METHOD+ assert caller.next_step.detail == "Declare the output 'ideas' as 'list', or make pipe 'analyze' produce 'single'."+ assert caller.location is not None+ assert caller.location.as_wire() == {"pipe": "analyze", "path": ["flow", "analyze"]}+ assert caller.diagnostics is None+ # The operator reads the combine's own restatement, with the remedy naming the branch to change.+ assert operator.diagnostics is not None+ assert operator.diagnostics.error_class == "StuffFactoryError"+ assert operator.diagnostics.message.startswith("PipeParallel 'analyze' cannot combine its branch results into its output 'Report'.")+ assert "make branch 'gen_ideas' output a single 'Idea'" in operator.diagnostics.message++ async def test_parallel_combine_refusal_no_multiplicity_explains_is_the_methods_fault(self) -> None:+ """A single `Idea` branch feeding a list of plain texts: no multiplicity to change, the combine's refusal of the field."""+ error = await _run_failing(+ pipe_code="flow",+ mthds_content=RunFaultViewsTestData.PARALLEL_NO_MULTIPLICITY_MTHDS,+ inputs={},+ pipe_run_mode=PipeRunMode.DRY,+ )++ caller, operator = _views(error)+ assert caller.code == CoreCode.PIPE_OUTPUT_INVALID+ assert caller.domain == ProblemDomain.METHOD+ assert caller.detail == "Pipe 'analyze' produced an output that does not fit the concept 'Review', at the fields ideas."+ assert caller.params is not None+ assert caller.params.as_wire() == {"pipe": "analyze", "output_concept": "Review", "fields": ["ideas"]}+ assert caller.location is not None+ assert caller.location.as_wire() == {"pipe": "analyze", "path": ["flow", "analyze"]}+ assert operator.diagnostics is not None+ assert operator.diagnostics.message.startswith("Error combining stuffs for concept Review")++ async def test_a_deployment_validators_text_is_the_operators_alone(self) -> None:+ """A deployment's structure class refusing the combine: its validator's text reaches the operator, never the caller."""+ # The process-global registry, which the run's own library is seeded from, as a deployment's Python module would.+ registry = KajsonManager.get_class_registry()+ registry.register_class(RunFaultViewsValidatedReview)+ try:+ error = await _run_failing(+ pipe_code="flow",+ mthds_content=RunFaultViewsTestData.DEPLOYMENT_VALIDATOR_MTHDS,+ inputs={"topic": "cats"},+ )+ finally:+ registry.unregister_class(RunFaultViewsValidatedReview)++ caller, operator = _views(error)+ validator_text = RunFaultViewsTestData.DEPLOYMENT_VALIDATOR_TEXT+ assert validator_text not in str(caller.to_wire())+ assert "DR-7" not in str(caller.to_wire())+ # The caller still reads which pipe, which concept and which fields, in the code's own sentences.+ assert caller.code == CoreCode.PIPE_OUTPUT_INVALID+ assert caller.detail == (+ "Pipe 'analyze' produced an output that does not fit the concept 'RunFaultViewsValidatedReview', at the fields idea, overview."+ )+ assert caller.next_step.kind == StepKind.CHANGE_METHOD+ assert caller.location is not None+ assert caller.location.pipe == "analyze"+ assert operator.diagnostics is not None+ assert validator_text in operator.diagnostics.message++ async def test_missing_required_input_is_the_callers_fault(self) -> None:+ """A run missing a required input: the input domain, a sentence and a next step naming the input."""+ error = await _run_failing(pipe_code="greet_flow", mthds_content=RunFaultViewsTestData.MISSING_INPUT_MTHDS, inputs={})++ caller, operator = _views(error)+ assert caller.code == CoreCode.INPUT_MISSING+ assert caller.domain == ProblemDomain.INPUT+ assert error_code_spec(CoreCode.INPUT_MISSING).status == 422+ assert caller.detail == "The request does not give the input 'name', which the method requires."+ assert caller.next_step.kind == StepKind.CHANGE_INPUT+ assert caller.next_step.detail == "Add the input 'name' to the request, then send it again."+ assert caller.location is not None+ assert caller.location.as_wire() == {"pipe": "greet_flow", "path": ["greet_flow"]}+ assert operator.diagnostics is not None+ assert operator.diagnostics.error_class == "PipeRunInputsError"++ async def test_model_only_the_method_names_is_the_methods_fault(self) -> None:+ """A step naming, in an inline setting, a model no entry of the deck names: the method's fault, naming the model."""+ error = await _run_failing(+ pipe_code="two_steps",+ mthds_content=LocatedRunFailureTestData.MODEL_MTHDS,+ inputs={"topic": "cats"},+ )++ caller, _ = _views(error)+ unserved_handle = LocatedRunFailureTestData.UNSERVED_MODEL_HANDLE+ assert caller.code == CoreCode.MODEL_UNKNOWN+ assert caller.domain == ProblemDomain.METHOD+ assert caller.detail == f"The method names the llm model '{unserved_handle}', which no catalog knows."+ assert caller.next_step.kind == StepKind.CHANGE_MODEL+ assert caller.location is not None+ assert caller.location.as_wire() == {"pipe": "summarize", "path": ["two_steps", "summarize"]}+ # Provider and model attribution are diagnostics, which no caller reads, whoever's fault it is.+ assert caller.diagnostics is None++ @pytest.mark.parametrize(+ ("_topic", "model_reference"),+ [+ ("preset", f"${RunFaultViewsTestData.DECK_PRESET}"),+ ("alias", f"@{RunFaultViewsTestData.DECK_ALIAS}"),+ ],+ )+ async def test_model_the_deck_names_but_does_not_serve_is_the_operators(self, mocker: MockerFixture, _topic: str, model_reference: str) -> None:+ """A model a preset or an alias of the deck names, which the deployment does not serve, is the operator's to fix."""+ model_deck = get_model_deck()+ unserved_handle = RunFaultViewsTestData.DECK_NAMED_UNSERVED_HANDLE+ mocker.patch.dict(model_deck.llm_presets, {RunFaultViewsTestData.DECK_PRESET: LLMSetting(model=unserved_handle, temperature=0.2)})+ mocker.patch.dict(model_deck.llm_aliases, {RunFaultViewsTestData.DECK_ALIAS: unserved_handle})+ mthds_content = RunFaultViewsTestData.DECK_NAMED_MODEL_MTHDS.replace(RunFaultViewsTestData.MODEL_REFERENCE_SLOT, model_reference)++ error = await _run_failing(pipe_code="summarize_flow", mthds_content=mthds_content, inputs={"topic": "cats"})++ assert error.pipe_code == "summarize"+ caller, operator = _views(error)+ assert caller.code == CoreCode.MODEL_UNAVAILABLE+ assert caller.domain == ProblemDomain.OPERATOR+ assert error_code_spec(CoreCode.MODEL_UNAVAILABLE).status == 501+ # The caller is told what it can do: choose another model, or ask the operator to serve this one.+ assert caller.next_step.kind == StepKind.CHANGE_MODEL+ assert operator.next_step.kind == StepKind.FIX_CONFIGURATION+ assert operator.diagnostics is not None+ assert operator.diagnostics.message == f"Model handle '{unserved_handle}' was not found in the model deck."+ assert caller.diagnostics is None++ async def test_model_output_that_does_not_fit_its_structure_is_no_caller_text(self, mocker: MockerFixture) -> None:+ """A model output the structure refuses, after the re-asks: its text, which quotes the model, stays the operator's."""+ unfit_output_error = LLMCompletionError(+ "Structured generation via 'instructor' failed trying to generate schema: Verdict with error: 1 validation error",+ error_category=InferenceErrorCategory.UNKNOWN,+ )+ fake_content_generator = mocker.MagicMock()+ fake_content_generator.make_object = mocker.AsyncMock(side_effect=unfit_output_error)+ mocker.patch("pipelex.kernel.llm_ops.get_content_generator", return_value=fake_content_generator)++ error = await _run_failing(+ pipe_code="judge_flow",+ mthds_content=RunFaultViewsTestData.STRUCTURED_OUTPUT_MTHDS,+ inputs={"claim": "The sky is green."},+ )++ assert error.pipe_code == "judge"+ caller, operator = _views(error)+ assert "instructor" not in str(caller.to_wire())+ assert caller.location is not None+ assert caller.location.as_wire() == {"pipe": "judge", "path": ["judge_flow", "judge"]}+ assert operator.diagnostics is not None+ assert operator.diagnostics.error_class == "LLMCompletionError"diff --git a/tests/integration/pipelex/pipeline/test_run_path_bundle_verdict.py b/tests/integration/pipelex/pipeline/test_run_path_bundle_verdict.pyindex 7be798f83..98be2fbec 100644--- a/tests/integration/pipelex/pipeline/test_run_path_bundle_verdict.py+++ b/tests/integration/pipelex/pipeline/test_run_path_bundle_verdict.py@@ -2,15 +2,15 @@A run loads its bundle before any pipe runs, and that load already refuses an invalid method. These testspin that the refusal reaches the caller the way validating the same bundle reports it: a-``ValidateBundleError`` carrying the same located ``validation_errors`` items, whose STRICT projection is-an HTTP 422 that keeps them. Before, each refusal reached a host in the raw class of whichever check+``ValidateBundleError`` carrying the same located ``validation_errors`` items, whose problem is+``method.invalid``, an HTTP 422 listing one item per validation item. Before, each refusal reached a host in the raw class of whichever checkmade it: a misspelled concept as a ``ConceptLibraryError`` answered 500, a wiring mismatch as a``PipeValidationError`` (a ``ValueError``) answered by the catch-all 500, a TOML fault as a 422 with noitems, and a check firing inside a pipe's pydantic validator as a ``runtime`` ``PipeExecutionError``reading "Input validation failed".- **Parity.** For each bundle, ``pipeline_run_setup`` raises the verdict with exactly the items- ``validate_bundle`` produces, and the STRICT projection is a 422 carrying them.+ ``validate_bundle`` produces, and its caller's problem is the one the validation gives.- **The model-validator case.** The runner's ``execute`` answers it with the verdict, not with the``runtime`` input-validation failure.- **The unknown entry pipe** is not a bundle fault: it still raises its own ``PipeNotFoundError``.@@ -23,9 +23,11 @@ from pathlib import Pathfrom typing import Any, NamedTupleimport pytest+from mthds.protocol.problem.registry import CoreCode-from pipelex.base_exceptions import DisclosureModefrom pipelex.config import get_config+from pipelex.errors.error_codes import error_code_spec+from pipelex.errors.problem import ProblemViewfrom pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.libraries.exceptions import LibraryErrorfrom pipelex.libraries.pipe.exceptions import PipeNotFoundError@@ -156,10 +158,11 @@ async def _run_setup(**kwargs: Any) -> None:)-def _strict_items(verdict: ValidateBundleError) -> list[dict[str, Any]]:- strict_payload = verdict.to_error_report().to_dict(disclosure_mode=DisclosureMode.STRICT)- strict_items: list[dict[str, Any]] = strict_payload["validation_errors"]- return strict_items+def _caller_problem_items(verdict: ValidateBundleError) -> list[dict[str, Any]]:+ problem = verdict.to_problem(view=ProblemView.CALLER)+ assert problem.code == CoreCode.METHOD_INVALID+ problem_items: list[dict[str, Any]] = problem.to_wire()["errors"]+ return problem_items@pytest.mark.asyncio(loop_scope="class")@@ -171,21 +174,19 @@ class TestRunPathBundleVerdict:with pytest.raises(ValidateBundleError) as raised:await _run_setup(mthds_contents=[case.bundle])- run_report = raised.value.to_error_report()- validate_items = validate_verdict.to_error_report().validation_errors+ validate_items = validate_verdict.validation_error_items()assert validate_items, "the validate path gives at least one item for an invalid bundle"- assert run_report.validation_errors == validate_items- assert run_report.http_status == 422- strict_payload = run_report.to_dict(disclosure_mode=DisclosureMode.STRICT)- assert strict_payload["error_type"] == "ValidateBundleError"- assert strict_payload["error_domain"] == "input"- assert _strict_items(raised.value) == _strict_items(validate_verdict)+ assert raised.value.validation_error_items() == validate_items+ assert error_code_spec(CoreCode.METHOD_INVALID).status == 422+ run_problem_items = _caller_problem_items(raised.value)+ assert len(run_problem_items) == len(validate_items)+ assert run_problem_items == _caller_problem_items(validate_verdict)async def test_misspelled_concept_is_located_on_the_pipe_and_the_field(self) -> None:with pytest.raises(ValidateBundleError) as raised:await _run_setup(mthds_contents=[_MISSPELLED_CONCEPT_BUNDLE])- items = raised.value.to_error_report().validation_errors or []+ items = raised.value.validation_error_items() or [](item,) = itemsassert item.error_type == PipeValidationErrorType.UNRESOLVED_CONCEPTassert item.pipe_code == "write_tide_notice"@@ -201,7 +202,7 @@ class TestRunPathBundleVerdict:await runner.execute(mthds_contents=[_MODEL_VALIDATOR_FAULT_BUNDLE])assert not isinstance(raised.value, PipeExecutionError)- items = raised.value.to_error_report().validation_errors or []+ items = raised.value.validation_error_items() or []assert any("format_harbour_tide_notice_nowhere_registered" in item.message for item in items)async def test_unknown_entry_pipe_keeps_its_own_class(self) -> None:@@ -217,14 +218,14 @@ class TestRunPathBundleVerdict:with pytest.raises(ValidateBundleError) as raised:await _run_setup(library_dirs=[str(tmp_path)], pipe_code="write_tide_notice", library_dirs_are_callers=True)- items = raised.value.to_error_report().validation_errors or []+ items = raised.value.validation_error_items() 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 == "write_tide_notice" for item in concept_items)# Validating the same file with the same library directory gives the same items.with pytest.raises(ValidateBundleError) as validated:await validate_bundle(mthds_file_path=bundle_path, library_dirs=[tmp_path])- assert items == validated.value.to_error_report().validation_errors+ assert items == validated.value.validation_error_items()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"@@ -234,4 +235,4 @@ class TestRunPathBundleVerdict:await _run_setup(library_dirs=[str(tmp_path)], pipe_code="write_tide_notice")assert isinstance(raised.value.__cause__, LibraryError)- assert raised.value.to_error_report().code == PipelexErrorCode.CONFIG_INVALID+ assert raised.value.to_problem(view=ProblemView.CALLER).code == PipelexErrorCode.CONFIG_INVALIDdiff --git a/tests/integration/pipelex/pipeline/test_strict_method_faults.py b/tests/integration/pipelex/pipeline/test_strict_method_faults.pydeleted file mode 100644index a6d24d404..000000000--- a/tests/integration/pipelex/pipeline/test_strict_method_faults.py+++ /dev/null@@ -1,180 +0,0 @@-from __future__ import annotations--from typing import TYPE_CHECKING, Any--import pytest--from pipelex.base_exceptions import INTERNAL_ERROR_PLACEHOLDER, DisclosureMode-from pipelex.cogt.exceptions import InferenceErrorCategory, LLMCompletionError-from pipelex.cogt.llm.llm_setting import LLMSetting-from pipelex.config import get_config-from pipelex.pipeline.exceptions import PipelineExecutionError-from pipelex.pipeline.runner import PipelexMTHDSProtocol-from pipelex.runtime_hub import get_model_deck-from pipelex.system.pipe_run_mode import PipeRunMode-from tests.integration.pipelex.pipeline.test_data import LocatedRunFailureTestData, StrictMethodFaultsTestData--if TYPE_CHECKING:- from pytest_mock import MockerFixture---def _strict_problem_document(error: PipelineExecutionError) -> dict[str, Any]:- """The body a hosted runner answers with: the run failure's report, projected under STRICT disclosure."""- return error.to_error_report().to_problem_document(disclosure_mode=DisclosureMode.STRICT)---async def _run_failing(- *,- pipe_code: str,- mthds_content: str,- inputs: dict[str, Any],- pipe_run_mode: PipeRunMode = PipeRunMode.LIVE,-) -> PipelineExecutionError:- if pipe_run_mode.is_dry:- execution_config = get_config().interpreter.pipeline_execution.with_execution_overrides(generate_graph=False, mock_inputs=True)- runner = PipelexMTHDSProtocol(pipe_run_mode=pipe_run_mode, execution_config=execution_config)- else:- runner = PipelexMTHDSProtocol()- with pytest.raises(PipelineExecutionError) as exc_info:- await runner.execute(pipe_code=pipe_code, mthds_contents=[mthds_content], inputs=inputs)- return exc_info.value--[email protected](loop_scope="class")-class TestStrictMethodFaults:- async def test_parallel_combine_mismatch_is_the_callers_fault(self) -> None:- """A branch declared `Idea[]` feeding a single field: HTTP 422, the input domain, and the combine's reason at `analyze`."""- error = await _run_failing(- pipe_code="flow",- mthds_content=LocatedRunFailureTestData.PARALLEL_MTHDS,- inputs={},- pipe_run_mode=PipeRunMode.DRY,- )-- document = _strict_problem_document(error)- assert document["status"] == 422- assert document["error_domain"] == "input"- assert document["error_type"] == "StuffFactoryError"- assert document["detail"] != INTERNAL_ERROR_PLACEHOLDER- # The multiplicity next step (the combine's refusal restated with its remedy) is what a STRICT caller reads.- assert document["detail"].startswith(- "Pipe 'analyze' failed (flow → analyze): PipeParallel 'analyze' cannot combine its branch results into its output 'Report'."- )- next_step = "Branch 'gen_ideas' gives result 'ideas' as a list, 'Idea[]', but field 'ideas' of 'Report' holds a single item."- assert next_step in document["detail"]- assert document["user_action"]["kind"] == "change_input"- assert document["user_action"]["detail"].startswith(next_step)- assert "make branch 'gen_ideas' output a single 'Idea'" in document["user_action"]["detail"]-- async def test_parallel_combine_refusal_no_multiplicity_explains_is_the_callers_fault(self) -> None:- """A single `Idea` branch feeding a list of plain texts: no multiplicity to change, the combine's own refusal at 422."""- error = await _run_failing(- pipe_code="flow",- mthds_content=StrictMethodFaultsTestData.PARALLEL_NO_MULTIPLICITY_MTHDS,- inputs={},- pipe_run_mode=PipeRunMode.DRY,- )-- document = _strict_problem_document(error)- assert document["status"] == 422- assert document["error_domain"] == "input"- assert document["error_type"] == "StuffFactoryError"- # The combine's own refusal, kept under STRICT, with no multiplicity advice that could not make it fit.- assert document["detail"].startswith("Pipe 'analyze' failed (flow → analyze): Error combining stuffs for concept Review")- assert "cannot combine its branch results" not in document["detail"]- assert "gives result" not in document["detail"]- assert document["user_action"] == {- "kind": "change_input",- "detail": (- "Change the method so that each branch of PipeParallel 'analyze' produces what the field of "- "'Review' it feeds expects, a list only where that field is a list, "- "and so that every required field is fed by a branch."- ),- }-- async def test_missing_required_input_is_the_callers_fault(self) -> None:- """A run missing a required input: HTTP 422, with a message and a next step naming the input."""- error = await _run_failing(pipe_code="greet_flow", mthds_content=StrictMethodFaultsTestData.MISSING_INPUT_MTHDS, inputs={})-- document = _strict_problem_document(error)- assert document["status"] == 422- assert document["error_domain"] == "input"- assert document["error_type"] == "PipeRunInputsError"- assert document["detail"] == "Pipe 'greet_flow' failed: Live run of PipeSequence 'greet_flow': missing required inputs: name."- assert document["user_action"] == {"kind": "change_input", "detail": "Provide the missing required inputs of 'greet_flow': name."}-- async def test_model_only_the_method_names_is_the_callers_fault(self) -> None:- """A step naming, in an inline setting, a model no entry of the deck names: HTTP 422, its reason, and a next step naming the model."""- error = await _run_failing(- pipe_code="two_steps",- mthds_content=LocatedRunFailureTestData.MODEL_MTHDS,- inputs={"topic": "cats"},- )-- document = _strict_problem_document(error)- unserved_handle = LocatedRunFailureTestData.UNSERVED_MODEL_HANDLE- assert document["status"] == 422- assert document["error_domain"] == "input"- assert document["error_type"] == "ModelNotFoundError"- assert (- document["detail"]- == f"Pipe 'summarize' failed (two_steps → summarize): Model handle '{unserved_handle}' was not found in the model deck."- )- assert document["user_action"] == {"kind": "change_model", "detail": f"Change the model '{unserved_handle}' to an LLM the model deck serves."}- # Provider and model attribution never reach a STRICT caller, whoever's fault it is.- assert "model" not in document-- @pytest.mark.parametrize(- ("_topic", "model_reference"),- [- ("preset", f"${StrictMethodFaultsTestData.DECK_PRESET}"),- ("alias", f"@{StrictMethodFaultsTestData.DECK_ALIAS}"),- ],- )- async def test_model_the_deck_names_but_does_not_serve_stays_redacted(self, mocker: MockerFixture, _topic: str, model_reference: str) -> None:- """A model a preset or an alias of the deck names, which the deployment does not serve, is not the caller's fault."""- model_deck = get_model_deck()- unserved_handle = StrictMethodFaultsTestData.DECK_NAMED_UNSERVED_HANDLE- mocker.patch.dict(model_deck.llm_presets, {StrictMethodFaultsTestData.DECK_PRESET: LLMSetting(model=unserved_handle, temperature=0.2)})- mocker.patch.dict(model_deck.llm_aliases, {StrictMethodFaultsTestData.DECK_ALIAS: unserved_handle})- mthds_content = StrictMethodFaultsTestData.DECK_NAMED_MODEL_MTHDS.replace(StrictMethodFaultsTestData.MODEL_REFERENCE_SLOT, model_reference)-- error = await _run_failing(pipe_code="summarize_flow", mthds_content=mthds_content, inputs={"topic": "cats"})-- assert error.pipe_code == "summarize"- report = error.to_error_report()- assert (- report.message- == f"Pipe 'summarize' failed (summarize_flow → summarize): Model handle '{unserved_handle}' was not found in the model deck."- )- document = _strict_problem_document(error)- assert document["status"] == 500- assert document["error_domain"] == "config"- assert document["error_type"] == "ModelNotFoundError"- assert document["detail"] == INTERNAL_ERROR_PLACEHOLDER- assert "user_action" not in document-- async def test_model_output_that_does_not_fit_its_structure_stays_redacted(self, mocker: MockerFixture) -> None:- """A model output the structure refuses, after the re-asks, is data-dependent: not flagged caller-facing."""- unfit_output_error = LLMCompletionError(- "Structured generation via 'instructor' failed trying to generate schema: Verdict with error: 1 validation error",- error_category=InferenceErrorCategory.UNKNOWN,- )- fake_content_generator = mocker.MagicMock()- fake_content_generator.make_object = mocker.AsyncMock(side_effect=unfit_output_error)- mocker.patch("pipelex.kernel.llm_ops.get_content_generator", return_value=fake_content_generator)-- error = await _run_failing(- pipe_code="judge_flow",- mthds_content=StrictMethodFaultsTestData.STRUCTURED_OUTPUT_MTHDS,- inputs={"claim": "The sky is green."},- )-- assert error.pipe_code == "judge"- report = error.to_error_report()- assert report.error_type == "LLMCompletionError"- assert report.caller_facing_message is False- document = _strict_problem_document(error)- assert document["status"] == 500- assert document["error_domain"] == "runtime"- assert document["detail"] == INTERNAL_ERROR_PLACEHOLDERdiff --git a/tests/integration/pipelex/pipeline/test_validate_bundle_clean_summary.py b/tests/integration/pipelex/pipeline/test_validate_bundle_clean_summary.pyindex fc687ac11..fe20de109 100644--- a/tests/integration/pipelex/pipeline/test_validate_bundle_clean_summary.py+++ b/tests/integration/pipelex/pipeline/test_validate_bundle_clean_summary.py@@ -49,7 +49,7 @@ def _assert_clean_summary(exc: ValidateBundleError) -> None:assert "Could not load blueprints because of" not in exc.messageassert "Could not load concepts because of" not in exc.message# The summary is derived from the structured items: a single item projects its message verbatim.- items = list(exc.to_error_report().validation_errors or [])+ items = list(exc.validation_error_items() or [])assert items, "an invalid verdict must carry structured items"assert exc.message == items[0].messagediff --git a/tests/integration/pipelex/pipeline/test_validate_bundle_entry_shape_parity.py b/tests/integration/pipelex/pipeline/test_validate_bundle_entry_shape_parity.pyindex 741d2dca2..f7383168e 100644--- a/tests/integration/pipelex/pipeline/test_validate_bundle_entry_shape_parity.py+++ b/tests/integration/pipelex/pipeline/test_validate_bundle_entry_shape_parity.py@@ -81,7 +81,7 @@ async def _observed_from_library_dir(mthds_contents: str, *, directory: Path) ->def _observed(error: ValidateBundleError) -> list[tuple[ValidationErrorCategory, str | None]]:- items = error.to_error_report().validation_errors or []+ items = error.validation_error_items() or []return [(item.category, item.error_type) for item in items]diff --git a/tests/integration/pipelex/pipeline/test_validate_bundle_load_refusals.py b/tests/integration/pipelex/pipeline/test_validate_bundle_load_refusals.pyindex 7cfa5c0da..ee32df32b 100644--- a/tests/integration/pipelex/pipeline/test_validate_bundle_load_refusals.py+++ b/tests/integration/pipelex/pipeline/test_validate_bundle_load_refusals.py@@ -13,11 +13,11 @@ bundles through ``validate_bundle`` and pin the verdict each refusal produces:was a Python repr).- **A model served as another type.** A pipe naming a handle the deck serves only as another model type, such as anLLM in an image-generation pipe, gets the same ``unknown_model`` item, whose message names the type the pipe needs.-- **The general arm.** Any other ``input``-domained refusal raised while building a pipe validates to one- item located on the pipe and its file, keeping its message only when it is caller-facing; a- ``config``-domained fault raised at the same place still propagates as no verdict.+- **The general arm.** Any other refusal of the method raised while building a pipe validates to one+ item located on the pipe and its file, reading the sentence its code renders, never its own message; a+ fault of the operator's configuration raised at the same place still propagates as no verdict.- **The run path.** Setting up a run on the unknown-model bundle refuses it with the same verdict, its- item naming the pipe, whose STRICT projection is still an HTTP 422 carrying the deck check's sentence.+ item naming the pipe, whose caller's problem is ``method.invalid``, an HTTP 422 with one ``model.unknown`` item.The deck is the test session's own, so the suggestion lists are read off it rather than pinned infull, except for the one-suggestion alias whose rename fix is the point of its case.@@ -30,11 +30,12 @@ import pytestfrom mthds.protocol.problem.registry import CoreCodefrom pytest_mock import MockerFixture-from pipelex.base_exceptions import DisclosureMode, PipelexError, ValidationErrorCategory, ValidationErrorItem+from pipelex.base_exceptions import PipelexError, ValidationErrorCategory, ValidationErrorItemfrom pipelex.cogt.model_backends.model_type import ModelTypefrom pipelex.config import get_configfrom pipelex.core.pipes.exceptions import PipeOperatorModelChoiceErrorfrom pipelex.errors.error_codes import PipelexErrorCode, error_code_spec+from pipelex.errors.problem import ProblemViewfrom pipelex.pipeline.exceptions import ValidateBundleErrorfrom pipelex.pipeline.fixes.planner import RENAME_MODEL_FIX_CODEfrom pipelex.pipeline.pipeline_run_setup import pipeline_run_setup@@ -230,18 +231,11 @@ def _write_bundle(*, directory: Path, content: str) -> Path:async def _single_item(*, bundle_path: Path) -> ValidationErrorItem:with pytest.raises(ValidateBundleError) as raised:await validate_bundle(mthds_file_path=bundle_path, library_dirs=[bundle_path.parent])- items = raised.value.to_error_report().validation_errors or []+ items = raised.value.validation_error_items() or []assert len(items) == 1, f"expected exactly one item, got {items!r}"return items[0]-class _CallerFacingRefusalError(PipelexError):- """An input refusal whose message was authored for the caller — stands in for any future one."""-- error_code = CoreCode.METHOD_INVALID- _authors_caller_facing_message = True--class _InternalInputRefusalError(PipelexError):"""An input refusal whose message is internal text the verdict must not carry."""@@ -346,11 +340,12 @@ class TestValidateBundleLoadRefusals:assert len(item.suggestions) > 1assert item.suggested_fix is None- async def test_caller_facing_input_refusal_at_load_is_a_located_item(self, tmp_path: Path, mocker: MockerFixture) -> None:- mocker.patch(- "pipelex.pipe_operators.llm.pipe_llm.check_llm_choice_with_deck",- side_effect=_CallerFacingRefusalError("The harbour board cannot show tides this far upriver."),+ async def test_input_refusal_at_load_is_a_located_item_reading_its_code_s_sentence(self, tmp_path: Path, mocker: MockerFixture) -> None:+ """The item reads the sentence the refusal's code renders from its parameters, never the refusal's own message."""+ refusal = _InternalInputRefusalError("internal detail: registry slot 7 is stale").with_params(+ field_path="pipe.write_tide_note.model", finding="the harbour board cannot show tides this far upriver")+ mocker.patch("pipelex.pipe_operators.llm.pipe_llm.check_llm_choice_with_deck", side_effect=refusal)bundle_path = _write_bundle(directory=tmp_path, content=_llm_bundle(model_line='model = "@best-gpt"'))item = await _single_item(bundle_path=bundle_path)@@ -360,7 +355,10 @@ class TestValidateBundleLoadRefusals:assert item.pipe_code == "write_tide_note"assert item.domain_code == _DOMAINassert item.source == str(bundle_path)- assert "The harbour board cannot show tides this far upriver." in item.message+ assert item.message == (+ "The declaration at 'pipe.write_tide_note.model' breaks a rule of the language (the harbour board cannot show tides this far upriver)."+ )+ assert "registry slot 7" not in item.messageasync def test_internal_input_refusal_carries_its_title_not_its_message(self, tmp_path: Path, mocker: MockerFixture) -> None:mocker.patch(@@ -401,16 +399,17 @@ class TestValidateBundleLoadRefusals:)assert isinstance(raised.value.__cause__, PipeOperatorModelChoiceError)- report = raised.value.to_error_report()- (item,) = report.validation_errors or []+ (item,) = raised.value.validation_error_items()assert item.error_type == PipeValidationErrorType.UNKNOWN_MODELassert item.pipe_code == "write_tide_note"assert item.field_name == "model"- assert report.http_status == 422- strict_payload = report.to_dict(disclosure_mode=DisclosureMode.STRICT)- assert strict_payload["error_type"] == "ValidateBundleError"- assert strict_payload["error_domain"] == "input"- assert "Pipe 'write_tide_note'" in strict_payload["message"]- assert "Model handle 'gpt-5.6-lunna' was not found in the model deck" in strict_payload["message"]- (strict_item,) = strict_payload["validation_errors"]- assert strict_item["error_type"] == "unknown_model"+ problem = raised.value.to_problem(view=ProblemView.CALLER)+ assert problem.code == CoreCode.METHOD_INVALID+ assert error_code_spec(CoreCode.METHOD_INVALID).status == 422+ assert problem.errors is not None+ (problem_item,) = problem.errors+ assert problem_item.code == CoreCode.MODEL_UNKNOWN+ assert problem_item.location is not None+ assert (problem_item.location.pipe, problem_item.location.field) == ("write_tide_note", "model")+ # The refusal's own message, which names the deck, stays on the chain for the operator.+ assert "Model handle 'gpt-5.6-lunna' was not found in the model deck" in str(raised.value.__cause__)diff --git a/tests/integration/pipelex/pipeline/test_validate_bundle_source_threading.py b/tests/integration/pipelex/pipeline/test_validate_bundle_source_threading.pyindex c0d8f303e..2a334f0f9 100644--- a/tests/integration/pipelex/pipeline/test_validate_bundle_source_threading.py+++ b/tests/integration/pipelex/pipeline/test_validate_bundle_source_threading.py@@ -125,22 +125,18 @@ prompt = "Say hi"def _pipe_channel_items(exc: ValidateBundleError, *, error_type: PipeValidationErrorType) -> list[ValidationErrorItem]:- report = exc.to_error_report()- assert report.validation_errors is not None- return [item for item in report.validation_errors if item.category == ValidationErrorCategory.PIPE_VALIDATION and item.error_type == error_type]+ items = exc.validation_error_items()+ return [item for item in items if item.category == ValidationErrorCategory.PIPE_VALIDATION and item.error_type == error_type]def _input_drift_items(exc: ValidateBundleError) -> list[ValidationErrorItem]:- report = exc.to_error_report()- assert report.validation_errors is not None+ items = exc.validation_error_items()input_drift_types = {PipeValidationErrorType.MISSING_INPUT_VARIABLE,PipeValidationErrorType.EXTRANEOUS_INPUT_VARIABLE,PipeValidationErrorType.INPUT_STUFF_SPEC_MISMATCH,}- return [- item for item in report.validation_errors if item.category == ValidationErrorCategory.PIPE_VALIDATION and item.error_type in input_drift_types- ]+ return [item for item in items if item.category == ValidationErrorCategory.PIPE_VALIDATION and item.error_type in input_drift_types]@pytest.mark.asyncio(loop_scope="class")@@ -188,9 +184,8 @@ class TestValidateBundleSourceThreading:load_empty_library()with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_contents=[_INVALID_MAIN_PIPE_MTHDS], mthds_sources=["broken.mthds"])- report = exc_info.value.to_error_report()- assert report.validation_errors is not None- seeded_items = [item for item in report.validation_errors if item.source == "broken.mthds"]+ items = exc_info.value.validation_error_items()+ seeded_items = [item for item in items if item.source == "broken.mthds"]assert seeded_items, "no validation_errors item carried the threaded source"assert any(item.category == ValidationErrorCategory.BLUEPRINT_VALIDATION for item in seeded_items)@@ -208,10 +203,10 @@ class TestValidateBundleSourceThreading:load_empty_library()with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_contents=[_MALFORMED_TOML_MTHDS], mthds_sources=["broken.mthds"])- report = exc_info.value.to_error_report()- assert report.validation_errors, "a parse-level failure must still carry a non-empty validation_errors[]"- assert all(item.category == ValidationErrorCategory.BLUEPRINT_VALIDATION for item in report.validation_errors)- assert [item.source for item in report.validation_errors] == ["broken.mthds"]+ items = exc_info.value.validation_error_items()+ assert items, "a parse-level failure must still carry a non-empty list of validation items"+ assert all(item.category == ValidationErrorCategory.BLUEPRINT_VALIDATION for item in items)+ assert [item.source for item in items] == ["broken.mthds"]async def test_length_mismatch_is_a_host_contract_error(self,@@ -219,7 +214,7 @@ class TestValidateBundleSourceThreading:) -> None:"""A ``mthds_sources``/``mthds_contents`` length mismatch is a host wiring bug, not user input.- It must raise an internal error (→ 500, redacted under STRICT), not a caller-facing+ It must raise an internal error (→ 500, its message the operator's alone), not a``ValidateBundleError`` (→ 422) — ``mthds_sources`` is never supplied by the end caller."""load_empty_library()diff --git a/tests/integration/pipelex/pipeline/test_validate_bundle_structured_errors.py b/tests/integration/pipelex/pipeline/test_validate_bundle_structured_errors.pyindex 3636d43b8..c7ea28d21 100644--- a/tests/integration/pipelex/pipeline/test_validate_bundle_structured_errors.py+++ b/tests/integration/pipelex/pipeline/test_validate_bundle_structured_errors.py@@ -2,8 +2,8 @@Three failure modes used to collapse to a bare message-only residual (no ``error_type``,no locator). They now carry a category + ``error_type`` + identity locators, built by the-one shared builder and projected onto ``ErrorReport.validation_errors`` (the same items the-agent CLI emits and the hosted ``InvalidReport`` carries):+one shared builder and listed by ``ValidateBundleError.validation_error_items()`` (the items the+agent CLI emits, each of which the invalid verdict's problem lists under its ``errors``):- pipe-owned unresolved concept reference (a pipe input/output) → ``pipe_validation`` /``unresolved_concept`` (with the referencing pipe, the missing concept, and the field).@@ -23,8 +23,10 @@ from collections.abc import Callablefrom pathlib import Pathimport pytest+from mthds.protocol.problem.registry import CoreCodefrom pipelex.base_exceptions import ValidationErrorCategory, ValidationErrorItem+from pipelex.errors.problem import ProblemViewfrom pipelex.pipeline.exceptions import ValidateBundleErrorfrom pipelex.pipeline.validate_bundle import validate_bundlefrom pipelex.validation_error_types import PipeValidationErrorType@@ -206,12 +208,15 @@ template = "A note about $topic"async def _validation_errors_for(mthds_contents: str) -> list[ValidationErrorItem]:- """Validate one invalid bundle and return its structured validation_errors[]."""+ """Validate one invalid bundle and return its structured validation items, one per item of its problem's `errors`."""with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_contents=[mthds_contents])- report = exc_info.value.to_error_report()- items = report.validation_errors- assert items, "Every invalid verdict must carry a non-empty validation_errors[]"+ items = exc_info.value.validation_error_items()+ assert items, "Every invalid verdict must carry a non-empty list of validation items"+ problem = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert problem.code == CoreCode.METHOD_INVALID+ assert problem.errors is not None+ assert len(problem.errors) == len(items)return items@@ -345,7 +350,7 @@ class TestValidateBundleStructuredErrors:"""Every item that carries a `pipe_code` must carry `domain_code` too — thepresentation chain identifies pipes by full ref (`domain_code.pipe_code`), so abare-code item degrades node decorations and click-to-navigate downstream. Pins- the report-wide invariant on an extraneous-input bundle (surfaced here by the+ the verdict-wide invariant on an extraneous-input bundle (surfaced here by theblueprint categorizer; the operator-raised `PipeValidationError` sites that usedto omit `domain_code` are fixed at their raise sites and pinned by the pipe-sorterunit test).@@ -357,7 +362,7 @@ class TestValidateBundleStructuredErrors:item = extraneous_items[0]assert item.pipe_code == "greet_person"assert item.domain_code == "structured_extraneous_input"- # The invariant holds across the whole report, not just the pinned channel.+ # The invariant holds across the whole verdict, not just the pinned channel.for reported in items:if reported.pipe_code is not None:assert reported.domain_code is not None, f"item {reported.error_type} carries pipe_code without domain_code"@@ -388,7 +393,7 @@ class TestValidateBundleStructuredErrors:bundle_path.write_text(mthds_contents)with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_file_path=bundle_path)- items = exc_info.value.to_error_report().validation_errors+ items = exc_info.value.validation_error_items()assert items, "Every invalid verdict must carry a non-empty validation_errors[]"extraneous_items = [item for item in items if item.error_type == PipeValidationErrorType.EXTRANEOUS_INPUT_VARIABLE]assert extraneous_items, f"Expected an extraneous_input_variable item, got {[(i.category, i.error_type) for i in items]}"diff --git a/tests/integration/pipelex/pipeline/test_validation_detail_kept.py b/tests/integration/pipelex/pipeline/test_validation_detail_kept.pyindex af01f3baf..ce73e8dcd 100644--- a/tests/integration/pipelex/pipeline/test_validation_detail_kept.py+++ b/tests/integration/pipelex/pipeline/test_validation_detail_kept.py@@ -10,7 +10,7 @@ Validation used to lose detail before the verdict was built. These tests load refield fails its combine; nested in a ``PipeSequence``, the failure used to reach the reader as oneitem holding a Python repr of the sweep's records, once for each level of nesting. It is now one``dry_run`` item for the innermost failing pipe, carrying its code, domain and source, whose text- follows the disclosure rule: the failure's own message only when it is caller-facing.+ is the sentence the failure's code renders for a caller, never the failure's own message.- **The positions the parser knew.** A TOML syntax error's item carries its 1-based line and column, andan unresolved concept's item lists the concepts its domain declares."""@@ -19,28 +19,22 @@ from pathlib import Pathimport pytestfrom mthds.protocol.problem.registry import CoreCode-from pytest_mock import MockerFixturefrom pipelex.base_exceptions import ValidationErrorCategory, ValidationErrorItem-from pipelex.cogt.inference.error_classification import UserAction-from pipelex.core.stuffs.exceptions import StuffFactoryError-from pipelex.errors.error_codes import error_code_spec+from pipelex.errors.problem import ProblemViewfrom pipelex.pipeline.exceptions import ValidateBundleErrorfrom pipelex.pipeline.validate_bundle import validate_bundlefrom pipelex.validation_error_types import PipeValidationErrorTypefrom tests.integration.pipelex.test_data import ValidationDetailBundles--def _keep_unclassified(self: StuffFactoryError, *, user_action: UserAction | None = None) -> StuffFactoryError:- """Stands in for ``as_caller_fault``, leaving the error unclassified."""- del user_action- return self+# The sentence `pipe.output_multiplicity` renders for the parallel whose plural branch feeds a single field.+_MULTIPLICITY_SENTENCE = "Pipe 'analyze_topic' produced an output of the multiplicity 'list', but its output 'ideas' is declared 'single'."async def _validation_items(*, bundle: str, dry_run_pipe_codes: list[str] | None = None) -> list[ValidationErrorItem]:with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_contents=[bundle], mthds_sources=[ValidationDetailBundles.SOURCE], dry_run_pipe_codes=dry_run_pipe_codes)- return list(exc_info.value.to_error_report().validation_errors or [])+ return list(exc_info.value.validation_error_items() or [])class TestValidationDetailKept:@@ -64,8 +58,7 @@ class TestValidationDetailKept:@pytest.mark.asyncioasync def test_a_nested_dry_run_failure_is_one_item_at_the_innermost_pipe(self) -> None:- # The combine's refusal is the caller's own method fault, restated with its multiplicity next step- # and classified caller-facing at its raise site, so the item carries that restatement.+ # The combine's refusal is the caller's own method fault: the item reads the sentence of its multiplicity code.items = await _validation_items(bundle=ValidationDetailBundles.NESTED_PARALLEL_MISMATCH)(item,) = items@@ -74,24 +67,26 @@ class TestValidationDetailKept:assert item.pipe_code == "analyze_topic"assert item.domain_code == ValidationDetailBundles.DOMAINassert item.source == ValidationDetailBundles.SOURCE- assert item.message.startswith(- "Pipe 'analyze_topic' failed its dry run: PipeParallel 'analyze_topic' cannot combine its branch results into its output 'IdeaReport'."- )- assert "Branch 'propose_ideas' gives result 'ideas' as a list, 'Idea[]'" in item.message+ assert item.message == f"Pipe 'analyze_topic' failed its dry run: {_MULTIPLICITY_SENTENCE}"assert not any(marker in item.message for marker in ValidationDetailBundles.RECORD_REPR_MARKERS)@pytest.mark.asyncio- async def test_a_dry_run_failure_that_is_not_caller_facing_names_its_title(self, mocker: MockerFixture) -> None:- # The combine classifies its refusal as the caller's fault; with that classification withheld, the- # same failure is not caller-facing, and the item names its title.- mocker.patch.object(StuffFactoryError, "as_caller_fault", new=_keep_unclassified)-- items = await _validation_items(bundle=ValidationDetailBundles.NESTED_PARALLEL_MISMATCH)-- (item,) = items- assert item.pipe_code == "analyze_topic"- # 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}"+ async def test_a_dry_run_failure_reads_its_codes_sentence_never_its_own_message(self) -> None:+ """The combine's own restatement, naming the branch to change, is the operator's: the verdict carries the code's sentence."""+ with pytest.raises(ValidateBundleError) as exc_info:+ await validate_bundle(mthds_contents=[ValidationDetailBundles.NESTED_PARALLEL_MISMATCH], mthds_sources=[ValidationDetailBundles.SOURCE])++ (item,) = exc_info.value.validation_error_items()+ assert "Branch 'propose_ideas'" not in item.message+ problem = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert problem.code == CoreCode.METHOD_INVALID+ assert problem.errors is not None+ (problem_item,) = problem.errors+ assert problem_item.code == CoreCode.PIPE_OUTPUT_MULTIPLICITY+ assert problem_item.location is not None+ assert problem_item.location.pipe == "analyze_topic"+ assert problem_item.detail == _MULTIPLICITY_SENTENCE+ assert "Branch 'propose_ideas'" not in str(problem.to_wire())@pytest.mark.asyncioasync def test_the_enclosing_pipe_alone_reports_the_innermost_failing_pipe(self) -> None:@@ -135,7 +130,7 @@ class TestValidationDetailKept:library_dirs=[library_dir],)- (item,) = exc_info.value.to_error_report().validation_errors or []+ (item,) = exc_info.value.validation_error_items() or []assert item.category == ValidationErrorCategory.DRY_RUNassert (item.pipe_code, item.domain_code) == ("analyze_topic", ValidationDetailBundles.DOMAIN)assert item.source is None@@ -157,7 +152,7 @@ class TestValidationDetailKept:library_dirs_are_callers=True,)- (item,) = exc_info.value.to_error_report().validation_errors or []+ (item,) = exc_info.value.validation_error_items() or []assert item.category == ValidationErrorCategory.DRY_RUNassert (item.pipe_code, item.domain_code) == ("analyze_topic", ValidationDetailBundles.DOMAIN)assert item.source is not None@@ -176,7 +171,7 @@ class TestValidationDetailKept:with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_file_path=entry_file, library_dirs=[method_dir])- (item,) = exc_info.value.to_error_report().validation_errors or []+ (item,) = exc_info.value.validation_error_items() or []assert (item.pipe_code, item.domain_code) == ("analyze_topic", ValidationDetailBundles.DOMAIN)assert item.source is not Noneassert Path(item.source).resolve() == sibling_file.resolve()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 ff5c22e6d..94c4348f5 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@@ -1,8 +1,8 @@-"""Pin: a verdict a STRICT caller reads names no path on the host.+"""Pin: a verdict a caller reads names no path on the host.-Every validation item is caller-facing, and STRICT disclosure keeps the items and the verdict's message-verbatim, so neither may carry a path on the host, in an item's ``source`` or in any message. Two origins-used to put one there:+Every validation item is the caller's, and so is the caller's view of the verdict's problem, so neither may+carry a path on the host, in an item's ``source`` or in any message or detail. Two origins used to put one+there:- **An address-based dependency.** A package the bundle depends on by address is installed on the host,and its bundles were named by their install path. They are named by the package's address and the@@ -10,7 +10,7 @@ used to put one there:dependency, and the files a duplicate declaration inside it names.- **The host's own library directories.** When submitted content is validated or run, the librarydirectories 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+ fault, a ``HostLibraryLoadRefusalError`` and no verdict at all, whose message is the operator's alone. A verdict on thecaller'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.@@ -23,10 +23,12 @@ from pathlib import Pathfrom typing import Any, NamedTupleimport pytest+from mthds.protocol.problem.registry import ProblemDomainfrom pytest_mock import MockerFixture-from pipelex.base_exceptions import DisclosureMode, ErrorDomain, PipelexError, ValidationErrorItem+from pipelex.base_exceptions import PipelexError, ValidationErrorItemfrom pipelex.config import get_config+from pipelex.errors.problem import ProblemViewfrom pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.libraries.exceptions import HostLibraryTreeErrorfrom pipelex.pipeline.exceptions import HostLibraryLoadRefusalError, ValidateBundleError@@ -201,14 +203,28 @@ def _host_path_markers(tmp_path: Path) -> list[str]:return sorted({str(tmp_path), str(tmp_path.resolve())})-def _strict_payload(verdict: ValidateBundleError) -> dict[str, Any]:- return verdict.to_error_report().to_dict(disclosure_mode=DisclosureMode.STRICT)+def _caller_payload(error: PipelexError) -> dict[str, Any]:+ """What a caller reads of a failure: its problem in the caller's view and, for a verdict, the validation items beside it."""+ payload: dict[str, Any] = {"problem": error.to_problem(view=ProblemView.CALLER).to_wire()}+ if isinstance(error, ValidateBundleError):+ payload["validation_errors"] = [item.model_dump(mode="json", exclude_none=True) for item in error.validation_error_items()]+ return payloaddef _assert_names_no_host_path(*, payload: dict[str, Any], tmp_path: Path) -> None:serialized = json.dumps(payload)for marker in _host_path_markers(tmp_path):- assert marker not in serialized, f"the STRICT payload names a path on the host ({marker}): {serialized}"+ assert marker not in serialized, f"what the caller reads names a path on the host ({marker}): {serialized}"+++def _assert_the_host_s_fault(*, error: PipelexError, tmp_path: Path) -> None:+ """The host's own directories are the operator's configuration: no verdict, no item, and nothing of the operator's message."""+ caller = error.to_problem(view=ProblemView.CALLER)+ assert caller.code == PipelexErrorCode.CONFIG_INVALID+ assert caller.domain == ProblemDomain.OPERATOR+ assert caller.errors is None+ assert error.message not in json.dumps(caller.to_wire())+ _assert_names_no_host_path(payload=_caller_payload(error), tmp_path=tmp_path)class _Surface(NamedTuple):@@ -282,12 +298,12 @@ class TestVerdictNamesNoHostPath:verdict = await _verdict_on(surface=surface, caller_bundle=_CALLER_BUNDLE, tmp_path=tmp_path)- items = verdict.to_error_report().validation_errors or []+ items = verdict.validation_error_items() or [](item,) = [item for item in items if item.error_type == PipeValidationErrorType.UNKNOWN_MODEL]assert item.pipe_code == "write_tide_notice"# The package's address, then the bundle's path inside the package: never where the host installed it.assert item.source == f"{_DEPENDENCY_ADDRESS}/notices/tide_notices.mthds", surface.description- _assert_names_no_host_path(payload=_strict_payload(verdict), tmp_path=tmp_path)+ _assert_names_no_host_path(payload=_caller_payload(verdict), tmp_path=tmp_path)@pytest.mark.parametrize("surface", _SURFACES, ids=[surface.surface_id for surface in _SURFACES])async def test_a_duplicate_declaration_in_a_dependency_names_its_files_by_address(@@ -300,11 +316,11 @@ class TestVerdictNamesNoHostPath:verdict = await _verdict_on(surface=surface, caller_bundle=_CALLER_BUNDLE, tmp_path=tmp_path)- items: list[ValidationErrorItem] = verdict.to_error_report().validation_errors or []+ items: list[ValidationErrorItem] = verdict.validation_error_items() or [](item,) = itemsassert f"'{_DEPENDENCY_ADDRESS}/notices/tide_notices.mthds'" in item.message, surface.descriptionassert f"'{_DEPENDENCY_ADDRESS}/notices/tide_notices_copy.mthds'" in item.message, surface.description- _assert_names_no_host_path(payload=_strict_payload(verdict), tmp_path=tmp_path)+ _assert_names_no_host_path(payload=_caller_payload(verdict), tmp_path=tmp_path)@pytest.mark.parametrize("surface", _SURFACES, ids=[surface.surface_id for surface in _SURFACES])async def test_a_dependency_s_tree_refusal_names_the_package_by_its_address(@@ -319,7 +335,7 @@ class TestVerdictNamesNoHostPath:assert "github.com/acme-tests/harbour-methods" in verdict.message, surface.descriptionassert "notices/linked_notices.mthds" in verdict.message, surface.descriptionassert "max_files" not in verdict.message, "no advice about this host's limits reaches the caller"- _assert_names_no_host_path(payload=_strict_payload(verdict), tmp_path=tmp_path)+ _assert_names_no_host_path(payload=_caller_payload(verdict), tmp_path=tmp_path)@pytest.mark.parametrize("surface",@@ -334,10 +350,7 @@ class TestVerdictNamesNoHostPath:with pytest.raises(HostLibraryTreeError) as raised:await _load_on(surface=surface, caller_bundle=_VALID_CALLER_BUNDLE, tmp_path=tmp_path)- report = raised.value.to_error_report()- assert report.error_domain == ErrorDomain.CONFIG- assert report.caller_facing_message is False- _assert_names_no_host_path(payload=report.to_dict(disclosure_mode=DisclosureMode.STRICT), tmp_path=tmp_path)+ _assert_the_host_s_fault(error=raised.value, tmp_path=tmp_path)async def test_a_callers_library_tree_that_cannot_be_listed_is_their_verdict(self, tmp_path: Path) -> None:library_dir = _valid_host_library(tmp_path=tmp_path)@@ -375,12 +388,7 @@ class TestVerdictNamesNoHostPath:with pytest.raises(HostLibraryLoadRefusalError) as raised:await validate_bundle(mthds_contents=[_VALID_CALLER_BUNDLE], library_dirs=[host_library_dir])- 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)+ _assert_the_host_s_fault(error=raised.value, tmp_path=tmp_path)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."""@@ -390,10 +398,10 @@ class TestVerdictNamesNoHostPath:with pytest.raises(ValidateBundleError) as raised:await validate_bundle(mthds_contents=[_BOARD_NOTICE_PIPE_BUNDLE], library_dirs=[host_library_dir])- (item,) = raised.value.to_error_report().validation_errors or []+ (item,) = raised.value.validation_error_items() or []assert "harbour_board.pin_board_notice" in item.messageassert HOST_LIBRARY_FILE_PLACEHOLDER in item.message- _assert_names_no_host_path(payload=_strict_payload(raised.value), tmp_path=tmp_path)+ _assert_names_no_host_path(payload=_caller_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:host_library_dir = tmp_path / "host" / "library"@@ -403,9 +411,7 @@ class TestVerdictNamesNoHostPath:await _run_setup(mthds_contents=[_VALID_CALLER_BUNDLE], library_dirs=[str(host_library_dir)])assert not isinstance(raised.value, ValidateBundleError), "a host's library directories load untranslated on a run"- strict_payload = raised.value.to_error_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)+ _assert_the_host_s_fault(error=raised.value, tmp_path=tmp_path)async def test_a_bundle_file_keeps_the_paths_of_its_library_directories(self, tmp_path: Path) -> None:library_dir = tmp_path / "caller" / "library"@@ -415,7 +421,7 @@ class TestVerdictNamesNoHostPath:with pytest.raises(ValidateBundleError) as raised:await validate_bundle(mthds_file_path=caller_file, library_dirs=[library_dir])- items = raised.value.to_error_report().validation_errors or []+ items = raised.value.validation_error_items() 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.source == str(library_file) for item in concept_items)@@ -432,7 +438,7 @@ class TestVerdictNamesNoHostPath: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)+ _assert_the_host_s_fault(error=raised.value, 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"@@ -447,7 +453,7 @@ class TestVerdictNamesNoHostPath:with pytest.raises(ValidateBundleError) as raised:await runtime.validate([_VALID_CALLER_BUNDLE])- items = raised.value.to_error_report().validation_errors or []+ items = raised.value.validation_error_items() 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.source == str(library_file) for item in concept_items)diff --git a/tests/integration/pipelex/pipes/controller/pipe_condition/test_pipe_condition_method_faults.py b/tests/integration/pipelex/pipes/controller/pipe_condition/test_pipe_condition_method_faults.pyindex c2a09278d..af980669e 100644--- a/tests/integration/pipelex/pipes/controller/pipe_condition/test_pipe_condition_method_faults.py+++ b/tests/integration/pipelex/pipes/controller/pipe_condition/test_pipe_condition_method_faults.py@@ -2,9 +2,9 @@A bundle's load refuses an outcome naming no pipe, an expression that does not parse and a chosen pipe'sundeclared input before any condition runs, so a run of a loaded bundle does not reach these raise sites:-the tests call the condition's run arms directly. Each refusal is classified as the caller's fault, keeps-its message under STRICT disclosure with a next step, and quotes no text of the condition, which may be a-host library's.+the tests call the condition's run arms directly. Each refusal is classified as the method's fault, the+caller reads its code's sentence and next step, rendered from the parameters the raise site gives, and+neither quotes text of the condition, which may be a host library's."""from datetime import UTC, datetime@@ -12,12 +12,14 @@ from pathlib import Pathfrom typing import Any, Callableimport pytest+from mthds.protocol.problem.registry import CoreCode, ProblemDomain, RetryVerdict-from pipelex.base_exceptions import DisclosureModefrom pipelex.core.concepts.native.concept_native import NativeConceptCodefrom pipelex.core.domains.domain import SpecialDomainfrom pipelex.core.memory.working_memory_factory import WorkingMemoryFactoryfrom pipelex.core.pipes.exceptions import PipeRunError+from pipelex.errors.error_codes import error_code_spec+from pipelex.errors.problem import ProblemViewfrom pipelex.graph.graph_tracer_manager import GraphTracerManagerfrom pipelex.graph.graphspec import NodeKindfrom pipelex.pipe_controllers.condition.pipe_condition import PipeCondition@@ -47,8 +49,16 @@ def _make_condition(*, pipe_code: str, expression_template: str, outcomes: dict[return PipeFactory[PipeCondition].make_from_blueprint(domain_code="test_integration", pipe_code=pipe_code, blueprint=blueprint)-def _strict_problem_document(error: PipeRunError) -> dict[str, Any]:- return error.to_error_report().to_problem_document(disclosure_mode=DisclosureMode.STRICT)+def _caller_problem_document(error: PipeRunError) -> dict[str, Any]:+ """The caller's problem document: a method fault, never retried, with the caller's own message on the operator's side."""+ problem = error.to_problem(view=ProblemView.CALLER)+ assert problem.domain == ProblemDomain.METHOD+ assert problem.retry == RetryVerdict.NO+ assert error_code_spec(CoreCode(problem.code)).status == 422+ operator = error.to_problem(view=ProblemView.OPERATOR)+ assert operator.diagnostics is not None+ assert operator.diagnostics.message == error.message+ return problem.to_wire()@pytest.mark.asyncio(loop_scope="class")@@ -71,18 +81,16 @@ class TestPipeConditionMethodFaults:pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=PipeRunMode.LIVE),)- document = _strict_problem_document(exc_info.value)- assert document["status"] == 422- assert document["error_domain"] == "input"- assert document["detail"] == (+ assert exc_info.value.message == ("PipeCondition 'length_gate' chose pipe 'test_integration2.capitalize_long_text', whose required inputs are missing: input_text.")- assert document["user_action"] == {- "kind": "change_input",- "detail": (- "Provide the missing required inputs of 'test_integration2.capitalize_long_text', which PipeCondition 'length_gate' chose: "- "input_text."- ),+ document = _caller_problem_document(exc_info.value)+ assert document["code"] == CoreCode.PIPE_INPUT_UNRESOLVED+ assert document["detail"] == "Pipe 'length_gate' could not read 'input_text', which an earlier step should have produced."+ assert document["location"] == {"pipe": "length_gate"}+ assert document["next_step"] == {+ "kind": "change_method",+ "detail": "Make an earlier step produce 'input_text' for pipe 'length_gate', then run the method again.",}@pytest.mark.parametrize(@@ -178,18 +186,16 @@ class TestPipeConditionMethodFaults:# The refusal is the root fault a run and a dry-run verdict report, not the parser error that quotes the expression.assert find_root_fault(error=exc_info.value) is exc_info.value- document = _strict_problem_document(exc_info.value)- assert document["status"] == 422- assert document["error_domain"] == "input"- assert (- document["detail"] == "Dry run failed for pipe 'parse_gate' (PipeCondition): its expression does not parse at line 2 of that expression."+ assert exc_info.value.message == (+ "Dry run failed for pipe 'parse_gate' (PipeCondition): its expression does not parse at line 2 of that expression.")- assert "frobnicate_the_parcel" not in document["detail"]- assert "input_text" not in document["detail"]- assert document["user_action"] == {- "kind": "change_input",- "detail": "Fix the expression of PipeCondition 'parse_gate' so that it parses as a Jinja2 expression.",- }+ document = _caller_problem_document(exc_info.value)+ assert document["code"] == CoreCode.METHOD_TEMPLATE_INVALID+ assert document["detail"] == "The template 'expression' of pipe 'parse_gate' is invalid (does not parse at line 2 of that expression)."+ assert document["location"] == {"pipe": "parse_gate"}+ for text in (str(document), exc_info.value.message):+ assert "frobnicate_the_parcel" not in text+ assert "input_text" not in textasync def test_outcomes_naming_no_pipe_are_the_callers_fault(self, job_metadata: JobMetadata, load_test_library: Callable[[list[Path]], None]@@ -210,18 +216,14 @@ class TestPipeConditionMethodFaults:pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=PipeRunMode.DRY),)- document = _strict_problem_document(exc_info.value)- assert document["status"] == 422- assert document["error_domain"] == "input"- assert document["detail"] == (+ assert exc_info.value.message == ("Dry run failed for PipeCondition 'route_gate': its outcomes name pipes that do not exist: ""test_integration.send_by_barge, test_integration.send_rush.")- assert "rush_lane" not in document["detail"]- assert document["user_action"] == {- "kind": "change_input",- "detail": (- "Declare the pipes test_integration.send_by_barge, test_integration.send_rush, "- "or change the outcomes of PipeCondition 'route_gate' to name existing pipes."- ),- }+ document = _caller_problem_document(exc_info.value)+ assert document["code"] == CoreCode.METHOD_PIPE_UNRESOLVED+ assert document["params"] == {"pipe": "route_gate", "missing": "test_integration.send_by_barge, test_integration.send_rush"}+ assert document["location"] == {"pipe": "route_gate"}+ assert document["next_step"]["kind"] == "change_method"+ for text in (str(document), exc_info.value.message):+ assert "rush_lane" not in textdiff --git a/tests/integration/pipelex/pipes/controller/pipe_sequence/test_binding_graph.py b/tests/integration/pipelex/pipes/controller/pipe_sequence/test_binding_graph.pyindex 5b5143433..c449b917c 100644--- a/tests/integration/pipelex/pipes/controller/pipe_sequence/test_binding_graph.py+++ b/tests/integration/pipelex/pipes/controller/pipe_sequence/test_binding_graph.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 PipelexError@@ -120,6 +121,9 @@ class TestBindingGraph:binding_node = _node(_in_process_graph(teardown_spy), pipe_code="invoice.total")assert binding_node.status == NodeStatus.FAILED+ # The node records the caller's view: a fault of ours, located at the binding, and none of the error's text.assert binding_node.error is not None- assert binding_node.error.error_type == "ValueError"- assert binding_node.error.message == "the content failed its validation"+ assert binding_node.error.code == CoreCode.RUNTIME_UNEXPECTED+ assert binding_node.error.location is not None+ assert binding_node.error.location.pipe == "invoice.total"+ assert "the content failed its validation" not in str(binding_node.error.to_wire())diff --git a/tests/integration/pipelex/pipes/controller/pipe_sequence/test_binding_refusal_remedy.py b/tests/integration/pipelex/pipes/controller/pipe_sequence/test_binding_refusal_remedy.pyindex 0d1695824..7616b674d 100644--- a/tests/integration/pipelex/pipes/controller/pipe_sequence/test_binding_refusal_remedy.py+++ b/tests/integration/pipelex/pipes/controller/pipe_sequence/test_binding_refusal_remedy.py@@ -122,7 +122,7 @@ class TestBindingRefusalRemedy:with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_contents=[_UPPERCASE_ROOT_BUNDLE])- validation_errors = exc_info.value.to_error_report().validation_errors or []+ validation_errors = exc_info.value.validation_error_items() or []assert [error.error_type for error in validation_errors] == [PipeValidationErrorType.INVALID_INPUT_NAME]assert validation_errors[0].variable_names == ["Invoice"]message = validation_errors[0].message or ""@@ -137,7 +137,7 @@ class TestBindingRefusalRemedy:with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_contents=[mthds_content])- validation_errors = exc_info.value.to_error_report().validation_errors or []+ validation_errors = exc_info.value.validation_error_items() or []assert [error.error_type for error in validation_errors] == [PipeValidationErrorType.MISSING_INPUT_VARIABLE]message = validation_errors[0].message or ""assert "Declare 'Invoice'" not in messagediff --git a/tests/integration/pipelex/pipes/controller/pipe_sequence/test_binding_typed_flow.py b/tests/integration/pipelex/pipes/controller/pipe_sequence/test_binding_typed_flow.pyindex f77535c46..aff550123 100644--- a/tests/integration/pipelex/pipes/controller/pipe_sequence/test_binding_typed_flow.py+++ b/tests/integration/pipelex/pipes/controller/pipe_sequence/test_binding_typed_flow.py@@ -662,7 +662,7 @@ class TestBindingTypedFlow:with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_file_path=entry_directory / "bundle.mthds", library_dirs=[entry_directory])- validation_errors = exc_info.value.to_error_report().validation_errors or []+ validation_errors = exc_info.value.validation_error_items() or []assert len(validation_errors) == 1message = validation_errors[0].message or ""for fragment in message_fragments: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 cd2a5272c..a520d7e46 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@@ -2,9 +2,10 @@ from pathlib import Pathfrom typing import TYPE_CHECKING, Anyimport pytest+from mthds.protocol.problem.registry import CoreCodefrom typing_extensions import override-from pipelex.base_exceptions import DisclosureMode+from pipelex.base_exceptions import PipelexError, iter_cause_chainfrom pipelex.cogt.doc_gen.doc_gen_format import DocGenFormat, DocGenSourcefrom pipelex.cogt.doc_gen.doc_gen_worker_abstract import DocGenWorkerAbstractfrom pipelex.cogt.doc_gen.exceptions import DocGenEngineMissingError@@ -17,6 +18,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.problem import ProblemViewfrom 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 DeliveryAssignment@@ -35,6 +37,8 @@ from pipelex.runtime_hub import get_secrets_providerfrom tests.integration.pipelex.pipes.operator.pipe_doc_gen.test_data import PipeDocGenTestDataif TYPE_CHECKING:+ from mthds.protocol.problem.models import ProblemItem+from pipelex.libraries.library_crate import LibraryCratefrom pipelex.pipe_machinery.pipe_abstract import PipeAbstract@@ -159,25 +163,66 @@ def make_models_manager(*, plugin_model_declarations: PluginModelDeclarations, basync 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 operator's problem, 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.+ gives no verdict and the load's `DocGenEngineMissingError` propagates as `pipelex.docgen.engine_unavailable`. Its+ message, which names the remedy, rides the operator's diagnostics; the caller reads the code's sentence over the format."""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())+ caller_problem = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert caller_problem.code == PipelexErrorCode.DOCGEN_ENGINE_UNAVAILABLE+ assert caller_problem.diagnostics is None+ operator_problem = exc_info.value.to_problem(view=ProblemView.OPERATOR)+ assert operator_problem.diagnostics is not None+ assert operator_problem.diagnostics.message == exc_info.value.message+ return str(operator_problem.to_wire())+++def verdict_items_text(error: ValidateBundleError) -> str:+ """An invalid verdict's items, as text: what `/validate` and the CLI show a caller."""+ return str([item.model_dump(mode="json", exclude_none=True) for item in error.validation_error_items()])+++def caller_text(error: PipelexError) -> str:+ """What a caller reads of a refusal, as text: an invalid verdict's items, and the caller's problem, in its code's sentences."""+ problem_text = str(error.to_problem(view=ProblemView.CALLER).to_wire())+ if isinstance(error, ValidateBundleError):+ return verdict_items_text(error) + problem_text+ return problem_text+++def refusal_messages(error: BaseException) -> str:+ """The messages along a refusal's cause chain, as text: what each raise site found, which only the operator reads.++ No problem a caller reads quotes them: a verdict's items read the sentences of their codes. They reach the operator+ as the diagnostics of the problem and in the run's log.+ """+ return "\n".join(str(node) for node in iter_cause_chain(error))+++def diagnosed_error_classes(error: PipelexError) -> list[str]:+ """The classes the operator's diagnostics name: the error's own, then those along its cause chain."""+ diagnostics = error.to_problem(view=ProblemView.OPERATOR).diagnostics+ assert diagnostics is not None+ return [diagnostics.error_class, *(cause.error_class for cause in diagnostics.causes or [])]+++def only_problem_item(error: ValidateBundleError) -> "ProblemItem":+ """The one item of an invalid verdict, as the caller's problem lists it."""+ problem = error.to_problem(view=ProblemView.CALLER)+ assert problem.code == CoreCode.METHOD_INVALID+ assert problem.errors is not None+ (item,) = problem.errors+ return item-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."""+async def refusal_report(*, step_fields: str) -> ValidateBundleError:+ """The invalid verdict of validating the test bundle with the given PipeDocGen step, which must be refused."""with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_contents=[PipeDocGenTestData.bundle(step_fields=step_fields)])- return str(exc_info.value.to_error_report().model_dump())+ return exc_info.valueclass RecordingMethodFileStore(MethodFileStoreProtocol):diff --git a/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_dependency_template_file.py b/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_dependency_template_file.pyindex 0c9b521cf..68c4ad368 100644--- a/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_dependency_template_file.py+++ b/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_dependency_template_file.py@@ -3,14 +3,17 @@ 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 MockerFixturefrom pipelex.core.pipes.exceptions import PipeLoadRefusalError+from pipelex.errors.problem import ProblemViewfrom pipelex.interpreter_hub import get_library_managerfrom pipelex.libraries.library import Libraryfrom pipelex.libraries.library_factory import LibraryFactoryfrom pipelex.libraries.library_manager import LibraryManagerfrom pipelex.pipe_operators.doc_gen.pipe_doc_gen import PipeDocGen+from tests.integration.pipelex.pipes.operator.pipe_doc_gen.doc_gen_helpers import refusal_messagesfrom tests.integration.pipelex.pipes.operator.pipe_doc_gen.test_data import PipeDocGenTestData_PACKAGE_ADDRESS = "github.com/acme/invoicing"@@ -57,12 +60,15 @@ class TestPipeDocGenDependencyTemplateFile:refusal = exc_info.valueassert refusal.source == f"{_PACKAGE_ADDRESS}/invoice/invoice.mthds"- report = str(refusal.to_error_report().model_dump())+ report = refusal_messages(refusal)assert ("The file reference 'invoice.html' in 'invoice/invoice.mthds' resolves to 'invoice/invoice.html', which is not a file of the tree."in report)assert str(tmp_path) not in report+ caller = refusal.to_problem(view=ProblemView.CALLER)+ assert caller.code == CoreCode.METHOD_RESOURCE_MISSING+ assert str(tmp_path) not in str(caller.to_wire())def test_a_dependency_s_step_reads_no_file_its_package_keeps_out(self, mocker: MockerFixture, tmp_path: Path) -> None:"""A file the package's own .gitignore keeps out of its tree is invisible to its steps, though it lies beside the bundle."""@@ -70,4 +76,4 @@ class TestPipeDocGenDependencyTemplateFile:with pytest.raises(PipeLoadRefusalError) as exc_info:self._load_dependency(mocker=mocker, package_root=tmp_path, template=_TEMPLATE)- assert "it is kept out by a .gitignore pattern" in str(exc_info.value.to_error_report().model_dump())+ assert "it is kept out by a .gitignore pattern" in refusal_messages(exc_info.value)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 063626d95..e66370bb8 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,17 +1,23 @@-import jsonfrom collections.abc import Iteratorfrom pathlib import Pathimport pytest+from mthds.protocol.problem.registry import CoreCode-from pipelex.base_exceptions import DisclosureModefrom pipelex.cogt.doc_gen.template_check import TemplateFinding, TemplateFindingSeverity+from pipelex.errors.problem import ProblemViewfrom 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_libraryfrom 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_process-from tests.integration.pipelex.pipes.operator.pipe_doc_gen.doc_gen_helpers import StubEngines, write_bundle+from tests.integration.pipelex.pipes.operator.pipe_doc_gen.doc_gen_helpers import (+ StubEngines,+ caller_text,+ only_problem_item,+ refusal_messages,+ write_bundle,+)from tests.integration.pipelex.pipes.operator.pipe_doc_gen.test_data import PipeDocGenTestData_HOST_TEMPLATE_FILE = "templates/host-invoice.docx"@@ -31,20 +37,20 @@ def restore_the_outer_library() -> Iterator[None]:clear_current_library()-async def _caller_verdict(*, mthds_content: str, host_dir: Path) -> str:- """The invalid verdict, as JSON, of submitted content validated beside a host's library directory."""+async def _caller_verdict(*, mthds_content: str, host_dir: Path) -> ValidateBundleError:+ """The invalid verdict of submitted content validated beside a host's library directory."""with pytest.raises(ValidateBundleError) as exc_info:await validate_bundles_in_process(mthds_contents=[mthds_content], library_dirs=[host_dir])- return exc_info.value.to_error_report().model_dump_json()+ return exc_info.valueasync 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."""+ """The caller's problem, as text, 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))+ problem = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert problem.code == PipelexErrorCode.CONFIG_INVALID+ return str(problem.to_wire())@pytest.mark.asyncio(loop_scope="class")@@ -58,9 +64,11 @@ class TestPipeDocGenHostTemplateFiles:verdict = await _caller_verdict(mthds_content=PipeDocGenTestData.CALLER_BUNDLE_MTHDS, host_dir=tmp_path)- assert "invoice.totl" in verdict- assert HOST_LIBRARY_FILE_PLACEHOLDER in verdict- assert "host-invoice" not in verdict+ assert only_problem_item(verdict).code == PipelexErrorCode.DOCGEN_TEMPLATE_INVALID+ report = caller_text(verdict)+ assert "invoice.totl" in report+ assert HOST_LIBRARY_FILE_PLACEHOLDER in report+ assert "host-invoice" not in report@pytest.mark.parametrize("step_fields",@@ -82,7 +90,7 @@ class TestPipeDocGenHostTemplateFiles:@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:- """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."""+ """A host step naming its template file by an absolute path is the host's fault, whose caller's problem 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()}"')@@ -100,6 +108,8 @@ class TestPipeDocGenHostTemplateFiles:verdict = await _caller_verdict(mthds_content=own_bundle, host_dir=tmp_path)- assert "which was not supplied with its bundle" in verdict- assert "'invoice.docx'" in verdict- assert HOST_LIBRARY_FILE_PLACEHOLDER not in verdict+ assert only_problem_item(verdict).code == CoreCode.METHOD_RESOURCE_MISSING+ assert "which was not supplied with its bundle" in refusal_messages(verdict)+ report = caller_text(verdict)+ assert "'invoice.docx'" in report+ assert HOST_LIBRARY_FILE_PLACEHOLDER not in reportdiff --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 135a3ea1e..9d3bf3e5f 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@@ -1,8 +1,15 @@import pytest+from mthds.protocol.problem.registry import CoreCodefrom 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 engine_unavailable_report, refusal_report+from tests.integration.pipelex.pipes.operator.pipe_doc_gen.doc_gen_helpers import (+ caller_text,+ engine_unavailable_report,+ only_problem_item,+ refusal_messages,+ refusal_report,+)from tests.integration.pipelex.pipes.operator.pipe_doc_gen.test_data import PipeDocGenTestData@@ -45,17 +52,20 @@ class TestPipeDocGenLoadRefusals:async def test_an_engine_that_does_not_print_the_step_s_source_is_refused(self) -> None:"""ReportLab prints only the auto-layout, so a step that names it with an HTML template is refused at load."""- report = await refusal_report(step_fields='format = "pdf"\nmodel = "reportlab-pdf"\ntemplate = "<h1>{{ invoice.number }}</h1>"')- assert "reportlab-pdf" in report- assert "from an HTML template, which it does not print" in report+ refusal = await refusal_report(step_fields='format = "pdf"\nmodel = "reportlab-pdf"\ntemplate = "<h1>{{ invoice.number }}</h1>"')+ assert only_problem_item(refusal).code == CoreCode.MODEL_CAPABILITY_UNSUPPORTED+ assert "reportlab-pdf" in caller_text(refusal)+ assert "from an HTML template, which it does not print" in refusal_messages(refusal)async def test_an_engine_the_deck_does_not_define_is_an_unknown_model(self) -> None:"""A misspelled engine is refused at load like any unknown model, located on the step's `model` field."""with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_contents=[PipeDocGenTestData.bundle(step_fields='format = "pdf"\nmodel = "reportlab-pfd"')])- report = str(exc_info.value.to_error_report().model_dump())- assert "reportlab-pfd" in report- assert "model" in report+ item = only_problem_item(exc_info.value)+ assert item.code == CoreCode.MODEL_UNKNOWN+ assert "'reportlab-pfd'" in item.detail+ assert item.location is not None+ assert item.location.field == "model"@pytest.mark.usefixtures("no_engines")async def test_a_pdf_layout_step_is_refused_where_the_built_in_engine_is_disabled(self) -> None:@@ -66,8 +76,10 @@ class TestPipeDocGenLoadRefusals:@pytest.mark.usefixtures("stub_engines")async def test_a_template_file_not_supplied_with_a_bundle_loaded_from_a_string_is_refused(self) -> None:"""A bundle loaded from a string has no directory to find a template file in, so the file must come with it."""- report = await refusal_report(step_fields='format = "docx"\ntemplate_file = "invoice.docx"')- assert "which was not supplied with its bundle" in report+ refusal = await refusal_report(step_fields='format = "docx"\ntemplate_file = "invoice.docx"')+ assert only_problem_item(refusal).code == CoreCode.METHOD_RESOURCE_MISSING+ assert "'invoice.docx'" in caller_text(refusal)+ assert "which was not supplied with its bundle" in refusal_messages(refusal)@pytest.mark.usefixtures("stub_engines")@pytest.mark.parametrize(@@ -83,8 +95,8 @@ class TestPipeDocGenLoadRefusals:)async def test_a_template_mistake_is_refused_at_load(self, step_fields: str, expected: str) -> None:"""A field a template or the filename names is checked against the input's concept, through loop variables too."""- report = await refusal_report(step_fields=step_fields)- assert expected in report+ refusal = await refusal_report(step_fields=step_fields)+ assert expected in caller_text(refusal)@pytest.mark.usefixtures("stub_engines")async def test_a_field_read_on_an_anything_input_is_left_to_the_dry_run(self) -> None:@@ -94,17 +106,18 @@ class TestPipeDocGenLoadRefusals:)with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_contents=[bundle])- report = str(exc_info.value.to_error_report().model_dump())- assert "could not render its template" in report- assert "title" in report- assert "AnythingContent" not in report+ item = only_problem_item(exc_info.value)+ assert item.code == CoreCode.PIPE_TEMPLATE_RENDER_FAILED+ assert "title" in item.detail+ assert "AnythingContent" not in caller_text(exc_info.value)@pytest.mark.usefixtures("stub_engines")async def test_a_misspelling_the_load_check_cannot_follow_fails_at_the_dry_run(self) -> None:"""A field read through a `set` alias escapes the load check, and the strict undefined names it at the dry run."""- report = await refusal_report(step_fields='format = "pdf"\ntemplate = "{% set buyer = invoice %}<h1>{{ buyer.custmer }}</h1>"')- assert "custmer" in report- assert "could not render its template" in report+ refusal = await refusal_report(step_fields='format = "pdf"\ntemplate = "{% set buyer = invoice %}<h1>{{ buyer.custmer }}</h1>"')+ item = only_problem_item(refusal)+ assert item.code == CoreCode.PIPE_TEMPLATE_RENDER_FAILED+ assert "custmer" in item.detail@pytest.mark.parametrize("filename",@@ -118,6 +131,6 @@ class TestPipeDocGenLoadRefusals:)with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_contents=[bundle])- report = str(exc_info.value.to_error_report().model_dump())+ report = caller_text(exc_info.value)assert "reference" in reportassert "filename" in reportdiff --git a/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_run_bundle_trees.py b/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_run_bundle_trees.pyindex f82193697..23effb06d 100644--- a/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_run_bundle_trees.py+++ b/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_run_bundle_trees.py@@ -7,6 +7,7 @@ from typing import TYPE_CHECKING, Anyimport pytestimport typer+from mthds.protocol.problem.registry import CoreCodefrom pipelex.cli.agent_cli.commands.agent_output import CliOutputFormat, set_agent_cli_error_formatfrom pipelex.cli.agent_cli.commands.run.bundle_cmd import run_bundle_cmd as agent_run_bundle_cmd@@ -50,7 +51,7 @@ class TestPipeDocGenRunBundleTrees:mocker.patch("pipelex.cli.agent_cli.commands.run.bundle_cmd.Pipelex.teardown_if_needed")def test_a_bundle_named_alone_is_refused_the_file_beside_it(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:- """With no METHODS.toml at or above it, the bundle's method is that one file, and the run says how to give it the rest."""+ """With no METHODS.toml at or above it, the bundle's method is that one file, and the run refuses the file beside it, naming it."""(tmp_path / "letter.docx").write_bytes(b"docx")bundle_path = write_bundle(directory=tmp_path, step_fields=_STEP_FIELDS, as_method=False)@@ -60,9 +61,11 @@ class TestPipeDocGenRunBundleTrees:assert exc_info.value.exit_code == 1envelope: dict[str, Any] = json.loads(capsys.readouterr().err)assert envelope["error_type"] == "ValidateBundleError"+ assert envelope["error_code"] == CoreCode.METHOD_INVALIDassert envelope["error_domain"] == "input"- messages = [item["message"] for item in envelope["validation_errors"]]- assert any("letter.docx" in message and "Run the method's folder instead, or add a METHODS.toml to it." in message for message in messages)+ # The item reads the sentence of the refusal's code, which names the file the step could not read.+ (item,) = envelope["validation_errors"]+ assert "'letter.docx'" in item["message"]def test_a_folder_whose_bundles_declare_several_main_pipes_is_refused_naming_them(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]diff --git a/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_submitted_files.py b/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_submitted_files.pyindex c819ca87a..c30f3b5b2 100644--- a/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_submitted_files.py+++ b/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_submitted_files.py@@ -5,6 +5,7 @@ from typing import Anyimport pytestfrom mthds.method_tree.digest import digest_of_contents+from mthds.protocol.problem.registry import CoreCodefrom pytest_mock import MockerFixturefrom pipelex.base_exceptions import PipelexError, ValidationErrorCategory@@ -14,6 +15,7 @@ from pipelex.core.bundle_resources.exceptions import BundleResourceNotNamedErrorfrom pipelex.core.method_trees.exceptions import MethodFileUnavailableErrorfrom pipelex.core.method_trees.tree_bundle import TreeBundleReffrom pipelex.core.stuffs.document_content import DocumentContent+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.pipe_operators.doc_gen.pipe_doc_gen import PipeDocGenfrom pipelex.pipe_operators.doc_gen.template_file_stage import DocGenTemplateFileStagefrom pipelex.pipeline.exceptions import ValidateBundleError@@ -26,6 +28,10 @@ from tests.integration.pipelex.pipes.operator.pipe_doc_gen.doc_gen_helpers imporRecordingMethodFileStore,StubEngines,WorkerLikePipeRun,+ caller_text,+ diagnosed_error_classes,+ only_problem_item,+ refusal_messages,write_bundle,)from tests.integration.pipelex.pipes.operator.pipe_doc_gen.test_data import PipeDocGenTestData@@ -95,7 +101,9 @@ class TestPipeDocGenSubmittedFiles:submitted_files=_docx_files(),)- assert "invoice.totl" in str(exc_info.value.to_error_report().model_dump())+ item = only_problem_item(exc_info.value)+ assert item.code == PipelexErrorCode.DOCGEN_TEMPLATE_INVALID+ assert "invoice.totl" in item.detail@pytest.mark.usefixtures("stub_engines")async def test_a_template_file_not_supplied_is_refused_saying_so(self) -> None:@@ -103,8 +111,12 @@ class TestPipeDocGenSubmittedFiles:with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_contents=[PipeDocGenTestData.bundle(step_fields=_DOCX_TEMPLATE_STEP)])- report = str(exc_info.value.to_error_report().model_dump())- assert "names the template file 'templates/invoice.docx', which was not supplied with its bundle" in report+ item = only_problem_item(exc_info.value)+ assert item.code == CoreCode.METHOD_RESOURCE_MISSING+ assert item.location is not None+ assert item.location.pipe == "print_invoice"+ assert "'templates/invoice.docx'" in item.detail+ assert "names the template file 'templates/invoice.docx', which was not supplied with its bundle" in refusal_messages(exc_info.value)@pytest.mark.usefixtures("stub_engines")@pytest.mark.parametrize("template_file", ["../invoice.docx", "templates/../invoice.docx"], ids=["leaves_the_bundle", "dot_dot_inside"])@@ -124,7 +136,7 @@ class TestPipeDocGenSubmittedFiles:with pytest.raises(ValidateBundleError) as exc_info:await _load_from_content(load=load, content=content, submitted_files=submitted_files)- items = exc_info.value.to_error_report().validation_errors+ items = exc_info.value.validation_error_items()assert items is not None(item,) = itemsassert item.category == ValidationErrorCategory.BLUEPRINT_VALIDATION@@ -160,7 +172,7 @@ class TestPipeDocGenSubmittedFiles:inputs=PipeDocGenTestData.INVOICE_INPUTS,)- (item,) = exc_info.value.to_error_report().validation_errors or []+ (item,) = exc_info.value.validation_error_items() or []assert item.category == ValidationErrorCategory.BLUEPRINT_VALIDATIONassert item.field_path == "pipe.print_invoice"assert "it leaves the bundle through a '..' segment" in item.message@@ -197,7 +209,7 @@ class TestPipeDocGenSubmittedFiles:mthds_contents=[content for content, _ in entries],inputs=PipeDocGenTestData.INVOICE_INPUTS,)- (item,) = exc_info.value.to_error_report().validation_errors or []+ (item,) = exc_info.value.validation_error_items() or []assert (item.category, item.domain_code, item.pipe_code) == (ValidationErrorCategory.BLUEPRINT_VALIDATION,PipeDocGenTestData.OTHER_DOMAIN,@@ -223,7 +235,7 @@ class TestPipeDocGenSubmittedFiles:submitted_files={"invoice.html": b"<h1>{{ invoice.numbr }}</h1>"},)- assert "numbr" in str(exc_info.value.to_error_report().model_dump())+ assert "numbr" in caller_text(exc_info.value)async def test_a_run_prints_with_the_submitted_html_template(self, stub_engines: StubEngines) -> None:await PipelexMTHDSProtocol(submitted_files={"invoice.html": b"<h1>{{ invoice.number }}</h1>"}).execute(@@ -339,8 +351,7 @@ class TestPipeDocGenSubmittedFiles:)assert remote_worker.received_crates- report = str(exc_info.value.to_error_report().model_dump())- assert MethodFileUnavailableError.__name__ in report+ assert MethodFileUnavailableError.__name__ in diagnosed_error_classes(exc_info.value)assert stub_engines.check_requests == []@pytest.mark.parametrize(@@ -361,7 +372,7 @@ class TestPipeDocGenSubmittedFiles:with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_contents=[bundle_path.read_text(encoding="utf-8")], mthds_sources=[str(bundle_path)])- assert "which was not supplied with its bundle" in str(exc_info.value.to_error_report().model_dump())+ assert "which was not supplied with its bundle" in refusal_messages(exc_info.value)assert stub_engines.check_requests == []@pytest.mark.parametrize("pipe_run_mode", [pytest.param(PipeRunMode.LIVE, id="live"), pytest.param(PipeRunMode.DRY, id="dry")])@@ -403,7 +414,7 @@ class TestPipeDocGenSubmittedFiles:await PipelexMTHDSProtocol().execute(mthds_contents=[content], inputs=PipeDocGenTestData.INVOICE_INPUTS)for exc_info in (validate_exc_info, run_exc_info):- assert "which was not supplied with its bundle" in str(exc_info.value.to_error_report().model_dump())+ assert "which was not supplied with its bundle" in refusal_messages(exc_info.value)assert stub_engines.check_requests == []assert stub_engines.engine.jobs == []diff --git a/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_template_assets.py b/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_template_assets.pyindex 453bc086d..e69b5b3ea 100644--- a/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_template_assets.py+++ b/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_template_assets.py@@ -19,6 +19,9 @@ from tests.integration.pipelex.pipes.operator.pipe_doc_gen.doc_gen_helpers imporStubEngine,StubEngines,WorkerLikePipeRun,+ caller_text,+ diagnosed_error_classes,+ refusal_messages,write_bundle,)from tests.integration.pipelex.pipes.operator.pipe_doc_gen.test_data import PipeDocGenTestData@@ -208,8 +211,8 @@ class TestPipeDocGenTemplateAssets:with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_file_path=bundle_path)- # The report names the caller's own bundle file as its source; the message names files by their tree paths alone.- message = exc_info.value.message+ # The verdict names the caller's own bundle file as its source; the refusal names files by their tree paths alone.+ message = refusal_messages(exc_info.value)assert f"names '{reference}' in the template file 'templates/invoice.html'" in messageassert expected in messageassert str(tmp_path) not in message@@ -247,10 +250,11 @@ class TestPipeDocGenTemplateAssets:mthds_contents=[bundle_path.read_text(encoding="utf-8")], inputs=inputs)- report = str(exc_info.value.to_error_report().model_dump())- assert TemplateUrlRefusedError.__name__ in report+ assert TemplateUrlRefusedError.__name__ in diagnosed_error_classes(exc_info.value)+ report = refusal_messages(exc_info.value)assert expected in reportassert str(tmp_path) not in report+ assert str(tmp_path) not in caller_text(exc_info.value)assert engine.read == {}async def test_a_bundle_named_alone_is_told_to_hand_over_its_folder(self, engine: _AssetReadingEngine, tmp_path: Path) -> None:@@ -262,8 +266,7 @@ class TestPipeDocGenTemplateAssets:with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_file_path=bundle_path)- report = str(exc_info.value.to_error_report().model_dump())- assert "Hand over the method's directory instead" in report+ assert "Hand over the method's directory instead" in refusal_messages(exc_info.value)assert engine.jobs == []async def test_an_inline_template_of_a_bundle_with_no_method_tree_names_no_file(self, engine: _AssetReadingEngine) -> None:@@ -273,7 +276,7 @@ class TestPipeDocGenTemplateAssets:with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_contents=[PipeDocGenTestData.bundle(step_fields=step_fields)])- assert "belongs to no method tree" in str(exc_info.value.to_error_report().model_dump())+ assert "belongs to no method tree" in refusal_messages(exc_info.value)assert engine.jobs == []async def test_a_url_a_run_s_input_supplies_names_no_file_when_the_template_has_no_method_tree(self, engine: _AssetReadingEngine) -> None:@@ -284,9 +287,8 @@ class TestPipeDocGenTemplateAssets:with pytest.raises(PipelexError) as exc_info:await PipelexMTHDSProtocol().execute(mthds_contents=[PipeDocGenTestData.bundle(step_fields=step_fields)], inputs=inputs)- report = str(exc_info.value.to_error_report().model_dump())- assert TemplateUrlRefusedError.__name__ in report- assert "belongs to no method's folder" in report+ assert TemplateUrlRefusedError.__name__ in diagnosed_error_classes(exc_info.value)+ assert "belongs to no method's folder" in refusal_messages(exc_info.value)(job,) = engine.jobsassert job.base_url is Noneassert engine.read == {}diff --git a/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_template_files.py b/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_template_files.pyindex 175b2964f..0da5da380 100644--- a/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_template_files.py+++ b/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_template_files.py@@ -2,16 +2,26 @@ from pathlib import Pathimport pytestfrom mthds.method_tree.models import MethodTree+from mthds.protocol.problem.registry import CoreCode, ProblemDomainfrom pytest_mock import MockerFixturefrom pipelex.cogt.doc_gen.input_shape import InputShapeKindfrom pipelex.cogt.doc_gen.template_check import TemplateFinding, TemplateFindingSeverityfrom pipelex.core.method_trees.method_file_store import LOCAL_METHOD_FILESfrom pipelex.core.method_trees.tree_bundle import MethodFileRef+from pipelex.errors.problem import ProblemView+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.pipe_operators.doc_gen.pipe_doc_gen import PipeDocGenfrom pipelex.pipeline.exceptions import ValidateBundleErrorfrom pipelex.pipeline.validate_bundle import ValidateBundleResult, validate_bundle-from tests.integration.pipelex.pipes.operator.pipe_doc_gen.doc_gen_helpers import METHOD_MANIFEST, StubEngines, write_bundle+from tests.integration.pipelex.pipes.operator.pipe_doc_gen.doc_gen_helpers import (+ METHOD_MANIFEST,+ StubEngines,+ caller_text,+ only_problem_item,+ refusal_messages,+ write_bundle,+)from tests.integration.pipelex.pipes.operator.pipe_doc_gen.test_data import PipeDocGenTestData_DOCX_TEMPLATE_STEP = 'format = "docx"\ntemplate_file = "invoice.docx"'@@ -35,16 +45,22 @@ async def _validate_with_html_template_file(*, directory: Path, load: str, templclass TestPipeDocGenTemplateFiles:@pytest.mark.usefixtures("stub_engines")@pytest.mark.parametrize(- ("template_file", "expected"),+ ("template_file", "expected_code", "expected"),[- ("invoice.docx", "resolves to 'invoice.docx', which is not a file of the tree."),- ("../outside.docx", "climbs above the root of its method tree"),- ("ignored.docx", "which is not a file of the tree: it is kept out by a .gitignore pattern"),- (".templates/invoice.docx", "which is not a file of the tree: it is kept out by a path segment starting with a dot"),+ ("invoice.docx", CoreCode.METHOD_RESOURCE_MISSING, "resolves to 'invoice.docx', which is not a file of the tree."),+ ("../outside.docx", CoreCode.SECURITY_METHOD_PATH_REFUSED, "climbs above the root of its method tree"),+ ("ignored.docx", CoreCode.METHOD_RESOURCE_MISSING, "which is not a file of the tree: it is kept out by a .gitignore pattern"),+ (+ ".templates/invoice.docx",+ CoreCode.METHOD_RESOURCE_MISSING,+ "which is not a file of the tree: it is kept out by a path segment starting with a dot",+ ),],ids=["missing_file", "outside_the_tree", "gitignored", "hidden"],)- async def test_a_template_file_is_a_file_of_the_bundle_s_method_tree(self, tmp_path: Path, template_file: str, expected: str) -> None:+ async def test_a_template_file_is_a_file_of_the_bundle_s_method_tree(+ self, tmp_path: Path, template_file: str, expected_code: CoreCode, expected: str+ ) -> None:"""A template file must be a file of the method's tree: one outside it, or one its membership rule keeps out, is never read."""method_dir = tmp_path / "method"method_dir.mkdir()@@ -58,7 +74,8 @@ class TestPipeDocGenTemplateFiles:with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_file_path=bundle_path)- assert expected in str(exc_info.value.to_error_report().model_dump())+ assert only_problem_item(exc_info.value).code == expected_code+ assert expected in refusal_messages(exc_info.value)@pytest.mark.usefixtures("stub_engines")async def test_a_template_file_climbs_through_dot_dot_to_another_folder_of_its_tree(self, tmp_path: Path) -> None:@@ -89,10 +106,12 @@ class TestPipeDocGenTemplateFiles:with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_file_path=bundle_path)- report = str(exc_info.value.to_error_report().model_dump())+ problem = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert problem.domain == ProblemDomain.METHOD+ assert only_problem_item(exc_info.value).code == CoreCode.METHOD_RESOURCE_MISSING+ report = refusal_messages(exc_info.value)assert "names the template file 'invoice.docx'" in reportassert "Run the method's folder instead, or add a METHODS.toml to it." in report- assert exc_info.value.to_error_report().error_domain == "input"@pytest.mark.usefixtures("stub_engines")async def test_a_symbolic_link_in_the_method_refuses_its_tree(self, tmp_path: Path) -> None:@@ -106,7 +125,7 @@ class TestPipeDocGenTemplateFiles:with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_file_path=bundle_path)- assert "holds a symbolic link, 'linked.docx'" in str(exc_info.value.to_error_report().model_dump())+ assert "holds a symbolic link, 'linked.docx'" in refusal_messages(exc_info.value)@pytest.mark.usefixtures("stub_engines")async def test_a_template_file_named_by_an_absolute_path_is_refused_without_repeating_it(self, tmp_path: Path) -> None:@@ -118,9 +137,10 @@ class TestPipeDocGenTemplateFiles:with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_file_path=bundle_path)- report = str(exc_info.value.to_error_report().model_dump())+ report = refusal_messages(exc_info.value)assert "a path relative to the bundle's file, in its method, and this one cannot be: it is absolute" in reportassert str(absolute_template) not in report+ assert str(absolute_template) not in caller_text(exc_info.value)@pytest.mark.usefixtures("stub_engines")@pytest.mark.parametrize("load", ["from_its_directory", "from_content"])@@ -129,7 +149,7 @@ class TestPipeDocGenTemplateFiles:with pytest.raises(ValidateBundleError) as exc_info:await _validate_with_html_template_file(directory=tmp_path, load=load, template_bytes="<p>Facture émise</p>".encode("latin-1"))- assert "could not read the template file 'invoice.html' as UTF-8 text" in str(exc_info.value.to_error_report().model_dump())+ assert "could not read the template file 'invoice.html' as UTF-8 text" in refusal_messages(exc_info.value)@pytest.mark.usefixtures("stub_engines")async def test_an_html_template_file_changed_after_its_tree_was_listed_is_refused_not_read_from_disk(@@ -149,7 +169,7 @@ class TestPipeDocGenTemplateFiles:with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_file_path=bundle_path)- assert "could not read the template file 'invoice.html' as its method tree listed it" in str(exc_info.value.to_error_report().model_dump())+ assert "could not read the template file 'invoice.html' as its method tree listed it" in refusal_messages(exc_info.value)@pytest.mark.usefixtures("stub_engines")@pytest.mark.parametrize("load", ["from_its_directory", "from_content"])@@ -172,7 +192,9 @@ class TestPipeDocGenTemplateFiles:with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_file_path=bundle_path)- assert "invoice.totl" in str(exc_info.value.to_error_report().model_dump())+ item = only_problem_item(exc_info.value)+ assert item.code == PipelexErrorCode.DOCGEN_TEMPLATE_INVALID+ assert "invoice.totl" in item.detail(request,) = stub_engines.check_requestsassert request.template == b"docx bytes"assert request.template_name == "invoice.docx"diff --git a/tests/integration/pipelex/pipes/operator/pipe_func/test_pipe_func_validation_errors.py b/tests/integration/pipelex/pipes/operator/pipe_func/test_pipe_func_validation_errors.pyindex eec2fe04a..d2cf643f8 100644--- a/tests/integration/pipelex/pipes/operator/pipe_func/test_pipe_func_validation_errors.py+++ b/tests/integration/pipelex/pipes/operator/pipe_func/test_pipe_func_validation_errors.py@@ -10,9 +10,10 @@ from pathlib import Pathfrom typing import ClassVarimport pytest+from mthds.protocol.problem.registry import CoreCode+from pipelex.errors.problem import ProblemViewfrom pipelex.interpreter_hub import clear_current_library, get_current_library_id_or_none, get_library_manager-from pipelex.libraries.exceptions import LibraryErrorfrom pipelex.pipeline.exceptions import ValidateBundleErrorfrom pipelex.pipeline.validate_bundle import ValidateBundleResult, validate_bundle@@ -180,6 +181,19 @@ async def _validate_and_release(*, mthds_file_path: Path, library_dirs: list[Patreturn result+def _caller_text(error: ValidateBundleError) -> str:+ """What a caller reads of the refused validation: each item of the invalid verdict, in the sentence its code renders.++ A function the step cannot call is the method's fault, found by the dry run, so the verdict holds one item coded+ `method.function_invalid`, whose sentence names the function and why it cannot be used.+ """+ problem = error.to_problem(view=ProblemView.CALLER)+ assert problem.code == CoreCode.METHOD_INVALID+ assert problem.errors is not None+ assert [item.code for item in problem.errors] == [CoreCode.METHOD_FUNCTION_INVALID]+ return " ".join(item.detail for item in problem.errors)++@pytest.mark.asyncio(loop_scope="class")class TestPipeFuncValidationErrors:"""Tests for PipeFunc validation error reporting when @pipe_func decorated functions have issues."""@@ -207,15 +221,14 @@ class TestPipeFuncValidationErrors:py_file.write_text(TestData.FUNC_WITH_DECORATOR_NO_RETURN_TYPE)# Validate the bundle - should fail with a CLEAR error message- # Currently raises LibraryError, but ValidateBundleError is also acceptable- with pytest.raises((ValidateBundleError, LibraryError)) as exc_info:+ with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_file_path=mthds_file,library_dirs=[temp_path],)error = exc_info.value- error_message = str(error)+ error_message = _caller_text(error)# The error should mention the function nameassert "my_func_no_return_type" in error_message, f"Error message should mention the function name. Got: {error_message}"@@ -285,14 +298,14 @@ class TestPipeFuncValidationErrors:mthds_file.write_text(TestData.MTHDS_CONTENT_WITH_PIPE_FUNC)# Try to validate - should fail with informative error- with pytest.raises((ValidateBundleError, LibraryError)) as exc_info:+ with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_file_path=mthds_file,library_dirs=[temp_path],)error = exc_info.value- error_message = str(error)+ error_message = _caller_text(error)# The function should be mentioned in the errorassert "my_func_no_return_type" in error_message@@ -340,14 +353,14 @@ class TestPipeFuncValidationErrors:py_file.write_text(python_code)# Validate the bundle - should fail with a specific error message- with pytest.raises((ValidateBundleError, LibraryError)) as exc_info:+ with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_file_path=mthds_file,library_dirs=[temp_path],)error = exc_info.value- error_message = str(error)+ error_message = _caller_text(error)# The error should mention the function nameassert function_name in error_message, f"Error message should mention the function name '{function_name}'. Got: {error_message}"@@ -403,14 +416,14 @@ output = "Text"py_file.write_text(func_code)# Validate the bundle - should fail because return type doesn't match concept's structure class- with pytest.raises((ValidateBundleError, LibraryError, TypeError)) as exc_info:+ with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_file_path=mthds_file,library_dirs=[temp_path],)error = exc_info.value- error_message = str(error)+ error_message = _caller_text(error)# The error should mention the function nameassert "func_wrong_structure_class" in error_message, f"Error should mention the function name. Got: {error_message}"@@ -513,14 +526,14 @@ output = "Text[]"py_file.write_text(func_code)# Validate the bundle - should fail with clear error about item type mismatch- with pytest.raises((ValidateBundleError, LibraryError, TypeError)) as exc_info:+ with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_file_path=mthds_file,library_dirs=[temp_path],)error = exc_info.value- error_message = str(error)+ error_message = _caller_text(error)# The error should mention the function nameassert "func_returns_wrong_list_content" in error_message, f"Error should mention the function name. Got: {error_message}"@@ -571,14 +584,14 @@ output = "Text[]"py_file.write_text(func_code)# Validate the bundle - should fail because return type is not ListContent- with pytest.raises((ValidateBundleError, LibraryError, TypeError)) as exc_info:+ with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_file_path=mthds_file,library_dirs=[temp_path],)error = exc_info.value- error_message = str(error)+ error_message = _caller_text(error)# The error should mention the function nameassert "func_returns_single_instead_of_list" in error_message, f"Error should mention the function name. Got: {error_message}"diff --git a/tests/integration/pipelex/pipes/operator/pipe_judge/test_pipe_judge_load_refusals.py b/tests/integration/pipelex/pipes/operator/pipe_judge/test_pipe_judge_load_refusals.pyindex acdaaadcf..57cd5f948 100644--- a/tests/integration/pipelex/pipes/operator/pipe_judge/test_pipe_judge_load_refusals.py+++ b/tests/integration/pipelex/pipes/operator/pipe_judge/test_pipe_judge_load_refusals.py@@ -1,8 +1,12 @@"""A PipeJudge step is refused when its method loads, before a run spends anything, for each thing it cannot do."""+from typing import TYPE_CHECKING+import pytest+from mthds.protocol.problem.registry import CoreCodefrom pipelex.cogt.model_backends.model_type import ModelType+from pipelex.errors.problem import ProblemViewfrom pipelex.pipeline.exceptions import ValidateBundleErrorfrom pipelex.pipeline.validate_bundle import validate_bundlefrom pipelex.runtime_hub import get_model_deck@@ -13,24 +17,49 @@ from tests.integration.pipelex.pipes.operator.pipe_judge.test_data import (PipeJudgeSeveralQuestionsTestData,)+if TYPE_CHECKING:+ from mthds.protocol.problem.models import ProblemItem+_MODEL = f'model = "{PipeJudgeLoadTestData.JUDGMENT_MODEL}"'_STRUCTURE = PipeJudgeSeveralQuestionsTestData.STRUCTURE_QUESTIONS = PipeJudgeSeveralQuestionsTestData.QUESTIONS-async def _refusal_report(bundle: str) -> str:+async def _refusal(bundle: str) -> ValidateBundleError:with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_contents=[bundle])- return str(exc_info.value.to_error_report().model_dump())+ return exc_info.value+++async def _refusal_report(bundle: str) -> str:+ """The invalid verdict a caller reads, as text: its items, as `/validate` and the CLI list them, and its problem."""+ refusal = await _refusal(bundle)+ items = [item.model_dump(mode="json", exclude_none=True) for item in refusal.validation_error_items()]+ return f"{items}{refusal.to_problem(view=ProblemView.CALLER).to_wire()}"+++def _only_problem_item(refusal: ValidateBundleError) -> "ProblemItem":+ """The one item of an invalid verdict, as the caller's problem lists it."""+ problem = refusal.to_problem(view=ProblemView.CALLER)+ assert problem.code == CoreCode.METHOD_INVALID+ assert problem.errors is not None+ (item,) = problem.errors+ return item@pytest.mark.asyncio(loop_scope="class")class TestPipeJudgeLoadRefusals:@pytest.mark.usefixtures("no_judgment_default")async def test_a_step_with_no_model_and_no_default_is_refused(self) -> None:- report = await _refusal_report(PipeJudgeLoadTestData.bundle())- assert "PipeJudge 'judge_it' has no judgment model" in report- assert "`choice_default` under `[judgment]`" in report+ """The caller reads the code's sentence, naming the kind of model; the deck's setting to fill is the operator's to read."""+ refusal = await _refusal(PipeJudgeLoadTestData.bundle())++ item = _only_problem_item(refusal)+ assert item.code == CoreCode.MODEL_UNSPECIFIED+ assert item.detail == "The step names no judgment model, and the deployment names no default for that kind."+ (validation_item,) = refusal.validation_error_items()+ assert validation_item.message == item.detail+ assert "`choice_default` under `[judgment]`" in str(refusal.__cause__)async def test_an_unknown_model_is_refused_on_its_field(self) -> None:report = await _refusal_report(PipeJudgeLoadTestData.bundle(step_fields='model = "jev-9.99.9"'))@@ -62,10 +91,17 @@ class TestPipeJudgeLoadRefusals:],)async def test_a_file_the_prompt_presents_is_refused_for_a_text_only_model(self, inputs: str, file_kind: str) -> None:- report = await _refusal_report(PipeJudgeLoadTestData.bundle(inputs=inputs, prompt="Inspect this: $photo", step_fields=_MODEL))- assert f"does not read {file_kind}" in report- assert "presents 'photo' in its prompt" in report- assert PipeJudgeLoadTestData.JUDGMENT_MODEL in report+ """The caller reads the code's sentence, naming the model and the kind of file it does not read."""+ refusal = await _refusal(PipeJudgeLoadTestData.bundle(inputs=inputs, prompt="Inspect this: $photo", step_fields=_MODEL))++ item = _only_problem_item(refusal)+ assert item.code == CoreCode.MODEL_CAPABILITY_UNSUPPORTED+ expected_detail = f"The model '{PipeJudgeLoadTestData.JUDGMENT_MODEL}' does not support {file_kind[:-1]} inputs, which the step needs."+ assert item.detail == expected_detail+ (validation_item,) = refusal.validation_error_items()+ assert validation_item.message == expected_detail+ # The refusal's own message, naming the input the prompt presents, is the operator's diagnostics.+ assert "presents 'photo' in its prompt" in str(refusal.__cause__)@pytest.mark.usefixtures("judgment_model_reading_files")@pytest.mark.parametrize(diff --git a/tests/integration/pipelex/pipes/templates/test_template_private_name_lint.py b/tests/integration/pipelex/pipes/templates/test_template_private_name_lint.pyindex d9973c143..799a2a945 100644--- a/tests/integration/pipelex/pipes/templates/test_template_private_name_lint.py+++ b/tests/integration/pipelex/pipes/templates/test_template_private_name_lint.py@@ -202,7 +202,7 @@ class TestTemplatePrivateNameLint:load_empty_library()with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_contents=[_CONSTRUCT_MTHDS])- items = exc_info.value.to_error_report().validation_errors or []+ items = exc_info.value.validation_error_items() or []assert [(item.category, item.error_type) for item in items] == [(ValidationErrorCategory.PIPE_VALIDATION, PipeValidationErrorType.TEMPLATE_PRIVATE_NAME)]@@ -214,6 +214,6 @@ class TestTemplatePrivateNameLint:load_empty_library()with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_contents=[_CONSTRUCT_FROM_DUNDER_MTHDS])- items = exc_info.value.to_error_report().validation_errors or []+ items = exc_info.value.validation_error_items() or []assert len(items) == 1assert "reads '__class__', a name starting with an underscore" in (items[0].message or "")diff --git a/tests/integration/pipelex/test_extras/test_mthds_corpus_entries.py b/tests/integration/pipelex/test_extras/test_mthds_corpus_entries.pyindex d6dfd94e0..8a3f1366d 100644--- a/tests/integration/pipelex/test_extras/test_mthds_corpus_entries.py+++ b/tests/integration/pipelex/test_extras/test_mthds_corpus_entries.py@@ -47,7 +47,7 @@ class TestMthdsCorpusEntries:with pytest.raises(ValidateBundleError) as raised:await validate_bundle(mthds_file_path=entry.bundle_path, library_dirs=[entry.directory])- observed = [item.error_type for item in raised.value.to_error_report().validation_errors or []]+ observed = [item.error_type for item in raised.value.validation_error_items()]assert observed == [entry.manifest.expected_error], (f"Corpus entry '{entry.name}' declares expected_error={entry.manifest.expected_error!r} but produced {observed!r}")@@ -85,6 +85,6 @@ prompt = "Write the berth note for $vessel arriving on the $tide tide."declared_by_a_correct_entry = "missing_input_variable"declared_by_a_drifted_entry = "unknown_pipe_type"- observed = [item.error_type for item in raised.value.to_error_report().validation_errors or []]+ observed = [item.error_type for item in raised.value.validation_error_items()]assert observed == [declared_by_a_correct_entry]assert observed != [declared_by_a_drifted_entry]diff --git a/tests/unit/pipelex/cli/agent_cli/test_folder_entry_commands.py b/tests/unit/pipelex/cli/agent_cli/test_folder_entry_commands.pyindex 710ce5bf3..85cc82fb2 100644--- a/tests/unit/pipelex/cli/agent_cli/test_folder_entry_commands.py+++ b/tests/unit/pipelex/cli/agent_cli/test_folder_entry_commands.py@@ -16,7 +16,7 @@ from pipelex.cli.agent_cli.commands.inputs.bundle_cmd import inputs_bundle_cmdfrom pipelex.cli.agent_cli.commands.run.bundle_cmd import run_bundle_cmdfrom pipelex.cli.agent_cli.commands.validate.bundle_cmd import validate_bundle_cmdfrom pipelex.cli.bundle_target_resolution import resolve_method_folder_run-from pipelex.pipeline.exceptions import ValidateBundleError+from pipelex.pipeline.exceptions import MethodEntryErrorfrom pipelex.pipeline.fixes.fix_loop import FixBundleResultfrom tests.helpers.method_folders import NAMED_PIPE, MethodFolderShape, write_method_folder@@ -36,8 +36,8 @@ _VALID_RESULT: dict[str, Any] = {"success": True, "is_valid": True, "is_runnabledef _run_refusal(*, directory: Path) -> str:- """The message `run bundle` refuses the folder with."""- with pytest.raises(ValidateBundleError) as exc_info:+ """The message `run bundle` refuses the folder with: no single pipe to start at is the run's own refusal, no verdict."""+ with pytest.raises(MethodEntryError) as exc_info:resolve_method_folder_run(directory=directory, pipe_override=None)return exc_info.value.messagediff --git a/tests/unit/pipelex/cli/commands/run/test_bundle_cmd_method_folder.py b/tests/unit/pipelex/cli/commands/run/test_bundle_cmd_method_folder.pyindex 14f6dbbd2..01f279953 100644--- a/tests/unit/pipelex/cli/commands/run/test_bundle_cmd_method_folder.py+++ b/tests/unit/pipelex/cli/commands/run/test_bundle_cmd_method_folder.py@@ -63,15 +63,19 @@ class TestBundleCmdMethodFolder:assert kwargs["pipe_code"] == "folder_b.second"assert kwargs["bundle_path"] is None- def test_a_folder_with_no_single_entry_is_refused(self, mocker: MockerFixture, tmp_path: Path) -> None:+ def test_a_folder_with_no_single_entry_is_refused(self, mocker: MockerFixture, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:+ """No single pipe to start at is the run's refusal, printed with its message, and no verdict on the method."""mock_execute = mocker.patch(f"{BUNDLE_CMD_MODULE}.execute_run")mock_handler = mocker.patch(f"{BUNDLE_CMD_MODULE}.handle_validate_bundle_error", side_effect=typer.Exit(1))(tmp_path / "a.mthds").write_text(_bundle(domain="folder_a", pipe_code="first", main_pipe="first"), encoding="utf-8")(tmp_path / "b.mthds").write_text(_bundle(domain="folder_b", pipe_code="second", main_pipe="second"), encoding="utf-8")- with pytest.raises(typer.Exit):+ with pytest.raises(typer.Exit) as exc_info:run_bundle_cmd(path=str(tmp_path))- verdict = mock_handler.call_args.args[0]- assert "several of its bundles declare a main_pipe: 'a.mthds' declares 'first', 'b.mthds' declares 'second'" in verdict.message+ assert exc_info.value.exit_code == 1+ printed = capsys.readouterr().err+ assert printed.startswith("Failed to run: ")+ assert "several of its bundles declare a main_pipe: 'a.mthds' declares 'first', 'b.mthds' declares 'second'" in printed+ mock_handler.assert_not_called()mock_execute.assert_not_called()diff --git a/tests/unit/pipelex/cli/commands/test_bundle_path_resolver.py b/tests/unit/pipelex/cli/commands/test_bundle_path_resolver.pyindex 9ce19d217..ad4392930 100644--- a/tests/unit/pipelex/cli/commands/test_bundle_path_resolver.py+++ b/tests/unit/pipelex/cli/commands/test_bundle_path_resolver.py@@ -17,7 +17,7 @@ from pipelex.base_exceptions import PipelexConfigErrorfrom pipelex.cli.bundle_target_resolution import resolve_method_folder_runfrom pipelex.cli.commands.bundle_path_resolver import resolve_build_bundle_target, resolve_bundle_targetfrom pipelex.cli.judged_target import JudgedBundleTarget-from pipelex.pipeline.exceptions import ValidateBundleError+from pipelex.pipeline.exceptions import MethodEntryError, ValidateBundleErrorfrom tests.helpers.method_folders import NAMED_PIPE, MethodFolderShape, write_method_folderif TYPE_CHECKING:@@ -30,10 +30,19 @@ _METHOD_TREES_MODULE = "pipelex.libraries.method_trees"def _run_refusal(*, directory: Path) -> str:- """The message `run bundle` refuses the folder with."""- with pytest.raises(ValidateBundleError) as exc_info:+ """The message of the refusal `run bundle` refuses the folder with.++ No single pipe to start at is the run's own `MethodEntryError`, no verdict on a method that may be valid. A folder+ holding no bundle is the method's refusal, so the run reports it as the invalid verdict, whose items read the code's+ sentence and whose cause is that same `MethodEntryError`, the one a `build` command reports as it is.+ """+ with pytest.raises((MethodEntryError, ValidateBundleError)) as exc_info:resolve_method_folder_run(directory=directory, pipe_override=None)- return exc_info.value.message+ refusal = exc_info.value+ if isinstance(refusal, ValidateBundleError):+ assert isinstance(refusal.__cause__, MethodEntryError)+ return refusal.__cause__.message+ return refusal.messageclass TestHumanBundlePathResolver:diff --git a/tests/unit/pipelex/cli/commands/test_folder_entry_commands.py b/tests/unit/pipelex/cli/commands/test_folder_entry_commands.pyindex 8b869aa6f..d8725de97 100644--- a/tests/unit/pipelex/cli/commands/test_folder_entry_commands.py+++ b/tests/unit/pipelex/cli/commands/test_folder_entry_commands.py@@ -15,7 +15,7 @@ from pipelex.cli.commands.build.output.bundle_cmd import build_output_bundle_cmdfrom pipelex.cli.commands.fix.bundle_cmd import fix_bundle_cmdfrom pipelex.cli.commands.run.bundle_cmd import run_bundle_cmdfrom pipelex.cli.commands.validate.bundle_cmd import validate_bundle_cmd-from pipelex.pipeline.exceptions import ValidateBundleError+from pipelex.pipeline.exceptions import MethodEntryErrorfrom tests.helpers.method_folders import NAMED_PIPE, MethodFolderShape, write_method_folderif TYPE_CHECKING:@@ -29,8 +29,8 @@ _BUILD_COMMANDS = ["build_inputs", "build_output"]def _run_refusal(*, directory: Path) -> str:- """The message `run bundle` refuses the folder with."""- with pytest.raises(ValidateBundleError) as exc_info:+ """The message `run bundle` refuses the folder with: no single pipe to start at is the run's own refusal, no verdict."""+ with pytest.raises(MethodEntryError) as exc_info:resolve_method_folder_run(directory=directory, pipe_override=None)return exc_info.value.messagediff --git a/tests/unit/pipelex/cli/test_agent_output.py b/tests/unit/pipelex/cli/test_agent_output.pyindex 9104dc6f1..0159bc631 100644--- a/tests/unit/pipelex/cli/test_agent_output.py+++ b/tests/unit/pipelex/cli/test_agent_output.py@@ -34,10 +34,14 @@ from pipelex.cogt.exceptions import ()from pipelex.cogt.inference.error_classification import UserAction, UserActionKindfrom pipelex.cogt.model_backends.model_type import ModelType+from pipelex.errors.problem import ProblemViewfrom pipelex.pipe_run.exceptions import PipeRouterError+from pipelex.pipe_run.located_failure import make_unexpected_failurefrom pipelex.pipeline.exceptions import PipelineExecutionError, ValidateBundleError+from pipelex.runtime_bridge.exceptions import MissingOrchestratorErrorfrom pipelex.system.pipe_run_mode import PipeRunModefrom pipelex.tools.misc.exceptions import RemoteFileFetchError+from tests.helpers.recovered_problem import make_recovered_url_refusalif TYPE_CHECKING:from collections.abc import Iterator@@ -269,11 +273,11 @@ class TestAgentOutput:assert "no traceback" in parsed["error_source"][0]# -------------------------------------------------------------------------- # to_error_report() integration tests+ # to_problem() integration tests# -------------------------------------------------------------------------def test_agent_error_uses_report_hint_from_cogt_error(self, capsys: pytest.CaptureFixture[str]) -> None:- """agent_error should use user_action from to_error_report() as the hint field."""+ """agent_error should use the next step from to_problem() as the hint field."""cause = CogtError("inference failed",user_action=UserAction(kind=UserActionKind.CHECK_CREDENTIALS, detail="Check your API key and try again"),@@ -307,6 +311,44 @@ class TestAgentOutput:parsed = json.loads(capsys.readouterr().err)assert parsed["error_code"] == CoreCode.INPUT_URL_UNREACHABLE+ def test_agent_error_classifies_a_recovered_problem_by_its_own_code(self, capsys: pytest.CaptureFixture[str]) -> None:+ """A cause reporting a problem it recovered gives its code, domain and verdict together with its step, never its class's."""+ cause = make_recovered_url_refusal()+ problem = cause.to_problem(view=ProblemView.OPERATOR)+ with pytest.raises(typer.Exit):+ agent_error("the run failed on the worker", error_type="RecoveredProblemError", cause=cause)++ parsed = json.loads(capsys.readouterr().err)+ assert parsed["error_code"] == CoreCode.INPUT_URL_UNREACHABLE+ assert parsed["error_domain"] == "input"+ assert parsed["retryable"] is True+ assert parsed["hint"] == problem.next_step.detail++ def test_agent_error_lists_no_item_of_a_verdict_behind_a_foreign_exception(self, capsys: pytest.CaptureFixture[str]) -> None:+ """A foreign exception raised from a handled verdict is a new failure: its envelope lists none of the verdict's items."""+ stale_verdict = ValidateBundleError(message="validation failed", pipelex_bundle_blueprint_validation_errors=[])+ foreign_fault = RuntimeError("the cache could not be written")+ foreign_fault.__cause__ = stale_verdict+ stand_in = make_unexpected_failure(error=foreign_fault)++ with pytest.raises(typer.Exit):+ agent_error("unexpected failure", error_type="PipelexUnexpectedError", cause=stand_in)++ parsed = json.loads(capsys.readouterr().err)+ assert parsed["error_code"] == CoreCode.RUNTIME_UNEXPECTED+ assert "validation_errors" not in parsed++ def test_agent_error_lists_the_items_of_a_verdict_under_pipelex_wrappers(self, capsys: pytest.CaptureFixture[str]) -> None:+ verdict = ValidateBundleError(message="Pipe 'post_notice' could not be loaded")+ wrapper = PipelexError("the run was refused")+ wrapper.__cause__ = verdict++ with pytest.raises(typer.Exit):+ agent_error("the run was refused", error_type="PipelexError", cause=wrapper)++ parsed = json.loads(capsys.readouterr().err)+ assert [item["message"] for item in parsed["validation_errors"]] == ["Pipe 'post_notice' could not be loaded"]+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):@@ -316,7 +358,7 @@ class TestAgentOutput: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()."""+ """agent_error should include error_category from to_problem()."""cause = CogtError("bad config", error_category=InferenceErrorCategory.CONFIGURATION)with pytest.raises(typer.Exit):agent_error("bad config", error_type="CogtError", cause=cause)@@ -344,6 +386,17 @@ class TestAgentOutput:# hint should come from AGENT_ERROR_HINTS since PipelexError has no user_actionassert parsed["hint"] == AGENT_ERROR_HINTS["PipeExecutionError"]+ def test_agent_error_falls_back_to_the_code_s_next_step(self, capsys: pytest.CaptureFixture[str]) -> None:+ """With no advice on the chain and no table entry, the hint is the code's next step as the operator reads it."""+ cause = MissingOrchestratorError(mode="temporal")+ with pytest.raises(typer.Exit):+ agent_error(cause.message, error_type="MissingOrchestratorError", cause=cause)++ parsed = json.loads(capsys.readouterr().err)+ assert parsed["hint"] == (+ "Install a plugin that provides 'temporal' for the setting 'orchestration_mode', or choose a value an installed plugin provides."+ )+def test_agent_error_report_hint_overrides_lookup(self, capsys: pytest.CaptureFixture[str]) -> None:"""When cause has user_action, it should override the lookup dict hint."""# Use an error_type that exists in AGENT_ERROR_HINTS@@ -371,7 +424,7 @@ class TestAgentOutput:assert parsed["hint"] == "custom override"def test_agent_error_includes_model_and_provider_from_report(self, capsys: pytest.CaptureFixture[str]) -> None:- """agent_error should include model and provider from to_error_report()."""+ """agent_error should include model and provider from to_problem()."""cause = InferenceBackendCredentialsError(credentials_error_type=InferenceBackendCredentialsErrorType.VAR_NOT_FOUND,backend_name="openai",@@ -432,7 +485,7 @@ class TestAgentOutput:assert parsed["error_category"] == "configuration"def test_agent_error_uses_report_error_domain(self, capsys: pytest.CaptureFixture[str]) -> None:- """agent_error should include error_domain from to_error_report() for a PipelexError cause."""+ """agent_error should include error_domain from to_problem() for a PipelexError cause."""cause = PipelexConfigError("bad config")with pytest.raises(typer.Exit):agent_error("bad config", error_type="PipelexConfigError", cause=cause)diff --git a/tests/unit/pipelex/cli/test_error_handlers.py b/tests/unit/pipelex/cli/test_error_handlers.pyindex eaccdcb1d..077a0132d 100644--- a/tests/unit/pipelex/cli/test_error_handlers.py+++ b/tests/unit/pipelex/cli/test_error_handlers.py@@ -28,8 +28,8 @@ if TYPE_CHECKING:class TestErrorHandlers:"""Tests for Rich error handler functions."""- def test_handle_model_choice_error_exits_and_calls_to_error_report(self, mocker: MockerFixture) -> None:- """handle_model_choice_error should call to_error_report() and exit with code 1."""+ def test_handle_model_choice_error_exits_and_reads_the_advice(self, mocker: MockerFixture) -> None:+ """handle_model_choice_error should read the advice for its tip and exit with code 1."""mocker.patch("pipelex.cli.error_handlers.get_console")exc = PipeOperatorModelChoiceError(message="model 'gpt-5' not found",@@ -40,7 +40,7 @@ class TestErrorHandlers:model_type=ModelType.LLM,model_choice="gpt-5",)- spy = mocker.spy(exc, "to_error_report")+ spy = mocker.spy(exc, "advised_action")with pytest.raises(typer.Exit) as exc_info:handle_model_choice_error(exc, context=ErrorContext.PIPE_RUN)@@ -48,8 +48,8 @@ class TestErrorHandlers:assert exc_info.value.exit_code == 1spy.assert_called_once()- def test_handle_model_availability_error_exits_and_calls_to_error_report(self, mocker: MockerFixture) -> None:- """handle_model_availability_error should call to_error_report() and exit with code 1."""+ def test_handle_model_availability_error_exits_and_reads_the_advice(self, mocker: MockerFixture) -> None:+ """handle_model_availability_error should read the advice for its tip and exit with code 1."""mocker.patch("pipelex.cli.error_handlers.get_console")exc = PipeOperatorModelAvailabilityError(message="model not available",@@ -60,7 +60,7 @@ class TestErrorHandlers:model_handle="gpt-4o",fallback_list=["gpt-4o-mini"],)- spy = mocker.spy(exc, "to_error_report")+ spy = mocker.spy(exc, "advised_action")with pytest.raises(typer.Exit) as exc_info:handle_model_availability_error(exc, context=ErrorContext.PIPE_RUN)@@ -68,8 +68,8 @@ class TestErrorHandlers:assert exc_info.value.exit_code == 1spy.assert_called_once()- 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."""+ def test_handle_model_deck_preset_error_exits_and_reads_the_advice(self, mocker: MockerFixture) -> None:+ """handle_model_deck_preset_error should read the advice for its tip and exit with code 1."""mocker.patch("pipelex.cli.error_handlers.get_console")exc = ModelDeckPresetValidationError(message="preset references unavailable model",@@ -78,7 +78,7 @@ class TestErrorHandlers:model_handle="gpt-5",enabled_backends={"openai"},)- spy = mocker.spy(exc, "to_error_report")+ spy = mocker.spy(exc, "advised_action")with pytest.raises(typer.Exit) as exc_info:handle_model_deck_preset_error(exc, context=ErrorContext.VALIDATION)@@ -86,11 +86,11 @@ class TestErrorHandlers:assert exc_info.value.exit_code == 1spy.assert_called_once()- def test_handle_validate_bundle_error_exits_and_calls_to_error_report(self, mocker: MockerFixture) -> None:- """handle_validate_bundle_error should call to_error_report() and exit with code 1."""+ def test_handle_validate_bundle_error_exits_and_reads_its_items(self, mocker: MockerFixture) -> None:+ """handle_validate_bundle_error should read the verdict's items and exit with code 1."""mocker.patch("pipelex.cli.error_handlers.get_console")exc = ValidateBundleError(message="validation failed")- spy = mocker.spy(exc, "to_error_report")+ spy = mocker.spy(exc, "validation_error_items")with pytest.raises(typer.Exit) as exc_info:handle_validate_bundle_error(exc)diff --git a/tests/unit/pipelex/cli/test_error_handlers_more.py b/tests/unit/pipelex/cli/test_error_handlers_more.pyindex c41f7bb32..a36912f25 100644--- a/tests/unit/pipelex/cli/test_error_handlers_more.py+++ b/tests/unit/pipelex/cli/test_error_handlers_more.py@@ -12,6 +12,7 @@ from typing import TYPE_CHECKINGimport pytestimport typer+from mthds.protocol.problem.registry import CoreCodefrom rich.console import Consolefrom pipelex.base_exceptions import MigrationErrorBlock@@ -158,6 +159,7 @@ class TestErrorHandlersExtended:pipe_validation_errors=[pipe_error],dry_run_failures=[DryRunFailureErrorData(+ code=CoreCode.PIPE_OUTPUT_INVALID,pipe_code="third_pipe",domain_code="demo",source="bundle.mthds",diff --git a/tests/unit/pipelex/cli/test_validate_exit_codes.py b/tests/unit/pipelex/cli/test_validate_exit_codes.pyindex f8f42e970..794669fc5 100644--- a/tests/unit/pipelex/cli/test_validate_exit_codes.py+++ b/tests/unit/pipelex/cli/test_validate_exit_codes.py@@ -18,6 +18,7 @@ from typing import TYPE_CHECKING, Anyimport pytestimport typer+from mthds.protocol.problem.registry import CoreCodefrom pipelex.cli.agent_cli.commands.agent_output import CliOutputFormatfrom pipelex.cli.agent_cli.commands.validate.bundle_cmd import validate_bundle_cmd as agent_validate_bundle_cmd@@ -41,7 +42,11 @@ def _make_dry_run_verdict() -> ValidateBundleError:"""The verdict the cascade makes of a failing dry run: one located dry_run item for the failing pipe."""return ValidateBundleError("pipe dry-run failed",- dry_run_failures=[DryRunFailureErrorData(pipe_code="my_pipe", domain_code="test", message="Pipe 'my_pipe' failed its dry run: Pipe run")],+ dry_run_failures=[+ DryRunFailureErrorData(+ code=CoreCode.PIPE_OUTPUT_INVALID, pipe_code="my_pipe", domain_code="test", message="Pipe 'my_pipe' failed its dry run: Pipe run"+ )+ ],)@@ -155,7 +160,10 @@ class TestValidateExitCodes:mocker.patch(f"{AGENT_BUNDLE_MODULE}.validate_bundle_core",new=mocker.AsyncMock(- side_effect=ValidateBundleError("Bundle is invalid", dry_run_failures=[DryRunFailureErrorData(pipe_code="my_pipe", message="boom")])+ side_effect=ValidateBundleError(+ "Bundle is invalid",+ dry_run_failures=[DryRunFailureErrorData(code=CoreCode.PIPE_OUTPUT_INVALID, pipe_code="my_pipe", message="boom")],+ )),)with pytest.raises(typer.Exit) as exc_info:diff --git a/tests/unit/pipelex/cli/test_validate_suggested_fix_rendering.py b/tests/unit/pipelex/cli/test_validate_suggested_fix_rendering.pyindex 4246d63e9..b166a8b17 100644--- a/tests/unit/pipelex/cli/test_validate_suggested_fix_rendering.py+++ b/tests/unit/pipelex/cli/test_validate_suggested_fix_rendering.py@@ -14,6 +14,7 @@ from typing import TYPE_CHECKINGimport pytestimport typer+from mthds.protocol.problem.registry import CoreCodefrom rich.console import Consolefrom pipelex.cli.error_handlers import handle_validate_bundle_error@@ -227,7 +228,12 @@ class TestValidateSuggestedFixRendering:message="validation failed",pipe_validation_errors=[_non_fixable_pipe_error()],dry_run_failures=[- DryRunFailureErrorData(pipe_code="third_pipe", domain_code="demo", message="Pipe 'third_pipe' failed its dry run: exploded")+ DryRunFailureErrorData(+ code=CoreCode.PIPE_OUTPUT_INVALID,+ pipe_code="third_pipe",+ domain_code="demo",+ message="Pipe 'third_pipe' failed its dry run: exploded",+ )],)diff --git a/tests/unit/pipelex/cogt/doc_gen/test_formatted_markdown.py b/tests/unit/pipelex/cogt/doc_gen/test_formatted_markdown.pyindex 1f7a05996..c77c3097a 100644--- a/tests/unit/pipelex/cogt/doc_gen/test_formatted_markdown.py+++ b/tests/unit/pipelex/cogt/doc_gen/test_formatted_markdown.py@@ -2,12 +2,14 @@ import tracemallocimport pytestfrom jinja2.exceptions import TemplateError+from mthds.protocol.problem.registry import CoreCode, ProblemDomainfrom pydantic import BaseModelfrom pytest_mock import MockerFixturefrom pipelex.cogt.doc_gen import formatted_markdownfrom pipelex.cogt.doc_gen.exceptions import MarkdownFormattingBudgetErrorfrom pipelex.cogt.doc_gen.formatted_markdown import FormattedHeading, FormattedParagraph, TextSpan, format_markdown, spans_text+from pipelex.errors.problem import ProblemViewfrom pipelex.tools.jinja2.jinja2_render_budget import (DEFAULT_RENDER_BUDGET_UNITS,MARKDOWN_UNITS_PER_CHARACTER,@@ -106,9 +108,9 @@ class TestFormattedMarkdown:def test_the_budget_error_is_the_caller_s(self) -> None:with pytest.raises(MarkdownFormattingBudgetError) as caught:format_markdown(markdown=MarkdownFormattingTestData.PADDED_TABLE)- report = caught.value.to_error_report()- assert report.error_domain == "input"- assert report.caller_facing_message+ caller = caught.value.to_problem(view=ProblemView.CALLER)+ assert caller.code == CoreCode.INPUT_TOO_LARGE+ assert caller.domain == ProblemDomain.INPUTassert f"{DEFAULT_RENDER_BUDGET_UNITS:,} work units" in caught.value.messagedef test_inside_a_render_the_render_s_budget_is_charged_for_the_source_the_tables_and_the_result(self) -> None:diff --git a/tests/unit/pipelex/cogt/extract/test_extract_input_format_check.py b/tests/unit/pipelex/cogt/extract/test_extract_input_format_check.pyindex 586c23b78..9cfb5e936 100644--- a/tests/unit/pipelex/cogt/extract/test_extract_input_format_check.py+++ b/tests/unit/pipelex/cogt/extract/test_extract_input_format_check.py@@ -8,9 +8,9 @@ so its format is not checked."""import pytest+from mthds.protocol.problem.registry import ProblemDomainfrom typing_extensions import override-from pipelex.base_exceptions import ErrorDomainfrom pipelex.cogt.exceptions import ExtractCapabilityError, ExtractInputFormatErrorfrom pipelex.cogt.extract.extract_input import ExtractInputfrom pipelex.cogt.extract.extract_job import ExtractJob@@ -21,6 +21,7 @@ from pipelex.cogt.llm.thinking_mode import ThinkingModefrom pipelex.cogt.model_backends.model_spec import InferenceModelSpecfrom pipelex.cogt.model_backends.model_type import ModelTypefrom pipelex.cogt.usage.cost_category import CostCategory+from pipelex.errors.problem import ProblemViewfrom pipelex.system.job_metadata import JobMetadata, RunMetadataDOCX_MIME = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"@@ -82,7 +83,7 @@ class TestExtractInputFormatCheck:"Input 'transcripts[0]' is a Word document (.docx), which model 'azure-document-intelligence' cannot extract: ""it reads PDF and images. Give a file in one of those formats, or use an extract model that reads this one.")- assert exc_info.value.to_error_report().error_domain == ErrorDomain.INPUT+ assert exc_info.value.to_problem(view=ProblemView.CALLER).domain == ProblemDomain.INPUTassert worker.nb_provider_calls == 0async def test_a_file_with_no_input_name_is_named_as_the_file_to_extract(self):diff --git a/tests/unit/pipelex/cogt/inference/test_error_classification_unknown.py b/tests/unit/pipelex/cogt/inference/test_error_classification_unknown.pyindex a527d4d37..a9ef178d0 100644--- a/tests/unit/pipelex/cogt/inference/test_error_classification_unknown.py+++ b/tests/unit/pipelex/cogt/inference/test_error_classification_unknown.py@@ -7,7 +7,10 @@ to retry) and surfaces a real "we should add this case" signal in telemetry.from __future__ import annotations-from pipelex.cogt.exceptions import CogtError, InferenceErrorCategory+from mthds.protocol.problem.registry import CoreCode++from pipelex.cogt.exceptions import CogtError, InferenceErrorCategory, find_inference_error_category_in_chain+from pipelex.errors.problem import ProblemViewclass TestInferenceErrorCategoryUnknown:@@ -20,10 +23,11 @@ class TestInferenceErrorCategoryUnknown:def test_unknown_is_not_retryable(self) -> None:assert InferenceErrorCategory.UNKNOWN.is_retryable is False- def test_error_report_round_trips_unknown(self) -> None:+ def test_unknown_rides_the_chain_and_its_problem_invites_no_retry(self) -> None:err = CogtError("boom", error_category=InferenceErrorCategory.UNKNOWN)- report = err.to_error_report()+ problem = err.to_problem(view=ProblemView.CALLER)- assert report.error_category == "unknown"- assert report.retryable is False+ assert find_inference_error_category_in_chain(err) == InferenceErrorCategory.UNKNOWN+ assert problem.code == CoreCode.RUNTIME_UNEXPECTED+ assert problem.is_retryable is Falsediff --git a/tests/unit/pipelex/cogt/inference/test_model_not_allowed.py b/tests/unit/pipelex/cogt/inference/test_model_not_allowed.pyindex c689af53f..bbc37bfc7 100644--- a/tests/unit/pipelex/cogt/inference/test_model_not_allowed.py+++ b/tests/unit/pipelex/cogt/inference/test_model_not_allowed.py@@ -33,12 +33,17 @@ from typing import TYPE_CHECKING, Anyimport anthropicimport httpximport pytest-from mthds.protocol.problem.registry import CoreCode+from mthds.protocol.problem.registry import CoreCode, ProblemDomain, StepKindfrom openai import OpenAIfrom portkey_ai import Portkey-from pipelex.base_exceptions import ErrorDomain-from pipelex.cogt.exceptions import CogtError, InferenceErrorCategory, LLMCompletionError, LLMModelNotFoundError+from pipelex.cogt.exceptions import (+ CogtError,+ InferenceErrorCategory,+ LLMCompletionError,+ LLMModelNotFoundError,+ find_inference_error_category_in_chain,+)from pipelex.cogt.inference.error_classification import (MODEL_NOT_ALLOWED_ERROR_CODE,ProviderErrorMetadata,@@ -50,6 +55,8 @@ from pipelex.cogt.inference.error_classification import (from pipelex.cogt.inference.error_classify import InferenceErrorFamily, classify_inference_errorfrom pipelex.cogt.inference.error_render import render_inference_errorfrom pipelex.cogt.inference.provider_name import ProviderName+from pipelex.errors.error_codes import error_code_spec+from pipelex.errors.problem import ProblemViewfrom pipelex.pipe_run.exceptions import PipeRouterErrorfrom pipelex.system.pipe_run_mode import PipeRunMode@@ -295,21 +302,23 @@ class TestWhatItAnswersOverHTTP: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()+ problem = _rendered_error(_envelope(MODEL_NOT_ALLOWED_ERROR_CODE)).to_problem(view=ProblemView.CALLER)+ unrecognized_problem = _rendered_error(_envelope("something-else")).to_problem(view=ProblemView.CALLER)- assert report.error_domain == ErrorDomain.CONFIG- assert unrecognized_report.error_domain == ErrorDomain.RUNTIME- assert unrecognized_report.http_status == 500+ assert problem.code == CoreCode.MODEL_UNAVAILABLE+ assert problem.domain == ProblemDomain.OPERATOR+ assert error_code_spec(CoreCode.MODEL_UNAVAILABLE).status == 501+ assert unrecognized_problem.code == CoreCode.RUNTIME_UNEXPECTED+ assert unrecognized_problem.domain == ProblemDomain.RUNTIME+ assert error_code_spec(CoreCode.RUNTIME_UNEXPECTED).status == 500class TestTheAdviceSurvivesThePipeBoundary:def test_the_advice_reaches_the_caller_through_the_located_failure(self) -> None:"""The failure class is not re-raised by the pipe operator, so the router's location is the boundary.- ``PipeRouterError`` reports the root fault located at the failing pipe, with- the classification its cause chain carries. When nothing on the chain carried- a user action, that report would fall back to "the message gives the cause".+ ``PipeRouterError`` reports the root fault located at the failing pipe, with the classification its cause+ chain carries, and the advice a local reader is printed is the nearest one on that chain."""rendered = _rendered_error(_envelope(MODEL_NOT_ALLOWED_ERROR_CODE))located = PipeRouterError.make_located(@@ -321,12 +330,19 @@ class TestTheAdviceSurvivesThePipeBoundary:)located.__cause__ = rendered- report = located.to_error_report()-- assert report.error_type == "LLMCompletionError"- assert report.error_domain == ErrorDomain.CONFIG- assert report.error_category == InferenceErrorCategory.CONFIGURATION- assert report.retryable is False- assert report.user_action is not None- assert report.user_action.kind == UserActionKind.CHANGE_MODEL- assert report.user_action_detail() == _rendered_detail(_envelope(MODEL_NOT_ALLOWED_ERROR_CODE))+ problem = located.to_problem(view=ProblemView.OPERATOR)++ assert problem.code == CoreCode.MODEL_UNAVAILABLE+ assert problem.domain == ProblemDomain.OPERATOR+ assert problem.is_retryable is False+ assert problem.location is not None+ assert problem.location.pipe == "score_lead"+ assert problem.diagnostics is not None+ assert problem.diagnostics.error_class == "LLMCompletionError"+ assert find_inference_error_category_in_chain(located) == InferenceErrorCategory.CONFIGURATION+ # The caller reads its own step: choose another model, the operator's being to serve or allow this one.+ assert located.to_problem(view=ProblemView.CALLER).next_step.kind == StepKind.CHANGE_MODEL+ advice = located.advised_action()+ assert advice is not None+ assert advice.kind == UserActionKind.CHANGE_MODEL+ assert advice.detail == _rendered_detail(_envelope(MODEL_NOT_ALLOWED_ERROR_CODE))diff --git a/tests/unit/pipelex/cogt/inference/test_render_inference_error.py b/tests/unit/pipelex/cogt/inference/test_render_inference_error.pyindex cc3b11a5c..a51cf2496 100644--- a/tests/unit/pipelex/cogt/inference/test_render_inference_error.py+++ b/tests/unit/pipelex/cogt/inference/test_render_inference_error.py@@ -9,7 +9,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, ClassVarimport pytest-from mthds.protocol.problem.registry import CoreCode+from mthds.protocol.problem.registry import CoreCode, StepKindfrom pipelex.cogt.exceptions import (INFERENCE_FAILURE_CODES,@@ -30,6 +30,7 @@ from pipelex.cogt.inference.error_classification import ProviderErrorMetadata, Ufrom pipelex.cogt.inference.error_classify import ClassificationResult, InferenceErrorFamilyfrom pipelex.cogt.inference.error_render import render_inference_errorfrom pipelex.cogt.inference.provider_name import ProviderName+from pipelex.errors.problem import ProblemViewfrom pipelex.pipe_run.exceptions import PipeRouterErrorfrom pipelex.pipeline.exceptions import PipelineExecutionErrorfrom pipelex.system.pipe_run_mode import PipeRunMode@@ -159,11 +160,11 @@ class TestRenderInferenceError:pytest.param(0.0, "Transient provider error — wait a moment, then run it again.", id="retry_after_zero"),],)- def test_failed_run_report_says_to_wait_then_run_again(self, retry_after_seconds: float | None, expected_detail: str) -> None:- """The advice a failed run's report carries for a transient inference error.+ def test_failed_run_advice_says_to_wait_then_run_again(self, retry_after_seconds: float | None, expected_detail: str) -> None:+ """The advice a failed run carries for a transient inference error.- The report is read once the run has failed and every automatic retry is spent, so the- advice says what the reader can do, and never that the system will retry.+ The advice is read once the run has failed and every automatic retry is spent, so it+ says what the reader can do, and never that the system will retry."""metadata = ProviderErrorMetadata(provider=ProviderName.OPENAI,@@ -201,10 +202,17 @@ class TestRenderInferenceError:)failed_run.__cause__ = located- report_payload = failed_run.to_error_report().to_dict()-- assert report_payload["user_action"] == {"kind": "wait_and_retry", "detail": expected_detail}- assert "automatically" not in report_payload["user_action"]["detail"]+ advice = failed_run.advised_action()+ assert advice is not None+ assert advice.kind == UserActionKind.WAIT_AND_RETRY+ assert advice.detail == expected_detail+ assert "automatically" not in advice.detail+ caller = failed_run.to_problem(view=ProblemView.CALLER)+ # The caller's problem invites the wait the provider asked for, as a member, never as advice.+ assert caller.code == CoreCode.PROVIDER_RATE_LIMITED+ assert caller.is_retryable is True+ assert caller.next_step.kind == StepKind.WAIT+ assert caller.retry_after == retry_after_seconds@pytest.mark.parametrize("error_code", INFERENCE_FAILURE_CODES, ids=str)@pytest.mark.parametrize(diff --git a/tests/unit/pipelex/cogt/llm/test_llm_worker_document_format.py b/tests/unit/pipelex/cogt/llm/test_llm_worker_document_format.pyindex 900d28108..0ee1a8f99 100644--- a/tests/unit/pipelex/cogt/llm/test_llm_worker_document_format.py+++ b/tests/unit/pipelex/cogt/llm/test_llm_worker_document_format.py@@ -12,9 +12,9 @@ import ioimport zipfileimport pytest+from mthds.protocol.problem.registry import ProblemDomainfrom typing_extensions import override-from pipelex.base_exceptions import ErrorDomainfrom pipelex.cogt.document.prompt_document import PromptDocument, PromptDocumentBase64, PromptDocumentBinary, PromptDocumentUrifrom pipelex.cogt.document.prompt_document_factory import PromptDocumentFactoryfrom pipelex.cogt.exceptions import LLMCapabilityError, PromptDocumentFormatError@@ -26,6 +26,7 @@ from pipelex.cogt.llm.thinking_mode import ThinkingModefrom pipelex.cogt.model_backends.model_spec import InferenceModelSpecfrom pipelex.cogt.model_backends.model_type import ModelTypefrom pipelex.cogt.usage.cost_category import CostCategory+from pipelex.errors.problem import ProblemViewfrom pipelex.system.job_metadata import JobMetadata, RunMetadatafrom pipelex.tools.typing.pydantic_utils import BaseModelTypeVar@@ -117,7 +118,7 @@ class TestLLMWorkerDocumentFormat:assert str(exc_info.value) == ("Prompt document 2 given to model 'gpt-docs-test' is a Word document (.docx), which it does not read: it reads PDF.")- assert exc_info.value.to_error_report().error_domain == ErrorDomain.INPUT+ assert exc_info.value.to_problem(view=ProblemView.CALLER).domain == ProblemDomain.INPUTassert worker.nb_provider_calls == 0async def test_a_model_reading_no_documents_is_still_a_capability_error(self):diff --git a/tests/unit/pipelex/cogt/llm/test_llm_worker_prompt_image_format.py b/tests/unit/pipelex/cogt/llm/test_llm_worker_prompt_image_format.pyindex da0a819c2..19978c137 100644--- a/tests/unit/pipelex/cogt/llm/test_llm_worker_prompt_image_format.py+++ b/tests/unit/pipelex/cogt/llm/test_llm_worker_prompt_image_format.py@@ -10,9 +10,9 @@ import base64from pathlib import Pathimport pytest+from mthds.protocol.problem.registry import ProblemDomainfrom typing_extensions import override-from pipelex.base_exceptions import ErrorDomainfrom pipelex.cogt.exceptions import PromptImageFormatErrorfrom pipelex.cogt.image.prompt_image import PromptImage, PromptImageBase64, PromptImageBinary, PromptImageUrifrom pipelex.cogt.llm.llm_job import LLMJob@@ -23,6 +23,7 @@ from pipelex.cogt.llm.thinking_mode import ThinkingModefrom pipelex.cogt.model_backends.model_spec import InferenceModelSpecfrom pipelex.cogt.model_backends.model_type import ModelTypefrom pipelex.cogt.usage.cost_category import CostCategory+from pipelex.errors.problem import ProblemViewfrom pipelex.system.job_metadata import JobMetadata, RunMetadatafrom pipelex.tools.typing.pydantic_utils import BaseModelTypeVar@@ -97,7 +98,7 @@ class TestLLMWorkerPromptImageFormat:await worker.gen_text(llm_job=_make_llm_job(user_images=[png_image, pdf_image]))assert str(exc_info.value) == ("Prompt image 2 given to model 'gpt-vision-test' is a PDF document (.pdf), not an image.")- assert exc_info.value.to_error_report().error_domain == ErrorDomain.INPUT+ assert exc_info.value.to_problem(view=ProblemView.CALLER).domain == ProblemDomain.INPUTassert worker.nb_provider_calls == 0@pytest.mark.parametrize(diff --git a/tests/unit/pipelex/cogt/llm/test_llm_worker_request_check.py b/tests/unit/pipelex/cogt/llm/test_llm_worker_request_check.pyindex 47faba9e2..a3559fae4 100644--- a/tests/unit/pipelex/cogt/llm/test_llm_worker_request_check.py+++ b/tests/unit/pipelex/cogt/llm/test_llm_worker_request_check.py@@ -15,6 +15,7 @@ from pipelex.cogt.llm.thinking_mode import ThinkingModefrom pipelex.cogt.model_backends.model_spec import InferenceModelSpecfrom pipelex.cogt.model_backends.model_type import ModelTypefrom pipelex.cogt.usage.cost_category import CostCategory+from pipelex.errors.problem import ProblemViewfrom pipelex.system.job_metadata import JobMetadata, RunMetadataif TYPE_CHECKING:@@ -106,7 +107,9 @@ class TestLLMWorkerRequestCheck:with pytest.raises(LLMCapabilityError) as exc_info:await invocationassert worker.calls == []- assert exc_info.value.to_error_report().model == "gpt-test"+ diagnostics = exc_info.value.to_problem(view=ProblemView.OPERATOR).diagnostics+ assert diagnostics is not None+ assert diagnostics.model == "gpt-test"@pytest.mark.asyncioasync def test_an_accepted_request_reaches_the_provider(self) -> None: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.pyindex 2fa9388e3..9fef03cac 100644--- a/tests/unit/pipelex/cogt/models/test_model_deck_choice_unresolved.py+++ b/tests/unit/pipelex/cogt/models/test_model_deck_choice_unresolved.py@@ -1,18 +1,20 @@"""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.+The deck's lookups refuse a reference they do not resolve as ``ModelChoiceNotFoundError``, ``model.unknown`` in the+method's domain, 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 method, 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, both in the operator's domain,+and names the deck's setting to its operator alone."""from __future__ import annotations+import loggingfrom typing import TYPE_CHECKING, Anyimport pytest-from mthds.protocol.problem.registry import CoreCode+from mthds.protocol.problem.registry import CoreCode, ProblemDomainfrom pipelex.cogt.config_cogt import ModelDeckConfigfrom pipelex.cogt.doc_gen.doc_gen_engine import resolve_doc_gen_setting@@ -26,6 +28,7 @@ from pipelex.cogt.model_backends.model_spec_index import ModelSpecIndexfrom pipelex.cogt.model_backends.model_type import ModelTypefrom pipelex.cogt.models.model_deck import ModelDeckfrom pipelex.cogt.usage.cost_category import CostCategory+from pipelex.errors.problem import ProblemViewfrom pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.kernel.extract_ops import resolve_extract_settingfrom pipelex.kernel.img_gen_ops import resolve_img_gen_setting@@ -155,9 +158,28 @@ class TestModelDeckChoiceUnresolved:assert expected_deck_setting in unresolved.messageassert unresolved.resolve_error_code() == expected_codeassert isinstance(unresolved.__cause__, ModelChoiceNotFoundError)- report = unresolved.to_error_report()- assert report.caller_facing_message is False- assert report.error_domain != "input"+ caller = unresolved.to_problem(view=ProblemView.CALLER)+ assert caller.domain == ProblemDomain.OPERATOR+ # The deck's setting is the deployment's configuration: its operator reads it, its caller does not.+ assert expected_deck_setting not in str(caller.to_wire())+ operator = unresolved.to_problem(view=ProblemView.OPERATOR)+ assert operator.diagnostics is not None+ assert expected_deck_setting in operator.diagnostics.message++ def test_a_stale_handle_s_sentence_renders_with_its_reason(self, mocker: MockerFixture, caplog: pytest.LogCaptureFixture) -> None:+ """`model.unavailable` declares why the model is not served, and a stale handle of the deck is served by no backend."""+ _use_deck(mocker, model_deck=_make_deck())++ with pytest.raises(ModelDeckChoiceUnresolvedError) as exc_info:+ resolve_llm_setting_for_text()+ with caplog.at_level(logging.WARNING, logger="pipelex.errors.problem"):+ caller = exc_info.value.to_problem(view=ProblemView.CALLER)++ assert caller.code == CoreCode.MODEL_UNAVAILABLE+ assert caller.params is not None+ assert caller.params.as_wire() == {"model": "stale-text-model", "model_type": "llm", "reason": "not_served"}+ assert caller.detail == "The llm model 'stale-text-model' exists, but this deployment does not serve it (reason: not_served)."+ assert not any(record.getMessage() == "A problem's sentence could not be rendered from its template" for record in caplog.records)@pytest.mark.parametrize(("_topic", "resolve", "expected_choice"),@@ -176,7 +198,7 @@ class TestModelDeckChoiceUnresolved: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."""+ """The method named the model, so the miss is the method's own: `model.unknown`, in the method's domain."""_use_deck(mocker, model_deck=_make_deck())with pytest.raises(ModelChoiceNotFoundError) as exc_info:@@ -186,9 +208,9 @@ class TestModelDeckChoiceUnresolved:assert not isinstance(not_found, ModelDeckChoiceUnresolvedError)assert not_found.model_choice == expected_choiceassert 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"+ caller = not_found.to_problem(view=ProblemView.CALLER)+ assert caller.code == CoreCode.MODEL_UNKNOWN+ assert caller.domain == ProblemDomain.METHOD@pytest.mark.parametrize(("_topic", "llm_choice_overrides", "expected_deck_setting", "expected_code"),@@ -221,7 +243,9 @@ class TestModelDeckChoiceUnresolved:unresolved = exc_info.valueassert unresolved.deck_setting == expected_deck_settingassert unresolved.resolve_error_code() == expected_code- assert unresolved.to_error_report().caller_facing_message is False+ caller = unresolved.to_problem(view=ProblemView.CALLER)+ assert caller.domain == ProblemDomain.OPERATOR+ assert expected_deck_setting not in str(caller.to_wire())@pytest.mark.parametrize(("_topic", "resolve"),@@ -242,4 +266,4 @@ class TestModelDeckChoiceUnresolved:not_found = exc_info.valueassert "served by the model deck, but not as an LLM" in not_found.messageassert not_found.resolve_error_code() == CoreCode.MODEL_CAPABILITY_UNSUPPORTED- assert not_found.to_error_report().caller_facing_message is True+ assert not_found.to_problem(view=ProblemView.CALLER).domain == ProblemDomain.METHODdiff --git a/tests/unit/pipelex/cogt/models/test_model_deck_lookups_per_pair.py b/tests/unit/pipelex/cogt/models/test_model_deck_lookups_per_pair.pyindex 3b0a71b3b..4c3ebd2b5 100644--- a/tests/unit/pipelex/cogt/models/test_model_deck_lookups_per_pair.py+++ b/tests/unit/pipelex/cogt/models/test_model_deck_lookups_per_pair.py@@ -1,13 +1,14 @@"""One handle, one model per model type: every lookup of the deck goes by the pair, so each pipe family reaches its own spec."""import pytest+from mthds.protocol.problem.registry import CoreCode, StepKindfrom pipelex.cogt.exceptions import ModelNotFoundError-from pipelex.cogt.inference.error_classification import UserActionKindfrom pipelex.cogt.llm.llm_setting import LLMSettingfrom pipelex.cogt.model_backends.model_type import ModelTypefrom pipelex.cogt.model_routing.routing_profile import RoutingProfilefrom pipelex.cogt.models.model_manager import ModelManager+from pipelex.errors.problem import ProblemViewfrom tests.unit.pipelex.cogt.models.model_deck_per_pair_utils import TWIN_HANDLE, build_deck_manager, make_backend@@ -45,15 +46,16 @@ class TestLookupsPerPair:"""The load-time check does not look into an inline setting, so the run-time lookup is what reports it.`verdict` is served as a judgment model only, and nothing of the deck's LLM half names it.- The report names the type the pipe asked for, never the type the deck serves the handle as.+ The caller's problem names the type the pipe asked for, never the type the deck serves the handle as."""inline_setting = LLMSetting(model="verdict", temperature=0.5)with pytest.raises(ModelNotFoundError) as exc_info:self._twin_manager().get_inference_model(inline_setting.model, model_type=ModelType.LLM)- report = exc_info.value.to_error_report()- assert report.user_action is not None- assert report.user_action.kind is UserActionKind.CHANGE_MODEL- assert "an LLM" in report.user_action.detail- assert "judgment" not in report.user_action.detail+ caller = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert caller.code == CoreCode.MODEL_UNKNOWN+ assert caller.next_step.kind == StepKind.CHANGE_MODEL+ assert caller.params is not None+ assert caller.params.as_wire() == {"model": "verdict", "model_type": ModelType.LLM}+ assert "judgment" not in str(caller.to_wire())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 fac351d44..b041f50be 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,12 +1,10 @@import pytest-from mthds.protocol.problem.registry import CoreCode+from mthds.protocol.problem.registry import CoreCode, ProblemDomain, StepKind-from pipelex.base_exceptions import INTERNAL_ERROR_PLACEHOLDER, DisclosureMode, ErrorReportfrom pipelex.cogt.config_cogt import ModelDeckConfig-from pipelex.cogt.exceptions import ModelNotFoundError+from pipelex.cogt.exceptions import InferenceErrorCategory, ModelNotFoundError, find_inference_error_category_in_chainfrom pipelex.cogt.extract.extract_setting import ExtractSettingfrom pipelex.cogt.img_gen.img_gen_job_components import Quality-from pipelex.cogt.inference.error_classification import UserAction, UserActionKindfrom pipelex.cogt.llm.llm_setting import LLMSetting, LLMSettingChoices, LLMSettingChoicesDefaultsfrom pipelex.cogt.llm.thinking_mode import ThinkingModefrom pipelex.cogt.model_backends.model_spec import InferenceModelSpec@@ -14,6 +12,8 @@ from pipelex.cogt.model_backends.model_spec_index import ModelSpecIndexfrom pipelex.cogt.model_backends.model_type import ModelTypefrom pipelex.cogt.models.model_deck import ModelDeckfrom pipelex.cogt.usage.cost_category import CostCategory+from pipelex.errors.error_codes import error_code_spec+from pipelex.errors.problem import PipelexProblem, ProblemViewfrom pipelex.system.runtime import ProblemReaction@@ -73,18 +73,18 @@ def _raise_not_found(*, model_handle: str, model_type: ModelType) -> ModelNotFouclass TestModelDeckUnknownReference:@pytest.mark.parametrize(- ("_topic", "model_handle", "model_type", "needed_model"),+ ("_topic", "model_handle", "model_type"),[- ("handle", "method-only-model", ModelType.LLM, "an LLM"),- ("alias", "@method-only-alias", ModelType.LLM, "an LLM"),- ("waterfall", "~method-only-waterfall", ModelType.LLM, "an LLM"),- ("preset_used_as_a_model", "$deck-preset", ModelType.LLM, "an LLM"),- ("extract_handle", "method-only-extractor", ModelType.TEXT_EXTRACTOR, "a text-extraction model"),- ("search_handle", "method-only-search", ModelType.SEARCH, "a search model"),+ ("handle", "method-only-model", ModelType.LLM),+ ("alias", "@method-only-alias", ModelType.LLM),+ ("waterfall", "~method-only-waterfall", ModelType.LLM),+ ("preset_used_as_a_model", "$deck-preset", ModelType.LLM),+ ("extract_handle", "method-only-extractor", ModelType.TEXT_EXTRACTOR),+ ("search_handle", "method-only-search", ModelType.SEARCH),# An LLM preset names it, but no image-generation entry does.- ("img_gen_handle", "deck-preset-model", ModelType.IMG_GEN, "an image-generation model"),+ ("img_gen_handle", "deck-preset-model", ModelType.IMG_GEN),# The deck serves it, but as an LLM, which an image-generation lookup refuses.- ("served_handle_of_another_type", "served-model", ModelType.IMG_GEN, "an image-generation model"),+ ("served_handle_of_another_type", "served-model", ModelType.IMG_GEN),],)def test_a_reference_only_the_method_names_is_the_callers_fault(@@ -92,26 +92,27 @@ class TestModelDeckUnknownReference:_topic: str,model_handle: str,model_type: ModelType,- needed_model: str,) -> None:- """A reference the deck neither defines nor names came from the method: input domain, and caller-facing."""- report = _raise_not_found(model_handle=model_handle, model_type=model_type).to_error_report()+ """A reference the deck neither defines nor names came from the method: `model.unknown`, in the method's domain."""+ error = _raise_not_found(model_handle=model_handle, model_type=model_type)+ caller = error.to_problem(view=ProblemView.CALLER)- 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_UNKNOWN- assert report.error_domain == "input"- assert report.caller_facing_message is True- assert report.http_status == 422+ assert caller.code == CoreCode.MODEL_UNKNOWN+ assert caller.domain == ProblemDomain.METHOD+ assert error_code_spec(CoreCode.MODEL_UNKNOWN).status == 422# The category still says the setup is wrong for the call; the domain says whose it is.- assert report.error_category == "configuration"- # The next step names the reference as the method wrote it and the type its lookup asked for,- # and nothing of the deck: not even the type the deck serves a model of another type as.- expected_detail = f"Change the model '{model_handle}' to {needed_model} the model deck serves."- assert report.user_action == UserAction(kind=UserActionKind.CHANGE_MODEL, detail=expected_detail)- strict_payload = report.to_dict(disclosure_mode=DisclosureMode.STRICT)- assert strict_payload["message"] == report.message- assert strict_payload["user_action"] == {"kind": "change_model", "detail": expected_detail}+ assert find_inference_error_category_in_chain(error) == InferenceErrorCategory.CONFIGURATION+ # The caller reads the reference as the method wrote it and the type its lookup asked for, and nothing of the+ # deck: not even the type the deck serves a model of another type as.+ assert caller.params is not None+ assert caller.params.as_wire() == {"model": model_handle, "model_type": model_type}+ assert caller.detail == f"The method names the {model_type} model '{model_handle}', which no catalog knows."+ assert caller.next_step.kind == StepKind.CHANGE_MODEL+ assert caller.diagnostics is None+ operator = error.to_problem(view=ProblemView.OPERATOR)+ assert operator.diagnostics is not None+ assert operator.diagnostics.error_class == "ModelNotFoundError"+ assert operator.diagnostics.message == f"Model handle '{model_handle}' was not found in the model deck."@pytest.mark.parametrize(("_topic", "model_handle", "model_type"),@@ -129,27 +130,31 @@ class TestModelDeckUnknownReference:],)def test_a_reference_the_deck_names_is_the_deployments_fault(self, _topic: str, model_handle: str, model_type: ModelType) -> None:- """A reference the deck itself defines or names but does not serve stays config-domain and redacted."""- report = _raise_not_found(model_handle=model_handle, model_type=model_type).to_error_report()+ """A reference the deck itself defines or names but does not serve is the operator's, its message the operator's alone."""+ error = _raise_not_found(model_handle=model_handle, model_type=model_type)+ caller = error.to_problem(view=ProblemView.CALLER)+ operator = error.to_problem(view=ProblemView.OPERATOR)- assert report.error_type == "ModelNotFoundError"- assert report.code == CoreCode.MODEL_UNAVAILABLE- assert report.error_domain == "config"- assert report.caller_facing_message is False- assert report.http_status == 500- # The caller cannot fix what the deck names, so no next step is theirs to read.- assert report.user_action is None- strict_payload = report.to_dict(disclosure_mode=DisclosureMode.STRICT)- assert strict_payload["message"] == INTERNAL_ERROR_PLACEHOLDER- assert "user_action" not in strict_payload+ assert caller.code == CoreCode.MODEL_UNAVAILABLE+ assert caller.domain == ProblemDomain.OPERATOR+ assert error_code_spec(CoreCode.MODEL_UNAVAILABLE).status == 501+ # The caller can only choose another model; serving this one is the operator's to configure.+ assert caller.next_step.kind == StepKind.CHANGE_MODEL+ assert operator.next_step.kind == StepKind.FIX_CONFIGURATION+ assert caller.diagnostics is None+ assert "was not found in the model deck" not in str(caller.to_wire())+ assert operator.diagnostics is not None+ assert operator.diagnostics.error_class == "ModelNotFoundError"+ assert operator.diagnostics.message == f"Model handle '{model_handle}' was not found in the model deck."+ assert error.advised_action() is Nonedef test_the_classification_rides_the_worker_to_runner_hop(self) -> None:- """On a hosted run the lookup fails on a worker: the report is packed VERBOSE there and projected STRICT on the runner."""- packed = _raise_not_found(model_handle="method-only-model", model_type=ModelType.LLM).to_error_report().to_dict()- recovered = ErrorReport.from_dict(packed)+ """On a hosted run the lookup fails on a worker: the problem is built there and read back on the runner."""+ packed = _raise_not_found(model_handle="method-only-model", model_type=ModelType.LLM).to_problem(view=ProblemView.CALLER).to_wire()+ recovered = PipelexProblem.model_validate(packed)- assert recovered.caller_facing_message is True- payload = recovered.to_problem_document(disclosure_mode=DisclosureMode.STRICT)- assert payload["status"] == 422- assert payload["detail"] == "Model handle 'method-only-model' was not found in the model deck."- assert payload["user_action"] == {"kind": "change_model", "detail": "Change the model 'method-only-model' to an LLM the model deck serves."}+ assert recovered.code == CoreCode.MODEL_UNKNOWN+ assert error_code_spec(CoreCode.MODEL_UNKNOWN).status == 422+ assert recovered.detail == "The method names the llm model 'method-only-model', which no catalog knows."+ assert recovered.next_step.kind == StepKind.CHANGE_MODEL+ assert recovered.to_wire() == packeddiff --git a/tests/unit/pipelex/cogt/models/test_model_manager_credentials_guard.py b/tests/unit/pipelex/cogt/models/test_model_manager_credentials_guard.pyindex 62f0b8de3..b89f2c528 100644--- a/tests/unit/pipelex/cogt/models/test_model_manager_credentials_guard.py+++ b/tests/unit/pipelex/cogt/models/test_model_manager_credentials_guard.py@@ -7,11 +7,19 @@ a configuration error naming the variables, rather than letting an unset key rea"""import pytest--from pipelex.cogt.exceptions import InferenceBackendCredentialsError, InferenceBackendCredentialsErrorType, InferenceErrorCategory, ModelManagerError+from mthds.protocol.problem.registry import CoreCode, ProblemDomain++from pipelex.cogt.exceptions import (+ InferenceBackendCredentialsError,+ InferenceBackendCredentialsErrorType,+ InferenceErrorCategory,+ ModelManagerError,+ find_inference_error_category_in_chain,+)from pipelex.cogt.inference.error_classification import UserActionKindfrom pipelex.cogt.model_backends.backend import InferenceBackendfrom pipelex.cogt.models.model_manager import ModelManager+from pipelex.errors.problem import ProblemViewdef _manager_with(*backends: InferenceBackend) -> ModelManager:@@ -39,19 +47,24 @@ class TestModelManagerCredentialsGuard:assert "needs_inference=False" in error.messageassert "endpoint (AZURE_API_BASE), api_key (AZURE_API_KEY)" in error.message- def test_its_report_is_a_configuration_error_whose_next_step_is_a_boot_with_inference(self) -> None:+ def test_it_is_a_configuration_error_whose_advice_is_a_boot_with_inference(self) -> None:"""Setting the variable alone would not help a process that booted without inference."""manager = _manager_with(InferenceBackend(name="anthropic", unresolved_credentials={"api_key": ["ANTHROPIC_API_KEY"]}))with pytest.raises(InferenceBackendCredentialsError) as exc_info:manager.get_required_inference_backend("anthropic")- report = exc_info.value.to_error_report()- assert report.error_type == "InferenceBackendCredentialsError"- assert report.error_category is InferenceErrorCategory.CONFIGURATION- assert report.user_action is not None- assert report.user_action.kind is UserActionKind.CHECK_CREDENTIALS- assert "needs_inference=True" in report.user_action.detail+ error = exc_info.value+ operator = error.to_problem(view=ProblemView.OPERATOR)+ assert operator.code == CoreCode.RUNTIME_MISCONFIGURED+ assert operator.domain == ProblemDomain.OPERATOR+ assert operator.diagnostics is not None+ assert operator.diagnostics.error_class == "InferenceBackendCredentialsError"+ assert find_inference_error_category_in_chain(error) == InferenceErrorCategory.CONFIGURATION+ advice = error.advised_action()+ assert advice is not None+ assert advice.kind is UserActionKind.CHECK_CREDENTIALS+ assert "needs_inference=True" in advice.detaildef test_the_class_keeps_its_own_next_step_elsewhere(self) -> None:"""The guard's advice is its instance's own: the boot's missing-key error still says to set the variable."""diff --git a/tests/unit/pipelex/cogt/test_cogt_provider_facts_merge.py b/tests/unit/pipelex/cogt/test_cogt_provider_facts_merge.pynew file mode 100644index 000000000..6350e981f--- /dev/null+++ b/tests/unit/pipelex/cogt/test_cogt_provider_facts_merge.py@@ -0,0 +1,63 @@+"""A wrapper ``CogtError``'s provider facts are merged over its cause's member by member, the wrapper's winning.++The operator's ``diagnostics.provider`` is assembled along the cause chain by :meth:`PipelexError.chain_facts`+(``pipelex/base_exceptions.py``) from each error's :meth:`CogtError.problem_facts` (``pipelex/cogt/exceptions.py``).+A wrapper that attaches attribution-only metadata, naming the backend but no status, must not discard the status, the+request id and the delay its cause recorded from the provider's answer, which an operator acts on.+"""++from typing_extensions import override++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.errors.problem import ProblemView, ProviderDiagnostics+++class _WrapperCogtError(CogtError):+ """Stand-in wrapper that attaches attribution-only ``provider_metadata`` of its own, with no status and no delay."""++ @override+ def __init__(self, message: str) -> None:+ super().__init__(+ message=message,+ error_category=InferenceErrorCategory.UNKNOWN,+ provider_metadata=ProviderErrorMetadata(+ provider=ProviderName.OPENAI,+ sdk_exception_type="WrapperAttributionOnlyError",+ status_code=None,+ retry_after_seconds=None,+ ),+ )+++class TestCogtProviderFactsMerge:+ def test_a_wrapper_keeps_what_its_cause_recorded_of_the_provider_answer(self) -> None:+ leaf = LLMCompletionError(+ message="rate limited on the worker",+ error_category=InferenceErrorCategory.TRANSIENT,+ provider_metadata=ProviderErrorMetadata(+ provider=ProviderName.OPENAI,+ sdk_exception_type="RateLimitError",+ status_code=429,+ retry_after_seconds=12.0,+ request_id="req_leaf",+ ),+ )+ leaf.fill_model_and_provider("gpt-4o-mini", backend_name="openai")+ try:+ try:+ raise leaf+ except LLMCompletionError as cause:+ wrapper = _WrapperCogtError(message="wrapped while doing the thing")+ wrapper.fill_model_and_provider(None, backend_name="openai_proxy")+ raise wrapper from cause+ except _WrapperCogtError as caught_wrapper:+ problem = caught_wrapper.to_problem(view=ProblemView.OPERATOR)++ assert problem.diagnostics is not None+ assert problem.diagnostics.error_class == "_WrapperCogtError"+ # The wrapper's backend wins, and the cause's answer fills every member the wrapper left unset.+ assert problem.diagnostics.provider == ProviderDiagnostics(name="openai_proxy", status=429, request_id="req_leaf")+ assert problem.diagnostics.model == "gpt-4o-mini"+ assert problem.retry_after == 12.0diff --git a/tests/unit/pipelex/cogt/test_cogt_provider_metadata_wrapper_wins.py b/tests/unit/pipelex/cogt/test_cogt_provider_metadata_wrapper_wins.pydeleted file mode 100644index ec68a55eb..000000000--- a/tests/unit/pipelex/cogt/test_cogt_provider_metadata_wrapper_wins.py+++ /dev/null@@ -1,72 +0,0 @@-"""Pin: a wrapper ``CogtError``'s ``provider_metadata`` wins, even when the cause carries richer fields.--Both cause-enrichment sites that merge ``provider_metadata`` use a whole-object-``or`` — :meth:`CogtError.to_error_report` (``pipelex/cogt/exceptions.py``) and-:meth:`PipelexError._enrich_error_report_from_cause`-(``pipelex/base_exceptions.py``). A :class:`ProviderErrorMetadata` instance is-always truthy regardless of internal state, so a wrapper that attached-attribution-only metadata (``status_code=None``, ``retry_after_seconds=None``)-discards the cause's actionable ``status_code=429`` / ``retry_after_seconds``-— the very hints the STRICT-disclosure curated subset is designed to-preserve.--No in-tree wrapper triggers this today (grep confirms only leaf workers set-non-None ``provider_metadata``), but the trap is latent. This test pins the-current wrapper-wins semantics so a future contributor changing the merge-strategy makes a deliberate decision and updates this test.-"""--from typing_extensions import override--from pipelex.cogt.exceptions import CogtError, InferenceErrorCategory, LLMCompletionError-from pipelex.cogt.inference.error_classification import ProviderErrorMetadata-from pipelex.cogt.inference.provider_name import ProviderName---class _WrapperCogtError(CogtError):- """Stand-in wrapper that attaches attribution-only ``provider_metadata`` of its own.-- Inherits the OR-merge code path from ``CogtError``. ``error_category`` is- set so the wrapper-level retryable computation does not stomp on the- cause-derived value.- """-- @override- def __init__(self, message: str) -> None:- super().__init__(- message=message,- error_category=InferenceErrorCategory.UNKNOWN,- provider_metadata=ProviderErrorMetadata(- provider=ProviderName.OPENAI,- sdk_exception_type="WrapperAttributionOnlyError",- status_code=None,- retry_after_seconds=None,- ),- )---class TestCogtProviderMetadataWrapperWins:- def test_wrapper_provider_metadata_wins_even_when_cause_has_richer_metadata(self) -> None:- leaf = LLMCompletionError(- message="rate limited on the worker",- error_category=InferenceErrorCategory.CAPACITY,- provider_metadata=ProviderErrorMetadata(- provider=ProviderName.OPENAI,- sdk_exception_type="RateLimitError",- status_code=429,- retry_after_seconds=12.0,- ),- )- try:- try:- raise leaf- except LLMCompletionError as cause:- raise _WrapperCogtError(message="wrapped while doing the thing") from cause- except _WrapperCogtError as wrapper:- report = wrapper.to_error_report()- # Wrapper-wins: the merged provider_metadata is the wrapper's, not the cause's.- # The cause's actionable status_code=429 / retry_after_seconds=12.0 are dropped.- assert report.provider_metadata is not None- assert report.provider_metadata.sdk_exception_type == "WrapperAttributionOnlyError"- assert report.provider_metadata.status_code is None- assert report.provider_metadata.retry_after_seconds is Nonediff --git a/tests/unit/pipelex/cogt/test_data.py b/tests/unit/pipelex/cogt/test_data.pyindex 2cef05d2b..121fe01e8 100644--- a/tests/unit/pipelex/cogt/test_data.py+++ b/tests/unit/pipelex/cogt/test_data.py@@ -1,8 +1,7 @@from typing import ClassVar-from mthds.protocol.problem.registry import CoreCode+from mthds.protocol.problem.registry import CoreCode, ProblemDomain-from pipelex.base_exceptions import ErrorDomainfrom pipelex.cogt.exceptions import InferenceErrorCategoryfrom pipelex.errors.error_codes import ErrorCode@@ -17,15 +16,15 @@ class ExceptionTestData:("ambiguous_not_retryable", InferenceErrorCategory.AMBIGUOUS, False),]- # (topic, category, expected_code, expected_error_domain, expected_retryable)+ # (topic, category, expected_code, expected_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),+ CATEGORY_CODE_CASES: ClassVar[list[tuple[str, InferenceErrorCategory, ErrorCode, ProblemDomain, bool]]] = [+ ("transient_invites_a_retry", InferenceErrorCategory.TRANSIENT, CoreCode.PROVIDER_UNAVAILABLE, ProblemDomain.RUNTIME, True),+ ("configuration_is_the_operator_s", InferenceErrorCategory.CONFIGURATION, CoreCode.RUNTIME_MISCONFIGURED, ProblemDomain.OPERATOR, False),+ ("content_keeps_the_fallback", InferenceErrorCategory.CONTENT, CoreCode.RUNTIME_UNEXPECTED, ProblemDomain.RUNTIME, False),+ ("capacity_is_the_quota", InferenceErrorCategory.CAPACITY, CoreCode.PROVIDER_QUOTA_EXHAUSTED, ProblemDomain.OPERATOR, False),+ ("ambiguous_is_an_unknown_outcome", InferenceErrorCategory.AMBIGUOUS, CoreCode.PROVIDER_OUTCOME_UNKNOWN, ProblemDomain.RUNTIME, True),+ ("unknown_keeps_the_fallback", InferenceErrorCategory.UNKNOWN, CoreCode.RUNTIME_UNEXPECTED, ProblemDomain.RUNTIME, False),]diff --git a/tests/unit/pipelex/cogt/test_exceptions.py b/tests/unit/pipelex/cogt/test_exceptions.pyindex e96482345..0c586afd6 100644--- a/tests/unit/pipelex/cogt/test_exceptions.py+++ b/tests/unit/pipelex/cogt/test_exceptions.py@@ -2,9 +2,8 @@ import jsonimport pytestfrom mthds.protocol.problem.registry import CoreCode-from pydantic import ValidationError-from pipelex.base_exceptions import ErrorReport, PipelexError+from pipelex.base_exceptions import PipelexErrorfrom pipelex.cogt.exceptions import (CogtError,ExtractJobFailureError,@@ -21,14 +20,16 @@ from pipelex.cogt.exceptions import (ModelWaterfallError,SearchJobFailureError,SearchModelNotFoundError,+ find_inference_error_category_in_chain,)from pipelex.cogt.inference.error_classification import ProviderErrorMetadata, UserAction, UserActionKindfrom pipelex.cogt.inference.provider_name import ProviderName+from pipelex.errors.problem import PipelexProblem, ProblemViewfrom tests.unit.pipelex.cogt.test_data import ExceptionTestDataclass TestErrorCategoryInfrastructure:- """Tests for the InferenceErrorCategory enum, CogtError fields, and to_error_report()."""+ """Tests for the InferenceErrorCategory enum, CogtError fields, and to_problem()."""# --- InferenceErrorCategory enum ---@@ -131,104 +132,106 @@ class TestErrorCategoryInfrastructure:assert err.user_action.kind is UserActionKind.CHECK_CREDENTIALSassert err.user_action.detail == "Check that the required API key environment variable is set"- # --- to_error_report() ---+ # --- to_problem() ---- def test_to_error_report_pipelex_error_minimal(self) -> None:- """PipelexError.to_error_report returns an ErrorReport with error_type and message, and the fallback code's verdict."""+ def test_to_problem_pipelex_error_minimal(self) -> None:+ """A bare PipelexError reports the fallback code and its verdict, its class and message for the operator alone."""err = PipelexError("basic error")- report = err.to_error_report()- assert report.error_type == "PipelexError"- assert report.message == "basic error"- assert report.code == CoreCode.RUNTIME_UNEXPECTED- assert report.error_category is None- assert report.retryable is False-- def test_to_error_report_cogt_error_no_category(self) -> None:- """A failure with no category and no cause reports its class's fallback code, and None for the optional fields."""+ problem = err.to_problem(view=ProblemView.OPERATOR)+ assert problem.code == CoreCode.RUNTIME_UNEXPECTED+ assert problem.is_retryable is False+ assert problem.diagnostics is not None+ assert problem.diagnostics.error_class == "PipelexError"+ assert problem.diagnostics.message == "basic error"+ assert find_inference_error_category_in_chain(err) is None++ def test_to_problem_cogt_error_no_category(self) -> None:+ """A failure with no category and no cause reports its class's fallback code, and no advice, model or provider."""err = LLMCompletionError("plain error")- report = err.to_error_report()- assert report.error_type == "LLMCompletionError"- assert report.message == "plain error"- assert report.code == CoreCode.RUNTIME_UNEXPECTED- assert report.error_category is None- assert report.retryable is False- assert report.user_action is None- assert report.model is None- assert report.provider is None-- def test_to_error_report_with_category(self) -> None:- """A report includes the category, and a content failure with no code keeps its class's fallback."""+ problem = err.to_problem(view=ProblemView.OPERATOR)+ assert problem.code == CoreCode.RUNTIME_UNEXPECTED+ assert problem.is_retryable is False+ assert problem.diagnostics is not None+ assert problem.diagnostics.error_class == "LLMCompletionError"+ assert problem.diagnostics.message == "plain error"+ assert problem.diagnostics.model is None+ assert problem.diagnostics.provider is None+ assert find_inference_error_category_in_chain(err) is None+ assert err.advised_action() is None++ def test_to_problem_with_category(self) -> None:+ """The category stays on the chain, 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_UNEXPECTED- assert report.retryable is False+ problem = err.to_problem(view=ProblemView.CALLER)+ assert find_inference_error_category_in_chain(err) == InferenceErrorCategory.CONTENT+ assert problem.code == CoreCode.RUNTIME_UNEXPECTED+ assert problem.is_retryable is False- def test_to_error_report_with_all_cogt_fields(self) -> None:- """Report includes user_action when set, and a transient failure with no code reports a code that invites a retry."""+ def test_to_problem_with_all_cogt_fields(self) -> None:+ """The advice rides the error, never the problem, 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_UNAVAILABLE- assert report.retryable is True- assert report.user_action is not None- assert report.user_action.kind is UserActionKind.WAIT_AND_RETRY- assert report.user_action.detail == "Retry in a moment"-- def test_to_error_report_with_model_handle(self) -> None:- """Report includes model field for errors with model_handle."""+ problem = err.to_problem(view=ProblemView.OPERATOR)+ assert find_inference_error_category_in_chain(err) == InferenceErrorCategory.TRANSIENT+ assert problem.code == CoreCode.PROVIDER_UNAVAILABLE+ assert problem.is_retryable is True+ advice = err.advised_action()+ assert advice is not None+ assert advice.kind is UserActionKind.WAIT_AND_RETRY+ assert advice.detail == "Retry in a moment"+ assert "Retry in a moment" not in json.dumps(problem.to_wire())++ def test_to_problem_with_model_handle(self) -> None:+ """The operator's diagnostics name the model of an error carrying a model_handle."""err = LLMModelNotFoundError(message="missing", model_handle="gpt-4o")- report = err.to_error_report()- assert report.model == "gpt-4o"- assert report.error_category == "configuration"+ problem = err.to_problem(view=ProblemView.OPERATOR)+ assert problem.diagnostics is not None+ assert problem.diagnostics.model == "gpt-4o"+ assert find_inference_error_category_in_chain(err) == InferenceErrorCategory.CONFIGURATION- def test_to_error_report_with_provider(self) -> None:- """Report includes provider field for errors with backend_name."""+ def test_to_problem_with_provider(self) -> None:+ """The operator's diagnostics name the provider of an error carrying a backend_name, which the caller never reads."""err = InferenceBackendCredentialsError(credentials_error_type=InferenceBackendCredentialsErrorType.VAR_NOT_FOUND,backend_name="openai",message="key missing",key_name="OPENAI_API_KEY",)- report = err.to_error_report()- assert report.provider == "openai"- assert report.error_category == "configuration"-- def test_to_error_report_to_dict_omits_none(self) -> None:- """to_dict() omits None-valued fields."""+ problem = err.to_problem(view=ProblemView.OPERATOR)+ assert problem.diagnostics is not None+ assert problem.diagnostics.provider is not None+ assert problem.diagnostics.provider.name == "openai"+ assert find_inference_error_category_in_chain(err) == InferenceErrorCategory.CONFIGURATION+ assert err.to_problem(view=ProblemView.CALLER).diagnostics is None++ def test_to_problem_to_wire_omits_none(self) -> None:+ """to_wire() omits every member that holds no value, and the caller's view carries no diagnostics."""err = LLMCompletionError("plain error")- report_dict = err.to_error_report().to_dict()- assert "error_category" not in report_dict- assert "user_action" not in report_dict- assert "model" not in report_dict- assert "provider" not in report_dict- assert report_dict == {- "code": "runtime.unexpected",- "error_type": "LLMCompletionError",- "message": "plain error",+ assert err.to_problem(view=ProblemView.CALLER).to_wire() == {+ "type": "https://mthds.ai/errors/runtime.unexpected","title": "An unexpected error occurred",- "type_uri": "https://mthds.ai/errors/runtime.unexpected",- "error_domain": "runtime",- "retryable": False,+ "detail": "The runtime met an unexpected error.",+ "code": "runtime.unexpected",+ "domain": "runtime",+ "retry": "no",+ "next_step": {"kind": "report", "detail": "Report this to whoever runs the runtime."},}-- def test_to_error_report_to_dict_json_serializable(self) -> None:- """to_dict() output can be serialized to JSON."""+ operator_wire = err.to_problem(view=ProblemView.OPERATOR).to_wire()+ assert operator_wire["diagnostics"]["error_class"] == "LLMCompletionError"+ assert operator_wire["diagnostics"]["message"] == "plain error"+ assert "model" not in operator_wire["diagnostics"]+ assert "provider" not in operator_wire["diagnostics"]++ def test_to_problem_to_wire_json_serializable(self) -> None:+ """to_wire() output can be serialized to JSON and read back as the same problem."""err = LLMModelNotFoundError(message="not found", model_handle="gpt-4o")- report_dict = err.to_error_report().to_dict()- serialized = json.dumps(report_dict)- deserialized = json.loads(serialized)- assert deserialized == report_dict-- def test_error_report_is_frozen(self) -> None:- """ErrorReport is immutable."""- report = ErrorReport.make_for_code(code=CoreCode.PROVIDER_FAILED, error_type="LLMCompletionError", message="test")- with pytest.raises(ValidationError):- report.message = "mutated" # type: ignore[misc]+ problem_wire = err.to_problem(view=ProblemView.OPERATOR).to_wire()+ deserialized = json.loads(json.dumps(problem_wire))+ assert deserialized == problem_wire+ assert PipelexProblem.model_validate(deserialized).to_wire() == problem_wiredef test_from_exc_chain_preserved(self) -> None:"""Exception cause chain is preserved with from exc."""@@ -237,8 +240,8 @@ class TestErrorCategoryInfrastructure:with pytest.raises(CogtError) as exc_info:raise LLMCompletionError(msg, error_category=InferenceErrorCategory.TRANSIENT) from originalassert exc_info.value.__cause__ is original- report = exc_info.value.to_error_report()- assert report.error_category == "transient"+ assert find_inference_error_category_in_chain(exc_info.value) == InferenceErrorCategory.TRANSIENT+ assert exc_info.value.to_problem(view=ProblemView.CALLER).is_retryable is True# --- ModelNotFoundError hierarchy: the load-bearing reroute invariant ---diff --git a/tests/unit/pipelex/cogt/test_inference_error_domain.py b/tests/unit/pipelex/cogt/test_inference_error_domain.pyindex d7d4bf89a..01513eca2 100644--- a/tests/unit/pipelex/cogt/test_inference_error_domain.py+++ b/tests/unit/pipelex/cogt/test_inference_error_domain.py@@ -7,12 +7,13 @@ or a cause carries one, so that a transient failure, which the run repeats, neve"""import pytest-from mthds.protocol.problem.registry import CoreCode+from mthds.protocol.problem.registry import CoreCode, ProblemDomain-from pipelex.base_exceptions import ErrorDomain, PipelexError-from pipelex.cogt.exceptions import InferenceErrorCategory, LLMCompletionError+from pipelex.base_exceptions import PipelexError+from pipelex.cogt.exceptions import InferenceErrorCategory, LLMCompletionError, find_inference_error_category_in_chainfrom pipelex.errors.error_code_declaration import InheritsCausefrom pipelex.errors.error_codes import ErrorCode+from pipelex.errors.problem import ProblemViewfrom pipelex.pipe_run.located_failure import find_root_faultfrom tests.unit.pipelex.cogt.test_data import ExceptionTestData@@ -39,16 +40,17 @@ class TestInferenceErrorDomain:_topic: str,category: InferenceErrorCategory,expected_code: ErrorCode,- expected_domain: ErrorDomain,+ expected_domain: ProblemDomain,expected_retryable: bool,) -> None:"""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()+ error = LLMCompletionError("boom", error_category=category)+ problem = error.to_problem(view=ProblemView.CALLER)- assert report.code == expected_code- assert report.error_domain == expected_domain- assert report.retryable is expected_retryable- assert report.error_category == category+ assert problem.code == expected_code+ assert problem.domain == expected_domain+ assert problem.is_retryable is expected_retryable+ assert find_inference_error_category_in_chain(error) == categorydef test_category_code_cases_cover_every_category(self) -> None:"""The parametrized table is exhaustive — a new category cannot slip in undecided."""@@ -56,11 +58,11 @@ class TestInferenceErrorDomain:assert covered == set(InferenceErrorCategory)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."""+ """The run repeats a call whose category is retryable, so the problem of one built with no code must invite a retry too."""for category in InferenceErrorCategory:- report = LLMCompletionError("boom", error_category=category).to_error_report()+ problem = LLMCompletionError("boom", error_category=category).to_problem(view=ProblemView.CALLER)if category.is_retryable:- assert report.retryable is True, category+ assert problem.is_retryable is True, categorydef test_a_chosen_code_beats_the_category(self) -> None:"""The raise site that chose a code knows more than the category."""@@ -88,10 +90,10 @@ class TestInferenceErrorDomain:wrapper = _WrapperError("Pipe 'greet' failed")wrapper.__cause__ = failure- report = wrapper.to_error_report()+ problem = wrapper.to_problem(view=ProblemView.CALLER)- assert report.code == CoreCode.PROVIDER_UNAVAILABLE- assert report.retryable is True+ assert problem.code == CoreCode.PROVIDER_UNAVAILABLE+ assert problem.is_retryable is Truedef 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."""@@ -103,6 +105,6 @@ class TestInferenceErrorDomain:wrapper.__cause__ = outerassert 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 outer.to_problem(view=ProblemView.OPERATOR).code == CoreCode.PROVIDER_UNAVAILABLE+ assert wrapper.to_problem(view=ProblemView.OPERATOR).code == CoreCode.PROVIDER_UNAVAILABLEassert find_root_fault(error=wrapper) is innerdiff --git a/tests/unit/pipelex/cogt/test_llm_completion_stop_errors.py b/tests/unit/pipelex/cogt/test_llm_completion_stop_errors.pyindex 083c3b8ae..a3bcb39e5 100644--- a/tests/unit/pipelex/cogt/test_llm_completion_stop_errors.py+++ b/tests/unit/pipelex/cogt/test_llm_completion_stop_errors.py@@ -1,8 +1,8 @@from __future__ import annotationsimport pytest+from mthds.protocol.problem.registry import CoreCode, ProblemDomain-from pipelex.base_exceptions import DisclosureMode, ErrorDomainfrom pipelex.cogt.exceptions import (CompletionOutputKind,CompletionTruncationLimit,@@ -11,8 +11,11 @@ from pipelex.cogt.exceptions import (LLMCompletionRefusedError,LLMCompletionTruncatedError,MaxTokensCeiling,+ find_inference_error_category_in_chain,)from pipelex.cogt.inference.error_classification import UserActionKind+from pipelex.errors.error_codes import ErrorCode, error_code_spec+from pipelex.errors.problem import ProblemViewfrom pipelex.pipe_run.exceptions import PipeRouterErrorfrom pipelex.system.pipe_run_mode import PipeRunModefrom tests.helpers.completion_stop import STOP_TEST_PARTIAL_TEXT@@ -206,50 +209,80 @@ class TestLLMCompletionStopErrors:)@pytest.mark.parametrize(- ("error_type", "error", "user_action_detail"),+ ("error_class", "error", "expected_code", "expected_domain", "user_action_detail"),[- ("LLMCompletionTruncatedError", _truncated_error(), "Raise the pipe's max_tokens, or shorten its input."),- ("LLMCompletionTruncatedError", _context_window_error(), CONTEXT_WINDOW_NEXT_STEP),- ("LLMCompletionRefusedError", _refused_error(), "Revise the pipe's prompt or its input."),+ (+ "LLMCompletionTruncatedError",+ _truncated_error(),+ CoreCode.MODEL_OUTPUT_TRUNCATED,+ ProblemDomain.METHOD,+ "Raise the pipe's max_tokens, or shorten its input.",+ ),+ ("LLMCompletionTruncatedError", _context_window_error(), CoreCode.MODEL_CONTEXT_EXCEEDED, ProblemDomain.INPUT, CONTEXT_WINDOW_NEXT_STEP),+ (+ "LLMCompletionRefusedError",+ _refused_error(),+ CoreCode.MODEL_CONTENT_REFUSED,+ ProblemDomain.INPUT,+ "Revise the pipe's prompt or its input.",+ ),],)- def test_the_report_carries_the_fields_an_agent_branches_on(self, error_type: str, error: LLMCompletionError, user_action_detail: str) -> None:- """A content error in the input domain, not retryable, its next step a change of input, its type its own."""+ def test_the_problem_carries_the_fields_an_agent_branches_on(+ self,+ error_class: str,+ error: LLMCompletionError,+ expected_code: ErrorCode,+ expected_domain: ProblemDomain,+ user_action_detail: str,+ ) -> None:+ """A content error no retry clears, its code and domain its stop's, its class and model for the operator, its advice a change of input."""assert isinstance(error, LLMCompletionError)- report = error.to_error_report()-- assert report.error_type == error_type- assert report.error_category == InferenceErrorCategory.CONTENT- assert report.error_domain == ErrorDomain.INPUT- assert report.retryable is False- assert report.model == "claude-5-sonnet"- assert report.user_action is not None- assert report.user_action.kind == UserActionKind.CHANGE_INPUT- assert report.user_action.detail == user_action_detail- assert report.http_status == 422+ problem = error.to_problem(view=ProblemView.OPERATOR)++ assert problem.code == expected_code+ assert problem.domain == expected_domain+ assert problem.is_retryable is False+ assert error_code_spec(expected_code).status == 422+ assert problem.diagnostics is not None+ assert problem.diagnostics.error_class == error_class+ assert problem.diagnostics.model == "claude-5-sonnet"+ assert find_inference_error_category_in_chain(error) == InferenceErrorCategory.CONTENT+ advice = error.advised_action()+ assert advice is not None+ assert advice.kind == UserActionKind.CHANGE_INPUT+ assert advice.detail == user_action_detail@pytest.mark.parametrize("error", [_truncated_error(), _context_window_error(), _refused_error()])- def test_the_message_survives_strict_disclosure_without_the_partial_text(self, error: LLMCompletionError) -> None:- payload = error.to_error_report().to_dict(disclosure_mode=DisclosureMode.STRICT)+ def test_the_caller_reads_the_model_without_the_partial_text(self, error: LLMCompletionError) -> None:+ """The caller's problem names the model in the code's parameters, and no view carries the partial text."""+ caller = error.to_problem(view=ProblemView.CALLER)+ operator = error.to_problem(view=ProblemView.OPERATOR)- assert payload["message"] == error.message- assert payload["user_action"]["kind"] == "change_input"- assert payload["error_domain"] == "input"- assert payload["retryable"] is False- assert STOP_TEST_PARTIAL_TEXT not in payload["message"]+ assert caller.params is not None+ assert caller.params.as_wire()["model"] == "claude-5-sonnet"+ assert caller.is_retryable is False+ assert caller.diagnostics is None+ assert operator.diagnostics is not None+ assert operator.diagnostics.message == error.message+ assert STOP_TEST_PARTIAL_TEXT not in str(caller.to_wire())+ assert STOP_TEST_PARTIAL_TEXT not in str(operator.to_wire())def test_a_run_failure_located_at_the_pipe_reports_the_truncation(self) -> None:- """The pipe router's located report keeps the truncation's identity, classification and caller-facing message."""+ """The pipe router's located problem keeps the truncation's code, its class and message for the operator, and the pipe's location."""truncation = _truncated_error()located = PipeRouterError.make_located(failure=truncation, run_mode=PipeRunMode.LIVE, pipe_code="ui_designer", output_name=None, pipe_stack=["flow", "ui_designer"])located.__cause__ = truncation- report = located.to_error_report()+ problem = located.to_problem(view=ProblemView.OPERATOR)- assert report.error_type == "LLMCompletionTruncatedError"- assert report.message == f"Pipe 'ui_designer' failed (flow → ui_designer): {TRUNCATED_MESSAGE}"- assert report.retryable is False- assert report.error_domain == ErrorDomain.INPUT- assert report.to_dict(disclosure_mode=DisclosureMode.STRICT)["message"] == report.message+ assert problem.code == CoreCode.MODEL_OUTPUT_TRUNCATED+ assert problem.domain == ProblemDomain.METHOD+ assert problem.is_retryable is False+ assert problem.location is not None+ assert problem.location.as_wire() == {"pipe": "ui_designer", "path": ["flow", "ui_designer"]}+ assert problem.diagnostics is not None+ assert problem.diagnostics.error_class == "LLMCompletionTruncatedError"+ assert problem.diagnostics.message == TRUNCATED_MESSAGEdiff --git a/tests/unit/pipelex/cogt/test_model_choice_not_found_disclosure.py b/tests/unit/pipelex/cogt/test_model_choice_not_found_disclosure.pyindex 6ecd8cd3c..467157954 100644--- a/tests/unit/pipelex/cogt/test_model_choice_not_found_disclosure.py+++ b/tests/unit/pipelex/cogt/test_model_choice_not_found_disclosure.py@@ -1,6 +1,8 @@-from pipelex.base_exceptions import INTERNAL_ERROR_PLACEHOLDER, DisclosureMode, ErrorReport+from mthds.protocol.problem.registry import CoreCode, ProblemDomain, StepKind+from pipelex.cogt.exceptions import ModelChoiceNotFoundErrorfrom pipelex.cogt.model_backends.model_type import ModelType+from pipelex.errors.problem import PipelexProblem, ProblemViewclass TestModelChoiceNotFoundDisclosure:@@ -13,23 +15,29 @@ class TestModelChoiceNotFoundDisclosure:suggestions=["gpt-5.5", "gpt-5.4"],)- def test_message_survives_strict_disclosure(self) -> None:- """The unknown model name and its suggestions reach a STRICT (hosted) caller instead of the placeholder."""- payload = self._make_error().to_error_report().to_dict(disclosure_mode=DisclosureMode.STRICT)- assert payload["message"] == "Model handle 'gpt-5.1' was not found in the model deck\n\nDid you mean: gpt-5.5, gpt-5.4"- assert payload["message"] != INTERNAL_ERROR_PLACEHOLDER- assert payload["error_type"] == "ModelChoiceNotFoundError"- assert payload["error_domain"] == "input"+ def test_the_caller_reads_the_unknown_model_and_its_suggestions(self) -> None:+ """The unknown model name and its suggestions reach a hosted caller, in the code's sentence and its parameters."""+ caller = self._make_error().to_problem(view=ProblemView.CALLER)+ assert caller.code == CoreCode.MODEL_UNKNOWN+ assert caller.domain == ProblemDomain.METHOD+ assert caller.detail == "The method names the llm model 'gpt-5.1', which no catalog knows."+ assert caller.next_step.kind == StepKind.CHANGE_MODEL+ assert caller.params is not None+ assert caller.params.as_wire() == {"model": "gpt-5.1", "model_type": "llm", "suggestions": ["gpt-5.5", "gpt-5.4"]}+ assert caller.diagnostics is None- def test_message_survives_the_worker_to_runner_hop(self) -> None:- """The hosted path packs the report VERBOSE on the worker, rebuilds it on the runner, then projects STRICT.+ def test_the_operator_reads_the_error_s_own_message(self) -> None:+ """The error's own message, its suggestions included, is the operator's diagnostics."""+ operator = self._make_error().to_problem(view=ProblemView.OPERATOR)+ assert operator.diagnostics is not None+ assert operator.diagnostics.error_class == "ModelChoiceNotFoundError"+ assert operator.diagnostics.message == "Model handle 'gpt-5.1' was not found in the model deck\n\nDid you mean: gpt-5.5, gpt-5.4"- The caller-facing flag is computed where the error is raised (the worker), so it must ride the- VERBOSE round trip for the runner's STRICT projection to keep the message.- """- packed = self._make_error().to_error_report().to_dict()- recovered = ErrorReport.from_dict(packed)- assert recovered.caller_facing_message is True- payload = recovered.to_dict(disclosure_mode=DisclosureMode.STRICT)- assert "gpt-5.1" in payload["message"]- assert "Did you mean: gpt-5.5, gpt-5.4" in payload["message"]+ def test_the_caller_s_view_survives_the_worker_to_runner_hop(self) -> None:+ """The hosted path builds the problem on the worker and reads it back on the runner, which answers the caller with it."""+ packed = self._make_error().to_problem(view=ProblemView.CALLER).to_wire()+ recovered = PipelexProblem.model_validate(packed)+ assert recovered.to_wire() == packed+ assert recovered.params is not None+ assert recovered.params.as_wire()["model"] == "gpt-5.1"+ assert recovered.params.as_wire()["suggestions"] == ["gpt-5.5", "gpt-5.4"]diff --git a/tests/unit/pipelex/cogt/test_worker_error_enrichment.py b/tests/unit/pipelex/cogt/test_worker_error_enrichment.pyindex b86777967..5404da2ef 100644--- a/tests/unit/pipelex/cogt/test_worker_error_enrichment.py+++ b/tests/unit/pipelex/cogt/test_worker_error_enrichment.py@@ -4,7 +4,7 @@ A `CogtError` raised deep inside a provider plugin (LLMCompletionError,ImgGenGenerationError, ExtractJobFailureError, SearchJobFailureError) carriesno model or provider of its own. Each worker family's public-method chokepointfills `model_handle` / `backend_name` from the worker — where both are-unambiguously known — so the eventual `ErrorReport` can attribute the failure.+unambiguously known — so the operator's diagnostics on the eventual problem can attribute the failure."""from __future__ import annotations@@ -17,6 +17,7 @@ from pydantic import BaseModelfrom typing_extensions import overridefrom pipelex.cogt.exceptions import (+ CogtError,ExtractJobFailureError,ImgGenGenerationError,InferenceErrorCategory,@@ -29,6 +30,7 @@ from pipelex.cogt.img_gen.img_gen_worker_abstract import ImgGenWorkerAbstractfrom pipelex.cogt.llm.llm_worker_abstract import LLMWorkerAbstractfrom pipelex.cogt.llm.thinking_mode import ThinkingModefrom pipelex.cogt.search.search_worker_abstract import SearchWorkerAbstract+from pipelex.errors.problem import ProblemDiagnostics, ProblemViewif TYPE_CHECKING:from pytest_mock import MockerFixture@@ -37,6 +39,14 @@ WORKER_MODEL = "claude-sonnet-4"WORKER_PROVIDER = "anthropic"+def _diagnostics_of(error: Exception) -> ProblemDiagnostics:+ """The operator's diagnostics of a worker's error, which attribute the failure to its model and its provider."""+ assert isinstance(error, CogtError)+ diagnostics = error.to_problem(view=ProblemView.OPERATOR).diagnostics+ assert diagnostics is not None+ return diagnostics++class _StubSchema(BaseModel):"""Minimal schema for the gen_object code path."""@@ -163,9 +173,10 @@ class TestWorkerErrorEnrichment:with pytest.raises(LLMCompletionError) as exc_info:await invocation- report = exc_info.value.to_error_report()- assert report.model == WORKER_MODEL- assert report.provider == WORKER_PROVIDER+ diagnostics = _diagnostics_of(exc_info.value)+ assert diagnostics.model == WORKER_MODEL+ assert diagnostics.provider is not None+ assert diagnostics.provider.name == WORKER_PROVIDERasync def test_llm_worker_does_not_overwrite_existing_model(self, mocker: MockerFixture) -> None:"""An inner error that already set model_handle keeps its value; only the missing provider is filled."""@@ -176,9 +187,10 @@ class TestWorkerErrorEnrichment:with pytest.raises(LLMModelNotFoundError) as exc_info:await worker.gen_text(llm_job=_make_llm_job(mocker))- report = exc_info.value.to_error_report()- assert report.model == inner_model- assert report.provider == WORKER_PROVIDER+ diagnostics = _diagnostics_of(exc_info.value)+ assert diagnostics.model == inner_model+ assert diagnostics.provider is not None+ assert diagnostics.provider.name == WORKER_PROVIDERasync def test_llm_worker_skips_unknown_provider(self, mocker: MockerFixture) -> None:"""A worker that does not know its provider ('unknown' default) leaves provider unset."""@@ -188,9 +200,9 @@ class TestWorkerErrorEnrichment:with pytest.raises(LLMCompletionError) as exc_info:await worker.gen_text(llm_job=_make_llm_job(mocker))- report = exc_info.value.to_error_report()- assert report.model == WORKER_MODEL- assert report.provider is None+ diagnostics = _diagnostics_of(exc_info.value)+ assert diagnostics.model == WORKER_MODEL+ assert diagnostics.provider is None@pytest.mark.parametrize("raised_error",@@ -225,9 +237,10 @@ class TestWorkerErrorEnrichment:with pytest.raises(ImgGenGenerationError) as exc_info:await invocation- report = exc_info.value.to_error_report()- assert report.model == WORKER_MODEL- assert report.provider == WORKER_PROVIDER+ diagnostics = _diagnostics_of(exc_info.value)+ assert diagnostics.model == WORKER_MODEL+ assert diagnostics.provider is not None+ assert diagnostics.provider.name == WORKER_PROVIDERasync def test_extract_worker_enriches_error(self, mocker: MockerFixture) -> None:"""extract_pages stamps model and provider onto a bare ExtractJobFailureError."""@@ -237,9 +250,10 @@ class TestWorkerErrorEnrichment:with pytest.raises(ExtractJobFailureError) as exc_info:await worker.extract_pages(extract_job=_make_extract_job(mocker))- report = exc_info.value.to_error_report()- assert report.model == WORKER_MODEL- assert report.provider == WORKER_PROVIDER+ diagnostics = _diagnostics_of(exc_info.value)+ assert diagnostics.model == WORKER_MODEL+ assert diagnostics.provider is not None+ assert diagnostics.provider.name == WORKER_PROVIDER@pytest.mark.parametrize("use_structured", [False, True])async def test_search_worker_enriches_error(self, mocker: MockerFixture, use_structured: bool) -> None:@@ -255,6 +269,7 @@ class TestWorkerErrorEnrichment:with pytest.raises(SearchJobFailureError) as exc_info:await invocation- report = exc_info.value.to_error_report()- assert report.model == WORKER_MODEL- assert report.provider == WORKER_PROVIDER+ diagnostics = _diagnostics_of(exc_info.value)+ assert diagnostics.model == WORKER_MODEL+ assert diagnostics.provider is not None+ assert diagnostics.provider.name == WORKER_PROVIDERdiff --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 a76feabb2..6288d9ff1 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,9 +1,10 @@import pytest-from mthds.protocol.problem.registry import CoreCode+from mthds.protocol.problem.registry import CoreCode, ProblemDomain, RetryVerdict-from pipelex.base_exceptions import DisclosureMode, ErrorDomain, PipelexError+from pipelex.base_exceptions import PipelexErrorfrom pipelex.core.bundle_resources.exceptions import BundleResourceNotNamedError, BundleResourcePathErrorfrom pipelex.errors.error_codes import ErrorCode+from pipelex.errors.problem import ProblemViewclass TestBundleResourceExceptions:@@ -17,17 +18,17 @@ class TestBundleResourceExceptions: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()+ """Deterministic refusals of what the caller sent, so their problem documents carry `retry: no` in either view."""+ error = error_class("The files sent are refused.")- assert report.code == expected_code- assert report.retryable is False- assert report.error_domain == ErrorDomain.INPUT- assert report.caller_facing_message is True- assert report.to_dict()["retryable"] is False- assert report.to_dict(disclosure_mode=DisclosureMode.STRICT)["retryable"] is False+ for view in (ProblemView.CALLER, ProblemView.OPERATOR):+ problem = error.to_problem(view=view)+ assert problem.code == expected_code+ assert problem.domain == ProblemDomain.INPUT+ assert problem.retry == RetryVerdict.NO+ assert problem.to_wire()["retry"] == "no"- def test_a_wrapper_raised_from_one_carries_its_retryable(self) -> None:+ def test_a_wrapper_raised_from_one_carries_its_code_and_retry(self) -> None:try:try:cause_msg = "A file no step names."@@ -36,15 +37,18 @@ class TestBundleResourceExceptions:msg = "The library could not be loaded."raise PipelexError(msg) from excexcept PipelexError as wrapper:- report = wrapper.to_error_report()+ problem = wrapper.to_problem(view=ProblemView.OPERATOR)- assert report.error_type == "PipelexError"- assert report.retryable is False+ assert problem.code == CoreCode.REQUEST_INVALID+ assert problem.retry == RetryVerdict.NO+ assert problem.diagnostics is not None+ assert problem.diagnostics.error_class == "PipelexError"+ assert [cause.error_class for cause in problem.diagnostics.causes or []] == ["BundleResourceNotNamedError"]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()+ problem = BundleResourcePathError("Two files name one file.").with_error_code(CoreCode.REQUEST_INVALID).to_problem(view=ProblemView.CALLER)- assert report.code == CoreCode.REQUEST_INVALID- assert report.error_domain == ErrorDomain.INPUT- assert report.retryable is False+ assert problem.code == CoreCode.REQUEST_INVALID+ assert problem.domain == ProblemDomain.INPUT+ assert problem.retry == RetryVerdict.NOdiff --git a/tests/unit/pipelex/core/memory/input_shaper/test_errors.py b/tests/unit/pipelex/core/memory/input_shaper/test_errors.pyindex b83dc4a48..8827b5862 100644--- a/tests/unit/pipelex/core/memory/input_shaper/test_errors.py+++ b/tests/unit/pipelex/core/memory/input_shaper/test_errors.py@@ -1,6 +1,7 @@from typing import Anyimport pytest+from mthds.protocol.problem.registry import CoreCodefrom pipelex import logfrom pipelex.core.memory.exceptions import (@@ -15,6 +16,8 @@ from pipelex.core.memory.exceptions import ()from pipelex.core.memory.input_shaper import InputShaperfrom pipelex.core.pipes.variable_multiplicity import VariableMultiplicity+from pipelex.errors.error_codes import error_code_spec+from pipelex.errors.problem import ProblemViewfrom pipelex.interpreter_hub import get_concept_libraryfrom tests.unit.pipelex.core.memory.input_shaper.data import build_input_specs@@ -118,6 +121,61 @@ ERROR_CASES: list[tuple[str, str, VariableMultiplicity | None, Any, type[InputSh]+# (test_name, concept_ref, multiplicity, provided_value, expected_code, expected_params, expected_detail)+# What the caller reads of a shaping error: its code's sentence, rendered from the input and the facts its factory knew.+# `None` for the detail is the code's title, which a code whose template needs a fact the refusal does not have falls back on.+CALLER_VIEW_CASES: list[tuple[str, str, VariableMultiplicity | None, Any, CoreCode, dict[str, Any], str | None]] = [+ (+ "count-mismatch",+ "shaper_test.Question",+ 2,+ ["a"],+ CoreCode.INPUT_WRONG_MULTIPLICITY,+ {"input": "my_input", "expected": "count", "expected_count": 2, "provided_count": 1},+ "The input 'my_input' gives 1 item or items, which does not fit the multiplicity the method declares (count).",+ ),+ (+ "list-where-singular",+ "shaper_test.Question",+ None,+ ["a", "b", "c"],+ CoreCode.INPUT_WRONG_MULTIPLICITY,+ {"input": "my_input", "expected": "single", "provided_count": 3},+ "The input 'my_input' gives 3 item or items, which does not fit the multiplicity the method declares (single).",+ ),+ (+ "explicit-incompatible",+ "shaper_test.Priority",+ None,+ {"concept": "shaper_test.Question", "content": "hi"},+ CoreCode.INPUT_WRONG_CONCEPT,+ {"input": "my_input", "expected": "shaper_test.Priority", "provided": "shaper_test.Question"},+ "The input 'my_input' is given as 'shaper_test.Question', but the method accepts 'shaper_test.Priority' there.",+ ),+ (+ "choice-bare-string",+ "native.Choice",+ None,+ "billing",+ CoreCode.INPUT_WRONG_CONCEPT,+ {"input": "my_input", "expected": "native.Choice", "provided": "native.Text"},+ "The input 'my_input' is given as 'native.Text', but the method accepts 'native.Choice' there.",+ ),+ (+ "structure-missing-field",+ "shaper_test.ShaperInvoice",+ None,+ {"invoice_number": "INV-1"},+ CoreCode.INPUT_INVALID,+ {"input": "my_input", "field": "amount"},+ "The input 'my_input' does not fit its concept's structure at 'amount'.",+ ),+ # `input.invalid` names the field at fault, and a value wrong as a whole has none: its sentence is the code's title.+ ("wrong-str-for-number", "shaper_test.Priority", None, "42", CoreCode.INPUT_INVALID, {"input": "my_input"}, None),+ ("null-top-level", "native.Text", None, None, CoreCode.INPUT_INVALID, {"input": "my_input"}, None),+]++class TestInputShaperErrors:@pytest.mark.parametrize(("test_name", "concept_ref", "multiplicity", "provided_value", "expected_exception", "error_match"),@@ -151,3 +209,42 @@ class TestInputShaperErrors:message = str(exc_info.value)assert "'question'" in message, "Unknown-name error should list the declared inputs"assert "'quesion'" in message, "Unknown-name error should name the offending input"++ @pytest.mark.parametrize(+ ("test_name", "concept_ref", "multiplicity", "provided_value", "expected_code", "expected_params", "expected_detail"),+ CALLER_VIEW_CASES,+ )+ def test_the_caller_reads_the_input_and_what_is_wrong_with_it(+ self,+ test_name: str,+ concept_ref: str,+ multiplicity: VariableMultiplicity | None,+ provided_value: Any,+ expected_code: CoreCode,+ expected_params: dict[str, Any],+ expected_detail: str | None,+ ) -> None:+ """The message is the operator's: the caller reads the input, and the facts its code declares, as parameters."""+ log.info(f"Testing the caller view of: {test_name}")+ input_specs = build_input_specs([("my_input", concept_ref, multiplicity)])++ with pytest.raises(InputShapingError) as exc_info:+ InputShaper.shape({"my_input": provided_value}, input_specs=input_specs, concept_provider=get_concept_library(), read_scope=None)++ caller = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert caller.code == expected_code+ assert caller.params is not None+ assert caller.params.as_wire() == expected_params+ assert caller.detail == (expected_detail or error_code_spec(expected_code).title)+ assert caller.location is not None+ assert caller.location.as_wire() == {"input": "my_input"}++ def test_an_unknown_input_name_is_named_to_the_caller(self) -> None:+ input_specs = build_input_specs([("question", "native.Text", None)])++ with pytest.raises(UnknownInputNameError) as exc_info:+ InputShaper.shape({"quesion": "typo"}, input_specs=input_specs, concept_provider=get_concept_library(), read_scope=None)++ caller = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert caller.code == CoreCode.INPUT_UNEXPECTED+ assert caller.detail == "The request gives the input 'quesion', which the method does not declare."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 cc9dec048..20541e5d6 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@@ -1,8 +1,8 @@from typing import Anyimport pytest+from mthds.protocol.problem.registry import CoreCode, ProblemDomain-from pipelex.base_exceptions import ErrorDomainfrom pipelex.cogt.inference.error_classification import UserActionKindfrom pipelex.core.memory.exceptions import (StructureValidationError,@@ -12,6 +12,7 @@ from pipelex.core.pipes.variable_multiplicity import VariableMultiplicityfrom pipelex.core.stuffs.exceptions import StuffFactoryErrorfrom pipelex.core.stuffs.number_content import NumberContentfrom pipelex.core.stuffs.text_content import TextContent+from pipelex.errors.problem import ProblemViewfrom pipelex.interpreter_hub import get_concept_libraryfrom tests.unit.pipelex.core.memory.input_shaper.data import build_input_specs@@ -46,12 +47,17 @@ 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.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 None- assert error.user_action.kind == UserActionKind.CHANGE_INPUT- assert "'JSON[]'" in error.user_action.detail- assert "envelope" not in error.user_action.detail+ caller = error.to_problem(view=ProblemView.CALLER)+ assert caller.code == CoreCode.INPUT_INVALID+ assert caller.domain == ProblemDomain.INPUT+ assert "typing.Union" not in str(caller.to_wire())+ # The fix is on the author's side: the declaration, and no envelope. The advice is a local tip, never on a problem.+ advice = error.advised_action()+ assert advice is not None+ assert advice.kind == UserActionKind.CHANGE_INPUT+ assert "'JSON[]'" in advice.detail+ assert "envelope" not in advice.detail+ assert advice.detail not in str(caller.to_wire())def test_a_bare_number_at_a_dynamic_slot_is_refused_naming_the_input(self) -> None:input_specs = build_input_specs([("payload", "native.Dynamic", None)])@@ -83,7 +89,7 @@ class TestInputShaperFallbackRefusal:with pytest.raises(StructureValidationError, match="with no reading for this one") as exc_info:InputShaper.shape(payload_input, input_specs=input_specs, concept_provider=get_concept_library(), read_scope=None)- user_action = exc_info.value.user_action+ user_action = exc_info.value.advised_action()assert user_action is not Noneassert f"as {suggested_declaration}," in user_action.detail@@ -140,10 +146,11 @@ class TestInputShaperFallbackRefusal:assert "Expected shape:" in str(error)assert isinstance(error.__cause__, StuffFactoryError)# The value is right in substance: declaring the input as `JSON` would discard the concept the method asked for.- assert error.user_action is not None- assert error.user_action.kind == UserActionKind.CHANGE_INPUT- assert "expected shape" in error.user_action.detail- assert "Declare" not in error.user_action.detail+ advice = error.advised_action()+ assert advice is not None+ assert advice.kind == UserActionKind.CHANGE_INPUT+ assert "expected shape" in advice.detail+ assert "Declare" not in advice.detail@pytest.mark.parametrize(("concept_ref", "multiplicity", "provided_value", "suggested_declaration"),@@ -165,7 +172,7 @@ class TestInputShaperFallbackRefusal:with pytest.raises(StructureValidationError, match="with no reading for this one") as exc_info:InputShaper.shape(payload_input, input_specs=input_specs, concept_provider=get_concept_library(), read_scope=None)- user_action = exc_info.value.user_action+ user_action = exc_info.value.advised_action()assert user_action is not Noneassert f"as {suggested_declaration}," in user_action.detail@@ -192,7 +199,8 @@ class TestInputShaperFallbackRefusal:assert "Expected shape:" in str(error)assert isinstance(error.__cause__, StuffFactoryError)# A bare level is a verdict's level without the verdict: declaring the input `Anything` would discard the verdict the method branches on.- assert error.user_action is not None- assert error.user_action.kind == UserActionKind.CHANGE_INPUT- assert "expected shape" in error.user_action.detail- assert "Declare" not in error.user_action.detail+ advice = error.advised_action()+ assert advice is not None+ assert advice.kind == UserActionKind.CHANGE_INPUT+ assert "expected shape" in advice.detail+ assert "Declare" not in advice.detaildiff --git a/tests/unit/pipelex/core/method_trees/test_tree_python.py b/tests/unit/pipelex/core/method_trees/test_tree_python.pyindex 98acc9fa2..e44c6dd09 100644--- a/tests/unit/pipelex/core/method_trees/test_tree_python.py+++ b/tests/unit/pipelex/core/method_trees/test_tree_python.py@@ -6,9 +6,9 @@ from pathlib import Pathimport pytestfrom mthds.method_tree.lister import list_method_treefrom mthds.method_tree.models import MethodTree+from mthds.protocol.problem.registry import CoreCodefrom pytest_mock import MockerFixture-from pipelex.base_exceptions import DisclosureModefrom pipelex.core.method_trees import tree_pythonfrom pipelex.core.method_trees.exceptions import TreeModuleExcludedError, TreeModuleShadowingError, TreePythonError, TreePythonHeldErrorfrom pipelex.core.method_trees.tree_python import (@@ -17,6 +17,7 @@ from pipelex.core.method_trees.tree_python import (import_held_tree_module,sharing_module_name_checks,)+from pipelex.errors.problem import ProblemViewfrom pipelex.tools.typing.module_inspector import import_module_from_file_LABEL = "the method tree holding probe.mthds"@@ -203,13 +204,15 @@ class TestTreePython:finally:sys.modules.pop("tree_probe_site", None)- def test_the_errors_of_a_tree_name_no_path_of_this_host_under_strict_disclosure(self, tmp_path: Path) -> None:+ def test_the_errors_of_a_tree_name_no_path_of_this_host(self, tmp_path: Path) -> None:shadowing = _write_tree(root=tmp_path / "shadowing", files={"shadowing.mthds": 'domain = "shadowing"\n', "json.py": "X = 1\n"})with pytest.raises(TreeModuleShadowingError) as shadowing_info:TREE_PYTHON_HOLD.acquire(tree=shadowing, holder="run-shadowing", label="the method tree holding shadowing.mthds")- strict_report = json.dumps(shadowing_info.value.to_error_report().to_dict(disclosure_mode=DisclosureMode.STRICT))- assert "the method tree holding shadowing.mthds" in strict_report- assert "json.py" in strict_report+ shadowing_problem = shadowing_info.value.to_problem(view=ProblemView.CALLER)+ assert shadowing_problem.code == CoreCode.METHOD_NAME_CONFLICT+ operator_report = json.dumps(shadowing_info.value.to_problem(view=ProblemView.OPERATOR).to_wire())+ assert "the method tree holding shadowing.mthds" in operator_report+ assert "json.py" in operator_reportguarded = _write_tree(root=tmp_path / "guarded",@@ -229,7 +232,9 @@ class TestTreePython:with pytest.raises(TreePythonHeldError) as held_info:TREE_PYTHON_HOLD.acquire(tree=other, holder="run-other", label="the method tree holding other.mthds")- for message in (strict_report, excluded_info.value.message, held_info.value.message):+ # The excluded-module refusal is an ImportError the import machinery raises, read by its message alone.+ caller_reports = [json.dumps(error.to_problem(view=ProblemView.CALLER).to_wire()) for error in (shadowing_info.value, held_info.value)]+ for message in (operator_report, excluded_info.value.message, held_info.value.message, *caller_reports):for host_path in _host_paths(tmp_path=tmp_path):assert host_path not in messagediff --git a/tests/unit/pipelex/core/test_validation_report.py b/tests/unit/pipelex/core/test_validation_report.pyindex f536a6670..11c488521 100644--- a/tests/unit/pipelex/core/test_validation_report.py+++ b/tests/unit/pipelex/core/test_validation_report.py@@ -27,8 +27,9 @@ from typing import TYPE_CHECKINGimport pytestfrom pydantic import BaseModel, ValidationError-from pipelex.base_exceptions import ErrorDomain, ErrorReport, PipelexConfigError+from pipelex.base_exceptions import ErrorDomain, PipelexConfigErrorfrom pipelex.core.validation import MIGRATE_COMMAND, raise_config_setup_error, report_validation_error+from pipelex.errors.problem import PipelexProblem, ProblemViewfrom pipelex.migration import run as migration_run_modulefrom pipelex.migration.exceptions import MigrationLedgerErrorfrom pipelex.migration.goldens import pre_history_document_path@@ -260,7 +261,7 @@ class TestAFailureInsideTheScanIsNotTheFailureTheUserSees:class TestTheErrorCarriesBothTheDomainAndTheBlock:- """The charter's own pair: `error_domain` stays `config`, and the block rides beside it."""+ """The charter's own pair: the error's domain stays `config`, and the block rides beside it in the operator's diagnostics."""def test_the_raised_error_reports_the_config_domain_and_the_migration(self, machine: Path) -> None:machine.joinpath("telemetry.toml").write_text(_old_shape_telemetry_document(), encoding="utf-8")@@ -270,19 +271,20 @@ class TestTheErrorCarriesBothTheDomainAndTheBlock:with pytest.raises(PipelexConfigError) as raised:raise_config_setup_error(config_error=refusal, surface_id=TELEMETRY_CONFIG_SURFACE_ID)- error_report = raised.value.to_error_report()- assert error_report.error_domain == ErrorDomain.CONFIG, "a new domain would route the agent hooks to BLOCK"- assert error_report.migration is not None- assert error_report.migration.remedy == MIGRATE_COMMAND+ problem = raised.value.to_problem(view=ProblemView.OPERATOR)+ assert ErrorDomain.from_problem_domain(problem.effective_domain) == ErrorDomain.CONFIG, "a new domain would route the agent hooks to BLOCK"+ assert problem.diagnostics is not None+ assert problem.diagnostics.migration is not None+ assert problem.diagnostics.migration.remedy == MIGRATE_COMMAND@pytest.mark.usefixtures("machine")def test_the_report_the_error_produces_is_json_serializable(self, machine: Path) -> None:- """`ErrorReport.to_dict()` is a serialization surface, and the block carries real `Path`s.+ """The problem's wire form is a serialization surface, and the block carries real `Path`s.The webhook delivery path hands that dict straight to `json.dumps`, which cannot serializea `PosixPath`. Not reachable from a pipeline run today — nothing raises this error inside- one — but `to_dict` is documented as *the* serialization surface, so a field that quietly- makes it unserializable is a trap left for whoever wires the next consumer.+ one — but `to_wire` is *the* serialization surface, so a field that quietly makes it+ unserializable is a trap left for whoever wires the next consumer."""machine.joinpath("telemetry.toml").write_text(_old_shape_telemetry_document(), encoding="utf-8")refusal = ConfigValidationError("the configuration was refused")@@ -291,9 +293,11 @@ class TestTheErrorCarriesBothTheDomainAndTheBlock:with pytest.raises(PipelexConfigError) as raised:raise_config_setup_error(config_error=refusal, surface_id=TELEMETRY_CONFIG_SURFACE_ID)- payload = raised.value.to_error_report().to_dict()+ payload = raised.value.to_problem(view=ProblemView.OPERATOR).to_wire()assert json.dumps(payload), "the block must survive a plain json.dumps"- assert ErrorReport.from_dict(payload).migration is not None, "and it must come back through the round-trip"+ diagnostics = PipelexProblem.model_validate(payload).diagnostics+ assert diagnostics is not None+ assert diagnostics.migration is not None, "and it must come back through the round-trip"@pytest.mark.usefixtures("machine")def test_a_healthy_machine_raises_the_same_error_without_a_block(self) -> None:@@ -304,7 +308,9 @@ class TestTheErrorCarriesBothTheDomainAndTheBlock:with pytest.raises(PipelexConfigError) as raised:raise_config_setup_error(config_error=refusal, surface_id=TELEMETRY_CONFIG_SURFACE_ID)- assert raised.value.to_error_report().migration is None+ diagnostics = raised.value.to_problem(view=ProblemView.OPERATOR).diagnostics+ assert diagnostics is not None+ assert diagnostics.migration is Nonedef test_a_refusal_carrying_no_pydantic_error_is_re_raised_as_itself(self) -> None:"""There is nothing to translate, and its own message is already the whole account."""diff --git a/tests/unit/pipelex/errors/test_data.py b/tests/unit/pipelex/errors/test_data.pynew file mode 100644index 000000000..41ecd191c--- /dev/null+++ b/tests/unit/pipelex/errors/test_data.py@@ -0,0 +1,65 @@+from typing import Any, ClassVar+++class ProblemViewsTestData:+ OPERATOR_MESSAGE: ClassVar[str] = "The backend 'acme' has no api_key in /etc/pipelex/backends.toml"+ COMPONENT: ClassVar[str] = "inference backend acme"+ GATEWAY_MESSAGE: ClassVar[str] = "The gateway refused the call; see its message for the integration"+ GATEWAY_PROVIDER_TEXT: ClassVar[str] = "integration 'acme-prod' is disabled: set ACME_PROD_KEY and ACME_PROD_URL"+ # Phrases that send a reader to a text a view may withhold: the error's own message or the provider's.+ HIDDEN_TEXT_PHRASES: ClassVar[tuple[str, ...]] = (+ "error message",+ "its message",+ "own message",+ "the message",+ "provider's message",+ "see the message",+ )++ # A problem whose code no registry of this process holds, as a newer worker or a stored record carries it, built in+ # the operator's view: its step and its diagnostics name a file of the host that a caller must never read.+ PRIVATE_HOST_FILE: ClassVar[str] = "/srv/pipelex/private/settings.toml"+ UNKNOWN_OPERATOR_CODE: ClassVar[str] = "pipelex.config.future_setting_missing"+ UNKNOWN_METHOD_CODE: ClassVar[str] = "method.future_fault"+ UNKNOWN_OPERATOR_PROBLEM: ClassVar[dict[str, Any]] = {+ "type": "https://docs.pipelex.com/errors/pipelex.config.future_setting_missing",+ "title": "A setting the runtime needs is missing",+ "detail": "A setting the runtime needs is missing.",+ "code": "pipelex.config.future_setting_missing",+ "domain": "operator",+ "retry": "no",+ "next_step": {"kind": "fix_configuration", "detail": "Set the setting in '/srv/pipelex/private/settings.toml', then restart the runtime."},+ "diagnostics": {"error_class": "FutureSettingError", "message": "no setting in /srv/pipelex/private/settings.toml"},+ }+ UNKNOWN_METHOD_PROBLEM: ClassVar[dict[str, Any]] = {+ "type": "https://mthds.ai/errors/method.future_fault",+ "title": "The method breaks a rule this runtime does not know",+ "detail": "The method breaks a rule.",+ "code": "method.future_fault",+ "domain": "method",+ "retry": "no",+ "next_step": {"kind": "change_method", "detail": "Correct the rule the host's '/srv/pipelex/private/settings.toml' enforces."},+ }+ # An item whose code no registry of this process holds, as a newer worker sends it: its parameter and its sentence name+ # a file of the host, and nothing tells this process whether its code declares that parameter operator-only.+ UNKNOWN_CODE_ITEM: ClassVar[dict[str, Any]] = {+ "code": "method.future_fault",+ "detail": "The rule in '/srv/pipelex/private/settings.toml' is broken.",+ "params": {"settings_file": "/srv/pipelex/private/settings.toml"},+ "location": {"pipe": "summarize"},+ }+ # Extension members a problem may carry, whose values hold null: the protocol refuses null on a member a model+ # declares, and nowhere else, so each is written back as it was read.+ NULL_HOLDING_EXTENSIONS: ClassVar[dict[str, Any]] = {+ "extension": {"clear": None, "keep": 1, "nested": [None, {"inner": None}]},+ "cleared": None,+ }+ NULL_HOLDING_ITEM_EXTENSIONS: ClassVar[dict[str, Any]] = {"vendor": {"hint": None}}+ # An item built by hand, not by `make_problem_item`, whose parameter and sentence name a part of the host that only an+ # operator may read: `component` is operator-only for `runtime.misconfigured`.+ HAND_BUILT_OPERATOR_ITEM: ClassVar[dict[str, Any]] = {+ "code": "runtime.misconfigured",+ "detail": "The component '/srv/pipelex/private/settings.toml' is misconfigured.",+ "params": {"component": "/srv/pipelex/private/settings.toml"},+ "location": {"pipe": "summarize"},+ }diff --git a/tests/unit/pipelex/errors/test_error_code_gate.py b/tests/unit/pipelex/errors/test_error_code_gate.pyindex ec3f9aaa0..f38a93206 100644--- a/tests/unit/pipelex/errors/test_error_code_gate.py+++ b/tests/unit/pipelex/errors/test_error_code_gate.py@@ -34,7 +34,7 @@ _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.+# What a code decides, which a class no longer declares: the problem reads all four from the code._ATTRIBUTES_THE_CODE_DECIDES: tuple[str, ...] = ("error_domain", "retryable", "_declared_title", "_declared_type_uri")diff --git a/tests/unit/pipelex/errors/test_error_code_resolution.py b/tests/unit/pipelex/errors/test_error_code_resolution.pyindex 10c845126..eb5a0fda7 100644--- a/tests/unit/pipelex/errors/test_error_code_resolution.py+++ b/tests/unit/pipelex/errors/test_error_code_resolution.py@@ -1,14 +1,18 @@-"""How a ``PipelexError`` resolves the registry code its report carries, and what the code decides on the report."""+"""How a ``PipelexError`` resolves the registry code its problem carries, and what the code decides on the problem."""import itertoolsimport reimport pytest-from mthds.protocol.problem.registry import CORE_CODE_SPECS, CoreCode+from mthds.protocol.problem.registry import CORE_CODE_SPECS, CoreCode, ProblemDomain, RetryVerdict-from pipelex.base_exceptions import ErrorDomain, ErrorReport, PipelexConfigError, PipelexError, PipelexUnexpectedError+from pipelex.base_exceptions import PipelexConfigError, PipelexError, PipelexUnexpectedError+from pipelex.cogt.exceptions import InferenceErrorCategory, LLMCompletionError+from pipelex.cogt.inference.error_classification import ProviderErrorMetadata, UserAction, UserActionKind+from pipelex.cogt.inference.provider_name import ProviderNamefrom pipelex.errors.error_code_declaration import ABSTRACT_ERROR, ErrorCodeSet, InheritsCausefrom pipelex.errors.error_codes import error_code_spec, parse_error_code+from pipelex.errors.problem import PipelexProblem, ProblemViewfrom pipelex.errors.registry.pipelex_codes import PipelexErrorCode@@ -44,27 +48,27 @@ def _raise_chain(*errors: BaseException) -> BaseException:class TestErrorCodeResolution:- def test_a_class_code_decides_the_report(self) -> None:- report = _ModelUnknownError("no such model").to_error_report()+ def test_a_class_code_decides_the_problem(self) -> None:+ problem = _ModelUnknownError("no such model").to_problem(view=ProblemView.CALLER)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+ assert problem.code == CoreCode.MODEL_UNKNOWN+ assert problem.title == spec.title+ assert problem.type == f"https://mthds.ai/errors/{CoreCode.MODEL_UNKNOWN}"+ assert problem.domain == ProblemDomain.METHOD+ assert problem.retry == RetryVerdict.NOdef 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+ problem = PipelexConfigError("bad config").to_problem(view=ProblemView.CALLER)+ assert problem.code == PipelexErrorCode.CONFIG_INVALID+ assert problem.type == f"https://docs.pipelex.com/errors/{PipelexErrorCode.CONFIG_INVALID}"+ assert problem.title == error_code_spec(PipelexErrorCode.CONFIG_INVALID).title+ assert problem.domain == ProblemDomain.OPERATORdef 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 _ProviderError("boom").to_problem(view=ProblemView.CALLER).code == CoreCode.PROVIDER_FAILED+ chosen = _ProviderError("slow down").with_error_code(CoreCode.PROVIDER_RATE_LIMITED).to_problem(view=ProblemView.CALLER)assert chosen.code == CoreCode.PROVIDER_RATE_LIMITED- assert chosen.retryable is True+ assert chosen.is_retryable is Truedef 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'")):@@ -73,10 +77,11 @@ class TestErrorCodeResolution: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"+ problem = error.to_problem(view=ProblemView.OPERATOR)+ assert problem.code == CoreCode.MODEL_UNKNOWN+ assert problem.diagnostics is not None+ assert problem.diagnostics.error_class == "_WrapperError"+ assert problem.diagnostics.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"))@@ -93,9 +98,31 @@ class TestErrorCodeResolution:assert isinstance(error, PipelexError)assert error.resolve_error_code() == CoreCode.INPUT_INVALID+ def test_nothing_crosses_a_foreign_exception(self) -> None:+ """An earlier failure below a foreign exception lends the error above it no fact and no advice."""+ earlier_failure = LLMCompletionError(+ "an earlier rate limit",+ error_category=InferenceErrorCategory.TRANSIENT,+ user_action=UserAction(kind=UserActionKind.WAIT_AND_RETRY, detail="Wait a minute."),+ provider_metadata=ProviderErrorMetadata(+ provider=ProviderName.OPENAI, sdk_exception_type="RateLimitError", status_code=429, retry_after_seconds=30.0+ ),+ )+ earlier_failure.fill_model_and_provider("gpt-4o-mini", backend_name="openai")+ error = _raise_chain(_ProviderError("slow down").with_error_code(CoreCode.PROVIDER_RATE_LIMITED), KeyError("raw"), earlier_failure)+ assert isinstance(error, PipelexError)++ problem = error.to_problem(view=ProblemView.OPERATOR)++ assert problem.retry_after is None+ assert problem.diagnostics is not None+ assert problem.diagnostics.model is None+ assert problem.diagnostics.provider is None+ assert error.advised_action() is None+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+ assert PipelexError("bare root").to_problem(view=ProblemView.CALLER).code == CoreCode.RUNTIME_UNEXPECTEDdef test_an_abstract_wrapper_keeps_walking(self) -> None:error = _raise_chain(_AbstractBaseError("outer"), _ModelUnknownError("inner"))@@ -109,20 +136,20 @@ class TestErrorCodeResolution:inner.__cause__ = outerassert 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_the_view_does_not_change_the_code(self) -> None:+ error = PipelexUnexpectedError("ours")+ assert error.to_problem(view=ProblemView.CALLER).code == error.to_problem(view=ProblemView.OPERATOR).code == CoreCode.RUNTIME_UNEXPECTED+ assert error.to_problem(view=ProblemView.CALLER).domain == ProblemDomain.RUNTIMEdef 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())+ problem = PipelexConfigError("config gone").with_error_code(PipelexErrorCode.CONFIG_SYNTAX).to_problem(view=ProblemView.OPERATOR)+ recovered = PipelexProblem.model_validate(problem.to_wire())assert recovered.code == PipelexErrorCode.CONFIG_SYNTAX- assert recovered == report+ assert recovered.to_wire() == problem.to_wire()class TestParseErrorCode:diff --git a/tests/unit/pipelex/errors/test_problem_views.py b/tests/unit/pipelex/errors/test_problem_views.pynew file mode 100644index 000000000..33679e6a2--- /dev/null+++ b/tests/unit/pipelex/errors/test_problem_views.py@@ -0,0 +1,502 @@+import json+import logging+from collections.abc import Sequence+from typing import Any, ClassVar, Self, cast, overload++import pytest+from mthds.protocol.problem.answers import MAX_BODY_NESTING, decode_json, nests_deeper_than+from mthds.protocol.problem.models import ProblemItem+from mthds.protocol.problem.registry import CoreCode, StepKind+from pydantic import BaseModel, model_validator+from pytest_mock import MockerFixture+from typing_extensions import override++from pipelex.base_exceptions import PipelexError+from pipelex.cogt.exceptions import InferenceErrorCategory, LLMCompletionError+from pipelex.cogt.inference.error_classification import ProviderErrorMetadata, UserAction, UserActionKind+from pipelex.cogt.inference.provider_name import ProviderName+from pipelex.errors.error_code_declaration import ErrorCodeDeclaration+from pipelex.errors.error_codes import ErrorCode, error_code_spec+from pipelex.errors.problem import (+ MAX_PROBLEM_TEXT_LENGTH,+ TRUNCATION_MARKER,+ UNKNOWN_CODE_ITEM_DETAIL,+ PipelexProblem,+ ProblemView,+ caller_view_of,+ make_problem,+ problem_metadata,+)+from pipelex.errors.registry.pipelex_codes import PipelexErrorCode+from tests.unit.pipelex.errors.test_data import ProblemViewsTestData+++class _MisconfiguredError(PipelexError):+ error_code: ClassVar[ErrorCodeDeclaration] = CoreCode.RUNTIME_MISCONFIGURED+++class _TemplateRefusalError(PipelexError):+ error_code: ClassVar[ErrorCodeDeclaration] = CoreCode.METHOD_TEMPLATE_INVALID+++class _AmbiguousPipeError(PipelexError):+ error_code: ClassVar[ErrorCodeDeclaration] = CoreCode.REQUEST_PIPE_AMBIGUOUS+++class _UnreadableSequence(Sequence[str]):+ """A sequence of a raise site's own whose items cannot be read: reading one raises what no validation catches."""++ @override+ def __len__(self) -> int:+ return 2++ @overload+ def __getitem__(self, index: int) -> str: ...++ @overload+ def __getitem__(self, index: slice) -> Sequence[str]: ...++ @override+ def __getitem__(self, index: int | slice) -> str | Sequence[str]:+ msg = "this sequence cannot be read"+ raise KeyError(msg)+++def _cyclic_list() -> list[Any]:+ cyclic: list[Any] = []+ cyclic.append(cyclic)+ return cyclic+++class _NodeHolder(BaseModel):+ error: PipelexProblem | None = None+++class _RefusedAsAWholeParams(BaseModel):+ """A parameters model whose refusal names no parameter, as a model-level validator's does."""++ pipe: str | None = None+ template: str | None = None+ finding: str | None = None++ @model_validator(mode="after")+ def _refuse_the_set(self) -> Self:+ msg = "the parameters are refused together"+ raise ValueError(msg)+++class _LaxBlobsParams(BaseModel):+ """A parameters model laxer than the problem's own, which types each missing blob as a SHA-256."""++ missing_blobs: list[str] | None = None+++def _all_codes() -> list[ErrorCode]:+ return [*CoreCode, *PipelexErrorCode]+++def _nulls_in(value: Any, *, path: str = "") -> list[str]:+ """The paths of every member of ``value``, at any depth, written as ``None``."""+ if value is None:+ return [path or "<root>"]+ if isinstance(value, dict):+ found: list[str] = []+ for key, item in cast("dict[str, Any]", value).items():+ found.extend(_nulls_in(item, path=f"{path}.{key}"))+ return found+ if isinstance(value, list):+ found = []+ for index_item, item in enumerate(cast("list[Any]", value)):+ found.extend(_nulls_in(item, path=f"{path}[{index_item}]"))+ return found+ return []+++class TestProblemViews:+ def test_the_caller_view_has_no_diagnostics_and_the_operator_view_has_them(self) -> None:+ error = _MisconfiguredError(ProblemViewsTestData.OPERATOR_MESSAGE).with_params(component=ProblemViewsTestData.COMPONENT)++ operator = error.to_problem(view=ProblemView.OPERATOR)+ caller = error.to_problem(view=ProblemView.CALLER)++ assert operator.diagnostics is not None+ assert operator.diagnostics.error_class == "_MisconfiguredError"+ assert operator.diagnostics.message == ProblemViewsTestData.OPERATOR_MESSAGE+ assert caller.diagnostics is None+ assert "diagnostics" not in caller.to_wire()+ assert ProblemViewsTestData.OPERATOR_MESSAGE not in str(caller.to_wire())+ # The same code, domain, verdict and sentence in both views.+ assert (caller.code, caller.domain, caller.retry, caller.detail) == (operator.code, operator.domain, operator.retry, operator.detail)+ assert caller.detail == error_code_spec(CoreCode.RUNTIME_MISCONFIGURED).detail++ def test_an_operator_code_aims_its_step_at_the_reader(self) -> None:+ """The operator reads the actor's step; the caller, who cannot fix the deployment, reads the other one."""+ error = _MisconfiguredError(ProblemViewsTestData.OPERATOR_MESSAGE).with_params(component=ProblemViewsTestData.COMPONENT)++ operator = error.to_problem(view=ProblemView.OPERATOR)+ caller = error.to_problem(view=ProblemView.CALLER)++ assert operator.next_step.kind == StepKind.FIX_CONFIGURATION+ assert operator.next_step.detail == f"Set or correct the configuration of '{ProblemViewsTestData.COMPONENT}', then restart the runtime."+ assert caller.next_step.kind == StepKind.REPORT+ assert caller.next_step.detail == "Report this to whoever runs the runtime."++ def test_an_operator_only_parameter_rides_the_operator_diagnostics_alone(self) -> None:+ error = _MisconfiguredError(ProblemViewsTestData.OPERATOR_MESSAGE).with_params(component=ProblemViewsTestData.COMPONENT)++ operator = error.to_problem(view=ProblemView.OPERATOR)+ caller = error.to_problem(view=ProblemView.CALLER)++ assert operator.params is None+ assert operator.diagnostics is not None+ assert operator.diagnostics.params == {"component": ProblemViewsTestData.COMPONENT}+ assert caller.params is None+ assert ProblemViewsTestData.COMPONENT not in str(caller.to_wire())++ def test_the_caller_view_of_the_operator_view_is_the_caller_view(self) -> None:+ for error in (+ _MisconfiguredError(ProblemViewsTestData.OPERATOR_MESSAGE).with_params(component=ProblemViewsTestData.COMPONENT),+ _TemplateRefusalError("the template does not parse").with_params(pipe="summarize", template="prompt", finding="unexpected '}'"),+ ):+ projected = caller_view_of(problem=error.to_problem(view=ProblemView.OPERATOR))+ assert projected.to_wire() == error.to_problem(view=ProblemView.CALLER).to_wire()++ def test_the_detail_is_rendered_from_the_code_and_its_parameters(self) -> None:+ error = _TemplateRefusalError("the raise site's own words").with_params(pipe="summarize", template="prompt", finding="unexpected '}'")++ caller = error.to_problem(view=ProblemView.CALLER)++ assert caller.detail == "The template 'prompt' of pipe 'summarize' is invalid (unexpected '}')."+ assert caller.params is not None+ assert caller.params.as_wire() == {"pipe": "summarize", "template": "prompt", "finding": "unexpected '}'"}+ assert "the raise site's own words" not in str(caller.to_wire())++ def test_a_template_missing_a_parameter_falls_back_on_the_title(self, caplog: pytest.LogCaptureFixture) -> None:+ """Rendering is total: a missing parameter costs the sentence, never the problem, and the raise site is logged."""+ error = _TemplateRefusalError("no parameters given")++ with caplog.at_level(logging.WARNING, logger="pipelex.errors.problem"):+ caller = error.to_problem(view=ProblemView.CALLER)++ spec = error_code_spec(CoreCode.METHOD_TEMPLATE_INVALID)+ assert caller.detail == spec.title+ assert caller.next_step.kind == spec.actor_step+ assert caller.next_step.detail+ assert any(record.getMessage() == "A problem's sentence could not be rendered from its template" for record in caplog.records)++ def test_an_undeclared_or_mistyped_parameter_is_dropped(self, caplog: pytest.LogCaptureFixture) -> None:+ error = _TemplateRefusalError("refused").with_params(pipe="summarize", template="prompt", finding="bad", undeclared="secret value")++ with caplog.at_level(logging.WARNING, logger="pipelex.errors.problem"):+ caller = error.to_problem(view=ProblemView.CALLER)++ assert caller.params is not None+ assert "undeclared" not in caller.params.as_wire()+ assert "secret value" not in str(caller.to_wire())+ assert any(record.getMessage() == "An error gives a parameter its code does not declare" for record in caplog.records)++ @pytest.mark.parametrize("view", list(ProblemView))+ def test_no_problem_holds_a_null_member(self, view: ProblemView) -> None:+ """Every code, in every view, with no parameter given: no member at any depth is written as null."""+ for code in _all_codes():+ problem = make_problem(code=code, view=view)+ assert _nulls_in(problem.to_wire()) == [], code+ assert _nulls_in(problem.model_dump(mode="json")) == [], code+ nested = _NodeHolder(error=problem).model_dump(mode="json")+ assert _nulls_in(nested["error"]) == [], code++ @pytest.mark.parametrize("view", list(ProblemView))+ def test_a_problem_built_from_a_rich_error_holds_no_null_member(self, view: ProblemView) -> None:+ error = LLMCompletionError(+ ProblemViewsTestData.OPERATOR_MESSAGE,+ error_category=InferenceErrorCategory.CONFIGURATION,+ provider_metadata=ProviderErrorMetadata(+ provider=ProviderName.OPENAI, sdk_exception_type="AuthenticationError", status_code=401, message="invalid key"+ ),+ )+ error.model_handle = "gpt-4o-mini"++ problem = error.to_problem(view=view, request_id="req-1", pipeline_run_id="run-1")++ assert _nulls_in(problem.to_wire()) == []++ def test_a_message_is_bounded(self) -> None:+ """An oversized exception message is capped, its head kept, in the operator's diagnostics."""+ oversized = "Validation failed: " + "x" * (MAX_PROBLEM_TEXT_LENGTH * 50)+ error = LLMCompletionError(oversized, error_category=InferenceErrorCategory.UNKNOWN)++ operator = error.to_problem(view=ProblemView.OPERATOR)++ assert operator.diagnostics is not None+ message = operator.diagnostics.message+ assert len(message) <= MAX_PROBLEM_TEXT_LENGTH+ assert message.startswith("Validation failed: ")+ assert message.endswith(TRUNCATION_MARKER)++ def test_a_provider_message_and_a_text_parameter_are_bounded(self) -> None:+ oversized = "y" * (MAX_PROBLEM_TEXT_LENGTH * 3)+ provider_error = LLMCompletionError(+ "provider refused",+ error_category=InferenceErrorCategory.CONFIGURATION,+ provider_metadata=ProviderErrorMetadata(+ provider=ProviderName.OPENAI, sdk_exception_type="BadRequestError", status_code=400, message=oversized+ ),+ )+ template_error = _TemplateRefusalError("refused").with_params(pipe="summarize", template="prompt", finding=oversized)++ operator = provider_error.to_problem(view=ProblemView.OPERATOR)+ caller = template_error.to_problem(view=ProblemView.CALLER)++ assert operator.diagnostics is not None+ assert operator.diagnostics.provider is not None+ assert operator.diagnostics.provider.message is not None+ assert len(operator.diagnostics.provider.message) <= MAX_PROBLEM_TEXT_LENGTH+ assert caller.params is not None+ assert len(caller.params.as_wire()["finding"]) <= MAX_PROBLEM_TEXT_LENGTH++ def test_an_inference_failure_keeps_a_next_step_in_the_caller_view(self) -> None:+ """No view drops the step: a classified inference failure tells its caller what to do."""+ error = LLMCompletionError(+ "provider said: invalid key sk-...",+ error_category=InferenceErrorCategory.CONFIGURATION,+ user_action=UserAction(kind=UserActionKind.CHECK_CREDENTIALS, detail="Verify the API key."),+ )++ caller = error.to_problem(view=ProblemView.CALLER)++ # A configuration failure is the operator's to fix, so its caller is told to report it.+ assert caller.code == CoreCode.RUNTIME_MISCONFIGURED+ assert caller.next_step.kind == StepKind.REPORT+ assert caller.next_step.detail == "Report this to whoever runs the runtime."+ assert "sk-" not in str(caller.to_wire())++ def test_no_step_points_at_text_a_caller_cannot_see(self) -> None:+ """Every step of every code stands alone: none sends its reader to an error message the view may not show."""+ for code in _all_codes():+ for view in ProblemView:+ step_detail = make_problem(code=code, view=view).next_step.detail.lower()+ for phrase in ProblemViewsTestData.HIDDEN_TEXT_PHRASES:+ assert phrase not in step_detail, (code, view, step_detail)++ def test_a_gateway_refusal_reads_without_the_provider_text(self) -> None:+ """The provider's specifics stay the operator's, and the caller's step and detail still read in full."""+ error = LLMCompletionError(+ ProblemViewsTestData.GATEWAY_MESSAGE,+ error_category=InferenceErrorCategory.CONFIGURATION,+ provider_metadata=ProviderErrorMetadata(+ provider=ProviderName.GATEWAY,+ sdk_exception_type="BadRequestError",+ status_code=400,+ message=ProblemViewsTestData.GATEWAY_PROVIDER_TEXT,+ ),+ )+ error.model_handle = "acme/large"++ caller = error.to_problem(view=ProblemView.CALLER)+ operator = error.to_problem(view=ProblemView.OPERATOR)++ assert ProblemViewsTestData.GATEWAY_PROVIDER_TEXT not in str(caller.to_wire())+ assert caller.detail+ assert caller.next_step.detail+ assert operator.diagnostics is not None+ assert operator.diagnostics.provider is not None+ assert operator.diagnostics.provider.message == ProblemViewsTestData.GATEWAY_PROVIDER_TEXT++ def test_an_unusable_retry_delay_is_left_out(self) -> None:+ for delay in (float("inf"), float("nan"), -1.0):+ problem = make_problem(code=CoreCode.PROVIDER_RATE_LIMITED, view=ProblemView.CALLER, retry_after=delay)+ assert problem.retry_after is None+ assert make_problem(code=CoreCode.PROVIDER_RATE_LIMITED, view=ProblemView.CALLER, retry_after=3.5).retry_after == 3.5+ # A code whose verdict is not `yes` never carries a delay.+ assert make_problem(code=CoreCode.RUNTIME_UNEXPECTED, view=ProblemView.CALLER, retry_after=3.5).retry_after is None++ def test_a_parameter_set_refused_as_a_whole_is_dropped(self, mocker: MockerFixture, caplog: pytest.LogCaptureFixture) -> None:+ """A refusal naming no parameter, a model-level one, drops them all: the error is reported, never replaced."""+ spec = error_code_spec(CoreCode.METHOD_TEMPLATE_INVALID).model_copy(+ update={"params_model": _RefusedAsAWholeParams, "param_names": frozenset({"pipe", "template", "finding"})}+ )+ mocker.patch("pipelex.errors.problem.error_code_spec", return_value=spec)++ with caplog.at_level(logging.WARNING, logger="pipelex.errors.problem"):+ problem = make_problem(code=CoreCode.METHOD_TEMPLATE_INVALID, view=ProblemView.CALLER, params={"pipe": "summarize", "template": "x"})++ assert problem.code == CoreCode.METHOD_TEMPLATE_INVALID+ assert problem.params is None+ assert problem.detail == spec.title+ assert any(record.getMessage() == "An error gives parameters its code refuses as a whole" for record in caplog.records)++ def test_a_parameter_the_wire_refuses_is_dropped(self, mocker: MockerFixture) -> None:+ """A value the code's model takes but the problem's own `params` model refuses never fails the problem."""+ spec = error_code_spec(CoreCode.REQUEST_BLOBS_MISSING).model_copy(update={"params_model": _LaxBlobsParams})+ mocker.patch("pipelex.errors.problem.error_code_spec", return_value=spec)++ problem = make_problem(code=CoreCode.REQUEST_BLOBS_MISSING, view=ProblemView.CALLER, params={"missing_blobs": ["not-a-sha256"]})++ assert problem.code == CoreCode.REQUEST_BLOBS_MISSING+ assert problem.params is None++ @pytest.mark.parametrize(+ ("wire", "expected_kind", "expected_detail"),+ [+ (ProblemViewsTestData.UNKNOWN_OPERATOR_PROBLEM, StepKind.REPORT, "Report this problem with its request id."),+ (+ ProblemViewsTestData.UNKNOWN_METHOD_PROBLEM,+ StepKind.CHANGE_METHOD,+ "Correct the method as the problem describes, then validate it again.",+ ),+ ],+ )+ def test_the_caller_view_of_an_unknown_code_fails_closed(self, wire: dict[str, Any], expected_kind: StepKind, expected_detail: str) -> None:+ """A code this process does not know keeps no operator sentence: its caller reads a generic step, nested ones included."""+ operator = PipelexProblem.model_validate(wire)+ outer = make_problem(+ code=CoreCode.RUN_FAILED, view=ProblemView.OPERATOR, params={"pipeline_run_id": "run-1", "run_status": "failed"}+ ).model_copy(update={"run_error": operator})++ for caller in (caller_view_of(problem=operator), caller_view_of(problem=outer).run_error):+ assert caller is not None+ assert caller.code == wire["code"]+ assert caller.next_step.kind == expected_kind+ assert caller.next_step.detail == expected_detail+ assert ProblemViewsTestData.PRIVATE_HOST_FILE not in str(caller.to_wire())+ assert caller.diagnostics is None++ def test_the_metadata_view_holds_no_sentence(self) -> None:+ error = _TemplateRefusalError("refused").with_params(pipe="summarize", template="prompt", finding="unexpected '}'")+ problem = error.to_problem(view=ProblemView.OPERATOR, request_id="req-1", pipeline_run_id="run-1")++ metadata = problem_metadata(problem=problem).to_wire()++ assert metadata["code"] == "method.template_invalid"+ assert metadata["request_id"] == "req-1"+ assert metadata["pipeline_run_id"] == "run-1"+ assert "summarize" not in str(metadata)+ assert problem.detail not in str(metadata)+ assert problem.next_step.detail not in str(metadata)++ def test_a_problem_nested_to_the_readers_limit_is_written_back(self) -> None:+ """A problem a reader accepts, an extension member nested to the body's limit included, is written by every write path."""+ nested: Any = "leaf"+ for _ in range(MAX_BODY_NESTING - 2):+ nested = {"inner": nested}+ operator_wire = make_problem(code=CoreCode.RUNTIME_UNEXPECTED, view=ProblemView.OPERATOR).to_wire()+ body = json.dumps({**operator_wire, "run_error": {**operator_wire, "extension": nested}})+ assert not nests_deeper_than(body, limit=MAX_BODY_NESTING)+ assert nests_deeper_than(body, limit=MAX_BODY_NESTING - 1)++ problem = PipelexProblem.model_validate(decode_json(body).value)++ assert json.loads(json.dumps(problem.to_wire())) == json.loads(body)+ assert problem.as_wire() == problem.to_wire()+ caller = caller_view_of(problem=problem)+ assert caller.run_error is not None+ assert caller.run_error.to_wire()["extension"] == nested+ assert "diagnostics" not in caller.to_wire()++ @pytest.mark.parametrize("view", list(ProblemView))+ def test_an_item_never_carries_an_operator_only_parameter(self, view: ProblemView) -> None:+ """An item built by hand is the same in every view: its operator-only parameter and the sentence quoting it are gone."""+ hand_built = ProblemItem.model_validate(ProblemViewsTestData.HAND_BUILT_OPERATOR_ITEM)+ expected_detail = error_code_spec(CoreCode.RUNTIME_MISCONFIGURED).detail++ built = make_problem(code=CoreCode.METHOD_INVALID, view=view, errors=[hand_built])+ # A stored record whose items no `make_problem` built, which its reader projects to the caller's view.+ stored = make_problem(code=CoreCode.METHOD_INVALID, view=ProblemView.OPERATOR).model_copy(update={"errors": [hand_built]})++ for problem in (built, caller_view_of(problem=stored)):+ assert problem.errors is not None+ assert problem.errors[0].as_wire() == {"code": "runtime.misconfigured", "detail": expected_detail, "location": {"pipe": "summarize"}}+ assert ProblemViewsTestData.PRIVATE_HOST_FILE not in str(problem.to_wire())++ def test_a_null_an_extension_member_holds_is_written_as_read(self) -> None:+ """Only a member a model declares is left out when null: an extension member's null survives every write and the caller view."""+ operator_wire = make_problem(code=CoreCode.RUNTIME_UNEXPECTED, view=ProblemView.OPERATOR).to_wire()+ item_wire = {**ProblemViewsTestData.HAND_BUILT_OPERATOR_ITEM, **ProblemViewsTestData.NULL_HOLDING_ITEM_EXTENSIONS}+ body = {+ **operator_wire,+ **ProblemViewsTestData.NULL_HOLDING_EXTENSIONS,+ "errors": [item_wire],+ "run_error": {**operator_wire, **ProblemViewsTestData.NULL_HOLDING_EXTENSIONS},+ }+ problem = PipelexProblem.model_validate(body)++ caller = caller_view_of(problem=problem)+ writes = {+ "to_wire": problem.to_wire(),+ "model_dump": problem.model_dump(mode="json"),+ "nested": _NodeHolder(error=problem).model_dump(mode="json")["error"],+ "caller": caller.to_wire(),+ "caller_dump": caller.model_dump(mode="json"),+ "round_trip": PipelexProblem.model_validate(json.loads(json.dumps(problem.to_wire()))).to_wire(),+ }+ for write_name, wire in writes.items():+ for name, value in ProblemViewsTestData.NULL_HOLDING_EXTENSIONS.items():+ assert wire[name] == value, write_name+ assert wire["run_error"][name] == value, write_name+ assert wire["errors"][0]["vendor"] == {"hint": None}, write_name+ # A declared member with no value is still left out, the item's and the nested problem's included.+ assert "suggestions" not in wire["errors"][0], write_name+ assert "request_id" not in wire, write_name+ assert "params" not in wire["run_error"], write_name++ @pytest.mark.parametrize("view", list(ProblemView))+ def test_an_item_whose_code_is_unknown_fails_closed_for_the_caller(self, view: ProblemView) -> None:+ """The caller reads no parameter of an item whose code this process does not know, and a sentence quoting none."""+ unknown_item = ProblemItem.model_validate(ProblemViewsTestData.UNKNOWN_CODE_ITEM)+ built = make_problem(code=CoreCode.METHOD_INVALID, view=view, errors=[unknown_item])+ stored = make_problem(code=CoreCode.METHOD_INVALID, view=ProblemView.OPERATOR).model_copy(update={"errors": [unknown_item]})++ match view:+ case ProblemView.CALLER:+ for problem in (built, caller_view_of(problem=stored)):+ assert problem.errors is not None+ assert problem.errors[0].as_wire() == {+ "code": "method.future_fault",+ "detail": UNKNOWN_CODE_ITEM_DETAIL,+ "location": {"pipe": "summarize"},+ }+ assert ProblemViewsTestData.PRIVATE_HOST_FILE not in str(problem.to_wire())+ case ProblemView.OPERATOR:+ assert built.errors is not None+ assert built.errors[0].as_wire() == ProblemViewsTestData.UNKNOWN_CODE_ITEM++ @pytest.mark.parametrize(+ "unreadable",+ [+ pytest.param(_cyclic_list(), id="cyclic_list"),+ pytest.param(_UnreadableSequence(), id="sequence_whose_items_raise"),+ pytest.param([["summarize.a"], ["summarize.b"]], id="list_of_lists"),+ ],+ )+ def test_a_value_that_is_no_parameter_value_is_dropped_without_replacing_the_error(+ self, unreadable: object, caplog: pytest.LogCaptureFixture+ ) -> None:+ """A malformed raise-site value is a parameter of the wrong type: it is dropped and logged, and the error keeps its code."""+ error = _AmbiguousPipeError("ambiguous").with_params(pipe="summarize", candidates=unreadable)++ with caplog.at_level(logging.WARNING, logger="pipelex.errors.problem"):+ problem = error.to_problem(view=ProblemView.CALLER)++ assert problem.code == CoreCode.REQUEST_PIPE_AMBIGUOUS+ assert problem.params is not None+ assert problem.params.as_wire() == {"pipe": "summarize"}+ assert any(record.getMessage() == "An error gives a parameter of the wrong type for its code" for record in caplog.records)++ @pytest.mark.parametrize(+ ("code", "params"),+ [+ (PipelexErrorCode.DOCGEN_PRINT_TIMEOUT, {"limit": float("inf")}),+ (PipelexErrorCode.DOCGEN_PRINT_TIMEOUT, {"limit": float("nan")}),+ (CoreCode.RUN_TIMED_OUT, {"timeout": float("inf")}),+ ],+ )+ def test_a_number_json_cannot_write_is_dropped(self, code: ErrorCode, params: dict[str, Any], caplog: pytest.LogCaptureFixture) -> None:+ """An infinity or NaN never renders into a sentence it would then vanish from: it is a parameter of the wrong type."""+ with caplog.at_level(logging.WARNING, logger="pipelex.errors.problem"):+ problem = make_problem(code=code, view=ProblemView.CALLER, params=params)++ assert problem.params is None+ assert problem.detail == error_code_spec(code).title+ assert "inf" not in problem.detail+ json.dumps(problem.to_wire(), allow_nan=False)+ assert any(record.getMessage() == "An error gives a parameter of the wrong type for its code" for record in caplog.records)diff --git a/tests/unit/pipelex/exceptions/test_as_caller_fault.py b/tests/unit/pipelex/exceptions/test_as_caller_fault.pydeleted file mode 100644index b7e92c9f4..000000000--- a/tests/unit/pipelex/exceptions/test_as_caller_fault.py+++ /dev/null@@ -1,84 +0,0 @@-from mthds.protocol.problem.registry import CoreCode--from pipelex.base_exceptions import INTERNAL_ERROR_PLACEHOLDER, DisclosureMode, ErrorDomain, PipelexError-from pipelex.cogt.exceptions import InferenceErrorCategory, ModelNotFoundError-from pipelex.cogt.inference.error_classification import UserAction, UserActionKind-from pipelex.core.stuffs.exceptions import StuffFactoryError-from pipelex.pipe_run.exceptions import PipeRouterError-from pipelex.system.pipe_run_mode import PipeRunMode---class 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").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.code == CoreCode.PIPE_OUTPUT_INVALID- assert caller_report.caller_facing_message is True- assert caller_report.http_status == 422-- other_report = other.to_error_report()- assert other_report.code == CoreCode.INPUT_INVALID- assert other_report.caller_facing_message is False-- def 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."""- user_action = UserAction(kind=UserActionKind.CHANGE_INPUT, detail="Provide the input 'topic'.")- error = StuffFactoryError("Input 'topic' is missing").as_caller_fault(user_action=user_action)-- payload = error.to_error_report().to_dict(disclosure_mode=DisclosureMode.STRICT)- assert payload["message"] == "Input 'topic' is missing"- assert payload["user_action"] == {"kind": "change_input", "detail": "Provide the input 'topic'."}-- 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.CONFIGURATION- assert report.error_category == "configuration"- assert report.code == CoreCode.MODEL_UNKNOWN- assert report.error_domain == ErrorDomain.INPUT- assert 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()- wrapper = PipelexError("An internal sentence about the cause")- wrapper.__cause__ = cause-- report = wrapper.to_error_report()- assert report.error_domain == ErrorDomain.INPUT- assert report.caller_facing_message is False- assert report.to_dict(disclosure_mode=DisclosureMode.STRICT)["message"] == INTERNAL_ERROR_PLACEHOLDER-- def test_a_located_wrapper_reports_the_caller_fault_it_locates(self) -> None:- """The pipe router's location takes the root fault's flag, so the located message survives STRICT."""- cause = StuffFactoryError("Error combining stuffs for concept Report").as_caller_fault()- located = PipeRouterError.make_located(- failure=cause,- run_mode=PipeRunMode.LIVE,- pipe_code="analyze",- output_name=None,- pipe_stack=["flow", "analyze"],- )- located.__cause__ = cause-- payload = located.to_error_report().to_problem_document(disclosure_mode=DisclosureMode.STRICT)- assert payload["status"] == 422- assert payload["detail"] == "Pipe 'analyze' failed (flow → analyze): Error combining stuffs for concept Report"diff --git a/tests/unit/pipelex/exceptions/test_class_level_metadata.py b/tests/unit/pipelex/exceptions/test_class_level_metadata.pyindex 99136e823..0a6cc814d 100644--- a/tests/unit/pipelex/exceptions/test_class_level_metadata.py+++ b/tests/unit/pipelex/exceptions/test_class_level_metadata.py@@ -1,7 +1,7 @@import pytest-from mthds.protocol.problem.registry import CoreCode+from mthds.protocol.problem.registry import CoreCode, ProblemDomain-from pipelex.base_exceptions import ErrorDomain, PipelexConfigError, PipelexError, PipelexSetupError+from pipelex.base_exceptions import PipelexConfigError, PipelexError, PipelexSetupErrorfrom pipelex.cogt.exceptions import (CogtError,ImgGenParameterError,@@ -13,9 +13,11 @@ from pipelex.cogt.exceptions import (PromptImageFactoryError,PromptImageFormatError,SdkTypeError,+ find_inference_error_category_in_chain,)from pipelex.core.stuffs.exceptions import DateContentErrorfrom pipelex.errors.error_codes import ErrorCode+from pipelex.errors.problem import ProblemViewfrom pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.libraries.pipe.exceptions import EntryPipeAmbiguousError, EntryPipeNotFoundError, PipeLibraryError, PipeNotFoundErrorfrom pipelex.mthds_parsing.exceptions import MthdsParserError@@ -31,6 +33,9 @@ from pipelex.system.exceptions import EnvVarNotFoundErrorfrom pipelex.system.pipe_run_mode import PipeRunModefrom pipelex.tools.tabular.exceptions import CsvError+# A message naming a path on the host, which no caller may read whatever the class.+_HOST_MESSAGE = "boom at /srv/pipelex/internal/library.mthds"+_PIPELINE_EXEC_ERROR = PipelineExecutionError(message="boom",run_mode=PipeRunMode.LIVE,@@ -41,36 +46,35 @@ _PIPELINE_EXEC_ERROR = PipelineExecutionError(class TestClassLevelMetadata:- """Key exceptions self-describe their code, user_action and error_category at the class level."""+ """Key exceptions self-describe their code, their advice and their error_category at the class level."""@pytest.mark.parametrize(("_topic", "exc", "expected_code", "expected_domain"),[# 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),+ ("pipeline_execution", _PIPELINE_EXEC_ERROR, CoreCode.RUNTIME_UNEXPECTED, ProblemDomain.RUNTIME),+ ("pipe_execution", PipeExecutionError("boom"), CoreCode.RUNTIME_UNEXPECTED, ProblemDomain.RUNTIME),+ ("validate_bundle", ValidateBundleError("boom"), CoreCode.METHOD_INVALID, ProblemDomain.METHOD),+ ("pipeline_input_content", PipelineInputContentError("boom"), PipelexErrorCode.STORAGE_URI_INVALID, ProblemDomain.INPUT),# The entry-shaped lookups report a pipe_code the caller supplied, so a typo is theirs# 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),+ ("entry_pipe_not_found", EntryPipeNotFoundError("boom"), CoreCode.REQUEST_PIPE_NOT_FOUND, ProblemDomain.INPUT),+ ("entry_pipe_ambiguous", EntryPipeAmbiguousError("boom"), CoreCode.REQUEST_PIPE_AMBIGUOUS, ProblemDomain.INPUT),+ ("interpreter", MthdsParserError("boom"), CoreCode.METHOD_INVALID, ProblemDomain.METHOD),+ ("setup", PipelexSetupError("boom"), CoreCode.RUNTIME_MISCONFIGURED, ProblemDomain.OPERATOR),+ ("config", PipelexConfigError("boom"), PipelexErrorCode.CONFIG_INVALID, ProblemDomain.OPERATOR),+ ("env_var_not_found", EnvVarNotFoundError("boom"), PipelexErrorCode.CONFIG_VARIABLE_MISSING, ProblemDomain.OPERATOR),],)- 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_code- assert report.error_domain == expected_domain+ def test_error_code(self, _topic: str, exc: PipelexError, expected_code: ErrorCode, expected_domain: ProblemDomain) -> None:+ """The targeted exceptions' problem carries their class's code, and the domain it decides."""+ problem = exc.to_problem(view=ProblemView.CALLER)+ assert problem.code == expected_code+ assert problem.domain == expected_domain@pytest.mark.parametrize(("_topic", "exc", "expected_detail"),[- ("pipeline_execution", _PIPELINE_EXEC_ERROR, "The run of 'some_pipe' failed: the message gives the cause."),("validate_bundle",ValidateBundleError("boom"),@@ -88,11 +92,17 @@ class TestClassLevelMetadata:),],)- def test_user_action(self, _topic: str, exc: PipelexError, expected_detail: str) -> None:- """The targeted exceptions carry their expected user_action detail in to_error_report()."""- report = exc.to_error_report()- assert report.user_action is not None- assert report.user_action.detail == expected_detail+ def test_advised_action(self, _topic: str, exc: PipelexError, expected_detail: str) -> None:+ """The targeted exceptions carry their advice, the local CLI's tip, which no problem carries."""+ advice = exc.advised_action()+ assert advice is not None+ assert advice.detail == expected_detail+ assert expected_detail not in str(exc.to_problem(view=ProblemView.OPERATOR).to_wire())++ def test_a_run_wrapper_with_no_cause_advises_nothing(self) -> None:+ """No fallback advice is invented: the problem's next step, from the code, is what the reader follows."""+ assert _PIPELINE_EXEC_ERROR.advised_action() is None+ assert _PIPELINE_EXEC_ERROR.to_problem(view=ProblemView.CALLER).next_step.detail == "Report this to whoever runs the runtime."@pytest.mark.parametrize(("_topic", "exc", "expected_category"),@@ -108,74 +118,51 @@ class TestClassLevelMetadata:],)def test_error_category(self, _topic: str, exc: CogtError, expected_category: InferenceErrorCategory) -> None:- """The previously-uncategorized CogtError subclasses now report a class-level error_category."""- report = exc.to_error_report()+ """The previously-uncategorized CogtError subclasses carry a class-level error_category, which the chain walk finds."""assert exc.error_category is expected_category- assert report.error_category == expected_category+ assert find_inference_error_category_in_chain(exc) is expected_category@pytest.mark.parametrize(- ("_topic", "exc", "expected_caller_facing"),+ ("_topic", "exc"),[- ("interpreter", MthdsParserError("boom"), True),- ("validate_bundle", ValidateBundleError("boom"), True),- # Regression pin: this class declared the *report field* name (``caller_facing_message``)- # instead of the class-level flag (``_authors_caller_facing_message``), so its- # caller-facing message was silently redacted under STRICT disclosure.- ("pipeline_input_url_missing", PipelineInputUrlMissingError("boom"), True),- # Security pin, and the reason the family is split: this class's message names the- # resolved local path and the OSError subclass that rejected it. Flagging it- # caller-facing would let STRICT disclosure answer "does this server-side path exist,- # and may the runner read it?" for any authenticated caller.- ("pipeline_input_content", PipelineInputContentError("boom"), False),- # The entry-lookup messages name the caller's own pipe_code and the qualified pipe_refs- # of bundles they loaded themselves — nothing server-side — and the candidate list is- # the only thing that makes an ambiguity actionable, so redacting it would gut the error.- ("entry_pipe_not_found", EntryPipeNotFoundError("boom"), True),- ("entry_pipe_ambiguous", EntryPipeAmbiguousError("boom"), True),- # The in-body doors stay redacted: their refs come from a bundle, not from the caller.- ("pipe_not_found", PipeNotFoundError("boom"), False),- ("pipe_library", PipeLibraryError("boom"), False),- ("csv", CsvError("boom"), True),- ("unknown_storage_method", UnknownStorageMethodError(method="bogus", registered_methods=["local", "s3"]), True),- ("unknown_secrets_method", UnknownSecretsMethodError(method="bogus", registered_methods=["env"]), True),- ("date_content", DateContentError("boom"), True),- ("config", PipelexConfigError("boom"), False),- ("pipe_execution", PipeExecutionError("boom"), False),- ("cogt", CogtError("boom"), False),+ ("interpreter", MthdsParserError(_HOST_MESSAGE)),+ # A `ValidateBundleError` is left out: its items are the verdict about the caller's own bundle, which the caller+ # reads, a message with no categorized data riding as its residual item.+ ("pipeline_input_url_missing", PipelineInputUrlMissingError(_HOST_MESSAGE)),+ # Security pin: this class's message names the resolved local path and the OSError subclass that+ # rejected it, which would answer "does this server-side path exist, and may the runner read it?".+ ("pipeline_input_content", PipelineInputContentError(_HOST_MESSAGE)),+ ("entry_pipe_not_found", EntryPipeNotFoundError(_HOST_MESSAGE)),+ ("entry_pipe_ambiguous", EntryPipeAmbiguousError(_HOST_MESSAGE)),+ ("pipe_not_found", PipeNotFoundError(_HOST_MESSAGE)),+ ("pipe_library", PipeLibraryError(_HOST_MESSAGE)),+ ("csv", CsvError(_HOST_MESSAGE)),+ ("date_content", DateContentError(_HOST_MESSAGE)),+ ("config", PipelexConfigError(_HOST_MESSAGE)),+ ("pipe_execution", PipeExecutionError(_HOST_MESSAGE)),+ ("cogt", CogtError(_HOST_MESSAGE)),],)- def test_caller_facing_message(self, _topic: str, exc: PipelexError, expected_caller_facing: bool) -> None:- """Only classes whose message describes the caller's own input carry caller_facing_message in to_error_report().-- ``MthdsParserError`` / ``ValidateBundleError`` author caller-facing- copy (.mthds syntax, bundle validation); every other class defaults to- False so STRICT disclosure redacts its message.- """- report = exc.to_error_report()- assert report.caller_facing_message is expected_caller_facing+ def test_a_message_reaches_the_operator_alone(self, _topic: str, exc: PipelexError) -> None:+ """Whatever the class, its message rides the operator's diagnostics and never the caller's view.- def test_caller_facing_message_inherits_for_interpreter_subclass(self) -> None:- """A subclass of ``MthdsParserError`` stays caller-facing.-- 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 the error-code gate- uses for ``error_code``) would silently downgrade- STRICT disclosure for every subclass and let internal messages leak under- STRICT — or, more likely, silently redact authored caller-facing copy.+ The caller reads the sentences its code renders, so no class has to vouch that its message is safe to show."""+ caller = exc.to_problem(view=ProblemView.CALLER)+ operator = exc.to_problem(view=ProblemView.OPERATOR)+ assert _HOST_MESSAGE not in str(caller.to_wire())+ assert "/srv/pipelex" not in str(caller.to_wire())+ assert operator.diagnostics is not None+ assert operator.diagnostics.message == _HOST_MESSAGE- class _SubInterpreterError(MthdsParserError):- pass-- report = _SubInterpreterError("boom").to_error_report()- assert report.caller_facing_message is True-- def test_caller_facing_message_inherits_for_validate_bundle_subclass(self) -> None:- """A subclass of ``ValidateBundleError`` stays caller-facing — same contract as the interpreter case."""-- class _SubValidateBundleError(ValidateBundleError):- pass-- report = _SubValidateBundleError("boom").to_error_report()- assert report.caller_facing_message is True+ @pytest.mark.parametrize(+ ("_topic", "exc"),+ [+ ("unknown_storage_method", UnknownStorageMethodError(method="bogus", registered_methods=["local", "s3"])),+ ("unknown_secrets_method", UnknownSecretsMethodError(method="bogus", registered_methods=["env"])),+ ],+ )+ def test_a_plugin_choice_refusal_names_its_value_to_the_operator(self, _topic: str, exc: PipelexError) -> None:+ operator = exc.to_problem(view=ProblemView.OPERATOR)+ assert operator.diagnostics is not None+ assert "bogus" in operator.diagnostics.messagediff --git a/tests/unit/pipelex/exceptions/test_error_domain.py b/tests/unit/pipelex/exceptions/test_error_domain.pyindex 7b83765b5..12ef9a700 100644--- a/tests/unit/pipelex/exceptions/test_error_domain.py+++ b/tests/unit/pipelex/exceptions/test_error_domain.py@@ -4,8 +4,8 @@ import pytestfrom mthds.protocol.problem.registry import ProblemDomainfrom pipelex.base_exceptions import ErrorDomain, PipelexError, error_domain_is_input+from pipelex.errors.problem import ProblemViewfrom pipelex.errors.registry.pipelex_codes import PipelexErrorCode-from tests.helpers.error_report import make_error_reportclass _ConfigCodedError(PipelexError):@@ -28,17 +28,17 @@ class TestErrorDomain:assert ErrorDomain.RUNTIME == "runtime"assert set(ErrorDomain) == {ErrorDomain.INPUT, ErrorDomain.CONFIG, ErrorDomain.RUNTIME}- def test_to_error_report_reports_the_fallback_domain_without_a_code(self) -> None:+ def test_an_error_with_no_code_is_in_the_runtime_domain(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.code == "runtime.unexpected"- assert report.error_domain == ErrorDomain.RUNTIME+ problem = PipelexError("plain error").to_problem(view=ProblemView.CALLER)+ assert problem.code == "runtime.unexpected"+ assert ErrorDomain.from_problem_domain(problem.effective_domain) is ErrorDomain.RUNTIME- 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.CONFIG- assert report.error_domain == "config"+ def test_the_domain_is_read_from_the_code(self) -> None:+ """A PipelexError subclass reads its domain from its code's registry domain."""+ error = _ConfigCodedError("config broke")+ assert error.resolve_domain() == ProblemDomain.OPERATOR+ assert ErrorDomain.from_problem_domain(error.resolve_domain()) is ErrorDomain.CONFIG@pytest.mark.parametrize(("problem_domain", "expected_error_domain"),@@ -51,19 +51,9 @@ class TestErrorDomain:],)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."""+ """A code's registry domain projects onto the envelope'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()- assert "error_domain" not in report_dict-- def test_to_dict_includes_error_domain_when_set(self) -> None:- """ErrorReport.to_dict() includes error_domain when it is set."""- report_dict = make_error_report(error_type="X", message="m", error_domain=ErrorDomain.CONFIG).to_dict()- assert report_dict["error_domain"] == "config"-@pytest.mark.parametrize(("error_domain", "expected_is_input"),[@@ -90,5 +80,5 @@ class TestErrorDomain:],)def test_error_domain_is_input(self, error_domain: ErrorDomain | str | None, expected_is_input: bool) -> None:- """error_domain_is_input tolerates the serialized str/None shape ErrorReport.error_domain carries."""+ """error_domain_is_input tolerates the serialized str/None shape a CLI envelope's error_domain carries."""assert error_domain_is_input(error_domain) is expected_is_inputdiff --git a/tests/unit/pipelex/exceptions/test_wrapper_error_enrichment.py b/tests/unit/pipelex/exceptions/test_wrapper_error_enrichment.pyindex 27763cb3b..8822f2b84 100644--- a/tests/unit/pipelex/exceptions/test_wrapper_error_enrichment.py+++ b/tests/unit/pipelex/exceptions/test_wrapper_error_enrichment.py@@ -1,9 +1,10 @@-from mthds.protocol.problem.registry import CoreCode+from mthds.protocol.problem.registry import CoreCode, ProblemDomain, StepKind-from pipelex.base_exceptions import ErrorDomain-from pipelex.cogt.exceptions import InferenceErrorCategory, LLMCompletionError+from pipelex.cogt.exceptions import InferenceErrorCategory, LLMCompletionError, find_inference_error_category_in_chainfrom pipelex.cogt.inference.error_classification import UserAction, UserActionKindfrom pipelex.core.pipes.exceptions import PipeRunError+from pipelex.errors.error_codes import error_code_spec+from pipelex.errors.problem import ProblemViewfrom pipelex.pipe_run.exceptions import PipeRouterErrorfrom pipelex.pipeline.exceptions import PipelineExecutionErrorfrom pipelex.system.pipe_run_mode import PipeRunMode@@ -43,20 +44,22 @@ class TestWrapperErrorEnrichment:)pipe_router_error.__cause__ = pipe_run_error- report = _make_pipeline_execution_error(cause=pipe_router_error).to_error_report()+ error = _make_pipeline_execution_error(cause=pipe_router_error)+ problem = error.to_problem(view=ProblemView.CALLER)- assert report.user_action is not None- 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+ advice = error.advised_action()+ assert advice is not None+ assert advice.kind == UserActionKind.WAIT_AND_RETRY, "the cause's actionable advice must not be masked by the wrapper"+ assert advice.detail == "Wait a moment and retry"+ assert find_inference_error_category_in_chain(error) == InferenceErrorCategory.TRANSIENT# A category with no code of its own reports the category's code, which invites a retry.- assert report.code == CoreCode.PROVIDER_UNAVAILABLE- assert report.retryable is True+ assert problem.code == CoreCode.PROVIDER_UNAVAILABLE+ assert problem.is_retryable is Truedef 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.+ """A content refusal coded `model.content_refused` reaches the wrapper as its code, the input's at 422, not a runtime fault.- The run's wrappers take their cause's code, so the report reads the refusal's own code and every fact it+ The run's wrappers take their cause's code, so the problem reads the refusal's own code and every fact itdecides, rather than the runtime fault a wrapper with a code of its own would report."""cogt_error = LLMCompletionError(message="the prompt was refused", error_category=InferenceErrorCategory.CONTENT).with_error_code(@@ -73,19 +76,20 @@ class TestWrapperErrorEnrichment:)pipe_router_error.__cause__ = pipe_run_error- report = _make_pipeline_execution_error(cause=pipe_router_error).to_error_report()+ error = _make_pipeline_execution_error(cause=pipe_router_error)+ problem = error.to_problem(view=ProblemView.CALLER)- 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 == 422- assert report.error_category == InferenceErrorCategory.CONTENT+ assert problem.code == CoreCode.MODEL_CONTENT_REFUSED+ assert problem.domain == ProblemDomain.INPUT, "the wrapper must not mask a caller-fixable cause"+ assert error_code_spec(CoreCode.MODEL_CONTENT_REFUSED).status == 422+ assert find_inference_error_category_in_chain(error) == InferenceErrorCategory.CONTENTdef test_falls_back_to_runtime_unknown_without_cause(self) -> None:- """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()+ """With no PipelexError cause, PipelineExecutionError reports its fallback code, located at the failing pipe."""+ problem = _make_pipeline_execution_error(cause=None).to_problem(view=ProblemView.CALLER)- assert report.code == CoreCode.RUNTIME_UNEXPECTED- assert report.error_domain == ErrorDomain.RUNTIME- assert report.user_action is not None- assert report.user_action.kind == UserActionKind.UNKNOWN- assert report.user_action.detail == "The run failed in pipe 'some_pipe': the message gives the cause."+ assert problem.code == CoreCode.RUNTIME_UNEXPECTED+ assert problem.domain == ProblemDomain.RUNTIME+ assert problem.next_step.kind == StepKind.REPORT+ assert problem.location is not None+ assert problem.location.as_wire() == {"pipe": "some_pipe", "path": ["some_pipe"]}diff --git a/tests/unit/pipelex/graph/test_graph_tracer.py b/tests/unit/pipelex/graph/test_graph_tracer.pyindex c3aa50d8b..114337bbd 100644--- a/tests/unit/pipelex/graph/test_graph_tracer.py+++ b/tests/unit/pipelex/graph/test_graph_tracer.py@@ -3,6 +3,9 @@import loggingfrom datetime import UTC, datetime, timedelta+from mthds.protocol.problem.registry import CoreCode++from pipelex.errors.problem import ProblemView, make_location, make_problemfrom pipelex.graph.graph_tracer import GraphTracerfrom pipelex.graph.graphspec import EdgeKind, GraphSpecMode, IOSpec, NodeKind, NodeStatusfrom pipelex.system.pipe_run_mode import PipeRunMode@@ -257,11 +260,15 @@ class TestGraphTracer:started_at=started_at,)+ problem = make_problem(+ code=CoreCode.RUNTIME_UNEXPECTED,+ view=ProblemView.CALLER,+ location=make_location(pipe="failing_pipe", path=["failing_pipe"]),+ )tracer.on_pipe_end_error(node_id=node_id,ended_at=started_at + timedelta(milliseconds=50),- error_type="ValueError",- error_message="Something went wrong",+ problem=problem,error_stack="Traceback...",)@@ -270,10 +277,8 @@ class TestGraphTracer:assert graph_spec is not Nonenode = graph_spec.nodes[0]assert node.status == NodeStatus.FAILED- assert node.error is not None- assert node.error.error_type == "ValueError"- assert node.error.message == "Something went wrong"- assert node.error.stack == "Traceback..."+ assert node.error == problem+ assert node.error_stack == "Traceback..."def test_skipped_tracking(self) -> None:"""A lifted (skipped) pipe ends its node in the SKIPPED state with the skip reason."""diff --git a/tests/unit/pipelex/graph/test_graph_tracer_event_emission.py b/tests/unit/pipelex/graph/test_graph_tracer_event_emission.pyindex 67df0b1c6..8c4b26f59 100644--- a/tests/unit/pipelex/graph/test_graph_tracer_event_emission.py+++ b/tests/unit/pipelex/graph/test_graph_tracer_event_emission.py@@ -6,8 +6,13 @@ correct trace events as a side effect alongside its existing in-memory accumulatfrom datetime import UTC, datetime, timedelta+from mthds.protocol.problem.registry import CoreCode++from pipelex.core.stuffs.exceptions import StuffFactoryError+from pipelex.errors.problem import ProblemView, make_location, make_problemfrom pipelex.graph.graph_tracer import GraphTracerfrom pipelex.graph.graphspec import EdgeKind, IOSpec, NodeKind, NodeStatus+from pipelex.graph.node_problem import make_node_problemfrom pipelex.system.execution_chain import ExecutionAttemptfrom pipelex.system.pipe_run_mode import PipeRunModefrom pipelex.tracing.in_memory_event_log import InMemoryEventLog@@ -190,11 +195,15 @@ class TestGraphTracerEventEmission:)ended_at = started_at + timedelta(milliseconds=50)+ problem = make_problem(+ code=CoreCode.RUNTIME_UNEXPECTED,+ view=ProblemView.CALLER,+ location=make_location(pipe="test_pipe", path=["test_pipe"]),+ )tracer.on_pipe_end_error(node_id=node_id,ended_at=ended_at,- error_type="ValueError",- error_message="Something went wrong",+ problem=problem,error_stack="traceback line 1\nline 2",)@@ -205,14 +214,13 @@ class TestGraphTracerEventEmission:evt = error_events[0]assert evt.node_id == node_idassert evt.ended_at == ended_at- assert evt.error.error_type == "ValueError"- assert evt.error.message == "Something went wrong"- assert evt.error.caller_facing is False+ assert evt.error == problem+ assert evt.error_stack == "traceback line 1\nline 2"# An end event names the pipe it ends, as its start does, and the invocation's path.assert (evt.pipe_code, evt.pipe_ref, evt.pipe_type, evt.path) == ("test_pipe", "tests.test_pipe", "PipeLLM", "tests.test_pipe")- def test_pipe_end_error_states_whether_its_message_was_written_for_the_caller(self) -> None:- """The failure's `caller_facing` reaches the event and the node of the graph."""+ def test_pipe_end_error_records_the_same_caller_view_on_the_event_and_the_node(self) -> None:+ """The node's problem reaches the event and the node of the graph alike, in the caller's view, without the error's message."""tracer, event_log = self._make_tracer_with_event_log()context = tracer.setup(graph_id=self.GRAPH_ID,@@ -232,21 +240,24 @@ class TestGraphTracerEventEmission:started_at=started_at,)- tracer.on_pipe_end_error(- node_id=node_id,- ended_at=started_at + timedelta(milliseconds=50),- error_type="StuffFactoryError",- error_message="PipeParallel 'test_pipe' cannot combine its branch results into its output 'Report'.",- caller_facing=True,+ error_message = "PipeParallel 'test_pipe' cannot combine its branch results into its output 'Report'."+ problem = make_node_problem(+ error=StuffFactoryError(error_message).with_error_code(CoreCode.PIPE_OUTPUT_INVALID),+ pipe_code="test_pipe",+ pipe_path=["test_pipe"],)+ tracer.on_pipe_end_error(node_id=node_id, ended_at=started_at + timedelta(milliseconds=50), problem=problem)graph_spec = tracer.teardown()error_events = [evt for evt in event_log.read_events(self.PIPELINE_RUN_ID) if isinstance(evt, PipeEndErrorEvent)]- assert [evt.error.caller_facing for evt in error_events] == [True]+ assert [evt.error for evt in error_events] == [problem]assert graph_spec is not Nonefailed_node = next(node for node in graph_spec.nodes if node.node_id == node_id)assert failed_node.error is not None- assert failed_node.error.caller_facing is True+ assert failed_node.error == problem+ assert failed_node.error.code == CoreCode.PIPE_OUTPUT_INVALID+ assert failed_node.error.diagnostics is None+ assert error_message not in str(failed_node.error.to_wire())assert failed_node.path == "tests.test_pipe"def test_add_edge_emits_event(self) -> None:diff --git a/tests/unit/pipelex/graph/test_graphspec_roundtrip.py b/tests/unit/pipelex/graph/test_graphspec_roundtrip.pyindex 44ac2ecf9..dffca98bd 100644--- a/tests/unit/pipelex/graph/test_graphspec_roundtrip.py+++ b/tests/unit/pipelex/graph/test_graphspec_roundtrip.py@@ -1,15 +1,17 @@"""Unit tests for GraphSpec JSON round-trip serialization."""+import jsonfrom datetime import UTC, datetimefrom pathlib import Pathimport pytest+from mthds.protocol.problem.registry import CoreCodefrom pydantic import ValidationError+from pipelex.errors.problem import ProblemView, make_location, make_problemfrom pipelex.graph.graphspec import (EdgeKind,EdgeSpec,- ErrorSpec,GraphSpec,GraphSpecMode,GraphUsageSpec,@@ -171,12 +173,13 @@ class TestGraphSpecRoundtrip:# Verify metaassert restored.meta == {"mode": GraphSpecMode.LIVE, "extra": "value", "format": "mthds"}- def test_roundtrip_with_error_spec(self) -> None:- """Test round-trip for a graph with a failed node containing error info."""- error = ErrorSpec(- error_type="PipeRunError",- message="LLM generation failed",- stack="Traceback (most recent call last):\n File ...\nPipeRunError: LLM generation failed",+ def test_roundtrip_with_error_problem(self) -> None:+ """Test round-trip for a graph with a failed node carrying its problem and its stack."""+ error = make_problem(+ code=CoreCode.INPUT_MISSING,+ view=ProblemView.CALLER,+ params={"input": "topic"},+ location=make_location(pipe="failed_pipe", path=["flow", "failed_pipe"]),)node = NodeSpec(@@ -186,6 +189,7 @@ class TestGraphSpecRoundtrip:pipe_type="PipeLLM",status=NodeStatus.FAILED,error=error,+ error_stack="Traceback (most recent call last):\n File ...\nPipeRunError: LLM generation failed",)graph = GraphSpec(@@ -201,9 +205,11 @@ class TestGraphSpecRoundtrip:assert restored.nodes[0].status == NodeStatus.FAILEDassert restored.nodes[0].error is not None- assert restored.nodes[0].error.error_type == "PipeRunError"- assert restored.nodes[0].error.message == "LLM generation failed"- assert "Traceback" in (restored.nodes[0].error.stack or "")+ assert restored.nodes[0].error == error+ assert restored.nodes[0].error.detail == "The request does not give the input 'topic', which the method requires."+ assert restored.nodes[0].error_stack == "Traceback (most recent call last):\n File ...\nPipeRunError: LLM generation failed"+ # The graph writes its node's problem as the wire does, with no member written as null.+ assert json.loads(json_str)["nodes"][0]["error"] == error.to_wire()def test_roundtrip_file_save_load(self, tmp_path: Path) -> None:"""Test save/load to file produces identical GraphSpec."""@@ -279,18 +285,22 @@ class TestGraphSpecRoundtrip:assert io_spec.preview.endswith("...")def test_stack_truncation_on_creation(self) -> None:- """Test that long stack traces are truncated on ErrorSpec creation."""+ """Test that a long stack trace is truncated on the failed node's creation."""long_stack = PreviewTruncationData.LONG_STACK_TEXT- error_spec = ErrorSpec(- error_type="TestError",- message="Test message",- stack=long_stack,+ node = NodeSpec(+ node_id="failed_node_001",+ kind=NodeKind.OPERATOR,+ pipe_code="failed_pipe",+ pipe_type="PipeLLM",+ status=NodeStatus.FAILED,+ error=make_problem(code=CoreCode.RUNTIME_UNEXPECTED, view=ProblemView.CALLER),+ error_stack=long_stack,)- # Stack should be truncated to max length- assert len(error_spec.stack or "") <= PreviewTruncationData.MAX_STACK_LENGTH- if error_spec.stack and len(long_stack) > PreviewTruncationData.MAX_STACK_LENGTH:- assert error_spec.stack.endswith("...")+ assert len(long_stack) > PreviewTruncationData.MAX_STACK_LENGTH+ assert node.error_stack is not None+ assert len(node.error_stack) <= PreviewTruncationData.MAX_STACK_LENGTH+ assert node.error_stack.endswith("...")def test_roundtrip_with_usage_preserves_none_cost(self) -> None:"""An unrated node round-trips as unrated — never as $0.00 (NodeUsageSpec invariant 2)."""@@ -477,7 +487,7 @@ class TestGraphSpecRoundtrip:pipe_code=f"pipe_{status}",pipe_type="TestType",status=status,- error=ErrorSpec(error_type="TestError", message="Test"),+ error=make_problem(code=CoreCode.RUNTIME_UNEXPECTED, view=ProblemView.CALLER),)nodes.append(node)diff --git a/tests/unit/pipelex/graph/test_graphspec_validation.py b/tests/unit/pipelex/graph/test_graphspec_validation.pyindex e369f2fda..854779ad8 100644--- a/tests/unit/pipelex/graph/test_graphspec_validation.py+++ b/tests/unit/pipelex/graph/test_graphspec_validation.py@@ -1,13 +1,14 @@"""Unit tests for GraphSpec validation."""import pytest+from mthds.protocol.problem.registry import CoreCodefrom pydantic import ValidationError+from pipelex.errors.problem import ProblemView, make_location, make_problemfrom pipelex.graph.exceptions import GraphSpecValidationErrorfrom pipelex.graph.graphspec import (EdgeKind,EdgeSpec,- ErrorSpec,GraphSpec,GraphSpecMode,NodeKind,@@ -229,9 +230,8 @@ class TestGraphSpecValidation:def test_accept_failed_status_with_error(self) -> None:"""Test that nodes with status=failed and proper error are accepted."""- error = ErrorSpec(- error_type="PipeRunError",- message="Pipe execution failed",+ error = make_problem(+ code=CoreCode.RUNTIME_UNEXPECTED, view=ProblemView.CALLER, location=make_location(pipe="failed_pipe", path=["failed_pipe"]))node = NodeSpec(diff --git a/tests/unit/pipelex/graph/test_node_problem.py b/tests/unit/pipelex/graph/test_node_problem.pynew file mode 100644index 000000000..494f2c3cf--- /dev/null+++ b/tests/unit/pipelex/graph/test_node_problem.py@@ -0,0 +1,55 @@+import logging++import pytest+from mthds.protocol.problem.registry import CoreCode+from pytest_mock import MockerFixture++from pipelex.core.stuffs.exceptions import StuffFactoryError+from pipelex.graph.node_problem import NODE_PROBLEM_FAULT_MESSAGE, make_node_problem+++class TestNodeProblem:+ def test_a_pipelex_error_records_its_problem_located_at_the_node(self) -> None:+ error = StuffFactoryError("Error combining stuffs for concept Report").with_error_code(CoreCode.PIPE_OUTPUT_INVALID)++ problem = make_node_problem(error=error, pipe_code="analyze", pipe_path=["flow", "analyze"])++ assert problem.code == CoreCode.PIPE_OUTPUT_INVALID+ assert problem.location is not None+ assert problem.location.as_wire() == {"pipe": "analyze", "path": ["flow", "analyze"]}+ assert problem.params is not None+ assert problem.params.as_wire()["pipe"] == "analyze"++ def test_the_node_records_the_caller_view(self) -> None:+ """The graph is read by whoever reads the run: no diagnostics, and never the error's own message."""+ error = StuffFactoryError("a deployment's validator said: secret-ish text")++ problem = make_node_problem(error=error, pipe_code="analyze", pipe_path=["flow", "analyze"])++ assert problem.diagnostics is None+ assert "secret-ish text" not in str(problem.to_wire())++ def test_an_entry_pipe_names_itself_as_its_path(self) -> None:+ problem = make_node_problem(error=StuffFactoryError("refused"), pipe_code="flow", pipe_path=[])++ assert problem.location is not None+ assert problem.location.as_wire() == {"pipe": "flow", "path": ["flow"]}++ def test_a_foreign_exception_is_a_fault_of_ours(self) -> None:+ problem = make_node_problem(error=RuntimeError("The worker was lost"), pipe_code="flow", pipe_path=["flow"])++ assert problem.code == CoreCode.RUNTIME_UNEXPECTED+ assert "The worker was lost" not in str(problem.to_wire())++ def test_a_problem_that_cannot_be_built_records_a_fault_of_ours(self, mocker: MockerFixture, caplog: pytest.LogCaptureFixture) -> None:+ """Tracing never changes how a run fails: a problem that raises is logged, and the node records `runtime.unexpected`."""+ error = StuffFactoryError("Input 'topic' is missing")+ mocker.patch.object(error, "to_problem", side_effect=RuntimeError("The problem could not be built"))++ with caplog.at_level(logging.ERROR):+ problem = make_node_problem(error=error, pipe_code="flow", pipe_path=["flow"])++ assert problem.code == CoreCode.RUNTIME_UNEXPECTED+ (record,) = [record for record in caplog.records if record.getMessage().endswith(NODE_PROBLEM_FAULT_MESSAGE)]+ assert record.levelno == logging.ERROR+ assert (vars(record)["failed_error_type"], vars(record)["error.type"]) == ("StuffFactoryError", "RuntimeError")diff --git a/tests/unit/pipelex/graph/test_traced_failure.py b/tests/unit/pipelex/graph/test_traced_failure.pydeleted file mode 100644index f93432b61..000000000--- a/tests/unit/pipelex/graph/test_traced_failure.py+++ /dev/null@@ -1,46 +0,0 @@-import logging--import pytest-from pytest_mock import MockerFixture--from pipelex.base_exceptions import PipelexError-from pipelex.core.stuffs.exceptions import StuffFactoryError-from pipelex.graph.traced_failure import ERROR_REPORT_FAULT_MESSAGE, TracedFailure, make_traced_failure---class TestTracedFailure:- @pytest.mark.parametrize(- ("error", "expected"),- [- (- StuffFactoryError("Input 'topic' is missing").as_caller_fault(),- TracedFailure(message="Input 'topic' is missing", caller_facing=True),- ),- (- StuffFactoryError("A factory refusal that is not the caller's"),- TracedFailure(message="A factory refusal that is not the caller's", caller_facing=False),- ),- (RuntimeError("The worker was lost"), TracedFailure(message="The worker was lost", caller_facing=False)),- ],- ids=["caller_fault", "pipelex_error", "foreign_exception"],- )- def test_a_failure_records_its_message_and_whether_it_was_written_for_the_caller(self, error: BaseException, expected: TracedFailure) -> None:- assert make_traced_failure(error=error) == expected-- def test_a_pipelex_error_records_its_report_message(self) -> None:- error = StuffFactoryError("Error combining stuffs for concept Report").as_caller_fault()- assert isinstance(error, PipelexError)- assert make_traced_failure(error=error).message == error.to_error_report().message-- def test_a_report_that_cannot_be_built_records_the_errors_text(self, mocker: MockerFixture, caplog: pytest.LogCaptureFixture) -> None:- """Tracing never changes how a run fails: a report that raises is logged, and the node records the error's text."""- error = StuffFactoryError("Input 'topic' is missing").as_caller_fault()- mocker.patch.object(error, "to_error_report", side_effect=RuntimeError("The report could not be built"))-- with caplog.at_level(logging.ERROR):- traced_failure = make_traced_failure(error=error)-- assert traced_failure == TracedFailure(message=str(error), caller_facing=False)- (record,) = [record for record in caplog.records if record.getMessage().endswith(ERROR_REPORT_FAULT_MESSAGE)]- assert record.levelno == logging.ERROR- assert (vars(record)["failed_error_type"], vars(record)["error.type"]) == ("StuffFactoryError", "RuntimeError")diff --git a/tests/unit/pipelex/hosted/test_data.py b/tests/unit/pipelex/hosted/test_data.pyindex 14b06e503..14140ae48 100644--- a/tests/unit/pipelex/hosted/test_data.py+++ b/tests/unit/pipelex/hosted/test_data.py@@ -68,14 +68,36 @@ class HostedVersions:class HostedPipeIoVerdicts:- """`POST /v1/pipe-io` invalid verdicts, as the runner's crate core builds them."""+ """`POST /v1/pipe-io` invalid verdicts, as the runner's crate core builds them in the caller's view."""++ # A method calling a package by its address that the request did not ship: pipe-io loads only the packages shipped+ # with the method, and `/v1/start` fetches the dependency and runs. Built from the item+ # `resolve_crate_from_method_dir`'s refusal carries on 2026-10-18.+ UNSHIPPED_ADDRESS_DEPENDENCY: ClassVar[str] = (+ '{"is_valid": false, "validation_errors": [{"category": "pipe_validation", "error_type": "unresolved_package_dependency", '+ '"source": "bundle.mthds", "message": "In-memory resolve cannot load address-based dependency '+ "'github.com/mthds/scoring-lib/scoring' from the host filesystem; provide the dependency contents in the request or "+ 'use directory-based resolution."}], "message": "The method does not validate."}'+ )+++class HostedPipeIoRefusals:+ """`POST /v1/pipe-io` refusals, as the runner answers them in the caller's view."""# A method calling a published method by address: the crate core behind pipe-io loads no address-based dependency,- # which `/v1/start` fetches and runs. Built from `resolve_crate_from_contents`'s refusal on 2026-10-07.+ # which `/v1/start` fetches and runs. Built from `resolve_crate_from_contents`'s refusal on 2026-10-17.ADDRESS_DEPENDENCY: ClassVar[str] = (- '{"is_valid": false, "validation_errors": [{"category": "blueprint_validation", "message": "In-memory resolve cannot load '- "address-based dependency 'github.com/mthds/scoring-lib/scoring' from the host filesystem; provide the dependency contents "- 'in the request or use directory-based resolution."}], "message": "In-memory resolve cannot load address-based dependency '- "'github.com/mthds/scoring-lib/scoring' from the host filesystem; provide the dependency contents in the request or use "- 'directory-based resolution."}'+ '{"type": "https://mthds.ai/errors/request.unsupported", "title": "The request uses a form this runtime does not accept", '+ '"status": 422, "detail": "This runtime does not accept the form the request\'s field \'files\' uses (reason: '+ 'address_based_dependency).", "code": "request.unsupported", "domain": "input", "retry": "no", "next_step": {"kind": '+ '"change_input", "detail": "Send the field \'files\' in a form this runtime accepts, then send the request again."}, '+ '"params": {"field": "files", "reason": "address_based_dependency"}, "request_id": "01K7ADDRESSDEPENDENCY0000"}'+ )+ # The same code for another reason, which is no address-based dependency.+ OTHER_UNSUPPORTED_FORM: ClassVar[str] = (+ '{"type": "https://mthds.ai/errors/request.unsupported", "title": "The request uses a form this runtime does not accept", '+ '"status": 422, "detail": "This runtime does not accept the form the request\'s field \'extra\' uses (reason: '+ 'hosted_only_extension).", "code": "request.unsupported", "domain": "input", "retry": "no", "next_step": {"kind": '+ '"change_input", "detail": "Send the field \'extra\' in a form this runtime accepts, then send the request again."}, '+ '"params": {"field": "extra", "reason": "hosted_only_extension"}}')diff --git a/tests/unit/pipelex/hosted/test_hosted_error_rendering.py b/tests/unit/pipelex/hosted/test_hosted_error_rendering.pyindex 7201946ff..2b1820ddb 100644--- a/tests/unit/pipelex/hosted/test_hosted_error_rendering.py+++ b/tests/unit/pipelex/hosted/test_hosted_error_rendering.py@@ -272,8 +272,7 @@ class TestHostedErrorRendering:def test_a_local_file_for_a_method_with_an_address_dependency_points_at_a_url(self) -> None:error = HostedLocalFileUploadUnavailableError(- "Local file upload is not available yet for methods with address-based dependencies: the method depends on "- "github.com/mthds/scoring-lib/scoring"+ "Local file upload is not available yet for methods with address-based dependencies, and the inputs name a local file")view = describe_hosted_error(error=error)diff --git a/tests/unit/pipelex/hosted/test_hosted_run.py b/tests/unit/pipelex/hosted/test_hosted_run.pyindex 386cec14c..70aecc52d 100644--- a/tests/unit/pipelex/hosted/test_hosted_run.py+++ b/tests/unit/pipelex/hosted/test_hosted_run.py@@ -10,6 +10,7 @@ from mthds.protocol.models import VersionInfofrom pipelex_sdk.client import PipelexAPIClientfrom pipelex_sdk.crate_models import CrateInvalidReport, MthdsFileItem, PipeIORequest, PipeIOValidReportfrom pipelex_sdk.errors import (+ ApiResponseError,ApiUnreachableError,MissingMainStuffError,RunFailedError,@@ -28,7 +29,7 @@ from pipelex.hosted.exceptions import (HostedRunPollingError,)from pipelex.hosted.hosted_run import HostedRunRequest, run_hosted-from tests.unit.pipelex.hosted.test_data import HostedDescriptors, HostedPipeIoVerdicts, HostedVersions+from tests.unit.pipelex.hosted.test_data import HostedDescriptors, HostedPipeIoRefusals, HostedPipeIoVerdicts, HostedVersionsif TYPE_CHECKING:from pathlib import Path@@ -62,6 +63,21 @@ def _invalid_report(*, verdict_json: str) -> CrateInvalidReport:return CrateInvalidReport.model_validate_json(verdict_json)+def _pipe_io_refusal(*, problem_json: str) -> ApiResponseError:+ """The error the client raises when `POST /v1/pipe-io` answers this problem document."""+ problem: dict[str, Any] = json.loads(problem_json)+ return ApiResponseError(+ f"API POST /v1/pipe-io failed (422): {problem['detail']}",+ api_url="https://hosted.test",+ status=422,+ status_text="Unprocessable Entity",+ response_body=problem_json,+ server_message=problem["detail"],+ code=problem["code"],+ problem_document=problem,+ )++def _mocked_client(mocker: MockerFixture, *, pipe_io_report: PipeIOValidReport | CrateInvalidReport | None = None, version: str = HostedVersions.HOSTED) -> MagicMock:@@ -165,7 +181,8 @@ class TestHostedRun:@pytest.mark.asyncioasync def test_an_address_dependency_runs_with_inputs_naming_no_local_file(self, mocker: MockerFixture) -> None:"""pipe-io loads no address-based dependency; with no file to upload it is not asked, and the run route fetches the dependency."""- client = _mocked_client(mocker, pipe_io_report=_invalid_report(verdict_json=HostedPipeIoVerdicts.ADDRESS_DEPENDENCY))+ client = _mocked_client(mocker)+ client.pipe_io.side_effect = _pipe_io_refusal(problem_json=HostedPipeIoRefusals.ADDRESS_DEPENDENCY)request = HostedRunRequest(mthds_files=[BUNDLE_FILE], inputs={"item": "a widget"})outcome = await run_hosted(client=client, request=request)@@ -231,9 +248,38 @@ class TestHostedRun:async def test_a_local_file_for_a_method_with_an_address_dependency_is_refused_with_a_url_to_use(self, mocker: MockerFixture, tmp_path: Path) -> None:- """Uploading needs the signature, which pipe-io cannot read through an address-based dependency: the method is not at fault."""+ """Uploading needs the signature, which pipe-io cannot read through an address-based dependency: the method is not at fault.++ pipe-io answers the refusal with its problem, coded `request.unsupported` and giving the address-dependency reason.+ """(tmp_path / "invoice.pdf").write_bytes(b"%PDF")- client = _mocked_client(mocker, pipe_io_report=_invalid_report(verdict_json=HostedPipeIoVerdicts.ADDRESS_DEPENDENCY))+ client = _mocked_client(mocker)+ client.pipe_io.side_effect = _pipe_io_refusal(problem_json=HostedPipeIoRefusals.ADDRESS_DEPENDENCY)+ request = HostedRunRequest(mthds_files=[BUNDLE_FILE], inputs={"document": "invoice.pdf"}, inputs_base_dir=tmp_path)++ with pytest.raises(HostedLocalFileUploadUnavailableError) as exc_info:+ await run_hosted(client=client, request=request)++ error = exc_info.value+ assert "address-based dependencies" in error.message+ assert isinstance(error.__cause__, ApiResponseError)+ assert error.user_action is not None+ assert "https URL" in error.user_action.detail+ assert "Fix the method" not in error.user_action.detail+ client.upload_file.assert_not_awaited()+ client.start.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_a_local_file_for_a_method_whose_address_dependency_was_not_shipped_is_refused_naming_it(+ self, mocker: MockerFixture, tmp_path: Path+ ) -> None:+ """pipe-io loads only the packages shipped with the method, and answers a call into another one with its verdict.++ The run route fetches that dependency, so the method is not at fault: the error names the dependency and the URL+ to use, never the verdict's advice to fix the method.+ """+ (tmp_path / "invoice.pdf").write_bytes(b"%PDF")+ client = _mocked_client(mocker, pipe_io_report=_invalid_report(verdict_json=HostedPipeIoVerdicts.UNSHIPPED_ADDRESS_DEPENDENCY))request = HostedRunRequest(mthds_files=[BUNDLE_FILE], inputs={"document": "invoice.pdf"}, inputs_base_dir=tmp_path)with pytest.raises(HostedLocalFileUploadUnavailableError) as exc_info:@@ -248,6 +294,21 @@ class TestHostedRun:client.upload_file.assert_not_awaited()client.start.assert_not_awaited()+ @pytest.mark.asyncio+ async def test_another_unsupported_request_form_from_pipe_io_is_the_hosted_api_s_refusal(self, mocker: MockerFixture, tmp_path: Path) -> None:+ """The same code for another reason is no address-based dependency, so the hosted API's refusal propagates as it is."""+ (tmp_path / "invoice.pdf").write_bytes(b"%PDF")+ refusal = _pipe_io_refusal(problem_json=HostedPipeIoRefusals.OTHER_UNSUPPORTED_FORM)+ client = _mocked_client(mocker)+ client.pipe_io.side_effect = refusal+ request = HostedRunRequest(mthds_files=[BUNDLE_FILE], inputs={"document": "invoice.pdf"}, inputs_base_dir=tmp_path)++ with pytest.raises(ApiResponseError) as exc_info:+ await run_hosted(client=client, request=request)++ assert exc_info.value is refusal+ client.start.assert_not_awaited()+@pytest.mark.asyncioasync def test_a_method_that_does_not_load_is_refused_before_the_run_with_its_labelled_items(self, mocker: MockerFixture, tmp_path: Path) -> None:"""pipe-io's verdict names each file by the label it was sent under; `/v1/start` takes bare contents and could not."""diff --git a/tests/unit/pipelex/kernel/test_check_llm_setting_with_served_model.py b/tests/unit/pipelex/kernel/test_check_llm_setting_with_served_model.pyindex 1ebcd6d24..5dd75c07e 100644--- a/tests/unit/pipelex/kernel/test_check_llm_setting_with_served_model.py+++ b/tests/unit/pipelex/kernel/test_check_llm_setting_with_served_model.py@@ -3,8 +3,8 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, Anyimport pytest+from mthds.protocol.problem.registry import CoreCode-from pipelex.base_exceptions import DisclosureModefrom pipelex.cogt.exceptions import LLMCapabilityError, LLMSettingRefusedError, ModelWaterfallErrorfrom pipelex.cogt.llm.llm_job_components import LLMJobParams, ReasoningEffortfrom pipelex.cogt.llm.llm_setting import LLMSetting@@ -13,6 +13,7 @@ from pipelex.cogt.model_backends.constraints import ValuedConstraintfrom pipelex.cogt.model_backends.model_spec import InferenceModelSpecfrom pipelex.cogt.model_backends.model_type import ModelTypefrom pipelex.cogt.usage.cost_category import CostCategory+from pipelex.errors.problem import ProblemViewfrom pipelex.kernel.llm_ops import check_llm_setting_with_served_modelfrom pipelex.plugins.inference_backend_registry import LLMRequestCheckfrom pipelex.system.exceptions import MissingDependencyError@@ -78,32 +79,31 @@ class TestCheckLLMSettingWithServedModel:with pytest.raises(LLMSettingRefusedError, match=r"does not support reasoning \(thinking_mode=none\)"):check_llm_setting_with_served_model(llm_setting=_SETTING, is_structured=True)- def test_a_refusal_names_the_model_by_its_handle_and_is_shown_under_strict_disclosure(self, mocker: MockerFixture) -> None:+ def test_a_refusal_names_the_model_by_its_handle(self, mocker: MockerFixture) -> None:"""A worker names the model with its SDK, backend and provider id, which only its operator may see."""_serve(mocker, served=_make_model(thinking_mode=ThinkingMode.NONE), check=None)with pytest.raises(LLMSettingRefusedError) as exc_info:check_llm_setting_with_served_model(llm_setting=_SETTING, is_structured=False)message = str(exc_info.value)assert message.startswith("Model 'some-model' does not support reasoning")+ caller = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert caller.code == CoreCode.MODEL_CAPABILITY_UNSUPPORTED+ assert "'some-model'" in caller.detailfor internal_name in ("some_sdk", "some_backend", "some-model-id"):assert internal_name not in message- assert exc_info.value.to_error_report().to_dict(disclosure_mode=DisclosureMode.STRICT)["message"] == message+ assert internal_name not in str(caller.to_wire())def test_an_external_plugin_s_refusal_is_raised_as_it_wrote_it(self, mocker: MockerFixture) -> None:- """Its text may carry what the plugin keeps private, so it stays internal under strict disclosure."""+ """Its text may carry what the plugin keeps private, so it rides the operator's diagnostics alone."""refusal = LLMCapabilityError("Model 'some-model' is refused by tenant 1234 at internal.example")_serve(mocker, served=_make_model(thinking_mode=ThinkingMode.NONE), check=mocker.MagicMock(side_effect=refusal), is_builtin=False)with pytest.raises(LLMCapabilityError) as exc_info:check_llm_setting_with_served_model(llm_setting=_SETTING, is_structured=False)assert exc_info.value is refusal- assert "tenant 1234" not in exc_info.value.to_error_report().to_dict(disclosure_mode=DisclosureMode.STRICT)["message"]-- def test_an_external_plugin_s_refusal_it_vouches_for_is_shown_under_strict_disclosure(self, mocker: MockerFixture) -> None:- refusal = LLMCapabilityError("Model 'some-model' takes no reasoning").as_caller_fault()- _serve(mocker, served=_make_model(thinking_mode=ThinkingMode.NONE), check=mocker.MagicMock(side_effect=refusal), is_builtin=False)- with pytest.raises(LLMCapabilityError) as exc_info:- check_llm_setting_with_served_model(llm_setting=_SETTING, is_structured=False)- assert exc_info.value.to_error_report().to_dict(disclosure_mode=DisclosureMode.STRICT)["message"] == "Model 'some-model' takes no reasoning"+ assert "tenant 1234" not in str(exc_info.value.to_problem(view=ProblemView.CALLER).to_wire())+ operator = exc_info.value.to_problem(view=ProblemView.OPERATOR)+ assert operator.diagnostics is not None+ assert "tenant 1234" in operator.diagnostics.message@pytest.mark.parametrize("served",diff --git a/tests/unit/pipelex/kernel/test_structure_prompt_owner.py b/tests/unit/pipelex/kernel/test_structure_prompt_owner.pyindex 7b7197b45..8b743f5f4 100644--- a/tests/unit/pipelex/kernel/test_structure_prompt_owner.py+++ b/tests/unit/pipelex/kernel/test_structure_prompt_owner.py@@ -9,6 +9,7 @@ from mthds.protocol.problem.registry import CoreCodefrom pytest_mock import MockerFixturefrom pipelex.cogt.config_cogt import LLMConfig+from pipelex.errors.problem import ProblemViewfrom pipelex.kernel.llm_ops import derive_structure_promptfrom pipelex.test_extras.registry_test_models import FictionCharacterfrom pipelex.tools.jinja2.exceptions import Jinja2TemplateInvalidError@@ -29,4 +30,4 @@ class TestStructurePromptOwner: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_UNEXPECTED+ assert exc_info.value.to_problem(view=ProblemView.CALLER).code == CoreCode.RUNTIME_UNEXPECTEDdiff --git a/tests/unit/pipelex/libraries/test_method_requirements_check.py b/tests/unit/pipelex/libraries/test_method_requirements_check.pyindex 08c978e74..cda729231 100644--- a/tests/unit/pipelex/libraries/test_method_requirements_check.py+++ b/tests/unit/pipelex/libraries/test_method_requirements_check.py@@ -5,9 +5,12 @@ from pathlib import Pathimport pytestfrom mthds.method_tree.lister import list_method_tree+from mthds.protocol.problem.registry import CoreCode, ProblemDomainfrom pytest_mock import MockerFixture-from pipelex.base_exceptions import INTERNAL_ERROR_PLACEHOLDER, DisclosureMode, ErrorDomain, ValidationErrorCategory+from pipelex.base_exceptions import PipelexError, ValidationErrorCategory+from pipelex.errors.problem import ProblemView+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.libraries.exceptions import (HostLibraryRequirementsError,HostLibraryTreeError,@@ -51,6 +54,17 @@ def _method(*, directory: Path, requirements: str | bytes | None, with_python: breturn directory+def _assert_the_host_s_fault(*, error: PipelexError) -> None:+ """The host's library is the operator's configuration: its code is the operator's, and its message the operator's alone."""+ caller = error.to_problem(view=ProblemView.CALLER)+ assert caller.code == PipelexErrorCode.CONFIG_INVALID+ assert caller.domain == ProblemDomain.OPERATOR+ assert error.message not in str(caller.to_wire())+ operator = error.to_problem(view=ProblemView.OPERATOR)+ assert operator.diagnostics is not None+ assert operator.diagnostics.message == error.message++class TestMethodRequirementsCheck:@pytest.mark.parametrize(("topic", "requirements", "with_python", "nested_requirements"),@@ -86,7 +100,9 @@ class TestMethodRequirementsCheck:assert "line 4 'name @ https://example.com/x.whl'" in messageitems = exc_info.value.blueprint_validation_errorsassert [(item.source, item.line) for item in items] == [("requirements.txt", 2), ("requirements.txt", 4)]- assert exc_info.value.to_error_report().error_domain == ErrorDomain.INPUT+ problem = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert problem.code == CoreCode.METHOD_PACKAGE_INVALID+ assert problem.domain == ProblemDomain.METHODdef test_a_file_that_is_not_utf8_is_refused(self, tmp_path: Path) -> None:_method(directory=tmp_path, requirements=b"pandas\xff\n")@@ -232,16 +248,16 @@ class TestMethodRequirementsCheck:with pytest.raises(ValidateBundleError) as verdict_info, translate_to_validate_bundle_error():ensure_served_method_requirements_met(library_dirs=[method_dir])- refusal = refusal_info.value.to_error_report()- assert refusal.error_domain == ErrorDomain.INPUT- message = refusal.to_dict(disclosure_mode=DisclosureMode.STRICT)["message"]+ message = refusal_info.value.messageassert message == f"The method needs Python packages that the Daytona sandbox cannot offer, as its requirements.txt declares: {reason}"- verdict = verdict_info.value.to_error_report()- assert verdict.validation_errors is not None- (item,) = verdict.validation_errors+ refusal = refusal_info.value.to_problem(view=ProblemView.CALLER)+ assert refusal.code == CoreCode.METHOD_DEPENDENCY_MISSING+ assert refusal.domain == ProblemDomain.METHOD+ (item,) = verdict_info.value.validation_error_items()assert (item.source, item.line) == ("requirements.txt", None)assert item.message == f"The requirements are refused by the Daytona sandbox: {reason}"- assert str(tmp_path) not in str(refusal.to_dict(disclosure_mode=DisclosureMode.STRICT))+ for disclosed in (message, str(refusal.to_wire()), str(item)):+ assert str(tmp_path) not in discloseddef test_a_served_method_checks_the_packages_nested_in_its_directory(self, tmp_path: Path) -> None:_write(directory=tmp_path, tree_path="top.mthds", content="domain = 'requirements_top'\n")@@ -258,16 +274,14 @@ class TestMethodRequirementsCheck:with pytest.raises(ValidateBundleError) as exc_info, translate_to_validate_bundle_error():ensure_served_method_requirements_met(library_dirs=[tmp_path])- report = exc_info.value.to_error_report()- assert report.validation_errors is not None- (item,) = report.validation_errors+ (item,) = exc_info.value.validation_error_items()assert item.category == ValidationErrorCategory.BLUEPRINT_VALIDATIONassert item.source == "requirements.txt"assert item.line == 1assert f"The requirement '{_ABSENT_PACKAGE}' is not met" in item.message- def test_under_strict_disclosure_a_served_method_refused_in_direct_mode_names_no_host_path(self, tmp_path: Path) -> None:- """This interpreter, read for real in the direct mode: the caller reads the method, its lines and the packages, and no path on the host."""+ def test_a_served_method_refused_in_direct_mode_names_no_host_path_to_its_caller(self, tmp_path: Path) -> None:+ """This interpreter, read for real in the direct mode: the caller reads the method's lines, and no path on the host."""method_dir = _method(directory=tmp_path / "request-files", requirements=f"pydantic>=2\n{_ABSENT_PACKAGE}>=1\n")with pytest.raises(MethodRequirementsNotMetError) as refusal_info:@@ -275,14 +289,17 @@ class TestMethodRequirementsCheck:with pytest.raises(ValidateBundleError) as verdict_info, translate_to_validate_bundle_error():ensure_served_method_requirements_met(library_dirs=[method_dir])- refusal = refusal_info.value.to_error_report().to_dict(disclosure_mode=DisclosureMode.STRICT)- verdict = verdict_info.value.to_error_report().to_dict(disclosure_mode=DisclosureMode.STRICT)- message = refusal["message"]+ # The refusal's message, which names the packages and the command that installs them, names no host path either.+ message = refusal_info.value.messageassert message.startswith("The method needs Python packages that the Python interpreter Pipelex runs in does not have")assert f"line 2 '{_ABSENT_PACKAGE}>=1' ({_ABSENT_PACKAGE} is missing)" in messageassert f"uv pip install '{_ABSENT_PACKAGE}>=1'" in message- assert [(item["source"], item["line"]) for item in verdict["validation_errors"]] == [("requirements.txt", 2)]- for disclosed in (str(refusal), str(verdict)):+ refusal = refusal_info.value.to_problem(view=ProblemView.CALLER)+ assert refusal.code == CoreCode.METHOD_DEPENDENCY_MISSING+ verdict_items = verdict_info.value.validation_error_items()+ assert [(item.source, item.line) for item in verdict_items] == [("requirements.txt", 2)]+ verdict = verdict_info.value.to_problem(view=ProblemView.CALLER)+ for disclosed in (message, str(refusal.to_wire()), str(verdict.to_wire()), str(verdict_items)):for host_path in (str(tmp_path), str(tmp_path.resolve()), sys.executable):assert host_path not in disclosed, host_path@@ -293,9 +310,7 @@ class TestMethodRequirementsCheck:with pytest.raises(HostLibraryTreeError) as exc_info:ensure_served_method_requirements_met(library_dirs=[method_dir])- report = exc_info.value.to_error_report()- assert report.error_domain == ErrorDomain.CONFIG- assert report.to_dict(disclosure_mode=DisclosureMode.STRICT)["message"] == INTERNAL_ERROR_PLACEHOLDER+ _assert_the_host_s_fault(error=exc_info.value)def test_around_a_hosts_library_directories_a_refusal_is_the_hosts_fault(self, tmp_path: Path) -> None:_method(directory=tmp_path, requirements=f"{_ABSENT_PACKAGE}\n")@@ -304,9 +319,7 @@ class TestMethodRequirementsCheck:ensure_method_requirements_met(trees=[list_method_tree(tmp_path)], names_host_paths=True)assert isinstance(exc_info.value.__cause__, MethodRequirementsNotMetError)- report = exc_info.value.to_error_report()- assert report.error_domain == ErrorDomain.CONFIG- assert report.to_dict(disclosure_mode=DisclosureMode.STRICT)["message"] == INTERNAL_ERROR_PLACEHOLDER+ _assert_the_host_s_fault(error=exc_info.value)def test_a_dependency_package_is_named_by_its_address(self, tmp_path: Path) -> None:package_dir = _method(directory=tmp_path / "installed" / "invoicing", requirements=f"-r base.txt\n{_ABSENT_PACKAGE}\n")diff --git a/tests/unit/pipelex/libraries/test_method_trees.py b/tests/unit/pipelex/libraries/test_method_trees.pyindex 8db4853e7..bd1722c84 100644--- a/tests/unit/pipelex/libraries/test_method_trees.py+++ b/tests/unit/pipelex/libraries/test_method_trees.py@@ -2,9 +2,11 @@ from pathlib import Pathimport pytestfrom mthds.method_tree.models import TreeLimits+from mthds.protocol.problem.registry import ProblemDomainfrom pytest_mock import MockerFixture-from pipelex.base_exceptions import ErrorDomain+from pipelex.errors.problem import ProblemView+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.libraries.exceptions import HostLibraryTreeError, MethodTreeLoadErrorfrom pipelex.libraries.method_trees import (LIMITS_ADVICE,@@ -194,9 +196,10 @@ class TestMethodTrees:with pytest.raises(HostLibraryTreeError) as exc_info, reporting_host_library_tree_faults():list_library_bundle_files(library_dirs=[tmp_path / "lib"])- report = exc_info.value.to_error_report()- assert report.error_domain == ErrorDomain.CONFIG- assert report.caller_facing_message is False+ caller = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert caller.code == PipelexErrorCode.CONFIG_INVALID+ assert caller.domain == ProblemDomain.OPERATOR+ assert exc_info.value.message not in str(caller.to_wire())assert isinstance(exc_info.value.__cause__, MethodTreeLoadError)def test_every_bundle_file_under_a_directory_is_found_whatever_the_membership_rule(self, tmp_path: Path) -> None:diff --git a/tests/unit/pipelex/libraries/test_package_environments.py b/tests/unit/pipelex/libraries/test_package_environments.pyindex 4fc61b1f8..0f4c70fde 100644--- a/tests/unit/pipelex/libraries/test_package_environments.py+++ b/tests/unit/pipelex/libraries/test_package_environments.py@@ -1,10 +1,11 @@from collections.abc import Callableimport pytest+from mthds.protocol.problem.registry import ProblemDomainfrom pytest_mock import MockerFixture-from pipelex.base_exceptions import ErrorDomainfrom pipelex.core.method_trees.requirements_file import RequirementLine, parse_requirements_text+from pipelex.errors.problem import ProblemViewfrom pipelex.libraries.exceptions import PipeFuncPackageSetUnstatedErrorfrom pipelex.libraries.package_environments import InterpreterPackageEnvironment, OfferedPackageEnvironment, resolve_pipe_func_package_environmentfrom pipelex.plugins.pipe_func_package_offer_registry import (@@ -86,4 +87,6 @@ class TestPackageEnvironments:assert exc_info.value.offer_registered is offer_registered, topicassert remedy in exc_info.value.message, topicassert ("registers a package offer that could not state" in exc_info.value.message) is offer_registered, topic- assert exc_info.value.to_error_report().error_domain == ErrorDomain.CONFIG+ caller = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert caller.domain == ProblemDomain.OPERATOR, topic+ assert exc_info.value.message not in str(caller.to_wire()), topicdiff --git a/tests/unit/pipelex/libraries/test_pipe_library_lookup.py b/tests/unit/pipelex/libraries/test_pipe_library_lookup.pyindex 0aae40b85..036754064 100644--- a/tests/unit/pipelex/libraries/test_pipe_library_lookup.py+++ b/tests/unit/pipelex/libraries/test_pipe_library_lookup.py@@ -1,10 +1,11 @@from typing import Anyimport pytest-from mthds.protocol.problem.registry import CoreCode+from mthds.protocol.problem.registry import CoreCode, ProblemDomainfrom pytest_mock import MockerFixture-from pipelex.base_exceptions import ErrorDomain+from pipelex.errors.error_codes import error_code_spec+from pipelex.errors.problem import ProblemViewfrom pipelex.libraries.pipe.exceptions import EntryPipeAmbiguousError, EntryPipeNotFoundError, PipeLibraryError, PipeNotFoundErrorfrom pipelex.libraries.pipe.pipe_library import PipeLibrary@@ -83,7 +84,7 @@ class TestPipeLibraryLookup:"""Two domains declaring the code: refuse to guess, and name both so the user can pick.The code came from a human — a CLI argument or an API request field — so the failure is the- caller's to fix: INPUT domain, 422, never a server fault the caller would retry.+ caller's to fix: the input domain, 422, never a server fault the caller would retry."""library = PipeLibrary.make_empty()library.root["scoring.compute_score"] = _make_stub_pipe(mocker, code="compute_score", domain_code="scoring")@@ -93,25 +94,30 @@ class TestPipeLibraryLookup:assert "analytics.compute_score" in str(exc_info.value)assert "scoring.compute_score" in str(exc_info.value)- report = exc_info.value.to_error_report()- assert report.code == CoreCode.REQUEST_PIPE_AMBIGUOUS- assert report.error_domain == ErrorDomain.INPUT- assert report.http_status == 422+ problem = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert problem.code == CoreCode.REQUEST_PIPE_AMBIGUOUS+ assert problem.domain == ProblemDomain.INPUT+ assert error_code_spec(CoreCode.REQUEST_PIPE_AMBIGUOUS).status == 422+ params = problem.to_wire()["params"]+ assert params["pipe"] == "compute_score"+ assert "analytics.compute_score" in str(params["candidates"])+ assert "scoring.compute_score" in str(params["candidates"])def test_entry_pipe_no_match_returns_none(self):library = PipeLibrary.make_empty()assert library.get_optional_entry_pipe("nonexistent") is Nonedef test_entry_pipe_required_raises_not_found(self):- """An entry code that resolves to nothing is a caller typo, reported as INPUT / 422."""+ """An entry code that resolves to nothing is a caller typo, reported in the input domain, 422."""library = PipeLibrary.make_empty()with pytest.raises(EntryPipeNotFoundError) as exc_info:library.get_required_entry_pipe("nonexistent")- report = exc_info.value.to_error_report()- assert report.code == CoreCode.REQUEST_PIPE_NOT_FOUND- assert report.error_domain == ErrorDomain.INPUT- assert report.http_status == 422+ problem = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert problem.code == CoreCode.REQUEST_PIPE_NOT_FOUND+ assert problem.domain == ProblemDomain.INPUT+ assert error_code_spec(CoreCode.REQUEST_PIPE_NOT_FOUND).status == 422+ assert problem.detail == "The method declares no pipe 'nonexistent'."def test_entry_pipe_translates_aliased_ambiguity(self, mocker: MockerFixture):"""An ambiguous `alias->bare_code` reaching the entry lookup is still the caller's typo.@@ -131,7 +137,12 @@ class TestPipeLibraryLookup:cause = exc_info.value.__cause__assert isinstance(cause, PipeLibraryError)assert not isinstance(cause, EntryPipeAmbiguousError)- assert exc_info.value.to_error_report().error_domain == ErrorDomain.INPUT+ problem = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert problem.domain == ProblemDomain.INPUT+ # The candidates ride the refusal, for its caller and for a selection that reads them back.+ expected_candidates = ["lib->analytics.compute_score", "lib->scoring.compute_score"]+ assert exc_info.value.given_params["candidates"] == expected_candidates+ assert problem.to_wire()["params"] == {"pipe": "lib->compute_score", "candidates": expected_candidates}def test_entry_pipe_does_not_translate_a_miss_into_an_ambiguity(self, mocker: MockerFixture):"""A miss surfacing from `get_optional_pipe` must not be re-raised as an ambiguity.@@ -162,9 +173,10 @@ class TestPipeLibraryLookup:with pytest.raises(PipeLibraryError) as exc_info:library.get_optional_pipe("lib->compute_score")assert not isinstance(exc_info.value, EntryPipeAmbiguousError)- report = exc_info.value.to_error_report()- assert report.code == CoreCode.METHOD_REF_AMBIGUOUS- assert report.caller_facing_message is False+ problem = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert problem.code == CoreCode.METHOD_REF_AMBIGUOUS+ assert problem.domain == ProblemDomain.METHOD+ assert exc_info.value.message not in str(problem.to_wire())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."""@@ -172,9 +184,10 @@ class TestPipeLibraryLookup:with pytest.raises(PipeNotFoundError) as exc_info:library.get_required_pipe("scoring.nonexistent")assert not isinstance(exc_info.value, EntryPipeNotFoundError)- report = exc_info.value.to_error_report()- assert report.code == CoreCode.METHOD_PIPE_UNRESOLVED- assert report.caller_facing_message is False+ problem = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert problem.code == CoreCode.METHOD_PIPE_UNRESOLVED+ assert problem.domain == ProblemDomain.METHOD+ assert exc_info.value.message not in str(problem.to_wire())def 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_controllers/binding/test_binding_step.py b/tests/unit/pipelex/pipe_controllers/binding/test_binding_step.pyindex d14d958f8..285030ab2 100644--- a/tests/unit/pipelex/pipe_controllers/binding/test_binding_step.py+++ b/tests/unit/pipelex/pipe_controllers/binding/test_binding_step.py@@ -1,4 +1,5 @@import pytest+from mthds.protocol.problem.registry import CoreCodefrom pytest_mock import MockerFixturefrom pipelex.core.concepts.concept import Concept@@ -9,6 +10,7 @@ from pipelex.core.stuffs.list_content import ListContentfrom pipelex.core.stuffs.number_content import NumberContentfrom pipelex.core.stuffs.stuff_content import StuffContentfrom pipelex.core.stuffs.stuff_factory import StuffFactory+from pipelex.errors.problem import PipelexProblemfrom pipelex.pipe_controllers.binding import binding_step as binding_step_modulefrom pipelex.pipe_controllers.binding.binding_derivation import BindingDerivation, BindingRoot, derive_bindingfrom pipelex.pipe_controllers.binding.binding_step import BindingStep@@ -244,16 +246,15 @@ class TestBindingStep:step.skip_untyped_root(working_memory=WorkingMemory(), calling_pipe_code=_SEQUENCE_CODE, run_mode=PipeRunMode.LIVE)@pytest.mark.parametrize(- ("error", "expected_failure"),+ ("error", "own_text"),[- (None, ("UnknownError", "the binding step stopped without binding a value", False)),- (RuntimeError("the root could not be read"), ("RuntimeError", "the root could not be read", False)),+ (None, "The binding step stopped without binding a value"),+ (RuntimeError("the root could not be read"), "the root could not be read"),],ids=["stopped_without_an_error", "stopped_by_an_error"],)- def test_a_stopped_binding_closes_its_node_as_failed_once(- self, mocker: MockerFixture, error: BaseException | None, expected_failure: tuple[str, str, bool]- ) -> None:+ def test_a_stopped_binding_closes_its_node_as_failed_once(self, mocker: MockerFixture, error: BaseException | None, own_text: str) -> None:+ """The node records a fault of ours in the caller's view, located at the path it binds from, and none of the error's text."""tracer_manager = mocker.MagicMock()mocker.patch.object(binding_step_module.GraphTracerManager, "get_instance", return_value=tracer_manager)job_metadata = JobMetadata(@@ -268,7 +269,13 @@ class TestBindingStep:tracer_manager.on_pipe_end_error.assert_called_once()call_kwargs = tracer_manager.on_pipe_end_error.call_args.kwargsassert (call_kwargs["lookup_key"], call_kwargs["node_id"]) == ("run_binding", "run_binding:node_3")- assert (call_kwargs["error_type"], call_kwargs["error_message"], call_kwargs["caller_facing"]) == expected_failure+ problem = call_kwargs["problem"]+ assert isinstance(problem, PipelexProblem)+ assert problem.code == CoreCode.RUNTIME_UNEXPECTED+ assert problem.diagnostics is None+ assert problem.location is not None+ assert (problem.location.pipe, problem.location.path) == ("invoice.supplier", ["invoice.supplier"])+ assert own_text not in str(problem.to_wire())def test_the_step_is_written_back_as_mthds_writes_it(self) -> None:step = BindingStep(from_path="invoice.supplier.address.city", output_name="city")diff --git a/tests/unit/pipelex/pipe_machinery/test_run_pipe_traced_failure.py b/tests/unit/pipelex/pipe_machinery/test_run_pipe_traced_failure.pyindex 09461d9e5..b8f6b8c06 100644--- a/tests/unit/pipelex/pipe_machinery/test_run_pipe_traced_failure.py+++ b/tests/unit/pipelex/pipe_machinery/test_run_pipe_traced_failure.py@@ -3,10 +3,12 @@from typing import Callableimport pytest+from mthds.protocol.problem.registry import CoreCodefrom pytest_mock import MockerFixturefrom pipelex.core.memory.working_memory_factory import WorkingMemoryFactoryfrom pipelex.core.stuffs.exceptions import StuffFactoryError+from pipelex.errors.problem import PipelexProblemfrom pipelex.pipe_machinery.pipe_abstract import InputPresenceScanfrom pipelex.pipe_machinery.pipe_factory import PipeFactoryfrom pipelex.pipe_operators.llm.pipe_llm import PipeLLM@@ -18,13 +20,13 @@ from tests.unit.pipelex.graph.conftest import make_trace_context@pytest.mark.asyncio(loop_scope="class")class TestRunPipeTracedFailure:- async def test_a_failure_whose_report_cannot_be_built_fails_the_run_with_the_pipes_own_error(+ async def test_a_failure_whose_problem_cannot_be_built_fails_the_run_with_the_pipes_own_error(self,mocker: MockerFixture,load_empty_library: Callable[[], str],) -> None:- """Building the failure's report runs while the pipe's error is on its way out: when it raises, the node records- the error's text, and the run still fails with the pipe's own error, never with the report's.+ """Building the failure's problem runs while the pipe's error is on its way out: when it raises, the node records+ a fault of ours, and the run still fails with the pipe's own error, never with the problem's."""load_empty_library()pipe = PipeFactory[PipeLLM].make_from_blueprint(@@ -33,7 +35,7 @@ class TestRunPipeTracedFailure:blueprint=PipeLLMBlueprint(description="Greet the user.", output="native.Text", prompt="Say hello."),)pipe_error = StuffFactoryError("The pipe's own failure")- mocker.patch.object(pipe_error, "to_error_report", side_effect=RuntimeError("The report could not be built"))+ mocker.patch.object(pipe_error, "to_problem", side_effect=RuntimeError("The problem could not be built"))empty_presence_scan = InputPresenceScan(missing_names=[], forced_absent=[], liftable=[])mocker.patch.object(PipeLLM, "validate_before_run", mocker.AsyncMock(return_value=empty_presence_scan))mocker.patch.object(PipeLLM, "live_run_pipe", mocker.AsyncMock(side_effect=pipe_error))@@ -55,9 +57,10 @@ class TestRunPipeTracedFailure:assert exc_info.value is pipe_errormock_manager.on_pipe_end_error.assert_called_once()end_kwargs = mock_manager.on_pipe_end_error.call_args.kwargs- assert (end_kwargs["node_id"], end_kwargs["error_type"], end_kwargs["error_message"], end_kwargs["caller_facing"]) == (- "test-run:node_0",- "StuffFactoryError",- str(pipe_error),- False,- )+ assert end_kwargs["node_id"] == "test-run:node_0"+ problem = end_kwargs["problem"]+ assert isinstance(problem, PipelexProblem)+ assert problem.code == CoreCode.RUNTIME_UNEXPECTED+ assert problem.location is not None+ assert problem.location.pipe == "say_hello"+ assert str(pipe_error) not in str(problem.to_wire())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.pyindex 6ed109214..76631d0e0 100644--- 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.py@@ -11,6 +11,7 @@ from pipelex.core.memory.working_memory_factory import WorkingMemoryFactoryfrom pipelex.core.pipes.exceptions import PipeRunErrorfrom pipelex.core.stuffs.text_content import TextContentfrom pipelex.errors.error_codes import ErrorCode+from pipelex.errors.problem import ProblemViewfrom pipelex.interpreter_hub import scoped_pipe_func_executorfrom pipelex.kernel.exceptions import FuncOutputTypeErrorfrom pipelex.pipe_machinery.pipe_factory import PipeFactory@@ -146,10 +147,16 @@ class TestPipeFuncFailureCode:failure = await _failure_of(pipe_func=_make_pipe_func(), executor=DirectPipeFuncExecutor(), function=function)- assert failure.to_error_report().code == CoreCode.PIPE_FUNCTION_RAISED+ caller = failure.to_problem(view=ProblemView.CALLER)+ assert caller.code == CoreCode.PIPE_FUNCTION_RAISEDassert isinstance(failure.__cause__, PipeFuncRaisedError)assert type(failure.__cause__.__cause__).__name__ == raised_typeassert f"Error: {raised_type}: " in failure.message+ # What the function raised can carry whatever the process holds, so its text is the operator's alone.+ assert raised_type not in str(caller.to_wire())+ operator = failure.to_problem(view=ProblemView.OPERATOR)+ assert operator.diagnostics is not None+ assert operator.diagnostics.message == failure.message@pytest.mark.parametrize(("executor", "expected_code"),@@ -173,7 +180,7 @@ class TestPipeFuncFailureCode:failure = await _failure_of(pipe_func=_make_pipe_func(), executor=executor, function=_raises_a_plain_error)- assert failure.to_error_report().code == expected_code+ assert failure.to_problem(view=ProblemView.CALLER).code == expected_code@pytest.mark.parametrize("function",@@ -190,5 +197,5 @@ class TestPipeFuncFailureCode:failure = await _failure_of(pipe_func=_make_pipe_func(), executor=DirectPipeFuncExecutor(), function=function)- assert failure.to_error_report().code == CoreCode.PIPE_OUTPUT_INVALID+ assert failure.to_problem(view=ProblemView.CALLER).code == CoreCode.PIPE_OUTPUT_INVALIDassert 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.pyindex 73b771a15..37fe61eb9 100644--- 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.py@@ -5,6 +5,7 @@ from mthds.protocol.problem.registry import CoreCodefrom pipelex.cogt.model_backends.model_type import ModelTypefrom pipelex.core.pipes.exceptions import PipeOperatorModelChoiceError+from pipelex.errors.problem import ProblemViewfrom pipelex.pipe_machinery.pipe_factory import PipeFactoryfrom pipelex.pipe_operators.img_gen.pipe_img_gen import PipeImgGenfrom pipelex.pipe_operators.img_gen.pipe_img_gen_blueprint import PipeImgGenBlueprint@@ -35,11 +36,11 @@ class TestPipeImgGenModelChoiceCode:refusal = _refusal_of(model=_llm_only_handle())assert refusal.field_name == "model"- assert refusal.to_error_report().code == CoreCode.MODEL_CAPABILITY_UNSUPPORTED+ assert refusal.to_problem(view=ProblemView.CALLER).code == CoreCode.MODEL_CAPABILITY_UNSUPPORTEDdef 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_UNKNOWN+ assert refusal.to_problem(view=ProblemView.CALLER).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.pyindex 3287b6753..1a16d87cd 100644--- 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.py@@ -1,8 +1,7 @@import pytest-from mthds.protocol.problem.registry import CoreCode+from mthds.protocol.problem.registry import CoreCode, ProblemDomainfrom pytest_mock import MockerFixture-from pipelex.base_exceptions import INTERNAL_ERROR_PLACEHOLDER, DisclosureModefrom pipelex.cogt.config_cogt import ModelDeckConfigfrom pipelex.cogt.exceptions import ModelChoiceNotFoundError, ModelDeckChoiceUnresolvedErrorfrom pipelex.cogt.img_gen.img_gen_job_components import Quality@@ -16,6 +15,7 @@ from pipelex.core.concepts.concept_factory import ConceptFactoryfrom pipelex.core.concepts.native.concept_native import NativeConceptCodefrom pipelex.core.pipes.exceptions import PipeOperatorModelChoiceErrorfrom pipelex.core.pipes.stuff_spec.stuff_spec import StuffSpec+from pipelex.errors.problem import ProblemViewfrom pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.kernel.prompt_assembly import UserPromptContentfrom pipelex.pipe_operators.judge.pipe_judge import PipeJudge, PipeJudgeQuestion@@ -80,12 +80,18 @@ class TestPipeJudgeDeckDefault: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+ caller = deck_fault.to_problem(view=ProblemView.CALLER)+ assert caller.code == PipelexErrorCode.CONFIG_INVALID+ assert caller.domain == ProblemDomain.OPERATOR+ assert caller.errors is None+ # The deck's setting is the operator's to fix and to read: the caller reads neither it nor the message.+ caller_wire = str(caller.to_wire())+ assert deck_fault.message not in caller_wire+ assert "choice_default" not in caller_wire+ operator = deck_fault.to_problem(view=ProblemView.OPERATOR)+ assert operator.diagnostics is not None+ assert operator.diagnostics.error_class == "ModelDeckChoiceUnresolvedError"+ assert operator.diagnostics.message == deck_fault.messagedef 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."""@@ -102,4 +108,4 @@ class TestPipeJudgeDeckDefault:located = exc_info.valueassert located.__cause__ is not_foundassert located.field_name == "model"- assert located.to_error_report().code == CoreCode.MODEL_UNKNOWN+ assert located.to_problem(view=ProblemView.CALLER).code == CoreCode.MODEL_UNKNOWNdiff --git a/tests/unit/pipelex/pipe_run/test_delivery_executor.py b/tests/unit/pipelex/pipe_run/test_delivery_executor.pyindex f173db50b..7f8732dc9 100644--- a/tests/unit/pipelex/pipe_run/test_delivery_executor.py+++ b/tests/unit/pipelex/pipe_run/test_delivery_executor.py@@ -8,8 +8,8 @@ from mthds.protocol.problem.registry import CoreCodefrom pytest_mock import MockerFixture, MockTypefrom pipelex import log-from pipelex.base_exceptions import ErrorReport-from pipelex.cogt.inference.error_classification import ProviderErrorMetadata, UserAction, UserActionKind+from pipelex.cogt.exceptions import InferenceErrorCategory, LLMCompletionError+from pipelex.cogt.inference.error_classification import ProviderErrorMetadatafrom pipelex.cogt.inference.provider_name import ProviderNamefrom pipelex.cogt.llm.llm_report import LLMTokensUsagefrom pipelex.cogt.usage.cost_category import CostCategory@@ -30,6 +30,7 @@ from pipelex.core.stuffs.list_content import ListContentfrom pipelex.core.stuffs.number_content import NumberContentfrom pipelex.core.stuffs.stuff import Stufffrom pipelex.core.stuffs.text_content import TextContent+from pipelex.errors.problem import PipelexProblem, ProblemView, caller_view_offrom pipelex.graph.graphspec import GraphSpec, PipelineReffrom pipelex.interpreter_hub import get_concept_library, get_current_library_id_or_none, get_library_manager, scoped_current_libraryfrom pipelex.pipe_run import delivery_executor as delivery_executor_module@@ -44,6 +45,7 @@ from pipelex.pipe_run.exceptions import PipeJobError, StorageDeliveryError, Webhfrom pipelex.system.job_metadata import JobMetadata, RunMetadatafrom pipelex.tools.network.exceptions import SsrfBlockedErrorfrom tests.helpers.pipe_io_artifacts import make_pipe_io_artifacts+from tests.unit.pipelex.errors.test_data import ProblemViewsTestDatadef _records_with_message(*, caplog: pytest.LogCaptureFixture, message: str) -> list[logging.LogRecord]:@@ -62,6 +64,22 @@ def _mock_webhook_client(mocker: MockerFixture) -> None:mocker.patch("pipelex.pipe_run.delivery_executor.httpx.AsyncClient", return_value=mock_client)+def _make_failed_run_problem() -> PipelexProblem:+ """A failed run's problem in the operator's view: a provider rate limit, with the provider's own answer among its diagnostics."""+ error = LLMCompletionError(+ message="provider returned 429",+ error_category=InferenceErrorCategory.TRANSIENT,+ provider_metadata=ProviderErrorMetadata(+ provider=ProviderName.OPENAI,+ sdk_exception_type="RateLimitError",+ message="429 Too Many Requests",+ status_code=429,+ retry_after_seconds=2.5,+ ),+ ).with_error_code(CoreCode.PROVIDER_RATE_LIMITED)+ return error.to_problem(view=ProblemView.OPERATOR, pipeline_run_id="plr-failed")++def _make_main_stuff() -> Stuff:return Stuff(stuff_code="main-code",@@ -872,8 +890,12 @@ class TestDeliveryExecutor:assert "Page 1 contents" in json_textassert "https://example.com/img.png" in json_text- async def test_webhook_includes_error_report_on_failed_status(self, mocker: MockerFixture) -> None:- """A FAILED delivery with an ``ErrorReport`` includes a VERBOSE ``error`` dict the receiver can rehydrate."""+ @pytest.mark.parametrize("problem_view", [ProblemView.OPERATOR, ProblemView.CALLER])+ async def test_webhook_includes_the_problem_in_its_own_view_on_failed_status(self, mocker: MockerFixture, problem_view: ProblemView) -> None:+ """A FAILED delivery sends the run's problem in the webhook's own view, which the receiver can rehydrate.++ The operator's webhook reads the diagnostics, the provider's own message among them; a caller's never does.+ """mock_client = mocker.AsyncMock()mock_response = mocker.MagicMock()mock_response.raise_for_status = mocker.Mock()@@ -882,28 +904,10 @@ 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.make_for_code(- code=CoreCode.PROVIDER_RATE_LIMITED,- error_type="LLMCompletionError",- message="provider returned 429",- user_action=UserAction(kind=UserActionKind.WAIT_AND_RETRY, detail="Wait a moment and retry"),- ).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,- ),- }- )+ problem = _make_failed_run_problem()executor = DeliveryExecutor()- assignment = DeliveryAssignment(webhooks=[WebhookTarget(url="https://example.com/callback")])+ assignment = DeliveryAssignment(webhooks=[WebhookTarget(url="https://example.com/callback", problem_view=problem_view)])await executor.execute(pipe_output=None,@@ -911,17 +915,66 @@ class TestDeliveryExecutor:pipeline_run_id="plr-failed",delivery_assignment=assignment,status=DeliveryStatus.FAILED,- error_report=error_report,+ problem=problem,)payload = mock_client.post.call_args.kwargs["json"]assert payload["status"] == DeliveryStatus.FAILED- assert "error" in payload, "FAILED webhook must include the structured error report"- rehydrated = ErrorReport.from_dict(payload["error"])- assert rehydrated == error_report, "VERBOSE payload must round-trip through from_dict"+ assert "error" in payload, "FAILED webhook must include the run's problem"+ rehydrated = PipelexProblem.model_validate(payload["error"])+ assert rehydrated.code == CoreCode.PROVIDER_RATE_LIMITED+ assert rehydrated.retry_after == 2.5+ match problem_view:+ case ProblemView.OPERATOR:+ assert rehydrated == problem, "the operator's payload must round-trip to the problem itself"+ assert rehydrated.diagnostics is not None+ assert rehydrated.diagnostics.message == "provider returned 429"+ case ProblemView.CALLER:+ assert rehydrated == caller_view_of(problem=problem)+ assert rehydrated.diagnostics is None+ assert "provider returned 429" not in json.dumps(payload["error"])+ assert "429 Too Many Requests" not in json.dumps(payload["error"])++ async def test_caller_webhooks_share_one_projection_that_fails_closed_on_an_unknown_code(self, mocker: MockerFixture) -> None:+ """Every caller webhook reads one caller view, built once, and a code this process does not know keeps no operator step."""+ mock_client = mocker.AsyncMock()+ mock_response = mocker.MagicMock()+ mock_response.raise_for_status = mocker.Mock()+ mock_client.__aenter__ = mocker.AsyncMock(return_value=mock_client)+ mock_client.__aexit__ = mocker.AsyncMock(return_value=False)+ mock_client.post = mocker.AsyncMock(return_value=mock_response)+ mocker.patch("pipelex.pipe_run.delivery_executor.httpx.AsyncClient", return_value=mock_client)+ projection_spy = mocker.spy(delivery_executor_module, "caller_view_of")++ problem = PipelexProblem.model_validate(ProblemViewsTestData.UNKNOWN_OPERATOR_PROBLEM)+ assignment = DeliveryAssignment(+ webhooks=[+ WebhookTarget(url="https://example.com/first", problem_view=ProblemView.CALLER),+ WebhookTarget(url="https://example.com/second", problem_view=ProblemView.CALLER),+ WebhookTarget(url="https://example.com/operator", problem_view=ProblemView.OPERATOR),+ ]+ )- async def test_webhook_omits_error_when_report_is_none(self, mocker: MockerFixture) -> None:- """A completed delivery (no report) must not introduce an ``error`` field in the payload."""+ await DeliveryExecutor().execute(+ pipe_output=None,+ storage_scope="test-user",+ pipeline_run_id="plr-failed",+ delivery_assignment=assignment,+ status=DeliveryStatus.FAILED,+ problem=problem,+ )++ assert projection_spy.call_count == 1+ errors_by_url = {call.args[0] if call.args else call.kwargs["url"]: call.kwargs["json"]["error"] for call in mock_client.post.call_args_list}+ for caller_url in ("https://example.com/first", "https://example.com/second"):+ caller_error = errors_by_url[caller_url]+ assert caller_error["next_step"] == {"kind": "report", "detail": "Report this problem with its request id."}+ assert "diagnostics" not in caller_error+ assert ProblemViewsTestData.PRIVATE_HOST_FILE not in json.dumps(caller_error)+ assert errors_by_url["https://example.com/operator"] == problem.to_wire()++ async def test_webhook_omits_error_when_problem_is_none(self, mocker: MockerFixture) -> None:+ """A completed delivery (no problem) must not introduce an ``error`` field in the payload."""mock_client = mocker.AsyncMock()mock_response = mocker.MagicMock()mock_response.raise_for_status = mocker.Mock()@@ -945,13 +998,13 @@ class TestDeliveryExecutor:assert payload["status"] == DeliveryStatus.COMPLETEDassert "error" not in payload- async def test_webhook_omits_error_when_failed_status_with_none_report(self, mocker: MockerFixture) -> None:- """A FAILED delivery with ``error_report=None`` must not introduce an ``error`` field in the payload.+ async def test_webhook_omits_error_when_failed_status_with_none_problem(self, mocker: MockerFixture) -> None:+ """A FAILED delivery with ``problem=None`` must not introduce an ``error`` field in the payload.- The COMPLETED case is pinned by ``test_webhook_omits_error_when_report_is_none``,+ The COMPLETED case is pinned by ``test_webhook_omits_error_when_problem_is_none``,but the FAILED case is not — a future regression defaulting ``error`` to ``{}``on FAILED would slip through. ``_notify_webhook`` only writes- ``payload["error"]`` when ``error_report is not None``, regardless of status.+ ``payload["error"]`` when ``problem is not None``, regardless of status."""mock_client = mocker.AsyncMock()mock_response = mocker.MagicMock()@@ -967,10 +1020,10 @@ class TestDeliveryExecutor:await executor.execute(pipe_output=None,storage_scope="test-user",- pipeline_run_id="plr-failed-no-report",+ pipeline_run_id="plr-failed-no-problem",delivery_assignment=assignment,status=DeliveryStatus.FAILED,- error_report=None,+ problem=None,)payload = mock_client.post.call_args.kwargs["json"]@@ -1010,23 +1063,16 @@ class TestDeliveryExecutor:assert vars(record)["file_count"] > 0@pytest.mark.parametrize(- ("status", "error_report"),+ ("status", "has_problem"),[- (DeliveryStatus.COMPLETED, None),- (- DeliveryStatus.FAILED,- ErrorReport.make_for_code(- code=CoreCode.PROVIDER_RATE_LIMITED,- error_type="LLMCompletionError",- message="provider returned 429",- ).model_copy(update={"error_category": "transient"}),- ),+ (DeliveryStatus.COMPLETED, False),+ (DeliveryStatus.FAILED, True),],)async def test_the_webhook_completion_line_names_the_run_and_the_receiver_host(- self, mocker: MockerFixture, caplog: pytest.LogCaptureFixture, status: DeliveryStatus, error_report: ErrorReport | None+ self, mocker: MockerFixture, caplog: pytest.LogCaptureFixture, status: DeliveryStatus, has_problem: bool) -> None:- """The webhook line carries the run's identifiers from the context, on a failed run with its error report as on a+ """The webhook line carries the run's identifiers from the context, on a failed run with its problem as on acompleted one, and names the receiver by its host alone: the URL is the caller's, and its path or query may carrya credential."""@@ -1040,7 +1086,7 @@ class TestDeliveryExecutor:pipeline_run_id="plr-webhook-req",delivery_assignment=DeliveryAssignment(webhooks=[WebhookTarget(url=webhook_url)]),status=status,- error_report=error_report,+ problem=_make_failed_run_problem() if has_problem else None,request_id="req-xyz-789",)diff --git a/tests/unit/pipelex/pipe_run/test_located_failure.py b/tests/unit/pipelex/pipe_run/test_located_failure.pyindex 8270f7787..c95b0d86a 100644--- a/tests/unit/pipelex/pipe_run/test_located_failure.py+++ b/tests/unit/pipelex/pipe_run/test_located_failure.py@@ -1,15 +1,21 @@from __future__ import annotations+import logging+import pytest-from mthds.protocol.problem.registry import CoreCode+from mthds.protocol.problem.registry import CoreCode, StepKindfrom typing_extensions import override-from pipelex.base_exceptions import INTERNAL_ERROR_PLACEHOLDER, DisclosureMode, ErrorDomain, ErrorReport, PipelexError-from pipelex.cogt.exceptions import CogtError, InferenceErrorCategory, LLMCompletionError-from pipelex.cogt.inference.error_classification import UserAction, UserActionKind+from pipelex.base_exceptions import PipelexError+from pipelex.cogt.exceptions import CogtError, InferenceErrorCategory, LLMCompletionError, ModelChoiceNotFoundError+from pipelex.cogt.inference.error_classification import ProviderErrorMetadata+from pipelex.cogt.inference.provider_name import ProviderName+from pipelex.cogt.model_backends.model_type import ModelTypefrom pipelex.core.memory.absence import AbsenceKind, AbsenceRecord+from pipelex.core.pipes.exceptions import PipeOperatorModelChoiceError, PipeRunErrorfrom pipelex.core.pipes.inputs.exceptions import OptionalValueAbsentErrorfrom pipelex.errors.error_codes import error_code_spec+from pipelex.errors.problem import PipelexProblem, ProblemView, caller_view_of, make_location, make_problem_itemfrom 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@@ -17,16 +23,16 @@ from pipelex.runtime_bridge.exceptions import PipelexBridgeDispatchErrorfrom pipelex.system.pipe_run_mode import PipeRunMode-class _RecoveredReportError(PipelexError):- """Carries a report recovered across a transport boundary, and reports it as it is."""+class _RecoveredProblemError(PipelexError):+ """Carries a problem recovered across a transport boundary, which it reports as it is, located where it is told."""- def __init__(self, message: str, *, error_report: ErrorReport):+ def __init__(self, message: str, *, problem: PipelexProblem):super().__init__(message)- self.error_report = error_report+ self.carried_problem = problem@override- def to_error_report(self) -> ErrorReport:- return self.error_report+ def recovered_problem(self) -> PipelexProblem | None:+ return self.carried_problemdef _locate(failure: PipelexError, *, pipe_stack: list[str]) -> PipeRouterError:@@ -62,7 +68,7 @@ def _make_absence_error() -> OptionalValueAbsentError:)-class TestLocatedFailureReport:+class TestLocatedFailureProblem:@pytest.mark.parametrize(("pipe_stack", "expected_message"),[@@ -94,7 +100,11 @@ class TestLocatedFailureReport:assert find_root_fault(error=located) is unexpected_failureassert find_foreign_fault(error=located) is foreign_fault- assert located.to_error_report().error_type == "PipelexUnexpectedError"+ problem = located.to_problem(view=ProblemView.OPERATOR)+ assert problem.code == CoreCode.RUNTIME_UNEXPECTED+ assert problem.diagnostics is not None+ assert problem.diagnostics.error_class == "PipelexUnexpectedError"+ assert "boom" not in str(located.to_problem(view=ProblemView.CALLER).to_wire())def test_a_same_class_rethrow_keeps_its_added_context(self) -> None:"""An error raised from one of its own class restates the fault with context: the outer one is reported."""@@ -104,10 +114,13 @@ class TestLocatedFailureReport:located = _locate(with_remedy, pipe_stack=["flow", "draw"])assert find_root_fault(error=located) is with_remedy- assert located.to_error_report().message == "Pipe 'draw' failed (flow → draw): Size tier '4k' is not satisfiable: use '1k' or '2k'"+ assert located.message == "Pipe 'draw' failed (flow → draw): Size tier '4k' is not satisfiable: use '1k' or '2k'"+ problem = located.to_problem(view=ProblemView.OPERATOR)+ assert problem.diagnostics is not None+ assert problem.diagnostics.message == "Size tier '4k' is not satisfiable: use '1k' or '2k'"- 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."""+ def test_the_problem_is_the_root_faults_located_at_the_failing_pipe(self) -> None:+ """Through the router, a bridge and the runner, the problem is the root fault's, located once at the innermost pipe."""root_fault = LLMCompletionError(message="rate limited", error_category=InferenceErrorCategory.TRANSIENT).with_error_code(CoreCode.PROVIDER_RATE_LIMITED)@@ -120,88 +133,220 @@ class TestLocatedFailureReport:assert find_failure_location(error=run_failure) is locatedassert run_failure.pipe_code == "gen_ideas"assert run_failure.pipe_stack == ["flow", "analyze", "gen_ideas"]-- report = run_failure.to_error_report()- 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_uri- assert report.message == "Pipe 'gen_ideas' failed (flow → analyze → gen_ideas): rate limited"- assert run_failure.message == report.message- # Classification inherited from the chain, and the retry verdict the root fault's code decides.- assert report.error_category == InferenceErrorCategory.TRANSIENT- assert report.retryable is True- assert report == located.to_error_report()-- def test_caller_facing_flag_is_the_root_faults(self) -> None:- """A caller-facing root keeps its located message under STRICT; the wrapper grants nothing of its own."""- report = _wrap_in_runner(- _locate(_make_absence_error(), pipe_stack=["force_flow", "force_echo"]), entry_pipe_code="force_flow"- ).to_error_report()-- assert report.caller_facing_message is True- strict_payload = report.to_dict(disclosure_mode=DisclosureMode.STRICT)- assert strict_payload["message"] == report.message- assert strict_payload["message"].startswith("Pipe 'force_echo' failed (force_flow → force_echo): ")- assert strict_payload["user_action"]["kind"] == UserActionKind.CHANGE_INPUT-- def test_a_bridge_sentence_is_never_caller_facing(self) -> None:- """A bridge error with no PipelexError under it reports as itself, and stays redacted under STRICT."""+ assert run_failure.message == "Pipe 'gen_ideas' failed (flow → analyze → gen_ideas): rate limited"++ for view in ProblemView:+ problem = run_failure.to_problem(view=view, pipeline_run_id="run-1")+ root_spec = error_code_spec(CoreCode.PROVIDER_RATE_LIMITED)+ assert problem.code == root_spec.code+ assert problem.title == root_spec.title+ assert problem.type == root_spec.type_uri+ assert problem.is_retryable is True+ assert problem.location is not None+ assert problem.location.pipe == "gen_ideas"+ assert problem.location.path == ["flow", "analyze", "gen_ideas"]+ assert problem.pipeline_run_id == "run-1"+ assert problem.to_wire() == located.to_problem(view=view, pipeline_run_id="run-1").to_wire()+ operator = run_failure.to_problem(view=ProblemView.OPERATOR)+ assert operator.diagnostics is not None+ assert operator.diagnostics.error_class == "LLMCompletionError"+ assert operator.diagnostics.message == "rate limited"++ def test_the_location_names_the_pipe_and_its_path_in_the_caller_view(self) -> None:+ """The caller reads where its run failed as members, never only inside the detail: they are its own pipe codes."""+ run_failure = _wrap_in_runner(_locate(_make_absence_error(), pipe_stack=["force_flow", "force_echo"]), entry_pipe_code="force_flow")++ caller = run_failure.to_problem(view=ProblemView.CALLER)++ assert caller.code == CoreCode.PIPE_FORCED_INPUT_ABSENT+ assert caller.location is not None+ assert caller.location.as_wire() == {"pipe": "force_echo", "path": ["force_flow", "force_echo"]}+ assert caller.params is not None+ assert caller.params.as_wire() == {"pipe": "force_echo", "variable": "clause"}+ assert caller.detail == "Pipe 'force_echo' forces 'clause' with '!', and it was absent in this run."+ assert caller.next_step.kind == StepKind.CHANGE_METHOD+ assert caller.diagnostics is None++ def test_an_entry_pipe_failure_has_no_location(self) -> None:+ """A failure no router located has no path, so its problem holds no location rather than an empty one."""+ run_failure = _wrap_in_runner(PipelexError("combine failed"), entry_pipe_code="flow")++ problem = run_failure.to_problem(view=ProblemView.CALLER)++ assert problem.location is None+ assert "location" not in problem.to_wire()++ def test_a_bridge_sentence_never_reaches_the_caller(self) -> None:+ """A bridge error with no PipelexError under it reports as itself, its sentence the operator's alone."""bridge_error = PipelexBridgeDispatchError("Pipe execution failed in DIRECT mode for pipe 'flow': internal detail")- report = _wrap_in_runner(bridge_error, entry_pipe_code="flow").to_error_report()-- assert report.error_type == "PipelexBridgeDispatchError"- assert report.caller_facing_message is False- assert report.to_dict(disclosure_mode=DisclosureMode.STRICT)["message"] == INTERNAL_ERROR_PLACEHOLDER-- def test_floor_and_fallback_apply_only_when_the_chain_is_silent(self) -> None:- """No domain and no action on the chain: RUNTIME, and a fallback naming the failing pipe."""- report = _locate(PipelexError("combine failed"), pipe_stack=["flow", "analyze"]).to_error_report()-- assert report.error_domain == ErrorDomain.RUNTIME- assert report.user_action == UserAction(kind=UserActionKind.UNKNOWN, detail="The run failed in pipe 'analyze': the message gives the cause.")+ run_failure = _wrap_in_runner(bridge_error, entry_pipe_code="flow")- def test_a_categorized_action_is_kept(self) -> None:- root_fault = CogtError(- message="quota exceeded",- error_category=InferenceErrorCategory.CAPACITY,- user_action=UserAction(kind=UserActionKind.CHECK_BILLING, detail="Check your billing"),- )- report = _locate(root_fault, pipe_stack=["flow"]).to_error_report()+ caller = run_failure.to_problem(view=ProblemView.CALLER)+ operator = run_failure.to_problem(view=ProblemView.OPERATOR)- assert report.user_action == UserAction(kind=UserActionKind.CHECK_BILLING, detail="Check your billing")+ assert "internal detail" not in str(caller.to_wire())+ assert operator.diagnostics is not None+ assert operator.diagnostics.error_class == "PipelexBridgeDispatchError"- def test_a_recovered_report_is_taken_as_it_is(self) -> None:- """A report recovered across a boundary already names its pipe: the runner does not locate it again."""- recovered_report = _locate(PipelexError("combine failed"), pipe_stack=["flow", "analyze"]).to_error_report()- recovered = _RecoveredReportError(recovered_report.message, error_report=recovered_report)+ def test_a_recovered_problem_is_taken_as_it_is(self) -> None:+ """A problem recovered across a boundary already names its pipe: the runner does not locate it again."""+ recovered_problem = _locate(PipelexError("combine failed"), pipe_stack=["flow", "analyze"]).to_problem(view=ProblemView.OPERATOR)+ recovered = _RecoveredProblemError("combine failed", problem=recovered_problem)bridge_error = PipelexBridgeDispatchError(f"Pipe execution failed in temporal blocking delivery for pipe 'flow': {recovered}")bridge_error.__cause__ = recoveredrun_failure = _wrap_in_runner(bridge_error, entry_pipe_code="flow")assert run_failure.pipe_code == "flow"assert run_failure.pipe_stack == []- assert run_failure.message == recovered_report.message- assert run_failure.to_error_report() == recovered_report+ assert run_failure.to_problem(view=ProblemView.OPERATOR).to_wire() == recovered_problem.to_wire()+ assert run_failure.to_problem(view=ProblemView.CALLER).to_wire() == caller_view_of(problem=recovered_problem).to_wire()++ def test_a_recovered_leaf_problem_is_located_by_the_router(self) -> None:+ """A PipelexError carrying a leaf's recovered problem is located with the leaf's identity."""+ leaf_problem = CogtError(message="model refused", error_category=InferenceErrorCategory.CONFIGURATION).to_problem(view=ProblemView.OPERATOR)+ located = _locate(_RecoveredProblemError("model refused", problem=leaf_problem), pipe_stack=["flow", "summarize"])++ problem = located.to_problem(view=ProblemView.OPERATOR)++ assert problem.code == leaf_problem.code+ assert problem.domain == leaf_problem.domain+ assert problem.diagnostics == leaf_problem.diagnostics+ assert problem.location is not None+ assert problem.location.as_wire() == {"pipe": "summarize", "path": ["flow", "summarize"]}++ def test_a_wrapper_attributing_its_coded_cause_reaches_the_run_problem(self) -> None:+ """A worker fills the model and the backend on a wrapper that takes its cause's code: the run's problem names both."""+ provider_refusal = LLMCompletionError(+ message="429 from the provider",+ error_category=InferenceErrorCategory.TRANSIENT,+ provider_metadata=ProviderErrorMetadata(+ provider=ProviderName.OPENAI, sdk_exception_type="RateLimitError", status_code=429, retry_after_seconds=7.0, request_id="req_abc"+ ),+ ).with_error_code(CoreCode.PROVIDER_RATE_LIMITED)+ attributed = LLMCompletionError(message="the completion failed")+ attributed.__cause__ = provider_refusal+ attributed.fill_model_and_provider("gpt-4o-mini", backend_name="openai")+ run_failure = _wrap_in_runner(_locate(attributed, pipe_stack=["flow", "summarize"]), entry_pipe_code="flow")++ operator = run_failure.to_problem(view=ProblemView.OPERATOR)+ caller = run_failure.to_problem(view=ProblemView.CALLER)++ assert operator.code == CoreCode.PROVIDER_RATE_LIMITED+ assert operator.diagnostics is not None+ assert operator.diagnostics.error_class == "LLMCompletionError"+ assert operator.diagnostics.message == "429 from the provider"+ assert operator.diagnostics.model == "gpt-4o-mini"+ assert operator.diagnostics.provider is not None+ # The wrapper names the backend, and the cause keeps what the provider answered.+ assert operator.diagnostics.provider.name == "openai"+ assert operator.diagnostics.provider.status == 429+ assert operator.diagnostics.provider.request_id == "req_abc"+ assert operator.retry_after == 7.0+ assert caller.detail == "The provider 'openai' is rate limiting this deployment's calls to the model 'gpt-4o-mini'."+ assert caller.retry_after == 7.0++ def test_a_wrapper_locating_its_coded_cause_keeps_its_location(self) -> None:+ """A pipe's refusal of an unknown model is located on the pipe, the field and the file, run or no run."""+ deck_refusal = ModelChoiceNotFoundError("no model 'gpt-9' in the deck", model_type=ModelType.LLM, model_choice="gpt-9")+ located_refusal = PipeOperatorModelChoiceError.make_from_model_choice_not_found(+ model_choice_error=deck_refusal, pipe_type="PipeLLM", pipe_code="summarize", domain_code="docs", field_name="model"+ )+ located_refusal.source = "docs.mthds"+ located_refusal.__cause__ = deck_refusal- def test_a_recovered_leaf_report_is_located_by_the_router(self) -> None:- """A PipelexError carrying a leaf's recovered report is located with the leaf's identity."""- leaf_report = CogtError(message="model refused", error_category=InferenceErrorCategory.CONFIGURATION).to_error_report()- report = _locate(_RecoveredReportError(leaf_report.message, error_report=leaf_report), pipe_stack=["flow", "summarize"]).to_error_report()+ problem = located_refusal.to_problem(view=ProblemView.CALLER)+ assert problem.code == CoreCode.MODEL_UNKNOWN+ assert problem.location is not None+ assert problem.location.as_wire() == {"pipe": "summarize", "field": "model", "file": "docs.mthds"}- assert report.error_type == "CogtError"- assert report.message == "Pipe 'summarize' failed (flow → summarize): model refused"- assert report.code == leaf_report.code- assert report.error_domain == leaf_report.error_domain+ run_problem = _wrap_in_runner(_locate(located_refusal, pipe_stack=["flow", "summarize"]), entry_pipe_code="flow").to_problem(+ view=ProblemView.CALLER+ )+ assert run_problem.location is not None+ assert run_problem.location.as_wire() == {"pipe": "summarize", "path": ["flow", "summarize"], "field": "model", "file": "docs.mthds"}def test_a_cyclic_chain_reports_the_wrapper_as_itself(self) -> None:- """A chain that loops back to the wrapper cannot make the report recurse."""+ """A chain that loops back to the wrapper cannot make the problem recurse."""root_fault = PipelexError("combine failed")located = _locate(root_fault, pipe_stack=["flow"])root_fault.__cause__ = located- report = located.to_error_report()+ problem = located.to_problem(view=ProblemView.OPERATOR)++ assert problem.diagnostics is not None+ assert problem.diagnostics.error_class == "PipeRouterError"+ assert problem.diagnostics.message.endswith("combine failed")++ def test_what_the_wrappers_above_a_coded_cause_give_reaches_its_problem(self, caplog: pytest.LogCaptureFixture) -> None:+ """A wrapper fills a parameter its coded cause did not give, the nearest one winning, and its items follow the cause's."""+ carrier = (+ PipeRunError("the template does not parse", run_mode=PipeRunMode.LIVE, pipe_code="summarize")+ .with_error_code(CoreCode.METHOD_TEMPLATE_INVALID)+ .with_params(template="prompt")+ .with_items(items=[make_problem_item(code=CoreCode.METHOD_TEMPLATE_INVALID, location=make_location(pipe="carrier"))])+ )+ wrapper = PipeRunError("summarize failed", run_mode=PipeRunMode.LIVE, pipe_code="summarize").with_params(+ finding="unexpected '}'", variable="clause"+ )+ wrapper.__cause__ = carrier+ located = (+ _locate(wrapper, pipe_stack=["flow", "summarize"])+ .with_params(finding="overridden by the wrapper nearer the cause")+ .with_items(items=[make_problem_item(code=CoreCode.METHOD_TEMPLATE_INVALID, location=make_location(pipe="router"))])+ )+ run_failure = _wrap_in_runner(located, entry_pipe_code="flow").with_items(+ items=[make_problem_item(code=CoreCode.METHOD_TEMPLATE_INVALID, location=make_location(pipe="runner"))]+ )- assert report.error_type == "PipeRouterError"- assert report.message.endswith("combine failed")+ with caplog.at_level(logging.WARNING, logger="pipelex.errors.problem"):+ caller = run_failure.to_problem(view=ProblemView.CALLER)++ assert caller.code == CoreCode.METHOD_TEMPLATE_INVALID+ assert caller.params is not None+ assert caller.params.as_wire() == {"template": "prompt", "finding": "unexpected '}'", "pipe": "summarize"}+ assert caller.detail == "The template 'prompt' of pipe 'summarize' is invalid (unexpected '}')."+ assert [item.location.pipe for item in caller.errors or [] if item.location is not None] == ["carrier", "router", "runner"]+ # `variable` is no parameter of the cause's code: it is dropped, and the raise site that gave it is logged.+ assert any(record.getMessage() == "An error gives a parameter its code does not declare" for record in caplog.records)+ # The wrapper reporting itself reads the same parameters as the run does.+ assert wrapper.to_problem(view=ProblemView.CALLER).params == caller.params++ def test_a_located_wrapper_over_a_foreign_exception_keeps_the_facts_above_it(self) -> None:+ """An inner router standing for a foreign exception is no carrier of a recovered problem: the runner reports it with the facts above it."""+ foreign_fault = ConnectionError("socket closed")+ inner_router = PipeRouterError(+ message="Pipe 'summarize' failed: socket closed",+ run_mode=PipeRunMode.LIVE,+ pipe_code="summarize",+ output_name=None,+ pipe_stack=["flow", "summarize"],+ )+ inner_router.__cause__ = foreign_fault+ attributed = LLMCompletionError(message="the completion failed")+ attributed.__cause__ = inner_router+ attributed.fill_model_and_provider("gpt-4o-mini", backend_name="openai")+ run_failure = _wrap_in_runner(attributed, entry_pipe_code="flow")++ assert find_root_fault(error=run_failure) is inner_router+ assert inner_router.recovered_problem() is None+ operator = run_failure.to_problem(view=ProblemView.OPERATOR)++ assert operator.code == CoreCode.RUNTIME_UNEXPECTED+ assert operator.diagnostics is not None+ assert operator.diagnostics.error_class == "PipeRouterError"+ assert operator.diagnostics.model == "gpt-4o-mini"+ assert operator.diagnostics.provider is not None+ assert operator.diagnostics.provider.name == "openai"+ assert operator.location is not None+ assert operator.location.as_wire() == {"pipe": "summarize", "path": ["flow", "summarize"]}++ def test_a_carrier_reports_its_problem_with_the_request_and_the_run_it_is_handed(self) -> None:+ """The hook alone makes a carrier: its problem is reported as it is, filling only the members it does not hold."""+ leaf_problem = CogtError(message="model refused", error_category=InferenceErrorCategory.CONFIGURATION).to_problem(view=ProblemView.OPERATOR)+ carrier = _RecoveredProblemError("model refused", problem=leaf_problem)++ operator = carrier.to_problem(view=ProblemView.OPERATOR, request_id="req-1", pipeline_run_id="run-1")+ caller = carrier.to_problem(view=ProblemView.CALLER, request_id="req-1")++ assert operator.to_wire() == {**leaf_problem.to_wire(), "request_id": "req-1", "pipeline_run_id": "run-1"}+ assert caller.to_wire() == caller_view_of(problem=leaf_problem.model_copy(update={"request_id": "req-1"})).to_wire()diff --git a/tests/unit/pipelex/pipe_run/test_pipe_router_run.py b/tests/unit/pipelex/pipe_run/test_pipe_router_run.pyindex addbfd1b3..7c2a0a481 100644--- a/tests/unit/pipelex/pipe_run/test_pipe_router_run.py+++ b/tests/unit/pipelex/pipe_run/test_pipe_router_run.py@@ -5,11 +5,12 @@ from mthds.protocol.problem.registry import CoreCodefrom pydantic import BaseModel, ValidationErrorfrom typing_extensions import override-from pipelex.base_exceptions import ErrorReport, PipelexError, PipelexUnexpectedError+from pipelex.base_exceptions import PipelexError, PipelexUnexpectedErrorfrom 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+from pipelex.errors.problem import PipelexProblem, ProblemViewfrom pipelex.observer.observer_protocol import ObserverNoOpfrom pipelex.pipe_run.exceptions import PipeRouterErrorfrom pipelex.pipe_run.pipe_job import PipeJob@@ -53,30 +54,31 @@ class _PassThroughRouter(_StubPipeRouter):return super()._as_pipelex_failure(error=error)-class _RecoveredReportCarrierError(PipelexError):- """Carries a root fault's report recovered across a transport boundary."""+class _RecoveredProblemCarrierError(PipelexError):+ """Carries a root fault's problem recovered across a transport boundary, located where it is told."""- def __init__(self, message: str, *, error_report: ErrorReport):+ def __init__(self, message: str, *, problem: PipelexProblem):super().__init__(message)- self.error_report = error_report+ self.carried_problem = problem@override- def to_error_report(self) -> ErrorReport:- return self.error_report+ def recovered_problem(self) -> PipelexProblem | None:+ return self.carried_problemclass _RelocatingHostRouter(_StubPipeRouter):- """A host router whose transport packed the root fault's report and the location found on the far side."""+ """A host router whose transport packed the root fault's problem and the location found on the far side."""- def __init__(self, error: Exception, *, packed_report: ErrorReport, packed_pipe_code: str, packed_pipe_stack: list[str]):+ def __init__(self, error: Exception, *, packed_problem: PipelexProblem, packed_message: str, packed_pipe_code: str, packed_pipe_stack: list[str]):super().__init__(error=error)- self._packed_report = packed_report+ self._packed_problem = packed_problem+ self._packed_message = packed_messageself._packed_pipe_code = packed_pipe_codeself._packed_pipe_stack = packed_pipe_stack@overridedef _as_pipelex_failure(self, *, error: Exception) -> PipelexError | None:- carrier = _RecoveredReportCarrierError(self._packed_report.message, error_report=self._packed_report)+ carrier = _RecoveredProblemCarrierError(self._packed_message, problem=self._packed_problem)located = PipeRouterError.make_located(failure=carrier, run_mode=PipeRunMode.LIVE, pipe_code=self._packed_pipe_code, output_name=None, pipe_stack=self._packed_pipe_stack)@@ -110,7 +112,7 @@ class TestPipeRouterRun:"""Direct execution is a single pipeline-level attempt: a transient CogtError is not retried.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.+ The error leaves located at the pipe, chained to the CogtError, and its problem is still the CogtError's."""error = LLMCompletionError(message="rate limited", error_category=InferenceErrorCategory.TRANSIENT).with_error_code(CoreCode.PROVIDER_RATE_LIMITED@@ -121,10 +123,11 @@ class TestPipeRouterRun:await router.run(_make_pipe_job())assert exc_info.value.__cause__ is error- report = exc_info.value.to_error_report()- assert report.error_type == "LLMCompletionError"- assert report.code == CoreCode.PROVIDER_RATE_LIMITED- assert report.retryable is True+ problem = exc_info.value.to_problem(view=ProblemView.OPERATOR)+ assert problem.diagnostics is not None+ assert problem.diagnostics.error_class == "LLMCompletionError"+ assert problem.code == CoreCode.PROVIDER_RATE_LIMITED+ assert problem.is_retryable is Trueassert router.call_count == 1async def test_pipe_run_error_wraps_as_pipe_router_error(self) -> None:@@ -144,8 +147,8 @@ class TestPipeRouterRun:assert exc_info.value.pipe_stack == ["stub_pipe"]assert router.call_count == 1- async def test_any_pipelex_error_is_located_with_its_own_report(self) -> None:- """A PipelexError that is neither a CogtError nor a PipeRunError is located too, and reports as itself."""+ async def test_any_pipelex_error_is_located_with_its_own_problem(self) -> None:+ """A PipelexError that is neither a CogtError nor a PipeRunError is located too, and its problem is its own."""stuff_error = StuffFactoryError("Error combining stuffs")router = _StubPipeRouter(error=stuff_error)@@ -157,12 +160,16 @@ class TestPipeRouterRun:assert located.pipe_code == "stub_pipe"assert located.pipe_stack == ["stub_pipe"]assert located.message == "Pipe 'stub_pipe' failed: Error combining stuffs"- report = located.to_error_report()- assert report.error_type == "StuffFactoryError"- assert report.message == "Pipe 'stub_pipe' failed: Error combining stuffs"+ problem = located.to_problem(view=ProblemView.OPERATOR)+ assert problem.code == stuff_error.resolve_error_code()+ assert problem.location is not None+ assert problem.location.as_wire() == {"pipe": "stub_pipe", "path": ["stub_pipe"]}+ assert problem.diagnostics is not None+ assert problem.diagnostics.error_class == "StuffFactoryError"+ assert problem.diagnostics.message == "Error combining stuffs"async def test_foreign_exception_is_located_as_unexpected_error(self) -> None:- """A non-PipelexError is wrapped into a PipelexUnexpectedError naming its class, never caller-facing."""+ """A non-PipelexError is wrapped into a PipelexUnexpectedError naming its class, a fault of ours the caller never reads."""foreign_error = ValueError("unexpected value")router = _StubPipeRouter(error=foreign_error)@@ -173,10 +180,13 @@ class TestPipeRouterRun:assert isinstance(unexpected, PipelexUnexpectedError)assert unexpected.__cause__ is foreign_errorassert unexpected.message == "ValueError: unexpected value"- report = exc_info.value.to_error_report()- assert report.error_type == "PipelexUnexpectedError"- assert report.message == "Pipe 'stub_pipe' failed: ValueError: unexpected value"- assert report.caller_facing_message is False+ assert exc_info.value.message == "Pipe 'stub_pipe' failed: ValueError: unexpected value"+ operator = exc_info.value.to_problem(view=ProblemView.OPERATOR)+ assert operator.code == CoreCode.RUNTIME_UNEXPECTED+ assert operator.diagnostics is not None+ assert operator.diagnostics.error_class == "PipelexUnexpectedError"+ assert operator.diagnostics.message == "ValueError: unexpected value"+ assert "unexpected value" not in str(exc_info.value.to_problem(view=ProblemView.CALLER).to_wire())async def test_pydantic_validation_error_keeps_its_readable_rendering(self) -> None:"""A pydantic ValidationError is named and rendered the way the runner renders one."""@@ -208,11 +218,12 @@ class TestPipeRouterRun:assert exc_info.value is inner_failureasync def test_a_host_router_rebuilding_the_far_location_is_not_located_again(self) -> None:- """A located failure the hook rebuilds from a packed report and location passes through, located once."""- root_report = CogtError(message="rate limited", error_category=InferenceErrorCategory.TRANSIENT).to_error_report()+ """A located failure the hook rebuilds from a packed problem and location passes through, located once."""+ root_problem = CogtError(message="rate limited", error_category=InferenceErrorCategory.TRANSIENT).to_problem(view=ProblemView.OPERATOR)router = _RelocatingHostRouter(error=RuntimeError("child workflow failed"),- packed_report=root_report,+ packed_problem=root_problem,+ packed_message="rate limited",packed_pipe_code="leaf",packed_pipe_stack=["flow", "ctrl", "leaf"],)@@ -221,10 +232,13 @@ class TestPipeRouterRun:await router.run(_make_pipe_job())assert exc_info.value.pipe_code == "leaf"- assert isinstance(exc_info.value.__cause__, _RecoveredReportCarrierError)- report = exc_info.value.to_error_report()- assert report.error_type == "CogtError"- assert report.message == "Pipe 'leaf' failed (flow → ctrl → leaf): rate limited"+ assert isinstance(exc_info.value.__cause__, _RecoveredProblemCarrierError)+ assert exc_info.value.message == "Pipe 'leaf' failed (flow → ctrl → leaf): rate limited"+ problem = exc_info.value.to_problem(view=ProblemView.OPERATOR)+ assert problem.code == root_problem.code+ assert problem.diagnostics == root_problem.diagnostics+ assert problem.location is not None+ assert problem.location.as_wire() == {"pipe": "leaf", "path": ["flow", "ctrl", "leaf"]}async def test_a_foreign_exception_raised_from_an_older_location_is_located_here(self) -> None:"""A foreign exception raised from an earlier located failure is a new failure: converted and located at this pipe."""@@ -245,7 +259,9 @@ class TestPipeRouterRun:assert exc_info.value.pipe_code == _StubPipe.codeassert isinstance(exc_info.value.__cause__, PipelexUnexpectedError)assert exc_info.value.__cause__.__cause__ is foreign_failure- assert exc_info.value.to_error_report().error_type == "PipelexUnexpectedError"+ operator = exc_info.value.to_problem(view=ProblemView.OPERATOR)+ assert operator.diagnostics is not None+ assert operator.diagnostics.error_class == "PipelexUnexpectedError"async def test_a_host_router_can_let_a_failure_through(self) -> None:"""A host router whose hook answers None sees its transport's exception propagate unchanged."""diff --git a/tests/unit/pipelex/pipe_run/test_pipe_run.py b/tests/unit/pipelex/pipe_run/test_pipe_run.pyindex e3db674be..ca42fbbd2 100644--- a/tests/unit/pipelex/pipe_run/test_pipe_run.py+++ b/tests/unit/pipelex/pipe_run/test_pipe_run.py@@ -3,15 +3,32 @@ from contextlib import AbstractContextManager, nullcontextfrom typing import Anyimport pytest+from mthds.protocol.problem.registry import CoreCodefrom pytest_mock import MockerFixture+from typing_extensions import override+from pipelex.base_exceptions import PipelexError+from pipelex.errors.problem import PipelexProblemfrom pipelex.pipe_run import pipe_run as pipe_run_module-from pipelex.pipe_run.delivery_assignment import DeliveryAssignment, DeliveryStatus, StorageTarget+from pipelex.pipe_run.delivery_assignment import DeliveryAssignment, DeliveryStatus, StorageTarget, WebhookTargetfrom pipelex.pipe_run.exceptions import PipeRouterError, WebhookDeliveryErrorfrom pipelex.pipe_run.pipe_run import PipeRunfrom pipelex.system.job_metadata import JobMetadata, RunMetadatafrom pipelex.system.pipe_run_mode import PipeRunMode+_WEBHOOK_URL = "https://hooks.example.test/runs"+++class _UnbuildableProblemError(PipelexError):+ """A run's error whose problem cannot be built: its parameters raise, as a faulty override in a plugin's error could."""++ error_code = CoreCode.INPUT_INVALID++ @override+ def problem_params(self) -> dict[str, Any]:+ msg = "the parameters could not be read"+ raise RuntimeError(msg)+@pytest.mark.asyncio(loop_scope="class")class TestPipeRun:@@ -212,10 +229,10 @@ class TestPipeRun:assert call_kwargs["status"] == "FAILED"assert call_kwargs["pipe_output"] is None- async def test_run_failure_bare_exception_synthesizes_report(self, mocker: MockerFixture) -> None:- """A bare (non-Pipelex) exception still delivers a structured error report.+ async def test_run_failure_bare_exception_synthesizes_problem(self, mocker: MockerFixture) -> None:+ """A bare (non-Pipelex) exception still delivers a problem, a fault of ours.- Direct mode must match Temporal mode, where ``recover_error_report`` is total:+ Direct mode must match Temporal mode, where the recovered problem is total:the FAILED webhook always carries an ``error`` object so receivers canrehydrate a failed run uniformly, whichever mode produced it."""@@ -237,16 +254,63 @@ class TestPipeRun:)pipe_run = PipeRun(pipe_router=mock_router)- assignment = DeliveryAssignment(storage=StorageTarget())+ assignment = DeliveryAssignment(storage=StorageTarget(), webhooks=[WebhookTarget(url=_WEBHOOK_URL)])with pytest.raises(RuntimeError, match="router blew up"):await pipe_run.run(pipe_job=mock_job, delivery_assignment=assignment)mock_executor_instance.execute.assert_called_once()- error_report = mock_executor_instance.execute.call_args.kwargs["error_report"]- assert error_report is not None- assert error_report.error_type == "PipelexUnexpectedError"- assert "router blew up" in error_report.message+ problem = mock_executor_instance.execute.call_args.kwargs["problem"]+ assert isinstance(problem, PipelexProblem)+ assert problem.code == CoreCode.RUNTIME_UNEXPECTED+ assert problem.pipeline_run_id == "plr-bare"+ # The problem is the operator's, which each webhook projects to its own view.+ assert problem.diagnostics is not None+ assert problem.diagnostics.error_class == "PipelexUnexpectedError"+ assert problem.diagnostics.message == "RuntimeError: router blew up"++ @pytest.mark.parametrize(+ "assignment",+ [+ pytest.param(None, id="no_delivery"),+ pytest.param(DeliveryAssignment(storage=StorageTarget()), id="no_webhook"),+ pytest.param(DeliveryAssignment(webhooks=[WebhookTarget(url=_WEBHOOK_URL)]), id="webhook"),+ ],+ )+ async def test_a_problem_that_cannot_be_built_never_replaces_the_run_s_error(+ self, mocker: MockerFixture, caplog: pytest.LogCaptureFixture, assignment: DeliveryAssignment | None+ ) -> None:+ """The run fails with its own error; the problem is built only for a webhook, and one that raises is a fault of ours."""+ run_error = _UnbuildableProblemError("the pipe refused its input")+ mock_router = mocker.AsyncMock()+ mock_router.run = mocker.AsyncMock(side_effect=run_error)+ mock_executor = mocker.patch("pipelex.pipe_run.pipe_run.DeliveryExecutor")+ mock_executor_instance = mock_executor.return_value+ mock_executor_instance.execute = mocker.AsyncMock()+ mock_job = mocker.MagicMock()+ mock_job.job_metadata = JobMetadata(+ run_metadata=RunMetadata(user_id="pytest", pipeline_run_id="plr-unbuildable", storage_scope="test/scope", read_scope=None)+ )++ with pytest.raises(_UnbuildableProblemError) as raised, caplog.at_level(logging.ERROR, logger=pipe_run_module.__name__):+ await PipeRun(pipe_router=mock_router).run(pipe_job=mock_job, delivery_assignment=assignment)++ assert raised.value is run_error+ fault_records = [record for record in caplog.records if record.getMessage() == pipe_run_module.WEBHOOK_PROBLEM_FAULT_MESSAGE]+ if assignment is None:+ mock_executor_instance.execute.assert_not_called()+ assert fault_records == []+ return+ problem = mock_executor_instance.execute.call_args.kwargs["problem"]+ if not assignment.webhooks:+ assert problem is None+ assert fault_records == []+ return+ assert isinstance(problem, PipelexProblem)+ assert problem.code == CoreCode.RUNTIME_UNEXPECTED+ assert problem.pipeline_run_id == "plr-unbuildable"+ (fault_record,) = fault_records+ assert vars(fault_record)["failed_error_type"] == "_UnbuildableProblemError"async def test_run_failure_delivers_before_raising(self, mocker: MockerFixture) -> None:"""Delivery runs BEFORE the error is re-raised."""diff --git a/tests/unit/pipelex/pipeline/test_direct_bundle_validator.py b/tests/unit/pipelex/pipeline/test_direct_bundle_validator.pyindex 8ba40e7dc..803a7df33 100644--- a/tests/unit/pipelex/pipeline/test_direct_bundle_validator.py+++ b/tests/unit/pipelex/pipeline/test_direct_bundle_validator.py@@ -2,8 +2,9 @@Pins the wrapper's two branches with the in-process sweep mocked out (its own report shaping iscovered by test_validation_report.py / the integration test_protocol_validate.py): a successful-sweep is returned verbatim as the valid arm; a ``ValidateBundleError`` is converted to its-structured ``ErrorReport`` (the invalid arm) rather than propagated. Also pins argument+sweep is returned verbatim as the valid arm; a ``ValidateBundleError`` is converted to a+``BundleValidationFailure`` (the invalid arm: its problem in the operator's view, and its validation+items) rather than propagated. Also pins argumentpassthrough, including the ``library_dirs`` host context, the explicit ``graph_pipe_code`` targetand the ``log_context`` label, and that the read scope stops here: the in-process arm reads everyfile in its own process, through no blob store, so the sweep is never handed one.@@ -15,8 +16,10 @@ from pathlib import Pathfrom typing import TYPE_CHECKINGimport pytest+from mthds.protocol.problem.registry import CoreCode-from pipelex.base_exceptions import ErrorReport+from pipelex.errors.bundle_validation_failure import BundleValidationFailure+from pipelex.errors.problem import ProblemViewfrom pipelex.pipeline.direct_bundle_validator import DirectBundleValidatorfrom pipelex.pipeline.exceptions import ValidateBundleErrorfrom pipelex.system.caller_identity import CallerIdentity@@ -64,7 +67,7 @@ class TestDirectBundleValidator:)async def test_validate_bundle_error_becomes_the_invalid_arm(self, mocker: MockerFixture) -> None:- """An invalid bundle's ValidateBundleError is converted to its ErrorReport, not propagated."""+ """An invalid bundle's ValidateBundleError is converted to the invalid arm, its operator's problem and its items, not propagated."""error = ValidateBundleError("bundle is invalid")mocker.patch("pipelex.pipeline.direct_bundle_validator.validate_bundles_in_process",@@ -84,9 +87,12 @@ class TestDirectBundleValidator:read_scope=None,)- assert isinstance(verdict, ErrorReport)- assert verdict.error_type == ValidateBundleError.__name__- assert verdict == error.to_error_report()+ assert isinstance(verdict, BundleValidationFailure)+ assert verdict.problem == error.to_problem(view=ProblemView.OPERATOR)+ assert verdict.problem.code == CoreCode.METHOD_INVALID+ assert verdict.problem.diagnostics is not None+ assert verdict.problem.diagnostics.error_class == ValidateBundleError.__name__+ assert verdict.validation_errors == error.validation_error_items()async def test_other_errors_propagate_as_no_verdict_faults(self, mocker: MockerFixture) -> None:"""A non-ValidateBundleError (a genuine infra fault) propagates — the host maps it to a 5xx."""diff --git a/tests/unit/pipelex/pipeline/test_dry_run_failure_location.py b/tests/unit/pipelex/pipeline/test_dry_run_failure_location.pyindex 77aef3836..73371a6bb 100644--- a/tests/unit/pipelex/pipeline/test_dry_run_failure_location.py+++ b/tests/unit/pipelex/pipeline/test_dry_run_failure_location.py@@ -1,9 +1,9 @@from pathlib import Path-from typing import ClassVarimport pytestfrom mthds.protocol.problem.registry import CoreCodefrom polyfactory.exceptions import FactoryException+from pydantic import BaseModel, ValidationErrorfrom pytest_mock import MockerFixturefrom pipelex.base_exceptions import PipelexError@@ -12,6 +12,7 @@ from pipelex.core.pipes.exceptions import PipeRunErrorfrom pipelex.errors.error_codes import error_code_specfrom pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.pipe_run.exceptions import DryRunError, PipeRouterError+from pipelex.pipe_run.located_failure import make_unexpected_failurefrom pipelex.pipeline.bundle_validator import (BundleValidator,DryRunOutput,@@ -23,15 +24,35 @@ from pipelex.pipeline.bundle_validator import (from pipelex.system.pipe_run_mode import PipeRunMode-class _CallerFacingMethodFaultError(PipelexError):+class _MethodFaultError(PipelexError):error_code = CoreCode.METHOD_WIRING_INVALID- _authors_caller_facing_message: ClassVar[bool] = Trueclass _StorageFaultError(PipelexError):error_code = PipelexErrorCode.STORAGE_UNAVAILABLE+class _MockedOutput(BaseModel):+ mock_count: int+++def _mock_validation_error() -> ValidationError:+ """The pydantic refusal a mock value meets when it is built into its structure inside a pipe."""+ try:+ _MockedOutput.model_validate({"mock_count": "not a number"})+ except ValidationError as validation_error:+ return validation_error+ msg = "the mock value was expected to be refused"+ raise AssertionError(msg)+++def _routed_foreign_failure(*, foreign: Exception) -> PipeRouterError:+ """A foreign exception raised inside a routed pipe, as the router hands it on: located, over the unexpected error standing in for it."""+ routed = PipeRouterError(message="the step failed", run_mode=PipeRunMode.DRY, pipe_code="analyze_topic", output_name=None, pipe_stack=[])+ routed.__cause__ = make_unexpected_failure(error=foreign)+ return routed++class TestDryRunFailureLocation:def _make_pipe(self, mocker: MockerFixture, *, pipe_ref: str):domain_code, code = pipe_ref.rsplit(".", maxsplit=1)@@ -45,7 +66,7 @@ class TestDryRunFailureLocation:"""A controller failing because a pipe it ran failed is attributed to that pipe, however it was wrapped."""inner_pipe = self._make_pipe(mocker, pipe_ref="board.analyze_topic")outer_pipe = self._make_pipe(mocker, pipe_ref="board.run_workshop")- inner_error = _CallerFacingMethodFaultError("the combine failed")+ inner_error = _MethodFaultError("the combine failed")outer_error = PipeRouterError(message="the step failed", run_mode=PipeRunMode.DRY, pipe_code="run_workshop", output_name=None, pipe_stack=[])outer_error.__cause__ = inner_error@@ -54,14 +75,14 @@ class TestDryRunFailureLocation:recorder.record(error=outer_error, pipe=outer_pipe)assert recorder.find_failing_pipe(error=outer_error) is inner_pipe- assert recorder.find_failing_pipe(error=_CallerFacingMethodFaultError("unrelated")) is None+ assert recorder.find_failing_pipe(error=_MethodFaultError("unrelated")) is Nonedef test_a_failure_at_a_pipe_allowed_to_fail_is_noted_at_the_next_pipe_outward(self, mocker: MockerFixture) -> None:"""However deep the controllers, a tolerated pipe's failure is noted once, at the innermost pipe that may not fail."""tolerated_pipe = self._make_pipe(mocker, pipe_ref="board.analyze_topic")middle_pipe = self._make_pipe(mocker, pipe_ref="board.run_workshop")outer_pipe = self._make_pipe(mocker, pipe_ref="board.host_workshop")- inner_error = _CallerFacingMethodFaultError("the combine failed")+ inner_error = _MethodFaultError("the combine failed")middle_error = PipeRouterError(message="the step failed", run_mode=PipeRunMode.DRY, pipe_code="run_workshop", output_name=None, pipe_stack=[])middle_error.__cause__ = inner_error@@ -76,7 +97,7 @@ class TestDryRunFailureLocation:@pytest.mark.asyncioasync def test_the_sweep_router_notes_the_pipe_a_failure_left(self, mocker: MockerFixture) -> None:pipe = self._make_pipe(mocker, pipe_ref="board.analyze_topic")- failure = _CallerFacingMethodFaultError("the combine failed")+ failure = _MethodFaultError("the combine failed")mocker.patch.object(_DryRunSweepRouter, "_run_pipe_job", side_effect=failure)pipe_job = mocker.MagicMock()pipe_job.pipe = pipe@@ -93,20 +114,52 @@ class TestDryRunFailureLocation:assert recorder.find_failing_pipe(error=raised.value) is pipe@pytest.mark.parametrize(- ("error", "expected_text"),+ ("error", "expected_code", "expected_text", "own_text"),[- (_CallerFacingMethodFaultError("branch 'ideas' is plural"), "branch 'ideas' is plural"),- (_StorageFaultError("bucket s3://internal-bucket refused the write"), error_code_spec(PipelexErrorCode.STORAGE_UNAVAILABLE).title),+ (+ _MethodFaultError("branch 'ideas' is plural").with_params(variable_path="ideas", finding="a list fed to a single field"),+ CoreCode.METHOD_WIRING_INVALID,+ "Pipe 'analyze_topic' reads 'ideas' in a shape its wiring does not give it (a list fed to a single field).",+ "branch 'ideas' is plural",+ ),+ (+ _StorageFaultError("bucket s3://internal-bucket refused the write"),+ PipelexErrorCode.STORAGE_UNAVAILABLE,+ error_code_spec(PipelexErrorCode.STORAGE_UNAVAILABLE).title,+ "s3://internal-bucket",+ ),(PipeRunError(message="expression rendered nothing", run_mode=PipeRunMode.DRY, pipe_code="route"),- error_code_spec(CoreCode.RUNTIME_UNEXPECTED).title,+ CoreCode.RUNTIME_UNEXPECTED,+ error_code_spec(CoreCode.RUNTIME_UNEXPECTED).detail,+ "expression rendered nothing",+ ),+ (+ FactoryException("polyfactory internals"),+ CoreCode.METHOD_MOCK_UNSATISFIABLE,+ "The dry run could not generate mock data for this pipe",+ "polyfactory internals",+ ),+ (+ _routed_foreign_failure(foreign=FactoryException("polyfactory internals")),+ CoreCode.METHOD_MOCK_UNSATISFIABLE,+ "The dry run could not generate mock data for this pipe",+ "the step failed",+ ),+ (+ _routed_foreign_failure(foreign=_mock_validation_error()),+ CoreCode.METHOD_MOCK_UNSATISFIABLE,+ "The dry run could not generate mock data for this pipe",+ "the step failed",),- (FactoryException("polyfactory internals"), "The dry run could not generate mock data for this pipe"),],- ids=["caller_facing", "config_fault", "not_caller_facing", "foreign"],+ ids=["method_fault", "config_fault", "uncoded", "foreign", "foreign_factory_in_routed_pipe", "foreign_validation_in_routed_pipe"],)@pytest.mark.asyncio- async def test_a_failure_keeps_its_text_only_when_it_is_caller_facing(self, mocker: MockerFixture, error: Exception, expected_text: str) -> None:+ async def test_a_failure_reads_its_code_s_sentence_never_its_own_text(+ self, mocker: MockerFixture, error: Exception, expected_code: str, expected_text: str, own_text: str+ ) -> None:+ """The failure's message is the sentence its code renders for a caller; its own text is the operator's error message."""mocker.patch("pipelex.pipeline.bundle_validator.get_telemetry_manager")mocker.patch("pipelex.pipeline.bundle_validator.get_config").return_value.inference.dry_run.allowed_to_fail_pipes = ["board.analyze_topic"]mocker.patch("pipelex.pipeline.bundle_validator.prepare_pipe_job")@@ -121,12 +174,21 @@ class TestDryRunFailureLocation:failure = results["board.analyze_topic"].failureassert failure is not Noneassert (failure.pipe_code, failure.domain_code) == ("analyze_topic", "board")+ assert failure.code == expected_code, failureassert failure.message == f"Pipe 'analyze_topic' failed its dry run: {expected_text}"+ assert own_text not in failure.message+ error_message = results["board.analyze_topic"].error_message+ assert error_message is not None+ assert own_text in error_messagedef test_a_failure_reached_through_a_controller_is_kept_once_its_own_preferred(self) -> None:- inner_failure_via_outer = DryRunFailureErrorData(pipe_code="analyze_topic", domain_code="board", message="via the sequence")- inner_failure_own = DryRunFailureErrorData(pipe_code="analyze_topic", domain_code="board", message="its own")- other_failure = DryRunFailureErrorData(pipe_code="publish", domain_code="board", message="publish failed")+ inner_failure_via_outer = DryRunFailureErrorData(+ pipe_code="analyze_topic", domain_code="board", message="via the sequence", code=CoreCode.METHOD_WIRING_INVALID+ )+ inner_failure_own = DryRunFailureErrorData(+ pipe_code="analyze_topic", domain_code="board", message="its own", code=CoreCode.METHOD_WIRING_INVALID+ )+ other_failure = DryRunFailureErrorData(pipe_code="publish", domain_code="board", message="publish failed", code=CoreCode.RUNTIME_UNEXPECTED)unexpected_failures = {"board.run_workshop": DryRunOutput(pipe_code="run_workshop", pipe_ref="board.run_workshop", status=DryRunStatus.FAILURE, failure=inner_failure_via_outer@@ -150,7 +212,7 @@ class TestDryRunFailureLocation:mocker.patch("pipelex.pipeline.bundle_validator.get_config").return_value.inference.dry_run.allowed_to_fail_pipes = ["board.analyze_topic"]mocker.patch("pipelex.pipeline.bundle_validator.prepare_pipe_job")inner_pipe = self._make_pipe(mocker, pipe_ref="board.analyze_topic")- failure = _CallerFacingMethodFaultError("the combine failed")+ failure = _MethodFaultError("the combine failed")def _fail_inside_the_inner_pipe(_pipe_job: object) -> None:recorder = _failing_pipe_recorder.get()@@ -178,7 +240,7 @@ class TestDryRunFailureLocation:mocker.patch("pipelex.pipeline.bundle_validator.prepare_pipe_job")mocker.patch("pipelex.pipeline.bundle_validator.get_library_manager").return_value.get_pipe_source.return_value = Path("board.mthds")pipe_run = mocker.MagicMock()- pipe_run.run = mocker.AsyncMock(side_effect=_CallerFacingMethodFaultError("the combine failed"))+ pipe_run.run = mocker.AsyncMock(side_effect=_MethodFaultError("the combine failed"))mocker.patch("pipelex.pipeline.bundle_validator.PipeRun", return_value=pipe_run)pipe = self._make_pipe(mocker, pipe_ref="board.analyze_topic")pipe.is_signature = Falsediff --git a/tests/unit/pipelex/pipeline/test_dry_run_fault_answer.py b/tests/unit/pipelex/pipeline/test_dry_run_fault_answer.pynew file mode 100644index 000000000..4b16d8bfb--- /dev/null+++ b/tests/unit/pipelex/pipeline/test_dry_run_fault_answer.py@@ -0,0 +1,143 @@+import logging++import pytest+from mthds.protocol.problem.registry import CoreCode++from pipelex.core.exceptions import DryRunFailureErrorData+from pipelex.core.pipes.exceptions import PipeRunError+from pipelex.errors.error_codes import ErrorCode, first_fault_code+from pipelex.errors.problem import ProblemView+from pipelex.errors.registry.pipelex_codes import PipelexErrorCode+from pipelex.pipe_run.exceptions import DryRunError, DryRunGraphNotProducedError+from pipelex.pipeline.exceptions import ValidateBundleError+from pipelex.pipeline.validate_bundle_translation import translate_to_validate_bundle_error+from pipelex.system.pipe_run_mode import PipeRunMode+++def _translate(*, error: Exception) -> None:+ """Raise ``error`` inside the validation translation, which answers what it becomes."""+ with translate_to_validate_bundle_error():+ raise error+++def _failure(*, code: ErrorCode, pipe_code: str) -> DryRunFailureErrorData:+ return DryRunFailureErrorData(code=code, pipe_code=pipe_code, domain_code="board", message=f"Pipe '{pipe_code}' failed its dry run")+++class TestDryRunFaultAnswer:+ def test_a_dry_run_failing_on_a_fault_of_ours_answers_that_fault(self) -> None:+ """No item is the method's, so validation gives no verdict: it answers the fault, every failure among its items."""+ failures = [+ _failure(code=PipelexErrorCode.STORAGE_UNAVAILABLE, pipe_code="draw"),+ _failure(code=CoreCode.RUNTIME_UNEXPECTED, pipe_code="summarize"),+ ]++ with pytest.raises(DryRunError) as exc_info:+ _translate(error=DryRunError("two pipes failed their dry run", failures=failures))++ assert not isinstance(exc_info.value, ValidateBundleError)+ problem = exc_info.value.to_problem(view=ProblemView.CALLER)+ # A verdict `no` comes before a retryable one, so no client retries what someone must fix.+ assert problem.code == CoreCode.RUNTIME_UNEXPECTED+ assert problem.code != CoreCode.METHOD_INVALID+ assert problem.errors is not None+ assert [(item.code, item.location.pipe if item.location else None) for item in problem.errors] == [+ (PipelexErrorCode.STORAGE_UNAVAILABLE, "draw"),+ (CoreCode.RUNTIME_UNEXPECTED, "summarize"),+ ]++ def test_one_failure_of_the_method_makes_the_dry_run_an_invalid_verdict(self) -> None:+ failures = [+ _failure(code=CoreCode.RUNTIME_UNEXPECTED, pipe_code="summarize"),+ _failure(code=CoreCode.METHOD_WIRING_INVALID, pipe_code="analyze"),+ ]++ with pytest.raises(ValidateBundleError) as exc_info:+ _translate(error=DryRunError("two pipes failed their dry run", failures=failures))++ problem = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert problem.code == CoreCode.METHOD_INVALID+ assert problem.effective_domain == "method"+ assert problem.errors is not None+ # Every item rides the verdict, each with its own code.+ assert [item.code for item in problem.errors] == [CoreCode.RUNTIME_UNEXPECTED, CoreCode.METHOD_WIRING_INVALID]++ def test_a_dry_run_that_produced_no_graph_is_a_fault_of_ours(self) -> None:+ with pytest.raises(DryRunGraphNotProducedError) as exc_info:+ _translate(error=DryRunGraphNotProducedError("the dry run produced no graph"))++ assert exc_info.value.to_problem(view=ProblemView.CALLER).code == CoreCode.RUNTIME_UNEXPECTED++ def test_a_pipe_run_failing_on_a_fault_of_ours_is_no_verdict(self) -> None:+ with pytest.raises(PipeRunError) as exc_info:+ _translate(error=PipeRunError(message="an invariant broke", run_mode=PipeRunMode.DRY, pipe_code="route"))++ assert not isinstance(exc_info.value, ValidateBundleError)+ assert exc_info.value.to_problem(view=ProblemView.CALLER).code == CoreCode.RUNTIME_UNEXPECTED++ def test_a_pipe_run_failing_on_the_methods_fault_is_a_verdict(self) -> None:+ with pytest.raises(ValidateBundleError) as exc_info:+ _translate(+ error=PipeRunError(message="unwired", run_mode=PipeRunMode.DRY, pipe_code="route").with_error_code(CoreCode.METHOD_WIRING_INVALID)+ )++ problem = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert problem.code == CoreCode.METHOD_INVALID+ assert problem.errors is not None+ (item,) = problem.errors+ assert item.code == CoreCode.METHOD_WIRING_INVALID+ assert item.location is not None+ assert item.location.pipe == "route"++ def test_a_dry_run_error_renders_its_sentence_from_the_failure_whose_code_it_carries(self, caplog: pytest.LogCaptureFixture) -> None:+ """Its code's sentence is rendered whole, from that failure's parameters and pipe, never falling back on the title."""+ failures = [+ _failure(code=PipelexErrorCode.STORAGE_UNAVAILABLE, pipe_code="draw"),+ DryRunFailureErrorData(+ code=CoreCode.METHOD_WIRING_INVALID,+ pipe_code="analyze",+ domain_code="board",+ message="Pipe 'analyze' failed its dry run",+ params={"variable_path": "ideas", "finding": "a list fed to a single field"},+ ),+ ]++ with caplog.at_level(logging.WARNING, logger="pipelex.errors.problem"):+ problem = DryRunError("two pipes failed their dry run", failures=failures).to_problem(view=ProblemView.CALLER)++ assert problem.code == CoreCode.METHOD_WIRING_INVALID+ assert problem.detail == "Pipe 'analyze' reads 'ideas' in a shape its wiring does not give it (a list fed to a single field)."+ assert problem.params is not None+ assert problem.params.as_wire() == {"pipe": "analyze", "variable_path": "ideas", "finding": "a list fed to a single field"}+ unrendered = [+ record+ for record in caplog.records+ if record.getMessage() == "A problem's sentence could not be rendered from its template"+ and getattr(record, "error.code", None) == CoreCode.METHOD_WIRING_INVALID+ ]+ assert unrendered == []++ @pytest.mark.parametrize(+ ("codes", "expected"),+ [+ ([CoreCode.PROVIDER_RATE_LIMITED, CoreCode.RUNTIME_UNEXPECTED], CoreCode.RUNTIME_UNEXPECTED),+ ([CoreCode.RUNTIME_UNEXPECTED, CoreCode.RUNTIME_MISCONFIGURED], CoreCode.RUNTIME_MISCONFIGURED),+ ([CoreCode.INPUT_INVALID, CoreCode.AUTH_FORBIDDEN, CoreCode.RUNTIME_UNEXPECTED], CoreCode.AUTH_FORBIDDEN),+ ([CoreCode.RUNTIME_UNEXPECTED, CoreCode.INPUT_INVALID], CoreCode.INPUT_INVALID),+ ([CoreCode.ACCOUNT_RATE_LIMITED, CoreCode.PROVIDER_RATE_LIMITED], CoreCode.ACCOUNT_RATE_LIMITED),+ ([CoreCode.PROVIDER_RATE_LIMITED, PipelexErrorCode.STORAGE_UNAVAILABLE], CoreCode.PROVIDER_RATE_LIMITED),+ ([], None),+ ],+ ids=[+ "no_before_retryable",+ "operator_before_runtime",+ "account_before_input",+ "input_before_runtime",+ "account_before_runtime",+ "first_given",+ "none",+ ],+ )+ def test_the_answer_takes_the_first_fault_code(self, codes: list[ErrorCode], expected: ErrorCode | None) -> None:+ """A verdict `no` before a retryable one, then the operator's, the account's, the input's, the runtime's, then the first given."""+ assert first_fault_code(codes=codes) == expecteddiff --git a/tests/unit/pipelex/pipeline/test_input_format_errors.py b/tests/unit/pipelex/pipeline/test_input_format_errors.pyindex 36515fc39..bf316fd8a 100644--- a/tests/unit/pipelex/pipeline/test_input_format_errors.py+++ b/tests/unit/pipelex/pipeline/test_input_format_errors.py@@ -1,15 +1,16 @@"""The input-format error family: a file input whose format its slot or its consumer cannot take.-Its messages carry only what the caller supplied (the input's path, the file's type) and what the-method declares, so they are caller-facing and survive STRICT disclosure, where a placeholder would-leave the caller with nothing to act on. The family sits in the input domain, so an API answers 422.+The family sits in the input domain, so an API answers 422, and the caller is told to change the input. Its messages+are the operator's diagnostics; the caller reads the sentence its code renders from the parameters the raise site+gives, the input, the file's format and the model, which leave the caller something to act on."""import pytest-from mthds.protocol.problem.registry import CoreCode+from mthds.protocol.problem.registry import CoreCode, ProblemDomain, StepKind-from pipelex.base_exceptions import INTERNAL_ERROR_PLACEHOLDER, DisclosureMode, ErrorDomain, error_domain_to_http_statusfrom pipelex.cogt.inference.error_classification import UserActionKind+from pipelex.errors.error_codes import error_code_spec+from pipelex.errors.problem import ProblemViewfrom pipelex.pipeline.exceptions import (PipelineInputContentError,PipelineInputFormatError,@@ -26,21 +27,27 @@ class TestPipelineInputFormatErrors:@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()+ problem = error.to_problem(view=ProblemView.CALLER)assert isinstance(error, PipelineInputContentError)- assert report.code == CoreCode.INPUT_FILE_TYPE_UNSUPPORTED- assert report.error_domain == ErrorDomain.INPUT- assert error_domain_to_http_status(report.error_domain) == 422- assert error.user_action is not None- assert error.user_action.kind == UserActionKind.CHANGE_INPUT+ assert problem.code == CoreCode.INPUT_FILE_TYPE_UNSUPPORTED+ assert problem.domain == ProblemDomain.INPUT+ assert error_code_spec(CoreCode.INPUT_FILE_TYPE_UNSUPPORTED).status == 422+ assert problem.next_step.kind == StepKind.CHANGE_INPUT+ advice = error.advised_action()+ assert advice is not None+ assert advice.kind == UserActionKind.CHANGE_INPUTdef test_not_an_image_is_a_format_error(self):assert issubclass(PipelineInputNotAnImageError, PipelineInputFormatError)@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)-- assert strict["message"] == NOT_AN_IMAGE_MESSAGE- assert strict["message"] != INTERNAL_ERROR_PLACEHOLDER+ def test_the_caller_reads_the_code_s_sentence_and_the_operator_the_message(self, error_class: type[PipelineInputFormatError]):+ error = error_class(NOT_AN_IMAGE_MESSAGE).with_params(input="referral_letter", format="application/pdf", model="vision-model")++ caller = error.to_problem(view=ProblemView.CALLER)+ assert caller.detail == "The model 'vision-model' cannot take the file of the input 'referral_letter', whose format is 'application/pdf'."+ assert NOT_AN_IMAGE_MESSAGE not in str(caller.to_wire())+ operator = error.to_problem(view=ProblemView.OPERATOR)+ assert operator.diagnostics is not None+ assert operator.diagnostics.message == NOT_AN_IMAGE_MESSAGEdiff --git a/tests/unit/pipelex/pipeline/test_input_normalizer.py b/tests/unit/pipelex/pipeline/test_input_normalizer.pyindex 420dda6f3..83a6b0ef9 100644--- a/tests/unit/pipelex/pipeline/test_input_normalizer.py+++ b/tests/unit/pipelex/pipeline/test_input_normalizer.py@@ -6,24 +6,25 @@ uncaught `IsADirectoryError` escaped as an InternalServerError. Both the blankurl and any unreadable local path must surface as the INPUT-domain`PipelineInputContentError` (→ 422 at the API layer), never a sanitized 500.-The family is split on what its message may disclose: the blank-url arm-(`PipelineInputUrlMissingError`) names only the accepted schemes and is-caller-facing copy, while the unreadable-path arm names the resolved path and-the OSError subclass and must stay redacted under STRICT disclosure.+Every message of the family is the operator's diagnostics: the caller reads its+code's sentence and the step to change its input. The unreadable-path arm's+message names the resolved path and the OSError subclass, which must never reach+the caller."""from pathlib import Pathimport pytest+from mthds.protocol.problem.registry import CoreCode, ProblemDomain, StepKindfrom pytest_mock import MockerFixture-from pipelex.base_exceptions import INTERNAL_ERROR_PLACEHOLDER, DisclosureModefrom 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.document_content import DocumentContentfrom pipelex.core.stuffs.stuff_factory import StuffFactory+from pipelex.errors.problem import ProblemViewfrom pipelex.pipeline.exceptions import PipelineInputContentError, PipelineInputUrlInvalidError, PipelineInputUrlMissingErrorfrom pipelex.pipeline.input_normalizer import prepare_file_inputsfrom pipelex.tools.storage.storage_provider_abstract import StorageProviderAbstract@@ -59,15 +60,17 @@ class TestInputNormalizerUrlGuards:await prepare_file_inputs(_memory_with_document(blank_url), storage_scope="test/scope", read_scope=None, is_relocation_enabled=True)@pytest.mark.parametrize("bad_url", ["https://", "https://exa mple.com/file.pdf"])- async def test_malformed_http_url_raises_caller_facing_input_error(self, mocker: MockerFixture, bad_url: str) -> None:- """A malformed http(s) url is refused at shaping time, with a message STRICT disclosure keeps."""+ async def test_malformed_http_url_raises_an_input_error_the_caller_can_fix(self, mocker: MockerFixture, bad_url: str) -> None:+ """A malformed http(s) url is refused at shaping time as the caller's input to change; its message is the operator's."""_patch_storage_and_config(mocker)with pytest.raises(PipelineInputUrlInvalidError) as exc_info:await prepare_file_inputs(_memory_with_document(bad_url), storage_scope="test/scope", read_scope=None, is_relocation_enabled=True)- strict = exc_info.value.to_error_report().to_dict(disclosure_mode=DisclosureMode.STRICT)- assert "not a valid http(s) URL" in strict["message"]+ caller = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert caller.code == CoreCode.INPUT_INVALID+ assert caller.next_step.kind == StepKind.CHANGE_INPUT+ assert "not a valid http(s) URL" in exc_info.value.messageasync def test_well_formed_http_url_passes_through_unchanged(self, mocker: MockerFixture) -> None:"""A well-formed http(s) url is not fetched or probed at shaping time, and it becomes its own public_url."""@@ -84,22 +87,21 @@ class TestInputNormalizerUrlGuards:assert content.public_url == "https://example.com/file.pdf"mock_get.assert_not_called()- async def test_blank_url_message_survives_strict_disclosure(self, mocker: MockerFixture) -> None:- """The blank-url message names only the accepted schemes, so STRICT keeps it.-- Under the placeholder a caller who simply forgot a url is told "internal- error" and has nothing to act on.- """+ async def test_blank_url_is_the_caller_s_input_to_change(self, mocker: MockerFixture) -> None:+ """A caller who simply forgot a url is told it is its own input to change, never that the runtime failed."""_patch_storage_and_config(mocker)with pytest.raises(PipelineInputUrlMissingError) as exc_info:await prepare_file_inputs(_memory_with_document(""), storage_scope="test/scope", read_scope=None, is_relocation_enabled=True)- strict = exc_info.value.to_error_report().to_dict(disclosure_mode=DisclosureMode.STRICT)- assert "blank url" in strict["message"]+ caller = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert caller.code == CoreCode.INPUT_INVALID+ assert caller.domain == ProblemDomain.INPUT+ assert caller.next_step.kind == StepKind.CHANGE_INPUT+ assert "blank url" in exc_info.value.message- async def test_unreadable_path_message_is_redacted_under_strict_disclosure(self, mocker: MockerFixture, tmp_path: Path) -> None:- """The unreadable-path message must NOT reach a caller under STRICT disclosure.+ async def test_unreadable_path_message_never_reaches_the_caller(self, mocker: MockerFixture, tmp_path: Path) -> None:+ """The unreadable-path message must NOT reach a caller: it is the operator's diagnostics alone.It names the resolved path and the OSError subclass that rejected it. Lettingthose through would answer "does this server-side path exist, and may the runner@@ -115,12 +117,12 @@ class TestInputNormalizerUrlGuards:_memory_with_document(str(missing_path)), storage_scope="test/scope", read_scope=None, is_relocation_enabled=True)- report = exc_info.value.to_error_report()- assert str(missing_path) in report.message, "precondition: the raw message carries the path"- strict = report.to_dict(disclosure_mode=DisclosureMode.STRICT)- assert strict["message"] == INTERNAL_ERROR_PLACEHOLDER- assert str(missing_path) not in str(strict)- assert "FileNotFoundError" not in str(strict)+ operator = exc_info.value.to_problem(view=ProblemView.OPERATOR)+ assert operator.diagnostics is not None+ assert str(missing_path) in operator.diagnostics.message, "precondition: the raw message carries the path"+ caller_wire = str(exc_info.value.to_problem(view=ProblemView.CALLER).to_wire())+ assert str(missing_path) not in caller_wire+ assert "FileNotFoundError" not in caller_wireasync def test_directory_path_raises_input_error(self, mocker: MockerFixture, tmp_path: Path) -> None:"""A local path that IS a directory must be an input error, not andiff --git a/tests/unit/pipelex/pipeline/test_inputs_template.py b/tests/unit/pipelex/pipeline/test_inputs_template.pyindex ac9689fc9..90df59698 100644--- a/tests/unit/pipelex/pipeline/test_inputs_template.py+++ b/tests/unit/pipelex/pipeline/test_inputs_template.py@@ -11,6 +11,7 @@ import pytestfrom mthds.protocol.problem.registry import CoreCodefrom pipelex.core.pipes.inputs.exceptions import NoInputsRequiredError+from pipelex.errors.problem import ProblemViewfrom pipelex.pipeline.exceptions import MethodEntryErrorfrom pipelex.pipeline.inputs_template import build_inputs_for_pipe@@ -81,7 +82,7 @@ class TestBuildInputsForPipe: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+ assert exc_info.value.to_problem(view=ProblemView.CALLER).code == CoreCode.REQUEST_PIPE_UNSPECIFIEDdef 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."""@@ -117,7 +118,7 @@ class TestBuildInputsForPipe: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_UNSPECIFIED+ assert exc_info.value.to_problem(view=ProblemView.CALLER).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."""@@ -155,7 +156,7 @@ class TestBuildInputsForPipe: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+ assert exc_info.value.to_problem(view=ProblemView.CALLER).code == CoreCode.REQUEST_PIPE_UNSPECIFIEDops_mocks["get_required_entry_pipe"].assert_not_called()diff --git a/tests/unit/pipelex/pipeline/test_method_entry.py b/tests/unit/pipelex/pipeline/test_method_entry.pyindex 6ce1b505c..1277a0563 100644--- a/tests/unit/pipelex/pipeline/test_method_entry.py+++ b/tests/unit/pipelex/pipeline/test_method_entry.py@@ -1,8 +1,11 @@from pathlib import Path+from typing import Anyimport pytestfrom mthds.method_tree.lister import list_method_tree+from mthds.protocol.problem.registry import CoreCode, ProblemDomain+from pipelex.errors.problem import ProblemViewfrom pipelex.mthds_parsing.exceptions import MthdsParserErrorfrom pipelex.pipeline.exceptions import MethodEntryErrorfrom pipelex.pipeline.method_entry import read_method_candidates, select_method_entry, select_named_pipe@@ -74,7 +77,7 @@ class TestMethodEntry:assert entry.tree_path == "steps/extract.mthds"@pytest.mark.parametrize(- ("files", "expected"),+ ("files", "expected", "expected_code", "expected_params"),[({@@ -82,6 +85,8 @@ class TestMethodEntry:"b/b.mthds": _bundle(domain="entry_b", pipe_code="second", main_pipe=None),},"none of its bundles declares a main_pipe ('a.mthds', 'b/b.mthds')",+ CoreCode.REQUEST_PIPE_UNSPECIFIED,+ None,),({@@ -89,6 +94,8 @@ class TestMethodEntry:"b/b.mthds": _bundle(domain="entry_b", pipe_code="second", main_pipe="second"),},"several of its bundles declare a main_pipe: 'a.mthds' declares 'first', 'b/b.mthds' declares 'second'",+ CoreCode.REQUEST_PIPE_UNSPECIFIED,+ {"candidates": ["entry_a.first", "entry_b.second"]},),({@@ -99,6 +106,8 @@ class TestMethodEntry:"declares no main_pipe, so the method has no pipe to start at. Declare main_pipe under [package], or name the pipe to run. ""Its bundles: 'a.mthds'."),+ CoreCode.REQUEST_PIPE_UNSPECIFIED,+ None,),({@@ -106,16 +115,37 @@ class TestMethodEntry:"a.mthds": _bundle(domain="entry_a", pipe_code="first", main_pipe="first"),},"declares the main_pipe 'missing', exported by 'entry_a', which none of its bundles defines in that domain: 'a.mthds'.",+ CoreCode.METHOD_PIPE_UNRESOLVED,+ {"missing": "missing"},+ ),+ (+ {+ "METHODS.toml": _manifest(main_pipe="first", exports={"entry_a": ["first"], "entry_b": ["first"]}),+ "a.mthds": _bundle(domain="entry_a", pipe_code="first", main_pipe=None),+ "b/b.mthds": _bundle(domain="entry_b", pipe_code="first", main_pipe=None),+ },+ "declares the main_pipe 'first', which several of its bundles define: 'a.mthds' in domain 'entry_a', 'b/b.mthds' in domain 'entry_b'",+ CoreCode.METHOD_REF_AMBIGUOUS,+ {"ref": "first", "candidates": ["entry_a.first", "entry_b.first"]},),({"notes.md": "# Notes\n"},"holds no .mthds bundle, so it has no pipe to start at",+ CoreCode.METHOD_INVALID,+ None,),],- ids=["no_main_pipe", "several_main_pipes", "manifest_without_main_pipe", "manifest_main_pipe_undefined", "no_bundle"],+ ids=[+ "no_main_pipe",+ "several_main_pipes",+ "manifest_without_main_pipe",+ "manifest_main_pipe_undefined",+ "manifest_main_pipe_twice",+ "no_bundle",+ ],)def test_a_method_with_no_single_entry_is_refused_naming_its_bundles_by_tree_path(- self, tmp_path: Path, files: dict[str, str], expected: str+ self, tmp_path: Path, files: dict[str, str], expected: str, expected_code: CoreCode, expected_params: dict[str, Any] | None) -> None:_write(directory=tmp_path, files=files)@@ -123,7 +153,11 @@ class TestMethodEntry:select_method_entry(tree=list_method_tree(tmp_path))assert expected in exc_info.value.message- assert exc_info.value.to_error_report().error_domain == "input"+ problem = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert problem.code == expected_code+ assert problem.domain != ProblemDomain.OPERATOR+ # The refusal gives the parameters its sentences name: the pipes to choose from, the missing one, the ambiguous one.+ assert problem.to_wire().get("params") == expected_paramsdef test_a_manifest_that_does_not_validate_is_an_entry_refusal(self, tmp_path: Path) -> None:"""A manifest the lister can read but the standard refuses, here one with no address, gives no entry."""diff --git a/tests/unit/pipelex/pipeline/test_pipeline_manager.py b/tests/unit/pipelex/pipeline/test_pipeline_manager.pyindex 8651fdc2a..27b129d99 100644--- a/tests/unit/pipelex/pipeline/test_pipeline_manager.py+++ b/tests/unit/pipelex/pipeline/test_pipeline_manager.py@@ -14,6 +14,8 @@ Pins the two-sided contract around explicit ``pipeline_run_id`` reuse:import pytest+from pipelex.errors.problem import ProblemView+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.pipeline.exceptions import PipelineManagerAlreadyExistsErrorfrom pipelex.pipeline.pipeline_manager import PipelineManager@@ -48,5 +50,12 @@ class TestPipelineManagerRemoval:"""manager = PipelineManager()manager.add_new_pipeline(pipe_code="some_pipe", pipeline_run_id="run-1")- with pytest.raises(PipelineManagerAlreadyExistsError):+ with pytest.raises(PipelineManagerAlreadyExistsError) as raised:manager.add_new_pipeline(pipe_code="some_pipe", pipeline_run_id="run-1")++ # The run id its code declares names the run that holds it, in the sentence the caller reads.+ problem = raised.value.to_problem(view=ProblemView.CALLER)+ assert problem.code == PipelexErrorCode.RUN_ALREADY_EXISTS+ assert problem.params is not None+ assert problem.params.as_wire() == {"pipeline_run_id": "run-1"}+ assert problem.detail == "A run with the id 'run-1' already exists."diff --git a/tests/unit/pipelex/pipeline/test_refusal_verdict_arms.py b/tests/unit/pipelex/pipeline/test_refusal_verdict_arms.pyindex b1ef4d26a..f7b9bbe47 100644--- a/tests/unit/pipelex/pipeline/test_refusal_verdict_arms.py+++ b/tests/unit/pipelex/pipeline/test_refusal_verdict_arms.py@@ -6,6 +6,7 @@ from pipelex.cogt.model_backends.model_type import ModelTypefrom pipelex.core.exceptions import DryRunFailureErrorDatafrom pipelex.core.pipes.exceptions import PipeLoadRefusalError, PipeOperatorModelChoiceErrorfrom pipelex.errors.error_codes import error_code_spec+from pipelex.errors.problem import ProblemViewfrom pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.libraries.exceptions import LibraryErrorfrom pipelex.pipeline.exceptions import ValidateBundleError@@ -13,11 +14,6 @@ from pipelex.pipeline.validate_bundle_translation import translate_to_validate_bfrom pipelex.validation_error_types import PipeValidationErrorType-class _CallerFacingInputRefusalError(PipelexError):- error_code = CoreCode.METHOD_INVALID- _authors_caller_facing_message = True--class _InternalInputRefusalError(PipelexError):error_code = CoreCode.METHOD_SCHEMA_VIOLATION@@ -32,10 +28,9 @@ class _UnclassifiedFaultError(PipelexError):class _InputSecurityRefusalError(SecurityError):error_code = CoreCode.SECURITY_TEMPLATE_REFUSED- _authors_caller_facing_message = True-# What a non-caller-facing refusal's item reads: its code's title.+# What the item of a refusal whose raise site gave no parameters reads: its code's title._INTERNAL_REFUSAL_TITLE = error_code_spec(CoreCode.METHOD_SCHEMA_VIOLATION).title@@ -44,22 +39,28 @@ def _verdict_items(refusal: BaseException) -> tuple[ValidateBundleError, list[Varaise refusalverdict = raised.valueassert verdict.__cause__ is refusal- return verdict, list(verdict.to_error_report().validation_errors or [])+ return verdict, list(verdict.validation_error_items() or [])class TestRefusalVerdictArms:- def test_unlocated_caller_facing_input_refusal_is_one_blueprint_item_keeping_its_message(self) -> None:- verdict, items = _verdict_items(_CallerFacingInputRefusalError("The tide table names a harbour that does not exist."))+ def test_unlocated_input_refusal_is_one_blueprint_item_reading_its_code_s_sentence(self) -> None:+ """The item reads the sentence the refusal's code renders from the parameters its raise site gave, never its message."""+ refusal = _InternalInputRefusalError("internal detail: registry slot 7 is stale").with_params(+ field_path="pipe.tide_table", finding="the tide table names a harbour that does not exist"+ )- assert items == [- ValidationErrorItem(- category=ValidationErrorCategory.BLUEPRINT_VALIDATION,- message="The tide table names a harbour that does not exist.",- )- ]- assert verdict.message == "The tide table names a harbour that does not exist."+ verdict, items = _verdict_items(refusal)++ sentence = "The declaration at 'pipe.tide_table' breaks a rule of the language (the tide table names a harbour that does not exist)."+ assert items == [ValidationErrorItem(category=ValidationErrorCategory.BLUEPRINT_VALIDATION, message=sentence)]+ assert verdict.message == sentence+ problem = verdict.to_problem(view=ProblemView.CALLER)+ assert problem.code == CoreCode.METHOD_INVALID+ (problem_item,) = problem.errors or []+ assert problem_item.code == CoreCode.METHOD_SCHEMA_VIOLATION+ assert "registry slot 7" not in str(problem.to_wire())- def test_non_caller_facing_input_refusal_is_named_by_its_title(self) -> None:+ def test_an_input_refusal_with_no_parameters_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] == [_INTERNAL_REFUSAL_TITLE]@@ -76,7 +77,9 @@ class TestRefusalVerdictArms:pipe_code="write_tide_note",domain_code="tide_tables",source="tides.mthds",- message=f"Pipe 'write_tide_note' could not be loaded: {_INTERNAL_REFUSAL_TITLE}",+ message=(+ "The declaration at 'pipe.write_tide_note' breaks a rule of the language (the pipe could not be built from its declaration)."+ ),)]@@ -131,7 +134,9 @@ class TestRefusalVerdictArms:def test_a_produced_verdict_passes_through_unwrapped(self) -> None:verdict = ValidateBundleError(message="already a verdict",- dry_run_failures=[DryRunFailureErrorData(pipe_code="route_parcel", message="the round has no lane")],+ dry_run_failures=[+ DryRunFailureErrorData(pipe_code="route_parcel", message="the round has no lane", code=CoreCode.PIPE_CONDITION_UNMATCHED)+ ],)with pytest.raises(ValidateBundleError) as raised, translate_to_validate_bundle_error():diff --git a/tests/unit/pipelex/pipeline/test_runner_protocol_surfaces.py b/tests/unit/pipelex/pipeline/test_runner_protocol_surfaces.pyindex d769a9505..d63e1aabd 100644--- a/tests/unit/pipelex/pipeline/test_runner_protocol_surfaces.py+++ b/tests/unit/pipelex/pipeline/test_runner_protocol_surfaces.py@@ -18,6 +18,7 @@ from mthds.protocol.problem.registry import CoreCodefrom mthds.protocol.protocol import PROTOCOL_VERSIONfrom pipelex.cogt.models.model_listing import ModelCategory+from pipelex.errors.problem import ProblemViewfrom pipelex.pipe_run.exceptions import AsyncExecutionNotEnabledErrorfrom pipelex.pipeline.request_exceptions import PipelexRequestErrorfrom pipelex.pipeline.runner import (@@ -59,7 +60,7 @@ class TestRunnerProtocolSurfaces: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_UNSUPPORTED+ assert exc_info.value.to_problem(view=ProblemView.CALLER).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."""@@ -74,7 +75,7 @@ class TestRunnerProtocolSurfaces: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_INVALID+ assert exc_info.value.to_problem(view=ProblemView.CALLER).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."""@@ -83,7 +84,7 @@ class TestRunnerProtocolSurfaces:with pytest.raises(AsyncExecutionNotEnabledError) as exc_info:await runner.start(pipe_code="any_pipe")- assert exc_info.value.to_error_report().code == CoreCode.RUNTIME_UNSUPPORTED+ assert exc_info.value.to_problem(view=ProblemView.CALLER).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/pipeline/test_usage_stats_reporting.py b/tests/unit/pipelex/pipeline/test_usage_stats_reporting.pyindex a55e902ff..18e9968aa 100644--- a/tests/unit/pipelex/pipeline/test_usage_stats_reporting.py+++ b/tests/unit/pipelex/pipeline/test_usage_stats_reporting.py@@ -17,6 +17,7 @@ from pipelex.pipeline.usage_stats_reporting import (from pipelex.system.usage_stats.usage_stats_contract import (UsageStatsCodegenArtifact,UsageStatsCodegenTarget,+ UsageStatsErrorDomain,UsageStatsEventName,UsageStatsOutcome,UsageStatsProvider,@@ -24,6 +25,7 @@ from pipelex.system.usage_stats.usage_stats_contract import (from pipelex.system.usage_stats.usage_stats_events import UsageStatsEventfrom pipelex.system.usage_stats.usage_stats_runs import RunInferenceTally, usage_stats_error_domainfrom pipelex.tracing.trace_events import TraceEvent+from tests.helpers.recovered_problem import make_recovered_url_refusalfrom tests.helpers.usage_stats_run_events import envelope_of, llm_usage_event, pipe_start_eventfrom tests.helpers.usage_stats_schema import assert_envelope_is_valid@@ -250,6 +252,10 @@ class TestUsageStatsReporting:assert "error_domain" not in runassert "secret" not in str(envelope)+ def test_a_recovered_problem_is_counted_in_its_own_domain(self) -> None:+ """A failure reporting a problem recovered from a worker is counted by that problem's domain, not by its carrier's class."""+ assert usage_stats_error_domain(error=make_recovered_url_refusal()) == UsageStatsErrorDomain.INPUT+@pytest.mark.parametrize(("backend_name", "model_handle", "provider", "model"),[diff --git a/tests/unit/pipelex/pipeline/test_validate_bundle_error_report.py b/tests/unit/pipelex/pipeline/test_validate_bundle_error_report.pyindex 832eda078..db642c6e3 100644--- a/tests/unit/pipelex/pipeline/test_validate_bundle_error_report.py+++ b/tests/unit/pipelex/pipeline/test_validate_bundle_error_report.py@@ -1,14 +1,17 @@-"""Unit tests for ``ValidateBundleError.to_error_report`` — structured errors on the wire.+"""Unit tests for the problem of an invalid verdict — structured errors on the wire.-The override attaches the shared ``build_validation_error_items`` output onto-``ErrorReport.validation_errors``, so the RFC 7807 problem document the API emits-on a 422 carries machine-mappable per-error diagnostics (with ``source``) instead-of only a single ``detail`` string. The cause-chain enrichment from the base-``to_error_report`` is preserved.+``ValidateBundleError`` is ``method.invalid``, and its problem lists one item per underlying error under ``errors``,+each with its own code and its location (the file included), so the problem document the API emits carries+machine-mappable per-error diagnostics instead of only a single ``detail`` string. The validation items the shared+``build_validation_error_items`` builds ride beside it, one per problem item."""-from pipelex.base_exceptions import DisclosureMode, ErrorDomain, ValidationErrorCategory+from mthds.protocol.problem.registry import CoreCode, ProblemDomain, RetryVerdict, StepKind++from pipelex.base_exceptions import ValidationErrorCategoryfrom pipelex.core.exceptions import PipelexBundleBlueprintValidationErrorData, PipesAndConceptValidationErrorData+from pipelex.errors.error_codes import error_code_spec+from pipelex.errors.problem import ProblemView, caller_view_offrom pipelex.pipeline.exceptions import ValidateBundleErrorfrom pipelex.validation_error_types import PipeValidationErrorType@@ -36,47 +39,57 @@ def _error_with_two_categories() -> ValidateBundleError:)-class TestValidateBundleErrorReport:- def test_to_error_report_populates_validation_errors(self) -> None:- """``to_error_report`` attaches one structured item per underlying error."""- report = _error_with_two_categories().to_error_report()- assert report.validation_errors is not None- sources = sorted(item.source or "" for item in report.validation_errors)- assert sources == ["helpers.mthds", "main.mthds"]+class TestValidateBundleErrorProblem:+ def test_the_problem_lists_one_item_per_underlying_error(self) -> None:+ """Each underlying error is an item with its own code and its file, in the order the validation items list them."""+ error = _error_with_two_categories()+ problem = error.to_problem(view=ProblemView.CALLER)++ assert problem.errors is not None+ assert [(item.code, item.location.file if item.location else None) for item in problem.errors] == [+ (CoreCode.METHOD_IDENTIFIER_INVALID, "main.mthds"),+ (CoreCode.METHOD_INPUT_UNDECLARED, "helpers.mthds"),+ ]+ assert [item.source for item in error.validation_error_items()] == ["main.mthds", "helpers.mthds"]- def test_report_keeps_caller_facing_input_classification(self) -> None:- """The base classification (INPUT domain, caller-facing message) still holds."""- report = _error_with_two_categories().to_error_report()- assert report.error_domain == ErrorDomain.INPUT- assert report.caller_facing_message is True- assert report.error_type == "ValidateBundleError"+ def test_the_verdict_is_the_method_s_fault(self) -> None:+ """An invalid verdict is the method's to fix and is never retried; its class is the operator's diagnostics."""+ error = _error_with_two_categories()+ caller = error.to_problem(view=ProblemView.CALLER)++ assert caller.code == CoreCode.METHOD_INVALID+ assert caller.domain == ProblemDomain.METHOD+ assert caller.retry == RetryVerdict.NO+ assert caller.next_step.kind == StepKind.CHANGE_METHOD+ assert error_code_spec(CoreCode.METHOD_INVALID).status == 422+ assert caller.diagnostics is None+ operator = error.to_problem(view=ProblemView.OPERATOR)+ assert operator.diagnostics is not None+ assert operator.diagnostics.error_class == "ValidateBundleError"def test_message_only_error_surfaces_a_residual_item(self) -> None:- """No categorized errors → a ``blueprint_validation`` residual still rides the wire (invariant is total).+ """No categorized errors → a ``blueprint_validation`` residual still rides the verdict (the invariant is total).- ``to_error_report`` passes ``fallback_message=self.message``, so a parse-level failure that- carries only a message (TOML syntax, an empty blueprint, a bundle elaborator) projects one- residual item rather than a bare ``detail`` with an empty ``validation_errors[]``.- """- report = ValidateBundleError(message="generic failure").to_error_report()- assert report.validation_errors is not None- assert [item.category for item in report.validation_errors] == [ValidationErrorCategory.BLUEPRINT_VALIDATION]- assert report.validation_errors[0].message == "generic failure"-- def test_problem_document_carries_validation_errors_with_source(self) -> None:- """The 422 problem document rides ``validation_errors[]`` as an extension member."""- document = _error_with_two_categories().to_error_report().to_problem_document()- assert document["status"] == 422- items = document["validation_errors"]- assert {item["source"] for item in items} == {"main.mthds", "helpers.mthds"}- assert {item["category"] for item in items} == {"blueprint_validation", "pipe_validation"}-- def test_strict_problem_document_retains_validation_errors(self) -> None:- """STRICT disclosure keeps ``validation_errors`` — they are the caller's own bundle diagnostics.-- ``ValidateBundleError`` is a caller-facing INPUT error, so STRICT also- keeps the ``detail`` message; the structured items ride alongside it.+ ``validation_error_items`` passes ``fallback_message=self.message``, so a parse-level failure that carries+ only a message (TOML syntax, an empty blueprint, a bundle elaborator) projects one residual item, and its+ problem one ``method.schema_violation`` item, rather than a bare ``detail`` with no items."""- document = _error_with_two_categories().to_error_report().to_problem_document(disclosure_mode=DisclosureMode.STRICT)- assert "validation_errors" in document- assert len(document["validation_errors"]) == 2+ error = ValidateBundleError(message="generic failure")++ items = error.validation_error_items()+ assert [item.category for item in items] == [ValidationErrorCategory.BLUEPRINT_VALIDATION]+ assert items[0].message == "generic failure"+ problem = error.to_problem(view=ProblemView.CALLER)+ assert problem.errors is not None+ assert [item.code for item in problem.errors] == [CoreCode.METHOD_SCHEMA_VIOLATION]++ def test_the_caller_view_of_the_operator_s_record_keeps_the_items(self) -> None:+ """The items are the caller's own bundle diagnostics, so the caller view of the operator's problem keeps every one."""+ operator = _error_with_two_categories().to_problem(view=ProblemView.OPERATOR)++ caller = caller_view_of(problem=operator)++ assert caller.diagnostics is None+ assert caller.errors == operator.errors+ wire_errors = caller.to_wire()["errors"]+ assert {item["location"]["file"] for item in wire_errors} == {"main.mthds", "helpers.mthds"}diff --git a/tests/unit/pipelex/pipeline/test_validate_bundle_error_withholding.py b/tests/unit/pipelex/pipeline/test_validate_bundle_error_withholding.pyindex bcc834cf6..6ee6fa971 100644--- a/tests/unit/pipelex/pipeline/test_validate_bundle_error_withholding.py+++ b/tests/unit/pipelex/pipeline/test_validate_bundle_error_withholding.py@@ -2,14 +2,17 @@ import inspectfrom pathlib import Pathimport pytest+from mthds.protocol.problem.registry import CoreCodefrom pytest_mock import MockerFixture+from pipelex.base_exceptions import PipelexErrorfrom pipelex.core.exceptions import (DryRunFailureErrorData,PipeFactoryErrorData,PipelexBundleBlueprintValidationErrorData,PipesAndConceptValidationErrorData,)+from pipelex.errors.problem import ProblemView, make_location, make_problem_itemfrom pipelex.pipeline import validate_bundle_translationfrom pipelex.pipeline.exceptions import ValidateBundleErrorfrom pipelex.pipeline.validate_bundle_translation import HOST_LIBRARY_FILE_PLACEHOLDER, withholding_host_library_files@@ -33,6 +36,10 @@ def _mentioning_the_host_file(*, label: str) -> str:return f"{label} in '{_HOST_FILE}'"+class _MethodSyntaxError(PipelexError):+ error_code = CoreCode.METHOD_SYNTAX++class TestValidateBundleErrorWithholding:def test_every_channel_of_the_verdict_is_carried(self) -> None:constructor_channels = set(inspect.signature(ValidateBundleError.__init__).parameters) - {"self"}@@ -56,12 +63,19 @@ class TestValidateBundleErrorWithholding:message=_mentioning_the_host_file(label="instantiation"), source="api://bundle-0.mthds", field_path="")],- dry_run_failures=[DryRunFailureErrorData(pipe_code="post_notice", message=_mentioning_the_host_file(label="dry run"), source=_HOST_FILE)],+ dry_run_failures=[+ DryRunFailureErrorData(+ pipe_code="post_notice",+ message=_mentioning_the_host_file(label="dry run"),+ source=_HOST_FILE,+ code=CoreCode.METHOD_WIRING_INVALID,+ )+ ],)withheld = verdict.withholding_files(withheld_files={_HOST_FILE}, placeholder=HOST_LIBRARY_FILE_PLACEHOLDER)- items = withheld.to_error_report().validation_errors or []+ items = withheld.validation_error_items() or []assert [item.message for item in items] == [f"blueprint in '{HOST_LIBRARY_FILE_PLACEHOLDER}'",f"factory in '{HOST_LIBRARY_FILE_PLACEHOLDER}'",@@ -73,6 +87,55 @@ class TestValidateBundleErrorWithholding:assert [item.source for item in items] == [None, None, None, "api://bundle-0.mthds", None]assert [item.field_path for item in items] == [None, None, None, None, None]assert _HOST_FILE not in withheld.message+ # The withheld verdict's problem keeps its items' codes and names the withheld file in no reader's view.+ problem_items = withheld.to_problem(view=ProblemView.CALLER).errors or []+ assert problem_items[-1].code == CoreCode.METHOD_WIRING_INVALID+ for view in (ProblemView.CALLER, ProblemView.OPERATOR):+ assert _HOST_FILE not in str(withheld.to_problem(view=view).to_wire())++ def test_what_the_raise_site_chose_is_carried(self) -> None:+ """The code a raise site chose, and the parameters and items it gave, survive the withholding, withheld as the messages are."""+ item = make_problem_item(+ code=CoreCode.METHOD_SYNTAX, params={"finding": _mentioning_the_host_file(label="item")}, location=make_location(file=_HOST_FILE)+ )+ verdict = (+ ValidateBundleError(message=_mentioning_the_host_file(label="raw"))+ .with_error_code(CoreCode.REQUEST_INVALID)+ .with_params(field=_mentioning_the_host_file(label="field"))+ .with_items(items=[item])+ )++ withheld = verdict.withholding_files(withheld_files={_HOST_FILE}, placeholder=HOST_LIBRARY_FILE_PLACEHOLDER)++ assert withheld.resolve_error_code() == CoreCode.REQUEST_INVALID+ assert withheld.given_params == {"field": f"field in '{HOST_LIBRARY_FILE_PLACEHOLDER}'"}+ (withheld_item,) = PipelexError.problem_items(withheld) or []+ assert withheld_item.code == CoreCode.METHOD_SYNTAX+ assert withheld_item.location is not None+ assert withheld_item.location.file == HOST_LIBRARY_FILE_PLACEHOLDER+ assert _HOST_FILE not in str(withheld_item.as_wire())+ caller = withheld.to_problem(view=ProblemView.CALLER)+ assert caller.code == CoreCode.REQUEST_INVALID+ assert caller.detail == f"The request's field 'field in '{HOST_LIBRARY_FILE_PLACEHOLDER}'' does not match the route's schema."++ def test_an_item_taking_its_cause_s_parameters_names_no_withheld_file(self, tmp_path: Path) -> None:+ """An item no stage classified reads its cause's parameters, which the withholding reaches too, its sentence with them."""+ host_library_file = tmp_path / "harbour_board.mthds"+ host_library_file.write_text('domain = "harbour_board"\n', encoding="utf-8")+ cause = _MethodSyntaxError("the host's bundle does not parse").with_params(finding=f"unexpected '=' in '{host_library_file}'")++ with pytest.raises(ValidateBundleError) as raised, withholding_host_library_files(library_dirs=[tmp_path]):+ raise ValidateBundleError(message=f"Could not load '{host_library_file}'") from cause++ caller = raised.value.to_problem(view=ProblemView.CALLER)+ assert caller.errors is not None+ (item,) = caller.errors+ assert item.code == CoreCode.METHOD_SYNTAX+ assert item.params is not None+ assert item.params.as_wire() == {"finding": f"unexpected '=' in '{HOST_LIBRARY_FILE_PLACEHOLDER}'"}+ assert item.detail == f"The method does not parse (unexpected '=' in '{HOST_LIBRARY_FILE_PLACEHOLDER}')."+ for view in (ProblemView.CALLER, ProblemView.OPERATOR):+ assert str(host_library_file) not in str(raised.value.to_problem(view=view).to_wire())def test_a_withheld_name_counts_only_standing_on_its_own(self) -> None:# A host library directory listed relatively names its files relatively, so a host file's name can be the@@ -106,7 +169,7 @@ class TestValidateBundleErrorWithholding:with pytest.raises(ValidateBundleError) as raised, withholding_host_library_files(library_dirs=[tmp_path], caller_sources=[callers_source]):raise verdict- (item,) = raised.value.to_error_report().validation_errors or []+ (item,) = raised.value.validation_error_items() or []assert item.source == callers_sourcedef test_the_host_s_files_and_the_template_files_its_steps_name_are_found_in_one_walk(self, tmp_path: Path, mocker: MockerFixture) -> None:diff --git a/tests/unit/pipelex/pipeline/test_validation_errors.py b/tests/unit/pipelex/pipeline/test_validation_errors.pyindex a132d73ec..a1edbfd3a 100644--- a/tests/unit/pipelex/pipeline/test_validation_errors.py+++ b/tests/unit/pipelex/pipeline/test_validation_errors.py@@ -1,8 +1,8 @@"""Unit tests for ``build_validation_error_items`` — the shared structured-error builder.The single builder feeds both the agent CLI's ``validation_errors`` JSON array-(via ``extract_validation_errors``) and the API 422's-``ErrorReport.validation_errors`` (via ``ValidateBundleError.to_error_report``),+(via ``extract_validation_errors``) and the API's invalid verdict+(``BundleValidationFailure.validation_errors``, via ``ValidateBundleError.validation_error_items``),so the two surfaces can never drift. These tests pin the per-category fieldprojection — including the ``source`` / ``field_name`` / ``concept_code`` fieldsthat the older CLI-only extractor dropped — and the CLI↔API shape parity.@@ -10,6 +10,8 @@ that the older CLI-only extractor dropped — and the CLI↔API shape parity.import json+from mthds.protocol.problem.registry import CoreCode+from pipelex.base_exceptions import ValidationErrorCategory, ValidationErrorItemfrom pipelex.cli.agent_cli.commands.agent_output import extract_validation_errorsfrom pipelex.core.exceptions import (@@ -18,6 +20,8 @@ from pipelex.core.exceptions import (PipelexBundleBlueprintValidationErrorData,PipesAndConceptValidationErrorData,)+from pipelex.errors.bundle_validation_failure import BundleValidationFailure+from pipelex.errors.problem import ProblemViewfrom pipelex.pipeline.exceptions import ValidateBundleErrorfrom pipelex.pipeline.validation_errors import build_validation_error_itemsfrom pipelex.suggested_fix import DeleteKeyOp, RenameTableKeyOp, SetKeyOp@@ -29,7 +33,7 @@ def _build_items(exc: ValidateBundleError) -> list[ValidationErrorItem]:The pipe-validation arm uses ``pipe_validation_error_data`` (pipe validation **plus**pipe/concept instantiation errors) — the same combined accessor both real call sites- (``ValidateBundleError.to_error_report`` and the CLI ``extract_validation_errors``) pass.+ (``ValidateBundleError.validation_error_items`` and the CLI ``extract_validation_errors``) pass.The dry-run failures and the ``fallback_message`` residual are intentionally omitted here so thesetests pin the categorized projection in isolation; they have their own dedicated tests below."""@@ -134,9 +138,15 @@ class TestBuildValidationErrorItems:pipe_validation_errors=[],dry_run_failures=[DryRunFailureErrorData(- pipe_code="analyze", domain_code="probe", source="probe.mthds", message="Pipe 'analyze' failed its dry run: x"+ code=CoreCode.METHOD_WIRING_INVALID,+ pipe_code="analyze",+ domain_code="probe",+ source="probe.mthds",+ message="Pipe 'analyze' failed its dry run: x",+ ),+ DryRunFailureErrorData(+ code=CoreCode.RUNTIME_UNEXPECTED, pipe_code="publish", domain_code="probe", message="Pipe 'publish' failed its dry run: y"),- DryRunFailureErrorData(pipe_code="publish", domain_code="probe", message="Pipe 'publish' failed its dry run: y"),],)assert [item.category for item in items] == [ValidationErrorCategory.DRY_RUN, ValidationErrorCategory.DRY_RUN]@@ -158,19 +168,32 @@ class TestBuildValidationErrorItems:),],pipe_validation_errors=[],- dry_run_failures=[DryRunFailureErrorData(pipe_code="pipe_y", domain_code="dom", message="Pipe 'pipe_y' failed its dry run: z")],+ dry_run_failures=[+ DryRunFailureErrorData(+ code=CoreCode.METHOD_WIRING_INVALID, pipe_code="pipe_y", domain_code="dom", message="Pipe 'pipe_y' failed its dry run: z"+ )+ ],)assert [item.category for item in items] == [ValidationErrorCategory.PIPE_FACTORY, ValidationErrorCategory.DRY_RUN]- def test_to_error_report_projects_dry_run_failures(self) -> None:- """A ``ValidateBundleError`` carrying dry-run failures surfaces one ``dry_run`` item per failure on the report."""- report = ValidateBundleError(+ def test_a_verdict_projects_its_dry_run_failures(self) -> None:+ """A ``ValidateBundleError`` carrying dry-run failures lists one ``dry_run`` item per failure, and its problem one item each."""+ exc = ValidateBundleError(message="Dry run failed",- dry_run_failures=[DryRunFailureErrorData(pipe_code="analyze", domain_code="probe", message="Pipe 'analyze' failed its dry run: x")],- ).to_error_report()- assert report.validation_errors is not None- assert [item.category for item in report.validation_errors] == [ValidationErrorCategory.DRY_RUN]- assert report.message == "Pipe 'analyze' failed its dry run: x"+ dry_run_failures=[+ DryRunFailureErrorData(+ code=CoreCode.METHOD_WIRING_INVALID, pipe_code="analyze", domain_code="probe", message="Pipe 'analyze' failed its dry run: x"+ )+ ],+ )+ assert [item.category for item in exc.validation_error_items()] == [ValidationErrorCategory.DRY_RUN]+ assert exc.message == "Pipe 'analyze' failed its dry run: x"+ problem = exc.to_problem(view=ProblemView.CALLER)+ assert problem.code == CoreCode.METHOD_INVALID+ assert problem.errors is not None+ assert [(item.code, item.location.pipe if item.location else None) for item in problem.errors] == [+ (CoreCode.METHOD_WIRING_INVALID, "analyze")+ ]def test_fallback_message_residual_becomes_single_blueprint_item(self) -> None:"""A parse-level failure (only a message, no categorized data) yields one ``blueprint_validation`` item.@@ -197,7 +220,9 @@ class TestBuildValidationErrorItems:blueprint_errors=[],factory_errors=[],pipe_validation_errors=[],- dry_run_failures=[DryRunFailureErrorData(pipe_code="analyze", message="Pipe 'analyze' failed its dry run: x")],+ dry_run_failures=[+ DryRunFailureErrorData(code=CoreCode.METHOD_WIRING_INVALID, pipe_code="analyze", message="Pipe 'analyze' failed its dry run: x")+ ],fallback_message="should not be used",)assert [item.category for item in items] == [ValidationErrorCategory.DRY_RUN]@@ -219,18 +244,21 @@ class TestBuildValidationErrorItems:)assert [item.category for item in items] == [ValidationErrorCategory.PIPE_FACTORY]- def test_to_error_report_is_total_for_message_only_error(self) -> None:- """A bare-message ``ValidateBundleError`` still surfaces a non-empty ``validation_errors`` — the invariant is total.+ def test_validation_items_are_total_for_message_only_error(self) -> None:+ """A bare-message ``ValidateBundleError`` still lists a non-empty set of items — the invariant is total.- ``to_error_report`` passes ``fallback_message=self.message``, so even an error with no- categorized data and no dry-run channel projects one ``blueprint_validation`` residual.- An invalid verdict is therefore NEVER a bare ``detail`` with an empty ``validation_errors[]``.+ ``validation_error_items`` passes ``fallback_message=self.message``, so even an error with no+ categorized data and no dry-run channel projects one ``blueprint_validation`` residual, and its+ problem one ``method.schema_violation`` item. An invalid verdict is therefore NEVER a bare+ ``detail`` with no items."""- report = ValidateBundleError(message="Could not make 'PipelexBundleBlueprint': no blueprint found").to_error_report()- assert report.validation_errors is not None- assert report.validation_errors # non-empty: the totality guarantee- assert [item.category for item in report.validation_errors] == [ValidationErrorCategory.BLUEPRINT_VALIDATION]- assert report.validation_errors[0].message == "Could not make 'PipelexBundleBlueprint': no blueprint found"+ exc = ValidateBundleError(message="Could not make 'PipelexBundleBlueprint': no blueprint found")+ items = exc.validation_error_items()+ assert [item.category for item in items] == [ValidationErrorCategory.BLUEPRINT_VALIDATION]+ assert items[0].message == "Could not make 'PipelexBundleBlueprint': no blueprint found"+ problem = exc.to_problem(view=ProblemView.CALLER)+ assert problem.errors is not None+ assert [item.code for item in problem.errors] == [CoreCode.METHOD_SCHEMA_VIOLATION]def test_cli_extractor_is_total_for_message_only_error(self) -> None:"""The CLI ``extract_validation_errors`` is also total — a bare-message error yields one item, never an empty array."""@@ -256,29 +284,29 @@ class TestBuildValidationErrorItems:def test_cli_extractor_matches_builder_dumped_shape(self) -> None:"""The CLI ``extract_validation_errors`` dicts equal the dumped builder items — single shape, two surfaces.- Pins that the agent CLI and the API 422 emit the identical structured+ Pins that the agent CLI and the API's invalid verdict emit the identical structureditems: the CLI adapter is exactly ``model_dump(exclude_none=True)`` over- the same builder the API report uses.+ the same builder the API verdict uses."""exc = _all_category_error()cli_dicts = extract_validation_errors(exc)builder_dicts = [item.model_dump(mode="json", exclude_none=True) for item in _build_items(exc)]assert cli_dicts == builder_dicts- def test_cli_extractor_equals_api_report_validation_errors(self) -> None:- """The CLI array and the API 422 ``validation_errors`` are identical on the wire.+ def test_cli_extractor_equals_api_verdict_validation_errors(self) -> None:+ """The CLI array and the API's invalid verdict ``validation_errors`` are identical on the wire.- The API report path dumps in python mode (``to_dict`` → ``model_dump(exclude_none=True)``),- so ``category`` rides as a live ``ValidationErrorCategory`` enum, while the CLI dumps- ``mode="json"`` strings. A plain ``==`` would pass merely because ``StrEnum`` subclasses- ``str``; to prove *wire-byte* parity (and catch a future python/json-divergent field that- is not a StrEnum), we also compare the encoded JSON, not just the in-memory dicts.+ The API's verdict is the ``BundleValidationFailure`` a validator returns, built as the direct+ validator builds it. A plain ``==`` would pass merely because ``StrEnum`` subclasses ``str``; to+ prove *wire-byte* parity (and catch a future python/json-divergent field that is not a StrEnum),+ we also compare the encoded JSON, not just the in-memory dicts."""exc = _all_category_error()cli_dicts = extract_validation_errors(exc)- problem_document = exc.to_error_report().to_problem_document()- assert problem_document["validation_errors"] == cli_dicts- assert json.dumps(problem_document["validation_errors"], sort_keys=True) == json.dumps(cli_dicts, sort_keys=True)+ verdict = BundleValidationFailure(problem=exc.to_problem(view=ProblemView.OPERATOR), validation_errors=exc.validation_error_items())+ verdict_items = verdict.model_dump(mode="json", exclude_none=True)["validation_errors"]+ assert verdict_items == cli_dicts+ assert json.dumps(verdict_items, sort_keys=True) == json.dumps(cli_dicts, sort_keys=True)def test_enriched_pipe_validation_error_rides_a_suggested_fix(self) -> None:"""An enriched output-mismatch error data yields an item carrying the planner's suggested_fix."""@@ -425,7 +453,5 @@ class TestBuildValidationErrorItems:items = _build_items(exc)assert [item.category for item in items] == [ValidationErrorCategory.PIPE_VALIDATION]assert items[0].source == "instantiated.mthds"- # And the API report surfaces it (would be None/empty if the list were dropped).- report = exc.to_error_report()- assert report.validation_errors is not None- assert report.validation_errors[0].pipe_code == "pipe_inst"+ # And the verdict lists it (it would be missing if the list were dropped).+ assert [item.pipe_code for item in exc.validation_error_items()] == ["pipe_inst"]diff --git a/tests/unit/pipelex/plugins/test_bundle_validator_registry.py b/tests/unit/pipelex/plugins/test_bundle_validator_registry.pyindex 34888566b..ff920771e 100644--- a/tests/unit/pipelex/plugins/test_bundle_validator_registry.py+++ b/tests/unit/pipelex/plugins/test_bundle_validator_registry.py@@ -24,7 +24,7 @@ if TYPE_CHECKING:from collections.abc import Mapping, Sequencefrom pathlib import Path- from pipelex.base_exceptions import ErrorReport+ from pipelex.errors.bundle_validation_failure import BundleValidationFailurefrom pipelex.pipeline.validation_report import PipelexValidationReportfrom pipelex.system.caller_identity import CallerIdentityfrom pipelex.system.configuration.configs import PipelexConfig@@ -46,7 +46,7 @@ class _FakeBundleValidator:method_dir: Path | None,methods_dirs: Sequence[Path] | None,read_scope: str | None,- ) -> PipelexValidationReport | ErrorReport:+ ) -> PipelexValidationReport | BundleValidationFailure:raise NotImplementedErrordiff --git a/tests/unit/pipelex/plugins/test_http_error_mapper_seam.py b/tests/unit/pipelex/plugins/test_http_error_mapper_seam.pyindex 7ece8416d..66e72362a 100644--- a/tests/unit/pipelex/plugins/test_http_error_mapper_seam.py+++ b/tests/unit/pipelex/plugins/test_http_error_mapper_seam.py@@ -1,4 +1,4 @@-"""Tests for the F3 HTTP-error-mapper seam: the registrar collects exc->ErrorReport mappers, resolving the exc type lazily (import-light register)."""+"""Tests for the F3 HTTP-error-mapper seam: the registrar collects exc->PipelexError mappers, resolving the exc type lazily (import-light)."""from __future__ import annotations@@ -8,12 +8,14 @@ from typing import TYPE_CHECKING, castimport pytestfrom mthds.protocol.problem.registry import CoreCode-from pipelex.base_exceptions import ErrorReport+from pipelex.errors.problem import ProblemViewfrom pipelex.plugins.contract import PLUGIN_API_VERSIONfrom pipelex.plugins.exceptions import DuplicateHttpErrorMapperErrorfrom pipelex.plugins.registrar import PluginOrigin, PluginRegistrar+from pipelex.runtime_bridge.exceptions import PipelexBridgeDispatchErrorif TYPE_CHECKING:+ from pipelex.base_exceptions import PipelexErrorfrom pipelex.system.configuration.configs import PipelexConfig@@ -25,26 +27,31 @@ def _make_registrar() -> PluginRegistrar:return PluginRegistrar(config=cast("PipelexConfig", SimpleNamespace(runtime=SimpleNamespace(plugins=SimpleNamespace(disabled=[])))))-def _to_report(exc: Exception) -> ErrorReport:- return ErrorReport.make_for_code(code=CoreCode.PROVIDER_UNAVAILABLE, error_type="FakeTransportError", message=str(exc))+def _to_pipelex_error(exc: Exception) -> PipelexError:+ """The error a plugin maps its orchestrator's transport fault to: here the bridge's own dispatch failure."""+ return PipelexBridgeDispatchError(str(exc))class TestHttpErrorMapperSeam:- """A plugin contributes an exc->ErrorReport mapper via a lazy exc-type provider; the registrar resolves it on read, fail-loud on dups."""+ """A plugin contributes an exc->PipelexError mapper via a lazy exc-type provider; the registrar resolves it on read, fail-loud on dups."""def test_add_and_get_mapper(self) -> None:- """A registered mapper is returned keyed by its resolved exc_type and produces the classified ErrorReport when invoked."""+ """A registered mapper is returned keyed by its resolved exc_type and produces the classified PipelexError when invoked."""registrar = _make_registrar()registrar.begin_plugin(name="alpha", origin=PluginOrigin.EXTERNAL, targets_api=PLUGIN_API_VERSION, group=None)- registrar.add_http_error_mapper(exc_type_provider=lambda: _FakeTransportError, to_error_report=_to_report)+ registrar.add_http_error_mapper(exc_type_provider=lambda: _FakeTransportError, to_pipelex_error=_to_pipelex_error)mappers = registrar.get_http_error_mappers()assert set(mappers) == {_FakeTransportError}- report = mappers[_FakeTransportError](_FakeTransportError("server unreachable"))- assert report.code == CoreCode.PROVIDER_UNAVAILABLE- assert report.retryable is True- assert report.message == "server unreachable"+ error = mappers[_FakeTransportError](_FakeTransportError("server unreachable"))+ caller = error.to_problem(view=ProblemView.CALLER)+ assert caller.code == CoreCode.RUNTIME_UNEXPECTED+ assert "server unreachable" not in str(caller.to_wire())+ operator = error.to_problem(view=ProblemView.OPERATOR)+ assert operator.diagnostics is not None+ assert operator.diagnostics.error_class == "PipelexBridgeDispatchError"+ assert operator.diagnostics.message == "server unreachable"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."""@@ -57,7 +64,7 @@ class TestHttpErrorMapperSeam:resolutions.append(1)return _FakeTransportError- registrar.add_http_error_mapper(exc_type_provider=_provider, to_error_report=_to_report)+ registrar.add_http_error_mapper(exc_type_provider=_provider, to_pipelex_error=_to_pipelex_error)assert resolutions == [] # registration must not have called the providerresolved = registrar.get_http_error_mappers()@@ -72,7 +79,7 @@ class TestHttpErrorMapperSeam:def _exploding_provider() -> type[Exception]:pytest.fail("provider must not run at registration")- registrar.add_http_error_mapper(exc_type_provider=_exploding_provider, to_error_report=_to_report)+ registrar.add_http_error_mapper(exc_type_provider=_exploding_provider, to_pipelex_error=_to_pipelex_error)assert "http error mapper" in discovery.contributions@@ -80,9 +87,9 @@ class TestHttpErrorMapperSeam:"""Two plugins resolving to the same exception type is a fail-loud conflict naming both — detected at resolution time."""registrar = _make_registrar()registrar.begin_plugin(name="alpha", origin=PluginOrigin.EXTERNAL, targets_api=PLUGIN_API_VERSION, group=None)- registrar.add_http_error_mapper(exc_type_provider=lambda: _FakeTransportError, to_error_report=_to_report)+ registrar.add_http_error_mapper(exc_type_provider=lambda: _FakeTransportError, to_pipelex_error=_to_pipelex_error)registrar.begin_plugin(name="beta", origin=PluginOrigin.EXTERNAL, targets_api=PLUGIN_API_VERSION, group=None)- registrar.add_http_error_mapper(exc_type_provider=lambda: _FakeTransportError, to_error_report=_to_report)+ registrar.add_http_error_mapper(exc_type_provider=lambda: _FakeTransportError, to_pipelex_error=_to_pipelex_error)with pytest.raises(DuplicateHttpErrorMapperError) as exc_info:registrar.get_http_error_mappers()@@ -95,12 +102,12 @@ class TestHttpErrorMapperSeam:"""The accessor hands back a freshly built dict, so a consumer cannot mutate the registrar's accumulated state."""registrar = _make_registrar()registrar.begin_plugin(name="alpha", origin=PluginOrigin.EXTERNAL, targets_api=PLUGIN_API_VERSION, group=None)- registrar.add_http_error_mapper(exc_type_provider=lambda: _FakeTransportError, to_error_report=_to_report)+ registrar.add_http_error_mapper(exc_type_provider=lambda: _FakeTransportError, to_pipelex_error=_to_pipelex_error)snapshot = registrar.get_http_error_mappers()snapshot.clear()- assert registrar.get_http_error_mappers() == {_FakeTransportError: _to_report}+ assert registrar.get_http_error_mappers() == {_FakeTransportError: _to_pipelex_error}def test_no_mappers_by_default(self) -> None:"""A registrar with no contributions exposes an empty mapper set (host wraps nothing, resolves nothing)."""diff --git a/tests/unit/pipelex/plugins/test_import_light_boot.py b/tests/unit/pipelex/plugins/test_import_light_boot.pyindex 9bcad8507..4bfe0efa2 100644--- a/tests/unit/pipelex/plugins/test_import_light_boot.py+++ b/tests/unit/pipelex/plugins/test_import_light_boot.py@@ -30,7 +30,7 @@ _GUARD_SCRIPT = textwrap.dedent("pypdfium2","typesafe_sdk",# No web framework either: the F3 HTTP-error-mapper seam is framework-agnostic- # (it carries the core ``ErrorReport`` type). A host runtime owns FastAPI/Starlette;+ # (it carries the core problem type). A host runtime owns FastAPI/Starlette;# discovery/registration in core must never pull one in."fastapi","starlette",diff --git a/tests/unit/pipelex/plugins/test_plugin_discovery.py b/tests/unit/pipelex/plugins/test_plugin_discovery.pyindex f77f5c13d..226a28acc 100644--- a/tests/unit/pipelex/plugins/test_plugin_discovery.py+++ b/tests/unit/pipelex/plugins/test_plugin_discovery.py@@ -171,7 +171,14 @@ class TestPluginDiscovery:with pytest.raises(PluginApiVersionMismatchError) as exc_info:_build_registrar_with(mocker=mocker, plugins=[v7_plugin])assert "written_against_v7" in str(exc_info.value)- assert PLUGIN_API_VERSION == 8++ def test_a_plugin_written_before_failures_crossed_as_problems_is_refused(self, mocker: MockerFixture) -> None:+ """Plugin API v8 took HTTP error mappers returning a report; a v8 plugin's mapper would hand the host a report it no longer reads."""+ v8_plugin = _InferencePlugin(name="written_against_v8", sdk="v8_sdk", targets_api=8)+ with pytest.raises(PluginApiVersionMismatchError) as exc_info:+ _build_registrar_with(mocker=mocker, plugins=[v8_plugin])+ assert "written_against_v8" in str(exc_info.value)+ assert PLUGIN_API_VERSION == 9def test_duplicate_inference_backend_names_both(self, mocker: MockerFixture) -> None:with pytest.raises(DuplicateInferenceBackendError) as exc_info:diff --git a/tests/unit/pipelex/plugins/test_plugin_group_split.py b/tests/unit/pipelex/plugins/test_plugin_group_split.pyindex 6e089e8f0..8f309e92b 100644--- a/tests/unit/pipelex/plugins/test_plugin_group_split.py+++ b/tests/unit/pipelex/plugins/test_plugin_group_split.py@@ -20,7 +20,7 @@ if TYPE_CHECKING:from pytest_mock import MockerFixture- from pipelex.base_exceptions import ErrorReport+ from pipelex.base_exceptions import PipelexErrorfrom pipelex.cogt.inference.inference_worker_abstract import InferenceWorkerAbstractfrom pipelex.plugins.bundle_validator_registry import BundleValidatorProtocolfrom pipelex.plugins.contract import PipelexPlugin@@ -84,7 +84,7 @@ def _add_inference_backend(registrar: PluginRegistrar) -> None:def _add_http_error_mapper(registrar: PluginRegistrar) -> None:- registrar.add_http_error_mapper(exc_type_provider=lambda: TimeoutError, to_error_report=cast("Callable[..., ErrorReport]", object))+ registrar.add_http_error_mapper(exc_type_provider=lambda: TimeoutError, to_pipelex_error=cast("Callable[..., PipelexError]", object))def _add_teardown(registrar: PluginRegistrar) -> None:diff --git a/tests/unit/pipelex/providers/anthropic/test_anthropic_structured_clamp.py b/tests/unit/pipelex/providers/anthropic/test_anthropic_structured_clamp.pyindex a5766fcb7..1958c287c 100644--- a/tests/unit/pipelex/providers/anthropic/test_anthropic_structured_clamp.py+++ b/tests/unit/pipelex/providers/anthropic/test_anthropic_structured_clamp.py@@ -9,6 +9,7 @@ from anthropic.types import ToolUseBlockfrom pipelex.cogt.exceptions import InferenceErrorCategory, LLMCompletionErrorfrom pipelex.cogt.llm.structured_output import StructureMethod+from pipelex.errors.problem import ProblemViewfrom pipelex.providers.anthropic import anthropic_llm_workerfrom tests.helpers.anthropic_structured_request import make_message, make_structured_worker, sent_requestfrom tests.helpers.instructor_test_utils import DummySchema, make_llm_job, wrap_in_instructor_retry@@ -114,7 +115,7 @@ class TestAnthropicStructuredClamp:assert error.message.endswith(LOWERED_NOTE)assert str(error) == error.messageassert error.error_category == InferenceErrorCategory.TRANSIENT- assert error.to_error_report().retryable is True+ assert error.to_problem(view=ProblemView.CALLER).is_retryable is Trueasync def test_an_invalid_output_of_the_lowered_call_says_the_limit_was_lowered(self, mocker: MockerFixture) -> None:"""An output that still fails validation once instructor's re-asks are spent may have been cut by the lowered limit."""diff --git a/tests/unit/pipelex/providers/anthropic/test_anthropic_worker_error_handling.py b/tests/unit/pipelex/providers/anthropic/test_anthropic_worker_error_handling.pyindex 2b5b03e21..09dc51a50 100644--- a/tests/unit/pipelex/providers/anthropic/test_anthropic_worker_error_handling.py+++ b/tests/unit/pipelex/providers/anthropic/test_anthropic_worker_error_handling.py@@ -11,8 +11,9 @@ import pytestif TYPE_CHECKING:from pytest_mock import MockerFixture-from pipelex.cogt.exceptions import InferenceErrorCategory, LLMCompletionError, LLMModelNotFoundError+from pipelex.cogt.exceptions import InferenceErrorCategory, LLMCompletionError, LLMModelNotFoundError, find_inference_error_category_in_chainfrom pipelex.cogt.inference.error_classification import UserActionKind+from pipelex.errors.problem import ProblemViewfrom pipelex.providers.anthropic.anthropic_llm_worker import AnthropicLLMWorkerfrom tests.unit.pipelex.providers.anthropic.test_data import AnthropicErrorHandlingTestData@@ -271,10 +272,10 @@ class TestAnthropicWorkerErrorHandling:assert exc_info.value.model_handle == "claude-sonnet-4"assert exc_info.value.__cause__ is sdk_exc- # ---- to_error_report() integration ----+ # ---- Problem integration ----- async def test_error_report_includes_category(self, mocker: MockerFixture) -> None:- """to_error_report() includes error_category and retryable from the exception."""+ async def test_problem_includes_category(self, mocker: MockerFixture) -> None:+ """The category stays on the chain, and the problem takes the retry verdict of the code it gives."""worker = _make_worker(mocker)sdk_exc = _make_anthropic_rate_limit_error("Rate limit exceeded")worker.anthropic_async_client.messages.stream.side_effect = sdk_exc # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue]@@ -282,6 +283,7 @@ class TestAnthropicWorkerErrorHandling:with pytest.raises(LLMCompletionError) as exc_info:await worker._gen_text(llm_job=_make_llm_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+ error = exc_info.value+ problem = error.to_problem(view=ProblemView.OPERATOR)+ assert find_inference_error_category_in_chain(error) == "transient"+ assert problem.is_retryable is Truediff --git a/tests/unit/pipelex/providers/anthropic/test_anthropic_worker_object_error_handling.py b/tests/unit/pipelex/providers/anthropic/test_anthropic_worker_object_error_handling.pyindex 215d25d58..478612466 100644--- a/tests/unit/pipelex/providers/anthropic/test_anthropic_worker_object_error_handling.py+++ b/tests/unit/pipelex/providers/anthropic/test_anthropic_worker_object_error_handling.py@@ -18,6 +18,7 @@ if TYPE_CHECKING:from pipelex.cogt.exceptions import InferenceErrorCategory, LLMCompletionError, LLMModelNotFoundErrorfrom pipelex.cogt.inference.error_classification import UserActionKind+from pipelex.errors.problem import ProblemViewfrom pipelex.providers.anthropic.anthropic_llm_worker import AnthropicLLMWorkerfrom tests.helpers.instructor_test_utils import DummySchema, make_llm_job, wrap_in_instructor_retry@@ -282,8 +283,8 @@ class TestAnthropicWorkerObjectErrorHandling:assert exc_info.value.user_action is not Noneassert exc_info.value.user_action.kind is UserActionKind.CONTACT_SUPPORT- async def test_provider_metadata_is_serialized_in_error_report(self, mocker: MockerFixture) -> None:- """``to_error_report()`` must surface ``provider_metadata`` so downstream consumers see it."""+ async def test_provider_facts_are_serialized_in_the_operator_problem(self, mocker: MockerFixture) -> None:+ """The operator's problem carries what the provider answered, and the error advises its local reader what to do."""_patch_gen_object_dependencies(mocker)worker = _make_worker(mocker)sdk_exc = _make_anthropic_rate_limit_error("Your account quota has been exceeded")@@ -293,19 +294,20 @@ class TestAnthropicWorkerObjectErrorHandling:with pytest.raises(LLMCompletionError) as exc_info:await worker._gen_object(llm_job=make_llm_job(mocker), schema=DummySchema) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]- report = exc_info.value.to_error_report()- report_dict = report.to_dict()- assert "provider_metadata" in report_dict- metadata_dict = report_dict["provider_metadata"]- assert isinstance(metadata_dict, dict)- assert metadata_dict["provider"] == "anthropic"- assert metadata_dict["sdk_exception_type"] == "RateLimitError"- assert metadata_dict["status_code"] == 429- assert "user_action" in report_dict- user_action_dict = report_dict["user_action"]- assert isinstance(user_action_dict, dict)- assert user_action_dict["kind"] == UserActionKind.CHECK_BILLING- assert isinstance(user_action_dict["detail"], str)+ error = exc_info.value+ problem = error.to_problem(view=ProblemView.OPERATOR)+ problem_wire = problem.to_wire()+ # The provider's `name` is the backend the error names, which the worker leaves to its caller to fill.+ assert problem_wire["diagnostics"]["provider"] == {+ "status": 429,+ "message": "Your account quota has been exceeded",+ }+ # What the provider answered is the operator's alone.+ assert "diagnostics" not in error.to_problem(view=ProblemView.CALLER).to_wire()+ advice = error.advised_action()+ assert advice is not None+ assert advice.kind == UserActionKind.CHECK_BILLING+ assert advice.detailasync def test_real_instructor_transport_error_is_unwrapped(self, mocker: MockerFixture) -> None:"""End-to-end: drive the real instructor library with an SDK transport exception and verifydiff --git a/tests/unit/pipelex/providers/azure_rest/test_azure_worker_error_handling.py b/tests/unit/pipelex/providers/azure_rest/test_azure_worker_error_handling.pyindex 07d5ba414..3c37c315d 100644--- a/tests/unit/pipelex/providers/azure_rest/test_azure_worker_error_handling.py+++ b/tests/unit/pipelex/providers/azure_rest/test_azure_worker_error_handling.py@@ -7,8 +7,9 @@ from typing import TYPE_CHECKING, Anyimport httpximport pytest-from pipelex.cogt.exceptions import ImgGenGenerationError, InferenceErrorCategory+from pipelex.cogt.exceptions import ImgGenGenerationError, InferenceErrorCategory, find_inference_error_category_in_chainfrom pipelex.cogt.inference.error_classification import UserActionKind+from pipelex.errors.problem import PipelexProblem, ProblemDiagnostics, ProblemViewfrom pipelex.providers.azure_rest.azure_img_gen_worker import AzureImgGenWorkerfrom tests.unit.pipelex.providers.azure_rest.test_data import AzureErrorHandlingTestData@@ -47,6 +48,12 @@ def _make_img_gen_job(mocker: MockerFixture) -> Any:return job+def _diagnostics_of(problem: PipelexProblem) -> ProblemDiagnostics:+ """The operator's diagnostics of a problem built in the operator view."""+ assert problem.diagnostics is not None+ return problem.diagnostics++@pytest.mark.asyncio(loop_scope="class")class TestAzureWorkerErrorHandling:"""Tests for Azure ImgGen worker HTTP exception handling and error categorization."""@@ -164,8 +171,8 @@ class TestAzureWorkerErrorHandling:assert exc_info.value.user_action.kind is expected_user_action_kindassert exc_info.value.__cause__ is sdk_exc- async def test_error_report_includes_category(self, mocker: MockerFixture) -> None:- """to_error_report() includes error_category and retryable from the exception."""+ async def test_problem_includes_category(self, mocker: MockerFixture) -> None:+ """The category stays on the chain, and the problem takes the retry verdict of the code it gives."""worker = _make_azure_img_gen_worker(mocker)sdk_exc = _make_httpx_status_error(429, "Rate limit exceeded")@@ -186,10 +193,11 @@ class TestAzureWorkerErrorHandling: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]- report = exc_info.value.to_error_report()- assert report.error_category == "transient"- assert report.retryable is True- assert report.error_type == "ImgGenGenerationError"+ error = exc_info.value+ problem = error.to_problem(view=ProblemView.OPERATOR)+ assert find_inference_error_category_in_chain(error) == "transient"+ assert problem.is_retryable is True+ assert _diagnostics_of(problem).error_class == "ImgGenGenerationError"assert exc_info.value.error_category is InferenceErrorCategory.TRANSIENTassert exc_info.value.user_action is not Noneassert exc_info.value.user_action.kind is UserActionKind.WAIT_AND_RETRYdiff --git a/tests/unit/pipelex/providers/bedrock/test_bedrock_worker_error_handling.py b/tests/unit/pipelex/providers/bedrock/test_bedrock_worker_error_handling.pyindex eaac87004..445d902ff 100644--- a/tests/unit/pipelex/providers/bedrock/test_bedrock_worker_error_handling.py+++ b/tests/unit/pipelex/providers/bedrock/test_bedrock_worker_error_handling.py@@ -10,7 +10,8 @@ from botocore.exceptions import ClientErrorif TYPE_CHECKING:from pytest_mock import MockerFixture-from pipelex.cogt.exceptions import InferenceErrorCategory, LLMCompletionError+from pipelex.cogt.exceptions import InferenceErrorCategory, LLMCompletionError, find_inference_error_category_in_chain+from pipelex.errors.problem import PipelexProblem, ProblemDiagnostics, ProblemViewfrom pipelex.providers.bedrock.bedrock_llm_worker import BedrockLLMWorkerfrom tests.unit.pipelex.providers.bedrock.test_data import BedrockLLMErrorHandlingTestData@@ -55,6 +56,12 @@ def _make_llm_job(mocker: MockerFixture) -> Any:return job+def _diagnostics_of(problem: PipelexProblem) -> ProblemDiagnostics:+ """The operator's diagnostics of a problem built in the operator view."""+ assert problem.diagnostics is not None+ return problem.diagnostics++@pytest.mark.asyncio(loop_scope="class")class TestBedrockWorkerErrorHandling:"""Tests for Bedrock worker ClientError exception handling and error categorization."""@@ -96,10 +103,10 @@ class TestBedrockWorkerErrorHandling:assert exc_info.value.user_action is not Noneassert expected_action_substring in exc_info.value.user_action.detail.lower()- # ---- to_error_report() integration ----+ # ---- Problem integration ----- async def test_error_report_transient_is_retryable(self, mocker: MockerFixture) -> None:- """to_error_report() for TRANSIENT Bedrock errors has retryable=True."""+ async def test_problem_transient_is_retryable(self, mocker: MockerFixture) -> None:+ """The problem of a TRANSIENT Bedrock error invites a retry."""worker = _make_bedrock_llm_worker(mocker)sdk_exc = _make_bedrock_client_error("ThrottlingException", "Rate exceeded for model")worker.bedrock_client_for_text.chat.side_effect = sdk_exc # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue]@@ -114,13 +121,14 @@ class TestBedrockWorkerErrorHandling:with pytest.raises(LLMCompletionError) as exc_info:await worker._gen_text(llm_job=_make_llm_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_type == "LLMCompletionError"+ error = exc_info.value+ problem = error.to_problem(view=ProblemView.OPERATOR)+ assert find_inference_error_category_in_chain(error) == "transient"+ assert problem.is_retryable is True+ assert _diagnostics_of(problem).error_class == "LLMCompletionError"- async def test_error_report_capacity_not_retryable(self, mocker: MockerFixture) -> None:- """to_error_report() for CAPACITY Bedrock errors has retryable=False."""+ async def test_problem_capacity_not_retryable(self, mocker: MockerFixture) -> None:+ """The problem of a CAPACITY Bedrock error invites no retry."""worker = _make_bedrock_llm_worker(mocker)sdk_exc = _make_bedrock_client_error("ServiceQuotaExceededException", "Service quota exceeded")worker.bedrock_client_for_text.chat.side_effect = sdk_exc # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue]@@ -135,12 +143,13 @@ class TestBedrockWorkerErrorHandling:with pytest.raises(LLMCompletionError) as exc_info:await worker._gen_text(llm_job=_make_llm_job(mocker)) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]- report = exc_info.value.to_error_report()- assert report.error_category == "capacity"- assert report.retryable is False+ error = exc_info.value+ problem = error.to_problem(view=ProblemView.OPERATOR)+ assert find_inference_error_category_in_chain(error) == "capacity"+ assert problem.is_retryable is False- async def test_error_report_configuration_not_retryable(self, mocker: MockerFixture) -> None:- """to_error_report() for CONFIGURATION Bedrock errors has retryable=False."""+ async def test_problem_configuration_not_retryable(self, mocker: MockerFixture) -> None:+ """The problem of a CONFIGURATION Bedrock error invites no retry."""worker = _make_bedrock_llm_worker(mocker)sdk_exc = _make_bedrock_client_error("AccessDeniedException", "Access denied")worker.bedrock_client_for_text.chat.side_effect = sdk_exc # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue]@@ -155,6 +164,7 @@ class TestBedrockWorkerErrorHandling:with pytest.raises(LLMCompletionError) as exc_info:await worker._gen_text(llm_job=_make_llm_job(mocker)) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]- report = exc_info.value.to_error_report()- assert report.error_category == "configuration"- assert report.retryable is False+ error = exc_info.value+ problem = error.to_problem(view=ProblemView.OPERATOR)+ assert find_inference_error_category_in_chain(error) == "configuration"+ assert problem.is_retryable is Falsediff --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 96f8a8a41..c707f8366 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@@ -12,7 +12,8 @@ if TYPE_CHECKING:from pipelex.cogt.inference.error_classification import UserActionKind-from pipelex.cogt.exceptions import ExtractJobFailureError, InferenceErrorCategory+from pipelex.cogt.exceptions import ExtractJobFailureError, InferenceErrorCategory, find_inference_error_category_in_chain+from pipelex.errors.problem import PipelexProblem, ProblemDiagnostics, ProblemViewfrom pipelex.providers.docling.docling_extract_worker import DoclingExtractWorkerfrom tests.unit.pipelex.providers.docling.test_data import DoclingErrorHandlingTestData@@ -33,6 +34,12 @@ def _make_docling_extract_worker(mocker: MockerFixture) -> DoclingExtractWorker:return worker+def _diagnostics_of(problem: PipelexProblem) -> ProblemDiagnostics:+ """The operator's diagnostics of a problem built in the operator view."""+ assert problem.diagnostics is not None+ return problem.diagnostics++@pytest.mark.asyncio(loop_scope="class")class TestDoclingWorkerErrorHandling:"""Tests for Docling extract worker exception handling and error categorization."""@@ -68,8 +75,8 @@ class TestDoclingWorkerErrorHandling:assert exc_info.value.user_action is not Noneassert exc_info.value.user_action.kind is expected_user_action_kind- async def test_error_report_for_file_not_found(self, mocker: MockerFixture) -> None:- """to_error_report() for FileNotFoundError has CONTENT category."""+ async def test_problem_for_file_not_found(self, mocker: MockerFixture) -> None:+ """A FileNotFoundError is a CONTENT failure, and its problem invites no retry."""worker = _make_docling_extract_worker(mocker)sdk_exc = FileNotFoundError("No such file: /tmp/missing.pdf")@@ -81,12 +88,13 @@ class TestDoclingWorkerErrorHandling:with pytest.raises(ExtractJobFailureError) as exc_info: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 == "content"- assert report.retryable is False- assert report.error_type == "ExtractJobFailureError"+ error = exc_info.value+ problem = error.to_problem(view=ProblemView.OPERATOR)+ assert find_inference_error_category_in_chain(error) == "content"+ assert problem.is_retryable is False+ assert _diagnostics_of(problem).error_class == "ExtractJobFailureError"- async def test_error_report_for_io_error(self, mocker: MockerFixture) -> None:+ async def test_problem_for_io_error(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_docling_extract_worker(mocker)sdk_exc = OSError("Disk I/O failure")@@ -99,7 +107,8 @@ class TestDoclingWorkerErrorHandling:with pytest.raises(ExtractJobFailureError) as exc_info: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 == "unknown"- assert report.code == CoreCode.RUNTIME_UNEXPECTED- assert report.retryable is False+ error = exc_info.value+ problem = error.to_problem(view=ProblemView.OPERATOR)+ assert find_inference_error_category_in_chain(error) == "unknown"+ assert problem.code == CoreCode.RUNTIME_UNEXPECTED+ assert problem.is_retryable is Falsediff --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 4e1f6f005..54751cad4 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@@ -9,8 +9,9 @@ import pytestfrom fal_client.auth import MissingCredentialsErrorfrom fal_client.client import FalClientError, FalClientHTTPError, FalClientTimeoutError-from pipelex.cogt.exceptions import ImgGenGenerationError, InferenceErrorCategory+from pipelex.cogt.exceptions import ImgGenGenerationError, InferenceErrorCategory, find_inference_error_category_in_chainfrom pipelex.cogt.inference.error_classification import UserActionKind+from pipelex.errors.problem import PipelexProblem, ProblemDiagnostics, ProblemViewfrom pipelex.providers.fal.fal_img_gen_worker import FalImgGenWorkerfrom tests.unit.pipelex.providers.fal.test_data import FalErrorHandlingTestData@@ -65,6 +66,12 @@ def _make_img_gen_job(mocker: MockerFixture) -> Any:return job+def _diagnostics_of(problem: PipelexProblem) -> ProblemDiagnostics:+ """The operator's diagnostics of a problem built in the operator view."""+ assert problem.diagnostics is not None+ return problem.diagnostics++@pytest.mark.asyncio(loop_scope="class")class TestFalWorkerErrorHandling:"""Tests for FAL ImgGen worker SDK exception handling and error categorization."""@@ -191,8 +198,8 @@ class TestFalWorkerErrorHandling:assert exc_info.value.user_action.kind is expected_user_action_kindassert exc_info.value.__cause__ is sdk_exc- async def test_error_report_includes_category(self, mocker: MockerFixture) -> None:- """to_error_report() includes error_category and retryable from the exception."""+ async def test_problem_includes_category(self, mocker: MockerFixture) -> None:+ """The category stays on the chain, and the problem takes the retry verdict of the code it gives."""worker = _make_fal_img_gen_worker(mocker)sdk_exc = _make_fal_http_error(402, "Payment required")worker.fal_async_client.submit.side_effect = sdk_exc # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue]@@ -206,10 +213,11 @@ class TestFalWorkerErrorHandling: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]- report = exc_info.value.to_error_report()- assert report.error_category == "capacity"- assert report.retryable is False- assert report.error_type == "ImgGenGenerationError"+ error = exc_info.value+ problem = error.to_problem(view=ProblemView.OPERATOR)+ assert find_inference_error_category_in_chain(error) == "capacity"+ assert problem.is_retryable is False+ assert _diagnostics_of(problem).error_class == "ImgGenGenerationError"assert exc_info.value.error_category is InferenceErrorCategory.CAPACITYassert exc_info.value.user_action is not Noneassert exc_info.value.user_action.kind is UserActionKind.CHECK_BILLINGdiff --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 b7462b7be..5a3bf55fe 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@@ -16,10 +16,11 @@ from google.genai import errors as genai_errorsif TYPE_CHECKING:from pytest_mock import MockerFixture-from pipelex.cogt.exceptions import ImgGenGenerationError, ImgGenModelNotFoundError, InferenceErrorCategory+from pipelex.cogt.exceptions import ImgGenGenerationError, ImgGenModelNotFoundError, InferenceErrorCategory, find_inference_error_category_in_chainfrom pipelex.cogt.img_gen.img_gen_gemini_mapping import ResolvedGeminiImageConfigfrom pipelex.cogt.img_gen.img_gen_model_rules import AspectRatioTaxonomy, ImgGenArgTopicfrom pipelex.cogt.inference.error_classification import UserActionKind+from pipelex.errors.problem import PipelexProblem, ProblemDiagnostics, ProblemView, ProviderDiagnosticsfrom pipelex.providers.google.google_img_gen_worker import GoogleImgGenWorker@@ -62,6 +63,19 @@ def _make_img_gen_job(mocker: MockerFixture) -> Any:return job+def _diagnostics_of(problem: PipelexProblem) -> ProblemDiagnostics:+ """The operator's diagnostics of a problem built in the operator view."""+ assert problem.diagnostics is not None+ return problem.diagnostics+++def _provider_of(problem: PipelexProblem) -> ProviderDiagnostics:+ """What the provider answered, from the operator's diagnostics."""+ provider = _diagnostics_of(problem).provider+ assert provider is not None+ return provider++@pytest.mark.asyncio(loop_scope="class")class TestGoogleImgGenWorkerErrorHandling:"""Asserts metadata + user_action.kind for every classification branch."""@@ -221,7 +235,7 @@ class TestGoogleImgGenWorkerErrorHandling:assert exc_info.value.provider_metadata.sdk_exception_type == expected_sdk_typeassert exc_info.value.__cause__ is sdk_exc- async def test_to_error_report_serializes_metadata(self, mocker: MockerFixture) -> None:+ async def test_the_operator_problem_carries_the_provider_facts(self, mocker: MockerFixture) -> None:worker = _make_worker(mocker)sdk_exc = _make_google_client_error(429, "Resource has been exhausted", status="RESOURCE_EXHAUSTED")worker.genai_async_client.models.generate_content.side_effect = sdk_exc # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue]@@ -229,9 +243,10 @@ 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]- report = exc_info.value.to_error_report()- assert report.error_category == "capacity"- assert report.retryable is False- assert report.provider_metadata is not None- assert report.provider_metadata.provider == "google"- assert report.provider_metadata.status_code == 429+ error = exc_info.value+ problem = error.to_problem(view=ProblemView.OPERATOR)+ assert find_inference_error_category_in_chain(error) == "capacity"+ assert problem.is_retryable is False+ # The provider's `name` is the backend the error names, which the worker leaves to its caller to fill.+ assert _provider_of(problem).name is None+ assert _provider_of(problem).status == 429diff --git a/tests/unit/pipelex/providers/google/test_google_img_gen_worker_refusal.py b/tests/unit/pipelex/providers/google/test_google_img_gen_worker_refusal.pyindex 480eef4fa..a9dc3b496 100644--- a/tests/unit/pipelex/providers/google/test_google_img_gen_worker_refusal.py+++ b/tests/unit/pipelex/providers/google/test_google_img_gen_worker_refusal.py@@ -7,14 +7,15 @@ import httpximport pytestfrom google import genaifrom google.genai import types as genai_types-from mthds.protocol.problem.registry import CoreCode+from mthds.protocol.problem.registry import CoreCode, ProblemDomain, RetryVerdict-from pipelex.base_exceptions import ErrorDomainfrom pipelex.cogt.exceptions import ImgGenGenerationError, ImgGenOutputTruncatedError, InferenceErrorCategoryfrom pipelex.cogt.img_gen.img_gen_gemini_mapping import ResolvedGeminiImageConfigfrom pipelex.cogt.img_gen.img_gen_model_rules import AspectRatioTaxonomy, ImgGenArgTopicfrom pipelex.cogt.inference.error_classification import UserActionKindfrom pipelex.cogt.llm import completion_stop+from pipelex.errors.error_codes import error_code_spec+from pipelex.errors.problem import ProblemViewfrom pipelex.providers.google.google_img_gen_worker import GoogleImgGenWorkerif TYPE_CHECKING:@@ -121,11 +122,15 @@ class TestGoogleImgGenWorkerRefusal:assert f"'{reason}'" in error.messageassert f"'{_MODEL_HANDLE}'" in error.messageassert _MODEL_ID not in error.message- report = error.to_error_report()- assert report.code == CoreCode.MODEL_CONTENT_REFUSED- assert report.error_domain == ErrorDomain.INPUT- assert report.http_status == 422- assert report.caller_facing_message is True+ caller = error.to_problem(view=ProblemView.CALLER)+ assert caller.code == CoreCode.MODEL_CONTENT_REFUSED+ assert caller.domain == ProblemDomain.INPUT+ assert error_code_spec(CoreCode.MODEL_CONTENT_REFUSED).status == 422+ # The caller reads the code's sentence, never the provider's model id, and the reason rides the operator's view.+ assert _MODEL_ID not in str(caller.to_wire())+ operator = error.to_problem(view=ProblemView.OPERATOR)+ assert operator.diagnostics is not None+ assert operator.diagnostics.message == error.message@pytest.mark.parametrize(("answer", "expected_message"),@@ -228,11 +233,14 @@ class TestGoogleImgGenWorkerRefusal:assert error.user_action is not Noneassert error.user_action.kind is UserActionKind.CHANGE_INPUTassert error.user_action.detail == "Simplify the image prompt, or choose another image model."- report = error.to_error_report()- assert report.code == CoreCode.MODEL_OUTPUT_TRUNCATED- assert report.http_status == 422- assert report.retryable is False- assert report.caller_facing_message is True+ caller = error.to_problem(view=ProblemView.CALLER)+ assert caller.code == CoreCode.MODEL_OUTPUT_TRUNCATED+ assert error_code_spec(CoreCode.MODEL_OUTPUT_TRUNCATED).status == 422+ assert caller.retry == RetryVerdict.NO+ assert _MODEL_ID not in str(caller.to_wire())+ operator = error.to_problem(view=ProblemView.OPERATOR)+ assert operator.diagnostics is not None+ assert operator.diagnostics.message == error.message@pytest.mark.parametrize("answer", [_GENERATED_IMAGE, _GENERATED_IMAGE_AT_THE_LIMIT], ids=["stopped", "stopped-at-the-limit"])async def test_a_generated_image_is_returned(self, mocker: MockerFixture, answer: dict[str, Any]) -> None:diff --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 13d65da21..11ce54a1f 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@@ -16,9 +16,11 @@ from pipelex.cogt.exceptions import (InferenceErrorCategory,LLMCompletionError,LLMModelNotFoundError,+ find_inference_error_category_in_chain,)from pipelex.cogt.img_gen.img_gen_model_rules import AspectRatioTaxonomy, ImgGenArgTopicfrom pipelex.cogt.inference.error_classification import UserActionKind+from pipelex.errors.problem import PipelexProblem, ProblemDiagnostics, ProblemViewfrom pipelex.providers.google.google_img_gen_worker import GoogleImgGenWorkerfrom pipelex.providers.google.google_llm_worker import GoogleLLMWorkerfrom tests.unit.pipelex.providers.google.test_data import GoogleErrorHandlingTestData@@ -114,6 +116,12 @@ def _make_img_gen_job(mocker: MockerFixture) -> Any:return job+def _diagnostics_of(problem: PipelexProblem) -> ProblemDiagnostics:+ """The operator's diagnostics of a problem built in the operator view."""+ assert problem.diagnostics is not None+ return problem.diagnostics++@pytest.mark.asyncio(loop_scope="class")class TestGoogleWorkerErrorHandling:"""Tests for Google worker SDK exception handling and error categorization."""@@ -237,10 +245,10 @@ class TestGoogleWorkerErrorHandling:assert exc_info.value.error_category is InferenceErrorCategory.AMBIGUOUSassert exc_info.value.__cause__ is sdk_exc- # ---- to_error_report() integration ----+ # ---- Problem integration ----- async def test_error_report_includes_category_and_retryable(self, mocker: MockerFixture) -> None:- """to_error_report() includes error_category and retryable from the exception."""+ async def test_problem_includes_category_and_retryable(self, mocker: MockerFixture) -> None:+ """The category stays on the chain, and the problem takes the retry verdict of the code it gives."""worker = _make_google_llm_worker(mocker)sdk_exc = _make_google_client_error(code=429, message="Too many requests")worker.genai_async_client.models.generate_content.side_effect = sdk_exc # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue]@@ -248,13 +256,14 @@ class TestGoogleWorkerErrorHandling:with pytest.raises(LLMCompletionError) as exc_info:await worker._gen_text(llm_job=_make_llm_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_type == "LLMCompletionError"+ error = exc_info.value+ problem = error.to_problem(view=ProblemView.OPERATOR)+ assert find_inference_error_category_in_chain(error) == "transient"+ assert problem.is_retryable is True+ assert _diagnostics_of(problem).error_class == "LLMCompletionError"- async def test_error_report_capacity_not_retryable(self, mocker: MockerFixture) -> None:- """to_error_report() for CAPACITY errors has retryable=False."""+ async def test_problem_capacity_not_retryable(self, mocker: MockerFixture) -> None:+ """The problem of a CAPACITY error invites no retry."""worker = _make_google_llm_worker(mocker)sdk_exc = _make_google_client_error(code=429, message="Resource has been exhausted (e.g. check quota)")worker.genai_async_client.models.generate_content.side_effect = sdk_exc # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue]@@ -262,6 +271,7 @@ class TestGoogleWorkerErrorHandling:with pytest.raises(LLMCompletionError) as exc_info:await worker._gen_text(llm_job=_make_llm_job(mocker)) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]- report = exc_info.value.to_error_report()- assert report.error_category == "capacity"- assert report.retryable is False+ error = exc_info.value+ problem = error.to_problem(view=ProblemView.OPERATOR)+ assert find_inference_error_category_in_chain(error) == "capacity"+ assert problem.is_retryable is Falsediff --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 7690b4f80..fa1b9e50d 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@@ -8,8 +8,9 @@ import httpximport pytestfrom huggingface_hub.errors import HfHubHTTPError, InferenceTimeoutError-from pipelex.cogt.exceptions import ImgGenGenerationError, InferenceErrorCategory+from pipelex.cogt.exceptions import ImgGenGenerationError, InferenceErrorCategory, find_inference_error_category_in_chainfrom pipelex.cogt.inference.error_classification import UserActionKind+from pipelex.errors.problem import PipelexProblem, ProblemDiagnostics, ProblemViewfrom pipelex.providers.huggingface.huggingface_img_gen_worker import HuggingFaceImgGenWorkerfrom tests.unit.pipelex.providers.huggingface.test_data import HuggingFaceErrorHandlingTestData@@ -61,6 +62,12 @@ def _make_img_gen_job(mocker: MockerFixture) -> Any:return job+def _diagnostics_of(problem: PipelexProblem) -> ProblemDiagnostics:+ """The operator's diagnostics of a problem built in the operator view."""+ assert problem.diagnostics is not None+ return problem.diagnostics++@pytest.mark.asyncio(loop_scope="class")class TestHuggingFaceWorkerErrorHandling:"""Tests for HuggingFace ImgGen worker SDK exception handling and error categorization."""@@ -127,8 +134,8 @@ class TestHuggingFaceWorkerErrorHandling:assert exc_info.value.user_action.kind is expected_user_action_kindassert exc_info.value.__cause__ is sdk_exc- async def test_error_report_includes_category(self, mocker: MockerFixture) -> None:- """to_error_report() includes error_category and retryable from the exception."""+ async def test_problem_includes_category(self, mocker: MockerFixture) -> None:+ """The category stays on the chain, and the problem takes the retry verdict of the code it gives."""worker = _make_hf_img_gen_worker(mocker)sdk_exc = _make_hf_http_error(401, "Invalid token")worker.hf_async_client.text_to_image.side_effect = sdk_exc # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue]@@ -142,10 +149,11 @@ class TestHuggingFaceWorkerErrorHandling: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]- report = exc_info.value.to_error_report()- assert report.error_category == "configuration"- assert report.retryable is False- assert report.error_type == "ImgGenGenerationError"+ error = exc_info.value+ problem = error.to_problem(view=ProblemView.OPERATOR)+ assert find_inference_error_category_in_chain(error) == "configuration"+ assert problem.is_retryable is False+ assert _diagnostics_of(problem).error_class == "ImgGenGenerationError"assert exc_info.value.error_category is InferenceErrorCategory.CONFIGURATIONassert exc_info.value.user_action is not Noneassert exc_info.value.user_action.kind is UserActionKind.CHECK_CREDENTIALSdiff --git a/tests/unit/pipelex/providers/linkup/test_linkup_worker_error_handling.py b/tests/unit/pipelex/providers/linkup/test_linkup_worker_error_handling.pyindex 8b8e3bd79..93dd31e1b 100644--- a/tests/unit/pipelex/providers/linkup/test_linkup_worker_error_handling.py+++ b/tests/unit/pipelex/providers/linkup/test_linkup_worker_error_handling.py@@ -10,8 +10,9 @@ from linkup import LinkupAuthenticationError, LinkupInsufficientCreditError, Linif TYPE_CHECKING:from pytest_mock import MockerFixture-from pipelex.cogt.exceptions import ExtractJobFailureError, InferenceErrorCategory, SearchJobFailureError+from pipelex.cogt.exceptions import ExtractJobFailureError, InferenceErrorCategory, SearchJobFailureError, find_inference_error_category_in_chainfrom pipelex.cogt.inference.error_classification import UserActionKind+from pipelex.errors.problem import PipelexProblem, ProblemDiagnostics, ProblemViewfrom pipelex.providers.linkup.linkup_extract_worker import LinkupExtractWorkerfrom pipelex.providers.linkup.linkup_search_worker import LinkupSearchWorkerfrom tests.unit.pipelex.providers.linkup.test_data import LinkupExtractErrorHandlingTestData, LinkupSearchErrorHandlingTestData@@ -81,6 +82,12 @@ def _make_search_job(mocker: MockerFixture) -> Any:return job+def _diagnostics_of(problem: PipelexProblem) -> ProblemDiagnostics:+ """The operator's diagnostics of a problem built in the operator view."""+ assert problem.diagnostics is not None+ return problem.diagnostics++@pytest.mark.asyncio(loop_scope="class")class TestLinkupWorkerErrorHandling:"""Tests for Linkup extract and search worker exception handling and error categorization."""@@ -168,10 +175,10 @@ class TestLinkupWorkerErrorHandling:assert exc_info.value.user_action is not Noneassert exc_info.value.user_action.kind is expected_kind- # ---- Error report tests ----+ # ---- Problem tests ----- async def test_extract_error_report_for_auth(self, mocker: MockerFixture) -> None:- """to_error_report() for authentication error has CONFIGURATION category."""+ async def test_extract_problem_for_auth(self, mocker: MockerFixture) -> None:+ """An authentication error is a CONFIGURATION failure, and its problem invites no retry."""worker = _make_linkup_extract_worker(mocker)sdk_exc = LinkupAuthenticationError("Invalid API key")_get_linkup_client(worker).async_fetch.side_effect = sdk_exc@@ -179,13 +186,14 @@ class TestLinkupWorkerErrorHandling:with pytest.raises(ExtractJobFailureError) as exc_info: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 == "configuration"- assert report.retryable is False- assert report.error_type == "ExtractJobFailureError"+ error = exc_info.value+ problem = error.to_problem(view=ProblemView.OPERATOR)+ assert find_inference_error_category_in_chain(error) == "configuration"+ assert problem.is_retryable is False+ assert _diagnostics_of(problem).error_class == "ExtractJobFailureError"- async def test_search_error_report_for_rate_limit(self, mocker: MockerFixture) -> None:- """to_error_report() for rate limit error has TRANSIENT category and is retryable."""+ async def test_search_problem_for_rate_limit(self, mocker: MockerFixture) -> None:+ """A rate limit error is a TRANSIENT failure, and its problem invites a retry."""worker = _make_linkup_search_worker(mocker)sdk_exc = LinkupTooManyRequestsError("Too many requests")_get_linkup_client(worker).async_search.side_effect = sdk_exc@@ -193,12 +201,13 @@ class TestLinkupWorkerErrorHandling:with pytest.raises(SearchJobFailureError) as exc_info:await worker._search_sourced_answer(search_job=_make_search_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+ error = exc_info.value+ problem = error.to_problem(view=ProblemView.OPERATOR)+ assert find_inference_error_category_in_chain(error) == "transient"+ assert problem.is_retryable is True- async def test_search_error_report_for_no_result(self, mocker: MockerFixture) -> None:- """to_error_report() for no-result error has CONTENT category and is not retryable."""+ async def test_search_problem_for_no_result(self, mocker: MockerFixture) -> None:+ """A no-result error is a CONTENT failure, and its problem invites no retry."""worker = _make_linkup_search_worker(mocker)sdk_exc = LinkupNoResultError("No results found")_get_linkup_client(worker).async_search.side_effect = sdk_exc@@ -206,12 +215,13 @@ class TestLinkupWorkerErrorHandling:with pytest.raises(SearchJobFailureError) as exc_info:await worker._search_sourced_answer(search_job=_make_search_job(mocker)) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]- report = exc_info.value.to_error_report()- assert report.error_category == "content"- assert report.retryable is False+ error = exc_info.value+ problem = error.to_problem(view=ProblemView.OPERATOR)+ assert find_inference_error_category_in_chain(error) == "content"+ assert problem.is_retryable is False- async def test_extract_error_report_for_no_result(self, mocker: MockerFixture) -> None:- """to_error_report() for no-result error has CONTENT category and is not retryable."""+ async def test_extract_problem_for_no_result(self, mocker: MockerFixture) -> None:+ """A no-result error is a CONTENT failure, and its problem invites no retry."""worker = _make_linkup_extract_worker(mocker)sdk_exc = LinkupNoResultError("No results found")_get_linkup_client(worker).async_fetch.side_effect = sdk_exc@@ -219,6 +229,7 @@ class TestLinkupWorkerErrorHandling:with pytest.raises(ExtractJobFailureError) as exc_info: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 == "content"- assert report.retryable is False+ error = exc_info.value+ problem = error.to_problem(view=ProblemView.OPERATOR)+ assert find_inference_error_category_in_chain(error) == "content"+ assert problem.is_retryable is Falsediff --git a/tests/unit/pipelex/providers/mistral/test_mistral_worker_error_handling.py b/tests/unit/pipelex/providers/mistral/test_mistral_worker_error_handling.pyindex 92f9f3ff9..d78c40e1b 100644--- a/tests/unit/pipelex/providers/mistral/test_mistral_worker_error_handling.py+++ b/tests/unit/pipelex/providers/mistral/test_mistral_worker_error_handling.py@@ -17,8 +17,10 @@ from pipelex.cogt.exceptions import (InferenceErrorCategory,LLMCompletionError,LLMModelNotFoundError,+ find_inference_error_category_in_chain,)from pipelex.cogt.inference.error_classification import UserActionKind+from pipelex.errors.problem import PipelexProblem, ProblemDiagnostics, ProblemViewfrom pipelex.providers.mistral.mistral_extract_worker import MistralExtractWorkerfrom pipelex.providers.mistral.mistral_llm_worker import MistralLLMWorkerfrom tests.unit.pipelex.providers.mistral.test_data import (@@ -91,6 +93,12 @@ def _make_llm_job(mocker: MockerFixture) -> Any:return job+def _diagnostics_of(problem: PipelexProblem) -> ProblemDiagnostics:+ """The operator's diagnostics of a problem built in the operator view."""+ assert problem.diagnostics is not None+ return problem.diagnostics++@pytest.mark.asyncio(loop_scope="class")class TestMistralWorkerErrorHandling:"""Tests for Mistral worker SDK exception handling and error categorization."""@@ -243,10 +251,10 @@ class TestMistralWorkerErrorHandling:assert exc_info.value.user_action.kind is UserActionKind.CHANGE_MODELassert exc_info.value.__cause__ is sdk_exc- # ---- to_error_report() integration ----+ # ---- Problem integration ----- async def test_llm_error_report_transient_is_retryable(self, mocker: MockerFixture) -> None:- """to_error_report() for TRANSIENT LLM errors has retryable=True."""+ async def test_llm_problem_transient_is_retryable(self, mocker: MockerFixture) -> None:+ """The problem of a TRANSIENT LLM error invites a retry."""worker = _make_mistral_llm_worker(mocker)sdk_exc = _make_mistral_error(429, "Rate limit exceeded")worker.mistral_client_for_text.chat.complete_async.side_effect = sdk_exc # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue]@@ -254,13 +262,14 @@ class TestMistralWorkerErrorHandling:with pytest.raises(LLMCompletionError) as exc_info:await worker._gen_text(llm_job=_make_llm_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_type == "LLMCompletionError"+ error = exc_info.value+ problem = error.to_problem(view=ProblemView.OPERATOR)+ assert find_inference_error_category_in_chain(error) == "transient"+ assert problem.is_retryable is True+ assert _diagnostics_of(problem).error_class == "LLMCompletionError"- async def test_llm_error_report_capacity_not_retryable(self, mocker: MockerFixture) -> None:- """to_error_report() for CAPACITY LLM errors has retryable=False."""+ async def test_llm_problem_capacity_not_retryable(self, mocker: MockerFixture) -> None:+ """The problem of a CAPACITY LLM error invites no retry."""worker = _make_mistral_llm_worker(mocker)sdk_exc = _make_mistral_error(402, "Payment required: insufficient credits")worker.mistral_client_for_text.chat.complete_async.side_effect = sdk_exc # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue]@@ -268,12 +277,13 @@ class TestMistralWorkerErrorHandling:with pytest.raises(LLMCompletionError) as exc_info:await worker._gen_text(llm_job=_make_llm_job(mocker)) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]- report = exc_info.value.to_error_report()- assert report.error_category == "capacity"- assert report.retryable is False+ error = exc_info.value+ problem = error.to_problem(view=ProblemView.OPERATOR)+ assert find_inference_error_category_in_chain(error) == "capacity"+ assert problem.is_retryable is False- async def test_extract_error_report_includes_category(self, mocker: MockerFixture) -> None:- """to_error_report() for Extract errors includes error_category."""+ async def test_extract_problem_includes_category(self, mocker: MockerFixture) -> None:+ """An extract error keeps its category on the chain."""worker = _make_mistral_extract_worker(mocker)sdk_exc = _make_mistral_error(401, "Invalid API key")worker.mistral_client.ocr.process_async.side_effect = sdk_exc # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue]@@ -289,6 +299,7 @@ class TestMistralWorkerErrorHandling:extract_job_params=mocker.MagicMock(max_nb_images=None, image_min_size=None),)- report = exc_info.value.to_error_report()- assert report.error_category == "configuration"- assert report.retryable is False+ error = exc_info.value+ problem = error.to_problem(view=ProblemView.OPERATOR)+ assert find_inference_error_category_in_chain(error) == "configuration"+ assert problem.is_retryable is Falsediff --git a/tests/unit/pipelex/providers/openai/test_openai_completions_retries_kept.py b/tests/unit/pipelex/providers/openai/test_openai_completions_retries_kept.pyindex e3f9c71c2..cb669e2a7 100644--- a/tests/unit/pipelex/providers/openai/test_openai_completions_retries_kept.py+++ b/tests/unit/pipelex/providers/openai/test_openai_completions_retries_kept.py@@ -12,6 +12,7 @@ from openai.types.chat.chat_completion_message_tool_call import Functionfrom pipelex.cogt.exceptions import InferenceErrorCategory, LLMCompletionErrorfrom pipelex.cogt.llm.thinking_mode import ThinkingMode+from pipelex.errors.problem import ProblemViewfrom tests.helpers.completion_stop import make_text_llm_jobfrom tests.helpers.instructor_test_utils import DummySchemafrom tests.helpers.openai_completions_request import make_worker, text_completion, tool_call_completion@@ -76,4 +77,4 @@ class TestOpenAICompletionsRetriesKept:await worker._gen_text(llm_job=make_text_llm_job()) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]assert exc_info.value.error_category == InferenceErrorCategory.TRANSIENT- assert exc_info.value.to_error_report().retryable is True+ assert exc_info.value.to_problem(view=ProblemView.CALLER).is_retryable is Truediff --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 2002a0290..3e9da9af2 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@@ -11,8 +11,9 @@ import pytestif TYPE_CHECKING:from pytest_mock import MockerFixture-from pipelex.cogt.exceptions import ImgGenGenerationError, ImgGenModelNotFoundError, InferenceErrorCategory+from pipelex.cogt.exceptions import ImgGenGenerationError, ImgGenModelNotFoundError, InferenceErrorCategory, find_inference_error_category_in_chainfrom pipelex.cogt.inference.error_classification import UserActionKind+from pipelex.errors.problem import PipelexProblem, ProblemDiagnostics, ProblemView, ProviderDiagnosticsfrom pipelex.providers.openai.openai_img_gen_worker import OpenAIImgGenWorker@@ -46,6 +47,19 @@ def _make_img_gen_job(mocker: MockerFixture) -> Any:return job+def _diagnostics_of(problem: PipelexProblem) -> ProblemDiagnostics:+ """The operator's diagnostics of a problem built in the operator view."""+ assert problem.diagnostics is not None+ return problem.diagnostics+++def _provider_of(problem: PipelexProblem) -> ProviderDiagnostics:+ """What the provider answered, from the operator's diagnostics."""+ provider = _diagnostics_of(problem).provider+ assert provider is not None+ return provider++@pytest.mark.asyncio(loop_scope="class")class TestOpenAIImgGenWorkerErrorHandling:"""Verifies categorization, metadata extraction, and semantic UserActionKind values."""@@ -279,7 +293,7 @@ class TestOpenAIImgGenWorkerErrorHandling:assert exc_info.value.provider_metadata.status_code == 404assert exc_info.value.model_handle == "gpt-image-1"- async def test_error_report_includes_provider_metadata(self, mocker: MockerFixture) -> None:+ async def test_problem_includes_provider_metadata(self, mocker: MockerFixture) -> None:worker = _make_openai_img_gen_worker(mocker)sdk_exc = openai.RateLimitError("rate limited",@@ -297,10 +311,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]- report = exc_info.value.to_error_report()- assert report.error_category == "transient"- assert report.retryable is True- assert report.provider_metadata is not None- assert report.provider_metadata.provider == "openai"- assert report.provider_metadata.status_code == 429- assert report.provider_metadata.retry_after_seconds == 5.0+ error = exc_info.value+ problem = error.to_problem(view=ProblemView.OPERATOR)+ assert find_inference_error_category_in_chain(error) == "transient"+ assert problem.is_retryable is True+ # The provider's `name` is the backend the error names, which the worker leaves to its caller to fill.+ assert _provider_of(problem).name is None+ assert _provider_of(problem).status == 429+ assert problem.retry_after == 5.0diff --git a/tests/unit/pipelex/providers/openai/test_openai_worker_error_handling.py b/tests/unit/pipelex/providers/openai/test_openai_worker_error_handling.pyindex c70feaec6..549de1d7c 100644--- a/tests/unit/pipelex/providers/openai/test_openai_worker_error_handling.py+++ b/tests/unit/pipelex/providers/openai/test_openai_worker_error_handling.py@@ -16,8 +16,10 @@ from pipelex.cogt.exceptions import (InferenceErrorCategory,LLMCompletionError,LLMModelNotFoundError,+ find_inference_error_category_in_chain,)from pipelex.cogt.inference.error_classification import UserActionKind+from pipelex.errors.problem import PipelexProblem, ProblemDiagnostics, ProblemViewfrom pipelex.providers.openai.openai_completions_llm_worker import OpenAICompletionsLLMWorkerfrom pipelex.providers.openai.openai_img_gen_worker import OpenAIImgGenWorkerfrom pipelex.providers.openai.openai_responses_llm_worker import OpenAIResponsesLLMWorker@@ -159,6 +161,12 @@ def _make_img_gen_job(mocker: MockerFixture) -> Any:return job+def _diagnostics_of(problem: PipelexProblem) -> ProblemDiagnostics:+ """The operator's diagnostics of a problem built in the operator view."""+ assert problem.diagnostics is not None+ return problem.diagnostics++@pytest.mark.asyncio(loop_scope="class")class TestOpenAIWorkerErrorHandling:"""Tests for OpenAI worker SDK exception handling and error categorization."""@@ -377,10 +385,10 @@ class TestOpenAIWorkerErrorHandling:assert exc_info.value.error_category is InferenceErrorCategory.CONFIGURATIONassert exc_info.value.__cause__ is sdk_exc- # ---- to_error_report() integration ----+ # ---- Problem integration ----- async def test_error_report_includes_category_and_retryable(self, mocker: MockerFixture) -> None:- """to_error_report() includes error_category and retryable from the exception."""+ async def test_problem_includes_category_and_retryable(self, mocker: MockerFixture) -> None:+ """The category stays on the chain, and the problem takes the retry verdict of the code it gives."""worker = _make_completions_llm_worker(mocker)sdk_exc = _make_openai_rate_limit_error("Rate limit exceeded")worker.openai_client_for_text.chat.completions.create.side_effect = sdk_exc # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue]@@ -388,13 +396,14 @@ class TestOpenAIWorkerErrorHandling:with pytest.raises(LLMCompletionError) as exc_info:await worker._gen_text(llm_job=_make_llm_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_type == "LLMCompletionError"+ error = exc_info.value+ problem = error.to_problem(view=ProblemView.OPERATOR)+ assert find_inference_error_category_in_chain(error) == "transient"+ assert problem.is_retryable is True+ assert _diagnostics_of(problem).error_class == "LLMCompletionError"- async def test_error_report_capacity_not_retryable(self, mocker: MockerFixture) -> None:- """to_error_report() for CAPACITY errors has retryable=False."""+ async def test_problem_capacity_not_retryable(self, mocker: MockerFixture) -> None:+ """The problem of a CAPACITY error invites no retry."""worker = _make_completions_llm_worker(mocker)sdk_exc = _make_openai_rate_limit_error("insufficient_quota")worker.openai_client_for_text.chat.completions.create.side_effect = sdk_exc # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue]@@ -402,6 +411,7 @@ class TestOpenAIWorkerErrorHandling:with pytest.raises(LLMCompletionError) as exc_info:await worker._gen_text(llm_job=_make_llm_job(mocker)) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]- report = exc_info.value.to_error_report()- assert report.error_category == "capacity"- assert report.retryable is False+ error = exc_info.value+ problem = error.to_problem(view=ProblemView.OPERATOR)+ assert find_inference_error_category_in_chain(error) == "capacity"+ assert problem.is_retryable is Falsediff --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 e34f14238..0bb541d7f 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@@ -12,7 +12,8 @@ if TYPE_CHECKING:from pipelex.cogt.inference.error_classification import UserActionKind-from pipelex.cogt.exceptions import ExtractJobFailureError, InferenceErrorCategory+from pipelex.cogt.exceptions import ExtractJobFailureError, InferenceErrorCategory, find_inference_error_category_in_chain+from pipelex.errors.problem import PipelexProblem, ProblemDiagnostics, ProblemViewfrom pipelex.providers.pypdfium2.pypdfium2_worker import Pypdfium2Workerfrom tests.unit.pipelex.providers.pypdfium2.test_data import Pypdfium2ErrorHandlingTestData@@ -38,6 +39,12 @@ def _make_extract_job(mocker: MockerFixture) -> Any:return job+def _diagnostics_of(problem: PipelexProblem) -> ProblemDiagnostics:+ """The operator's diagnostics of a problem built in the operator view."""+ assert problem.diagnostics is not None+ return problem.diagnostics++@pytest.mark.asyncio(loop_scope="class")class TestPypdfium2WorkerErrorHandling:"""Tests for pypdfium2 extract worker exception handling and error categorization."""@@ -82,8 +89,8 @@ class TestPypdfium2WorkerErrorHandling:assert exc_info.value.user_action is not Noneassert exc_info.value.user_action.kind is expected_user_action_kind- async def test_error_report_for_file_not_found(self, mocker: MockerFixture) -> None:- """to_error_report() for FileNotFoundError has CONTENT category."""+ async def test_problem_for_file_not_found(self, mocker: MockerFixture) -> None:+ """A FileNotFoundError is a CONTENT failure, and its problem invites no retry."""worker = _make_pypdfium2_worker(mocker)sdk_exc = FileNotFoundError("No such file: /tmp/missing.pdf")@@ -102,12 +109,13 @@ class TestPypdfium2WorkerErrorHandling:with pytest.raises(ExtractJobFailureError) as exc_info: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 == "content"- assert report.retryable is False- assert report.error_type == "ExtractJobFailureError"+ error = exc_info.value+ problem = error.to_problem(view=ProblemView.OPERATOR)+ assert find_inference_error_category_in_chain(error) == "content"+ assert problem.is_retryable is False+ assert _diagnostics_of(problem).error_class == "ExtractJobFailureError"- async def test_error_report_for_os_error_is_the_runtime_s(self, mocker: MockerFixture) -> None:+ async def test_problem_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,7 +135,8 @@ class TestPypdfium2WorkerErrorHandling:with pytest.raises(ExtractJobFailureError) as exc_info: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 == "unknown"- assert report.code == CoreCode.RUNTIME_UNEXPECTED- assert report.retryable is False+ error = exc_info.value+ problem = error.to_problem(view=ProblemView.OPERATOR)+ assert find_inference_error_category_in_chain(error) == "unknown"+ assert problem.code == CoreCode.RUNTIME_UNEXPECTED+ assert problem.is_retryable is Falsediff --git a/tests/unit/pipelex/providers/reportlab/test_reportlab_pdf_renderer.py b/tests/unit/pipelex/providers/reportlab/test_reportlab_pdf_renderer.pyindex b6a78576e..65b6d29b6 100644--- a/tests/unit/pipelex/providers/reportlab/test_reportlab_pdf_renderer.py+++ b/tests/unit/pipelex/providers/reportlab/test_reportlab_pdf_renderer.py@@ -6,10 +6,10 @@ from concurrent.futures import ThreadPoolExecutorfrom typing import TYPE_CHECKING, Anyimport pytest+from mthds.protocol.problem.registry import ProblemDomainfrom reportlab.platypus import Table # type: ignore[import-untyped]from reportlab.platypus.doctemplate import BaseDocTemplate, LayoutError # type: ignore[import-untyped]-from pipelex.base_exceptions import ErrorDomainfrom pipelex.cogt.doc_gen.doc_gen_format import DocGenFormat, DocGenSourcefrom pipelex.cogt.doc_gen.exceptions import DocGenRenderErrorfrom pipelex.cogt.doc_gen.layout_tree import (@@ -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.problem import ProblemViewfrom pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom tests.unit.pipelex.providers.reportlab.reportlab_test_helpers import (TEST_FILENAME,@@ -131,11 +132,12 @@ 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)- # 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 True+ # The run's data the engine cannot lay out: the caller's to change, told which element in the code's sentence.+ caller = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert caller.params is not None+ assert caller.params.as_wire() == {"reason": "image_unreadable", "element": "image 1 of the document"}+ assert caller.code == PipelexErrorCode.DOCGEN_CONTENT_UNPRINTABLE+ assert caller.domain == ProblemDomain.INPUTdef test_a_job_that_is_not_a_pdf_from_the_layout_is_refused(self) -> None:job = RenderJob(@@ -164,11 +166,12 @@ 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.")- # 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 True+ # The run's data the engine cannot lay out: the caller's to change, told which element in the code's sentence.+ caller = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert caller.params is not None+ assert caller.params.as_wire() == {"reason": "too_tall_for_page", "element": "the table 'Line items'"}+ assert caller.code == PipelexErrorCode.DOCGEN_CONTENT_UNPRINTABLE+ assert caller.domain == ProblemDomain.INPUTdef test_table_cells_print_their_scalars(self) -> None:table = TableBlock(diff --git a/tests/unit/pipelex/providers/test_context_window_refusals.py b/tests/unit/pipelex/providers/test_context_window_refusals.pyindex 7bdc8a5aa..1f449f86e 100644--- a/tests/unit/pipelex/providers/test_context_window_refusals.py+++ b/tests/unit/pipelex/providers/test_context_window_refusals.py@@ -13,9 +13,8 @@ from google.genai import errors as genai_errorsfrom mistralai.client import Mistralfrom mistralai.client.errors import MistralErrorfrom mistralai.client.models import UserMessage-from mthds.protocol.problem.registry import CoreCode+from mthds.protocol.problem.registry import CoreCode, ProblemDomain, RetryVerdict-from pipelex.base_exceptions import ErrorDomainfrom pipelex.cogt.exceptions import (CogtError,ExtractJobFailureError,@@ -37,6 +36,8 @@ from pipelex.cogt.inference.error_classification import (from pipelex.cogt.inference.error_classify import InferenceErrorFamily, classify_inference_errorfrom pipelex.cogt.inference.error_render import render_inference_errorfrom pipelex.cogt.inference.provider_name import ProviderName+from pipelex.errors.error_codes import error_code_spec+from pipelex.errors.problem import ProblemViewfrom pipelex.providers.openai.openai_completions_llm_worker import OpenAICompletionsLLMWorkerfrom tests.helpers.completion_stop import make_text_llm_job@@ -473,9 +474,9 @@ class TestContextWindowRefusals:with pytest.raises(LLMCompletionError) as exc_info:await worker._gen_text(llm_job=make_text_llm_job()) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]- report = exc_info.value.to_error_report()- assert report.code == CoreCode.MODEL_CONTEXT_EXCEEDED- assert report.error_domain == ErrorDomain.INPUT- assert report.retryable is False- assert report.http_status == 422+ caller = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert caller.code == CoreCode.MODEL_CONTEXT_EXCEEDED+ assert caller.domain == ProblemDomain.INPUT+ assert caller.retry == RetryVerdict.NO+ assert error_code_spec(CoreCode.MODEL_CONTEXT_EXCEEDED).status == 422assert isinstance(exc_info.value.__cause__, openai.BadRequestError)diff --git a/tests/unit/pipelex/providers/test_instructor_retry_shapes.py b/tests/unit/pipelex/providers/test_instructor_retry_shapes.pyindex 8a6b369c4..d8c28c5d5 100644--- a/tests/unit/pipelex/providers/test_instructor_retry_shapes.py+++ b/tests/unit/pipelex/providers/test_instructor_retry_shapes.py@@ -29,13 +29,15 @@ import openaiimport pytestfrom instructor import Mode, from_anthropic, from_openaifrom instructor.core import FailedAttempt, InstructorRetryException+from mthds.protocol.problem.registry import CoreCode, ProblemDomainfrom pydantic import ValidationErrorfrom tenacity import RetryError-from pipelex.base_exceptions import ErrorDomain-from pipelex.cogt.exceptions import InferenceErrorCategory, LLMCompletionError, LLMModelNotFoundError-from pipelex.cogt.inference.error_classification import UserActionKind, extract_underlying_sdk_exception+from pipelex.cogt.exceptions import InferenceErrorCategory, LLMCompletionError, LLMModelNotFoundError, find_inference_error_category_in_chain+from pipelex.cogt.inference.error_classification import UserAction, UserActionKind, extract_underlying_sdk_exceptionfrom pipelex.cogt.llm.instructor_retry import make_instructor_schema_retrying+from pipelex.errors.error_codes import error_code_spec+from pipelex.errors.problem import PipelexProblem, ProblemDiagnostics, ProblemViewfrom pipelex.pipe_run.exceptions import PipeRouterErrorfrom pipelex.providers.openai.openai_completions_llm_worker import OpenAICompletionsLLMWorkerfrom pipelex.system.pipe_run_mode import PipeRunMode@@ -46,6 +48,8 @@ if TYPE_CHECKING:from pytest_mock import MockerFixture+ from pipelex.base_exceptions import PipelexError+_ORIGIN = "https://gateway.example.com"_MAX_ATTEMPTS = 3@@ -177,6 +181,19 @@ _SPENT_BUDGET_SHAPES = []+def _diagnostics_of(problem: PipelexProblem) -> ProblemDiagnostics:+ """The operator's diagnostics of a problem built in the operator view."""+ assert problem.diagnostics is not None+ return problem.diagnostics+++def _advice_of(error: PipelexError) -> UserAction:+ """The advice nearest the error on its chain, which a local CLI prints as its tip."""+ advice = error.advised_action()+ assert advice is not None+ return advice++@pytest.mark.asyncio(loop_scope="class")class TestInstructorRetryShapes:@pytest.mark.parametrize(("raised_by", "responses", "sdk_exception_class", "nb_parse_failures"), _API_ERROR_SHAPES)@@ -290,15 +307,20 @@ class TestInstructorRetryShapes:pipe_stack=["score_lead"],)located.__cause__ = failure- report = located.to_error_report()-- assert report.error_type == "LLMCompletionError"- assert report.error_domain == ErrorDomain.CONFIG- assert report.error_category == InferenceErrorCategory.CONFIGURATION- assert report.retryable is False- assert report.http_status == 500- assert report.user_action is not None- assert report.user_action.kind == UserActionKind.CHANGE_MODEL- assert f"'{_MODEL_HANDLE}'" in report.user_action.detail- assert _WIRE_ID not in report.user_action.detail- assert report.message.startswith("Pipe 'score_lead' failed: ")+ problem = located.to_problem(view=ProblemView.OPERATOR)++ # The deployment does not serve the model to this integration: the operator's to fix, the caller's to work around.+ assert problem.code == CoreCode.MODEL_UNAVAILABLE+ assert problem.domain == ProblemDomain.OPERATOR+ assert error_code_spec(CoreCode.MODEL_UNAVAILABLE).status == 501+ # The problem is the root fault's, located at the pipe the router wrapped it for.+ assert _diagnostics_of(problem).error_class == "LLMCompletionError"+ assert problem.location is not None+ assert problem.location.pipe == "score_lead"+ assert find_inference_error_category_in_chain(located) == InferenceErrorCategory.CONFIGURATION+ assert problem.is_retryable is False+ advice = _advice_of(located)+ assert advice.kind == UserActionKind.CHANGE_MODEL+ assert f"'{_MODEL_HANDLE}'" in advice.detail+ assert _WIRE_ID not in advice.detail+ assert "HTTP 412" in _diagnostics_of(problem).messagediff --git a/tests/unit/pipelex/runtime_bridge/test_exceptions_disclosure.py b/tests/unit/pipelex/runtime_bridge/test_exceptions_disclosure.pyindex 37c782600..c4f5d1382 100644--- a/tests/unit/pipelex/runtime_bridge/test_exceptions_disclosure.py+++ b/tests/unit/pipelex/runtime_bridge/test_exceptions_disclosure.py@@ -1,20 +1,30 @@import pytest+from mthds.protocol.problem.registry import ProblemDomain, StepKind-from pipelex.base_exceptions import INTERNAL_ERROR_PLACEHOLDER, DisclosureMode+from pipelex.errors.problem import ProblemView+from pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.runtime_bridge.exceptions import MissingOrchestratorErrorclass TestRuntimeBridgeExceptionDisclosure:@pytest.mark.parametrize("mode", ["temporal", "mistral-workflows", "acme"])- def test_generic_plugin_hint_survives_strict_disclosure(self, mode: str) -> None:- """MissingOrchestratorError carries a caller-actionable, plugin-decoupled hint in its message.+ def test_generic_plugin_hint_reaches_the_operator(self, mode: str) -> None:+ """MissingOrchestratorError's plugin-decoupled hint is the operator's to read, its code the caller's.- ``_authors_caller_facing_message = True`` must keep that message intact under- STRICT disclosure; without the flag STRICT would replace it with- ``INTERNAL_ERROR_PLACEHOLDER`` and the "is its plugin installed?" hint would be lost.+ A configured mode with no orchestrator is the deployment's to fix: the operator reads the message naming the+ mode and asking whether its plugin is installed, and the caller reads the code's sentences, which name no+ plugin of the deployment."""error = MissingOrchestratorError(mode=mode)- payload = error.to_error_report().to_dict(disclosure_mode=DisclosureMode.STRICT)- assert mode in payload["message"]- assert "is its plugin installed?" in payload["message"]- assert payload["message"] != INTERNAL_ERROR_PLACEHOLDER++ caller = error.to_problem(view=ProblemView.CALLER)+ operator = error.to_problem(view=ProblemView.OPERATOR)++ assert caller.code == PipelexErrorCode.PLUGIN_NOT_FOUND+ assert caller.domain == ProblemDomain.OPERATOR+ assert caller.next_step.kind == StepKind.REPORT+ assert caller.diagnostics is None+ assert "is its plugin installed?" not in str(caller.to_wire())+ assert operator.next_step.kind == StepKind.FIX_CONFIGURATION+ assert operator.diagnostics is not None+ assert operator.diagnostics.message == f"No orchestrator is registered for orchestration mode '{mode}'; is its plugin installed?"diff --git a/tests/unit/pipelex/system/telemetry/test_telemetry_stale_remedy.py b/tests/unit/pipelex/system/telemetry/test_telemetry_stale_remedy.pyindex c0e93ad2a..d561229d1 100644--- a/tests/unit/pipelex/system/telemetry/test_telemetry_stale_remedy.py+++ b/tests/unit/pipelex/system/telemetry/test_telemetry_stale_remedy.py@@ -21,8 +21,10 @@ from pathlib import Pathfrom typing import TYPE_CHECKINGimport pytest+from mthds.protocol.problem.registry import ProblemDomainfrom pipelex.core.validation import MIGRATE_COMMAND+from pipelex.errors.problem import ProblemViewfrom pipelex.migration.goldens import pre_history_document_pathfrom pipelex.migration.ledger import packaged_migration_dirfrom pipelex.system.configuration.config_surface import TELEMETRY_CONFIG_SURFACE_ID@@ -108,15 +110,18 @@ class TestTheErrorSaysWhetherTheFileIsOldOrWrong:assert exc.migration.needs_attention is Trueassert [unexplained.path for plan in exc.migration.plans for unexplained in plan.unexplained] == [UNKNOWN_KEY]- def test_the_domain_comes_from_the_class_and_the_block_rides_the_report(self, global_dir: Path) -> None:- """What an agent consumer actually reads: one structured envelope, `config` either way."""+ def test_the_domain_comes_from_the_class_and_the_block_rides_the_operator_s_problem(self, global_dir: Path) -> None:+ """What an agent consumer actually reads: one structured envelope, the operator's either way."""exc = load_and_capture(config_dir=global_dir, body=f"{old_shape_document()}\n{UNKNOWN_KEY} = true\n")- report = exc.to_error_report()+ operator = exc.to_problem(view=ProblemView.OPERATOR)- assert report.error_domain == "config"- assert report.migration is not None- assert report.to_dict()["migration"]["remedy"] == MIGRATE_COMMAND+ assert operator.domain == ProblemDomain.OPERATOR+ assert operator.diagnostics is not None+ assert operator.diagnostics.migration is not None+ assert operator.to_wire()["diagnostics"]["migration"]["remedy"] == MIGRATE_COMMAND+ # The block describes this host's own configuration directories: no caller reads it.+ assert MIGRATE_COMMAND not in str(exc.to_problem(view=ProblemView.CALLER).to_wire())def test_no_remedy_ever_tells_a_reader_to_start_the_file_over(self, global_dir: Path) -> None:"""The whole point of the change: a migratable file is never answered with a reset."""diff --git a/tests/unit/pipelex/system/test_job_metadata_request_id.py b/tests/unit/pipelex/system/test_job_metadata_request_id.pyindex 91b0c97ba..6cf00fadf 100644--- a/tests/unit/pipelex/system/test_job_metadata_request_id.py+++ b/tests/unit/pipelex/system/test_job_metadata_request_id.py@@ -56,7 +56,7 @@ class TestJobMetadataRequestId:Defense-in-depth: an upstream consumer of pipelex that forwards the``X-Request-ID`` header without sanitization cannot inject newlines,ANSI escapes, or control characters into the log lines and- ``ErrorReport`` envelopes that quote it.+ problem documents that quote it."""with pytest.raises(ValidationError):JobMetadata(diff --git a/tests/unit/pipelex/test_base_exceptions.py b/tests/unit/pipelex/test_base_exceptions.pyindex 9fc6b1c68..96c05c28c 100644--- a/tests/unit/pipelex/test_base_exceptions.py+++ b/tests/unit/pipelex/test_base_exceptions.py@@ -2,34 +2,35 @@ import subprocess # ruff: ignore[suspicious-subprocess-import]import sys-class TestErrorReportColdImport:- def test_error_report_constructable_without_cogt_exceptions_loaded(self):- """``ErrorReport`` must be fully defined without importing ``pipelex.cogt.exceptions``.+class TestProblemColdImport:+ def test_a_problem_is_built_without_cogt_exceptions_loaded(self):+ """A problem is built from an error, or from a code alone, without importing ``pipelex.cogt.exceptions``.- Regression: ``ErrorReport``'s ``user_action`` / ``provider_metadata`` fields- were forward references resolved only by a ``rebuild_dataclass()`` call living- in ``pipelex.cogt.exceptions``. Any cold path that built an error report before- that module happened to load raised ``PydanticUserError`` — error reporting- itself crashed. Runs in a subprocess so a clean interpreter is guaranteed; the- in-process pytest session has already imported ``cogt`` and would mask the bug.+ Regression: the error document's fields were once forward references resolved only by a rebuild living in+ ``pipelex.cogt.exceptions``, so any cold path that reported an error before that module happened to load+ crashed while reporting it. Runs in a subprocess so a clean interpreter is guaranteed; the in-process pytest+ session has already imported ``cogt`` and would mask the bug.- ``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.+ The problem is built both from a ``PipelexError``, in the operator's view, and from a code through+ ``make_problem``, which reads the registry's generated tables and so needs no bootstrap either."""code = ("import sys\n"- "from pipelex.base_exceptions import ErrorReport\n"+ "from mthds.protocol.problem.registry import CoreCode\n"+ "from pipelex.base_exceptions import PipelexError\n"+ "from pipelex.errors.problem import ProblemView, make_problem\n""assert 'pipelex.cogt.exceptions' not in sys.modules, ""'cogt.exceptions already loaded — test no longer exercises the cold path'\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"+ "operator = PipelexError('m').to_problem(view=ProblemView.OPERATOR).to_wire()\n"+ "assert operator['code'] == 'runtime.unexpected', operator\n"+ "assert operator['type'] == 'https://mthds.ai/errors/runtime.unexpected', operator\n"+ "assert operator['diagnostics']['error_class'] == 'PipelexError', operator\n"+ "assert operator['diagnostics']['message'] == 'm', operator\n"+ "coded = make_problem(code=CoreCode.RUNTIME_UNEXPECTED, view=ProblemView.CALLER).to_wire()\n"+ "assert coded == {'type': 'https://mthds.ai/errors/runtime.unexpected', 'title': 'An unexpected error occurred', "+ "'detail': 'The runtime met an unexpected error.', 'code': 'runtime.unexpected', 'domain': 'runtime', 'retry': 'no', "+ "'next_step': {'kind': 'report', 'detail': 'Report this to whoever runs the runtime.'}}, coded\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}"+ assert result.returncode == 0, f"cold-path problem construction failed:\nstdout: {result.stdout}\nstderr: {result.stderr}"diff --git a/tests/unit/pipelex/test_error_http_status.py b/tests/unit/pipelex/test_error_http_status.pydeleted file mode 100644index 6eae2993e..000000000--- a/tests/unit/pipelex/test_error_http_status.py+++ /dev/null@@ -1,81 +0,0 @@-"""Unit tests for the error_domain -> HTTP-status mapping."""--from __future__ import annotations--import pytest--from pipelex.base_exceptions import ErrorDomain, error_domain_to_http_status-from pipelex.cogt.inference.error_classification import ProviderErrorMetadata-from pipelex.cogt.inference.provider_name import ProviderName-from tests.helpers.error_report import make_error_report---class TestErrorHttpStatus:- @pytest.mark.parametrize(- ("error_domain", "expected_status"),- [- (ErrorDomain.INPUT, 422),- (ErrorDomain.CONFIG, 500),- (ErrorDomain.RUNTIME, 500),- (None, 500),- ("input", 422),- ("config", 500),- ("runtime", 500),- ("domain-from-the-future", 500),- ],- )- def test_error_domain_to_http_status(self, error_domain: ErrorDomain | str | None, expected_status: int) -> None:- """The mapping yields 422 for INPUT and 500 for CONFIG/RUNTIME/unknown/None, for enum or raw-string input."""- assert error_domain_to_http_status(error_domain) == expected_status-- @pytest.mark.parametrize(- ("error_domain", "expected_status"),- [- ("input", 422),- ("config", 500),- ("runtime", 500),- (None, 500),- ],- )- def test_error_report_http_status_follows_domain(self, error_domain: str | None, expected_status: int) -> None:- """ErrorReport.http_status follows error_domain when there is no provider 429."""- report = make_error_report(error_type="SomeError", message="boom", error_domain=error_domain)- assert report.http_status == expected_status-- def test_provider_429_takes_precedence_over_domain(self) -> None:- """A provider 429 overrides the domain default and exposes retry_after_seconds."""- provider_metadata = ProviderErrorMetadata(- provider=ProviderName.OPENAI,- sdk_exception_type="RateLimitError",- status_code=429,- retry_after_seconds=12.0,- )- report = make_error_report(- error_type="LLMCompletionError",- message="rate limited",- error_domain="input",- provider_metadata=provider_metadata,- )- assert report.http_status == 429- assert report.provider_metadata is not None- assert report.provider_metadata.retry_after_seconds == 12.0-- def test_non_429_provider_status_does_not_override_domain(self) -> None:- """A non-429 provider status code leaves the domain default in place."""- provider_metadata = ProviderErrorMetadata(- provider=ProviderName.OPENAI,- sdk_exception_type="BadRequestError",- status_code=400,- )- report = make_error_report(- error_type="LLMCompletionError",- message="bad request",- error_domain="input",- provider_metadata=provider_metadata,- )- assert report.http_status == 422-- def test_unknown_error_domain_falls_back_to_500(self) -> None:- """An unrecognized error_domain string (e.g. from a newer Pipelex) yields 500, not a crash."""- report = make_error_report(error_type="SomeError", message="boom", error_domain="domain-from-the-future")- assert report.http_status == 500diff --git a/tests/unit/pipelex/test_error_report_disclosure_mode.py b/tests/unit/pipelex/test_error_report_disclosure_mode.pydeleted file mode 100644index cea5aad15..000000000--- a/tests/unit/pipelex/test_error_report_disclosure_mode.py+++ /dev/null@@ -1,498 +0,0 @@-"""Unit tests for ``ErrorReport.to_dict(disclosure_mode=...)`` — strict vs verbose projection.--``DisclosureMode.VERBOSE`` is the exact inverse of ``from_dict`` (round-trip preserved).-``DisclosureMode.STRICT`` is a lossy projection for untrusted external surfaces:-``provider`` / ``model`` are always dropped, ``provider_metadata`` is projected-through the curated subset (just ``status_code`` and ``retry_after_seconds`` —-actionable HTTP client hints), and the ``message`` is kept only when the report-is flagged ``caller_facing_message`` — the flag set by error classes-(``MthdsParserError`` / ``ValidateBundleError``) whose message describes-the caller's own input. Every other report has its ``message`` replaced with a-generic placeholder and ``user_action`` dropped, keeping the stable identifiers-(``error_type`` / ``error_domain`` / ``error_category`` / ``retryable`` /-``title`` / ``type_uri``) plus the curated ``provider_metadata`` slice.--The flag is keyed on message *provenance*, not ``error_domain``: ``error_domain``-is inherited up the ``__cause__`` chain, so a domain-less wrapper raised ``from``-an INPUT cause is classified INPUT — but its own internal ``message`` must still-be redacted. ``caller_facing_message`` is not inherited, so STRICT redacts it.-"""--from typing import Any--import pytest-from mthds.protocol.problem.registry import CoreCode-from pydantic import ValidationError--from pipelex.base_exceptions import (- INTERNAL_ERROR_PLACEHOLDER,- DisclosureMode,- ErrorDomain,- ErrorReport,- PipelexError,- ValidationErrorCategory,- ValidationErrorItem,-)-from pipelex.cogt.inference.error_classification import ProviderErrorMetadata, UserAction, UserActionKind-from pipelex.cogt.inference.provider_name import ProviderName-from pipelex.errors.error_code_declaration import InheritsCause-from 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",- type_uri="https://docs.pipelex.com/latest/errors/cogt-error/",- error_category="capacity",- error_domain=ErrorDomain.RUNTIME,- retryable=False,- user_action=UserAction(kind=UserActionKind.CHECK_BILLING, detail="check your billing page"),- model="gpt-5",- provider="openai",- provider_metadata=ProviderErrorMetadata(- provider=ProviderName.OPENAI,- sdk_exception_type="RateLimitError",- status_code=429,- retry_after_seconds=12.0,- ),- )---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",- type_uri="https://docs.pipelex.com/latest/errors/env-var-not-found-error/",- error_domain=ErrorDomain.CONFIG,- )---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",- type_uri="https://docs.pipelex.com/latest/errors/mthds-parser-error/",- error_domain=ErrorDomain.INPUT,- user_action=UserAction(kind=UserActionKind.CHANGE_INPUT, detail="fix the concept name in your .mthds"),- caller_facing_message=True,- )---def _input_domain_wrapper_report(message: str = "internal invariant violated: cache slot is None") -> ErrorReport:- """An INPUT-classified report whose message is NOT caller-facing.-- Models a domain-less wrapper that inherited ``error_domain=INPUT`` up the- ``__cause__`` chain while keeping its own internal ``message``.- """- return ErrorReport(- code="runtime.unexpected",- error_type="PipelexUnexpectedError",- message=message,- title="Unexpected internal error",- type_uri="https://docs.pipelex.com/latest/errors/pipelex-unexpected-error/",- error_domain=ErrorDomain.INPUT,- )---class TestErrorReportDisclosureMode:- @pytest.mark.parametrize(- "report",- [- pytest.param(_runtime_report(), id="runtime"),- pytest.param(_config_report(), id="config"),- pytest.param(_caller_facing_report(), id="caller-facing"),- pytest.param(_input_domain_wrapper_report(), id="input-domain-wrapper"),- ],- )- def test_verbose_preserves_every_populated_field(self, report: ErrorReport) -> None:- """VERBOSE is a pure passthrough — ``message`` and every populated field survive."""- payload = report.to_dict(disclosure_mode=DisclosureMode.VERBOSE)- assert payload["message"] == report.message- assert payload["error_type"] == report.error_type- if report.user_action is not None:- assert "user_action" in payload- if report.model is not None:- assert payload["model"] == report.model- if report.provider is not None:- assert payload["provider"] == report.provider-- @pytest.mark.parametrize(- "report",- [- pytest.param(_runtime_report(), id="runtime"),- pytest.param(_config_report(), id="config"),- pytest.param(_input_domain_wrapper_report(), id="input-domain-wrapper"),- ],- )- def test_strict_redacts_non_caller_facing_reports(self, report: ErrorReport) -> None:- """STRICT replaces ``message`` and drops disclosure-leaking fields for any non-caller-facing report.-- The ``input-domain-wrapper`` case is the regression pin: ``error_domain``- alone (here INPUT, inherited up a ``__cause__`` chain) does NOT earn a- message passthrough — only the ``caller_facing_message`` flag does.-- ``provider_metadata`` is the one classification field allowed through- STRICT as a curated subset: ``status_code`` and ``retry_after_seconds``- (HTTP client hints) survive — see ``test_strict_preserves_curated_provider_metadata``.- """- payload = report.to_dict(disclosure_mode=DisclosureMode.STRICT)- assert payload["message"] == INTERNAL_ERROR_PLACEHOLDER- assert "user_action" not in payload- assert "model" not in payload- assert "provider" not in payload- # Stable identifiers survive.- assert payload["error_type"] == report.error_type- assert payload["title"] == report.title- assert payload["type_uri"] == report.type_uri- if report.error_domain is not None:- assert payload["error_domain"] == report.error_domain- if report.error_category is not None:- assert payload["error_category"] == report.error_category-- def test_strict_passes_through_caller_facing_message(self) -> None:- """A report flagged ``caller_facing_message`` keeps its ``message`` and ``user_action`` in STRICT.-- The ``caller_facing_message`` flag itself is internal redaction plumbing —- it rides only the VERBOSE round-trip format, never the STRICT projection.- """- report = _caller_facing_report()- payload = report.to_dict(disclosure_mode=DisclosureMode.STRICT)- assert payload["message"] == report.message- assert "user_action" in payload- assert "caller_facing_message" not in payload-- def test_strict_strips_provider_fields_even_from_caller_facing_passthrough(self) -> None:- """Gap 2: provider/model attribution is stripped from the caller-facing passthrough branch.-- An INPUT-classification error can pick up ``provider`` / ``model`` /- ``provider_metadata`` from an inference-layer ``__cause__`` during- enrichment. STRICT must never reflect that onto an external surface,- even when the ``message`` itself is allowed through. A- ``provider_metadata`` with no curated fields (no ``status_code`` /- ``retry_after_seconds``) is omitted entirely.- """- report = _caller_facing_report().model_copy(- update={- "model": "gpt-5",- "provider": "openai",- "provider_metadata": ProviderErrorMetadata(provider=ProviderName.OPENAI, sdk_exception_type="RateLimitError"),- }- )- payload = report.to_dict(disclosure_mode=DisclosureMode.STRICT)- assert payload["message"] == report.message- assert "model" not in payload- assert "provider" not in payload- assert "provider_metadata" not in payload-- def test_strict_preserves_curated_provider_metadata(self) -> None:- """STRICT preserves ``status_code`` and ``retry_after_seconds`` — actionable HTTP client hints.-- Provider 429s carry a ``Retry-After`` hint the HTTP adapter needs to emit- a useful response header. Provider identity / SDK type / free-form- message / request_id are still stripped — only the curated subset rides.-- Holds for BOTH the redacted (non-caller-facing) and caller-facing- passthrough branches.- """- non_caller_facing_report = _runtime_report()- payload = non_caller_facing_report.to_dict(disclosure_mode=DisclosureMode.STRICT)- assert "provider_metadata" in payload- assert payload["provider_metadata"] == {"status_code": 429, "retry_after_seconds": 12.0}- # The other ProviderErrorMetadata fields (provider, sdk_exception_type) must not leak.- assert "provider" not in payload["provider_metadata"]- assert "sdk_exception_type" not in payload["provider_metadata"]-- caller_facing_report = _caller_facing_report().model_copy(- update={- "provider_metadata": ProviderErrorMetadata(- provider=ProviderName.OPENAI,- sdk_exception_type="RateLimitError",- status_code=429,- retry_after_seconds=12.0,- ),- }- )- caller_facing_payload = caller_facing_report.to_dict(disclosure_mode=DisclosureMode.STRICT)- assert caller_facing_payload["provider_metadata"] == {"status_code": 429, "retry_after_seconds": 12.0}-- def test_strict_omits_provider_metadata_when_only_curated_subset_is_empty(self) -> None:- """A ``provider_metadata`` with no curated fields is omitted entirely rather than emitted as an empty dict."""- report = _runtime_report().model_copy(- update={- "provider_metadata": ProviderErrorMetadata(- provider=ProviderName.OPENAI,- sdk_exception_type="RateLimitError",- status_code=None,- retry_after_seconds=None,- ),- }- )- payload = report.to_dict(disclosure_mode=DisclosureMode.STRICT)- assert "provider_metadata" not in payload-- def test_strict_provider_metadata_dict_carries_http_status_for_adapter(self) -> None:- """A STRICT-projected dict carries ``status_code=429`` and ``retry_after_seconds`` for the HTTP adapter.-- STRICT is not meant to round-trip through :meth:`ErrorReport.from_dict`- (see ``test_strict_does_not_round_trip``) — consumers read the dict- directly. This pins the contract the HTTP adapter relies on: it can- read ``payload["provider_metadata"]["status_code"]`` to emit the right- status and ``payload["provider_metadata"]["retry_after_seconds"]`` to- emit a useful ``Retry-After`` header, without rehydrating.- """- report = _runtime_report()- strict_payload = report.to_dict(disclosure_mode=DisclosureMode.STRICT)- provider_metadata = strict_payload["provider_metadata"]- assert provider_metadata["status_code"] == 429- assert provider_metadata["retry_after_seconds"] == 12.0-- def test_strict_redacts_domain_less_wrapper_raised_from_input_cause(self) -> None:- """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 _PassThroughWrapperError(wrapper_message) from cause- except _PassThroughWrapperError as exc:- report = exc.to_error_report()- # 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- payload = report.to_dict(disclosure_mode=DisclosureMode.STRICT)- assert payload["message"] == INTERNAL_ERROR_PLACEHOLDER- assert "invariant" not in payload["message"]-- def test_strict_passes_through_real_interpreter_error_message(self) -> None:- """A genuine ``MthdsParserError`` reflects its caller-facing message through STRICT."""- report = MthdsParserError("pipe 'foo' references unknown concept at line 5").to_error_report()- assert report.caller_facing_message is True- payload = report.to_dict(disclosure_mode=DisclosureMode.STRICT)- assert payload["message"] == "pipe 'foo' references unknown concept at line 5"-- def test_strict_does_not_sanitize_paths_inside_a_caller_facing_message(self) -> None:- """STRICT is a provenance projection, NOT a path-leak shield.-- A genuinely caller-facing message is reflected verbatim — even if it- contains a path. If such a message could surface a secret, the fix is to- repair the upstream message, not to widen STRICT's scope.- """- report = _caller_facing_report("syntax error in /workspace/caller/bundle.mthds at line 8")- payload = report.to_dict(disclosure_mode=DisclosureMode.STRICT)- assert payload["message"] == "syntax error in /workspace/caller/bundle.mthds at line 8"-- @pytest.mark.parametrize(- "retryable",- [- pytest.param(True, id="retryable-true"),- pytest.param(False, id="retryable-false"),- pytest.param(None, id="retryable-none"),- ],- )- @pytest.mark.parametrize(- "mode",- [- pytest.param(DisclosureMode.VERBOSE, id="verbose"),- pytest.param(DisclosureMode.STRICT, id="strict"),- ],- )- 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",- type_uri="https://docs.pipelex.com/latest/errors/cogt-error/",- error_domain=ErrorDomain.RUNTIME,- retryable=retryable,- )- payload = report.to_dict(disclosure_mode=mode)- if retryable is None:- assert "retryable" not in payload- else:- assert payload["retryable"] is retryable-- def test_caller_facing_message_serialized_only_when_set(self) -> None:- """``caller_facing_message`` rides in ``to_dict`` only when True — a non-caller-facing report omits it.-- Keeps the common-case payload identical to a report without the field,- while ``from_dict`` defaults the flag back to False so the round-trip holds.- """- assert "caller_facing_message" not in _runtime_report().to_dict()- assert _caller_facing_report().to_dict()["caller_facing_message"] is True-- @pytest.mark.parametrize(- "report",- [- pytest.param(_runtime_report(), id="runtime"),- pytest.param(_caller_facing_report(), id="caller-facing"),- ],- )- def test_verbose_round_trip_preserves_report(self, report: ErrorReport) -> None:- """``from_dict(to_dict(VERBOSE))`` reconstructs the original report exactly, ``caller_facing_message`` included."""- recovered = ErrorReport.from_dict(report.to_dict(disclosure_mode=DisclosureMode.VERBOSE))- assert recovered == report- assert recovered.caller_facing_message == report.caller_facing_message-- def test_strict_does_not_round_trip(self) -> None:- """STRICT is not the inverse of :meth:`ErrorReport.from_dict` — consumers must read the dict directly.-- STRICT carries a redacted ``message``, drops provider/model identity,- drops ``user_action``, and projects ``provider_metadata`` through a- curated subset. Read the dict's fields directly (``payload[<key>]``);- ``from_dict`` is meant only as the VERBOSE round-trip inverse.- """- report = _runtime_report()- strict_payload = report.to_dict(disclosure_mode=DisclosureMode.STRICT)- # Direct dict reads — the HTTP adapter / API surface doesn't rehydrate.- assert strict_payload["message"] == INTERNAL_ERROR_PLACEHOLDER- assert "provider" not in strict_payload- assert "model" not in strict_payload- assert "user_action" not in strict_payload- # The curated ``provider_metadata`` slice rides for the HTTP adapter to- # emit Retry-After / the right status — see- # ``test_strict_provider_metadata_dict_carries_http_status_for_adapter``.-- def test_strict_payload_with_provider_metadata_fails_from_dict_rehydration(self) -> None:- """A STRICT payload that carries ``provider_metadata`` is not rehydratable via :meth:`from_dict`.-- Pins the sharp failure mode external consumers should expect: the- curated subset (``status_code`` / ``retry_after_seconds``) lacks the- ``provider`` and ``sdk_exception_type`` fields required by- :class:`ProviderErrorMetadata`, so :meth:`ErrorReport.from_dict` raises- :class:`pydantic.ValidationError`. Consumers must read the STRICT dict- directly (e.g. via :meth:`ErrorReport.to_problem_document`) rather than- rebuilding through ``from_dict``; any code path that relied on the- pre-curated-subset behavior — where STRICT dropped ``provider_metadata``- entirely and was therefore still rehydratable — must migrate.- """- report = _runtime_report()- strict_payload = report.to_dict(disclosure_mode=DisclosureMode.STRICT)- assert "provider_metadata" in strict_payload- with pytest.raises(ValidationError):- ErrorReport.from_dict(strict_payload)-- def test_to_dict_defaults_to_verbose(self) -> None:- """No argument == VERBOSE — the safe default for in-process / round-trip callers."""- report = _runtime_report()- assert report.to_dict() == report.to_dict(disclosure_mode=DisclosureMode.VERBOSE)-- def test_strict_branch_kept_field_parity(self) -> None:- """STRICT projection: both branches emit the same key set modulo the deliberately divergent keys.-- Pins the single-allowlist contract introduced when the two STRICT- branches were unified: caller-facing and redacted branches share- ``_STRICT_KEPT_FIELDS`` as the base, and the caller-facing branch- adds ``message`` and ``user_action`` on top while the redacted branch- only emits a placeholder ``message``. Both branches reattach the- same curated ``provider_metadata`` slice. The remaining key set must- match — without this pin, a new ``ErrorReport`` field added in the- future could silently appear on one branch and silently disappear- from the other.- """- # A report with every populatable field set, so both branches see the- # same payload going in. We then flip ``caller_facing_message`` to- # 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",- type_uri="https://docs.pipelex.com/latest/errors/mthds-parser-error/",- error_category="capacity",- error_domain=ErrorDomain.INPUT,- retryable=False,- user_action=UserAction(kind=UserActionKind.CHANGE_INPUT, detail="fix the concept name"),- model="gpt-5",- provider="openai",- provider_metadata=ProviderErrorMetadata(- provider=ProviderName.OPENAI,- sdk_exception_type="RateLimitError",- status_code=429,- retry_after_seconds=12.0,- ),- caller_facing_message=True,- )- redacted_report = caller_facing_report.model_copy(update={"caller_facing_message": False})-- caller_facing_payload = caller_facing_report.to_dict(disclosure_mode=DisclosureMode.STRICT)- redacted_payload = redacted_report.to_dict(disclosure_mode=DisclosureMode.STRICT)-- # ``message`` is on both (different values), ``user_action`` only on caller-facing —- # those are the legitimate divergences. After removing them, the key sets must match.- assert set(caller_facing_payload) - {"message", "user_action"} == set(redacted_payload) - {"message"}-- @pytest.mark.parametrize(- "caller_facing",- [- pytest.param(True, id="caller-facing-branch"),- pytest.param(False, id="redacted-branch"),- ],- )- def test_strict_retains_validation_errors_on_both_branches(self, caller_facing: bool) -> None:- """``validation_errors`` survives STRICT on BOTH the caller-facing and redacted branches.-- The structured per-error list describes the caller's own submitted bundle,- not server internals — so it is kept on the external surface via- ``_STRICT_KEPT_FIELDS`` rather than by the caller-facing branch's bespoke- message logic. A real ``ValidateBundleError`` only ever rides the- caller-facing branch, but the field must be branch-independent so a future- 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",- type_uri="https://docs.pipelex.com/latest/errors/validate-bundle-error/",- error_domain=ErrorDomain.INPUT,- caller_facing_message=caller_facing,- validation_errors=[- ValidationErrorItem(- category=ValidationErrorCategory.PIPE_VALIDATION,- source="main.mthds",- pipe_code="summarize",- message="Missing input variable(s): doc.",- ),- ],- )- payload = report.to_dict(disclosure_mode=DisclosureMode.STRICT)- assert "validation_errors" in payload- assert payload["validation_errors"][0]["source"] == "main.mthds"-- def test_receiver_rehydrates_verbose_payload_for_webhook(self) -> None:- """An API-side receiver rebuilds the report from a VERBOSE webhook payload.-- Pins the contract pipelex-api consumes on the delivery webhook: the- runner serializes a report into ``payload["error"]`` using- ``to_dict(VERBOSE)`` and the receiver round-trips it back through- ``ErrorReport.from_dict``.- """- report = _runtime_report()- envelope: dict[str, Any] = {"status": "failed", "error": report.to_dict(disclosure_mode=DisclosureMode.VERBOSE)}- recovered = ErrorReport.from_dict(envelope["error"])- assert recovered == reportdiff --git a/tests/unit/pipelex/test_error_report_from_dict.py b/tests/unit/pipelex/test_error_report_from_dict.pydeleted file mode 100644index ab244dff8..000000000--- a/tests/unit/pipelex/test_error_report_from_dict.py+++ /dev/null@@ -1,121 +0,0 @@-"""Unit tests for ``ErrorReport.from_dict`` — the strict inverse of ``to_dict``.--``from_dict`` rebuilds an ``ErrorReport`` from a serialized payload (e.g. a-Temporal ``ApplicationError.details`` dict) so it re-enters the-``to_error_report()`` world. It must round-trip ``to_dict`` exactly — nested-``UserAction`` / ``ProviderErrorMetadata`` included — and stay strict, raising-``ValidationError`` on a malformed or schema-drifted dict.-"""--from typing import Any--import pytest-from pydantic import ValidationError--from pipelex.base_exceptions import ErrorDomain, ErrorReport-from pipelex.cogt.inference.error_classification import ProviderErrorMetadata, UserAction, UserActionKind-from pipelex.cogt.inference.provider_name import ProviderName---class TestErrorReportFromDict:- @pytest.mark.parametrize(- "report",- [- pytest.param(- ErrorReport(- code="runtime.unexpected",- error_type="X",- message="m",- title="X error",- type_uri="https://docs.pipelex.com/latest/errors/x/",- ),- id="minimal",- ),- pytest.param(- ErrorReport(- code="provider.quota_exhausted",- error_type="CogtError",- message="rate limited",- title="AI inference failed",- type_uri="https://docs.pipelex.com/latest/errors/cogt-error/",- error_category="capacity",- error_domain=ErrorDomain.RUNTIME,- retryable=False,- user_action=UserAction(kind=UserActionKind.CHECK_BILLING, detail="check your billing page"),- model="gpt-5",- provider="openai",- ),- id="full-with-user-action",- ),- pytest.param(- ErrorReport(- code="runtime.unexpected",- error_type="LLMCompletionError",- message="429 Too Many Requests",- title="LLM completion",- type_uri="https://docs.pipelex.com/latest/errors/llm-completion-error/",- error_category="capacity",- retryable=True,- provider_metadata=ProviderErrorMetadata(- provider=ProviderName.OPENAI,- sdk_exception_type="RateLimitError",- status_code=429,- retry_after_seconds=12.0,- ),- ),- id="provider-metadata-429",- ),- ],- )- def test_from_dict_round_trips_to_dict(self, report: ErrorReport) -> None:- """``from_dict`` is the exact inverse of ``to_dict``, nested models included."""- recovered = ErrorReport.from_dict(report.to_dict())- assert recovered == report- # The 429 passthrough must survive so HTTP adapters keep the right status.- assert recovered.http_status == report.http_status-- @pytest.mark.parametrize(- "bad_data",- [- pytest.param(- {"message": "missing error_type", "title": "t", "type_uri": "u"},- id="missing-required-error-type",- ),- pytest.param(- {"error_type": "X", "title": "t", "type_uri": "u"},- id="missing-required-message",- ),- pytest.param(- {"error_type": "X", "message": "m", "type_uri": "u"},- id="missing-required-title",- ),- pytest.param(- {"error_type": "X", "message": "m", "title": "t"},- id="missing-required-type-uri",- ),- pytest.param(- {- "error_type": "X",- "message": "m",- "title": "t",- "type_uri": "u",- "surprise": "extra",- },- id="extra-forbidden-key",- ),- pytest.param(- {- "error_type": "X",- "message": "m",- "title": "t",- "type_uri": "u",- "retryable": ["not", "a", "bool"],- },- id="wrong-field-type",- ),- ],- )- def test_g1_from_dict_raises_on_malformed_dict(self, bad_data: dict[str, Any]) -> None:- """G1 — ``from_dict`` is strict: a malformed / schema-drifted dict raises ``ValidationError``."""- with pytest.raises(ValidationError):- ErrorReport.from_dict(bad_data)diff --git a/tests/unit/pipelex/test_error_report_problem_document.py b/tests/unit/pipelex/test_error_report_problem_document.pydeleted file mode 100644index 4b00fe527..000000000--- a/tests/unit/pipelex/test_error_report_problem_document.py+++ /dev/null@@ -1,197 +0,0 @@-"""Unit tests for ``ErrorReport.to_problem_document`` — RFC 7807 envelope.--The runner stays HTTP-agnostic (no FastAPI/Starlette import); ``to_problem_document``-returns a plain dict that downstream HTTP adapters serialize as JSON. The-standard 7807 slots (``type``, ``title``, ``status``, ``detail``, ``instance``)-are populated from the report; pipelex-native classification fields ride as-extension members. ``type_uri`` and ``title`` are mapped, not duplicated — there-is exactly one ``title`` key and ``type == type_uri``.-"""--import pytest--from pipelex.base_exceptions import INTERNAL_ERROR_PLACEHOLDER, DisclosureMode, ErrorDomain, ErrorReport-from pipelex.cogt.inference.error_classification import ProviderErrorMetadata, UserAction, UserActionKind-from pipelex.cogt.inference.provider_name import ProviderName---def _runtime_report() -> ErrorReport:- return ErrorReport(- code="provider.quota_exhausted",- error_type="CogtError",- message="rate limited on the worker",- title="AI inference failed",- type_uri="https://docs.pipelex.com/latest/errors/cogt-error/",- error_category="capacity",- error_domain=ErrorDomain.RUNTIME,- retryable=False,- user_action=UserAction(kind=UserActionKind.CHECK_BILLING, detail="check your billing page"),- model="gpt-5",- provider="openai",- provider_metadata=ProviderErrorMetadata(- provider=ProviderName.OPENAI,- sdk_exception_type="RateLimitError",- status_code=429,- retry_after_seconds=12.0,- ),- )---class TestErrorReportProblemDocument:- def test_standard_slots_populated_from_report(self) -> None:- """``type`` / ``title`` / ``status`` / ``detail`` / ``instance`` come straight off the report or args."""- report = _runtime_report()- document = report.to_problem_document(instance="urn:pipelex:run:123", request_id="r-abc")- assert document["type"] == report.type_uri- assert document["title"] == report.title- assert document["status"] == report.http_status- assert document["detail"] == report.message- assert document["instance"] == "urn:pipelex:run:123"- assert document["request_id"] == "r-abc"-- def test_rfc_7807_mapping_does_not_duplicate_title_or_type(self) -> None:- """``type_uri`` / ``title`` are mapped into the standard slots — not echoed in extensions."""- report = _runtime_report()- document = report.to_problem_document()- # Single ``title`` key — no extension would otherwise collide with the standard slot.- assert sum(1 for key in document if key == "title") == 1- # ``type`` standard slot holds the URI value; no separate ``type_uri`` extension survives.- assert document["type"] == report.type_uri- assert "type_uri" not in document-- def test_extension_members_carry_pipelex_classification(self) -> None:- """Pipelex-native fields ride as extensions; the standard slots do not duplicate them."""- report = _runtime_report()- document = report.to_problem_document()- assert document["error_type"] == "CogtError"- assert document["error_domain"] == ErrorDomain.RUNTIME- assert document["error_category"] == "capacity"- assert document["retryable"] is False- assert document["model"] == "gpt-5"- assert document["provider"] == "openai"- assert document["user_action"]["kind"] == UserActionKind.CHECK_BILLING-- def test_request_id_extension_absent_when_not_provided(self) -> None:- """``request_id`` is an optional extension — omitted when the caller does not pass it."""- document = _runtime_report().to_problem_document()- assert "request_id" not in document-- def test_instance_extension_absent_when_not_provided(self) -> None:- """``instance`` is optional — omitted when the caller does not pass it."""- document = _runtime_report().to_problem_document()- assert "instance" not in document-- @pytest.mark.parametrize(- ("error_domain", "expected_status"),- [- pytest.param(ErrorDomain.INPUT, 422, id="input-422"),- pytest.param(ErrorDomain.CONFIG, 500, id="config-500"),- pytest.param(ErrorDomain.RUNTIME, 500, id="runtime-500"),- ],- )- 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",- type_uri="https://docs.pipelex.com/latest/errors/x/",- error_domain=error_domain,- )- document = report.to_problem_document()- assert document["status"] == expected_status-- def test_strict_mode_redacts_detail_and_drops_disclosure_fields(self) -> None:- """Strict ``to_problem_document`` redacts ``detail`` and drops disclosure-leaking extensions.-- ``provider`` / ``model`` identity is stripped. ``provider_metadata`` is- projected through the curated subset — ``status_code`` and- ``retry_after_seconds`` ride as an extension member so HTTP adapters can- derive ``Retry-After`` headers from the problem document.- """- report = _runtime_report()- document = report.to_problem_document(disclosure_mode=DisclosureMode.STRICT)- assert document["detail"] == INTERNAL_ERROR_PLACEHOLDER- assert "model" not in document- assert "provider" not in document- assert "user_action" not in document- # Stable identifiers are kept.- assert document["error_type"] == "CogtError"- assert document["error_category"] == "capacity"- assert document["retryable"] is False- # Curated provider_metadata slice rides as an extension member.- assert document["provider_metadata"] == {"status_code": 429, "retry_after_seconds": 12.0}-- 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",- type_uri="https://docs.pipelex.com/latest/errors/mthds-parser-error/",- error_domain=ErrorDomain.INPUT,- caller_facing_message=True,- )- document = report.to_problem_document(disclosure_mode=DisclosureMode.STRICT)- assert document["detail"] == "pipe 'summarize' references unknown concept at line 14"-- def test_strict_mode_redacts_detail_for_input_domain_without_caller_facing_flag(self) -> None:- """An INPUT-classified report whose message is NOT caller-facing is still redacted in STRICT.-- Regression pin: ``error_domain == INPUT`` alone (here inherited up a- ``__cause__`` chain by a domain-less wrapper) must not earn a ``detail``- 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",- type_uri="https://docs.pipelex.com/latest/errors/pipelex-unexpected-error/",- error_domain=ErrorDomain.INPUT,- )- document = report.to_problem_document(disclosure_mode=DisclosureMode.STRICT)- assert document["detail"] == INTERNAL_ERROR_PLACEHOLDER-- def test_strict_mode_never_emits_provider_fields_regardless_of_error_domain(self) -> None:- """STRICT ``to_problem_document`` never echoes ``provider`` / ``model`` / ``provider_metadata``.-- Gap 2: even a caller-facing INPUT report whose cause-enrichment pulled- provider metadata from an inference ``__cause__`` must not surface it on- the RFC 7807 envelope.- """- report = ErrorReport(- code="method.syntax",- error_type="MthdsParserError",- message="pipe 'summarize' references unknown concept at line 14",- title="MTHDS parser",- type_uri="https://docs.pipelex.com/latest/errors/mthds-parser-error/",- error_domain=ErrorDomain.INPUT,- caller_facing_message=True,- model="gpt-5",- provider="openai",- provider_metadata=ProviderErrorMetadata(provider=ProviderName.OPENAI, sdk_exception_type="RateLimitError"),- )- document = report.to_problem_document(disclosure_mode=DisclosureMode.STRICT)- assert document["detail"] == report.message- assert "model" not in document- assert "provider" not in document- assert "provider_metadata" not in document-- 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",- type_uri="https://docs.pipelex.com/latest/errors/mthds-parser-error/",- error_domain=ErrorDomain.INPUT,- caller_facing_message=True,- )- verbose_document = report.to_problem_document(disclosure_mode=DisclosureMode.VERBOSE)- strict_document = report.to_problem_document(disclosure_mode=DisclosureMode.STRICT)- assert "caller_facing_message" not in verbose_document- assert "caller_facing_message" not in strict_documentdiff --git a/tests/unit/pipelex/test_pipelex_error_message_init.py b/tests/unit/pipelex/test_pipelex_error_message_init.pyindex 09193326e..7da9066c6 100644--- a/tests/unit/pipelex/test_pipelex_error_message_init.py+++ b/tests/unit/pipelex/test_pipelex_error_message_init.py@@ -4,8 +4,8 @@ A subclass that mixes in ``ValueError`` / ``TypeError`` (so Pydantic validatorsits raises into a ``ValidationError``) must list the ``PipelexError``-derived base*first*. Otherwise ``BaseException.__init__`` — inherited through ``ValueError`` /``TypeError`` — shadows ``PipelexError.__init__`` in the MRO, ``self.message`` is never-set, and ``to_error_report()`` raises ``AttributeError`` the moment an error-report-rendering path touches the instance.+set, and ``to_problem()`` raises ``AttributeError`` the moment a problem-building path touches+the instance."""import pytest@@ -13,6 +13,7 @@ import pytestfrom pipelex.base_exceptions import PipelexErrorfrom pipelex.cogt.exceptions import RoutingProfileBlueprintValueErrorfrom pipelex.errors.error_class_discovery import iter_pipelex_error_subclasses+from pipelex.errors.problem import ProblemViewfrom pipelex.pipe_operators.compose.exceptions import ConstructFieldBlueprintValueError@@ -31,14 +32,15 @@ class TestPipelexErrorMessageInit:assert not offenders, "Exception classes shadow PipelexError.__init__ — `.message` will be unset:\n" + "\n".join(offenders)@pytest.mark.parametrize("error_cls", [ConstructFieldBlueprintValueError, RoutingProfileBlueprintValueError])- def test_message_set_and_error_report_succeeds(self, error_cls: type[PipelexError]) -> None:+ def test_message_set_and_problem_succeeds(self, error_cls: type[PipelexError]) -> None:"""A reordered ``(PipelexError, ValueError)`` mixin sets ``.message``, keeps its- ``ValueError`` identity (so Pydantic still wraps validator raises), and renders a report.+ ``ValueError`` identity (so Pydantic still wraps validator raises), and builds a problem."""message = "the configuration section is invalid"exc = error_cls(message)assert exc.message == messageassert isinstance(exc, ValueError)- report = exc.to_error_report()- assert report.message == message- assert report.error_type == error_cls.__name__+ problem = exc.to_problem(view=ProblemView.OPERATOR)+ assert problem.diagnostics is not None+ assert problem.diagnostics.message == message+ assert problem.diagnostics.error_class == error_cls.__name__diff --git a/tests/unit/pipelex/test_runtime_boot_credential_refusals.py b/tests/unit/pipelex/test_runtime_boot_credential_refusals.pyindex c3d256e47..edea56082 100644--- a/tests/unit/pipelex/test_runtime_boot_credential_refusals.py+++ b/tests/unit/pipelex/test_runtime_boot_credential_refusals.py@@ -5,6 +5,7 @@ from pytest_mock import MockerFixturefrom pipelex.base_exceptions import PipelexSetupErrorfrom pipelex.cogt.exceptions import InferenceBackendCredentialsError, InferenceBackendCredentialsErrorTypefrom pipelex.errors.error_codes import ErrorCode+from pipelex.errors.problem import ProblemViewfrom pipelex.errors.registry.pipelex_codes import PipelexErrorCodefrom pipelex.pipelex import Pipelexfrom pipelex.system.runtime import IntegrationMode, runtime_manager@@ -52,7 +53,7 @@ class TestRuntimeBootCredentialRefusals:assert raised.value.__cause__ is refusalassert "LIGHTHOUSE_API_KEY" in str(raised.value)- assert raised.value.to_error_report().code == expected_code+ assert raised.value.to_problem(view=ProblemView.OPERATOR).code == expected_codefinally: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.pyindex 2fc7613a0..6610f7189 100644--- a/tests/unit/pipelex/tools/jinja2/test_jinja2_render_owner.py+++ b/tests/unit/pipelex/tools/jinja2/test_jinja2_render_owner.py@@ -3,9 +3,9 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, Anyimport pytest-from mthds.protocol.problem.registry import CoreCode+from mthds.protocol.problem.registry import CoreCode, ProblemDomain-from pipelex.base_exceptions import INTERNAL_ERROR_PLACEHOLDER, DisclosureMode, PipelexError+from pipelex.errors.problem import ProblemViewfrom pipelex.system.exceptions import ToolErrorfrom pipelex.tools.jinja2.exceptions import (Jinja2StuffError,@@ -23,6 +23,7 @@ from pipelex.tools.templating.templating_style import TagStyle, TemplatingStylefrom pipelex.tools.templating.text_format import TextFormatif TYPE_CHECKING:+ from pipelex.base_exceptions import PipelexErrorfrom pipelex.errors.error_codes import ErrorCode_TEMPLATING_STYLE = TemplatingStyle(tag_style=TagStyle.NO_TAG, text_format=TextFormat.PLAIN)@@ -67,30 +68,37 @@ class TestJinja2RenderOwner: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."""+ async def test_an_invalid_method_template_is_the_methods_and_the_caller_reads_the_fault(self, template_source: str, fault: str) -> None:+ """A method's template naming what its environment lacks: `method.template_invalid`, its fault the caller's, 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"]+ caller = error.to_problem(view=ProblemView.CALLER)+ assert caller.code == CoreCode.METHOD_TEMPLATE_INVALID+ assert caller.domain == ProblemDomain.METHOD+ assert caller.params is not None+ assert caller.params.as_wire()["finding"] == fault+ assert "quietly_routed" not in str(caller.to_wire())+ operator = error.to_problem(view=ProblemView.OPERATOR)+ assert operator.diagnostics is not None+ assert operator.diagnostics.message == f"Jinja2 render — the template cannot render as written: {fault}"@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."""+ """Pipelex's own template, the default owner: `runtime.unexpected`, whose fault only the operator reads."""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+ caller = error.to_problem(view=ProblemView.CALLER)+ assert caller.code == CoreCode.RUNTIME_UNEXPECTED+ assert caller.params is None+ assert "frob_the_lane" not in str(caller.to_wire())+ operator = error.to_problem(view=ProblemView.OPERATOR)+ assert operator.diagnostics is not None+ assert "frob_the_lane" in operator.diagnostics.message@pytest.mark.parametrize(("topic", "template_source", "context", "is_undefined_strict", "error_class", "method_code", "pipelex_code"),@@ -181,7 +189,7 @@ class TestJinja2RenderOwner: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"+ assert error.to_problem(view=ProblemView.CALLER).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:@@ -191,7 +199,7 @@ class TestJinja2RenderOwner:templating_context={"lane": "express"},template_owner=TemplateOwner.METHOD,)- assert exc_info.value.to_error_report().code == CoreCode.METHOD_TEMPLATE_INVALID+ assert exc_info.value.to_problem(view=ProblemView.CALLER).code == CoreCode.METHOD_TEMPLATE_INVALID@pytest.mark.parametrize(("template_source", "expected_names"),diff --git a/tests/unit/pipelex/tools/misc/test_file_fetch_utils.py b/tests/unit/pipelex/tools/misc/test_file_fetch_utils.pyindex a2f3ceda8..27a52c227 100644--- a/tests/unit/pipelex/tools/misc/test_file_fetch_utils.py+++ b/tests/unit/pipelex/tools/misc/test_file_fetch_utils.py@@ -1,8 +1,9 @@import httpximport pytest-from mthds.protocol.problem.registry import CoreCode+from mthds.protocol.problem.registry import CoreCode, ProblemDomain-from pipelex.base_exceptions import DisclosureMode+from pipelex.errors.error_codes import error_code_spec+from pipelex.errors.problem import ProblemViewfrom pipelex.tools.misc.exceptions import RemoteFileFetchErrorfrom pipelex.tools.misc.file_fetch_utils import fetch_file_and_content_type_from_url_httpx, fetch_file_from_url_httpx@@ -36,8 +37,8 @@ class TestFetchFileFromUrl:(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.+ async def test_error_status_raises_an_input_error(self, status_code: int, expected_code: CoreCode) -> None:+ """A 4xx/5xx becomes an input error, whose message names the URL and the status.A server that will not serve the file is ``input.file_unreadable``; one that cannot answer now, a 5xx or a429, is ``input.url_unreachable``, which a retry may get past.@@ -46,9 +47,14 @@ class TestFetchFileFromUrl:await fetch_file_from_url_httpx(url=URL, transport=_transport_answering(status_code))assert exc_info.value.resolve_error_code() == expected_code- strict = 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"]+ caller = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert caller.code == expected_code+ assert caller.domain == ProblemDomain.INPUT+ assert caller.is_retryable is error_code_spec(expected_code).invites_retry+ operator = exc_info.value.to_problem(view=ProblemView.OPERATOR)+ assert operator.diagnostics is not None+ assert f"HTTP {status_code}" in operator.diagnostics.message+ assert URL in operator.diagnostics.message@pytest.mark.parametrize(("exc", "expected", "expected_code"),@@ -58,7 +64,7 @@ class TestFetchFileFromUrl: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, expected_code: CoreCode) -> None:+ async def test_network_failure_raises_an_input_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_codediff --git a/tests/unit/pipelex/tools/test_jinja2_render_budget.py b/tests/unit/pipelex/tools/test_jinja2_render_budget.pyindex 7a83c923f..c0ede6d6b 100644--- a/tests/unit/pipelex/tools/test_jinja2_render_budget.py+++ b/tests/unit/pipelex/tools/test_jinja2_render_budget.py@@ -21,11 +21,12 @@ import pytestfrom jinja2 import DictLoaderfrom jinja2.sandbox import ImmutableSandboxedEnvironmentfrom markupsafe import Markup+from mthds.protocol.problem.registry import CoreCode, ProblemDomainfrom typing_extensions import override-from pipelex.base_exceptions import ErrorDomainfrom pipelex.core.stuffs.markdown_content import MarkdownContentfrom pipelex.core.stuffs.text_content import TextContent+from pipelex.errors.problem import ProblemViewfrom pipelex.tools.jinja2.exceptions import Jinja2TemplateBudgetErrorfrom pipelex.tools.jinja2.jinja2_environment import make_jinja2_env_without_loaderfrom pipelex.tools.jinja2.jinja2_filters import markdown_to_html@@ -601,10 +602,13 @@ class TestRenderBudget:text = "word " * 2400assert _render("{{ doc | striptags }}", doc=_text_content(text)) == _render("{{ text | striptags }}", text=text)- def test_budget_error_is_the_caller_s_and_caller_facing(self) -> None:- report = Jinja2TemplateBudgetError("refused by the render budget").to_error_report()- assert report.error_domain == ErrorDomain.INPUT- assert report.caller_facing_message+ def test_budget_error_is_the_method_s_or_the_input_s(self) -> None:+ """A method's template past its budget is the method's to fix; a Pipelex template's, the caller's input."""+ method_fault = Jinja2TemplateBudgetError("refused by the render budget").to_problem(view=ProblemView.CALLER)+ assert method_fault.code == CoreCode.PIPE_TEMPLATE_BUDGET_EXCEEDED+ assert method_fault.domain == ProblemDomain.METHOD+ input_fault = Jinja2TemplateBudgetError("refused by the render budget").with_error_code(CoreCode.INPUT_TOO_LARGE)+ assert input_fault.to_problem(view=ProblemView.CALLER).domain == ProblemDomain.INPUT@pytest.mark.parametrize("template_source", _UNCHANGED)@pytest.mark.parametrize("autoescape", [False, True])diff --git a/tests/unit/pipelex/tools/test_jinja2_sandbox.py b/tests/unit/pipelex/tools/test_jinja2_sandbox.pyindex 82377c229..36b32516b 100644--- a/tests/unit/pipelex/tools/test_jinja2_sandbox.py+++ b/tests/unit/pipelex/tools/test_jinja2_sandbox.py@@ -20,6 +20,7 @@ from pipelex.core.stuffs.stuff import Stufffrom pipelex.core.stuffs.stuff_artefact import StuffArtefactfrom pipelex.core.stuffs.stuff_content import StuffContentfrom pipelex.core.stuffs.text_content import TextContent+from pipelex.errors.problem import ProblemViewfrom pipelex.system.exceptions import ToolErrorfrom pipelex.tools.jinja2.exceptions import Jinja2TemplateRenderError, Jinja2TemplateSecurityErrorfrom pipelex.tools.jinja2.image_registry import ImageRegistry@@ -271,7 +272,9 @@ class TestTemplateSandbox:templating_context=_make_context(),)assert type(exc_info.value) is Jinja2TemplateSecurityError- assert exc_info.value.to_error_report().error_type == "Jinja2TemplateSecurityError"+ operator = exc_info.value.to_problem(view=ProblemView.OPERATOR)+ assert operator.diagnostics is not None+ assert operator.diagnostics.error_class == "Jinja2TemplateSecurityError"def test_sync_render_reads_metadata(self) -> None:rendered = render_jinja2_sync(diff --git a/tests/unit/pipelex/tools/uri/test_uri_read_scope.py b/tests/unit/pipelex/tools/uri/test_uri_read_scope.pyindex 0e774c3f4..c88e3e5fb 100644--- a/tests/unit/pipelex/tools/uri/test_uri_read_scope.py+++ b/tests/unit/pipelex/tools/uri/test_uri_read_scope.py@@ -1,8 +1,10 @@"""The read scope's check: a scoped run reads only its own storage prefix, and never the local disk."""import pytest+from mthds.protocol.problem.registry import CoreCode, ProblemDomain-from pipelex.base_exceptions import DisclosureMode, ErrorDomain+from pipelex.errors.error_codes import error_code_spec+from pipelex.errors.problem import ProblemViewfrom pipelex.tools.uri.exceptions import UriReadRefusalReason, UriReadRefusedErrorfrom pipelex.tools.uri.uri_read_scope import UriReference, authorize_uri_read, authorize_uri_reads@@ -94,15 +96,18 @@ class TestAuthorizeUriRead:assert "secret.png" not in messageassert READ_SCOPE not in message- def test_the_refusal_is_a_caller_facing_input_error_answered_as_a_422(self) -> None:+ def test_the_refusal_is_an_input_error_answered_as_a_422_quoting_no_uri(self) -> None:with pytest.raises(UriReadRefusedError) as exc_info:authorize_uri_read(uri="/etc/passwd", read_scope=READ_SCOPE, position="the input 'photo'")- error_report = exc_info.value.to_error_report()- assert error_report.error_domain == ErrorDomain.INPUT- assert error_report.http_status == 422- strict = error_report.to_dict(disclosure_mode=DisclosureMode.STRICT)- assert "the input 'photo'" in strict["message"]- assert "/etc/passwd" not in strict["message"]+ caller = exc_info.value.to_problem(view=ProblemView.CALLER)+ assert caller.code == CoreCode.SECURITY_INPUT_URL_REFUSED+ assert caller.domain == ProblemDomain.INPUT+ assert error_code_spec(CoreCode.SECURITY_INPUT_URL_REFUSED).status == 422+ assert "/etc/passwd" not in str(caller.to_wire())+ operator = exc_info.value.to_problem(view=ProblemView.OPERATOR)+ assert operator.diagnostics is not None+ assert "the input 'photo'" in operator.diagnostics.message+ assert "/etc/passwd" not in operator.diagnostics.messagedef test_the_list_form_refuses_the_first_reference_the_scope_does_not_allow(self) -> None:uri_references = [diff --git a/tests/unit/pipelex/tracing/test_assembler_equivalence.py b/tests/unit/pipelex/tracing/test_assembler_equivalence.pyindex 796363f13..187cb845a 100644--- a/tests/unit/pipelex/tracing/test_assembler_equivalence.py+++ b/tests/unit/pipelex/tracing/test_assembler_equivalence.py@@ -13,11 +13,13 @@ from datetime import UTC, datetime, timedeltafrom typing import Any, Callableimport pytest+from mthds.protocol.problem.registry import CoreCodefrom pytest_mock import MockerFixturefrom pipelex.cogt.llm.llm_report import LLMTokensUsagefrom pipelex.cogt.usage.cost_category import CostCategoryfrom pipelex.cogt.usage.token_category import TokenCategory+from pipelex.errors.problem import ProblemView, make_location, make_problemfrom pipelex.graph.condition_output_merge import ConditionOutputMerge, ConditionOutputTypingfrom pipelex.graph.graph_tracer import GraphTracerfrom pipelex.graph.graphspec import EdgeKind, EdgeSpec, GraphSpec, IOSpec, NodeKind, NodeSpec@@ -61,8 +63,8 @@ def _normalize_node(node: NodeSpec) -> dict[str, Any]:"pipe_code": node.pipe_code,"pipe_type": node.pipe_type,"status": node.status,- "error_type": node.error.error_type if node.error else None,- "error_message": node.error.message if node.error else None,+ "error": node.error.to_wire() if node.error else None,+ "error_stack": node.error_stack,"metrics": node.metrics,# Concept and multiplicity ride along so both builders are held to carry each io item's typing."inputs": sorted(@@ -407,8 +409,12 @@ def _scenario_partial_failure(tracer: GraphTracer, context: TraceContext) -> Nontracer.on_pipe_end_error(node_id=child_id,ended_at=started_at + timedelta(seconds=2),- error_type="LLMError",- error_message="Model returned an error",+ problem=make_problem(+ code=CoreCode.PROVIDER_UNAVAILABLE,+ view=ProblemView.CALLER,+ location=make_location(pipe="gen_text", path=["parent_pipe", "gen_text"]),+ ),+ error_stack="Traceback (most recent call last):\n File ...",)# Parent has no end event → will be marked CANCELEDdiff --git a/tests/unit/pipelex/tracing/test_assembler_supersession.py b/tests/unit/pipelex/tracing/test_assembler_supersession.pyindex 03743e900..36e6f1cff 100644--- a/tests/unit/pipelex/tracing/test_assembler_supersession.py+++ b/tests/unit/pipelex/tracing/test_assembler_supersession.py@@ -2,11 +2,13 @@ from datetime import UTC, datetime, timedeltafrom typing import Anyimport pytest+from mthds.protocol.problem.registry import CoreCodefrom pipelex.cogt.llm.llm_report import LLMTokensUsagefrom pipelex.cogt.usage.cost_category import CostCategoryfrom pipelex.cogt.usage.token_category import TokenCategory-from pipelex.graph.graphspec import ErrorSpec, GraphSpec, NodeKind, NodeStatus+from pipelex.errors.problem import ProblemView, make_location, make_problem+from pipelex.graph.graphspec import GraphSpec, NodeKind, NodeStatusfrom pipelex.system.execution_chain import ExecutionAttemptfrom pipelex.system.job_metadata import JobCategory, JobMetadata, RunMetadata, UnitJobIdfrom pipelex.system.pipe_run_mode import PipeRunMode@@ -75,7 +77,7 @@ class _Writer:pipe_ref=f"filings.{pipe_code}",pipe_type=pipe_type,ended_at=base["timestamp"],- error=ErrorSpec(error_type="WorkerLostError", message="An internal error occurred."),+ error=make_problem(code=CoreCode.RUNTIME_UNEXPECTED, view=ProblemView.CALLER, location=make_location(pipe=pipe_code, path=[pipe_code])),)def usage(self, *, node_id: str, path: str) -> UsageReportEvent:diff --git a/tests/unit/pipelex/tracing/test_graphspec_assembler.py b/tests/unit/pipelex/tracing/test_graphspec_assembler.pyindex dca19d52e..78f62b160 100644--- a/tests/unit/pipelex/tracing/test_graphspec_assembler.py+++ b/tests/unit/pipelex/tracing/test_graphspec_assembler.py@@ -4,8 +4,10 @@ from datetime import UTC, datetime, timedeltafrom typing import Anyimport pytest+from mthds.protocol.problem.registry import CoreCode-from pipelex.graph.graphspec import EdgeKind, ErrorSpec, GraphSpecMode, IOSpec, NodeKind, NodeStatus+from pipelex.errors.problem import ProblemView, make_location, make_problem+from pipelex.graph.graphspec import EdgeKind, GraphSpecMode, IOSpec, NodeKind, NodeStatusfrom pipelex.system.pipe_run_mode import PipeRunModefrom pipelex.tracing.exceptions import TraceEventModeErrorfrom pipelex.tracing.graphspec_assembler import GraphSpecAssembler@@ -751,10 +753,12 @@ class TestGraphSpecAssembler:**_base(_WF_A, 3),node_id=child,ended_at=_time_at(3),- error=ErrorSpec(- error_type="LLMError",- message="Model returned an error",+ error=make_problem(+ code=CoreCode.PROVIDER_UNAVAILABLE,+ view=ProblemView.CALLER,+ location=make_location(pipe="gen_text", path=["parent_pipe", "gen_text"]),),+ error_stack="Traceback (most recent call last):\n File ...",),# No end event for parent]@@ -765,7 +769,10 @@ class TestGraphSpecAssembler:assert nodes_by_id[child].status == NodeStatus.FAILEDchild_error = nodes_by_id[child].errorassert child_error is not None- assert child_error.error_type == "LLMError"+ assert child_error.code == CoreCode.PROVIDER_UNAVAILABLE+ assert child_error.location is not None+ assert child_error.location.as_wire() == {"pipe": "gen_text", "path": ["parent_pipe", "gen_text"]}+ assert nodes_by_id[child].error_stack == "Traceback (most recent call last):\n File ..."assert nodes_by_id[parent].status == NodeStatus.CANCELEDdef test_multiple_workflows(self) -> None:diff --git a/tests/unit/pipelex/tracing/test_trace_events.py b/tests/unit/pipelex/tracing/test_trace_events.pyindex 75bb25f29..9ba9ecf37 100644--- a/tests/unit/pipelex/tracing/test_trace_events.py+++ b/tests/unit/pipelex/tracing/test_trace_events.py@@ -1,17 +1,20 @@"""Serialization round-trip tests for trace event models."""+import jsonfrom datetime import UTC, datetimefrom typing import Any, ClassVarimport pytest+from mthds.protocol.problem.registry import CoreCodefrom pydantic import TypeAdapter, ValidationErrorfrom pytest_mock import MockerFixturefrom pipelex.cogt.llm.llm_report import LLMTokensUsagefrom pipelex.cogt.usage.cost_category import CostCategoryfrom pipelex.cogt.usage.token_category import TokenCategory+from pipelex.errors.problem import PipelexProblem, ProblemView, make_location, make_problemfrom pipelex.graph.condition_output_merge import ConditionOutputMerge, ConditionOutputTyping-from pipelex.graph.graphspec import EdgeKind, ErrorSpec, IOSpec, NodeKind+from pipelex.graph.graphspec import MAX_STACK_LENGTH, EdgeKind, IOSpec, NodeKindfrom pipelex.system.execution_chain import ExecutionAttemptfrom pipelex.system.job_metadata import JobCategory, JobMetadata, RunMetadata, UnitJobIdfrom pipelex.system.pipe_run_mode import PipeRunMode@@ -72,12 +75,11 @@ class _Shared:)@staticmethod- def make_error_spec() -> ErrorSpec:- return ErrorSpec(- error_type="LLMError",- message="Model returned an error",- stack="Traceback (most recent call last):\n File ...",- caller_facing=True,+ def make_error_problem() -> PipelexProblem:+ return make_problem(+ code=CoreCode.PROVIDER_UNAVAILABLE,+ view=ProblemView.CALLER,+ location=make_location(pipe="gen_summary", path=["records", "gen_summary"]),)@staticmethod@@ -143,7 +145,8 @@ class TestTraceEvents:"pipe_ref": "records.gen_summary","pipe_type": "PipeLLM","ended_at": _Shared.TIMESTAMP,- "error": _Shared.make_error_spec(),+ "error": _Shared.make_error_problem(),+ "error_stack": "Traceback (most recent call last):\n File ...",},),(@@ -374,12 +377,13 @@ class TestTraceEvents:assert restored_io.multiplicity is Trueassert restored_io.extra == {"custom_field": "custom_value"}- def test_error_spec_survives_round_trip_within_event(self) -> None:- """ErrorSpec fields are preserved through event serialization."""- error = ErrorSpec(- error_type="ValidationError",- message="Field 'name' is required",- stack="long stack trace here...",+ def test_problem_survives_round_trip_within_event(self) -> None:+ """The problem and the stack are preserved through event serialization, with no member written as null."""+ error = make_problem(+ code=CoreCode.INPUT_MISSING,+ view=ProblemView.CALLER,+ params={"input": "name"},+ location=make_location(pipe="test_pipe", path=["test_pipe"]),)event = PipeEndErrorEvent(pipe_code="test_pipe",@@ -389,14 +393,39 @@ class TestTraceEvents:node_id=_Shared.NODE_ID,ended_at=_Shared.TIMESTAMP,error=error,+ error_stack="long stack trace here...",)json_str = event.model_dump_json()restored = PipeEndErrorEvent.model_validate_json(json_str)- assert restored.error.error_type == "ValidationError"- assert restored.error.message == "Field 'name' is required"- assert restored.error.stack == "long stack trace here..."+ assert restored.error == error+ assert restored.error.code == CoreCode.INPUT_MISSING+ assert restored.error.detail == "The request does not give the input 'name', which the method requires."+ assert restored.error.location is not None+ assert restored.error.location.as_wire() == {"pipe": "test_pipe", "path": ["test_pipe"]}+ assert restored.error_stack == "long stack trace here..."+ # The event writes its problem as the wire does, with no member written as null.+ assert json.loads(json_str)["error"] == error.to_wire()++ def test_a_failed_pipe_event_caps_its_stack_as_the_graph_does(self) -> None:+ """An unbounded stack trace never reaches a trace subscriber: the event caps it at the node's limit."""+ error = make_problem(code=CoreCode.RUNTIME_UNEXPECTED, view=ProblemView.CALLER)+ long_stack = "Traceback (most recent call last):\n" + " frame\n" * MAX_STACK_LENGTH+ event = PipeEndErrorEvent(+ pipe_code="test_pipe",+ pipe_ref=None,+ pipe_type="PipeFunc",+ **_Shared.make_base_fields(),+ node_id=_Shared.NODE_ID,+ ended_at=_Shared.TIMESTAMP,+ error=error,+ error_stack=long_stack,+ )++ assert event.error_stack is not None+ assert len(event.error_stack) == MAX_STACK_LENGTH+ assert event.error_stack == long_stack[: MAX_STACK_LENGTH - 3] + "..."def test_usage_report_with_llm_tokens_round_trip(self) -> None:"""UsageReportEvent with LLMTokensUsage survives round-trip via AnyTokensUsage discriminator."""