lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

commit b6f927c4d484ed2f8afcf171a83f2c8f967fb4d4
parent 12ebab67c3c5927bb19ca204706fe60fd9d97283
Author: triesap <tyson@radroots.org>
Date:   Sat, 17 Oct 2026 08:05:13 +0000

execution: add bounded typed error and admission reports

- Keep proposed, confirmed and uncertain admission distinct by operation ID.
- Validate retained reconciliation and refuse conflicting same-operation retry.
- Expose fixed redacted diagnostics without backend messages or allocations.
- Verify native and WASM compilation, context cases, coverage and native provenance.

Diffstat:
MCargo.lock | 7+++++++
MCargo.toml | 2++
Mcontracts/architecture/deviations.toml | 26++++++++++++++++++++++++++
Mcontracts/coverage.toml | 1+
Mcontracts/crates/catalog.v2.toml | 20+++++++++++++++++++-
Mcontracts/crates/generated/package_groups.v1.toml | 10+++++-----
Mcontracts/crates/generated/platform_inventory.v1.toml | 4++--
Mcontracts/crates/generated/release_inventory.v2.toml | 4++--
Mcontracts/releases/publish_policy.toml | 1+
Acrates/execution/Cargo.toml | 18++++++++++++++++++
Acrates/execution/LICENSE-APACHE | 201+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/execution/LICENSE-MIT | 21+++++++++++++++++++++
Acrates/execution/README.md | 57+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/execution/src/diagnostic.rs | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/execution/src/error.rs | 270+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/execution/src/lib.rs | 13+++++++++++++
Acrates/execution/tests/error.rs | 226+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
17 files changed, 949 insertions(+), 10 deletions(-)

diff --git a/Cargo.lock b/Cargo.lock @@ -3151,6 +3151,13 @@ dependencies = [ ] [[package]] +name = "radroots_execution" +version = "0.1.0-alpha" +dependencies = [ + "radroots_domain", +] + +[[package]] name = "radroots_geonames" version = "0.1.0-alpha" dependencies = [ diff --git a/Cargo.toml b/Cargo.toml @@ -2,6 +2,7 @@ members = [ "crates/core", "crates/domain", + "crates/execution", "crates/event", "crates/event_codec", "crates/blossom", @@ -113,6 +114,7 @@ radroots = { path = "crates/radroots", version = "=0.1.0-alpha" } radroots_core_bindings = { path = "crates/core_bindings", version = "=0.1.0-alpha" } radroots_core = { package = "radroots_core", path = "crates/core", version = "=0.1.0-alpha", default-features = false } radroots_domain = { path = "crates/domain", version = "=0.1.0-alpha", default-features = false } +radroots_execution = { path = "crates/execution", version = "=0.1.0-alpha", default-features = false } radroots_event = { package = "radroots_event", path = "crates/event", version = "=0.1.0-alpha", default-features = false } radroots_event_codec = { package = "radroots_event_codec", path = "crates/event_codec", version = "=0.1.0-alpha", default-features = false } radroots_event_bindings = { path = "crates/event_bindings", version = "=0.1.0-alpha" } diff --git a/contracts/architecture/deviations.toml b/contracts/architecture/deviations.toml @@ -2,6 +2,32 @@ schema_version = 1 architecture_id = "radroots.crates.release.v1" [[deviation]] +id = "RCRV1-DEV-048" +date = "2026-10-17" +status = "closed" +approval = "The user authorizes the complete shared SDK refactor, necessary breaking changes, verified source checkpoints and master integration." +affected_steps = ["040", "060", "100", "110", "120", "130"] +spec_anchors = ["contracts/crates/release_v1/radroots_crates_release_v1.toml#release_policy"] +source_evidence = [ + "The approved shared SDK target assigns execution to crates/execution and requires typed stable errors, bounded redacted details, four explicit retry classes and an operation identity that does not imply durable admission.", + "The existing SDK errors describe the current composed client and transport. The successor execution error boundary must distinguish an unadmitted proposed operation from a retained operation and must not retain arbitrary backend messages or private payloads.", +] +replacement_action = "Independently implement the allocation-free typed execution error boundary in an active unpublished native package. Use the existing validated domain operation ID, fixed diagnostic enums and checked operation/retry combinations. Preserve current executable sources and every retained test until actual facade/caller replacement; introduce no compatibility alias or claimed command implementation." +verification = [ + "Validate this prospective record before implementation and bind the exact original source, package/catalog/lock and compiler inputs. Stage the complete new package before deriving its native introduction-tree digest and generating catalog projections.", + "Prove proposed IDs remain explicitly unadmitted, unknown signing/commit states require retained identity, safe-same-operation retry requires retained state, and owned error output contains only bounded fixed diagnostics. Check canonical code uniqueness, error-source redaction, malformed API use and independent operation IDs.", + "Run focused native/no-default and actual WASM checks and tests, strict lint/docs, the unchanged measured coverage gate and owning catalog/architecture/contract/preflight checks. Preserve all prior report scope and keep actual execution, bindings, caller adoption and final acceptance open.", +] +unresolved_risk = "This typed value boundary does not prove durable admission, signing, storage effects or the public facade. Only the actual executor may report retained state after its durable store confirms it. Full known-kind native/browser operations and final qualification remain required." +normative_architecture_change = false +adr_required = false +closure_evidence = [ + "The execution package independently implements allocation-free typed errors, fixed diagnostic enums and four canonical retry strings. Proposed IDs remain NotAdmitted. An uncertain initial admission preserves its original ID as Unknown; it does not claim confirmed storage. Signing/delivery observations require confirmed preparation, and unknown outcomes require exact-operation or manual reconciliation. Conflicting command inputs cannot resume an existing different command.", + "Seven focused native cases pass under default and no-default commands, plus three documentation cases including two compile failures. Strict lint/docs, actual wasm32-unknown-unknown compilation and owning catalog/architecture/contracts pass. The unchanged measured gate records 84/84 executable lines and 6/6 recorded branches covered, with all functions and regions covered.", + "All 601 original complete dependency records and 52 earlier catalog entries remain unchanged. The new package is active and unpublished with staged native introduction provenance; the nineteen-package public release closure is preserved. These are value-boundary checks, not actual durable admission, signer/store faults, facade operations, binding calls, consumer adoption or final platform qualification.", +] + +[[deviation]] id = "RCRV1-DEV-047" date = "2026-10-17" status = "closed" diff --git a/contracts/coverage.toml b/contracts/coverage.toml @@ -57,6 +57,7 @@ crates = [ "radroots_core", "radroots_core_bindings", "radroots_domain", + "radroots_execution", "radroots_event", "radroots_event_bindings", "radroots_event_codec", diff --git a/contracts/crates/catalog.v2.toml b/contracts/crates/catalog.v2.toml @@ -7,7 +7,7 @@ rust_version = "1.99.0" edition = "2024" resolver = "3" public_package_count = 19 -package_count = 52 +package_count = 53 digest_algorithm = "sha256-raw-bytes-v1" source_tree_digest_algorithm = "sha256-git-ls-tree-r-v1" native_introduction_tree_digest_algorithm = "sha256-git-tree-records-z-v1" @@ -79,6 +79,24 @@ compatibility = ["package_private"] replaces = [] [[package]] +name = "radroots_execution" +path = "crates/execution" +state = "active" +tier = "orchestration" +visibility = "private_boundary" +publish = false +version = "0.1.0-alpha" +license = "MIT OR Apache-2.0" +platforms = ["any"] +groups = ["coverage_required", "preview"] +owners = ["execution"] +permitted_dependency_tiers = ["domain"] +provenance_kind = "native" +introduction_tree_sha256 = "c3513293d70957c4ee2c93a722549573a8dc1bc9e893873a4f3e2dfdaa2881da" +compatibility = ["package_private"] +replaces = [] + +[[package]] name = "radroots_identity" path = "crates/identity" state = "active" diff --git a/contracts/crates/generated/package_groups.v1.toml b/contracts/crates/generated/package_groups.v1.toml @@ -1,5 +1,5 @@ schema = "radroots.workspace.package-groups.v1" -catalog_sha256 = "dd9492323450398c9c7eb2e9880cdd595a950bde24d03060c3c957f7530cad61" +catalog_sha256 = "1e679431ad70a024affc52e6c71151459aca41707429dd8015d014d27e5f40b6" [[group]] id = "boundaries" @@ -9,8 +9,8 @@ reserved_packages = [] [[group]] id = "coverage_required" -packages = ["radroots", "radroots_blossom", "radroots_core", "radroots_core_bindings", "radroots_domain", "radroots_event", "radroots_event_bindings", "radroots_event_codec", "radroots_event_codec_wasm", "radroots_geonames", "radroots_identity", "radroots_identity_bindings", "radroots_mesh", "radroots_mesh_agent_client", "radroots_mesh_agent_proto", "radroots_nostr", "radroots_nostr_connect", "radroots_nostrdb", "radroots_protocol", "radroots_replica_schema", "radroots_replica_schema_bindings", "radroots_replica_store", "radroots_replica_store_wasm", "radroots_replica_sync", "radroots_replica_sync_wasm", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_sdk", "radroots_sdk_ffi", "radroots_sdk_sql_wasm_runtime", "radroots_secrets", "radroots_service_host", "radroots_service_sqlite", "radroots_signing", "radroots_sql_core", "radroots_storage", "radroots_storage_sqlite", "radroots_sync", "radroots_test_fixtures", "radroots_trade", "radroots_trade_bindings", "radroots_transport", "radroots_transport_nostr", "radroots_transport_reticulum", "xtask"] -active_packages = ["radroots", "radroots_blossom", "radroots_core", "radroots_core_bindings", "radroots_domain", "radroots_event", "radroots_event_bindings", "radroots_event_codec", "radroots_event_codec_wasm", "radroots_geonames", "radroots_identity", "radroots_identity_bindings", "radroots_mesh", "radroots_mesh_agent_client", "radroots_mesh_agent_proto", "radroots_nostr", "radroots_nostr_connect", "radroots_nostrdb", "radroots_protocol", "radroots_replica_schema", "radroots_replica_schema_bindings", "radroots_replica_store", "radroots_replica_store_wasm", "radroots_replica_sync", "radroots_replica_sync_wasm", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_sdk", "radroots_sdk_ffi", "radroots_sdk_sql_wasm_runtime", "radroots_secrets", "radroots_service_host", "radroots_service_sqlite", "radroots_signing", "radroots_sql_core", "radroots_storage", "radroots_storage_sqlite", "radroots_sync", "radroots_test_fixtures", "radroots_trade", "radroots_trade_bindings", "radroots_transport", "radroots_transport_nostr", "radroots_transport_reticulum", "xtask"] +packages = ["radroots", "radroots_blossom", "radroots_core", "radroots_core_bindings", "radroots_domain", "radroots_event", "radroots_event_bindings", "radroots_event_codec", "radroots_event_codec_wasm", "radroots_execution", "radroots_geonames", "radroots_identity", "radroots_identity_bindings", "radroots_mesh", "radroots_mesh_agent_client", "radroots_mesh_agent_proto", "radroots_nostr", "radroots_nostr_connect", "radroots_nostrdb", "radroots_protocol", "radroots_replica_schema", "radroots_replica_schema_bindings", "radroots_replica_store", "radroots_replica_store_wasm", "radroots_replica_sync", "radroots_replica_sync_wasm", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_sdk", "radroots_sdk_ffi", "radroots_sdk_sql_wasm_runtime", "radroots_secrets", "radroots_service_host", "radroots_service_sqlite", "radroots_signing", "radroots_sql_core", "radroots_storage", "radroots_storage_sqlite", "radroots_sync", "radroots_test_fixtures", "radroots_trade", "radroots_trade_bindings", "radroots_transport", "radroots_transport_nostr", "radroots_transport_reticulum", "xtask"] +active_packages = ["radroots", "radroots_blossom", "radroots_core", "radroots_core_bindings", "radroots_domain", "radroots_event", "radroots_event_bindings", "radroots_event_codec", "radroots_event_codec_wasm", "radroots_execution", "radroots_geonames", "radroots_identity", "radroots_identity_bindings", "radroots_mesh", "radroots_mesh_agent_client", "radroots_mesh_agent_proto", "radroots_nostr", "radroots_nostr_connect", "radroots_nostrdb", "radroots_protocol", "radroots_replica_schema", "radroots_replica_schema_bindings", "radroots_replica_store", "radroots_replica_store_wasm", "radroots_replica_sync", "radroots_replica_sync_wasm", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_sdk", "radroots_sdk_ffi", "radroots_sdk_sql_wasm_runtime", "radroots_secrets", "radroots_service_host", "radroots_service_sqlite", "radroots_signing", "radroots_sql_core", "radroots_storage", "radroots_storage_sqlite", "radroots_sync", "radroots_test_fixtures", "radroots_trade", "radroots_trade_bindings", "radroots_transport", "radroots_transport_nostr", "radroots_transport_reticulum", "xtask"] reserved_packages = [] [[group]] @@ -21,8 +21,8 @@ reserved_packages = [] [[group]] id = "preview" -packages = ["radroots_domain", "radroots_mesh", "radroots_mesh_agent_client", "radroots_mesh_agent_proto", "radroots_nostrdb", "radroots_replica_schema", "radroots_replica_store", "radroots_replica_sync", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_service_host", "radroots_service_sqlite", "radroots_simplex_agent_proto", "radroots_simplex_app_store", "radroots_simplex_chat_proto", "radroots_simplex_smp_crypto", "radroots_simplex_smp_proto", "radroots_simplex_smp_transport", "radroots_sql_core", "radroots_test_fixtures", "radroots_transport_reticulum"] -active_packages = ["radroots_domain", "radroots_mesh", "radroots_mesh_agent_client", "radroots_mesh_agent_proto", "radroots_nostrdb", "radroots_replica_schema", "radroots_replica_store", "radroots_replica_sync", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_service_host", "radroots_service_sqlite", "radroots_simplex_agent_proto", "radroots_simplex_app_store", "radroots_simplex_chat_proto", "radroots_simplex_smp_crypto", "radroots_simplex_smp_proto", "radroots_simplex_smp_transport", "radroots_sql_core", "radroots_test_fixtures", "radroots_transport_reticulum"] +packages = ["radroots_domain", "radroots_execution", "radroots_mesh", "radroots_mesh_agent_client", "radroots_mesh_agent_proto", "radroots_nostrdb", "radroots_replica_schema", "radroots_replica_store", "radroots_replica_sync", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_service_host", "radroots_service_sqlite", "radroots_simplex_agent_proto", "radroots_simplex_app_store", "radroots_simplex_chat_proto", "radroots_simplex_smp_crypto", "radroots_simplex_smp_proto", "radroots_simplex_smp_transport", "radroots_sql_core", "radroots_test_fixtures", "radroots_transport_reticulum"] +active_packages = ["radroots_domain", "radroots_execution", "radroots_mesh", "radroots_mesh_agent_client", "radroots_mesh_agent_proto", "radroots_nostrdb", "radroots_replica_schema", "radroots_replica_store", "radroots_replica_sync", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_service_host", "radroots_service_sqlite", "radroots_simplex_agent_proto", "radroots_simplex_app_store", "radroots_simplex_chat_proto", "radroots_simplex_smp_crypto", "radroots_simplex_smp_proto", "radroots_simplex_smp_transport", "radroots_sql_core", "radroots_test_fixtures", "radroots_transport_reticulum"] reserved_packages = [] [[group]] diff --git a/contracts/crates/generated/platform_inventory.v1.toml b/contracts/crates/generated/platform_inventory.v1.toml @@ -1,9 +1,9 @@ schema = "radroots.workspace.platform-inventory.v1" -catalog_sha256 = "dd9492323450398c9c7eb2e9880cdd595a950bde24d03060c3c957f7530cad61" +catalog_sha256 = "1e679431ad70a024affc52e6c71151459aca41707429dd8015d014d27e5f40b6" [[platform]] id = "any" -packages = ["radroots", "radroots_blossom", "radroots_core", "radroots_domain", "radroots_event", "radroots_event_codec", "radroots_identity", "radroots_mesh_agent_proto", "radroots_nostr", "radroots_nostr_connect", "radroots_protocol", "radroots_replica_schema", "radroots_sdk", "radroots_signing", "radroots_simplex_agent_proto", "radroots_simplex_chat_proto", "radroots_simplex_smp_crypto", "radroots_simplex_smp_proto", "radroots_test_fixtures", "radroots_trade", "radroots_transport"] +packages = ["radroots", "radroots_blossom", "radroots_core", "radroots_domain", "radroots_event", "radroots_event_codec", "radroots_execution", "radroots_identity", "radroots_mesh_agent_proto", "radroots_nostr", "radroots_nostr_connect", "radroots_protocol", "radroots_replica_schema", "radroots_sdk", "radroots_signing", "radroots_simplex_agent_proto", "radroots_simplex_chat_proto", "radroots_simplex_smp_crypto", "radroots_simplex_smp_proto", "radroots_test_fixtures", "radroots_trade", "radroots_transport"] [[platform]] id = "native" diff --git a/contracts/crates/generated/release_inventory.v2.toml b/contracts/crates/generated/release_inventory.v2.toml @@ -1,7 +1,7 @@ schema = "radroots.workspace.release-inventory.v2" -catalog_sha256 = "dd9492323450398c9c7eb2e9880cdd595a950bde24d03060c3c957f7530cad61" +catalog_sha256 = "1e679431ad70a024affc52e6c71151459aca41707429dd8015d014d27e5f40b6" architecture = "radroots.crates.release.v2" version = "0.1.0-alpha" public_packages = ["radroots", "radroots_blossom", "radroots_core", "radroots_event", "radroots_event_codec", "radroots_geonames", "radroots_identity", "radroots_nostr", "radroots_nostr_connect", "radroots_protocol", "radroots_sdk", "radroots_secrets", "radroots_signing", "radroots_storage", "radroots_storage_sqlite", "radroots_sync", "radroots_trade", "radroots_transport", "radroots_transport_nostr"] -private_packages = ["radroots_core_bindings", "radroots_domain", "radroots_event_bindings", "radroots_event_codec_wasm", "radroots_identity_bindings", "radroots_mesh", "radroots_mesh_agent_client", "radroots_mesh_agent_proto", "radroots_nostrdb", "radroots_replica_schema", "radroots_replica_schema_bindings", "radroots_replica_store", "radroots_replica_store_wasm", "radroots_replica_sync", "radroots_replica_sync_wasm", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_sdk_ffi", "radroots_sdk_sql_wasm_runtime", "radroots_service_host", "radroots_service_sqlite", "radroots_simplex_agent_proto", "radroots_simplex_app_store", "radroots_simplex_chat_proto", "radroots_simplex_smp_crypto", "radroots_simplex_smp_proto", "radroots_simplex_smp_transport", "radroots_sql_core", "radroots_test_fixtures", "radroots_trade_bindings", "radroots_transport_reticulum", "xtask"] +private_packages = ["radroots_core_bindings", "radroots_domain", "radroots_event_bindings", "radroots_event_codec_wasm", "radroots_execution", "radroots_identity_bindings", "radroots_mesh", "radroots_mesh_agent_client", "radroots_mesh_agent_proto", "radroots_nostrdb", "radroots_replica_schema", "radroots_replica_schema_bindings", "radroots_replica_store", "radroots_replica_store_wasm", "radroots_replica_sync", "radroots_replica_sync_wasm", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_sdk_ffi", "radroots_sdk_sql_wasm_runtime", "radroots_service_host", "radroots_service_sqlite", "radroots_simplex_agent_proto", "radroots_simplex_app_store", "radroots_simplex_chat_proto", "radroots_simplex_smp_crypto", "radroots_simplex_smp_proto", "radroots_simplex_smp_transport", "radroots_sql_core", "radroots_test_fixtures", "radroots_trade_bindings", "radroots_transport_reticulum", "xtask"] reserved_packages = [] diff --git a/contracts/releases/publish_policy.toml b/contracts/releases/publish_policy.toml @@ -53,6 +53,7 @@ external_packages = [] [workspace_classification] private = [ "radroots_domain", + "radroots_execution", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", diff --git a/crates/execution/Cargo.toml b/crates/execution/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "radroots_execution" +publish = false +version = "0.1.0-alpha" +edition.workspace = true +authors.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +homepage.workspace = true +description = "Typed Radroots command execution and recovery boundaries" +readme = "README.md" + +[dependencies] +radroots_domain = { workspace = true, default-features = false } + +[lints] +workspace = true diff --git a/crates/execution/LICENSE-APACHE b/crates/execution/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2025 Tyson Lupul + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/crates/execution/LICENSE-MIT b/crates/execution/LICENSE-MIT @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2025 Tyson Lupul + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/crates/execution/README.md b/crates/execution/README.md @@ -0,0 +1,57 @@ +# Radroots execution + +Typed command execution and recovery boundaries. The current implementation +contains allocation-free errors with canonical codes, fixed diagnostic enums, +four explicit retry classes and a validated operation/admission relationship. +The package supports native Rust and `no_std` targets without a runtime. + +A proposed operation ID is not durable admission. Unknown signing or commit +outcomes keep the original identity and require exact-operation continuation +or manual reconciliation. Uncertain initial admission remains explicitly +`Admission::Unknown`; it is neither confirmed admission nor known failure. +Signing and delivery results require confirmed durable preparation. +Same-operation continuation means +resuming or querying retained state; it never authorizes fresh preparation or +blind signing. An executor may construct a retained report only after its +actual durable store confirms admission. This reporting value grants no +authority and performs no transaction. + +```rust +use radroots_domain::OperationId; +use radroots_execution::{Admission, Code, Error, OperationContext, RetryClass}; + +let operation = OperationId::from_bytes([7; 32]); +let error = Error::new( + Code::InvalidInput, + OperationContext::proposed(Some(operation)), + RetryClass::Never, + None, +)?; +assert_eq!(error.context().operation_id(), Some(operation)); +assert_eq!(error.context().admission(), Admission::NotAdmitted); +# Ok::<(), radroots_execution::InvalidErrorContext>(()) +``` + +Details accept fixed field/reason categories, never private payloads, paths or +backend prose. Display contains only a canonical code and fixed message; +errors have no retained underlying cause. Bindings must preserve the typed +operation ID and explicit admission/retry disposition. + +```compile_fail +use radroots_execution::{Detail, Field}; + +let _ = Detail::new(Field::Signer, String::from("private signer response")); +``` + +```compile_fail +use radroots_execution::{Code, Error, RetryClass}; + +let _ = Error { + code: Code::CommitUnknown, + retry: RetryClass::Never, +}; +``` + +The package is unpublished while the shared facade is migrated. It does not +yet implement command admission, durable operations, signing, outbox workers, +inventory authority, public listing/private chat execution or bindings. diff --git a/crates/execution/src/diagnostic.rs b/crates/execution/src/diagnostic.rs @@ -0,0 +1,78 @@ +use core::fmt; + +macro_rules! diagnostic { + ($name:ident, $description:literal, {$($variant:ident => $value:literal),+ $(,)?}) => { + #[doc = $description] + #[derive(Clone, Copy, Debug, Eq, PartialEq)] + #[non_exhaustive] + pub enum $name { + $(#[doc = $value] $variant,)+ + } + + impl $name { + /// Every supported diagnostic value. + pub const ALL: &'static [Self] = &[$(Self::$variant),+]; + + /// Returns the fixed, input-free diagnostic string. + pub const fn as_str(self) -> &'static str { + match self { $(Self::$variant => $value,)+ } + } + } + + impl fmt::Display for $name { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(self.as_str()) + } + } + }; +} + +diagnostic!(Field, "A diagnostic field category, never a caller-supplied path.", { + Input => "input", + Currency => "currency", + Unit => "unit", + Source => "source", + History => "history", + Approval => "approval", + Authority => "authority", + Stock => "stock", + Operation => "operation", + Storage => "storage", + Signer => "signer", + Delivery => "delivery", + Retention => "retention", +}); + +diagnostic!(Reason, "An input-free diagnostic reason.", { + Missing => "missing", + OutOfRange => "out_of_range", + InvalidEncoding => "invalid_encoding", + Unsupported => "unsupported", + Conflict => "conflict", + Unavailable => "unavailable", + Unknown => "unknown", +}); + +/// Fixed-size redacted details with no arbitrary message, key or payload. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct Detail { + field: Field, + reason: Reason, +} + +impl Detail { + /// Constructs one bounded diagnostic from supported categories. + pub const fn new(field: Field, reason: Reason) -> Self { + Self { field, reason } + } + + /// Returns the field category. + pub const fn field(self) -> Field { + self.field + } + + /// Returns the diagnostic reason. + pub const fn reason(self) -> Reason { + self.reason + } +} diff --git a/crates/execution/src/error.rs b/crates/execution/src/error.rs @@ -0,0 +1,270 @@ +use core::fmt; +use radroots_domain::OperationId; + +use crate::Detail; + +macro_rules! codes { + ($($variant:ident => ($code:literal, $message:literal, $retained:literal)),+ $(,)?) => { + /// A stable execution failure category. + #[derive(Clone, Copy, Debug, Eq, PartialEq)] + #[non_exhaustive] + pub enum Code { + $(#[doc = $message] $variant,)+ + } + + impl Code { + /// Every supported execution failure category. + pub const ALL: &'static [Self] = &[$(Self::$variant),+]; + + /// Returns the stable machine code. + pub const fn as_str(self) -> &'static str { + match self { $(Self::$variant => $code,)+ } + } + + /// Returns an input-free bounded human message. + pub const fn message(self) -> &'static str { + match self { $(Self::$variant => $message,)+ } + } + + const fn requires_reconciliation(self) -> bool { + match self { $(Self::$variant => $retained,)+ } + } + } + }; +} + +codes! { + InvalidInput => ("invalid_input", "Command input is invalid", false), + Unauthenticated => ("unauthenticated", "Authentication is required", false), + Unauthorized => ("unauthorized", "The action is not authorized", false), + GrantRevoked => ("grant_revoked", "The authorizing grant was revoked", false), + MissingAuthority => ("missing_authority", "Selected execution authority is missing", false), + StaleState => ("stale_state", "Expected state must be refreshed and approved", false), + MissingSource => ("missing_source", "Required source evidence is missing", false), + MissingHistory => ("missing_history", "Required authenticated history is missing", false), + UnsupportedVersion => ("unsupported_version", "The version is unsupported", false), + UnsupportedProfile => ("unsupported_profile", "The profile is unsupported", false), + CapabilityUnavailable => ("capability_unavailable", "A required capability is unavailable", false), + IdempotencyConflict => ("idempotency_conflict", "The operation identity binds different command inputs", false), + InsufficientStock => ("insufficient_stock", "Available stock does not satisfy the command", false), + Deficit => ("deficit", "Stock reconciliation is required", false), + AuthorityConflict => ("authority_conflict", "Execution authority is conflicted", false), + RecordFork => ("record_fork", "Authenticated records contain a causal fork", false), + StorageFailure => ("storage_failure", "Storage reported a known failure", false), + CommitUnknown => ("commit_unknown", "The retained transaction outcome requires reconciliation", true), + RecoveryRequired => ("recovery_required", "Explicit recovery is required", false), + SignerRefused => ("signer_refused", "The signer refused the request", false), + SignerUnavailable => ("signer_unavailable", "The signer is unavailable", false), + SignerTampering => ("signer_tampering", "The signer result does not match the retained intent", true), + IdentityChanged => ("identity_changed", "The signer identity changed", false), + SigningPending => ("signing_pending", "The retained signing request is pending", true), + SigningUnknown => ("signing_unknown", "The retained signing outcome requires reconciliation", true), + RetentionExhausted => ("retention_exhausted", "Protected retention capacity is exhausted", false), + DeliveryPending => ("delivery_pending", "The retained delivery requires continuation", true), +} + +/// How an observer may continue after the reported failure. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum RetryClass { + /// Do not retry this command. + Never, + /// Resume or reconcile the exact retained operation, without re-preparing it. + SafeSameOperation, + /// Refresh state and obtain any required new approval before a new command. + AfterStateRefresh, + /// Require explicit reconciliation by the operator. + ManualReconciliation, +} + +impl RetryClass { + /// Returns the canonical machine retry class. + pub const fn as_str(self) -> &'static str { + match self { + Self::Never => "never", + Self::SafeSameOperation => "safe_same_operation", + Self::AfterStateRefresh => "after_state_refresh", + Self::ManualReconciliation => "manual_reconciliation", + } + } +} + +/// What is known about durable command admission, independently of a later +/// signing, installation or delivery result. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum Admission { + /// This command has not been durably admitted. + NotAdmitted, + /// The executor confirmed durable admission of the original command. + Confirmed, + /// The initial admission commit is uncertain and must be queried by ID. + Unknown, +} + +/// An execution report's operation identity and durable-admission disposition. +/// +/// This value is neither authorization nor evidence that a transaction ran. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct OperationContext { + operation_id: Option<OperationId>, + admission: Admission, +} + +impl OperationContext { + /// Reports a failure before durable admission, optionally retaining the + /// caller's proposed operation ID. + pub const fn proposed(operation_id: Option<OperationId>) -> Self { + Self { + operation_id, + admission: Admission::NotAdmitted, + } + } + + /// Reports the original identity after the executor has confirmed durable + /// admission. Constructing this report does not perform admission. + pub const fn retained(operation_id: OperationId) -> Self { + Self { + operation_id: Some(operation_id), + admission: Admission::Confirmed, + } + } + + /// Reports uncertain initial admission. The original ID is the query + /// anchor; neither successful admission nor a known failed commit is claimed. + pub const fn admission_unknown(operation_id: OperationId) -> Self { + Self { + operation_id: Some(operation_id), + admission: Admission::Unknown, + } + } + + /// Returns the proposed or retained operation identity. + pub const fn operation_id(self) -> Option<OperationId> { + self.operation_id + } + + /// Returns the explicit admission disposition. + pub const fn admission(self) -> Admission { + self.admission + } +} + +/// An internally inconsistent execution error report. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum InvalidErrorContext { + /// Signing and delivery require confirmed durable preparation. + ConfirmedAdmissionRequired, + /// Commit uncertainty requires an original retained or uncertain identity. + OperationIdentityRequired, + /// Same-operation continuation requires retained or uncertain admission. + RetainedRetryRequired, + /// An uncertain or pending outcome must retain reconciliation semantics. + ReconciliationRequired, + /// Conflicting inputs cannot resume the operation that bound other inputs. + ConflictingRetry, +} + +impl fmt::Display for InvalidErrorContext { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(match self { + Self::ConfirmedAdmissionRequired => "outcome requires confirmed admission", + Self::OperationIdentityRequired => "outcome requires an original operation identity", + Self::RetainedRetryRequired => "retry requires retained or uncertain admission", + Self::ReconciliationRequired => "outcome requires retained reconciliation", + Self::ConflictingRetry => "conflicting inputs cannot resume the retained command", + }) + } +} + +impl core::error::Error for InvalidErrorContext {} + +/// An allocation-free error with typed code, bounded redacted details and the +/// exact reported operation identity. It never owns backend messages or causes. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct Error { + code: Code, + context: OperationContext, + retry: RetryClass, + detail: Option<Detail>, +} + +impl Error { + /// Validates the relationship between the outcome, durable identity and + /// retry policy. Safe same-operation continuation never means blind reissue. + pub const fn new( + code: Code, + context: OperationContext, + retry: RetryClass, + detail: Option<Detail>, + ) -> core::result::Result<Self, InvalidErrorContext> { + if matches!( + code, + Code::SigningPending + | Code::SigningUnknown + | Code::DeliveryPending + | Code::SignerTampering + ) && !matches!(context.admission, Admission::Confirmed) + { + return Err(InvalidErrorContext::ConfirmedAdmissionRequired); + } + if matches!(code, Code::CommitUnknown) + && matches!(context.admission, Admission::NotAdmitted) + { + return Err(InvalidErrorContext::OperationIdentityRequired); + } + if matches!(retry, RetryClass::SafeSameOperation) + && matches!(context.admission, Admission::NotAdmitted) + { + return Err(InvalidErrorContext::RetainedRetryRequired); + } + if code.requires_reconciliation() + && !matches!( + retry, + RetryClass::SafeSameOperation | RetryClass::ManualReconciliation + ) + { + return Err(InvalidErrorContext::ReconciliationRequired); + } + if matches!(code, Code::IdempotencyConflict) + && matches!(retry, RetryClass::SafeSameOperation) + { + return Err(InvalidErrorContext::ConflictingRetry); + } + Ok(Self { + code, + context, + retry, + detail, + }) + } + + /// Returns the stable error category. + pub const fn code(self) -> Code { + self.code + } + + /// Returns the operation identity and admission disposition. + pub const fn context(self) -> OperationContext { + self.context + } + + /// Returns the required continuation class. + pub const fn retry(self) -> RetryClass { + self.retry + } + + /// Returns the optional fixed diagnostic. + pub const fn detail(self) -> Option<Detail> { + self.detail + } +} + +impl fmt::Display for Error { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(formatter, "{}: {}", self.code.as_str(), self.code.message()) + } +} + +impl core::error::Error for Error {} diff --git a/crates/execution/src/lib.rs b/crates/execution/src/lib.rs @@ -0,0 +1,13 @@ +#![no_std] +#![doc = include_str!("../README.md")] +#![forbid(unsafe_code)] +#![warn(missing_docs)] + +mod diagnostic; +mod error; + +pub use diagnostic::{Detail, Field, Reason}; +pub use error::{Admission, Code, Error, InvalidErrorContext, OperationContext, RetryClass}; + +/// A result owned by the execution boundary. +pub type Result<T> = core::result::Result<T, Error>; diff --git a/crates/execution/tests/error.rs b/crates/execution/tests/error.rs @@ -0,0 +1,226 @@ +use std::{collections::BTreeSet, error::Error as _, mem::size_of}; + +use radroots_domain::OperationId; +use radroots_execution::{ + Admission, Code, Detail, Error, Field, InvalidErrorContext, OperationContext, Reason, + RetryClass, +}; + +const FIRST: OperationId = OperationId::from_bytes([7; 32]); +const SECOND: OperationId = OperationId::from_bytes([8; 32]); + +#[test] +fn proposed_identity_never_claims_durable_admission() { + for id in [None, Some(FIRST), Some(SECOND)] { + let error = Error::new( + Code::InvalidInput, + OperationContext::proposed(id), + RetryClass::Never, + Some(Detail::new(Field::Currency, Reason::Unsupported)), + ) + .unwrap(); + assert_eq!(error.context().operation_id(), id); + assert_eq!(error.context().admission(), Admission::NotAdmitted); + assert_eq!(error.code(), Code::InvalidInput); + assert_eq!(error.retry(), RetryClass::Never); + let detail = error.detail().unwrap(); + assert_eq!(detail.field(), Field::Currency); + assert_eq!(detail.reason(), Reason::Unsupported); + assert_eq!(error.to_string(), "invalid_input: Command input is invalid"); + assert!(error.source().is_none()); + } +} + +#[test] +fn uncertain_initial_commit_preserves_id_without_claiming_admission() { + for id in [FIRST, SECOND] { + for retry in [ + RetryClass::SafeSameOperation, + RetryClass::ManualReconciliation, + ] { + let error = Error::new( + Code::CommitUnknown, + OperationContext::admission_unknown(id), + retry, + None, + ) + .unwrap(); + assert_eq!(error.context().operation_id(), Some(id)); + assert_eq!(error.context().admission(), Admission::Unknown); + assert_eq!(error.retry(), retry); + assert_eq!(error.detail(), None); + } + } + assert_eq!( + Error::new( + Code::CommitUnknown, + OperationContext::proposed(Some(FIRST)), + RetryClass::ManualReconciliation, + None + ), + Err(InvalidErrorContext::OperationIdentityRequired) + ); +} + +#[test] +fn signing_delivery_and_tampering_cannot_precede_confirmed_preparation() { + for code in [ + Code::SigningPending, + Code::SigningUnknown, + Code::DeliveryPending, + Code::SignerTampering, + ] { + for context in [ + OperationContext::proposed(None), + OperationContext::proposed(Some(FIRST)), + OperationContext::admission_unknown(FIRST), + ] { + assert_eq!( + Error::new(code, context, RetryClass::ManualReconciliation, None), + Err(InvalidErrorContext::ConfirmedAdmissionRequired) + ); + } + for retry in [ + RetryClass::SafeSameOperation, + RetryClass::ManualReconciliation, + ] { + let error = Error::new(code, OperationContext::retained(FIRST), retry, None).unwrap(); + assert_eq!(error.context().admission(), Admission::Confirmed); + assert_eq!(error.context().operation_id(), Some(FIRST)); + } + } +} + +#[test] +fn uncertain_work_cannot_be_reprepared_using_fresh_state_or_forgotten() { + for code in [ + Code::CommitUnknown, + Code::SigningPending, + Code::SigningUnknown, + Code::DeliveryPending, + Code::SignerTampering, + ] { + for retry in [RetryClass::Never, RetryClass::AfterStateRefresh] { + assert_eq!( + Error::new(code, OperationContext::retained(FIRST), retry, None), + Err(InvalidErrorContext::ReconciliationRequired) + ); + } + } + for retry in [RetryClass::Never, RetryClass::AfterStateRefresh] { + assert_eq!( + Error::new( + Code::CommitUnknown, + OperationContext::admission_unknown(FIRST), + retry, + None + ), + Err(InvalidErrorContext::ReconciliationRequired) + ); + } +} + +#[test] +fn same_operation_retry_requires_an_original_retained_or_uncertain_identity() { + for context in [ + OperationContext::proposed(None), + OperationContext::proposed(Some(FIRST)), + ] { + assert_eq!( + Error::new( + Code::StorageFailure, + context, + RetryClass::SafeSameOperation, + None + ), + Err(InvalidErrorContext::RetainedRetryRequired) + ); + } + for context in [ + OperationContext::retained(FIRST), + OperationContext::admission_unknown(SECOND), + ] { + let error = Error::new( + Code::RecoveryRequired, + context, + RetryClass::SafeSameOperation, + None, + ) + .unwrap(); + assert_eq!(error.context(), context); + } + let conflict = Error::new( + Code::IdempotencyConflict, + OperationContext::retained(FIRST), + RetryClass::SafeSameOperation, + None, + ); + assert_eq!(conflict, Err(InvalidErrorContext::ConflictingRetry)); + let refresh = Error::new( + Code::StaleState, + OperationContext::proposed(Some(SECOND)), + RetryClass::AfterStateRefresh, + None, + ) + .unwrap(); + assert_eq!(refresh.context().admission(), Admission::NotAdmitted); + assert_eq!(refresh.context().operation_id(), Some(SECOND)); +} + +#[test] +fn fixed_diagnostics_and_messages_are_canonical_bounded_and_input_free() { + let mut codes = BTreeSet::new(); + for &code in Code::ALL { + assert!(codes.insert(code.as_str())); + assert!(!code.as_str().is_empty() && code.as_str().len() <= 80); + assert!( + code.as_str() + .bytes() + .all(|byte| byte.is_ascii_lowercase() || byte == b'_') + ); + assert!(!code.message().is_empty() && code.message().len() <= 512); + let error = Error::new( + code, + OperationContext::retained(FIRST), + RetryClass::ManualReconciliation, + None, + ) + .unwrap(); + assert_eq!(error.code(), code); + assert!(error.source().is_none()); + assert!(format!("{error}").len() < 600); + assert!(format!("{error:?}").len() < 1024); + } + for &field in Field::ALL { + for &reason in Reason::ALL { + let detail = Detail::new(field, reason); + assert_eq!(detail.field().to_string(), field.as_str()); + assert_eq!(detail.reason().to_string(), reason.as_str()); + assert!(field.as_str().len() < 32 && reason.as_str().len() < 32); + assert!(format!("{detail:?}").len() < 128); + } + } + assert!(size_of::<Error>() <= 64); +} + +#[test] +fn retry_classes_and_construction_failures_have_fixed_protocol_strings() { + for (retry, expected) in [ + (RetryClass::Never, "never"), + (RetryClass::SafeSameOperation, "safe_same_operation"), + (RetryClass::AfterStateRefresh, "after_state_refresh"), + (RetryClass::ManualReconciliation, "manual_reconciliation"), + ] { + assert_eq!(retry.as_str(), expected); + } + for error in [ + InvalidErrorContext::ConfirmedAdmissionRequired, + InvalidErrorContext::OperationIdentityRequired, + InvalidErrorContext::RetainedRetryRequired, + InvalidErrorContext::ReconciliationRequired, + InvalidErrorContext::ConflictingRetry, + ] { + assert!(!error.to_string().is_empty() && error.to_string().len() < 80); + assert!(error.source().is_none()); + } +}