From 331c795f463d5c51f9e122eb6eb2bbeee3871342 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 29 Nov 2026 01:27:19 +0800 Subject: [PATCH 01/14] fix(provider): preserve JSON contracts under SDK feature unification Introduce the shared protocol SDK pins alongside the provider and gateway serialization changes required by their serde_json feature set. Preserve persisted request fingerprints and opaque payload bytes; pin them with provider wire, replay, and gateway regression tests. --- Cargo.lock | 1013 ++++++++++++++++- Cargo.toml | 7 + rss/llm/openai_chat.rss | 12 +- rss/llm/openai_responses_codec.rss | 8 +- src/auth/authenticated_stream.rs | 44 +- src/auth/host.rs | 2 +- src/domain.rs | 114 +- src/durable_provider.rs | 280 ++++- src/effects/journal.rs | 5 +- src/gateway/api_server.rs | 151 ++- src/json_canonical.rs | 129 +++ src/lib.rs | 1 + src/runtime/agent_host.rs | 70 +- .../cases/auth_sanitized_stream_rss_tests.rs | 84 ++ tests/fixtures/providers/chat_body.rss | 40 + tests/provider_json_canonical_tests.rs | 391 +++++++ 16 files changed, 2258 insertions(+), 93 deletions(-) create mode 100644 src/json_canonical.rs create mode 100644 tests/fixtures/providers/chat_body.rss create mode 100644 tests/provider_json_canonical_tests.rs diff --git a/Cargo.lock b/Cargo.lock index 3c939fa6..1b89fac3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,55 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "agent-client-protocol" +version = "5.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2889673b9bc92e57857cb780f5431b684840c78a95a8edaa4afc00293d10dda" +dependencies = [ + "agent-client-protocol-derive", + "agent-client-protocol-schema", + "anyhow", + "async-io", + "async-process", + "blocking", + "futures", + "futures-concurrency", + "rustc-hash", + "rustix", + "serde", + "serde_json", + "shell-words", + "tracing", + "uuid", + "windows-sys 0.61.2", +] + +[[package]] +name = "agent-client-protocol-derive" +version = "5.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28022fad62329e9d350c3ddf818b6966b91196ef948e772d9a4d27f441f955f3" +dependencies = [ + "quote", + "syn 3.0.3", +] + +[[package]] +name = "agent-client-protocol-schema" +version = "1.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650e76dae0c8d3e772acb35184e6dd4defa0e15e130c96bf4c4586597f1f2d91" +dependencies = [ + "anyhow", + "derive_more", + "indexmap 2.14.2", + "serde", + "serde_json", + "serde_with", + "strum", +] + [[package]] name = "ahash" version = "0.8.12" @@ -31,6 +80,15 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + [[package]] name = "anyhow" version = "1.0.104" @@ -88,6 +146,89 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "async-channel" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" +dependencies = [ + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite", + "parking", + "polling", + "rustix", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-lock" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0876700b0d007ad25d5508865a4259c3af9af6d296bf663a0d586d0bc3369f6f" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-process" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" +dependencies = [ + "async-channel", + "async-io", + "async-lock", + "async-signal", + "async-task", + "blocking", + "cfg-if", + "event-listener", + "futures-lite", + "rustix", +] + +[[package]] +name = "async-signal" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" +dependencies = [ + "async-io", + "async-lock", + "atomic-waker", + "cfg-if", + "futures-core", + "futures-io", + "rustix", + "signal-hook-registry", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + [[package]] name = "atomic-waker" version = "1.1.2" @@ -200,12 +341,43 @@ version = "2.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "blocking" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa" +dependencies = [ + "async-channel", + "async-task", + "futures-io", + "futures-lite", + "piper", +] + [[package]] name = "borrow-or-share" version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc0b364ead1874514c8c2855ab558056ebfeb775653e7ae45ff72f28f8f3166c" +[[package]] +name = "bs58" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4" +dependencies = [ + "tinyvec", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -243,6 +415,57 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "num-traits", + "serde", + "windows-link", +] + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + +[[package]] +name = "convert_case" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9" +dependencies = [ + "unicode-segmentation", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + [[package]] name = "cranelift-assembler-x64" version = "0.129.2" @@ -424,6 +647,49 @@ version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.3", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core", + "quote", + "syn 3.0.3", +] + [[package]] name = "data-encoding" version = "2.11.1" @@ -449,6 +715,43 @@ name = "deranged" version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +dependencies = [ + "serde_core", +] + +[[package]] +name = "derive_more" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.119", + "unicode-xid", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", +] [[package]] name = "displaydoc" @@ -461,6 +764,12 @@ dependencies = [ "syn 3.0.3", ] +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + [[package]] name = "email_address" version = "0.2.9" @@ -486,6 +795,26 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + [[package]] name = "fallible-iterator" version = "0.3.0" @@ -509,12 +838,24 @@ dependencies = [ "regex-syntax", ] +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + [[package]] name = "find-msvc-tools" version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" +[[package]] +name = "fixedbitset" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5905ec755cc8386d7928353e4d356d2be3e89e81e5ca01fe630a1ca4d08dc175" + [[package]] name = "fluent-uri" version = "0.4.1" @@ -563,47 +904,116 @@ dependencies = [ "num-bigint", ] +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + [[package]] name = "futures-channel" -version = "0.3.33" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "262590f4fe6afeb0bc83be1daa64e52657fe185690a958af7f3ad0e92085c5ae" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" dependencies = [ "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-concurrency" +version = "7.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175cd8cca9e1d45b87f18ffa75088f2099e3c4fe5e2f83e42de112560bea8ea6" +dependencies = [ + "fixedbitset", + "futures-core", + "futures-lite", + "pin-project", + "smallvec", ] [[package]] name = "futures-core" -version = "0.3.33" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-lite" +version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2cd50c473c80f6d7c3670a752354b8e569b1a7cbfdc0419ec88e5edad85e0dc7" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] [[package]] name = "futures-macro" -version = "0.3.33" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d6d3cde68c518367be28956066ddfef33813991b77a55005a69dae04bf3b10b" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.3", ] +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + [[package]] name = "futures-task" -version = "0.3.33" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b231ed28831efb4a61a08580c4bc233ec56bc009f4cd8f52da2c3cb97df0c109" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" [[package]] name = "futures-util" -version = "0.3.33" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a77a90a256fce34da66415271e30f94ee91c57b04b8a2c042d9cf3220179deaa" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ + "futures-channel", "futures-core", + "futures-io", "futures-macro", + "futures-sink", "futures-task", + "memchr", "pin-project-lite", "slab", ] @@ -652,10 +1062,16 @@ checksum = "0bf7f043f89559805f8c7cacc432749b2fa0d0a0a9ee46ce47164ed5ba7f126c" dependencies = [ "fnv", "hashbrown 0.16.1", - "indexmap", + "indexmap 2.14.2", "stable_deref_trait", ] +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + [[package]] name = "hashbrown" version = "0.15.5" @@ -700,6 +1116,18 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + [[package]] name = "http" version = "1.5.0" @@ -745,6 +1173,15 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + [[package]] name = "hyper" version = "1.11.0" @@ -802,6 +1239,30 @@ dependencies = [ "tracing", ] +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + [[package]] name = "icu_collections" version = "2.2.0" @@ -873,53 +1334,176 @@ checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" name = "icu_provider" version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" +checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", + "serde", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jiff" +version = "0.2.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175dc66334db3b9ab9985bf8b61cfed50dc16d20964bb47f9e479adcae984a7f" +dependencies = [ + "jiff-core 0.1.8", + "jiff-static 0.2.46", + "jiff-tzdb-platform 0.1.3", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "windows-link", +] + +[[package]] +name = "jiff" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "107f2e89536b6818514025f6787b0d94d819e54fe3b40365275fc753de485b3f" +dependencies = [ + "jiff-core 1.0.2", + "jiff-static 1.0.3", + "jiff-tzdb-platform 1.0.0", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "windows-link", +] + +[[package]] +name = "jiff-core" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e599b80292e597019b8b3e392de3f4bea2959ddfb8c7dff60e035e9e311a2c1b" +dependencies = [ + "log", +] + +[[package]] +name = "jiff-core" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d44c923edf2bf456a982253f1a9ee1f6e89e421dffd0065d9b9a581da0def58f" dependencies = [ - "displaydoc", - "icu_locale_core", - "writeable", - "yoke", - "zerofrom", - "zerotrie", - "zerovec", + "log", ] [[package]] -name = "idna" -version = "1.1.0" +name = "jiff-static" +version = "0.2.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +checksum = "c7b1af7547d47354bc438d797e3854601bde8f8d185780c5ba4ab27afa54f1ba" dependencies = [ - "idna_adapter", - "smallvec", - "utf8_iter", + "jiff-core 0.1.8", + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] -name = "idna_adapter" -version = "1.2.2" +name = "jiff-static" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +checksum = "4996f71e569e3a3e32b925c28ef8f0027dc30bb1d594b33eeda409eea185f5c8" dependencies = [ - "icu_normalizer", - "icu_properties", + "jiff-core 1.0.2", + "proc-macro2", + "quote", + "syn 3.0.3", ] [[package]] -name = "indexmap" -version = "2.14.2" +name = "jiff-tzdb" +version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +checksum = "0980fca2cc272465bd60e82397607ba9f33add9e48defd77923301bbd03808f2" + +[[package]] +name = "jiff-tzdb" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12e71a1b68a875a44a33bb7a1dd84392cb77145a3367a552a3cfe6a4f5cf3afc" + +[[package]] +name = "jiff-tzdb-platform" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" dependencies = [ - "equivalent", - "hashbrown 0.17.1", + "jiff-tzdb 0.1.10", ] [[package]] -name = "itoa" -version = "1.0.18" +name = "jiff-tzdb-platform" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +checksum = "dc65b284afcfa8f6cf189c7274c805505314a7ab975c60e1f548bff56525420e" +dependencies = [ + "jiff-tzdb 1.0.0", +] [[package]] name = "js-sys" @@ -1013,6 +1597,12 @@ dependencies = [ "vcpkg", ] +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + [[package]] name = "litemap" version = "0.8.2" @@ -1199,6 +1789,12 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e" +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + [[package]] name = "parking_lot" version = "0.12.5" @@ -1228,6 +1824,12 @@ version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" +[[package]] +name = "pastey" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" + [[package]] name = "pd-host-function" version = "0.1.0" @@ -1298,18 +1900,78 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "pin-project" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6c2123f4708bbd422630a6dae7c03f678b1ce1f1c99e4c4b3beac69c8174cc9" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "358938fd6df944c1e44bb328b60fb275f13c804aac47ba26a1165d45a3f87756" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + [[package]] name = "pin-project-lite" version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "piper" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" +dependencies = [ + "atomic-waker", + "fastrand", + "futures-io", +] + [[package]] name = "pkg-config" version = "0.3.33" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + [[package]] name = "potential_utf" version = "0.1.5" @@ -1484,6 +2146,46 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "rmcp" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "391f153431ab68664d946513ea0cb3edbca78eaf99c5a983036cacab6220d85b" +dependencies = [ + "chrono", + "futures", + "indexmap 2.14.2", + "libc", + "pastey", + "percent-encoding", + "pin-project-lite", + "rmcp-macros", + "schemars 1.2.3", + "serde", + "serde_json", + "sha2", + "thiserror", + "tokio", + "tokio-util", + "tracing", + "unicode-general-category", + "unicode-normalization", + "uuid", +] + +[[package]] +name = "rmcp-macros" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3598e3f36f4af2b5219b133baf7d97a2197039225adc3d4acf3dd8805b5a2aef" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "serde_json", + "syn 3.0.3", +] + [[package]] name = "rsqlite-vfs" version = "0.1.1" @@ -1525,6 +2227,15 @@ version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + [[package]] name = "rusticata-macros" version = "4.1.0" @@ -1534,6 +2245,19 @@ dependencies = [ "nom", ] +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags 2.13.1", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + [[package]] name = "rustls" version = "0.23.43" @@ -1572,6 +2296,7 @@ dependencies = [ name = "rustscript-agent" version = "0.1.0" dependencies = [ + "agent-client-protocol", "axum", "bytes", "futures-util", @@ -1585,6 +2310,7 @@ dependencies = [ "pd-vm", "rcgen", "ring", + "rmcp", "rustls", "semver", "serde", @@ -1614,6 +2340,44 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +[[package]] +name = "schemars" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + +[[package]] +name = "schemars" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" +dependencies = [ + "chrono", + "dyn-clone", + "ref-cast", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 3.0.3", +] + [[package]] name = "scopeguard" version = "1.2.0" @@ -1662,12 +2426,24 @@ dependencies = [ "syn 3.0.3", ] +[[package]] +name = "serde_derive_internals" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + [[package]] name = "serde_json" version = "1.0.151" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" dependencies = [ + "indexmap 2.14.2", "itoa", "memchr", "serde", @@ -1698,19 +2474,70 @@ dependencies = [ "serde", ] +[[package]] +name = "serde_with" +version = "3.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56cb1ca7c93ae63d6439b5250f6b6b040f7e121f32e5dd2f5d523dd4149b3204" +dependencies = [ + "base64 0.23.1", + "bs58", + "chrono", + "hex", + "indexmap 1.9.3", + "indexmap 2.14.2", + "jiff 0.2.46", + "jiff 1.0.3", + "schemars 0.9.0", + "schemars 1.2.3", + "serde_core", + "serde_json", + "serde_with_macros", + "time", +] + +[[package]] +name = "serde_with_macros" +version = "3.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cff15a7c864bbec77d9586ca6822bc7c369bdf19e9243134a62b0b51ce26b31f" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn 3.0.3", +] + [[package]] name = "serde_yaml" version = "0.9.34+deprecated" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47" dependencies = [ - "indexmap", + "indexmap 2.14.2", "itoa", "ryu", "serde", "unsafe-libyaml", ] +[[package]] +name = "sha2" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shell-words" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc6fe69c597f9c37bfeeeeeb33da3530379845f10be461a66d16d03eca2ded77" + [[package]] name = "shlex" version = "2.0.1" @@ -1767,6 +2594,12 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + [[package]] name = "strum" version = "0.28.0" @@ -1899,6 +2732,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + [[package]] name = "tokio" version = "1.53.1" @@ -1948,6 +2787,20 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + [[package]] name = "tower" version = "0.5.3" @@ -2015,6 +2868,12 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "unicode-general-category" version = "1.1.0" @@ -2027,6 +2886,27 @@ version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + [[package]] name = "unsafe-libyaml" version = "0.2.11" @@ -2201,12 +3081,65 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + [[package]] name = "windows-sys" version = "0.52.0" diff --git a/Cargo.toml b/Cargo.toml index e2db998b..531be5aa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,6 +17,12 @@ name = "rustscript-agent-gateway" path = "src/bin/rustscript-agent-gateway.rs" [dependencies] +# Stable ACP v1 process/stdin-stdout proxy boundary. Direct features are limited +# to process and stdio: draft v2, unstable MCP-over-ACP, HTTP/auth surfaces, and +# rmcp client features stay off. Every released v5 SDK unconditionally enables +# the schema's `unstable_proxy_chains` because Proxy/Conductor is its stable +# proxy surface; no v5 feature selection can disable that internal prerequisite. +agent-client-protocol = { version = "5.6.1", default-features = false, features = ["process", "stdio"] } axum = "0.8" bytes = "1" futures-util = "0.3" @@ -24,6 +30,7 @@ http-body-util = "0.1" hyper = { version = "1", features = ["client", "http1"] } hyper-util = { version = "0.1", features = ["client-legacy", "http1", "tokio"] } parking_lot = "0.12" +rmcp = { version = "3.11.0", default-features = false, features = ["server", "macros", "transport-io"] } rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } rustscript-vm = { package = "pd-vm", git = "https://github.com/rustscript-lang/rustscript.git", rev = "11c9ee908a29365bd02573311f56e9308eb7dbe6", default-features = false, features = ["runtime", "http-client", "sqlite", "cranelift-jit"] } pd-host-function = { git = "https://github.com/rustscript-lang/rustscript.git", rev = "11c9ee908a29365bd02573311f56e9308eb7dbe6" } diff --git a/rss/llm/openai_chat.rss b/rss/llm/openai_chat.rss index a71598ff..3390fa5a 100644 --- a/rss/llm/openai_chat.rss +++ b/rss/llm/openai_chat.rss @@ -123,7 +123,12 @@ pub fn chat_build_public_body(request: map, model: string) -> string { body_text, types::request_array(request, "messages") ); - chat_splice_tool_schemas(with_user_parts, types::request_array(request, "tools")) + // The generated Chat objects and user-parts array historically came from + // `serde_json`'s sorted map, so the whole generated body gets that + // projection here. Tool `schema_json` is opaque caller bytes: splice it + // only after canonicalization so its key order and escaping stay exact. + let canonical: string = agent::canonical_json_text(with_user_parts); + chat_splice_tool_schemas(canonical, types::request_array(request, "tools")) } /// Public streaming body: identical to the buffered builder except the wire @@ -136,7 +141,8 @@ pub fn chat_build_public_stream_body(request: map, model: string) -> string { body_text, types::request_array(request, "messages") ); - chat_splice_tool_schemas(with_user_parts, types::request_array(request, "tools")) + let canonical: string = agent::canonical_json_text(with_user_parts); + chat_splice_tool_schemas(canonical, types::request_array(request, "tools")) } fn chat_build_wire(request: map, model: string, stream: bool) -> WireRequest { @@ -272,7 +278,7 @@ fn chat_tool_result_output(part: map) -> string { message: types::request_string(error, "message"), content: content }; - json::encode(failure) + agent::canonical_json_text(json::encode(failure)) } else if content == "" && field_is_map(part, "result") => { chat_tool_success(part) } else => { diff --git a/rss/llm/openai_responses_codec.rss b/rss/llm/openai_responses_codec.rss index 03199841..08574067 100644 --- a/rss/llm/openai_responses_codec.rss +++ b/rss/llm/openai_responses_codec.rss @@ -938,7 +938,11 @@ struct ResponsesWireFunctionCallOutputItem { pub fn responses_build_public_body(request: map, model: string, stream: bool) -> string { let messages: array = types::request_array(request, "messages"); let instructions: string = responses_collect_instructions(messages); - let input_json: string = responses_build_input(messages); + // Each input item was historically encoded through `serde_json`, so its + // object keys were sorted at every depth. The host projection restores that + // per-item byte stream while the top-level key order stays the manual + // Codex-compatible assembly below. + let input_json: string = agent::canonical_json_text(responses_build_input(messages)); let head: string = "{\"model\":" + json::encode::(model) + ",\"instructions\":" + json::encode::(instructions) + ",\"input\":" + input_json; @@ -1075,7 +1079,7 @@ fn responses_tool_output(part: map) -> string { message: types::request_string(error, "message"), content: content }; - json::encode::(failure) + agent::canonical_json_text(json::encode::(failure)) } else if field_is_map(part, "result") => { responses_tool_success(part) } else => { diff --git a/src/auth/authenticated_stream.rs b/src/auth/authenticated_stream.rs index e9ebe589..ab7da25b 100644 --- a/src/auth/authenticated_stream.rs +++ b/src/auth/authenticated_stream.rs @@ -385,7 +385,11 @@ impl SanitizedAccessSseStream { if !matches!(cleaned, JsonValue::Object(_) | JsonValue::Array(_)) { return Err(static_malformed("sse data is not a json object or array")); } - let serialized = cleaned.to_string(); + // Redaction preserves insertion order; the pre-ACP serde map emitted + // recursively sorted keys. Apply that projection after redaction so + // the public record bytes match the historical stream exactly. + let serialized = crate::json_canonical::to_canonical_string(&cleaned) + .map_err(|_| static_malformed("sse data is not strict json"))?; if serialized.len() > MAX_SSE_OUTPUT_BYTES { return Err(static_malformed("sse record exceeds output limit")); } @@ -1233,6 +1237,44 @@ mod sanitized_sse_tests { ); } + #[test] + fn sanitized_sse_records_match_literal_pre_acp_bytes_and_framing_order() { + let chunk = b"data: {\"z\":1,\"text\":\"hi\",\"access_token\":\"SYNTHETIC_SECRET\",\"nested\":{\"b\":2,\"a\":1}}\n\n\ +data: DONE\n\n\ +data: {\"b\":[{\"y\":2,\"x\":1}],\"a\":true}\n\n" + .to_vec(); + let (_store, access) = issue_access("literal-order"); + let (transport, state) = make_transport( + 200, + mime("text/event-stream"), + vec![Injected::Chunk(chunk), Injected::Eof], + ); + let clock = Arc::new(ScriptedClock::new(1_900_000_000_000)); + let cancel = Arc::new(ScriptedCancel::new()); + let host = make_host(transport, &clock, &cancel); + let mut stream = start_stream(&host, access, &cancel, vec!["DONE".to_string()]); + + assert_eq!( + json_text(expect_record(stream.read_record())), + r#"{"nested":{"a":1,"b":2},"text":"hi","z":1}"#, + "redacted SSE records must serialize with recursively sorted keys" + ); + assert_eq!( + expect_record(stream.read_record()), + SanitizedSseRecord::Literal(0), + "the caller literal must keep its exact record position" + ); + assert_eq!( + json_text(expect_record(stream.read_record())), + r#"{"a":true,"b":[{"x":1,"y":2}]}"#, + "later framed records must keep the same canonical bytes and order" + ); + expect_end(stream.read_record()); + let state = locked(&state); + assert_eq!(state.starts, 1); + assert_eq!(state.eofs, 1); + } + #[test] fn sanitized_sse_public_depth_bound_keeps_credential_limit_and_redacts() { assert_eq!( diff --git a/src/auth/host.rs b/src/auth/host.rs index 5b2cf2a2..593e7558 100644 --- a/src/auth/host.rs +++ b/src/auth/host.rs @@ -2079,7 +2079,7 @@ fn transport_call_shared( _ => return Err(error("response_handle_unsupported")), } } - let body = serde_json::to_string(&response.body_without_secret_fields) + let body = crate::json_canonical::to_canonical_string(&response.body_without_secret_fields) .map_err(|_| error("malformed_response"))?; if body.len() > 64 * 1024 { return Err(error("response_too_large")); diff --git a/src/domain.rs b/src/domain.rs index 1b3e49a6..190d15f8 100644 --- a/src/domain.rs +++ b/src/domain.rs @@ -330,10 +330,17 @@ pub(crate) fn input_text(input: &Value) -> String { match input { Value::String(text) => text.clone(), Value::Null => String::new(), - other => other.to_string(), + other => canonical_value_text(other), } } +/// Renders one JSON value parsed by this module as the recursively sorted text +/// the pre-ACP `serde_json` map projection produced. Only values this module +/// parsed are passed here; caller-supplied JSON text strings stay opaque. +fn canonical_value_text(value: &Value) -> String { + crate::json_canonical::to_canonical_string(value).unwrap_or_else(|_| value.to_string()) +} + /// Redacts free-text log messages by truncating at a char boundary, so /// embedded payload text (which may carry sensitive values) never reaches /// logs unbounded. Structured ids and typed reasons are logged as fields, @@ -424,28 +431,27 @@ pub fn decode_message_blocks(value: &Value) -> Vec { } else if let Some(text) = map.get("text") { let rendered = match text { Value::String(value) => value.clone(), - other => other.to_string(), + other => canonical_value_text(other), }; vec![text_block(&rendered)] } else { - vec![text_block(&value.to_string())] + vec![text_block(&canonical_value_text(value))] } } Value::Null => Vec::new(), - other => vec![text_block(&other.to_string())], + other => vec![text_block(&canonical_value_text(other))], } } fn decode_one_block(value: &Value) -> LlmContentBlock { - let mut block = - serde_json::from_value(value.clone()).unwrap_or_else(|_| text_block(&value.to_string())); + let mut block = serde_json::from_value(value.clone()) + .unwrap_or_else(|_| text_block(&canonical_value_text(value))); if block.truncated == Some(false) { block.truncated = None; } if block.arguments_json.is_none() { if let Some(arguments) = block.arguments.take() { - block.arguments_json = - Some(serde_json::to_string(&arguments).unwrap_or_else(|_| arguments.to_string())); + block.arguments_json = Some(canonical_value_text(&arguments)); } } else { block.arguments = None; @@ -492,8 +498,7 @@ fn bound_content_block(block: &LlmContentBlock) -> LlmContentBlock { } if bounded.arguments_json.is_none() { if let Some(arguments) = bounded.arguments.take() { - bounded.arguments_json = - Some(serde_json::to_string(&arguments).unwrap_or_else(|_| arguments.to_string())); + bounded.arguments_json = Some(canonical_value_text(&arguments)); } } else { bounded.arguments = None; @@ -540,3 +545,92 @@ fn bound_structured_json(value: Value, retain_error_code: bool) -> (Value, bool) } (Value::Object(redacted), true) } + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + /// Parsed object values synthesized into text must carry the recursively + /// sorted bytes the pre-ACP `BTreeMap` serializer produced. + const SYNTHESIZED_ARGUMENTS: &str = r#"{"a":{"b":3,"y":2},"z":1}"#; + + /// A provider/user-supplied `arguments_json` string is opaque input, not a + /// value this module parsed and re-encoded. Its bytes must survive exactly, + /// even when the key order is not canonical. + const VERBATIM_ARGUMENTS: &str = r#"{"z":1,"a":{"y":2,"b":3}}"#; + + #[test] + fn structured_input_text_matches_literal_pre_acp_bytes() { + assert_eq!( + input_text(&json!({ + "z": 1, + "a": {"y": 2, "b": 3}, + "items": [{"q": 4, "p": 5}] + })), + r#"{"a":{"b":3,"y":2},"items":[{"p":5,"q":4}],"z":1}"# + ); + assert_eq!(input_text(&json!("verbatim text")), "verbatim text"); + assert_eq!(input_text(&Value::Null), ""); + } + + #[test] + fn history_arguments_json_sorts_parsed_objects_but_keeps_supplied_text_verbatim() { + let synthesized = decode_message_blocks(&json!([{ + "type": "tool_call", + "tool_call_id": "c1", + "name": "read_file", + "arguments": {"z": 1, "a": {"y": 2, "b": 3}} + }])); + assert_eq!( + synthesized[0].arguments_json.as_deref(), + Some(SYNTHESIZED_ARGUMENTS), + "object-only history blocks must synthesize pre-ACP sorted text" + ); + + let supplied = decode_message_blocks(&json!([{ + "type": "tool_call", + "tool_call_id": "c1", + "name": "read_file", + "arguments_json": VERBATIM_ARGUMENTS, + "arguments": {"z": 1, "a": 2} + }])); + assert_eq!( + supplied[0].arguments_json.as_deref(), + Some(VERBATIM_ARGUMENTS), + "a preexisting arguments_json string is opaque and must stay byte-identical" + ); + assert!( + supplied[0].arguments.is_none(), + "the supplied text wins without a synthesized duplicate" + ); + + let encoded = encode_message_content(&[LlmContentBlock { + block_type: "tool_call".to_string(), + arguments: Some(json!({"z": 1, "a": {"y": 2, "b": 3}})), + ..LlmContentBlock::default() + }]); + assert_eq!( + encoded[0]["arguments_json"], + json!(SYNTHESIZED_ARGUMENTS), + "encode_message_content must also synthesize pre-ACP sorted text" + ); + } + + #[test] + fn legacy_history_text_shapes_match_literal_pre_acp_bytes() { + let text_field = decode_message_blocks(&json!({"text": {"z": 1, "a": 2}})); + assert_eq!( + text_field[0].text.as_deref(), + Some(r#"{"a":2,"z":1}"#), + "structured legacy text must be rendered with sorted keys" + ); + + let opaque_object = decode_message_blocks(&json!({"z": 1, "a": 2})); + assert_eq!( + opaque_object[0].text.as_deref(), + Some(r#"{"a":2,"z":1}"#), + "a non-block object fallback must be rendered with sorted keys" + ); + } +} diff --git a/src/durable_provider.rs b/src/durable_provider.rs index 3f650b37..a4a2e719 100644 --- a/src/durable_provider.rs +++ b/src/durable_provider.rs @@ -732,8 +732,13 @@ pub(crate) fn canonical_provider_request_fingerprint(request: &JsonValue) -> Str } } } - let bytes = serde_json::to_vec(&JsonValue::Object(safe)).unwrap_or_else(|_| b"{}".to_vec()); - format!("sha256:{}", crate::registry::sha256_hex(&bytes)) + // `safe` is inserted in `SAFE_REQUEST_KEYS` order, which is not key order. + // Persisted `sha256:` fingerprints record the recursively sorted bytes the + // pre-`preserve_order` `BTreeMap` produced, so the projection is applied + // here rather than relying on map insertion order. + let bytes = crate::json_canonical::to_canonical_string(&JsonValue::Object(safe)) + .unwrap_or_else(|_| "{}".to_string()); + format!("sha256:{}", crate::registry::sha256_hex(bytes.as_bytes())) } pub(crate) fn canonical_provider_step_from_envelope( @@ -919,7 +924,8 @@ fn tool_call_block(call: &JsonValue) -> LlmContentBlock { let arguments_json = if let Some(raw) = call.get("arguments_json").and_then(JsonValue::as_str) { Some(raw.to_string()) } else { - call.get("arguments").map(ToString::to_string) + call.get("arguments") + .and_then(|arguments| crate::json_canonical::to_canonical_string(arguments).ok()) }; let arguments = call.get("arguments").cloned().or_else(|| { arguments_json @@ -1066,7 +1072,7 @@ fn parse_strict_tool_arguments( "tool_call arguments must be a JSON object".to_string(), )); } - let encoded = serde_json::to_string(arguments).map_err(|_| { + let encoded = crate::json_canonical::to_canonical_string(arguments).map_err(|_| { EventCommitError::Corrupt("tool_call arguments could not be encoded".to_string()) })?; return Ok((Some(encoded), None)); @@ -1770,6 +1776,19 @@ mod tests { .collect() } + fn model_events(state: &AgentGatewayState, run_id: &str) -> Vec { + state + .service() + .run_events(run_id) + .into_iter() + .filter(|event| { + event["event"] + .as_str() + .is_some_and(|name| name.starts_with("model.")) + }) + .collect() + } + fn retryable_error() -> JsonValue { json!({ "status": 503, @@ -1820,6 +1839,259 @@ mod tests { ); } + /// The reference request is the one persisted under `e9da5dc` by the + /// independent pre-ACP oracle (`serde_json` without `preserve_order`). + /// Its safe projection and digest are byte-for-byte historical. + const PRE_ACP_SAFE_BYTES: &str = concat!( + r#"{"max_output_tokens":2048,"model":"gpt-test","provider":"openai","#, + r#""stream":true,"tool_choice":{"function":{"name":"read_file"},"#, + r#""priority":[3,1,2],"type":"function"}}"#, + ); + const PRE_ACP_FINGERPRINT: &str = + "sha256:3df51c015beb70b6de203e5e536a905410fb75578a2f464e48eb38ddb8460c29"; + + fn nested_request(tool_choice: JsonValue) -> JsonValue { + json!({ + "model": "gpt-test", + "provider": "openai", + "stream": true, + "max_output_tokens": 2048, + "tool_choice": tool_choice, + "prompt": "SECRET_PROMPT", + "messages": [{"role": "user", "content": "SECRET_MSG"}], + }) + } + + #[test] + fn canonical_fingerprint_matches_pre_acp_nested_bytes_and_digest() { + let request = nested_request(json!({ + "type": "function", + "function": {"name": "read_file"}, + "priority": [3, 1, 2], + })); + + let mut safe = serde_json::Map::new(); + for key in SAFE_REQUEST_KEYS { + if let Some(value) = request.get(*key) { + safe.insert((*key).to_string(), value.clone()); + } + } + assert_eq!( + crate::json_canonical::to_canonical_string(&JsonValue::Object(safe)) + .expect("canonical safe projection"), + PRE_ACP_SAFE_BYTES, + "candidate bytes must equal the pre-ACP oracle" + ); + assert_eq!( + canonical_provider_request_fingerprint(&request), + PRE_ACP_FINGERPRINT + ); + } + + #[tokio::test] + async fn persisted_pre_acp_fingerprint_replays_scoped_step_and_rejects_array_reorder() { + let path = temporary_db_path(); + let source = "pub fn run(context: map) -> map { context; }"; + let reordered = json!({ + "_provider_step_key": "business:0", + "tool_choice": { + "priority": [3, 1, 2], + "function": {"name": "read_file"}, + "type": "function", + }, + "max_output_tokens": 2048, + "stream": true, + "provider": "openai", + "model": "gpt-test", + "prompt": "SECRET_PROMPT", + "messages": [{"content": "SECRET_MSG", "role": "user"}], + }); + assert_eq!( + canonical_provider_request_fingerprint(&reordered), + PRE_ACP_FINGERPRINT, + "reordered object keys must reproduce the historical digest" + ); + + // Seed one completed scoped step through a real SQLite-backed gateway. + // The block returns only plain data plus a Weak proof of the live + // service, so the store, service, run handle, and first provider are + // all dropped before the reopen below. + let (run_id, live_envelope, live_model_events, live_service) = { + let state = AgentGatewayState::with_agent_source_and_sqlite( + AgentGatewayConfig::default(), + source, + &path, + ) + .expect("sqlite gateway"); + let admitted = state + .service() + .admit(AdmitRunRequest { + input: json!({"message": "hello"}), + platform: "durable_provider_tests".to_string(), + ..AdmitRunRequest::default() + }) + .await + .expect("admit"); + let inner = ScriptedProvider::new(); + inner.push_ok(text_ok("recorded pre-acp response")); + let cancel = admitted_cancel(&state, &admitted.run_id); + let mut request = nested_request(json!({ + "type": "function", + "function": {"name": "read_file"}, + "priority": [3, 1, 2], + })); + request["_provider_step_key"] = json!("business:0"); + + let live_envelope = + host_for(&state, &admitted.run_id, inner.clone()).call(&request, &cancel); + assert_eq!(live_envelope["ok"], json!(true), "{live_envelope}"); + assert_eq!(inner.call_count(), 1); + + // The completed scoped record itself carries the literal pre-ACP + // digest, so the replay below compares against a persisted + // historical fingerprint rather than a candidate-generated + // substitute. + let requested = events_named(&state, &admitted.run_id, "model.requested"); + assert_eq!(requested.len(), 1, "{requested:?}"); + assert_eq!(requested[0]["data"]["step_key"], json!("business:0")); + assert_eq!( + requested[0]["data"]["request_fingerprint"], + json!(PRE_ACP_FINGERPRINT) + ); + let completed = events_named(&state, &admitted.run_id, "model.completed"); + assert_eq!(completed.len(), 1, "{completed:?}"); + + let live_service = Arc::downgrade(&state.service()); + let live_model_events = model_events(&state, &admitted.run_id); + ( + admitted.run_id, + live_envelope, + live_model_events, + live_service, + ) + }; + assert!( + live_service.upgrade().is_none(), + "the original live gateway service must be fully dropped before reopen" + ); + + // Reopening the same temporary backend is the production restore path: + // `open_gateway_store` runs `GatewayPersistence::load()`, which rebuilds + // the in-memory store from the persisted rows. The fingerprint and + // completed response below can therefore only come from SQLite. + let reopened = AgentGatewayState::with_agent_source_and_sqlite( + AgentGatewayConfig::default(), + source, + &path, + ) + .expect("reopen"); + assert!(reopened.persistence().is_some()); + let restored_model_events = model_events(&reopened, &run_id); + assert_eq!( + restored_model_events, live_model_events, + "model.requested/model.completed must be restored exactly from persisted records" + ); + let restored_requested = events_named(&reopened, &run_id, "model.requested"); + assert_eq!(restored_requested.len(), 1, "{restored_requested:?}"); + assert_eq!( + restored_requested[0]["data"]["step_key"], + json!("business:0") + ); + assert_eq!( + restored_requested[0]["data"]["request_fingerprint"], + json!(PRE_ACP_FINGERPRINT) + ); + let resumed_inner = ScriptedProvider::new(); + let resumed = host_for(&reopened, &run_id, resumed_inner.clone()); + + // The reordered object keys are semantically identical, so the + // canonical digest matches the restored historical fingerprint and the + // completed turn replays without any native provider call. + let replay = resumed.call(&reordered, &RunCancellation::new()); + assert_eq!(replay["ok"], json!(true), "{replay}"); + assert_eq!( + replay, live_envelope, + "the exact completed response must replay from persisted records" + ); + assert_eq!( + replay["response"]["text"], + json!("recorded pre-acp response") + ); + assert_eq!(resumed_inner.call_count(), 0); + assert_eq!(events_named(&reopened, &run_id, "model.requested").len(), 1); + + // Array order is part of the fingerprint. The same scope/key with a + // reordered `priority` array must fail the persisted digest comparison + // before any provider call; a key-only replay would incorrectly + // succeed. + let mut array_reordered = reordered.clone(); + array_reordered["tool_choice"]["priority"] = json!([1, 3, 2]); + let rejected = resumed.call(&array_reordered, &RunCancellation::new()); + assert_eq!( + rejected["error"]["code"], + json!("corrupt_provider_step"), + "{rejected}" + ); + assert_eq!(resumed_inner.call_count(), 0); + assert_eq!(events_named(&reopened, &run_id, "model.requested").len(), 1); + + drop(reopened); + let _ = std::fs::remove_file(path); + } + + #[test] + fn nested_object_order_is_irrelevant_but_array_order_changes_the_fingerprint() { + let reordered = nested_request(json!({ + "priority": [3, 1, 2], + "function": {"name": "read_file"}, + "type": "function", + })); + assert_eq!( + canonical_provider_request_fingerprint(&reordered), + PRE_ACP_FINGERPRINT, + "reordered nested object keys must replay the same fingerprint" + ); + + let array_reordered = nested_request(json!({ + "type": "function", + "function": {"name": "read_file"}, + "priority": [1, 3, 2], + })); + assert_ne!( + canonical_provider_request_fingerprint(&array_reordered), + PRE_ACP_FINGERPRINT, + "array order must stay part of the fingerprint" + ); + } + + #[test] + fn durable_tool_arguments_use_canonical_json_text() { + let call = json!({ + "id": "call-1", + "name": "read_file", + "arguments": {"z": 1, "a": {"y": 2, "b": 3}} + }); + let block = tool_call_block(&call); + assert_eq!( + block.arguments_json.as_deref(), + Some(r#"{"a":{"b":3,"y":2},"z":1}"#), + "tool_call arguments persisted without arguments_json must be canonical" + ); + + let stored = serde_json::Map::from_iter([ + ("id".to_string(), json!("call-1")), + ("name".to_string(), json!("read_file")), + ( + "arguments".to_string(), + json!({"z": 1, "a": {"y": 2, "b": 3}}), + ), + ]); + let (encoded, parsed) = + parse_strict_tool_arguments(&stored).expect("strict tool arguments"); + assert_eq!(encoded.as_deref(), Some(r#"{"a":{"b":3,"y":2},"z":1}"#)); + assert!(parsed.is_none()); + } + #[tokio::test] async fn fresh_request_attempt_aligns_with_failed_attempt() { let (state, run_id, _) = admitted_state().await; diff --git a/src/effects/journal.rs b/src/effects/journal.rs index 63282d9d..37e267eb 100644 --- a/src/effects/journal.rs +++ b/src/effects/journal.rs @@ -810,7 +810,10 @@ impl CanonicalToolResultJson { // immutable receipt and typed durable facade have the same envelope. let result = crate::service::canonical_tool_result(value).map_err(|e| e.code().to_string())?; - let canonical = serde_json::to_value(result).map_err(|e| e.to_string())?; + let typed = serde_json::to_value(result).map_err(|e| e.to_string())?; + // Match the native pinned result's historical byte order even when + // an SDK enables insertion-ordered JSON maps. + let canonical = crate::json_canonical::canonicalize_json_keys(&typed); let measured = BoundedJsonCounter::measure(&canonical, limit)?; let json = serde_json::to_string(&canonical).map_err(|e| e.to_string())?; debug_assert_eq!(json.len() as u64, measured); diff --git a/src/gateway/api_server.rs b/src/gateway/api_server.rs index 6f16c9fc..acd5a022 100644 --- a/src/gateway/api_server.rs +++ b/src/gateway/api_server.rs @@ -38,6 +38,7 @@ use uuid::Uuid; use crate::config::{AgentGatewayConfig, RateLimitConfig}; use crate::domain::{fnv1a64, input_text, timestamp, vm_value_to_json}; +use crate::json_canonical::canonicalize_json_keys; use crate::runtime::delivery::DiscardingSink; use crate::runtime::rss_runner::execute_rss_source; use crate::service::{AdmitError, SubscriberGuard, failed_payload}; @@ -1091,23 +1092,9 @@ async fn create_run_handler( .map(str::trim) .filter(|value| !value.is_empty()) .map(ToOwned::to_owned); - let request_hash = idempotency_key.as_ref().map(|_| { - let canonical = serde_json::to_string(&json!({ - "input": request.input.clone(), - "session_id": request.session_id.clone(), - "model": request.model.clone(), - "provider": request.provider.clone(), - "parent_run_id": request.parent_run_id.clone(), - "instructions": request.instructions.clone(), - "workspace": request.workspace.clone(), - "conversation_history": request.conversation_history.clone(), - "graph_id": request.graph_id.clone(), - "workspace_branch": request.workspace_branch.clone(), - "extra": request.extra.clone(), - })) - .unwrap_or_default(); - format!("fnv64:{:016x}", fnv1a64(canonical.as_bytes())) - }); + let request_hash = idempotency_key + .as_ref() + .map(|_| create_run_request_hash(&request)); let input = request.input.clone().unwrap_or(Value::Null); let text = input_text(&input); let agent_input = if request.conversation_history.is_none() && request.extra.is_empty() { @@ -1715,10 +1702,45 @@ fn job_payload(view: &JobView, now: u64) -> Value { }) } -/// FNV-1a 64-bit hash of the canonical idempotency payload. The `fnv64:` -/// label matches the algorithm exactly, so persisted hashes stay -/// unambiguous regardless of the platform's `DefaultHasher`. Shared with the -/// Telegram adapter through `crate::domain::fnv1a64`. +/// Builds the idempotency payload for one create-run request. +/// +/// This is the exact semantic request shape persisted in `idempotency_hash` +/// records; object key order is normalized by [`canonicalize_json_keys`] +/// before hashing. +fn create_run_idempotency_payload(request: &CreateRunRequest) -> Value { + json!({ + "input": request.input.clone(), + "session_id": request.session_id.clone(), + "model": request.model.clone(), + "provider": request.provider.clone(), + "parent_run_id": request.parent_run_id.clone(), + "instructions": request.instructions.clone(), + "workspace": request.workspace.clone(), + "conversation_history": request.conversation_history.clone(), + "graph_id": request.graph_id.clone(), + "workspace_branch": request.workspace_branch.clone(), + "extra": request.extra.clone(), + }) +} + +/// Recursively canonicalizes object keys while preserving array order and +/// scalar values. +/// +/// Before `serde_json`'s `preserve_order` feature was enabled by an unrelated +/// dependency, its map was a sorted `BTreeMap`, so serializing this payload +/// produced recursively sorted keys. Persisted `fnv64:` idempotency hashes +/// record that historical byte stream; sorting every object here keeps those +/// records replayable and makes nested key order irrelevant. The projection is +/// shared with the provider loop boundaries through +/// [`crate::json_canonical`]. +fn create_run_request_hash(request: &CreateRunRequest) -> String { + let canonical = serde_json::to_string(&canonicalize_json_keys( + &create_run_idempotency_payload(request), + )) + .unwrap_or_default(); + format!("fnv64:{:016x}", fnv1a64(canonical.as_bytes())) +} + fn event_stream( history: Vec, receiver: Option>, @@ -1933,3 +1955,90 @@ mod rate_limiter_tests { )); } } + +#[cfg(test)] +mod idempotency_hash_tests { + use super::*; + + /// Recursively sorted serialization of the reference request below. This + /// is the exact byte stream the pre-`preserve_order` build hashed when it + /// persisted idempotency records. + const EXPECTED_CANONICAL: &str = concat!( + r#"{"conversation_history":[{"content":"hi","role":"user"}],"#, + r#""extra":{"alpha":[1,2,3],"zeta":{"a":1,"b":2}},"#, + r#""graph_id":null,"#, + r#""input":{"a":{"alpha":"x","beta":true},"#, + r#""items":[{"a":1,"z":2},{"b":"keep-order"}],"z":1},"#, + r#""instructions":"do the thing","model":"model-a","#, + r#""parent_run_id":null,"provider":"provider-b","#, + r#""session_id":"session-1","workspace":"workspace","#, + r#""workspace_branch":"main"}"#, + ); + const EXPECTED_HASH: &str = "fnv64:97a96f99a70d933d"; + + fn request_with_input(input: Value) -> CreateRunRequest { + CreateRunRequest { + input: Some(input), + session_id: Some("session-1".to_owned()), + model: Some("model-a".to_owned()), + provider: Some("provider-b".to_owned()), + parent_run_id: None, + instructions: Some("do the thing".to_owned()), + workspace: Some("workspace".to_owned()), + conversation_history: Some(json!([{"role": "user", "content": "hi"}])), + graph_id: None, + workspace_branch: Some("main".to_owned()), + extra: HashMap::from([ + ("zeta".to_owned(), json!({"b": 2, "a": 1})), + ("alpha".to_owned(), json!([1, 2, 3])), + ]), + } + } + + #[test] + fn canonical_request_hash_matches_pre_preserve_order_bytes() { + let request = request_with_input(json!({ + "z": 1, + "a": {"beta": true, "alpha": "x"}, + "items": [{"z": 2, "a": 1}, {"b": "keep-order"}], + })); + + let canonical = canonicalize_json_keys(&create_run_idempotency_payload(&request)); + assert_eq!( + serde_json::to_string(&canonical).expect("serialize canonical payload"), + EXPECTED_CANONICAL, + "the hashed bytes must equal the historical recursively sorted form" + ); + assert_eq!(create_run_request_hash(&request), EXPECTED_HASH); + } + + #[test] + fn nested_object_key_order_does_not_change_the_request_hash() { + let first: Value = serde_json::from_str( + r#"{"z":1,"a":{"beta":true,"alpha":"x"},"items":[{"z":2,"a":1}]}"#, + ) + .expect("first payload"); + let second: Value = serde_json::from_str( + r#"{"items":[{"a":1,"z":2}],"a":{"alpha":"x","beta":true},"z":1}"#, + ) + .expect("second payload"); + + assert_eq!( + create_run_request_hash(&request_with_input(first)), + create_run_request_hash(&request_with_input(second)), + "object key order at any depth must not change idempotency identity" + ); + } + + #[test] + fn array_order_still_changes_the_request_hash() { + let first = request_with_input(json!({"items": [1, 2]})); + let second = request_with_input(json!({"items": [2, 1]})); + + assert_ne!( + create_run_request_hash(&first), + create_run_request_hash(&second), + "canonicalization must not reorder arrays" + ); + } +} diff --git a/src/json_canonical.rs b/src/json_canonical.rs new file mode 100644 index 00000000..befcea34 --- /dev/null +++ b/src/json_canonical.rs @@ -0,0 +1,129 @@ +//! Canonical JSON projection used by legacy provider and gateway boundaries. +//! +//! Before the ACP dependency graph enabled `serde_json`'s `preserve_order` +//! feature, `serde_json::Map` was a sorted `BTreeMap`, so every object +//! serialized through `serde_json::to_string` produced recursively sorted +//! keys. Persisted idempotency hashes, provider request fingerprints, and the +//! provider wire adapters all recorded that byte stream. +//! +//! `preserve_order` switches the map to insertion order. This module restores +//! the historical projection at the boundaries that own a byte contract: +//! object keys are sorted at every depth, array order and scalar values are +//! preserved, and JSON text is re-encoded only through the same serde encoder +//! that produced the historical bytes. + +use serde_json::{Map, Value}; + +/// Recursively sorts object keys while preserving array order and scalar +/// values. +/// +/// This is exactly the projection `serde_json` applied when its map was a +/// `BTreeMap`: object insertion order is irrelevant at any depth, arrays keep +/// their order, and scalars are untouched. +pub(crate) fn canonicalize_json_keys(value: &Value) -> Value { + match value { + Value::Object(object) => { + let mut canonical = Map::new(); + for (key, nested) in object { + canonical.insert(key.clone(), canonicalize_json_keys(nested)); + } + canonical.sort_keys(); + Value::Object(canonical) + } + Value::Array(items) => Value::Array(items.iter().map(canonicalize_json_keys).collect()), + scalar => scalar.clone(), + } +} + +/// Serializes one value with recursively sorted object keys. +/// +/// Number formatting, string escaping, and array order match the historical +/// `serde_json::to_string` bytes because the same encoder is used after the +/// key projection. +pub(crate) fn to_canonical_string(value: &Value) -> serde_json::Result { + serde_json::to_string(&canonicalize_json_keys(value)) +} + +/// Re-encodes one JSON document as canonical text. +/// +/// Returns `None` when the text is not JSON; callers keep their own refusal or +/// pass-through semantics for non-JSON payloads such as form bodies. +pub(crate) fn canonicalize_json_text(text: &str) -> Option { + let value: Value = serde_json::from_str(text).ok()?; + to_canonical_string(&value).ok() +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn object_keys_are_sorted_recursively() { + let value = json!({ + "z": 1, + "a": {"beta": true, "alpha": "x"}, + "m": [{"y": 2, "b": 3}], + }); + + assert_eq!( + to_canonical_string(&value).expect("canonical json"), + r#"{"a":{"alpha":"x","beta":true},"m":[{"b":3,"y":2}],"z":1}"# + ); + } + + #[test] + fn reordered_nested_keys_converge_but_array_order_stays_significant() { + let first: Value = serde_json::from_str( + r#"{"z":1,"a":{"beta":true,"alpha":"x"},"items":[{"z":2,"a":1},{"b":"keep-order"}]}"#, + ) + .expect("first payload"); + let second: Value = serde_json::from_str( + r#"{"items":[{"a":1,"z":2},{"b":"keep-order"}],"a":{"alpha":"x","beta":true},"z":1}"#, + ) + .expect("second payload"); + + let first = to_canonical_string(&first).expect("first canonical"); + let second = to_canonical_string(&second).expect("second canonical"); + assert_eq!(first, second); + + // Negative control: canonicalization must not reorder arrays, so the + // same elements in a different order remain a different document. + let reordered: Value = + serde_json::from_str(r#"{"items":[{"b":"keep-order"},{"a":1,"z":2}]}"#) + .expect("reordered array"); + let expected: Value = serde_json::from_str( + r#"{"items":[{"z":2,"a":1},{"b":"keep-order"}],"a":{"beta":true,"alpha":"x"},"z":1}"#, + ) + .expect("expected array"); + assert_ne!( + to_canonical_string(&reordered).expect("reordered canonical"), + to_canonical_string(&expected).expect("expected canonical"), + "array order must remain significant" + ); + } + + #[test] + fn scalars_and_escapes_keep_their_serde_form() { + let value = json!({ + "text": "line\n\"quoted\"\u{1f600}", + "number": 1.5, + "flag": false, + "nothing": null, + }); + + assert_eq!( + to_canonical_string(&value).expect("canonical json"), + r#"{"flag":false,"nothing":null,"number":1.5,"text":"line\n\"quoted\"😀"}"# + ); + } + + #[test] + fn canonicalize_json_text_returns_none_for_non_json() { + assert_eq!(canonicalize_json_text("grant_type=refresh_token"), None); + assert_eq!( + canonicalize_json_text(r#"{"b":2,"a":1}"#).as_deref(), + Some(r#"{"a":1,"b":2}"#) + ); + } +} diff --git a/src/lib.rs b/src/lib.rs index 24ac8092..31fec657 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -31,6 +31,7 @@ pub mod tool_schema; mod bundled_sources; mod durable_provider; +mod json_canonical; mod transport; pub use bundled_sources::bundled_rss_sources; diff --git a/src/runtime/agent_host.rs b/src/runtime/agent_host.rs index 3627c3c2..dd9c443b 100644 --- a/src/runtime/agent_host.rs +++ b/src/runtime/agent_host.rs @@ -66,6 +66,14 @@ const PARSE_JSON_OBJECT: &str = "agent::parse_json_object"; const PREVIEW_ARGUMENTS: &str = "agent::preview_arguments"; const PARSE_JSON_OBJECT_MAX_BYTES: usize = 64 * 1024; const JSON_TEXT: &str = "agent::json_text"; +/// Canonicalizes one JSON document's object key order without changing array +/// order or scalar values. +/// +/// The provider adapters used to inherit recursively sorted keys from +/// `serde_json`'s `BTreeMap`. After `preserve_order` reached the dependency +/// graph, guest-encoded bodies kept insertion order, so the adapter asks the +/// host for the historical projection instead of depending on map layout. +const CANONICAL_JSON_TEXT: &str = "agent::canonical_json_text"; /// Bound applied to one serialized open payload leaving the guest. const JSON_TEXT_MAX_BYTES: usize = 4 * 1024 * 1024; /// Bound applied to one open payload entering a host adapter (tool metadata, @@ -117,6 +125,7 @@ const AGENT_HOST_FUNCTIONS: &[fn() -> HostFunctionDescriptor] = &[ parse_json_object_descriptor, preview_arguments_descriptor, json_text_descriptor, + canonical_json_text_descriptor, state_read_descriptor, state_write_descriptor, ]; @@ -595,6 +604,15 @@ fn json_text_descriptor() -> HostFunctionDescriptor { ) } +fn canonical_json_text_descriptor() -> HostFunctionDescriptor { + stack_desc( + CANONICAL_JSON_TEXT, + vec![HostParamSchema::value("text", HostTypeSchema::String)], + HostTypeSchema::String, + canonical_json_text_adapter, + ) +} + fn state_read_descriptor() -> HostFunctionDescriptor { stack_desc( STATE_READ, @@ -4400,7 +4418,7 @@ fn provider_envelope(vm: &mut Vm, envelope: JsonValue) -> VmResult else { continue; }; - match serde_json::to_string(arguments) { + match crate::json_canonical::to_canonical_string(arguments) { Ok(text) => { call.insert("arguments_json".to_string(), JsonValue::String(text)); } @@ -4411,7 +4429,7 @@ fn provider_envelope(vm: &mut Vm, envelope: JsonValue) -> VmResult } } } - let text = serde_json::to_string(&body).map_err(|_| { + let text = crate::json_canonical::to_canonical_string(&body).map_err(|_| { VmError::HostError("provider envelope body is not serializable".to_string()) })?; // The provider body owns this bound: the guest decodes whatever the host @@ -4422,10 +4440,10 @@ fn provider_envelope(vm: &mut Vm, envelope: JsonValue) -> VmResult "provider_body_too_large", "provider envelope body exceeds the 4 MiB bound", ); - let refusal = serde_json::to_string(refusal.get("error").unwrap_or(&JsonValue::Null)) - .map_err(|_| { - VmError::HostError("provider refusal body is not serializable".to_string()) - })?; + let refusal = crate::json_canonical::to_canonical_string( + refusal.get("error").unwrap_or(&JsonValue::Null), + ) + .map_err(|_| VmError::HostError("provider refusal body is not serializable".to_string()))?; (false, refusal) } else { (ok, text) @@ -4479,7 +4497,7 @@ fn refresh_envelope(vm: &mut Vm, answer: &JsonValue) -> VmResult { let ok = answer.get("ok") == Some(&JsonValue::Bool(true)); let messages = answer.get("messages").filter(|value| value.is_array()); let messages_json = if ok && storage_available { - messages.map(JsonValue::to_string) + messages.and_then(|messages| crate::json_canonical::to_canonical_string(messages).ok()) } else { Some(String::new()) }; @@ -4617,7 +4635,8 @@ fn parse_json_object_adapter(vm: &mut Vm, args: &[Value]) -> VmResult Value { let value = match parsed.get("value") { Some(JsonValue::Object(object)) => { - serde_json::to_string(object).unwrap_or_else(|_| "{}".to_string()) + crate::json_canonical::to_canonical_string(&JsonValue::Object(object.clone())) + .unwrap_or_else(|_| "{}".to_string()) } _ => String::new(), }; @@ -4849,12 +4868,21 @@ fn malformed_json_object() -> JsonValue { /// Refuses anything the JSON boundary cannot represent (bytes, callables, NaN) /// and anything past the payload bound. The caller gets a typed envelope, not a /// VM error, because every consumer reports these as `malformed_payload`. +/// +/// This is also the standalone MCP argument identity: `rss/tools/dispatch.rss` +/// calls it when a structured call carries no provider-supplied +/// `arguments_json`. The pre-ACP adapter serialized through the same +/// `serde_json` encoder while its map was a sorted `BTreeMap`, so these +/// canonical bytes are the historical ones. MCP wire serialization is not +/// involved. `tests/provider_json_canonical_tests.rs::json_text_matches_literal_pre_acp_mcp_argument_bytes` +/// pins these exact bytes through this adapter. fn json_text_adapter(vm: &mut Vm, args: &[Value]) -> VmResult { let text = match args.first() { Some(value) => match vm_value_to_json(value) { value if value_has_unrepresentable(&value) => Err("value is not JSON representable"), JsonValue::Null => Ok("null".to_string()), - other => serde_json::to_string(&other).map_err(|_| "value is not JSON representable"), + other => crate::json_canonical::to_canonical_string(&other) + .map_err(|_| "value is not JSON representable"), }, None => Err("value is missing"), }; @@ -4888,6 +4916,28 @@ fn json_text_adapter(vm: &mut Vm, args: &[Value]) -> VmResult { ) } +/// Canonicalizes one JSON document already encoded as text. +/// +/// Non-JSON text (a form body, a raw provider payload) is returned unchanged: +/// the adapter only owns the projection that `serde_json` used to apply to +/// object keys, never the caller's encoding. Text past the open-payload bound +/// is also passed through so the downstream transport keeps reporting its own +/// size refusal. +fn canonical_json_text_adapter(_vm: &mut Vm, args: &[Value]) -> VmResult { + let text = match args.first() { + Some(Value::String(value)) => value.as_str(), + _ => "", + }; + let canonical = if text.len() > JSON_TEXT_MAX_BYTES { + None + } else { + crate::json_canonical::canonicalize_json_text(text) + }; + return_json(JsonValue::String( + canonical.unwrap_or_else(|| text.to_string()), + )) +} + /// `vm_value_to_json` renders bytes as an empty array; a payload the guest /// cannot round-trip is refused instead of silently corrupted. fn value_has_unrepresentable(value: &JsonValue) -> bool { @@ -5444,7 +5494,7 @@ fn pinned_tool_result_with_limit(value: &JsonValue, max_bytes: usize) -> JsonVal "artifacts": canonical_value.get("artifacts").filter(|artifacts| artifacts.as_array().is_some_and(|items| items.iter().all(JsonValue::is_string))).cloned().unwrap_or_else(|| json!([])), }); } - let canonical = match serde_json::to_string(&canonical_value) { + let canonical = match crate::json_canonical::to_canonical_string(&canonical_value) { Ok(encoded) if encoded.len() <= max_bytes => encoded, Ok(_) => { return pinned_outcome( diff --git a/tests/cases/auth_sanitized_stream_rss_tests.rs b/tests/cases/auth_sanitized_stream_rss_tests.rs index 806e3a67..645c4029 100644 --- a/tests/cases/auth_sanitized_stream_rss_tests.rs +++ b/tests/cases/auth_sanitized_stream_rss_tests.rs @@ -431,6 +431,90 @@ fn guest_stream_orders_literal_json_then_terminal_eof() { assert_eq!(state.eofs, 1, "EOF observed exactly once"); } +#[test] +fn guest_stream_records_match_literal_pre_acp_bytes_and_framing() { + let chunk = concat!( + "data: {\"z\":1,\"text\":\"hi\",\"access_token\":\"SYNTHETIC_SECRET\",\"nested\":{\"b\":2,\"a\":1}}\n\n", + "data: DONE\n\n", + "data: {\"b\":[{\"y\":2,\"x\":1}],\"a\":true}\n\n", + ); + let (transport, state) = event_stream( + 200, + vec![Injected::Chunk(chunk.as_bytes().to_vec()), Injected::Eof], + ); + let home = PrivateHome::new(); + let cancellation = RunCancellation::with_timeout(Duration::from_secs(30)); + let (host, catalog) = native_host(&home, cancellation, transport); + let mut vm = fixture_vm(&host, catalog.as_ref()); + let policy = bind_policy(&host, &mut vm); + + let opened = invoke( + &mut vm, + "stream_open_result", + &start_args(&policy, markers(&["DONE"])), + ) + .expect("open typed stream"); + assert_eq!(field(&opened, "ok"), &Value::Bool(true), "{opened:?}"); + let stream = option_field(&opened, "stream") + .expect("open stream") + .clone(); + + let first = invoke( + &mut vm, + "stream_read_one_result", + std::slice::from_ref(&stream), + ) + .expect("read first record"); + assert_eq!(field(&first, "kind"), &Value::string("json"), "{first:?}"); + assert_eq!( + field(&first, "json"), + &Value::string(r#"{"nested":{"a":1,"b":2},"text":"hi","z":1}"#), + "the host must forward the sanitized record's literal canonical bytes" + ); + assert!(!format!("{first:?}").contains(RESPONSE_SECRET)); + + let second = invoke( + &mut vm, + "stream_read_one_result", + std::slice::from_ref(&stream), + ) + .expect("read literal record"); + assert_eq!( + field(&second, "kind"), + &Value::string("literal"), + "{second:?}" + ); + assert_eq!(field(&second, "literal_index"), &Value::Int(0)); + + let third = invoke( + &mut vm, + "stream_read_one_result", + std::slice::from_ref(&stream), + ) + .expect("read third record"); + assert_eq!(field(&third, "kind"), &Value::string("json"), "{third:?}"); + assert_eq!( + field(&third, "json"), + &Value::string(r#"{"a":true,"b":[{"x":1,"y":2}]}"#), + "framing order and canonical bytes must survive the host bridge" + ); + + let fourth = invoke( + &mut vm, + "stream_read_one_result", + std::slice::from_ref(&stream), + ) + .expect("read eof"); + assert_eq!(field(&fourth, "kind"), &Value::string("eof")); + assert_eq!( + invoke(&mut vm, "stream_close", &[stream]).expect("explicit close"), + Value::Null + ); + let state = locked(&state); + assert_eq!(state.starts, 1); + assert_eq!(state.eofs, 1); +} + #[test] fn guest_stream_terminal_eof_survives_owner_cancellation() { let (transport, state) = event_stream(200, vec![Injected::Eof]); diff --git a/tests/fixtures/providers/chat_body.rss b/tests/fixtures/providers/chat_body.rss new file mode 100644 index 00000000..e39b61a3 --- /dev/null +++ b/tests/fixtures/providers/chat_body.rss @@ -0,0 +1,40 @@ +// Public fixture driving the production OpenAI Chat body builders through the +// restricted runner. No auth, transport, or provider loop is involved. +use agent; +use self::llm::openai_chat as chat; +use self::llm::tool_descriptor; +use self::llm::types; + +/// Public buffered body for the canonical request map. +pub fn request_body(args: array) -> string { + let request: map = args[0]; + let model: string = types::request_string(request, "model"); + chat::chat_build_public_body(request, model) +} + +/// Streaming public body for the canonical request map. +pub fn stream_body(args: array) -> string { + let request: map = args[0]; + let model: string = types::request_string(request, "model"); + chat::chat_build_public_stream_body(request, model) +} + +/// Exposes the host's `agent::json_text` projection so the provider suite can +/// pin the exact bytes the standalone MCP argument identity uses when a +/// structured call carries no provider-supplied `arguments_json`. +pub fn json_text(args: array) -> string { + let encoded = agent::json_text(args[0]); + encoded.text +} + +/// Body built from native tool descriptors, so the real `schema_json` +/// projection and splice path are exercised. +pub fn native_descriptor_body(args: array) -> string { + let mut request: map = args[0]; + let model: string = types::request_string(request, "model"); + let tools: array = types::request_array(request, "tools"); + let descriptor: map = types::array_entry(tools, 0); + let tool = tool_descriptor::from_native(descriptor); + request["tools"] = [tool]; + chat::chat_build_public_body(request, model) +} diff --git a/tests/provider_json_canonical_tests.rs b/tests/provider_json_canonical_tests.rs new file mode 100644 index 00000000..f2fae027 --- /dev/null +++ b/tests/provider_json_canonical_tests.rs @@ -0,0 +1,391 @@ +//! Canonical provider JSON byte contracts. +//! +//! `agent-client-protocol` transitively enables `serde_json/preserve_order`, +//! which changed legacy map serialization from recursively sorted keys to +//! insertion order. These tests pin the provider-facing boundaries back to the +//! pre-ACP bytes: the ChatGPT body builder, the Responses input assembly, and +//! the embedded tool-result JSON text. They run the real production RSS modules +//! through the restricted runner, so a regression in either the host +//! canonicalization primitive or its guest call sites fails here. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use rustscript_agent::runtime::{ + AgentConfig, AgentRunner, RunCancellation, RunDeliveryError, RunEventSink, +}; +use rustscript_vm::Value; +use serde_json::{Value as JsonValue, json}; + +struct Fixture { + runner: AgentRunner, + _sources: Sources, +} + +struct Sources(PathBuf); + +impl Drop for Sources { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +struct NoEvents; + +impl RunEventSink for NoEvents { + fn deliver(&mut self, value: Value) -> Result<(), RunDeliveryError> { + panic!("pure provider body builder unexpectedly emitted an event: {value:?}"); + } +} + +fn copy_modules(repo: &Path, root: &Path, modules: &[&str]) { + std::fs::create_dir_all(root.join("llm")).expect("create module root"); + for name in modules { + std::fs::copy(repo.join("rss/llm").join(name), root.join("llm").join(name)) + .unwrap_or_else(|error| panic!("copy production module {name}: {error}")); + } +} + +fn fixture(entry_fixture: &str, modules: &[&str]) -> Fixture { + let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let root = std::env::temp_dir().join(format!( + "provider-json-canonical-{}-{}", + entry_fixture, + uuid::Uuid::new_v4() + )); + std::fs::create_dir_all(&root).expect("create fixture root"); + let entry = root.join("entry.rss"); + std::fs::copy( + repo.join("tests/fixtures/providers").join(entry_fixture), + &entry, + ) + .expect("copy fixture entry"); + copy_modules(&repo, &root, modules); + let runner = AgentRunner::from_file(entry, AgentConfig::default()) + .expect("compile production provider modules"); + Fixture { + runner, + _sources: Sources(root), + } +} + +fn invoke(fixture: &Fixture, name: &str, args: &[Value]) -> Value { + let cancellation = RunCancellation::with_timeout(std::time::Duration::from_secs(20)); + fixture + .runner + .run_named_with_context_and_events( + name, + Value::Array(Arc::new(args.to_vec())), + &mut NoEvents, + &cancellation, + ) + .unwrap_or_else(|error| panic!("invoke {name}: {error}")) +} + +fn invoke_text(fixture: &Fixture, name: &str, args: &[Value]) -> String { + match invoke(fixture, name, args) { + Value::String(text) => text.to_string(), + other => panic!("{name} returned a non-string: {other:?}"), + } +} + +fn request_value(value: JsonValue) -> Value { + match value { + JsonValue::Null => Value::Null, + JsonValue::Bool(value) => Value::Bool(value), + JsonValue::Number(value) => match value.as_i64() { + Some(value) => Value::Int(value), + None => Value::Float(value.as_f64().expect("finite JSON number")), + }, + JsonValue::String(value) => Value::string(value), + JsonValue::Array(values) => { + Value::Array(Arc::new(values.into_iter().map(request_value).collect())) + } + JsonValue::Object(entries) => Value::map( + entries + .into_iter() + .map(|(key, value)| (Value::string(key), request_value(value))) + .collect(), + ), + } +} + +/// Re-serializes a value with sorted object keys, independently of the +/// production helper, to prove the observed bytes are canonical. +fn sorted(value: &JsonValue) -> String { + fn project(value: &JsonValue) -> JsonValue { + match value { + JsonValue::Object(object) => { + let mut keys: Vec<&String> = object.keys().collect(); + keys.sort(); + let mut out = serde_json::Map::new(); + for key in keys { + out.insert(key.clone(), project(&object[key])); + } + JsonValue::Object(out) + } + JsonValue::Array(items) => JsonValue::Array(items.iter().map(project).collect()), + scalar => scalar.clone(), + } + } + serde_json::to_string(&project(value)).expect("sorted json") +} + +fn chat_request() -> JsonValue { + json!({ + "model": "fixture-model", + "stream": true, + "messages": [ + {"role": "user", "content": [{"type": "text", "text": "read note.txt"}]}, + {"role": "assistant", "content": [{"type": "tool_call", "tool_call_id": "read-1", "name": "read_file", "arguments_json": "{\"path\":\"note.txt\"}"}]}, + {"role": "user", "content": [ + {"type": "tool_result", "tool_call_id": "read-1", "content": "", "result": {"z": 1, "a": {"y": 2, "b": 3}}, "truncated": false}, + {"type": "tool_result", "tool_call_id": "bad-1", "is_error": true, "error": {"code": "path_denied", "message": "dot components are not permitted"}, "content": ""} + ]} + ], + "tools": [{ + "name": "read_file", + "description": "Read bounded text from a workspace file", + "schema_json": "{\"properties\":{\"path\":{\"type\":\"string\"}},\"additionalProperties\":false,\"required\":[\"path\"],\"type\":\"object\"}" + }], + "sampling": {"temperature": 0.5} + }) +} + +/// The raw schema text from [`chat_request`]. Its key order is deliberately +/// not sorted (`properties` precedes `additionalProperties`), so a builder that +/// re-encodes the spliced schema cannot reproduce the historical bytes. +const RAW_OPAQUE_SCHEMA: &str = r#"{"properties":{"path":{"type":"string"}},"additionalProperties":false,"required":["path"],"type":"object"}"#; + +/// Exact pre-ACP Chat tool-success feedback text. The outer object is the +/// adapter's manual `content/result/truncated` assembly; the nested result is +/// recursively sorted because it came from native `agent::json_text`. +const CHAT_SUCCESS_FEEDBACK: &str = + r#"{"content":"","result":{"a":{"b":3,"y":2},"z":1},"truncated":false}"#; + +/// Exact pre-ACP Chat tool-error feedback text (sorted by the historical +/// serde projection). +const CHAT_ERROR_FEEDBACK: &str = + r#"{"content":"","error":"path_denied","message":"dot components are not permitted"}"#; + +/// Literal pre-ACP buffered Chat body for [`chat_request`]: generated Chat +/// objects and the user parts array are recursively sorted, while the opaque +/// `schema_json` bytes are spliced verbatim. +const CHAT_BUFFERED_PRE_ACP_BODY: &str = concat!( + r#"{"messages":[{"content":[{"text":"read note.txt","type":"text"}],"role":"user"},"#, + r#"{"role":"assistant","tool_calls":[{"function":{"arguments":"{\"path\":\"note.txt\"}","name":"read_file"},"id":"read-1","type":"function"}]},"#, + r#"{"content":"{\"content\":\"\",\"result\":{\"a\":{\"b\":3,\"y\":2},\"z\":1},\"truncated\":false}","role":"tool","tool_call_id":"read-1"},"#, + r#"{"content":"{\"content\":\"\",\"error\":\"path_denied\",\"message\":\"dot components are not permitted\"}","role":"tool","tool_call_id":"bad-1"}],"#, + r#""model":"fixture-model","stream":false,"temperature":0.5,"tools":[{"function":{"description":"Read bounded text from a workspace file","name":"read_file","parameters":"#, + r#"{"properties":{"path":{"type":"string"}},"additionalProperties":false,"required":["path"],"type":"object"}},"type":"function"}]}"#, +); + +/// Literal pre-ACP streaming Chat body for [`chat_request`]: same generated and +/// opaque bytes as the buffered body plus `stream` and `stream_options`. +const CHAT_STREAM_PRE_ACP_BODY: &str = concat!( + r#"{"messages":[{"content":[{"text":"read note.txt","type":"text"}],"role":"user"},"#, + r#"{"role":"assistant","tool_calls":[{"function":{"arguments":"{\"path\":\"note.txt\"}","name":"read_file"},"id":"read-1","type":"function"}]},"#, + r#"{"content":"{\"content\":\"\",\"result\":{\"a\":{\"b\":3,\"y\":2},\"z\":1},\"truncated\":false}","role":"tool","tool_call_id":"read-1"},"#, + r#"{"content":"{\"content\":\"\",\"error\":\"path_denied\",\"message\":\"dot components are not permitted\"}","role":"tool","tool_call_id":"bad-1"}],"#, + r#""model":"fixture-model","stream":true,"stream_options":{"include_usage":true},"temperature":0.5,"tools":[{"function":{"description":"Read bounded text from a workspace file","name":"read_file","parameters":"#, + r#"{"properties":{"path":{"type":"string"}},"additionalProperties":false,"required":["path"],"type":"object"}},"type":"function"}]}"#, +); + +/// Literal pre-ACP body whose tool schema is generated natively through +/// `agent::json_text` and is therefore recursively sorted before splicing. +const CHAT_NATIVE_SCHEMA_PRE_ACP_BODY: &str = concat!( + r#"{"messages":[{"content":[{"text":"read note.txt","type":"text"}],"role":"user"},"#, + r#"{"role":"assistant","tool_calls":[{"function":{"arguments":"{\"path\":\"note.txt\"}","name":"read_file"},"id":"read-1","type":"function"}]},"#, + r#"{"content":"{\"content\":\"\",\"result\":{\"a\":{\"b\":3,\"y\":2},\"z\":1},\"truncated\":false}","role":"tool","tool_call_id":"read-1"},"#, + r#"{"content":"{\"content\":\"\",\"error\":\"path_denied\",\"message\":\"dot components are not permitted\"}","role":"tool","tool_call_id":"bad-1"}],"#, + r#""model":"fixture-model","stream":false,"temperature":0.5,"tools":[{"function":{"description":"native schema","name":"read_file","parameters":"#, + r#"{"properties":{"path":{"type":"string"}},"required":["path"],"type":"object"}},"type":"function"}]}"#, +); + +#[test] +fn chat_public_body_matches_literal_pre_acp_golden_and_preserves_opaque_schema() { + let modules = ["openai_chat.rss", "types.rss", "tool_descriptor.rss"]; + let first = fixture("chat_body.rss", &modules); + let second = fixture("chat_body.rss", &modules); + let request = request_value(chat_request()); + + let body = invoke_text(&first, "request_body", std::slice::from_ref(&request)); + let rebuilt = invoke_text(&second, "request_body", &[request]); + + assert_eq!( + body, rebuilt, + "two independent compilations must emit byte-identical bodies" + ); + assert_eq!( + body, CHAT_BUFFERED_PRE_ACP_BODY, + "buffered Chat body must equal the literal pre-ACP bytes" + ); + assert!( + body.contains(&format!("\"parameters\":{RAW_OPAQUE_SCHEMA}")), + "opaque schema bytes must be spliced verbatim, including key order: {body}" + ); + assert!( + RAW_OPAQUE_SCHEMA.find("\"properties\"") + < RAW_OPAQUE_SCHEMA.find("\"additionalProperties\""), + "the golden schema is intentionally not in canonical key order" + ); + + let parsed: JsonValue = serde_json::from_str(&body).expect("chat body json"); + assert_eq!( + parsed["messages"][2]["content"], + json!(CHAT_SUCCESS_FEEDBACK), + "embedded Chat success feedback must be byte-exact" + ); + assert_eq!( + parsed["messages"][3]["content"], + json!(CHAT_ERROR_FEEDBACK), + "embedded Chat error feedback must be byte-exact" + ); +} + +#[test] +fn chat_stream_body_matches_literal_pre_acp_golden() { + let modules = ["openai_chat.rss", "types.rss", "tool_descriptor.rss"]; + let fixture = fixture("chat_body.rss", &modules); + let body = invoke_text(&fixture, "stream_body", &[request_value(chat_request())]); + assert_eq!( + body, CHAT_STREAM_PRE_ACP_BODY, + "streaming Chat body must equal the literal pre-ACP bytes" + ); +} + +#[test] +fn native_descriptor_schema_matches_literal_pre_acp_canonical_bytes() { + let modules = ["openai_chat.rss", "types.rss", "tool_descriptor.rss"]; + let fixture = fixture("chat_body.rss", &modules); + let mut request = chat_request(); + request["tools"] = json!([{ + "name": "read_file", + "description": "native schema", + "schema": { + "type": "object", + "properties": {"path": {"type": "string"}}, + "required": ["path"] + } + }]); + + let body = invoke_text( + &fixture, + "native_descriptor_body", + &[request_value(request)], + ); + assert_eq!( + body, CHAT_NATIVE_SCHEMA_PRE_ACP_BODY, + "native schema objects must retain the pre-ACP sorted bytes" + ); +} + +#[test] +fn chat_preserves_opaque_schema_escaping_verbatim() { + let modules = ["openai_chat.rss", "types.rss", "tool_descriptor.rss"]; + let fixture = fixture("chat_body.rss", &modules); + // `\u00e9` is authored as an escape. Re-encoding the schema would emit the + // UTF-8 scalar, so this pins exact opaque bytes rather than just key order. + let raw = "{\"description\":\"caf\\u00e9\",\"properties\":{\"path\":{\"type\":\"string\"}},\"type\":\"object\"}"; + let mut request = chat_request(); + request["tools"][0]["schema_json"] = json!(raw); + + let body = invoke_text(&fixture, "request_body", &[request_value(request)]); + assert!( + body.contains(&format!("\"parameters\":{raw}")), + "opaque schema escaping must be spliced verbatim: {body}" + ); + let parsed: JsonValue = serde_json::from_str(&body).expect("chat body json"); + assert_eq!( + parsed["tools"][0]["function"]["parameters"]["description"], + json!("caf\u{00e9}") + ); +} + +#[test] +fn json_text_matches_literal_pre_acp_mcp_argument_bytes() { + let modules = ["openai_chat.rss", "types.rss", "tool_descriptor.rss"]; + let fixture = fixture("chat_body.rss", &modules); + let value = request_value(json!({ + "z": 1, + "a": {"y": 2, "b": 3}, + "items": [{"q": 4, "p": 5}], + "order": [3, 1, 2] + })); + + let text = invoke_text(&fixture, "json_text", &[value]); + assert_eq!( + text, r#"{"a":{"b":3,"y":2},"items":[{"p":5,"q":4}],"order":[3,1,2],"z":1}"#, + "agent::json_text must reproduce the pre-ACP sorted bytes" + ); + assert!( + text.contains(r#""order":[3,1,2]"#), + "array order must not be sorted" + ); +} + +#[test] +fn responses_input_items_and_tool_texts_are_canonical() { + let modules = [ + "openai_responses_codec.rss", + "types.rss", + "tool_descriptor.rss", + ]; + let first = fixture("responses_codec.rss", &modules); + let second = fixture("responses_codec.rss", &modules); + let request = request_value(json!({ + "model": "fixture-model", + "messages": [ + {"role": "user", "content": [{"type": "text", "text": "read note.txt"}]}, + {"role": "assistant", "content": [{"type": "tool_call", "tool_call_id": "read-1", "name": "read_file", "arguments_json": "{\"path\":\"note.txt\"}"}]}, + {"role": "user", "content": [ + {"type": "tool_result", "tool_call_id": "read-1", "content": "", "result": {"z": 1, "a": {"y": 2, "b": 3}}, "truncated": false}, + {"type": "tool_result", "tool_call_id": "bad-1", "is_error": true, "error": {"code": "path_denied", "message": "dot components are not permitted"}, "content": ""} + ]} + ], + "tools": [{ + "name": "read_file", + "description": "Read bounded text from a workspace file", + "schema_json": "{\"properties\":{\"path\":{\"type\":\"string\"}},\"additionalProperties\":false,\"required\":[\"path\"],\"type\":\"object\"}" + }] + })); + + let body = invoke_text(&first, "stream_body", std::slice::from_ref(&request)); + let rebuilt = invoke_text(&second, "stream_body", &[request]); + assert_eq!( + body, rebuilt, + "two independent compilations must emit byte-identical Responses bodies" + ); + // The Responses top-level assembly is manual and must stay in that order. + assert!( + body.starts_with(r#"{"model":"fixture-model","instructions":"#), + "Responses top-level key order is a manual wire contract: {body}" + ); + + let parsed: JsonValue = serde_json::from_str(&body).expect("Responses body json"); + let input = parsed["input"].as_array().expect("input array"); + for item in input { + assert_eq!( + serde_json::to_string(item).expect("item json"), + sorted(item), + "each Responses input item must use sorted object keys: {item}" + ); + } + let outputs: Vec<&JsonValue> = input.iter().filter_map(|item| item.get("output")).collect(); + assert_eq!(outputs.len(), 2, "one success and one error output"); + for output in &outputs { + let text = output.as_str().expect("function_call_output text"); + let parsed: JsonValue = serde_json::from_str(text).expect("tool output json"); + assert_eq!(text, sorted(&parsed), "tool output text must be canonical"); + } + assert_eq!( + outputs[0].as_str().expect("success output text"), + CHAT_SUCCESS_FEEDBACK, + "embedded Responses success feedback must equal the literal pre-ACP bytes" + ); + assert_eq!( + outputs[1].as_str().expect("error output text"), + CHAT_ERROR_FEEDBACK, + "embedded Responses error feedback must equal the literal pre-ACP bytes" + ); +} From 20ea55a0b0d5721d57f4d54750b5aa1e03eaf2f3 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 29 Nov 2026 01:27:19 +0800 Subject: [PATCH 02/14] feat(mcp): serve workspace tools over stdio without providers Add the provider-free executor, shared workspace capabilities, and stdio server with durable settlement, cancellation, and process ownership. Keep the server and its capability contracts together because admission and shutdown exercise the same lifecycle and ownership boundaries. --- Cargo.lock | 30 + Cargo.toml | 8 + rss/tools/patch.rss | 3 + rss/tools/process.rss | 130 +- rss/tools/terminal.rss | 148 +- rss/tools/types.rss | 8 +- rss/tools/write_file.rss | 3 + src/bin/rustscript-agent.rs | 64 +- src/capabilities/artifacts.rs | 193 +- src/capabilities/confined_io.rs | 36 +- src/capabilities/filesystem.rs | 287 +- src/capabilities/filesystem_ledger_tests.rs | 133 + src/capabilities/lifecycle.rs | 3442 +++++++++++- .../lifecycle_settlement_tests.rs | 456 ++ src/capabilities/mod.rs | 25 +- src/capabilities/process.rs | 1456 ++++- src/capabilities/types.rs | 8 + src/capabilities/vm_io/bounded_process.rs | 4418 ++++++++++++++- src/capabilities/vm_io/confined_fs.rs | 485 +- src/capabilities/vm_io/exec_gate.rs | 414 ++ src/capabilities/vm_io/mod.rs | 9 +- src/capabilities/vm_io/shared.rs | 18 +- src/cli.rs | 211 +- src/effects/broker.rs | 4 +- src/effects/managed_authority_tests.rs | 1 + src/lib.rs | 9 +- src/mcp/catalog.rs | 149 + src/mcp/executor.rs | 3070 +++++++++++ src/mcp/mod.rs | 92 + src/mcp/result.rs | 57 + src/mcp/server.rs | 1582 ++++++ src/runtime/agent_host.rs | 26 + src/runtime/agent_host/option_text_tests.rs | 2 + src/runtime/agent_host/preview_tests.rs | 2 + src/runtime/mod.rs | 3 +- src/runtime/rss_runner.rs | 142 +- src/service.rs | 1778 +++++- src/service/managed_checkpoints.rs | 3 +- src/service/managed_effects_tests.rs | 18 +- src/tool_result.rs | 99 + tests/capability_lifecycle_tests.rs | 384 +- tests/capability_tests.rs | 134 +- tests/cases/rss_file_tool_tests.rs | 6 +- tests/cases/rss_mutating_file_tool_tests.rs | 101 + tests/mcp_catalog_tests.rs | 254 + tests/mcp_executor_hardening_tests.rs | 846 +++ tests/mcp_provider_isolation_tests.rs | 165 + tests/mcp_sol_lifecycle_tests.rs | 4896 +++++++++++++++++ tests/mcp_sol_publication_settlement_tests.rs | 655 +++ tests/mcp_sol_synchronized_tests.rs | 650 +++ tests/mcp_tool_cli_tests.rs | 357 ++ tests/mcp_tool_retained_tests.rs | 288 + tests/mcp_tool_server_tests.rs | 3605 ++++++++++++ tests/mcp_tool_stdio_tests.rs | 2563 +++++++++ tests/mcp_tool_transport_tests.rs | 1360 +++++ tests/rss_process_tool_tests.rs | 128 +- tests/service_tests.rs | 93 + tests/tools_pin_invoke_tracer.rs | 7 + 58 files changed, 34810 insertions(+), 704 deletions(-) create mode 100644 src/capabilities/filesystem_ledger_tests.rs create mode 100644 src/capabilities/lifecycle_settlement_tests.rs create mode 100644 src/capabilities/vm_io/exec_gate.rs create mode 100644 src/mcp/catalog.rs create mode 100644 src/mcp/executor.rs create mode 100644 src/mcp/mod.rs create mode 100644 src/mcp/result.rs create mode 100644 src/mcp/server.rs create mode 100644 tests/mcp_catalog_tests.rs create mode 100644 tests/mcp_executor_hardening_tests.rs create mode 100644 tests/mcp_provider_isolation_tests.rs create mode 100644 tests/mcp_sol_lifecycle_tests.rs create mode 100644 tests/mcp_sol_publication_settlement_tests.rs create mode 100644 tests/mcp_sol_synchronized_tests.rs create mode 100644 tests/mcp_tool_cli_tests.rs create mode 100644 tests/mcp_tool_retained_tests.rs create mode 100644 tests/mcp_tool_server_tests.rs create mode 100644 tests/mcp_tool_stdio_tests.rs create mode 100644 tests/mcp_tool_transport_tests.rs diff --git a/Cargo.lock b/Cargo.lock index 1b89fac3..36c21829 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2321,6 +2321,7 @@ dependencies = [ "tower", "tracing", "tracing-core", + "tracing-subscriber", "url", "uuid", "webpki-roots", @@ -2532,6 +2533,15 @@ dependencies = [ "digest", ] +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + [[package]] name = "shell-words" version = "1.1.1" @@ -2692,6 +2702,15 @@ dependencies = [ "syn 3.0.3", ] +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + [[package]] name = "time" version = "0.3.55" @@ -2862,6 +2881,17 @@ dependencies = [ "valuable", ] +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "sharded-slab", + "thread_local", + "tracing-core", +] + [[package]] name = "try-lock" version = "0.2.5" diff --git a/Cargo.toml b/Cargo.toml index 531be5aa..57441cbf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -46,6 +46,7 @@ tokio = { version = "1", features = ["full"] } tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12"] } tower = { version = "0.5", features = ["util"] } tracing = "0.1" +tracing-subscriber = { version = "0.3", default-features = false, features = ["fmt"] } url = "2" uuid = { version = "1", features = ["v4"] } webpki-roots = "1" @@ -80,3 +81,10 @@ required-features = ["config-fixture"] name = "provider_config_fixture_tests" path = "tests/provider_config_fixture_tests.rs" required-features = ["config-fixture"] + +# The retained-disposition wire test needs the real publisher seam to hold a +# permit across the guest commit decision. +[[test]] +name = "mcp_tool_retained_tests" +path = "tests/mcp_tool_retained_tests.rs" +required-features = ["workspace-io-fault"] diff --git a/rss/tools/patch.rss b/rss/tools/patch.rss index 2f1be067..3c5acc34 100644 --- a/rss/tools/patch.rss +++ b/rss/tools/patch.rss @@ -96,6 +96,9 @@ fn fail_host(error: map) -> map { if code == "publication_indeterminate" { data = { publication: "indeterminate" }; } + if code == "publication_restored" { + data = { publication: "restored" }; + } fail(code, message, data) } diff --git a/rss/tools/process.rss b/rss/tools/process.rss index 58ca922e..a75d8025 100644 --- a/rss/tools/process.rss +++ b/rss/tools/process.rss @@ -339,7 +339,114 @@ fn compact_overflow_envelope(result: map) -> map { compacted } -fn enforce_serialized_cap(result: map, cap: int) -> map { +/// JSON-encoded byte contribution of one string value, including escaping. +/// +/// The host serializer is the only encoder admitted by this pin, so measuring +/// two otherwise identical maps isolates the exact escaped size of the string. +fn json_string_bytes(value: string) -> int { + let mut with_value: map = {}; + with_value.v = value; + let mut without_value: map = {}; + without_value.v = ""; + let delta: int = encoded_len(with_value) - encoded_len(without_value); + if delta < 0 => { 0 } else => { delta } +} + +/// Truncates `text` to at most `limit` JSON-encoded bytes. +fn truncate_json_bytes(text: string, limit: int) -> string { + let mut end: int = 0; + let mut used: int = 0; + let mut walking: bool = true; + while walking && end < text.length { + let ch: string = char_at(text, end); + let ch_bytes: int = json_string_bytes(ch); + if used + ch_bytes > limit { + walking = false; + } else { + used = used + ch_bytes; + end = end + 1; + } + } + text[0:end] +} + +/// At most one artifact identity, truncated to its canonical 36-byte form. +fn bounded_artifacts(artifacts: array) -> array { + let mut bounded: array = []; + if artifacts.length > 0 { + if type(artifacts[0].copy()) == "string" { + let first: string = artifacts[0]; + bounded[0] = truncate_json_bytes(first, 36); + } + } + bounded +} + +fn minimal_terminal_status(data: map) -> map { + let mut status: map = {}; + let name: string = truncate_json_bytes(types::map_string(data, "status", ""), 8); + if utf8_len(name) > 0 { + status.status = name; + } + if data.has("exit_code") { + status.exit_code = map_int(data, "exit_code", 0); + } + if data.has("signal") { + status.signal = map_int(data, "signal", 0); + } + status +} + +fn minimal_receipt(ok: bool, code: string, message: string, status: map, artifacts: array) -> map { + if ok => { + { + ok: true, + content: "", + data: status, + error: (), + truncated: true, + artifacts: artifacts + } + } else => { + let mut error: map = { code: code }; + if message.length > 0 { + error.message = message; + } + { + ok: false, + content: "", + data: status, + error: error, + truncated: true, + artifacts: artifacts + } + } +} + +// The MCP coding floor admits this receipt with JSON-escaped text and a +// canonical artifact ID; the managed dispatch keeps its own overflow result. +fn minimal_canonical_receipt(result: map) -> map { + let ok: bool = map_bool(result, "ok", false); + let data: map = types::map_map(result, "data"); + let error: map = types::map_map(result, "error"); + let code: string = types::map_string(error, "code", "output_truncated"); + let message: string = types::map_string(error, "message", "tool result exceeds the configured bound"); + minimal_receipt( + ok, + truncate_json_bytes(code, 48), + truncate_json_bytes(message, 96), + minimal_terminal_status(data), + bounded_artifacts(types::map_array(result, "artifacts")) + ) +} + +/// Applies the serialized output cap. +/// +/// The managed/agent path keeps the historical `e9da5dc` envelope exactly: a +/// receipt that cannot hold even the stripped data becomes the canonical +/// `output_truncated` failure. Only the MCP dispatch configuration selects the +/// canonical terminal receipt, which keeps terminal status and artifact identity. +fn enforce_serialized_cap(result: map, cap: int, lossless: bool) -> map { let mut bounded: map = result; if encoded_len(bounded) > cap { bounded.truncated = true; @@ -353,7 +460,11 @@ fn enforce_serialized_cap(result: map, cap: int) -> map { data.stderr = ""; bounded.data = data; if encoded_len(bounded) > cap { - bounded = fail_with("output_truncated", "tool result exceeds the configured bound", "", unpublished(), true); + if lossless { + bounded = minimal_canonical_receipt(bounded); + } else { + bounded = fail_with("output_truncated", "tool result exceeds the configured bound", "", unpublished(), true); + } } else { let budget: int = cap - encoded_len(bounded); bounded.content = truncate_to_bytes(original_content, budget); @@ -377,11 +488,15 @@ fn enforce_serialized_cap(result: map, cap: int) -> map { data.stderr = ""; bounded.data = data; if encoded_len(bounded) > cap { - bounded = fail_with("output_truncated", "tool result exceeds the configured bound", "", unpublished(), true); - if encoded_len(bounded) > cap { - bounded = fail_with("output_truncated", "bounded", "", unpublished(), true); + if lossless { + bounded = minimal_canonical_receipt(bounded); + } else { + bounded = fail_with("output_truncated", "tool result exceeds the configured bound", "", unpublished(), true); if encoded_len(bounded) > cap { - bounded = fail_with("output_truncated", "", "", unpublished(), true); + bounded = fail_with("output_truncated", "bounded", "", unpublished(), true); + if encoded_len(bounded) > cap { + bounded = fail_with("output_truncated", "", "", unpublished(), true); + } } } } @@ -429,7 +544,8 @@ fn apply_output_bounds(result: map, token: string, config: map, envelope: map) - data.retained_bytes = payload.length; bounded.data = data; } - bounded = enforce_serialized_cap(bounded, max_output_bytes); + let lossless: bool = map_bool(config, "overflow_lossless", false); + bounded = enforce_serialized_cap(bounded, max_output_bytes, lossless); } } bounded diff --git a/rss/tools/terminal.rss b/rss/tools/terminal.rss index b8c7b00d..e3eb6874 100644 --- a/rss/tools/terminal.rss +++ b/rss/tools/terminal.rss @@ -339,7 +339,114 @@ fn compact_overflow_envelope(result: map) -> map { compacted } -fn enforce_serialized_cap(result: map, cap: int) -> map { +/// JSON-encoded byte contribution of one string value, including escaping. +/// +/// The host serializer is the only encoder admitted by this pin, so measuring +/// two otherwise identical maps isolates the exact escaped size of the string. +fn json_string_bytes(value: string) -> int { + let mut with_value: map = {}; + with_value.v = value; + let mut without_value: map = {}; + without_value.v = ""; + let delta: int = encoded_len(with_value) - encoded_len(without_value); + if delta < 0 => { 0 } else => { delta } +} + +/// Truncates `text` to at most `limit` JSON-encoded bytes. +fn truncate_json_bytes(text: string, limit: int) -> string { + let mut end: int = 0; + let mut used: int = 0; + let mut walking: bool = true; + while walking && end < text.length { + let ch: string = char_at(text, end); + let ch_bytes: int = json_string_bytes(ch); + if used + ch_bytes > limit { + walking = false; + } else { + used = used + ch_bytes; + end = end + 1; + } + } + text[0:end] +} + +/// At most one artifact identity, truncated to its canonical 36-byte form. +fn bounded_artifacts(artifacts: array) -> array { + let mut bounded: array = []; + if artifacts.length > 0 { + if type(artifacts[0].copy()) == "string" { + let first: string = artifacts[0]; + bounded[0] = truncate_json_bytes(first, 36); + } + } + bounded +} + +fn minimal_terminal_status(data: map) -> map { + let mut status: map = {}; + let name: string = truncate_json_bytes(types::map_string(data, "status", ""), 8); + if utf8_len(name) > 0 { + status.status = name; + } + if data.has("exit_code") { + status.exit_code = map_int(data, "exit_code", 0); + } + if data.has("signal") { + status.signal = map_int(data, "signal", 0); + } + status +} + +fn minimal_receipt(ok: bool, code: string, message: string, status: map, artifacts: array) -> map { + if ok => { + { + ok: true, + content: "", + data: status, + error: (), + truncated: true, + artifacts: artifacts + } + } else => { + let mut error: map = { code: code }; + if message.length > 0 { + error.message = message; + } + { + ok: false, + content: "", + data: status, + error: error, + truncated: true, + artifacts: artifacts + } + } +} + +// The MCP coding floor admits this receipt with JSON-escaped text and a +// canonical artifact ID; the managed dispatch keeps its own overflow result. +fn minimal_canonical_receipt(result: map) -> map { + let ok: bool = map_bool(result, "ok", false); + let data: map = types::map_map(result, "data"); + let error: map = types::map_map(result, "error"); + let code: string = types::map_string(error, "code", "output_truncated"); + let message: string = types::map_string(error, "message", "tool result exceeds the configured bound"); + minimal_receipt( + ok, + truncate_json_bytes(code, 48), + truncate_json_bytes(message, 96), + minimal_terminal_status(data), + bounded_artifacts(types::map_array(result, "artifacts")) + ) +} + +/// Applies the serialized output cap. +/// +/// The managed/agent path keeps the historical `e9da5dc` envelope exactly: a +/// receipt that cannot hold even the stripped data becomes the canonical +/// `output_truncated` failure. Only the MCP dispatch configuration selects the +/// canonical terminal receipt, which keeps terminal status and artifact identity. +fn enforce_serialized_cap(result: map, cap: int, lossless: bool) -> map { let mut bounded: map = result; if encoded_len(bounded) > cap { bounded.truncated = true; @@ -353,11 +460,15 @@ fn enforce_serialized_cap(result: map, cap: int) -> map { data.stderr = ""; bounded.data = data; if encoded_len(bounded) > cap { - bounded = fail_with("output_truncated", "tool result exceeds the configured bound", "", unpublished(), true); - if encoded_len(bounded) > cap { - bounded = fail_with("output_truncated", "bounded", "", unpublished(), true); + if lossless { + bounded = minimal_canonical_receipt(bounded); + } else { + bounded = fail_with("output_truncated", "tool result exceeds the configured bound", "", unpublished(), true); if encoded_len(bounded) > cap { - bounded = fail_with("output_truncated", "", "", unpublished(), true); + bounded = fail_with("output_truncated", "bounded", "", unpublished(), true); + if encoded_len(bounded) > cap { + bounded = fail_with("output_truncated", "", "", unpublished(), true); + } } } } else { @@ -383,11 +494,15 @@ fn enforce_serialized_cap(result: map, cap: int) -> map { data.stderr = ""; bounded.data = data; if encoded_len(bounded) > cap { - bounded = fail_with("output_truncated", "tool result exceeds the configured bound", "", unpublished(), true); - if encoded_len(bounded) > cap { - bounded = fail_with("output_truncated", "bounded", "", unpublished(), true); + if lossless { + bounded = minimal_canonical_receipt(bounded); + } else { + bounded = fail_with("output_truncated", "tool result exceeds the configured bound", "", unpublished(), true); if encoded_len(bounded) > cap { - bounded = fail_with("output_truncated", "", "", unpublished(), true); + bounded = fail_with("output_truncated", "bounded", "", unpublished(), true); + if encoded_len(bounded) > cap { + bounded = fail_with("output_truncated", "", "", unpublished(), true); + } } } } @@ -435,7 +550,8 @@ fn apply_output_bounds(result: map, token: string, config: map, envelope: map) - data.retained_bytes = payload.length; bounded.data = data; } - bounded = enforce_serialized_cap(bounded, max_output_bytes); + let lossless: bool = map_bool(config, "overflow_lossless", false); + bounded = enforce_serialized_cap(bounded, max_output_bytes, lossless); } } bounded @@ -446,11 +562,15 @@ fn map_spawn_error(code: string, message: string) -> map { if code == "path_denied" { mapped = fail("invalid_cwd", "cwd is outside the workspace", unpublished()); } else { - if code == "process_failed" || code == "invalid_request" { - mapped = fail("spawn_failed", message, unpublished()); + if code == "process_limit" { + mapped = fail("process_limit", message, unpublished()); } else { - if code == "budget_exceeded" { - mapped = fail("invalid_stdin", "stdin exceeds the configured bound", unpublished()); + if code == "process_failed" || code == "invalid_request" { + mapped = fail("spawn_failed", message, unpublished()); + } else { + if code == "budget_exceeded" { + mapped = fail("invalid_stdin", "stdin exceeds the configured bound", unpublished()); + } } } } diff --git a/rss/tools/types.rss b/rss/tools/types.rss index 072f1822..13812d08 100644 --- a/rss/tools/types.rss +++ b/rss/tools/types.rss @@ -5,7 +5,7 @@ use json; struct ToolCapabilityFailure { code: string, - message: string + message: Option } struct AgentCanonicalToolResult { @@ -36,7 +36,11 @@ pub fn file_replay_result(text: string) -> map { } fn with_replay_error(result: map, failure: ToolCapabilityFailure) -> map { - result.error = { code: failure.code, message: failure.message }; + let message: string = match failure.message { + Some(text) => text, + None => "" + }; + result.error = { code: failure.code, message: message }; result } diff --git a/rss/tools/write_file.rss b/rss/tools/write_file.rss index d607d719..9073da5a 100644 --- a/rss/tools/write_file.rss +++ b/rss/tools/write_file.rss @@ -96,6 +96,9 @@ fn fail_host(error: map) -> map { if code == "publication_indeterminate" { data = { publication: "indeterminate" }; } + if code == "publication_restored" { + data = { publication: "restored" }; + } fail(code, message, data) } diff --git a/src/bin/rustscript-agent.rs b/src/bin/rustscript-agent.rs index ea2dff4d..64fe831d 100644 --- a/src/bin/rustscript-agent.rs +++ b/src/bin/rustscript-agent.rs @@ -20,9 +20,10 @@ use rustscript_agent::auth::native_browser::NativeBrowserOpener; use rustscript_agent::auth::native_https::NativeHttpsTransport; use rustscript_agent::auth::oauth::{OAuthError, OAuthHost}; use rustscript_agent::cli::{ - CliInvocation, CliOutput, cli_usage, execute_auth_cli, execute_config_path_cli, parse_cli_args, - resolve_cli_paths, + CliInvocation, CliOutput, ToolsServeOptions, cli_usage, execute_auth_cli, + execute_config_path_cli, parse_cli_args, resolve_cli_paths, }; +use rustscript_agent::mcp::server::RustScriptToolServer; use rustscript_agent::runtime::{AuthEntryRunner, RunCancellation}; use rustscript_agent::{ AgentConfig, AgentRunner, CancellationReason, RunDeliveryError, RunError, RunEventSink, @@ -77,6 +78,13 @@ const PATH_SOURCES: &[(&str, &str)] = #[tokio::main] async fn main() -> ExitCode { + // The Linux pre-exec gate re-executes this packaged binary to hold a child + // before any tool code exists. It is parsed before the public CLI so the + // gate argument never becomes an admitted invocation. + #[cfg(target_os = "linux")] + if let Some(code) = rustscript_agent::capabilities::run_exec_gate_if_requested() { + return ExitCode::from(u8::try_from(code).unwrap_or(1)); + } let invocation = match parse_cli_args(env::args_os().skip(1)) { Ok(invocation) => invocation, Err(error) => { @@ -94,10 +102,59 @@ async fn main() -> ExitCode { stdout: format!("{}\n", cli_usage()), stderr: String::new(), }), + // MCP mode owns stdout exclusively: it must never pass through the + // human-oriented `CliOutput` renderer or the legacy signal driver. + CliInvocation::ToolsServe(options) => run_tool_server(options).await, invocation => run_with_owned_signal(invocation).await, } } +async fn run_tool_server(options: ToolsServeOptions) -> ExitCode { + // Start the bounded stderr writer before any fallible construction. A + // constructor refusal then goes through the same non-blocking, guaranteed + // path as the serving diagnostics; a synchronous `eprintln!` here could + // block forever on a stalled stderr pipe. + rustscript_agent::mcp::server::install_tool_server_diagnostics(); + let server = match RustScriptToolServer::new(options.executor_config().with_exec_gate()) { + Ok(server) => server, + Err(error) => { + rustscript_agent::mcp::server::write_construction_diagnostic(&error); + return ExitCode::from(1); + } + }; + let exit_code = match server.serve_stdio().await { + Ok(outcome) => { + if outcome.cleanup.is_clean() { + 0 + } else { + 1 + } + } + Err(_) => { + // `serve_stdio` already emitted the one bounded diagnostic + // carrying the stable code; printing it here would duplicate it. + 1 + } + }; + // The rmcp stdio worker may still own an uncancellable blocking stdin read + // or a stdout write stalled behind a peer that stopped reading. Dropping + // the Tokio runtime would wait for those blocking tasks; the server has + // already produced its bounded teardown proof. + // + // A worker can also be parked between the OS spawn and the conversion of + // its spawn reservation into a killable process-table record. Exit would + // remove the only thread that could make that conversion, so every + // registered pid (including reservation-owned spawns) is signalled and + // reaped directly before the process leaves. + let retained = rustscript_agent::capabilities::sweep_spawned_children( + std::time::Instant::now() + Duration::from_secs(2), + ); + // The sweep result is part of the teardown proof, not just an exit status. + rustscript_agent::mcp::server::write_exit_sweep_diagnostic(retained); + let exit_code = if retained == 0 { exit_code } else { 1 }; + std::process::exit(exit_code); +} + async fn run_with_owned_signal(invocation: CliInvocation) -> ExitCode { let output = run_with_owned_signal_driver(invocation, install_sigint_watcher).await; emit_output(output) @@ -175,6 +232,9 @@ fn execute_invocation(invocation: CliInvocation, cancellation: RunCancellation) } => execute_legacy_run(script, allowed_hosts, &cancellation), CliInvocation::Auth(input) => execute_auth(input, &cancellation), CliInvocation::ConfigPath(input) => execute_config_path(input, &cancellation), + // `tools serve` runs on the async tool-server path in `main`; reaching + // this synchronous legacy driver means the mode was misrouted. + CliInvocation::ToolsServe(_) => code_output("tools_serve_unavailable", 1), } } diff --git a/src/capabilities/artifacts.rs b/src/capabilities/artifacts.rs index bf4ddfda..876f0bde 100644 --- a/src/capabilities/artifacts.rs +++ b/src/capabilities/artifacts.rs @@ -10,7 +10,9 @@ use std::sync::{Arc, Mutex}; use serde_json::{Value, json}; use super::hash::content_hash; -use super::lifecycle::{CapabilityLifecycle, TokenOwnedResource}; +use super::lifecycle::{ + CapabilityLifecycle, NativeArtifactIdentity, NativeEffectRecord, TokenOwnedResource, +}; use super::types::{CapabilityError, CapabilityOwner, CapabilityRisk, TokenClaims}; /// Store-wide artifact ceilings. @@ -55,6 +57,12 @@ struct ArtifactInner { objects: Mutex>, total_bytes: Mutex, result_calls: Mutex>, + /// Test-only publication barrier that runs inside the per-call fence, + /// immediately before the object insertion. + before_publish: Mutex>>, + /// Test-only seam between the irreversible object insertion and the + /// token-resource registration. + after_store: Mutex>>, } /// In-memory run-scoped artifact store. @@ -84,10 +92,32 @@ impl ArtifactCapability { objects: Mutex::new(HashMap::new()), total_bytes: Mutex::new(0), result_calls: Mutex::new(HashSet::new()), + before_publish: Mutex::new(None), + after_store: Mutex::new(None), }), }) } + /// Installs a production-neutral hook that runs inside the per-call + /// publication fence, immediately before the artifact insertion. + pub fn inject_before_publish(&self, hook: Arc) { + *self + .inner + .before_publish + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(hook); + } + + /// Installs a production-neutral seam immediately after the irreversible + /// artifact insertion and before token-resource registration. + pub fn inject_after_store_for_test(&self, hook: Arc) { + *self + .inner + .after_store + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(hook); + } + /// Stores bytes under a new opaque id. /// /// Workspace-mutating callers must still present a Write token. Read-only @@ -128,22 +158,22 @@ impl ArtifactCapability { )); } } - match self.store_bytes(&claims, bytes, &bound) { + match self.store_bytes( + token, + &claims, + bytes, + &bound, + !self.inner.lifecycle.retains_published_tokens(), + ) { Ok(refer) => { - let guard = Arc::new(ResultArtifactGuard { - inner: Arc::clone(&self.inner), - id: refer.id.clone(), - call_key: call_key.clone(), - len: refer.len, - released: AtomicBool::new(false), - }); - if let Err(error) = self + if let Some(hook) = self .inner - .lifecycle - .register_resource(token, Arc::clone(&guard) as Arc) + .after_store + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .clone() { - guard.rollback_unpublished_side_effects(); - return Err(CapabilityError::from(error)); + hook(); } Ok(refer) } @@ -166,14 +196,16 @@ impl ArtifactCapability { risk: CapabilityRisk, ) -> Result { let claims = self.authorize(token, risk)?; - self.store_bytes(&claims, bytes, metadata) + self.store_bytes(token, &claims, bytes, metadata, false) } fn store_bytes( &self, + token: &str, claims: &TokenClaims, bytes: &[u8], metadata: &Value, + retract_on_interrupt: bool, ) -> Result { if bytes.len() > self.inner.limits.max_object_bytes { return Err(CapabilityError::new( @@ -181,43 +213,117 @@ impl ArtifactCapability { "artifact exceeds the per-object bound", )); } - let mut objects = self + { + let objects = self + .inner + .objects + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let total = self + .inner + .total_bytes + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if objects.len() >= self.inner.limits.max_objects + || total.saturating_add(bytes.len()) > self.inner.limits.max_total_bytes + { + return Err(CapabilityError::new( + "artifact_store_exhausted", + "artifact store quota is exhausted", + )); + } + } + // The publication permit stays valid across registration, so an + // interrupt that races this insertion is judged against the same + // irreversible point. The store locks are reacquired only for the + // insertion itself and released before registration: a stop that marks + // the token Interrupted makes `register_resource` call the guard's + // `release()`, which needs those same locks. + let permit = self .inner - .objects - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - let mut total = self + .lifecycle + .enter_publication(token) + .map_err(CapabilityError::from)?; + if let Some(hook) = self .inner - .total_bytes + .before_publish .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - if objects.len() >= self.inner.limits.max_objects - || total.saturating_add(bytes.len()) > self.inner.limits.max_total_bytes + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .clone() { - return Err(CapabilityError::new( - "artifact_store_exhausted", - "artifact store quota is exhausted", - )); + hook(); } let id = uuid::Uuid::new_v4().to_string(); let hash = content_hash(bytes); - objects.insert( - id.clone(), - ArtifactRecord { - owner_key: claims.owner.key(), - generation: claims.generation, - bytes: bytes.to_vec(), + let refer = { + let mut objects = self + .inner + .objects + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let mut total = self + .inner + .total_bytes + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + // Recheck under the locks: a concurrent store may have consumed + // the quota while this publication was entering the fence. + if objects.len() >= self.inner.limits.max_objects + || total.saturating_add(bytes.len()) > self.inner.limits.max_total_bytes + { + return Err(CapabilityError::new( + "artifact_store_exhausted", + "artifact store quota is exhausted", + )); + } + objects.insert( + id.clone(), + ArtifactRecord { + owner_key: claims.owner.key(), + generation: claims.generation, + bytes: bytes.to_vec(), + hash: hash.clone(), + metadata: metadata.clone(), + }, + ); + *total = total.saturating_add(bytes.len()); + ArtifactRef { + id: id.clone(), + len: bytes.len(), hash: hash.clone(), metadata: metadata.clone(), - }, - ); - *total = total.saturating_add(bytes.len()); - Ok(ArtifactRef { - id, + } + }; + // Base behavior: a result artifact is a token-owned resource in the + // managed path, so an interrupt or a commit-storage failure retracts it + // and releases its quota charge. The MCP retention mode deliberately + // keeps a published artifact for its canonical settlement. + if retract_on_interrupt { + let guard = Arc::new(ResultArtifactGuard { + inner: Arc::clone(&self.inner), + id: id.clone(), + call_key: result_call_key(claims), + len: bytes.len(), + released: AtomicBool::new(false), + }); + if let Err(error) = self + .inner + .lifecycle + .register_resource(token, Arc::clone(&guard) as Arc) + { + guard.rollback_unpublished_side_effects(); + return Err(CapabilityError::from(error)); + } + } + // Record the complete irreversible artifact identity inside the fence. + // A VM abort before the guest's `tool_commit` must return this stored + // object instead of a cancellation that drops the artifact. + permit.published_effect(NativeEffectRecord::artifact_store(NativeArtifactIdentity { + id: id.clone(), len: bytes.len(), - hash, - metadata: metadata.clone(), - }) + hash: hash.clone(), + })); + Ok(refer) } /// Returns stored bytes for an owned artifact. @@ -306,6 +412,9 @@ impl ArtifactCapability { } } +/// Token-owned result artifact for the managed path. Retracts the object and +/// releases its quota charge on interrupt or on a failed commit, exactly like +/// `e9da5dc`; the MCP retention mode never installs it. struct ResultArtifactGuard { inner: Arc, id: String, diff --git a/src/capabilities/confined_io.rs b/src/capabilities/confined_io.rs index 0d20416e..e69a3b81 100644 --- a/src/capabilities/confined_io.rs +++ b/src/capabilities/confined_io.rs @@ -9,8 +9,6 @@ //! Listing streams `readdir` with a skip cursor, page limit, and one-entry //! lookahead. Non-Unix targets fail closed. -use std::path::Path; - use super::types::CapabilityError; use super::vm_io::ConfinedFsRoot; @@ -45,20 +43,6 @@ pub(crate) struct ListPage { } impl FrozenDir { - /// Opens and retains `path` as a directory descriptor. The path is not - /// reopened for later reads. - pub(crate) fn open(path: &Path) -> Result { - #[cfg(unix)] - { - unix::open_root(path) - } - #[cfg(not(unix))] - { - let _ = path; - Err(unsupported()) - } - } - /// Duplicates the already-retained directory descriptor without reopening /// its display path. pub(crate) fn adopt(root: &ConfinedFsRoot) -> Result { @@ -194,9 +178,8 @@ mod unix { mem::MaybeUninit, os::{ fd::{AsRawFd, FromRawFd, OwnedFd, RawFd}, - unix::{ffi::OsStrExt, fs::FileExt}, + unix::fs::FileExt, }, - path::Path, }; use super::{ @@ -205,23 +188,6 @@ mod unix { }; use crate::capabilities::types::CapabilityError; - pub(super) fn open_root(path: &Path) -> Result { - let c_path = CString::new(path.as_os_str().as_bytes()) - .map_err(|_| path_denied("workspace path contains a NUL byte"))?; - let fd = unsafe { - libc::open( - c_path.as_ptr(), - libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC | libc::O_NOFOLLOW, - ) - }; - if fd < 0 { - return Err(map_io("fs::root", io::Error::last_os_error())); - } - Ok(FrozenDir { - fd: unsafe { OwnedFd::from_raw_fd(fd) }, - }) - } - pub(super) fn read_range( root: &FrozenDir, path: &str, diff --git a/src/capabilities/filesystem.rs b/src/capabilities/filesystem.rs index 2b1ec8b6..72b63d37 100644 --- a/src/capabilities/filesystem.rs +++ b/src/capabilities/filesystem.rs @@ -8,16 +8,20 @@ use std::{ sync::{Arc, Mutex}, }; +use crate::capabilities::vm_io::confined_fs::ConfinedPublication; use crate::capabilities::vm_io::{ ConfinedFileType, ConfinedFsError, ConfinedFsErrorKind, ConfinedFsLimits, ConfinedFsRoot, - ConfinedMetadata, ConfinedPublicationState, MAX_COMPONENT_BYTES, MAX_ENUM_ENTRIES, - MAX_READ_BYTES, MAX_WRITE_BYTES, + ConfinedMetadata, ConfinedObservedIdentity, ConfinedPublicationState, MAX_COMPONENT_BYTES, + MAX_ENUM_ENTRIES, MAX_READ_BYTES, MAX_WRITE_BYTES, }; use super::{ confined_io::FrozenDir, hash::content_hash, - lifecycle::CapabilityLifecycle, + lifecycle::{ + CapabilityLifecycle, NativeEffectRecord, NativeIndeterminateEvidence, + NativeObservedFileType, NativeObservedIdentity, NativeWriteOutcome, + }, types::{CapabilityError, CapabilityOwner, CapabilityRisk, TokenClaims}, }; @@ -83,6 +87,8 @@ pub struct FsWrite { type BeforeWriteHook = Arc Result<(), CapabilityError> + Send + Sync>; type AfterPublishHook = Arc bool + Send + Sync>; +type BeforePublishHook = Arc; +type DuringStagingHook = Arc; /// Confined filesystem capability bound to one lifecycle owner. #[derive(Clone)] @@ -96,6 +102,8 @@ pub struct FilesystemCapability { managed: Option>, cas_locks: Arc>>>>, before_write: Arc>>, + before_publish: Arc>>, + during_staging: Arc>>, after_publish: Arc>>, } @@ -126,7 +134,10 @@ impl FilesystemCapability { }, ) .map_err(map_fs_error)?; - let frozen = FrozenDir::open(lifecycle.workspace())?; + // Adopt the one retained root descriptor. Opening the workspace path a + // second time here would leave a reachable construction-time race + // where a replaced path could give reads and writes different trees. + let frozen = FrozenDir::adopt(&root)?; Ok(Self { lifecycle, owner, @@ -137,6 +148,8 @@ impl FilesystemCapability { managed: None, cas_locks: Arc::new(Mutex::new(HashMap::new())), before_write: Arc::new(Mutex::new(None)), + before_publish: Arc::new(Mutex::new(None)), + during_staging: Arc::new(Mutex::new(None)), after_publish: Arc::new(Mutex::new(None)), }) } @@ -181,6 +194,51 @@ impl FilesystemCapability { managed: None, cas_locks: Arc::new(Mutex::new(HashMap::new())), before_write: Arc::new(Mutex::new(None)), + before_publish: Arc::new(Mutex::new(None)), + during_staging: Arc::new(Mutex::new(None)), + after_publish: Arc::new(Mutex::new(None)), + }) + } + + /// Constructs a filesystem capability from one already-admitted retained + /// workspace root. The root descriptor is adopted, never reopened from a + /// path string, so a sibling capability built from the same root cannot + /// observe a different directory identity. + pub(crate) fn new_with_root( + lifecycle: CapabilityLifecycle, + owner: CapabilityOwner, + limits: FilesystemLimits, + root: &Arc, + ) -> Result { + if limits.max_read_bytes == 0 || limits.max_write_bytes == 0 || limits.max_list_entries == 0 + { + return Err(CapabilityError::new( + "invalid_configuration", + "filesystem limits must be positive", + )); + } + let root = root + .adopt(ConfinedFsLimits { + max_read_bytes: MAX_READ_BYTES, + max_write_bytes: limits.max_write_bytes.min(MAX_WRITE_BYTES), + max_entries: MAX_ENUM_ENTRIES, + max_entry_name_bytes: MAX_COMPONENT_BYTES, + max_temp_attempts: 32, + }) + .map_err(map_fs_error)?; + let frozen = FrozenDir::adopt(&root)?; + Ok(Self { + lifecycle, + owner, + limits, + root: Arc::new(root), + frozen: Arc::new(frozen), + workspace: None, + managed: None, + cas_locks: Arc::new(Mutex::new(HashMap::new())), + before_write: Arc::new(Mutex::new(None)), + before_publish: Arc::new(Mutex::new(None)), + during_staging: Arc::new(Mutex::new(None)), after_publish: Arc::new(Mutex::new(None)), }) } @@ -212,6 +270,31 @@ impl FilesystemCapability { .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(hook); } + /// Installs a production-neutral hook that runs inside the per-call + /// publication fence, immediately before the atomic rename. + /// + /// The hook is the deterministic test seam for the publication boundary: + /// a cancellation requested while it blocks is classified as losing to an + /// already-started publication, and the rename that follows still settles. + pub fn inject_before_publish(&self, hook: BeforePublishHook) { + *self + .before_publish + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(hook); + } + + /// Installs a production-neutral staging hook for tests. + /// + /// The hook runs once the confined temporary content is written and + /// flushed, before synchronization and the publication boundary. It is + /// tool-name-agnostic and never changes production behavior. + pub fn inject_during_staging(&self, hook: DuringStagingHook) { + *self + .during_staging + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(hook); + } + /// Installs a production-neutral post-publish hook for tests. /// /// The hook runs after confined rename/publish returns a published @@ -406,21 +489,91 @@ impl FilesystemCapability { if expected_hash != "*" { self.validate_expected_hash(path, expected_hash)?; } + // The per-call publication fence is entered inside the confined write, + // after staging and every fallible pre-publication check, immediately + // before the destination entry is created. A cancellation that arrives + // while the temporary is still being prepared therefore refuses the + // rename instead of being recorded against an effect that never + // existed. + let permit_slot: Arc>> = + Arc::new(Mutex::new(None)); + let refusal: Arc>> = Arc::new(Mutex::new(None)); + let before_publish_hook = self + .before_publish + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .clone(); + #[allow(clippy::result_large_err)] + let boundary = { + let lifecycle = self.lifecycle.clone(); + let token = token.to_string(); + let slot = Arc::clone(&permit_slot); + let refusal = Arc::clone(&refusal); + Some(Box::new(move || match lifecycle.enter_publication(&token) { + Ok(permit) => { + if let Some(hook) = &before_publish_hook { + hook(); + } + *slot.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(permit); + Ok(()) + } + Err(error) => { + *refusal + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = + Some(CapabilityError::from(error)); + Err(publication_refused_error()) + } + }) + as Box Result<(), ConfinedFsError> + Send>) + }; let publication = if let Some(managed) = &self.managed { let call = managed.upgrade().ok_or_else(|| { CapabilityError::new("managed_call_unavailable", "managed call unavailable") })?; call.accounted_write(token, path, bytes, || { - self.root.write_file(path, bytes).map_err(Box::new) + self.write_confined(path, bytes, boundary).map_err(Box::new) })? } else { - self.root.write_file(path, bytes).map_err(Box::new) + self.write_confined(path, bytes, boundary).map_err(Box::new) }; + if let Some(refusal) = refusal + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .take() + { + return Err(refusal); + } + let permit = permit_slot + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .take(); match publication { Ok(publication) => { if self.after_publish_forces_indeterminate(path, bytes) { + if let Some(permit) = permit { + permit.published_effect(NativeEffectRecord::atomic_write_indeterminate( + Some(write_outcome( + bytes, + publication.is_durable(), + publication.staging_cleaned(), + )), + NativeIndeterminateEvidence { + destination: None, + staging: None, + temp_completed: true, + }, + )); + } return Err(publication_indeterminate_error()); } + if let Some(permit) = permit { + permit.published_effect(NativeEffectRecord::atomic_write(write_outcome( + bytes, + publication.is_durable(), + publication.staging_cleaned(), + ))); + } Ok(FsWrite { hash: content_hash(bytes), len: bytes.len(), @@ -434,8 +587,27 @@ impl FilesystemCapability { staging_cleaned, } => { if self.after_publish_forces_indeterminate(path, bytes) { + if let Some(permit) = permit { + permit.published_effect( + NativeEffectRecord::atomic_write_indeterminate( + Some(write_outcome(bytes, durable, staging_cleaned)), + NativeIndeterminateEvidence { + destination: None, + staging: None, + temp_completed: true, + }, + ), + ); + } return Err(publication_indeterminate_error()); } + if let Some(permit) = permit { + permit.published_effect(NativeEffectRecord::atomic_write(write_outcome( + bytes, + durable, + staging_cleaned, + ))); + } Ok(FsWrite { hash: content_hash(bytes), len: bytes.len(), @@ -443,14 +615,73 @@ impl FilesystemCapability { staging_cleaned, }) } - ConfinedPublicationState::Indeterminate { .. } => { + ConfinedPublicationState::Indeterminate { + destination, + staging, + } => { + // The rename succeeded but its post-rename readback could + // not classify the destination. This is an explicit + // failed/indeterminate outcome, never an unpublished + // failure that a later cancellation could roll back. + if let Some(permit) = permit { + permit.published_effect(NativeEffectRecord::atomic_write_indeterminate( + Some(write_outcome(bytes, false, false)), + NativeIndeterminateEvidence { + destination: destination.map(native_observed_identity), + staging: staging.map(native_observed_identity), + temp_completed: true, + }, + )); + } Err(publication_indeterminate_error()) } + ConfinedPublicationState::RestoredAfterExchange { + destination, + staging, + } => { + // A successful exchange was followed by a proven reverse + // exchange that restored the destination directory. The + // net effect did not publish, but the irreversible + // exchange did cross the fence and is recorded as an + // explicit failed outcome instead of a NotPublished path. + if let Some(permit) = permit { + permit.published_effect(NativeEffectRecord::atomic_write_restored( + write_outcome(bytes, false, false), + NativeIndeterminateEvidence { + destination: destination.map(native_observed_identity), + staging: staging.map(native_observed_identity), + temp_completed: true, + }, + )); + } + Err(publication_restored_error()) + } ConfinedPublicationState::NotPublished => Err(map_fs_error(*error)), }, } } + /// Runs one confined atomic write with the optional staging observation + /// point and publication boundary. Both hooks are production-neutral: only + /// a caller that installed a test barrier observes them. + #[allow(clippy::result_large_err)] + fn write_confined( + &self, + path: &str, + bytes: &[u8], + before_publish: Option Result<(), ConfinedFsError> + Send>>, + ) -> Result { + let staging = self + .during_staging + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .clone(); + let during_staging = + staging.map(|hook| Box::new(move || hook()) as Box); + self.root + .write_file_with_hooks(path, bytes, during_staging, before_publish) + } + fn validate_expected_hash( &self, path: &str, @@ -582,6 +813,44 @@ fn publication_indeterminate_error() -> CapabilityError { ) } +fn publication_restored_error() -> CapabilityError { + CapabilityError::new( + "publication_restored", + "write publication was restored after an exchange", + ) +} + +/// Complete typed write identity recorded inside the publication fence. +fn write_outcome(bytes: &[u8], durable: bool, staging_cleaned: bool) -> NativeWriteOutcome { + NativeWriteOutcome { + len: bytes.len(), + hash: content_hash(bytes), + durable, + staging_cleaned, + } +} + +fn native_observed_identity(identity: ConfinedObservedIdentity) -> NativeObservedIdentity { + NativeObservedIdentity { + file_type: match identity.file_type() { + ConfinedFileType::File => NativeObservedFileType::File, + ConfinedFileType::Directory => NativeObservedFileType::Directory, + ConfinedFileType::Symlink => NativeObservedFileType::Symlink, + ConfinedFileType::Other => NativeObservedFileType::Other, + }, + device: identity.device(), + inode: identity.inode(), + } +} + +/// Sentinel returned by the confined writer when the capability's publication +/// boundary refused the effect. The capability replaces it with the precise +/// typed refusal (`cancelled`, `deadline_elapsed`, ...) it recorded before +/// returning to the caller. +fn publication_refused_error() -> ConfinedFsError { + ConfinedFsError::publication_refused() +} + fn bounded_identity(offset: u64, window_len: usize, file_len: u64) -> String { format!("range:{offset}:{window_len}:{file_len}") } @@ -625,3 +894,7 @@ fn map_fs_error(error: ConfinedFsError) -> CapabilityError { }; CapabilityError::new(code, error.message()) } + +#[cfg(all(test, target_os = "linux"))] +#[path = "filesystem_ledger_tests.rs"] +mod filesystem_ledger_tests; diff --git a/src/capabilities/filesystem_ledger_tests.rs b/src/capabilities/filesystem_ledger_tests.rs new file mode 100644 index 00000000..56c5225c --- /dev/null +++ b/src/capabilities/filesystem_ledger_tests.rs @@ -0,0 +1,133 @@ +//! Typed effect-ledger coverage for post-rename readback evidence. + +use std::fs; +use std::sync::Arc; + +use serde_json::Value; + +use super::{FilesystemCapability, FilesystemLimits}; +use crate::capabilities::{ + CapabilityLifecycle, CapabilityOwner, CapabilityRisk, DurableStarted, DurableToolLifecycle, + LifecycleClock, LifecycleError, LifecycleLimits, NativeEffectStatus, NeverCancelled, + PrepareMetadata, PrepareOutcome, SystemClock, TokenIssuer, UuidIssuer, +}; + +struct MemoryDurable; + +impl DurableToolLifecycle for MemoryDurable { + fn assert_active_run(&self, _run_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } + + fn prepare_parent( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result<(), LifecycleError> { + Ok(()) + } + + fn replay_result( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result, LifecycleError> { + Ok(None) + } + + fn commit_started(&self, _record: &DurableStarted) -> Result<(), LifecycleError> { + Ok(()) + } + + fn commit_result(&self, _call_id: &str, result: &Value) -> Result { + Ok(result.clone()) + } + + fn interrupt(&self, _call_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } +} + +#[test] +fn indeterminate_readback_record_retains_destination_and_temp_completion_evidence() { + let root = std::env::temp_dir().join(format!( + "fs-ledger-evidence-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("clock") + .as_nanos() + )); + fs::create_dir_all(&root).expect("fixture root"); + let owner = CapabilityOwner::new("fs-ledger", "session", "run").expect("owner"); + let lifecycle = CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry") + .workspace(&root) + .limits(LifecycleLimits { + max_tool_calls: 8, + max_output_bytes: 8192, + max_summary_bytes: 256, + }) + .deadline_ms(SystemClock.now_ms().saturating_add(60_000)) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(Arc::new(MemoryDurable) as Arc) + .approval(Arc::new(crate::capabilities::AllowAllApproval) + as Arc) + .cancellation(Arc::new(NeverCancelled) as Arc) + .build() + .expect("lifecycle"); + let filesystem = FilesystemCapability::new( + lifecycle.clone(), + owner.clone(), + FilesystemLimits::default(), + ) + .expect("filesystem"); + let token = match lifecycle + .prepare( + &owner, + PrepareMetadata { + run_id: owner.run().to_string(), + call_id: "readback-evidence".to_string(), + tool_name: "write_file".to_string(), + argument_digest: "digest".to_string(), + registry_identity: "registry".to_string(), + risk_class: CapabilityRisk::Write, + summary: "write".to_string(), + }, + ) + .expect("prepare") + { + PrepareOutcome::Execute { + execution_token, .. + } => execution_token, + other => panic!("expected execute, got {other:?}"), + }; + crate::capabilities::vm_io::confined_fs::fail_post_rename_observe_at_for_test(1); + let error = filesystem + .write_atomic(&token, "out.txt", "*", b"new-content\n") + .expect_err("the injected staging readback failure must surface"); + assert_eq!(error.code(), "publication_indeterminate", "{error:?}"); + let outcome = lifecycle + .call_native_outcome("readback-evidence") + .expect("typed native outcome"); + assert_eq!(outcome.record.status, NativeEffectStatus::Failed); + let evidence = outcome + .record + .indeterminate + .expect("an explicit indeterminate marker"); + assert!(evidence.temp_completed); + let destination = evidence + .destination + .expect("the already observed destination identity"); + assert_eq!( + destination.file_type, + crate::capabilities::NativeObservedFileType::File + ); + assert!(destination.inode > 0); + assert!(evidence.staging.is_none()); + let _ = fs::remove_dir_all(&root); +} diff --git a/src/capabilities/lifecycle.rs b/src/capabilities/lifecycle.rs index 567d4a9c..25c44410 100644 --- a/src/capabilities/lifecycle.rs +++ b/src/capabilities/lifecycle.rs @@ -1,7 +1,7 @@ //! Injectable durable lifecycle, clock, tokens, and approval. use std::{ - collections::HashMap, + collections::{HashMap, HashSet}, path::{Path, PathBuf}, sync::{ Arc, OnceLock, @@ -14,6 +14,8 @@ use parking_lot::Mutex; use serde_json::{Value, json}; use uuid::Uuid; +use crate::tool_result::{ToolError, ToolResult}; + use super::types::{ CapabilityOwner, CapabilityRisk, CommitOutcome, DurableStarted, LifecycleError, LifecycleLimits, PrepareMetadata, PrepareOutcome, TokenClaims, @@ -277,6 +279,52 @@ impl CancellationFlag for NeverCancelled { } } +/// Per-call cancellation state observed at prepare/authorize/commit/pre-effect. +/// +/// The lifecycle-wide [`CancellationFlag`] covers executor shutdown; this +/// source binds an individual admitted call's RSS control root to native +/// capability authorization and settlement. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum CallCancellationState { + Active, + Cancelled, + DeadlineElapsed, +} + +/// Optional call-scoped cancellation source. +/// +/// The default implementation keeps every call active so legacy lifecycle +/// callers are unchanged. +pub trait CallCancellationSource: Send + Sync { + fn call_state(&self, _call_id: &str) -> CallCancellationState { + CallCancellationState::Active + } +} + +/// Default call-scoped source: no call is individually cancelled. +#[derive(Debug, Default)] +pub struct AllowAllCallCancellation; + +impl CallCancellationSource for AllowAllCallCancellation {} + +/// Per-lifecycle policy for an open token that already crossed its publication +/// fence when its lease is aborted or its run is recovered. +/// +/// The managed/agent-run lifecycle keeps the base behavior: an abort or +/// recovery interrupts the token and the durable journal records the +/// interruption. The standalone MCP executor instead settles the exact +/// published effect through one canonical receipt, so it is the only owner +/// that enables [`PublishedTokenPolicy::RetainForSettlement`]. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub enum PublishedTokenPolicy { + /// Base behavior: abort and recovery interrupt every open token. + #[default] + Abort, + /// MCP behavior: a published or publishing token keeps its right to one + /// canonical receipt; abort and recovery must not retract it. + RetainForSettlement, +} + /// Builder for [`CapabilityLifecycle`]. pub struct CapabilityLifecycleBuilder { owner: Option, @@ -289,6 +337,9 @@ pub struct CapabilityLifecycleBuilder { durable: Option>, approval: Option>, cancellation: Option>, + call_cancellation: Option>, + defer_lease_abort: bool, + published_token_policy: PublishedTokenPolicy, generation: u64, } @@ -305,6 +356,9 @@ impl Default for CapabilityLifecycleBuilder { durable: None, approval: None, cancellation: None, + call_cancellation: None, + defer_lease_abort: false, + published_token_policy: PublishedTokenPolicy::Abort, generation: 1, } } @@ -361,6 +415,31 @@ impl CapabilityLifecycleBuilder { self } + /// Installs a call-scoped cancellation source. Legacy builders may omit it; + /// every call stays active by default. + pub fn call_cancellation(mut self, call_cancellation: Arc) -> Self { + self.call_cancellation = Some(call_cancellation); + self + } + + /// Declares that the owner settles every call through + /// [`CapabilityLifecycle::settle_call_with_receipt`] and therefore must not + /// receive host-state abort leases. The standalone MCP executor sets this; + /// managed/gateway builders keep the default and their RAII abort leases. + pub fn defer_lease_abort(mut self, defer: bool) -> Self { + self.defer_lease_abort = defer; + self + } + + /// Selects how abort and recovery treat a token whose effect already + /// crossed its publication fence. The manager/agent-run default is + /// [`PublishedTokenPolicy::Abort`]; only the standalone MCP executor + /// enables [`PublishedTokenPolicy::RetainForSettlement`]. + pub fn published_token_policy(mut self, policy: PublishedTokenPolicy) -> Self { + self.published_token_policy = policy; + self + } + pub fn generation(mut self, generation: u64) -> Self { self.generation = generation; self @@ -416,9 +495,35 @@ impl CapabilityLifecycleBuilder { cancellation: self .cancellation .unwrap_or_else(|| Arc::new(NeverCancelled)), + call_cancellation: self + .call_cancellation + .unwrap_or_else(|| Arc::new(AllowAllCallCancellation)), + defer_lease_abort: self.defer_lease_abort, + published_token_policy: self.published_token_policy, generation: AtomicU64::new(self.generation), call_count: AtomicU64::new(0), token_states: Mutex::new(HashMap::new()), + preparing_calls: Mutex::new(HashSet::new()), + prepare_gates: Mutex::new(PrepareGates::default()), + recovery_pending: Mutex::new(Vec::new()), + #[cfg(any(test, feature = "workspace-io-fault"))] + settle_snapshot_observer: Mutex::new(None), + #[cfg(any(test, feature = "workspace-io-fault"))] + admission_recheck_observer: Mutex::new(None), + #[cfg(any(test, feature = "workspace-io-fault"))] + recovery_pre_generation_observer: Mutex::new(None), + #[cfg(any(test, feature = "workspace-io-fault"))] + recovery_entry_observer: Mutex::new(None), + #[cfg(any(test, feature = "workspace-io-fault"))] + settle_commit_observer: Mutex::new(None), + #[cfg(any(test, feature = "workspace-io-fault"))] + settle_unpublished_observer: Mutex::new(None), + #[cfg(any(test, feature = "workspace-io-fault"))] + publisher_copy_observer: Mutex::new(None), + #[cfg(any(test, feature = "workspace-io-fault"))] + commit_attempt_observer: Mutex::new(None), + #[cfg(any(test, feature = "workspace-io-fault"))] + commit_decision_observer: Mutex::new(None), }), }) } @@ -428,15 +533,981 @@ enum TokenState { Open { claims: Box, resources: Vec>, + /// One authoritative per-call publication fence. The first effect that + /// crosses it owns the irreversible native point; a later cancellation + /// can no longer invalidate that effect's canonical receipt. + fence: Arc>, }, + /// The call-wide terminal decision is taken and its single durable write + /// is still in progress. + /// + /// The token is neither open nor terminal: its fence is already closed so + /// a publisher that copied it is refused, but a concurrent settlement must + /// observe retained ownership and the exact retry disposition rather than + /// NoOp. On durable success this becomes `Committed`/`Interrupted`; on + /// failure the original open token is restored so its owner keeps the + /// retry. + PendingWrite(Box), Committed { call_id: String, + /// Tool identity retained so the committed payload can be read back + /// through the durable replay boundary. + tool_name: String, }, Interrupted { call_id: String, }, } +/// Token material held while one call's durable terminal write is in flight. +#[derive(Clone)] +struct PendingTerminal { + call_id: String, + /// Exact caller-visible disposition the pending decision selected: the + /// receipt being persisted for a commit, or the bytes an interrupt will + /// report. A second settler returns this instead of deriving new bytes. + retry: Option, + claims: Box, + resources: Vec>, + fence: Arc>, + /// Whether the token had published before the terminal decision, so the + /// commit arm releases only its unpublished siblings' resources. + published: bool, +} + +/// Terminal state one successful pending write installs for its tokens. +#[derive(Clone, Copy)] +enum PendingTerminalState { + Committed, + Interrupted, +} + +/// Exclusive owner of one in-flight call-wide terminal write. +/// +/// The terminal decision removes every open token into this owner and +/// installs [`TokenState::PendingWrite`] for each while it still holds the +/// token-state lock and every contributor fence. From that point the owner is +/// the only writer allowed to finish the call: +/// +/// - [`Self::finish`] installs the durable terminal state and hands the closed +/// entries back so exactly the resources that failed to bind are released. +/// - [`Self::reopen`] restores every original open token, with its claims, +/// resources and an unclosed fence, so the owner keeps the retry. +/// - `Drop` reopens whatever was not finished, so a panic in resource release +/// or in the durable callback can never strand a `PendingWrite` token with no +/// writer left to finish it. +/// +/// Resources are therefore held until the durable write acknowledges: an +/// interrupt that fails reopens the token with the very resources it owned, +/// and a commit releases only the resources of siblings that never published. +struct PendingTerminalWrite<'a> { + lifecycle: &'a CapabilityLifecycle, + closing: Vec<(String, PendingTerminal)>, + finished: bool, +} + +impl<'a> PendingTerminalWrite<'a> { + fn new(lifecycle: &'a CapabilityLifecycle, closing: Vec<(String, PendingTerminal)>) -> Self { + Self { + lifecycle, + closing, + finished: false, + } + } + + /// Installs the pending state while the caller still holds the token-state + /// lock and every contributor fence. + fn install(&self, states: &mut HashMap) { + for (token, pending) in &self.closing { + states.insert( + token.clone(), + TokenState::PendingWrite(Box::new(pending.clone())), + ); + } + } + + /// Count of tokens this write owns. + fn len(&self) -> usize { + self.closing.len() + } + + /// Installs the durable terminal state and returns the closed entries. + /// + /// The owner stays armed until every terminal state is installed, so a + /// panic during installation reopens only the tokens still pending. + fn finish(mut self, terminal: PendingTerminalState) -> Vec<(String, PendingTerminal)> { + let mut states = self.lifecycle.inner.token_states.lock(); + for (token, pending) in &self.closing { + let still_pending = matches!( + states.get(token), + Some(TokenState::PendingWrite(current)) if current.call_id == pending.call_id + ); + if !still_pending { + continue; + } + let next = match terminal { + PendingTerminalState::Committed => TokenState::Committed { + call_id: pending.call_id.clone(), + tool_name: pending.claims.tool_name.clone(), + }, + PendingTerminalState::Interrupted => TokenState::Interrupted { + call_id: pending.call_id.clone(), + }, + }; + states.insert(token.clone(), next); + } + drop(states); + self.finished = true; + std::mem::take(&mut self.closing) + } + + /// Restores every token this write closed. + fn reopen(mut self) { + self.lifecycle.reopen_pending_tokens(&self.closing); + self.finished = true; + } +} + +impl Drop for PendingTerminalWrite<'_> { + fn drop(&mut self) { + if self.finished { + return; + } + self.lifecycle.reopen_pending_tokens(&self.closing); + } +} + +/// One call id whose durable start is being persisted. +/// +/// Inserting the call id into [`LifecycleInner::preparing_calls`] before the +/// durable write and removing it afterwards keeps exactly one durable start +/// per call without holding the shared token-state lock across persistence. +/// Dropping the reservation without [`Self::commit`] releases the call id, so +/// a failed or panicking start can be retried by a later prepare. +struct StartReservation<'a> { + lifecycle: &'a CapabilityLifecycle, + call_id: String, + committed: bool, +} + +impl<'a> StartReservation<'a> { + fn new(lifecycle: &'a CapabilityLifecycle, call_id: String) -> Self { + Self { + lifecycle, + call_id, + committed: false, + } + } + + fn commit(mut self) { + self.committed = true; + self.lifecycle + .inner + .preparing_calls + .lock() + .remove(&self.call_id); + } +} + +impl Drop for StartReservation<'_> { + fn drop(&mut self) { + if self.committed { + return; + } + self.lifecycle + .inner + .preparing_calls + .lock() + .remove(&self.call_id); + } +} + +/// Cross-call ordering for native effect records. The executor reads the +/// authoritative effect of a call back as its settlement result, so the order +/// must be deterministic even when token storage is a `HashMap`. +static PUBLICATION_SEQUENCE: AtomicU64 = AtomicU64::new(1); + +/// Irreversible native primitive that crossed a call's publication fence. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum NativeEffectKind { + /// An atomic destination replacement (file write or patch). + AtomicWrite, + /// An artifact object was inserted into the bounded store. + ArtifactStore, + /// An operating-system child process was spawned. + ProcessSpawn, +} + +/// Terminal disposition of one native effect. `Indeterminate` and `Restored` +/// are recorded as `Failed` with an explicit marker so a failed effect can +/// never be presented as an artifact-only success. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum NativeEffectStatus { + Ok, + Failed, +} + +/// Bounded error carried by a native effect record. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct NativeEffectError { + pub code: String, + pub message: Option, +} + +/// Identity of one artifact stored by a crossing primitive. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct NativeArtifactIdentity { + pub id: String, + pub len: usize, + pub hash: String, +} + +/// Bounded write identity recorded by an atomic destination replacement. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct NativeWriteOutcome { + pub len: usize, + pub hash: String, + pub durable: bool, + pub staging_cleaned: bool, +} + +/// Observed process state of one OS spawn. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum NativeProcessState { + Running, + Exited { code: Option }, + Signaled { signal: i32 }, + Unknown, +} + +/// One OS spawn identity and its last observed process state. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct NativeProcessOutcome { + pub pid: u32, + pub background: bool, + pub state: NativeProcessState, +} + +/// Observed file type of a post-rename directory entry. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum NativeObservedFileType { + File, + Directory, + Symlink, + Other, +} + +/// Observed device/inode identity of a post-rename directory entry. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct NativeObservedIdentity { + pub file_type: NativeObservedFileType, + pub device: u64, + pub inode: u64, +} + +/// Evidence recorded when a rename succeeded but its post-rename readback +/// failed. `temp_completed` records that the temporary guard was already +/// marked complete, so the effect may exist even though it could not be +/// classified. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct NativeIndeterminateEvidence { + pub destination: Option, + pub staging: Option, + pub temp_completed: bool, +} + +/// One complete typed native effect outcome. +/// +/// Every irreversible primitive that crosses its call's publication fence +/// writes exactly one of these into the call's ledger. The record is never a +/// fragment: an atomic write carries its bounded write identity, an artifact +/// store carries the artifact id/length/hash, and an OS spawn carries the +/// exact pid plus its observed running/exited/signaled state. Post-rename +/// readback failures and restored directory exchanges are explicit failed +/// outcomes with their observed evidence. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct NativeEffectRecord { + pub effect: NativeEffectKind, + pub status: NativeEffectStatus, + pub error: Option, + pub artifacts: Vec, + pub write: Option, + pub process: Option, + pub indeterminate: Option, + /// The exchange happened and a proven reverse exchange restored the + /// destination directory. The net effect is not published, but the + /// primitive did cross the fence and must not look unpublished. + pub restored: bool, +} + +const MAX_EFFECT_ERROR_CODE_BYTES: usize = 48; +const MAX_EFFECT_ERROR_MESSAGE_BYTES: usize = 96; + +fn bounded_effect_text(value: &str, limit: usize) -> String { + if value.len() <= limit { + return value.to_string(); + } + let mut end = limit; + while !value.is_char_boundary(end) { + end -= 1; + } + value[..end].to_string() +} + +impl NativeEffectError { + fn bounded(code: &str, message: Option<&str>) -> Self { + Self { + code: bounded_effect_text(code, MAX_EFFECT_ERROR_CODE_BYTES), + message: message + .map(|message| bounded_effect_text(message, MAX_EFFECT_ERROR_MESSAGE_BYTES)), + } + } +} + +impl NativeEffectRecord { + /// Successful atomic destination replacement. + pub fn atomic_write(outcome: NativeWriteOutcome) -> Self { + Self { + effect: NativeEffectKind::AtomicWrite, + status: NativeEffectStatus::Ok, + error: None, + artifacts: Vec::new(), + write: Some(outcome), + process: None, + indeterminate: None, + restored: false, + } + } + + /// Rename succeeded but the post-rename readback could not classify it. + pub fn atomic_write_indeterminate( + write: Option, + evidence: NativeIndeterminateEvidence, + ) -> Self { + Self { + effect: NativeEffectKind::AtomicWrite, + status: NativeEffectStatus::Failed, + error: Some(NativeEffectError::bounded( + "publication_indeterminate", + Some("write publication could not be classified"), + )), + artifacts: Vec::new(), + write, + process: None, + indeterminate: Some(evidence), + restored: false, + } + } + + /// Exchange happened, then a proven reverse exchange restored the + /// destination directory. + pub fn atomic_write_restored( + write: NativeWriteOutcome, + evidence: NativeIndeterminateEvidence, + ) -> Self { + Self { + effect: NativeEffectKind::AtomicWrite, + status: NativeEffectStatus::Failed, + error: Some(NativeEffectError::bounded( + "publication_restored", + Some("write publication was restored after an exchange"), + )), + artifacts: Vec::new(), + write: Some(write), + process: None, + indeterminate: Some(evidence), + restored: true, + } + } + + /// Successful artifact store. + pub fn artifact_store(artifact: NativeArtifactIdentity) -> Self { + Self { + effect: NativeEffectKind::ArtifactStore, + status: NativeEffectStatus::Ok, + error: None, + artifacts: vec![artifact], + write: None, + process: None, + indeterminate: None, + restored: false, + } + } + + /// Successful OS spawn, observed running immediately after the syscall. + pub fn process_spawn(pid: u32, background: bool) -> Self { + Self { + effect: NativeEffectKind::ProcessSpawn, + status: NativeEffectStatus::Ok, + error: None, + artifacts: Vec::new(), + write: None, + process: Some(NativeProcessOutcome { + pid, + background, + state: NativeProcessState::Running, + }), + indeterminate: None, + restored: false, + } + } + + /// Replace the terminal failure of an already recorded effect exactly once. + pub(crate) fn mark_failed(&mut self, code: &str, message: Option<&str>) { + if self.status == NativeEffectStatus::Ok { + self.status = NativeEffectStatus::Failed; + self.error = Some(NativeEffectError::bounded(code, message)); + } + } + + /// Record a later observed process state without downgrading a terminal + /// state back to `Running`. + pub(crate) fn observe_process(&mut self, state: NativeProcessState) { + let Some(process) = self.process.as_mut() else { + return; + }; + if matches!(process.state, NativeProcessState::Running) { + process.state = state; + } + } +} + +/// The authoritative typed outcome of one call plus its call-level fence +/// observations. `record` is complete; `artifacts` may aggregate identities +/// stored by later effects of the same call. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct NativeEffectOutcome { + pub record: NativeEffectRecord, + pub artifacts: Vec, + pub cancel_requested: bool, + pub deadline_elapsed: bool, +} + +impl NativeEffectOutcome { + /// Canonical model-visible result for a call whose guest never committed. + /// + /// The record's terminal status is authoritative. A foreground process + /// spawn that is settled after cancellation/deadline remains a typed + /// failure whose data still carries the real pid and process state; a + /// background spawn keeps its complete success receipt. An artifact-only + /// OK record can never replace a failed or indeterminate terminal record. + pub fn to_tool_result(&self, output_budget: usize) -> ToolResult { + let record = &self.record; + let data = effect_data(record); + let artifacts = merged_artifact_ids(record, &self.artifacts); + let result = match record.status { + NativeEffectStatus::Failed => { + let error = record.error.as_ref(); + ToolResult::failure_with( + error.map_or("effect_failed", |error| error.code.as_str()), + error + .and_then(|error| error.message.clone()) + .unwrap_or_default(), + "", + data, + false, + ) + } + NativeEffectStatus::Ok => { + let completed_successfully = record.process.is_some_and(|process| { + matches!(process.state, NativeProcessState::Exited { code: Some(0) }) + }); + if record.effect == NativeEffectKind::ProcessSpawn + && !record.process.is_some_and(|process| process.background) + && !completed_successfully + && (self.cancel_requested || self.deadline_elapsed) + { + let (code, message) = if self.deadline_elapsed { + ("deadline_elapsed", "tool call deadline elapsed") + } else { + ("cancelled", "tool call was cancelled") + }; + ToolResult::failure_with(code, message, "", data, false) + } else { + let content = match record.effect { + NativeEffectKind::ArtifactStore => record + .artifacts + .first() + .map(|artifact| format!("artifact {}", artifact.id)) + .unwrap_or_default(), + _ => String::new(), + }; + ToolResult::success(content, data) + } + } + }; + let mut result = result; + result.artifacts = artifacts; + result.compact_to_bytes(output_budget) + } +} + +/// JSON data describing the authoritative native effect. Later callers may +/// compact this at the typed byte boundary; they never synthesize a fragment. +fn effect_data(record: &NativeEffectRecord) -> Value { + let mut data = serde_json::Map::new(); + match record.effect { + NativeEffectKind::AtomicWrite => { + data.insert("effect".to_string(), json!("atomic_write")); + let publication = if record.restored { + "restored" + } else if record.indeterminate.is_some() { + "indeterminate" + } else { + "published" + }; + data.insert("publication".to_string(), json!(publication)); + if let Some(write) = &record.write { + data.insert("len".to_string(), json!(write.len)); + data.insert("hash".to_string(), json!(write.hash)); + data.insert("durable".to_string(), json!(write.durable)); + data.insert("staging_cleaned".to_string(), json!(write.staging_cleaned)); + } + if let Some(evidence) = &record.indeterminate { + data.insert("temp_completed".to_string(), json!(evidence.temp_completed)); + data.insert( + "destination".to_string(), + evidence + .destination + .map(observed_identity_value) + .unwrap_or(Value::Null), + ); + data.insert( + "staging".to_string(), + evidence + .staging + .map(observed_identity_value) + .unwrap_or(Value::Null), + ); + } + } + NativeEffectKind::ArtifactStore => { + data.insert("effect".to_string(), json!("artifact_store")); + if let Some(artifact) = record.artifacts.first() { + data.insert("artifact".to_string(), json!(artifact.id)); + data.insert("len".to_string(), json!(artifact.len)); + data.insert("hash".to_string(), json!(artifact.hash)); + } + } + NativeEffectKind::ProcessSpawn => { + data.insert("effect".to_string(), json!("process_spawn")); + if let Some(process) = &record.process { + data.insert("pid".to_string(), json!(process.pid)); + data.insert("background".to_string(), json!(process.background)); + match process.state { + NativeProcessState::Running => { + data.insert("process_state".to_string(), json!("running")); + } + NativeProcessState::Exited { code } => { + data.insert("process_state".to_string(), json!("exited")); + if let Some(code) = code { + data.insert("exit_code".to_string(), json!(code)); + } + } + NativeProcessState::Signaled { signal } => { + data.insert("process_state".to_string(), json!("signaled")); + data.insert("signal".to_string(), json!(signal)); + } + NativeProcessState::Unknown => { + data.insert("process_state".to_string(), json!("unknown")); + } + } + } + } + } + Value::Object(data) +} + +fn observed_identity_value(identity: NativeObservedIdentity) -> Value { + json!({ + "file_type": match identity.file_type { + NativeObservedFileType::File => "file", + NativeObservedFileType::Directory => "directory", + NativeObservedFileType::Symlink => "symlink", + NativeObservedFileType::Other => "other", + }, + "device": identity.device, + "inode": identity.inode, + }) +} + +fn merged_artifact_ids( + record: &NativeEffectRecord, + aggregated: &[NativeArtifactIdentity], +) -> Vec { + let mut ids: Vec = Vec::new(); + for artifact in record.artifacts.iter().chain(aggregated.iter()) { + if !ids.iter().any(|existing| existing == &artifact.id) { + ids.push(artifact.id.clone()); + } + } + ids +} + +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +enum PublicationPhase { + #[default] + Unpublished, + Publishing, + Published, +} + +#[derive(Clone, Debug, Default)] +struct PublicationFenceState { + phase: PublicationPhase, + cancel_requested: bool, + /// Later effects of this call that hold an inactive publication permit and + /// have not recorded their outcome yet. A recovery (or a settlement from + /// the ledger) must not observe a ledger that is still being appended to, + /// so it skips the call while this is non-zero and reports it pending. + pending_publishers: usize, + /// Complete native effect records written by primitives that crossed this + /// call's fence, in publication order. Settlement chooses the worst + /// terminal outcome and appends every artifact identity; a later artifact + /// record can never replace a failed or indeterminate terminal status. + effects: Vec<(u64, NativeEffectRecord)>, + /// Monotonic version of the ledger this fence describes. Every admission + /// of a later publisher and every recorded or amended effect advances it. + /// A settlement receipt carries the version its snapshot was derived from; + /// a mismatch at the final closure means the receipt no longer describes + /// the whole ledger and must be retained for a retry. + ledger_version: u64, + /// Set under the same fence lock when this token leaves the open state. + /// A publisher that copied this fence before the transition must observe + /// the closure when it finally takes the lock instead of appending to an + /// already settled call. + closed: bool, +} + +/// Ledger snapshot a settlement receipt was derived from. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +struct ReceiptLedgerVersion { + latest_effect: u64, + ledger_version: u64, +} + +/// Canonical caller-visible receipt together with the exact ledger snapshot +/// its bytes describe. +/// +/// [`CapabilityLifecycle::derive_call_receipt`] builds the bytes and the +/// per-token versions under one token-state/fence critical section, so a +/// ledger change can never slip between the read that produced the bytes and +/// the sample that gives them a version. +#[derive(Clone, Debug, PartialEq)] +pub struct CallReceipt { + result: ToolResult, + encoded: Value, + binding: ReceiptBinding, +} + +#[derive(Clone, Debug, PartialEq)] +enum ReceiptBinding { + /// The receipt bytes were derived from the native effect ledger. Each open + /// published token carries the exact version visible at derivation time. + Ledger(Vec<(String, ReceiptLedgerVersion)>), + /// Bytes read back from an already durable committed receipt. They have no + /// live ledger version, so a prepared settlement can never use them to + /// close a published contributor that the durable read never described. + Authoritative, +} + +impl CallReceipt { + fn new(result: ToolResult, binding: ReceiptBinding) -> Self { + let encoded = serde_json::to_value(&result).unwrap_or(Value::Null); + Self { + result, + encoded, + binding, + } + } + + /// The caller-visible result these bytes represent. + pub fn result(&self) -> &ToolResult { + &self.result + } + + /// Exact canonical bytes settlement commits for this receipt. + pub fn encoded(&self) -> &Value { + &self.encoded + } + + /// Receipt from already canonical bytes plus the binding captured with + /// them. The accepted payload is normalized to a typed result before it is + /// exposed or persisted, so the bytes this receipt commits always + /// round-trip through a strict typed replay. Missing optional fields are + /// filled with their canonical defaults; a payload without a canonical + /// `ok`/`content` pair becomes the explicit `internal_error` failure. + fn from_encoded(encoded: Value, binding: ReceiptBinding) -> Self { + let result = serde_json::from_value(encoded.clone()) + .unwrap_or_else(|_| receipt_result_from_canonical_bytes(&encoded)); + Self::new(result, binding) + } +} + +/// Builds the typed result described by a raw canonical receipt. +/// +/// The public raw settlement path accepts the canonical `ok`/`content` shape +/// rather than a fully typed `ToolResult`. Normalizing it here keeps the +/// returned typed result and the bytes persisted to the durable boundary the +/// same representation; a payload outside that canonical shape is an explicit +/// `internal_error` failure, never verbatim unreadable bytes. +fn receipt_result_from_canonical_bytes(encoded: &Value) -> ToolResult { + let Some(object) = encoded.as_object() else { + return ToolResult::failure( + "internal_error", + "settlement receipt is not a typed canonical result", + ); + }; + let Some(ok) = object.get("ok").and_then(Value::as_bool) else { + return ToolResult::failure( + "internal_error", + "settlement receipt is not a typed canonical result", + ); + }; + let content = object + .get("content") + .and_then(Value::as_str) + .unwrap_or("") + .to_string(); + let data = object.get("data").cloned().unwrap_or_else(|| json!({})); + let error = object + .get("error") + .and_then(|value| serde_json::from_value::(value.clone()).ok()); + let truncated = object + .get("truncated") + .and_then(Value::as_bool) + .unwrap_or(false); + let artifacts = object + .get("artifacts") + .and_then(Value::as_array) + .map(|values| { + values + .iter() + .filter_map(Value::as_str) + .map(str::to_string) + .collect() + }) + .unwrap_or_default(); + ToolResult { + ok, + content, + data, + error, + truncated, + artifacts, + replayed: false, + } +} + +/// Ledger binding decision for one published token. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum ReceiptVersion { + /// Validate the receipt against this exact version before closing. + Bound(ReceiptLedgerVersion), + /// The receipt does not describe this token; keep it open. + Missing, +} + +impl PublicationFenceState { + /// Whether this fence's current ledger is exactly the one a receipt + /// version was derived from. A closed fence, a later in-flight publisher, + /// a phase that never published or any appended/amended effect makes the + /// receipt stale; committing it would describe only part of the call. + fn receipt_describes(&self, version: ReceiptVersion) -> bool { + match version { + ReceiptVersion::Bound(snapshot) => { + let latest_effect = self + .effects + .iter() + .map(|(sequence, _)| *sequence) + .max() + .unwrap_or(0); + !self.closed + && self.phase == PublicationPhase::Published + && self.pending_publishers == 0 + && latest_effect <= snapshot.latest_effect + && self.ledger_version == snapshot.ledger_version + } + ReceiptVersion::Missing => false, + } + } + + /// Authoritative record plus every artifact stored by later effects of + /// this call. Any failed/indeterminate/restored record outranks every OK + /// record; among OK records the first non-artifact native terminal is the + /// primary record that later artifacts may only append to. Artifact + /// identities from all effects are merged into the chosen record. + fn authoritative(&self) -> Option<(NativeEffectRecord, Vec)> { + // A failed/indeterminate/restored terminal is always authoritative and + // the earliest such record wins. When every effect succeeded, the + // earliest non-artifact native terminal is the record that a later + // artifact may only append to; an artifact-only call uses its artifact + // record. No later artifact can replace the chosen terminal status or + // the typed identity of the primitive that produced it. + let mut best_failed: Option<(u64, &NativeEffectRecord)> = None; + let mut best_primary: Option<(u64, &NativeEffectRecord)> = None; + let mut best_artifact: Option<(u64, &NativeEffectRecord)> = None; + for (sequence, record) in &self.effects { + match record.status { + NativeEffectStatus::Failed => { + if best_failed.is_none_or(|(best, _)| *sequence < best) { + best_failed = Some((*sequence, record)); + } + } + NativeEffectStatus::Ok if record.effect == NativeEffectKind::ArtifactStore => { + if best_artifact.is_none_or(|(best, _)| *sequence < best) { + best_artifact = Some((*sequence, record)); + } + } + NativeEffectStatus::Ok => { + if best_primary.is_none_or(|(best, _)| *sequence < best) { + best_primary = Some((*sequence, record)); + } + } + } + } + let (_, record) = best_failed.or(best_primary).or(best_artifact)?; + let mut artifacts = Vec::new(); + for (_, effect) in &self.effects { + for artifact in &effect.artifacts { + if !artifacts + .iter() + .any(|existing: &NativeArtifactIdentity| existing.id == artifact.id) + { + artifacts.push(artifact.clone()); + } + } + } + let mut record = record.clone(); + record.artifacts = artifacts.clone(); + Some((record, artifacts)) + } +} + +/// Outcome of one authoritative call settlement. +/// +/// Exactly one terminal decision is taken for the whole call over the live +/// token set: `Committed` writes one receipt, `Interrupted` closes every open +/// token without a receipt, `Retained` leaves every open token in place for a +/// later retry, and `NoOp` finds no open token. An interrupt and a receipt +/// commit are never mixed for one call. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct CallSettlement { + pub decision: CallTerminalDecision, + /// Exact caller-visible bytes the decision selected, together with the + /// ledger snapshot they were derived from or validated against. For a + /// retained decision this is the disposition a later retry must reuse. + pub result: Option, + pub interrupted: usize, + pub committed: usize, + pub retained: usize, +} + +/// One call-wide terminal decision. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub enum CallTerminalDecision { + /// No open token belongs to the call. + #[default] + NoOp, + /// Every open token was unpublished; the call closed without a receipt. + Interrupted, + /// One canonical receipt is the terminal outcome of the whole call. + Committed, + /// A publisher is still crossing the fence or the supplied receipt no + /// longer describes every contributor; nothing was closed. + Retained, +} + +/// Input facts one terminal decision is asked to settle. +#[derive(Clone, Copy)] +pub enum CallTerminalRequest<'a> { + /// Caller-visible canonical bytes that are not a native derivation (guest + /// result or caller-supplied receipt). Their ledger versions are captured + /// in the same critical section that decides the call. + Caller(&'a Value), + /// Synthetic cancellation/deadline bytes. They are returned to the caller + /// only while nothing published; a published contributor always wins and + /// the terminal bytes are derived from the live ledger instead. + Synthetic(&'a Value), + /// Guest `tool_commit` bytes. They always decide a receipt commit for the + /// whole call, even when no native effect published, but the decision + /// retains instead of freezing while any publisher still holds a permit. + /// The ledger versions they describe are captured in the same critical + /// section that decides the call. + GuestCommit(&'a Value), + /// Bytes and versions captured earlier by [`CapabilityLifecycle::derive_call_receipt`]. + /// The decision refuses the receipt if any live contributor advanced. + Prepared(&'a CallReceipt), + /// No caller bytes: derive the authoritative native receipt from the live + /// ledger. A call with no published contributor is interrupted. + Derived, +} + +/// Exclusive right to cross one call's publication fence. +/// +/// The permit is returned only after all cancellation/deadline/generation +/// checks were evaluated under the same lock that a cancellation request +/// uses. The caller then performs the real native publication and reports +/// [`PublicationPermit::published`]; until that call the fence stays +/// unpublished, so a failed or refused effect can never be mistaken for a +/// committed one. +pub struct PublicationPermit { + fence: Arc>, + active: bool, + /// This permit is a later effect that was counted as an in-flight + /// publisher, so every exit path (recorded, refused, or unwound) must + /// decrement that count. + counted: bool, +} + +impl PublicationPermit { + /// Records that the irreversible native effect really published and stores + /// its complete typed outcome. + /// + /// Every crossing primitive writes exactly one complete record: an atomic + /// write carries its identity, an artifact store its id/len/hash, and an + /// OS spawn its pid and observed process state. A later effect of the same + /// call receives an inactive permit and still records its outcome; only + /// its artifacts are merged into the authoritative terminal record. + pub fn published_effect(mut self, record: NativeEffectRecord) { + self.finish(Some(record)); + } + + fn finish(&mut self, record: Option) { + let mut state = self.fence.lock(); + if self.active { + state.phase = PublicationPhase::Published; + self.active = false; + } + if self.counted { + state.pending_publishers = state.pending_publishers.saturating_sub(1); + self.counted = false; + } + if let Some(record) = record { + let sequence = PUBLICATION_SEQUENCE.fetch_add(1, Ordering::SeqCst); + state.effects.push((sequence, record)); + state.ledger_version = state.ledger_version.saturating_add(1); + } + } +} + +impl Drop for PublicationPermit { + fn drop(&mut self) { + if !self.active && !self.counted { + return; + } + let mut state = self.fence.lock(); + if self.active && state.phase == PublicationPhase::Publishing { + state.phase = PublicationPhase::Unpublished; + } + self.active = false; + if self.counted { + state.pending_publishers = state.pending_publishers.saturating_sub(1); + self.counted = false; + } + } +} + /// Resource bound to an open execution token. Released on interrupt, not on commit. pub(crate) trait TokenOwnedResource: Send + Sync { fn release(&self); @@ -450,51 +1521,1587 @@ fn release_resources(resources: Vec>) { for resource in resources { resource.release(); } -} +} + +fn token_call_id(state: &TokenState) -> &str { + match state { + TokenState::Open { claims, .. } => claims.call_id.as_str(), + TokenState::PendingWrite(pending) => pending.call_id.as_str(), + TokenState::Committed { call_id, .. } => call_id.as_str(), + TokenState::Interrupted { call_id } => call_id.as_str(), + } +} + +/// Claims and fence of a token that is not terminal, whether it is still open +/// or its terminal write is pending. Both states own a live publication +/// ledger that observers of a call may read. +fn token_live_parts( + state: &TokenState, +) -> Option<(&TokenClaims, &Arc>)> { + match state { + TokenState::Open { claims, fence, .. } => Some((claims, fence)), + TokenState::PendingWrite(pending) => Some((&pending.claims, &pending.fence)), + TokenState::Committed { .. } | TokenState::Interrupted { .. } => None, + } +} + +/// Test-only observer that receives the token a seam is about to act on. +#[cfg(any(test, feature = "workspace-io-fault"))] +type TokenObserver = Arc; + +struct LifecycleInner { + owner: CapabilityOwner, + registry_identity: String, + workspace: PathBuf, + limits: LifecycleLimits, + deadline_ms: u64, + clock: Arc, + tokens: Arc, + durable: Arc, + approval: Arc, + cancellation: Arc, + call_cancellation: Arc, + defer_lease_abort: bool, + published_token_policy: PublishedTokenPolicy, + generation: AtomicU64, + call_count: AtomicU64, + token_states: Mutex>, + /// Call ids whose durable start is being persisted. `prepare` inserts its + /// call id before it releases every lock for `commit_started`, so a second + /// prepare of that call cannot write a second start; other calls never + /// wait on this set or on the durable write. + preparing_calls: Mutex>, + /// Call-scoped gates at the durable prepare boundary. + /// + /// Each call owns its own gate, so a prepare, approval validation or + /// cancellation of one call never waits on another call's durable write. + /// A gate is created by a prepare or by a cancellation recorded before the + /// call prepared; a completed prepare drops it again, so the map stays + /// bounded by the in-flight prepares plus the cancelled-call budget. + prepare_gates: Mutex, + /// Calls the last recovery attempt could not claim because a publisher was + /// still in flight. The owner observes them as pending and retries + /// instead of treating a successful-but-partial recovery as complete. + recovery_pending: Mutex>, + /// Test-only seam at the entry of the call-wide terminal decision, before + /// the live token set is read. A test can publish inside this window and + /// prove the publication is part of the one snapshot the decision takes. + #[cfg(any(test, feature = "workspace-io-fault"))] + settle_snapshot_observer: Mutex>>, + /// Test-only seam between a later effect's `ensure_call_active` pass and + /// the final fence revalidation that counts it as an in-flight publisher. + #[cfg(any(test, feature = "workspace-io-fault"))] + admission_recheck_observer: Mutex>>, + /// Test-only seam after recovery released its per-call claims and before + /// it advances the generation. + #[cfg(any(test, feature = "workspace-io-fault"))] + recovery_pre_generation_observer: Mutex>>, + /// Test-only seam at the entry of a recovery attempt, before any token + /// state is read. + #[cfg(any(test, feature = "workspace-io-fault"))] + recovery_entry_observer: Mutex>>, + /// Test-only seam of a settlement commit while it holds the publication + /// fence, after the ledger validation and before the token closure. + #[cfg(any(test, feature = "workspace-io-fault"))] + settle_commit_observer: Mutex>>, + /// Test-only seam of the unpublished-arm decision. In the settlement it + /// runs while the fence is still held; the fence is never released between + /// the phase decision and the token closure. + #[cfg(any(test, feature = "workspace-io-fault"))] + settle_unpublished_observer: Mutex>>, + /// Test-only seam after a publisher copied its fence and before it locks + /// it. A settlement can then be proven to win the fence atomically. + #[cfg(any(test, feature = "workspace-io-fault"))] + publisher_copy_observer: Mutex>>, + /// Test-only seam at the entry of a retention-mode guest commit, before + /// the token state is read. A test can hold a publisher permit on the + /// exact token while the guest reaches `tool_commit`. + #[cfg(any(test, feature = "workspace-io-fault"))] + commit_attempt_observer: Mutex>, + /// Test-only seam immediately after a retention-mode guest commit is + /// decided and before the guest receives its envelope. A test can finish + /// a publication that was refused by the decision. + #[cfg(any(test, feature = "workspace-io-fault"))] + commit_decision_observer: Mutex>, +} + +/// Admission into one call's durable prepare boundary. +/// +/// The gate belongs to exactly one call id. `admission` admits one prepare +/// into the boundary section. The cancelled-before-prepare ledger deliberately +/// does *not* live here: a cancellation request records it in +/// [`PrepareGates::cancelled`] under the same map lock a prepare takes for its +/// lookup and retirement, so setting the flag and removing the entry can never +/// be reordered. A cancellation therefore never waits on this call's durable +/// write (and, because the gate is per call, never on another call's either). +struct PrepareGate { + /// Held across the final per-call cancellation read and the durable + /// parent insert, so exactly one prepare for this call crosses the + /// boundary at a time. + admission: Mutex<()>, +} + +impl Default for PrepareGate { + fn default() -> Self { + Self { + admission: Mutex::new(()), + } + } +} + +/// Call-scoped prepare gates and the lifecycle's own cancellation ledger. +/// +/// Unlike a lifecycle-wide fence, nothing here is held across a durable write: +/// the map lock only covers lookups, insertion, the cancellation ledger and +/// removal of per-call gates. +#[derive(Default)] +struct PrepareGates { + /// One admission gate per call id whose prepare is still able to cross the + /// boundary. An entry is retired only when its prepare is the last holder + /// and its token exists (or that prepare gave up), so every prepare of one + /// call id shares exactly one mutex and the map stays bounded by the + /// concurrent prepares. + calls: HashMap>, + /// Call ids whose cancellation arrived while no open token existed, i.e. + /// before the durable prepare. This is the lifecycle's shared + /// cancellation source: every [`CapabilityLifecycle::check_call_cancellation`] + /// reads it, so the cancellation is observed by the default source too, + /// not only by an owner that installs a per-call one. It is bounded by the + /// lifetime call limit; if it is ever exhausted the ledger seals and every + /// later prepare is refused, which is the safe direction for a + /// durable-effect boundary. + cancelled: HashSet, + sealed: bool, + /// Test-only: how many admission gates were ever created. A same-call + /// prepare that is refused before the boundary must not create a second + /// gate for the call id. + #[cfg(any(test, feature = "workspace-io-fault"))] + created: u64, +} + +/// One prepare's reference to its call's gate. +/// +/// The gate stays in the call's map entry while this lease lives, which is from +/// the durable boundary through the token handoff. Dropping the lease retires +/// the entry only when this prepare is the last holder. +struct PrepareGateLease { + inner: Arc, + call_id: String, + gate: Arc, +} + +impl PrepareGateLease { + /// Retires the call's gate now that the token exists and owns the call. + /// + /// Consumes the lease, so the retirement runs exactly once and only after + /// the handoff. + fn retire(self) { + // Dropping the lease here runs `retire_prepare_gate`. + } +} + +impl Drop for PrepareGateLease { + fn drop(&mut self) { + retire_prepare_gate(&self.inner, &self.call_id, &self.gate); + } +} + +/// Retires one call's gate when this prepare is its last holder. +/// +/// Two references are the map's and this prepare's. While another prepare +/// still holds the gate, the entry stays, so every prepare of one call id keeps +/// sharing exactly one admission mutex; the last prepare to finish removes it. +fn retire_prepare_gate(inner: &LifecycleInner, call_id: &str, gate: &Arc) { + let mut gates = inner.prepare_gates.lock(); + let current = gates + .calls + .get(call_id) + .is_some_and(|existing| Arc::ptr_eq(existing, gate)); + if current && Arc::strong_count(gate) == 2 { + gates.calls.remove(call_id); + } +} + +/// Atomic lifetime-call reservation. The counter is incremented before any +/// approval or effect preparation and released if prepare fails afterwards. +struct CallSlotReservation { + inner: Arc, + committed: bool, +} + +impl CallSlotReservation { + fn reserve(inner: &Arc) -> Result { + inner + .call_count + .try_update(Ordering::SeqCst, Ordering::SeqCst, |count| { + (count < inner.limits.max_tool_calls).then_some(count + 1) + }) + .map_err(|_| LifecycleError::LimitExceeded)?; + Ok(Self { + inner: Arc::clone(inner), + committed: false, + }) + } + + fn commit(mut self) { + self.committed = true; + } +} + +impl Drop for CallSlotReservation { + fn drop(&mut self) { + if !self.committed { + self.inner.call_count.fetch_sub(1, Ordering::SeqCst); + } + } +} + +/// Run-scoped generic tool lifecycle engine. +#[derive(Clone)] +pub struct CapabilityLifecycle { + inner: Arc, +} + +impl CapabilityLifecycle { + pub fn builder() -> CapabilityLifecycleBuilder { + CapabilityLifecycleBuilder::default() + } + + /// Frozen workspace path captured at admission. + pub fn workspace(&self) -> &Path { + &self.inner.workspace + } + + /// Registry identity captured when this lifecycle was admitted. + pub fn registry_identity(&self) -> &str { + &self.inner.registry_identity + } + + /// True when the owner is the authoritative settlement path, so hosts must + /// not hold an abort lease for prepared tokens. + pub fn defers_lease_abort(&self) -> bool { + self.inner.defer_lease_abort + } + + /// True when this lifecycle keeps a published token open for the owner's + /// canonical settlement instead of interrupting it on abort/recovery. + pub fn retains_published_tokens(&self) -> bool { + self.inner.published_token_policy == PublishedTokenPolicy::RetainForSettlement + } + + fn check_call_cancellation(&self, call_id: &str) -> Result<(), LifecycleError> { + // The prepare ledger is the lifecycle's shared source: a cancellation + // recorded before the call's token existed is observed here by every + // later prepare, validation, publication and settlement check, not only + // by an owner that installed its own per-call source. A sealed ledger + // cannot prove that this call's intent was ever recorded, so it fails + // closed here even when the owner's cancellation source is the default + // one and reports `Active`. + { + let gates = self.inner.prepare_gates.lock(); + if gates.sealed || gates.cancelled.contains(call_id) { + return Err(LifecycleError::Cancelled); + } + } + match self.inner.call_cancellation.call_state(call_id) { + CallCancellationState::Active => Ok(()), + CallCancellationState::Cancelled => Err(LifecycleError::Cancelled), + CallCancellationState::DeadlineElapsed => Err(LifecycleError::DeadlineElapsed), + } + } + + /// Crosses the durable prepare boundary for one call. + /// + /// The gate is call-scoped: it admits exactly one prepare for this call and + /// is never shared with another call, so a prepare, approval validation or + /// cancellation of a different call never waits behind this call's durable + /// write. + /// + /// The final per-call cancellation read and `prepare_parent` run under the + /// gate, and the gate stays in the call's map entry until the returned + /// lease is dropped after the token handoff. A cancellation recorded before + /// the boundary therefore cannot enter the durable prepare, while one + /// recorded after the gate was entered belongs to the token's publication + /// fence: it is stored in the shared prepare ledger and transferred to the + /// fence when the token is created. + fn prepare_parent_for_call( + &self, + run_id: &str, + call_id: &str, + tool_name: &str, + ) -> Result { + let gate = self.prepare_gate(call_id); + let outcome = { + let _admission = gate.admission.lock(); + self.cross_prepare_boundary(call_id, run_id, tool_name) + }; + let lease = PrepareGateLease { + inner: Arc::clone(&self.inner), + call_id: call_id.to_string(), + gate, + }; + outcome.map(|()| lease) + } + + /// One attempt at the durable boundary, with the call's gate held. + fn cross_prepare_boundary( + &self, + call_id: &str, + run_id: &str, + tool_name: &str, + ) -> Result<(), LifecycleError> { + // A sealed ledger means the cancelled-before-prepare set overflowed, + // so this lifecycle can no longer prove that no cancellation arrived + // first. The cancellation read is part of one critical section that no + // later removal can reorder: the flag lives in this map, not in the + // gate, so retiring a gate can never lose it. + let refused = { + let gates = self.inner.prepare_gates.lock(); + gates.sealed || gates.cancelled.contains(call_id) + }; + if refused { + return Err(LifecycleError::Cancelled); + } + self.check_call_cancellation(call_id)?; + // The boundary is crossed; a later cancellation belongs to the token's + // publication fence, not to this one. + self.inner + .durable + .prepare_parent(run_id, call_id, tool_name) + } + + /// Reserves one call id for the whole prepare, from before the durable + /// boundary through the token handoff. + /// + /// The existing-reservation check, the live-token check and the insertion + /// share the `preparing_calls` lock, so a concurrent or late prepare of the + /// same call id is refused before it can create a second admission gate or + /// write a second durable start. A committed or interrupted token is left + /// to the replay/unresolved checks of `prepare`, so a completed call still + /// replays instead of being refused here. + fn begin_prepare_call(&self, call_id: &str) -> Result, LifecycleError> { + let mut preparing = self.inner.preparing_calls.lock(); + if preparing.contains(call_id) { + return Err(LifecycleError::UnresolvedCall); + } + { + let states = self.inner.token_states.lock(); + if states.values().any(|state| { + token_call_id(state) == call_id + && matches!(state, TokenState::Open { .. } | TokenState::PendingWrite(_)) + }) { + return Err(LifecycleError::UnresolvedCall); + } + } + preparing.insert(call_id.to_string()); + drop(preparing); + Ok(StartReservation::new(self, call_id.to_string())) + } + + /// The gate of one call, created on first use. + /// + /// Entry creation by a prepare is bounded by the concurrent prepares + /// because the prepare retires its own entry again after the token handoff. + fn prepare_gate(&self, call_id: &str) -> Arc { + let mut gates = self.inner.prepare_gates.lock(); + if let Some(gate) = gates.calls.get(call_id) { + return Arc::clone(gate); + } + let gate = Arc::new(PrepareGate::default()); + gates.calls.insert(call_id.to_string(), Arc::clone(&gate)); + #[cfg(any(test, feature = "workspace-io-fault"))] + { + gates.created = gates.created.saturating_add(1); + } + gate + } + + /// Test-only: the number of admission gates ever created, the number still + /// alive in the map, and the cancelled-ledger size/seal state. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn prepare_gate_state_for_test(&self) -> (u64, usize, usize, bool) { + let gates = self.inner.prepare_gates.lock(); + ( + gates.created, + gates.calls.len(), + gates.cancelled.len(), + gates.sealed, + ) + } + + /// Records a cancellation for a call whose durable prepare has not + /// happened yet. Never takes a gate, so it cannot wait on durable I/O. + fn record_prepare_cancellation(&self, call_id: &str) { + let capacity = usize::try_from(self.inner.limits.max_tool_calls).unwrap_or(usize::MAX); + let mut gates = self.inner.prepare_gates.lock(); + if gates.sealed || gates.cancelled.contains(call_id) { + return; + } + if gates.cancelled.len() >= capacity { + // Never forget an accepted cancellation: seal the ledger so every + // later prepare is refused instead of crossing unproven. + gates.sealed = true; + return; + } + gates.cancelled.insert(call_id.to_string()); + } + + /// Revalidates an already authorized token immediately before a native + /// effect. Call-scoped cancellation and deadline are checked alongside the + /// lifecycle-wide shutdown flag and token generation. + pub fn ensure_call_active(&self, claims: &TokenClaims) -> Result<(), LifecycleError> { + if self.inner.clock.now_ms() >= claims.deadline_ms { + return Err(LifecycleError::DeadlineElapsed); + } + if self.inner.cancellation.is_cancelled() { + return Err(LifecycleError::Cancelled); + } + self.check_call_cancellation(&claims.call_id)?; + if claims.generation != self.inner.generation.load(Ordering::SeqCst) { + return Err(LifecycleError::Interrupted); + } + Ok(()) + } + + /// Serializes a cancellation request with the irreversible publication + /// point of exactly this call, and with this call's durable prepare + /// boundary. Nothing here is lifecycle-wide. + /// + /// If the call has not crossed its publication fence, the request wins and + /// every later publication attempt is refused. If the fence is already + /// `Publishing`/`Published`, the publication has won: the request is still + /// recorded (so later effects in the same call are cancelled) but the + /// already published effect keeps its right to settle one receipt. + /// Returns whether an open token for `call_id` was found. + /// + /// A call with no open token has not prepared yet. Its id is recorded in + /// the shared prepare ledger under the token-map lock that a prepare takes + /// to publish the call's token, so the two can never miss each other: + /// either the prepare observes the intent before the token exists and + /// transfers it to the token's fence, or this recording observes the token + /// and fences it directly. Recording never takes a gate, so a cancellation + /// is never blocked by this call's or any other call's durable I/O. The + /// ledger is bounded by the lifetime call limit and seals (refusing every + /// later prepare) if it is ever exhausted. + pub fn request_call_cancellation(&self, call_id: &str) -> bool { + let fences = { + let states = self.inner.token_states.lock(); + let mut fences = Vec::new(); + let mut prepared = false; + for state in states.values() { + if token_call_id(state) != call_id { + continue; + } + prepared = true; + if let TokenState::Open { fence, .. } = state { + fences.push(Arc::clone(fence)); + } + } + if !prepared { + // A call without an open token has not handed off yet. The + // intent is recorded in the shared prepare ledger while the + // token map is still locked: the prepare that publishes this + // call's token holds the same lock, so it either observes this + // intent before the token exists (and transfers it to the + // fence) or this recording observes that token and fences it + // directly. There is no window in which both miss it. + self.record_prepare_cancellation(call_id); + } + fences + }; + let found = !fences.is_empty(); + for fence in fences { + fence.lock().cancel_requested = true; + } + found + } + + /// Enters the per-call publication fence for `token`. + /// + /// Success means no cancellation/deadline/generation refusal can race the + /// irreversible native effect that follows. The returned permit must be + /// marked [`PublicationPermit::published`] only after that effect really + /// happened; dropping it unpublished leaves the call eligible for a later + /// refusal or for rollback. + pub fn enter_publication(&self, token: &str) -> Result { + let (claims, fence) = { + let states = self.inner.token_states.lock(); + match states.get(token) { + Some(TokenState::Open { claims, fence, .. }) => { + (claims.as_ref().clone(), Arc::clone(fence)) + } + Some(TokenState::Committed { .. }) => return Err(LifecycleError::DuplicateClose), + Some(TokenState::Interrupted { .. }) => return Err(LifecycleError::Interrupted), + // A terminal write owns the call; no publisher may append to + // the ledger this token is closing. + Some(TokenState::PendingWrite(_)) => return Err(LifecycleError::Interrupted), + None => return Err(LifecycleError::TokenUnknown), + } + }; + if claims.owner != self.inner.owner { + return Err(LifecycleError::OwnerMismatch { + expected: self.inner.owner.key(), + actual: claims.owner.key(), + }); + } + // Test-only: the fence was copied, but not yet locked. A settlement + // that holds the fence must decide the phase and close the token + // before this publisher can acquire it. + #[cfg(any(test, feature = "workspace-io-fault"))] + let copy_observer = self.inner.publisher_copy_observer.lock().clone(); + #[cfg(any(test, feature = "workspace-io-fault"))] + if let Some(observer) = copy_observer { + observer(); + } + let mut state = fence.lock(); + if state.closed { + // The token was settled after this publisher copied the fence. + // Admission can no longer append to its ledger. + return Err(LifecycleError::Interrupted); + } + if state.cancel_requested { + return Err(LifecycleError::Cancelled); + } + if state.phase == PublicationPhase::Published { + // An earlier effect in this call already owns the publication + // point. Further effects remain possible only while the call itself + // is still admissible: a later effect must pass the same deadline, + // run/call cancellation and generation checks at its own boundary. + drop(state); + self.ensure_call_active(&claims)?; + #[cfg(any(test, feature = "workspace-io-fault"))] + { + let observer = self.inner.admission_recheck_observer.lock().clone(); + if let Some(observer) = observer { + observer(); + } + } + // Count this later effect as an in-flight publisher until it + // records its outcome. Recovery must not read a ledger that a + // still-running insertion is about to extend. The fence was + // released across `ensure_call_active`, so the exclusive claim and + // the token generation must be revalidated under it: a recovery + // claim that was taken and cleared on this fence in that window + // must not let the old admission resume. + let mut state = fence.lock(); + if state.closed || claims.generation != self.inner.generation.load(Ordering::SeqCst) { + return Err(LifecycleError::Interrupted); + } + if state.cancel_requested { + return Err(LifecycleError::Cancelled); + } + // Re-check the per-call cancellation while the fence is held. A + // cancellation recorded after the published phase began must still + // stop every later effect before it can append to this call's + // ledger. + self.check_call_cancellation(&claims.call_id)?; + state.pending_publishers = state.pending_publishers.saturating_add(1); + state.ledger_version = state.ledger_version.saturating_add(1); + drop(state); + return Ok(PublicationPermit { + fence, + active: false, + counted: true, + }); + } + if state.phase == PublicationPhase::Publishing { + return Err(LifecycleError::Interrupted); + } + if self.inner.clock.now_ms() >= claims.deadline_ms { + return Err(LifecycleError::DeadlineElapsed); + } + if self.inner.cancellation.is_cancelled() { + return Err(LifecycleError::Cancelled); + } + match self.inner.call_cancellation.call_state(&claims.call_id) { + CallCancellationState::Active => {} + CallCancellationState::Cancelled => return Err(LifecycleError::Cancelled), + CallCancellationState::DeadlineElapsed => return Err(LifecycleError::DeadlineElapsed), + } + if claims.generation != self.inner.generation.load(Ordering::SeqCst) { + return Err(LifecycleError::Interrupted); + } + state.phase = PublicationPhase::Publishing; + drop(state); + Ok(PublicationPermit { + fence, + active: true, + counted: false, + }) + } + + fn token_is_published(&self, token: &str) -> bool { + let fence = { + let states = self.inner.token_states.lock(); + match states.get(token) { + Some(TokenState::Open { fence, .. }) => Some(Arc::clone(fence)), + Some(TokenState::PendingWrite(pending)) => Some(Arc::clone(&pending.fence)), + _ => None, + } + }; + fence.is_some_and(|fence| fence.lock().phase == PublicationPhase::Published) + } + + /// Number of execution tokens that are not terminal, plus one reservation + /// for each call id whose durable start is still in flight. A token whose + /// durable terminal write is still in flight is retained ownership, so it + /// counts here until the write resolves; an in-flight start owns the call + /// before its token exists, so it counts here for the same reason. + pub fn open_token_count(&self) -> usize { + let starting = self.inner.preparing_calls.lock().len(); + let open = self + .inner + .token_states + .lock() + .values() + .filter(|state| matches!(state, TokenState::Open { .. } | TokenState::PendingWrite(_))) + .count(); + open.saturating_add(starting) + } + + /// Test-only: the number of real open token states, excluding in-flight + /// prepare reservations. This is the exact "a durable boundary has not yet + /// handed out a token" assertion. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn open_token_state_count_for_test(&self) -> usize { + self.inner + .token_states + .lock() + .values() + .filter(|state| matches!(state, TokenState::Open { .. } | TokenState::PendingWrite(_))) + .count() + } + + /// Number of tokens that settled through a canonical committed receipt. + pub fn committed_token_count(&self) -> usize { + self.inner + .token_states + .lock() + .values() + .filter(|state| matches!(state, TokenState::Committed { .. })) + .count() + } + + /// Number of tokens that were interrupted without a committed receipt. + pub fn interrupted_token_count(&self) -> usize { + self.inner + .token_states + .lock() + .values() + .filter(|state| matches!(state, TokenState::Interrupted { .. })) + .count() + } + + /// Settles every open token belonging to `call_id` with one call-wide + /// terminal decision. + /// + /// The live token set is enumerated under `token_states`, every + /// contributor's publication fence is locked, and exactly one outcome is + /// chosen for the whole call: commit one receipt, interrupt, retain, or + /// no-op. The receipt bytes and the ledger versions they describe are + /// captured in that same critical section, and every contributing fence is + /// closed there too. Nothing is written when a contributor is still + /// crossing its fence or when a prepared receipt no longer matches a live + /// contributor; the returned disposition is what a later retry reuses. + /// A call whose durable start is still being persisted has no token yet; + /// it is likewise retained so a caller never mistakes the pending start + /// for a call that nothing owns. + /// At most one durable operation is performed after the locks are + /// released, and an interrupt is never mixed with a receipt commit. + pub fn settle_call_terminal( + &self, + call_id: &str, + request: CallTerminalRequest<'_>, + ) -> Result { + // Validate raw request bytes in their canonical shape before anything + // fills optional defaults. Normalizing first would turn a malformed + // payload such as a success without string `content` into a valid + // success with empty content that could then be persisted. + match request { + CallTerminalRequest::Caller(bytes) + | CallTerminalRequest::Synthetic(bytes) + | CallTerminalRequest::GuestCommit(bytes) => validate_canonical_result(bytes)?, + CallTerminalRequest::Prepared(_) | CallTerminalRequest::Derived => {} + } + // Test-only: the decision has not read the live set yet, so a test can + // publish inside this window and prove the publication is part of the + // one snapshot the decision then takes. + #[cfg(any(test, feature = "workspace-io-fault"))] + { + let observer = self.inner.settle_snapshot_observer.lock().clone(); + if let Some(observer) = observer { + observer(); + } + } + // A prepare reserves its call id before the durable start is written, + // so no token exists yet while `commit_started` is parked. That + // reservation is retained ownership: deciding the call here would + // report NoOp and let the caller believe nothing owns it. Report it + // retained instead; the owner retries after the token exists. Reading + // this set before the token table keeps the same lock order as + // `prepare` without holding any lock across the durable write. + if self.inner.preparing_calls.lock().contains(call_id) { + return Ok(CallSettlement { + decision: CallTerminalDecision::Retained, + retained: 1, + ..CallSettlement::default() + }); + } + let mut states = self.inner.token_states.lock(); + let open: Vec = states + .iter() + .filter_map(|(token, state)| match state { + TokenState::Open { claims, .. } if claims.call_id == call_id => Some(token.clone()), + _ => None, + }) + .collect(); + // A terminal decision for this call may already be persisting its + // durable outcome. That token is not terminal: report retained with + // the exact disposition the retry must reuse, so no caller can treat + // the call as settled before the durable write acknowledges. + let pending: Vec = states + .values() + .filter_map(|state| match state { + TokenState::PendingWrite(pending) if pending.call_id == call_id => { + Some(pending.as_ref().clone()) + } + _ => None, + }) + .collect(); + if !pending.is_empty() { + // Nothing new is decided here: another owner already took the + // terminal decision and its durable write is still in flight. Only + // the disposition that decision stored may be reused. Bytes from + // this request were never bound by any decision, so promoting them + // (in particular to `Authoritative`) could later overwrite an + // effect the pending write never saw; retaining without a receipt + // keeps the call's retry owned by a live derivation instead. + let result = pending.iter().find_map(|pending| pending.retry.clone()); + let retained = open.len().saturating_add(pending.len()); + drop(states); + return Ok(CallSettlement { + decision: CallTerminalDecision::Retained, + result, + retained, + ..CallSettlement::default() + }); + } + if open.is_empty() { + let committed = states.values().any(|state| { + matches!(state, TokenState::Committed { call_id: closed, .. } if closed == call_id) + }); + drop(states); + let result = if committed { + self.committed_receipt(call_id)? + } else { + // No token can be closed, but the caller may still have + // synthetic bytes to observe (a call the VM stopped before any + // effect). They are returned, never written, and never carry + // ledger authority: a later publication must not be settled by + // bytes that no decision bound. + match request { + CallTerminalRequest::Synthetic(bytes) => Some(CallReceipt::from_encoded( + bytes.clone(), + ReceiptBinding::Ledger(Vec::new()), + )), + CallTerminalRequest::GuestCommit(_) => { + // A guest commit with no open token has no ledger to + // bind and no durable receipt was read back above. + // Returning these bytes would grant authority to a + // payload no write ever produced. + None + } + CallTerminalRequest::Caller(bytes) => Some(CallReceipt::from_encoded( + bytes.clone(), + ReceiptBinding::Ledger(Vec::new()), + )), + CallTerminalRequest::Prepared(receipt) => Some(receipt.clone()), + CallTerminalRequest::Derived => None, + } + }; + return Ok(CallSettlement { + decision: CallTerminalDecision::NoOp, + result, + ..CallSettlement::default() + }); + } + // Hold the token-state guard and every fence continuously from the + // live read through the decision and the token closure. A publisher + // that copied a fence before this point blocks on it and observes the + // closure; a publisher that arrives later cannot insert a token for + // this call because `prepare` re-checks the unresolved call id under + // this same token-state lock. + let fence_arcs: Vec>> = open + .iter() + .filter_map(|token| match states.get(token) { + Some(TokenState::Open { fence, .. }) => Some(Arc::clone(fence)), + _ => None, + }) + .collect(); + if fence_arcs.len() != open.len() { + drop(states); + return Ok(CallSettlement { + decision: CallTerminalDecision::Retained, + retained: open.len(), + ..CallSettlement::default() + }); + } + let mut guards: Vec> = + Vec::with_capacity(fence_arcs.len()); + for fence in &fence_arcs { + guards.push(fence.lock()); + } + let mut published: Vec = Vec::new(); + let mut in_flight = false; + for (index, guard) in guards.iter().enumerate() { + if guard.closed || guard.pending_publishers != 0 { + in_flight = true; + continue; + } + match guard.phase { + PublicationPhase::Unpublished => {} + PublicationPhase::Publishing => in_flight = true, + PublicationPhase::Published => published.push(index), + } + } + // A prepared receipt is usable only when every live published + // contributor still matches the exact version captured with its bytes. + let mut stale = false; + if let CallTerminalRequest::Prepared(receipt) = request { + for &index in &published { + let version = self.receipt_version_for(&open[index], receipt); + if !guards[index].receipt_describes(version) { + stale = true; + } + } + } + if in_flight || stale { + let result = match request { + CallTerminalRequest::Prepared(receipt) => Some(receipt.clone()), + CallTerminalRequest::Caller(bytes) | CallTerminalRequest::GuestCommit(bytes) => { + Some(self.bind_live_bytes(bytes, &open, &guards, &published)) + } + CallTerminalRequest::Synthetic(bytes) => { + // Synthetic bytes describe no native effect. They may be + // the retry disposition only while nothing published; + // otherwise the live ledger decides the bytes. + if published.is_empty() { + Some(self.bind_live_bytes(bytes, &open, &guards, &published)) + } else { + self.live_native_receipt(&states, &open, &guards, &published) + } + } + CallTerminalRequest::Derived => { + self.live_native_receipt(&states, &open, &guards, &published) + } + }; + let retained = guards.len(); + drop(guards); + drop(states); + return Ok(CallSettlement { + decision: CallTerminalDecision::Retained, + result, + retained, + ..CallSettlement::default() + }); + } + let budget = Self::call_output_budget(&states, &open); + let guest_commit = matches!(request, CallTerminalRequest::GuestCommit(_)); + if published.is_empty() && !guest_commit { + // Test-only: the unpublished-arm decision runs while every fence + // is still held, so a publisher that copied one cannot acquire it + // until the whole call is already interrupted. + #[cfg(any(test, feature = "workspace-io-fault"))] + { + let observer = self.inner.settle_unpublished_observer.lock().clone(); + if let Some(observer) = observer { + observer(); + } + } + // Nothing published: the whole call is an explicit interrupt. The + // caller bytes (if any) stay caller-visible but are never written + // as a durable result. + let result = match request { + CallTerminalRequest::Caller(bytes) => Some(CallReceipt::from_encoded( + bytes.clone(), + ReceiptBinding::Ledger(Vec::new()), + )), + // Nothing published and no decision bound these bytes: they + // are caller-visible only and never ledger authority. + CallTerminalRequest::Synthetic(bytes) => Some(CallReceipt::from_encoded( + bytes.clone(), + ReceiptBinding::Ledger(Vec::new()), + )), + CallTerminalRequest::Prepared(receipt) => Some(receipt.clone()), + // Guest commit never interrupts; it always decides a receipt. + CallTerminalRequest::GuestCommit(_) => None, + CallTerminalRequest::Derived => None, + }; + let mut closing: Vec<(String, PendingTerminal)> = Vec::with_capacity(guards.len()); + for (index, guard) in guards.iter_mut().enumerate() { + guard.closed = true; + if let Some(TokenState::Open { + claims, resources, .. + }) = states.remove(&open[index]) + { + closing.push(( + open[index].clone(), + PendingTerminal { + call_id: call_id.to_string(), + retry: result.clone(), + claims, + resources, + fence: Arc::clone(&fence_arcs[index]), + published: false, + }, + )); + } + } + // The owner installs the pending state and, on every later exit + // including a panic, either finishes it or reopens the exact token. + let owner = PendingTerminalWrite::new(self, closing); + owner.install(&mut states); + drop(guards); + drop(states); + let interrupted = owner.len(); + // Resources stay owned until the durable interrupt acknowledges: a + // failed interrupt reopens the token with the resources it had, so + // its retry still holds what it must release. + return match self.inner.durable.interrupt(call_id) { + Ok(()) => { + let closing = owner.finish(PendingTerminalState::Interrupted); + let mut resources = Vec::new(); + for (_, pending) in closing { + resources.extend(pending.resources); + } + release_resources(resources); + Ok(CallSettlement { + decision: CallTerminalDecision::Interrupted, + result, + interrupted, + ..CallSettlement::default() + }) + } + Err(error) => { + owner.reopen(); + Err(error) + } + }; + } + if guest_commit && published.is_empty() { + // The guest result is authoritative even without a native effect, + // but the managed commit's unpublished rules and messages still + // decide whether it may be written. Every fence is held here, so + // no publisher can slip in between this check and the closure. + for (index, token) in open.iter().enumerate() { + let Some(TokenState::Open { claims, .. }) = states.get(token) else { + continue; + }; + if guards[index].cancel_requested { + return Err(LifecycleError::Cancelled); + } + if self.inner.clock.now_ms() >= claims.deadline_ms { + return Err(LifecycleError::DeadlineElapsed); + } + if self.inner.cancellation.is_cancelled() { + return Err(LifecycleError::Cancelled); + } + self.check_call_cancellation(&claims.call_id)?; + } + } + let receipt = match request { + CallTerminalRequest::Prepared(receipt) => receipt.clone(), + CallTerminalRequest::Caller(bytes) | CallTerminalRequest::GuestCommit(bytes) => { + self.bind_live_bytes(bytes, &open, &guards, &published) + } + CallTerminalRequest::Synthetic(_) | CallTerminalRequest::Derived => { + match self.live_native_receipt(&states, &open, &guards, &published) { + Some(receipt) => receipt, + None => { + let versions = self.live_versions(&open, &guards, &published); + let result = recovery_failure_result( + "effect_outcome_unrecorded", + "a published effect was recovered without its guest result", + json!({"publication": "published", "recovered": true}), + budget, + ); + CallReceipt::new(result, ReceiptBinding::Ledger(versions)) + } + } + } + }; + if json_size(receipt.encoded()) > budget { + drop(guards); + drop(states); + return Err(LifecycleError::ResultTooLarge); + } + if let Err(error) = validate_canonical_result(receipt.encoded()) { + drop(guards); + drop(states); + return Err(error); + } + // Test-only: every contributing fence is held here, after validation + // and before the closure, so a publisher that copied one cannot slip + // into the commit window. + #[cfg(any(test, feature = "workspace-io-fault"))] + { + let observer = self.inner.settle_commit_observer.lock().clone(); + if let Some(observer) = observer { + observer(); + } + } + let mut closing: Vec<(String, PendingTerminal)> = Vec::with_capacity(guards.len()); + for (index, guard) in guards.iter_mut().enumerate() { + let was_published = guard.phase == PublicationPhase::Published; + guard.closed = true; + if let Some(TokenState::Open { + claims, resources, .. + }) = states.remove(&open[index]) + { + closing.push(( + open[index].clone(), + PendingTerminal { + call_id: call_id.to_string(), + retry: Some(receipt.clone()), + claims, + resources, + fence: Arc::clone(&fence_arcs[index]), + published: was_published, + }, + )); + } + } + // The owner is the only writer that may finish this call from here on, + // including when the durable callback or a release panics. + let owner = PendingTerminalWrite::new(self, closing); + owner.install(&mut states); + drop(guards); + drop(states); + let committed = owner.len(); + let encoded = receipt.encoded().clone(); + match self.inner.durable.commit_result(call_id, &encoded) { + Ok(_) => { + let closing = owner.finish(PendingTerminalState::Committed); + // Published objects stay owned by their native capability; + // resources of an unpublished sibling only guarded an effect + // that never crossed, so they are released now. + let mut unbound = Vec::new(); + for (_, pending) in closing { + if pending.published { + drop(pending.resources); + } else { + unbound.extend(pending.resources); + } + } + release_resources(unbound); + Ok(CallSettlement { + decision: CallTerminalDecision::Committed, + result: Some(receipt), + committed, + ..CallSettlement::default() + }) + } + Err(error) => { + owner.reopen(); + Err(error) + } + } + } + + /// Settles every open token belonging to `call_id` without caller bytes. + pub fn settle_call(&self, call_id: &str) -> Result { + self.settle_call_terminal(call_id, CallTerminalRequest::Derived) + } + + /// Settles one call with raw caller bytes. The ledger versions the bytes + /// describe are captured by the terminal decision itself. + pub fn settle_call_with_receipt( + &self, + call_id: &str, + receipt: Option<&Value>, + ) -> Result { + match receipt { + Some(receipt) => { + self.settle_call_terminal(call_id, CallTerminalRequest::Caller(receipt)) + } + None => self.settle_call_terminal(call_id, CallTerminalRequest::Derived), + } + } + + /// Settles one call with a receipt whose bytes and ledger versions were + /// captured together by [`Self::derive_call_receipt`]. + pub fn settle_call_with_call_receipt( + &self, + call_id: &str, + receipt: &CallReceipt, + ) -> Result { + self.settle_call_terminal(call_id, CallTerminalRequest::Prepared(receipt)) + } + + fn receipt_version_for(&self, token: &str, receipt: &CallReceipt) -> ReceiptVersion { + match &receipt.binding { + // Durable read-back bytes carry no live ledger version, so they can + // never describe a published contributor of this call. + ReceiptBinding::Authoritative => ReceiptVersion::Missing, + ReceiptBinding::Ledger(versions) => versions + .iter() + .find(|(bound, _)| bound == token) + .map_or(ReceiptVersion::Missing, |(_, version)| { + ReceiptVersion::Bound(*version) + }), + } + } + + fn live_versions( + &self, + tokens: &[String], + guards: &[parking_lot::MutexGuard<'_, PublicationFenceState>], + published: &[usize], + ) -> Vec<(String, ReceiptLedgerVersion)> { + published + .iter() + .map(|&index| { + ( + tokens[index].clone(), + ReceiptLedgerVersion { + latest_effect: guards[index] + .effects + .iter() + .map(|(sequence, _)| *sequence) + .max() + .unwrap_or(0), + ledger_version: guards[index].ledger_version, + }, + ) + }) + .collect() + } + + fn bind_live_bytes( + &self, + bytes: &Value, + tokens: &[String], + guards: &[parking_lot::MutexGuard<'_, PublicationFenceState>], + published: &[usize], + ) -> CallReceipt { + CallReceipt::from_encoded( + bytes.clone(), + ReceiptBinding::Ledger(self.live_versions(tokens, guards, published)), + ) + } + + /// Authoritative native receipt for the published contributors of one + /// call, derived while `token_states` and every contributor fence are + /// held. Bytes and per-token ledger versions cannot be separated by a + /// concurrent publisher, extension or amendment. + fn live_native_receipt( + &self, + states: &parking_lot::MutexGuard<'_, HashMap>, + tokens: &[String], + guards: &[parking_lot::MutexGuard<'_, PublicationFenceState>], + published: &[usize], + ) -> Option { + let mut effects = Vec::new(); + let mut cancel_requested = false; + let mut deadline_elapsed = false; + let mut budget = self.inner.limits.max_output_bytes; + for &index in published { + let fence = &guards[index]; + cancel_requested |= fence.cancel_requested; + if let Some(TokenState::Open { claims, .. }) = states.get(&tokens[index]) { + budget = claims.output_budget; + deadline_elapsed |= self.inner.clock.now_ms() >= claims.deadline_ms + || matches!( + self.inner.call_cancellation.call_state(&claims.call_id), + CallCancellationState::DeadlineElapsed + ); + } + effects.extend(fence.effects.iter().cloned()); + } + if effects.is_empty() { + return None; + } + effects.sort_by_key(|(sequence, _)| *sequence); + let ledger = PublicationFenceState { + phase: PublicationPhase::Published, + cancel_requested, + effects, + ..PublicationFenceState::default() + }; + let (record, artifacts) = ledger.authoritative()?; + let outcome = NativeEffectOutcome { + record, + artifacts, + cancel_requested, + deadline_elapsed, + }; + Some(CallReceipt::new( + outcome.to_tool_result(budget), + ReceiptBinding::Ledger(self.live_versions(tokens, guards, published)), + )) + } + + fn call_output_budget( + states: &parking_lot::MutexGuard<'_, HashMap>, + tokens: &[String], + ) -> usize { + tokens + .iter() + .find_map(|token| match states.get(token) { + Some(TokenState::Open { claims, .. }) => Some(claims.output_budget), + _ => None, + }) + .unwrap_or(0) + } + + /// Re-opens every token a failed or unwound terminal write still holds as + /// pending, so the owner's retained receipt can retry the same decision + /// instead of losing the call. + /// + /// Only a token this owner still owns is restored: a state another owner + /// already made terminal is never rotated back, and an absent entry (the + /// write was interrupted between removal and installation) is restored as + /// the original open token. The fence is reopened before the token becomes + /// visible again, and both keep the resources the write never released. + fn reopen_pending_tokens(&self, closing: &[(String, PendingTerminal)]) { + let mut states = self.inner.token_states.lock(); + for (token, pending) in closing { + let still_pending = match states.get(token) { + None => true, + Some(TokenState::PendingWrite(current)) => current.call_id == pending.call_id, + Some( + TokenState::Open { .. } + | TokenState::Committed { .. } + | TokenState::Interrupted { .. }, + ) => false, + }; + if !still_pending { + continue; + } + pending.fence.lock().closed = false; + states.insert( + token.clone(), + TokenState::Open { + claims: pending.claims.clone(), + resources: pending.resources.clone(), + fence: Arc::clone(&pending.fence), + }, + ); + } + } + + /// Receipt for a durable guest commit already written for `call_id`. + fn committed_receipt(&self, call_id: &str) -> Result, LifecycleError> { + let Some(value) = self.committed_result(call_id)? else { + return Ok(None); + }; + let result: ToolResult = serde_json::from_value(value.clone()).map_err(|error| { + LifecycleError::InvalidMetadata(format!( + "committed canonical result is invalid: {error}" + )) + })?; + Ok(Some(CallReceipt::new( + result, + ReceiptBinding::Authoritative, + ))) + } + + /// Reads the exact durable payload committed by the guest for `call_id`. + /// + /// A call whose guest reached `tool_commit` before the VM stopped must be + /// returned by the owner as the committed content, never as a synthetic + /// cancellation. The lookup uses the durable replay boundary and the tool + /// identity retained on the committed token. + pub fn committed_result(&self, call_id: &str) -> Result, LifecycleError> { + let tool_name = { + let states = self.inner.token_states.lock(); + states.iter().find_map(|(_, state)| match state { + TokenState::Committed { + call_id: committed, + tool_name, + } if committed.as_str() == call_id => Some(tool_name.clone()), + _ => None, + }) + }; + let Some(tool_name) = tool_name else { + return Ok(None); + }; + self.inner + .durable + .replay_result(self.inner.owner.run(), call_id, &tool_name) + } + + /// Returns the authoritative typed native outcome of `call_id` that + /// published without a guest commit. + /// + /// The ledger of every token belonging to the call is read; a failed, + /// indeterminate or restored terminal record always outranks an OK record, + /// and artifact identities stored later in the same call are merged into + /// the returned record. Returns `None` when the call has no published + /// effect or when only a guest commit describes it. + pub fn call_native_outcome(&self, call_id: &str) -> Option { + let mut effects: Vec<(u64, NativeEffectRecord)> = Vec::new(); + let mut cancel_requested = false; + let mut deadline_elapsed = false; + { + let states = self.inner.token_states.lock(); + for state in states.values() { + let Some((claims, fence)) = token_live_parts(state) else { + continue; + }; + if claims.call_id.as_str() != call_id { + continue; + } + let fence = fence.lock(); + cancel_requested |= fence.cancel_requested; + deadline_elapsed |= self.inner.clock.now_ms() >= claims.deadline_ms + || matches!( + self.inner.call_cancellation.call_state(&claims.call_id), + CallCancellationState::DeadlineElapsed + ); + if fence.phase == PublicationPhase::Published { + effects.extend(fence.effects.iter().cloned()); + } + } + } + effects.sort_by_key(|(sequence, _)| *sequence); + let fence = PublicationFenceState { + phase: PublicationPhase::Published, + cancel_requested, + effects, + ..PublicationFenceState::default() + }; + let (record, artifacts) = fence.authoritative()?; + Some(NativeEffectOutcome { + record, + artifacts, + cancel_requested, + deadline_elapsed, + }) + } + + /// Records the latest observed process state for an OS spawn already in the + /// call's ledger. It never creates a second record for the same primitive. + pub(crate) fn note_process_state(&self, token: &str, pid: u32, state: NativeProcessState) { + self.update_process_record(token, pid, None, Some(state)); + } + + /// Marks the recorded OS spawn as a failed terminal outcome. The process + /// state is enriched when it is already known, but a failed record is never + /// downgraded back to OK by a later artifact store. + pub(crate) fn note_process_failure( + &self, + token: &str, + pid: u32, + code: &str, + message: Option<&str>, + state: Option, + ) { + self.update_process_record(token, pid, Some((code, message)), state); + } + + fn update_process_record( + &self, + token: &str, + pid: u32, + failure: Option<(&str, Option<&str>)>, + state: Option, + ) { + let fence = { + let states = self.inner.token_states.lock(); + match states.get(token) { + Some(TokenState::Open { fence, .. }) => Arc::clone(fence), + _ => return, + } + }; + let mut fence = fence.lock(); + let mut changed = false; + for (_, record) in fence.effects.iter_mut().rev() { + if record.effect != NativeEffectKind::ProcessSpawn { + continue; + } + let Some(process) = record.process.as_mut() else { + continue; + }; + if process.pid != pid { + continue; + } + if let Some(state) = state { + record.observe_process(state); + changed = true; + } + if let Some((code, message)) = failure { + record.mark_failed(code, message); + changed = true; + } + break; + } + if changed { + // An in-place amendment is still a ledger change: a settlement + // receipt derived before it no longer describes this call. + fence.ledger_version = fence.ledger_version.saturating_add(1); + } + } -fn token_call_id(state: &TokenState) -> &str { - match state { - TokenState::Open { claims, .. } => claims.call_id.as_str(), - TokenState::Committed { call_id } => call_id.as_str(), - TokenState::Interrupted { call_id } => call_id.as_str(), + /// Typed canonical result for a call whose guest never committed. + /// + /// The result is built from the native effect record and compacted at the + /// typed byte boundary against the call's configured output budget. Returns + /// `None` when no published native effect exists. + pub fn native_effect_result(&self, call_id: &str) -> Option { + let outcome = self.call_native_outcome(call_id)?; + let budget = { + let states = self.inner.token_states.lock(); + states + .values() + .find_map(|state| match token_live_parts(state) { + Some((claims, _)) if claims.call_id == call_id => Some(claims.output_budget), + _ => None, + }) + .unwrap_or(self.inner.limits.max_output_bytes) + }; + Some(outcome.to_tool_result(budget)) } -} -struct LifecycleInner { - owner: CapabilityOwner, - registry_identity: String, - workspace: PathBuf, - limits: LifecycleLimits, - deadline_ms: u64, - clock: Arc, - tokens: Arc, - durable: Arc, - approval: Arc, - cancellation: Arc, - generation: AtomicU64, - call_count: AtomicU64, - token_states: Mutex>, -} + /// Derives the caller-visible receipt and the exact ledger versions its + /// bytes describe in one token-state/fence critical section. + /// + /// A guest commit already froze the payload; otherwise the authoritative + /// native record of every published effect is chosen and compacted while + /// each contributing token's `latest_effect`/`ledger_version` pair is + /// sampled under the same fence lock. Bytes and versions can therefore + /// never be separated by a concurrent publisher, extension, or amendment. + pub fn derive_call_receipt( + &self, + call_id: &str, + ) -> Result, LifecycleError> { + if let Some(committed) = self.committed_receipt(call_id)? { + return Ok(Some(committed)); + } + Ok(self.native_call_receipt(call_id)) + } -/// Run-scoped generic tool lifecycle engine. -#[derive(Clone)] -pub struct CapabilityLifecycle { - inner: Arc, -} + /// Binds a guest-produced caller result to the ledger versions visible + /// when it was captured. A later admission or recorded effect changes the + /// version, so settlement retains the token instead of committing bytes + /// that no longer describe the whole call. + pub fn bind_caller_receipt(&self, call_id: &str, result: ToolResult) -> CallReceipt { + let versions = self.published_versions(call_id); + // An empty binding still refuses any published token that appears + // later: only the exact versions captured here may close one. + CallReceipt::new(result, ReceiptBinding::Ledger(versions)) + } -impl CapabilityLifecycle { - pub fn builder() -> CapabilityLifecycleBuilder { - CapabilityLifecycleBuilder::default() + /// Binds a synthetic caller result (cancellation, deadline, internal + /// fallback) to the published ledger versions visible when it was + /// created. When the receipt was derived from an empty read this binding + /// is empty, so a publication that finishes afterwards can never be + /// settled with synthetic bytes; the owner must re-derive the canonical + /// receipt from the advanced ledger instead. + pub fn bind_synthetic_result(&self, call_id: &str, result: ToolResult) -> CallReceipt { + self.bind_caller_receipt(call_id, result) } - /// Frozen workspace path captured at admission. - pub fn workspace(&self) -> &Path { - &self.inner.workspace + /// One-read native receipt: bytes and per-token ledger versions under the + /// same `token_states` guard and each contributing fence lock. + fn native_call_receipt(&self, call_id: &str) -> Option { + let mut effects = Vec::new(); + let mut cancel_requested = false; + let mut deadline_elapsed = false; + let mut versions = Vec::new(); + let mut budget = self.inner.limits.max_output_bytes; + { + let states = self.inner.token_states.lock(); + for (token, state) in states.iter() { + let Some((claims, fence)) = token_live_parts(state) else { + continue; + }; + if claims.call_id.as_str() != call_id { + continue; + } + budget = claims.output_budget; + let fence = fence.lock(); + cancel_requested |= fence.cancel_requested; + deadline_elapsed |= self.inner.clock.now_ms() >= claims.deadline_ms + || matches!( + self.inner.call_cancellation.call_state(&claims.call_id), + CallCancellationState::DeadlineElapsed + ); + if fence.phase != PublicationPhase::Published { + continue; + } + let latest_effect = fence + .effects + .iter() + .map(|(sequence, _)| *sequence) + .max() + .unwrap_or(0); + versions.push(( + token.clone(), + ReceiptLedgerVersion { + latest_effect, + ledger_version: fence.ledger_version, + }, + )); + effects.extend(fence.effects.iter().cloned()); + } + } + if effects.is_empty() { + return None; + } + effects.sort_by_key(|(sequence, _)| *sequence); + let ledger = PublicationFenceState { + phase: PublicationPhase::Published, + cancel_requested, + effects, + ..PublicationFenceState::default() + }; + let (record, artifacts) = ledger.authoritative()?; + let outcome = NativeEffectOutcome { + record, + artifacts, + cancel_requested, + deadline_elapsed, + }; + Some(CallReceipt::new( + outcome.to_tool_result(budget), + ReceiptBinding::Ledger(versions), + )) } - /// Registry identity captured when this lifecycle was admitted. - pub fn registry_identity(&self) -> &str { - &self.inner.registry_identity + /// Ledger versions of every published open token of `call_id`, read under + /// one token-state guard and per-token fence lock. + fn published_versions(&self, call_id: &str) -> Vec<(String, ReceiptLedgerVersion)> { + let mut versions = Vec::new(); + let states = self.inner.token_states.lock(); + for (token, state) in states.iter() { + let Some((claims, fence)) = token_live_parts(state) else { + continue; + }; + if claims.call_id.as_str() != call_id { + continue; + } + let fence = fence.lock(); + if fence.phase != PublicationPhase::Published { + continue; + } + let latest_effect = fence + .effects + .iter() + .map(|(sequence, _)| *sequence) + .max() + .unwrap_or(0); + versions.push(( + token.clone(), + ReceiptLedgerVersion { + latest_effect, + ledger_version: fence.ledger_version, + }, + )); + } + versions } pub(crate) fn parent_arguments( @@ -580,12 +3187,17 @@ impl CapabilityLifecycle { actual: owner.key(), }); } + // A cancelled call must not cross the durable prepare boundary. The + // per-call source is consulted before `prepare_parent`, not only at + // the later validation, so "prepare never ran" is literally true. + self.check_call_cancellation(&metadata.call_id)?; self.inner.durable.assert_active_run(&metadata.run_id)?; - self.inner.durable.prepare_parent( - &metadata.run_id, - &metadata.call_id, - &metadata.tool_name, - )?; + // The durable prepare boundary is crossed under the call-scoped gate, + // so a cancellation that arrived after `assert_active_run` still + // refuses before any parent record is written. The lease retires the + // gate at the end of this validation. + let _gate = + self.prepare_parent_for_call(&metadata.run_id, &metadata.call_id, &metadata.tool_name)?; if metadata.registry_identity != self.inner.registry_identity { return Err(LifecycleError::RegistryMismatch); } @@ -605,9 +3217,19 @@ impl CapabilityLifecycle { if self.inner.cancellation.is_cancelled() { return Err(LifecycleError::Cancelled); } + self.check_call_cancellation(&metadata.call_id)?; Ok(()) } + /// Admits one call and issues exactly one execution token for it. + /// + /// The unresolved-call check and the token insertion share one + /// `token_states` critical section, so two prepares of the same call id + /// can never both publish: the later one is refused with + /// [`LifecycleError::UnresolvedCall`] before it can cross any fence. A + /// call id therefore names at most one live token for the lifetime of this + /// lifecycle, and managed recovery/settlement may rely on that invariant + /// instead of interrupting duplicate tokens of one call. pub fn prepare( &self, owner: &CapabilityOwner, @@ -625,12 +3247,26 @@ impl CapabilityLifecycle { actual: self.inner.owner.with_run(&metadata.run_id), }); } + // Refuse a cancelled call before the durable prepare boundary. The + // same check is repeated below after replay/unresolved validation, but + // this one guarantees the prepare itself never starts. + self.check_call_cancellation(&metadata.call_id)?; self.inner.durable.assert_active_run(&metadata.run_id)?; - self.inner.durable.prepare_parent( - &metadata.run_id, - &metadata.call_id, - &metadata.tool_name, - )?; + // One call id is reserved before the durable write and released only + // after the token exists. The reservation is taken before the gate is + // looked up, so a concurrent or late prepare of the same call id can + // neither create a second admission gate nor cross the durable + // boundary again. It is call-scoped, not the shared token table, so + // another call's token operations never wait behind this persistence. + let start = self.begin_prepare_call(&metadata.call_id)?; + // The boundary itself runs under the call-scoped gate: a cancellation + // for this call that lands after `assert_active_run` cannot enter the + // durable prepare. The lease keeps this call's one gate in the map + // until the token below owns the call, so a cancellation that arrives + // while `commit_started` runs is recorded in the same ledger this + // prepare reads at the handoff. + let gate = + self.prepare_parent_for_call(&metadata.run_id, &metadata.call_id, &metadata.tool_name)?; if let Some(result) = self.inner.durable.replay_result( &metadata.run_id, &metadata.call_id, @@ -655,6 +3291,7 @@ impl CapabilityLifecycle { if self.inner.cancellation.is_cancelled() { return Err(LifecycleError::Cancelled); } + self.check_call_cancellation(&metadata.call_id)?; if metadata.registry_identity != self.inner.registry_identity { return Err(LifecycleError::RegistryMismatch); } @@ -668,9 +3305,9 @@ impl CapabilityLifecycle { "summary exceeds the configured bound".to_string(), )); } - if self.inner.call_count.load(Ordering::SeqCst) >= self.inner.limits.max_tool_calls { - return Err(LifecycleError::LimitExceeded); - } + // Reserve the hard lifetime slot atomically before approval or any + // effect preparation. A failed approval/started commit releases it. + let reservation = CallSlotReservation::reserve(&self.inner)?; let generation = self.inner.generation.load(Ordering::SeqCst); let ceiling = self.inner @@ -691,8 +3328,6 @@ impl CapabilityLifecycle { summary: metadata.summary.clone(), generation, }; - self.inner.durable.commit_started(&record)?; - let execution_token = self.inner.tokens.issue(); let remaining_ms = self .inner .deadline_ms @@ -703,26 +3338,59 @@ impl CapabilityLifecycle { .now() .checked_add(std::time::Duration::from_millis(remaining_ms)) .unwrap_or_else(|| self.inner.clock.now()); - self.inner.token_states.lock().insert( - execution_token.clone(), - TokenState::Open { - claims: Box::new(TokenClaims { - owner: self.inner.owner.clone(), - call_id: metadata.call_id, - tool_name: metadata.tool_name, - argument_digest: metadata.argument_digest, - registry_identity: metadata.registry_identity, - risk_ceiling: ceiling, - output_budget: self.inner.limits.max_output_bytes, - generation, - deadline, - deadline_ms: self.inner.deadline_ms, - workspace: self.inner.workspace.clone(), - }), - resources: Vec::new(), - }, - ); - self.inner.call_count.fetch_add(1, Ordering::SeqCst); + // Persist the start without holding the token-state lock: a stalled + // durable write delays only this call id, never another token + // operation. The call-id reservation (and its Drop) makes a failed or + // panicking start retryable. + self.inner.durable.commit_started(&record)?; + // Base ordering: the unforgeable token exists only after the durable + // start has acknowledged. + let execution_token = self.inner.tokens.issue(); + { + let mut states = self.inner.token_states.lock(); + // The cancellation read and the token publication share this + // critical section with `request_call_cancellation`: a cancellation + // that lost the token race is read here and becomes the token's own + // publication cancellation below, and one that arrives later + // observes the token this section publishes and fences it directly. + // Either way the intent is never dropped with a retired gate. A + // sealed ledger cannot prove this call's intent was recorded, so + // it fails closed here exactly like an explicit cancellation. + let prepare_cancelled = { + let gates = self.inner.prepare_gates.lock(); + gates.sealed || gates.cancelled.contains(&metadata.call_id) + }; + states.insert( + execution_token.clone(), + TokenState::Open { + claims: Box::new(TokenClaims { + owner: self.inner.owner.clone(), + call_id: metadata.call_id, + tool_name: metadata.tool_name, + argument_digest: metadata.argument_digest, + registry_identity: metadata.registry_identity, + risk_ceiling: ceiling, + output_budget: self.inner.limits.max_output_bytes, + generation, + deadline, + deadline_ms: self.inner.deadline_ms, + workspace: self.inner.workspace.clone(), + }), + resources: Vec::new(), + fence: Arc::new(Mutex::new(PublicationFenceState { + cancel_requested: prepare_cancelled, + ..PublicationFenceState::default() + })), + }, + ); + } + // The token owns the call now; the prepare gate is retired with this + // lease (exactly after the handoff). + gate.retire(); + // The token is visible before the reservation is released, so a later + // prepare either blocks on the reservation or observes the token. + start.commit(); + reservation.commit(); Ok(PrepareOutcome::Execute { execution_token, deadline_ms: self.inner.deadline_ms, @@ -752,7 +3420,12 @@ impl CapabilityLifecycle { match self.commit_inner(owner, token, result) { Ok(outcome) => Ok(outcome), Err(error) => { - if should_rollback_unpublished(&error) { + // Base behavior for the managed path retracts a result artifact + // even when its insertion already crossed the fence; only the + // MCP retention mode keeps a published artifact for settlement. + if should_rollback_unpublished(&error) + && (!self.token_is_published(token) || !self.retains_published_tokens()) + { self.rollback_unpublished(token); } Err(error) @@ -766,6 +3439,136 @@ impl CapabilityLifecycle { token: &str, result: Value, ) -> Result { + // The MCP retention mode commits through the same call-wide terminal + // decision that settles every other path. The managed/default mode + // keeps the base single-token closure below exactly as before. + if self.retains_published_tokens() { + return self.commit_retained(owner, token, result); + } + match self.commit_inner_settled(owner, token, result, None)? { + Some(outcome) => Ok(outcome), + // The receipt-ordered variant is the only caller that can observe + // a superseded commit; a plain guest commit never passes a mark. + None => Err(LifecycleError::Interrupted), + } + } + + /// Guest `tool_commit` in the MCP retention mode. + /// + /// The decision is the same call-wide terminal one the owner and the guard + /// use. It freezes the guest bytes only when no publisher still holds a + /// permit; otherwise it retains the token and the owner's later settlement + /// derives the true receipt from the completed ledger. + fn commit_retained( + &self, + owner: &CapabilityOwner, + token: &str, + result: Value, + ) -> Result { + if owner != &self.inner.owner { + return Err(LifecycleError::OwnerMismatch { + expected: self.inner.owner.key(), + actual: owner.key(), + }); + } + // Test-only: the guest is about to ask the lifecycle to freeze its + // bytes. A test can hold a publisher permit here and prove the refusal + // travels through the real dispatch path. + #[cfg(any(test, feature = "workspace-io-fault"))] + { + let observer = self.inner.commit_attempt_observer.lock().clone(); + if let Some(observer) = observer { + observer(token); + } + } + let call_id = { + let states = self.inner.token_states.lock(); + match states.get(token) { + Some(TokenState::Open { claims, .. }) => { + if &claims.owner != owner { + return Err(LifecycleError::OwnerMismatch { + expected: claims.owner.key(), + actual: owner.key(), + }); + } + claims.call_id.clone() + } + Some(TokenState::PendingWrite(pending)) => { + if &pending.claims.owner != owner { + return Err(LifecycleError::OwnerMismatch { + expected: pending.claims.owner.key(), + actual: owner.key(), + }); + } + return Err(LifecycleError::Interrupted); + } + Some(TokenState::Committed { .. }) => return Err(LifecycleError::DuplicateClose), + Some(TokenState::Interrupted { .. }) => return Err(LifecycleError::Interrupted), + None => return Err(LifecycleError::TokenUnknown), + } + }; + let settlement = + self.settle_call_terminal(&call_id, CallTerminalRequest::GuestCommit(&result)); + // Test-only: the decision is taken and the guest has not received its + // envelope yet. + #[cfg(any(test, feature = "workspace-io-fault"))] + { + let observer = self.inner.commit_decision_observer.lock().clone(); + if let Some(observer) = observer { + observer(token); + } + } + let settlement = settlement?; + match settlement.decision { + CallTerminalDecision::Committed => { + let receipt = settlement.result.ok_or(LifecycleError::Interrupted)?; + Ok(CommitOutcome { + envelope: json!({ + "ok": true, + "kind": "committed", + "call_id": call_id, + "result": receipt.encoded(), + }), + }) + } + // The decision refused to freeze while a publisher was still in + // flight. The token stays open; the owner's later settlement + // commits the true receipt. The dedicated code is a host + // disposition, so neither the guest nor the dispatch layer can + // mistake the refusal for a terminal interrupted result. + CallTerminalDecision::Retained => Err(LifecycleError::CommitRetained), + CallTerminalDecision::Interrupted => Err(LifecycleError::Interrupted), + CallTerminalDecision::NoOp => { + let states = self.inner.token_states.lock(); + match states.get(token) { + Some(TokenState::Committed { .. }) => Err(LifecycleError::DuplicateClose), + Some(TokenState::Open { .. }) + | Some(TokenState::PendingWrite(_)) + | Some(TokenState::Interrupted { .. }) => Err(LifecycleError::Interrupted), + None => Err(LifecycleError::TokenUnknown), + } + } + } + } + + /// Commits one token, optionally validating a settlement receipt against + /// the ledger snapshot it was derived from. + /// + /// `receipt_snapshot` carries the highest effect sequence and ledger + /// version visible when the settlement took its snapshot. The final + /// validation and the token closure run under the same fence critical + /// section, so an admission that copied this fence before the transition + /// cannot slip into the gap between the check and the closure. Returning + /// `Ok(None)` means the snapshot was superseded, so the token stays open + /// for the owner's next settlement instead of committing a receipt that + /// omits a later effect. + fn commit_inner_settled( + &self, + owner: &CapabilityOwner, + token: &str, + result: Value, + receipt_snapshot: Option, + ) -> Result, LifecycleError> { if owner != &self.inner.owner { return Err(LifecycleError::OwnerMismatch { expected: self.inner.owner.key(), @@ -773,10 +3576,13 @@ impl CapabilityLifecycle { }); } let mut states = self.inner.token_states.lock(); - let claims = match states.get(token) { - Some(TokenState::Open { claims, .. }) => claims.clone(), + let (claims, fence) = match states.get(token) { + Some(TokenState::Open { claims, fence, .. }) => (claims.clone(), Arc::clone(fence)), Some(TokenState::Committed { .. }) => return Err(LifecycleError::DuplicateClose), Some(TokenState::Interrupted { .. }) => return Err(LifecycleError::Interrupted), + // A call-wide terminal write owns this token; a second commit must + // not write another durable result. + Some(TokenState::PendingWrite(_)) => return Err(LifecycleError::Interrupted), None => return Err(LifecycleError::TokenUnknown), }; if &claims.owner != owner { @@ -785,14 +3591,64 @@ impl CapabilityLifecycle { actual: owner.key(), }); } + // Hold the fence from validation through the token transition. A + // publisher that copied this fence before the closure is blocked on + // it until the token is already Committed, then observes `closed`. + let mut fence_state = fence.lock(); + if fence_state.closed { + return Err(LifecycleError::Interrupted); + } + let published = fence_state.phase == PublicationPhase::Published; + let cancel_requested = fence_state.cancel_requested; + if let Some(snapshot) = receipt_snapshot { + // The snapshot was taken while the fence was held, then released + // before this commit. A later publisher admitted in that window + // either left the ledger unchanged, is still in flight, amended a + // record in place, or has already appended an effect. Only the + // first case may commit the snapshot receipt, so the receipt is + // bound to the exact ledger version it was derived from. + if !fence_state.receipt_describes(ReceiptVersion::Bound(snapshot)) { + return Ok(None); + } + } + #[cfg(any(test, feature = "workspace-io-fault"))] + { + let observer = self.inner.settle_commit_observer.lock().clone(); + if let Some(observer) = observer { + observer(); + } + } if json_size(&result) > claims.output_budget { return Err(LifecycleError::ResultTooLarge); } - if self.inner.clock.now_ms() >= claims.deadline_ms { - return Err(LifecycleError::DeadlineElapsed); - } - if self.inner.cancellation.is_cancelled() { - return Err(LifecycleError::Cancelled); + // Base behavior applies to the managed path: an elapsed deadline or a + // lifecycle-wide cancellation rejects the commit even after + // publication, and the caller retracts the result artifact. The MCP + // retention mode alone lets a published effect settle its canonical + // receipt. A call-scoped cancellation still refuses later effects at + // their own boundary, but it never rewrites the base outcome of an + // effect that already crossed the OS/publication boundary. + if !published { + // The fence records a cancellation that won before publication, + // including one that already refused this token's effect. Such a + // call can never commit a result afterwards. + if cancel_requested { + return Err(LifecycleError::Cancelled); + } + if self.inner.clock.now_ms() >= claims.deadline_ms { + return Err(LifecycleError::DeadlineElapsed); + } + if self.inner.cancellation.is_cancelled() { + return Err(LifecycleError::Cancelled); + } + self.check_call_cancellation(&claims.call_id)?; + } else if !self.retains_published_tokens() { + if self.inner.clock.now_ms() >= claims.deadline_ms { + return Err(LifecycleError::DeadlineElapsed); + } + if self.inner.cancellation.is_cancelled() { + return Err(LifecycleError::Cancelled); + } } validate_canonical_result(&result)?; let resources = match states.remove(token) { @@ -808,24 +3664,32 @@ impl CapabilityLifecycle { token.to_string(), TokenState::Committed { call_id: claims.call_id.clone(), + tool_name: claims.tool_name.clone(), }, ); + fence_state.closed = true; + drop(fence_state); drop(states); match self.inner.durable.commit_result(&claims.call_id, &result) { Ok(committed) => { drop(resources); - Ok(CommitOutcome { + Ok(Some(CommitOutcome { envelope: json!({ "ok": true, "kind": "committed", "call_id": claims.call_id, "result": committed, }), - }) + })) } Err(error) => { - for resource in resources { - resource.rollback_unpublished_side_effects(); + // The managed path restores base retraction on a commit-storage + // failure even after publication; the MCP retention mode keeps + // the published object and only rolls back unpublished ones. + if !published || !self.retains_published_tokens() { + for resource in resources { + resource.rollback_unpublished_side_effects(); + } } Err(error) } @@ -852,6 +3716,7 @@ impl CapabilityLifecycle { token: token.to_string(), closed: false, }), + Some(TokenState::PendingWrite(_)) => Err(LifecycleError::Interrupted), Some(TokenState::Committed { .. }) => Err(LifecycleError::DuplicateClose), Some(TokenState::Interrupted { .. }) => Err(LifecycleError::Interrupted), None => Err(LifecycleError::TokenUnknown), @@ -877,6 +3742,7 @@ impl CapabilityLifecycle { let states = self.inner.token_states.lock(); let claims = match states.get(token) { Some(TokenState::Open { claims, .. }) => claims.as_ref().clone(), + Some(TokenState::PendingWrite(_)) => return Err(LifecycleError::Interrupted), Some(TokenState::Committed { .. }) => return Err(LifecycleError::DuplicateClose), Some(TokenState::Interrupted { .. }) => return Err(LifecycleError::Interrupted), None => return Err(LifecycleError::TokenUnknown), @@ -891,6 +3757,7 @@ impl CapabilityLifecycle { if self.inner.clock.now_ms() >= claims.deadline_ms { return Err(LifecycleError::DeadlineElapsed); } + self.check_call_cancellation(&claims.call_id)?; if claims.generation != self.inner.generation.load(Ordering::SeqCst) { return Err(LifecycleError::Interrupted); } @@ -914,6 +3781,11 @@ impl CapabilityLifecycle { resources.push(resource); Ok(()) } + Some(TokenState::PendingWrite(_)) => { + drop(states); + resource.release(); + Err(LifecycleError::Interrupted) + } Some(TokenState::Committed { .. }) => Err(LifecycleError::DuplicateClose), Some(TokenState::Interrupted { .. }) => { drop(states); @@ -928,62 +3800,362 @@ impl CapabilityLifecycle { } } - pub fn recover_open_tokens(&self) -> Result, LifecycleError> { - // Eager Interrupted before durable I/O prevents Drop from racing a still-Open - // token. Durable interrupt failure is returned to the caller; in-process - // re-prepare is fenced by the Interrupted call_id unless durable replay - // already exists. Cross-restart repeated effects are Task 0F. - let mut states = self.inner.token_states.lock(); - let open: Vec<(String, String)> = states - .iter() - .filter_map(|(token, state)| match state { - TokenState::Open { claims, .. } => Some((token.clone(), claims.call_id.clone())), - TokenState::Committed { .. } | TokenState::Interrupted { .. } => None, - }) - .collect(); - let mut resources = Vec::new(); - for (token, call_id) in &open { - if let Some(TokenState::Open { - resources: owned, .. - }) = states.insert( - token.clone(), - TokenState::Interrupted { - call_id: call_id.clone(), - }, - ) { - resources.extend(owned); + /// Base `e9da5dc` batch recovery for the managed/default policy. + /// + /// Every open token is transitioned to `Interrupted` and every owned + /// resource released under one token-state critical section, before the + /// first durable interrupt. A durable interrupt failure is returned after + /// that batch, so no later call is left open for a close to retry. + fn recover_open_tokens_managed(&self) -> Result, LifecycleError> { + let starting_at_entry = self.pending_start_calls(); + let (resources, calls) = { + let mut states = self.inner.token_states.lock(); + let tokens: Vec = states + .iter() + .filter_map(|(token, state)| match state { + TokenState::Open { .. } => Some(token.clone()), + _ => None, + }) + .collect(); + let mut resources = Vec::new(); + let mut calls: Vec = Vec::new(); + for token in tokens { + let call_id = match states.get(&token) { + Some(TokenState::Open { claims, .. }) => claims.call_id.clone(), + _ => continue, + }; + // Close the fence under the token-state lock so an admission + // that copied it observes `closed` instead of appending to a + // call the batch already interrupted. + if let Some(TokenState::Open { fence, .. }) = states.get(&token) { + fence.lock().closed = true; + } + if let Some(TokenState::Open { + resources: owned, .. + }) = states.insert( + token, + TokenState::Interrupted { + call_id: call_id.clone(), + }, + ) { + resources.extend(owned); + } + if !calls.contains(&call_id) { + calls.push(call_id); + } } - } - drop(states); + (resources, calls) + }; + self.inner.recovery_pending.lock().clear(); release_resources(resources); - let mut recovered = Vec::with_capacity(open.len()); - for (_, call_id) in open { + let mut recovered = Vec::with_capacity(calls.len()); + for call_id in calls { self.inner.durable.interrupt(&call_id)?; recovered.push(call_id); } + // A start that was parked at entry has no token in `calls`; a start + // that finished during the batch may have inserted its token after the + // table snapshot. Report both as pending unless this batch recovered + // their call through an already visible token. + let mut pending_starts = starting_at_entry; + pending_starts.extend(self.pending_start_calls()); + pending_starts.sort(); + pending_starts.dedup(); + { + let mut pending = self.inner.recovery_pending.lock(); + for call_id in pending_starts { + if !recovered.contains(&call_id) && !pending.contains(&call_id) { + pending.push(call_id); + } + } + pending.sort(); + } + #[cfg(any(test, feature = "workspace-io-fault"))] + { + let observer = self.inner.recovery_pre_generation_observer.lock().clone(); + if let Some(observer) = observer { + observer(); + } + } + self.inner.generation.fetch_add(1, Ordering::SeqCst); + Ok(recovered) + } + + /// Recovers every token that a stopping run left open. + /// + /// Each call is settled by the same call-wide terminal decision the owner + /// and the guard use: a call with an in-flight later publisher is left + /// untouched and reported through [`Self::pending_recovery_calls`] so the + /// owner retries; its ledger is never read while an insertion can still + /// extend it. A call whose durable start is still parked has no token yet + /// and is likewise reported pending, so the token it later inserts is not + /// missed. A duplicate call id cannot exist after the atomic prepare + /// admission, so one decision covers the whole call. In the MCP retention + /// mode a call whose effect worker is still inside the fence + /// (`Publishing`) is likewise left for its own worker. The managed base + /// mode interrupts a `Publishing` token exactly as `e9da5dc` did through + /// the batch path above. + /// + /// In the MCP retention mode an unpublished token is interrupted, while a + /// token that already crossed the fence is settled with the authoritative + /// typed native outcome (compacted to the token's configured output + /// budget), or with an explicit `effect_outcome_unrecorded` record when + /// the ledger is empty. The workspace effect itself is never rolled back + /// by recovery. + pub fn recover_open_tokens(&self) -> Result, LifecycleError> { + #[cfg(any(test, feature = "workspace-io-fault"))] + { + let observer = self.inner.recovery_entry_observer.lock().clone(); + if let Some(observer) = observer { + observer(); + } + } + // The managed/default policy keeps the base `e9da5dc` batch ordering: + // every open token is transitioned and every resource is released + // before the first durable interrupt. A durable failure therefore + // leaves no later call open for a retry, exactly as base. Only the MCP + // retention policy settles per call and keeps published tokens open. + if !self.retains_published_tokens() { + return self.recover_open_tokens_managed(); + } + // Every distinct call is settled by the same call-wide terminal + // decision the owner and the guard use. A call whose publisher is + // still crossing its fence is left untouched and reported pending so + // the owner retries it instead of reading a partial ledger. + let starting_at_entry = self.pending_start_calls(); + let mut calls: Vec = { + let states = self.inner.token_states.lock(); + states + .values() + .filter_map(|state| match state { + TokenState::Open { .. } | TokenState::PendingWrite(_) => { + Some(token_call_id(state).to_string()) + } + _ => None, + }) + .collect() + }; + calls.sort(); + calls.dedup(); + self.inner.recovery_pending.lock().clear(); + let mut recovered = Vec::new(); + for call_id in calls { + match self.settle_call_terminal(&call_id, CallTerminalRequest::Derived)? { + settlement if settlement.decision == CallTerminalDecision::Retained => { + self.inner.recovery_pending.lock().push(call_id); + } + _ => recovered.push(call_id), + } + } + recovered.sort(); + // A call whose durable start is still parked owns no token yet, so the + // table above cannot show it. A start that finished during this pass + // may likewise have inserted its token after the table snapshot. + // Report both as pending so the owner's next recovery covers the token + // the start inserts instead of treating a partial pass as complete. + let mut pending_starts = starting_at_entry; + pending_starts.extend(self.pending_start_calls()); + pending_starts.sort(); + pending_starts.dedup(); + { + let mut pending = self.inner.recovery_pending.lock(); + for call_id in pending_starts { + if !recovered.contains(&call_id) && !pending.contains(&call_id) { + pending.push(call_id); + } + } + pending.sort(); + } + // The tokens are already closed here. A publisher that copied a + // settled fence cannot resume admission because the decision closed + // it; this observation point lets a test prove the window between the + // terminal decision and the generation advance. + #[cfg(any(test, feature = "workspace-io-fault"))] + { + let observer = self.inner.recovery_pre_generation_observer.lock().clone(); + if let Some(observer) = observer { + observer(); + } + } self.inner.generation.fetch_add(1, Ordering::SeqCst); Ok(recovered) } + /// Calls whose durable start is still being persisted. They own their call + /// id before a token exists, so recovery reports them as pending instead of + /// advancing past a call it could not see. + fn pending_start_calls(&self) -> Vec { + let mut starting: Vec = self.inner.preparing_calls.lock().iter().cloned().collect(); + starting.sort(); + starting.dedup(); + starting + } + + /// Calls the last [`Self::recover_open_tokens`] attempt left alone because + /// a later publisher was still extending their ledger, or because their + /// durable start had not inserted a token yet. The owner observes this as + /// pending work and retries instead of reporting the call settled. + pub fn pending_recovery_calls(&self) -> Vec { + let mut pending = self.inner.recovery_pending.lock().clone(); + pending.sort(); + pending + } + + /// Test-only observation at the entry of the call-wide terminal decision. + /// A test can park here, publish a later effect, and prove the single + /// decision either takes that publication into its snapshot or refuses the + /// now-stale receipt. + #[cfg(any(test, feature = "workspace-io-fault"))] + pub fn inject_settle_snapshot_observer_for_test(&self, observer: Arc) { + *self.inner.settle_snapshot_observer.lock() = Some(observer); + } + + /// Test-only observation between a later effect's active-call validation + /// and its final in-flight publisher count on the fence. + #[cfg(any(test, feature = "workspace-io-fault"))] + pub fn inject_admission_recheck_observer_for_test( + &self, + observer: Arc, + ) { + *self.inner.admission_recheck_observer.lock() = Some(observer); + } + + /// Test-only observation after recovery released its per-call claims and + /// before it advances the generation. + #[cfg(any(test, feature = "workspace-io-fault"))] + pub fn inject_recovery_pre_generation_observer_for_test( + &self, + observer: Arc, + ) { + *self.inner.recovery_pre_generation_observer.lock() = Some(observer); + } + + /// Test-only observation at the entry of a recovery attempt, before any + /// token state is read. + #[cfg(any(test, feature = "workspace-io-fault"))] + pub fn inject_recovery_entry_observer_for_test(&self, observer: Arc) { + *self.inner.recovery_entry_observer.lock() = Some(observer); + } + + /// Test-only observation of a settlement commit while it holds the + /// publication fence, after the ledger validation and before the token + /// closure. A test can park here and prove admission is refused atomically. + #[cfg(any(test, feature = "workspace-io-fault"))] + pub fn inject_settle_commit_observer_for_test(&self, observer: Arc) { + *self.inner.settle_commit_observer.lock() = Some(observer); + } + + /// Test-only observation of the unpublished-arm decision. The fence is + /// still held here, so a publisher that copied it cannot acquire it until + /// the token is already interrupted. + #[cfg(any(test, feature = "workspace-io-fault"))] + pub fn inject_settle_unpublished_observer_for_test( + &self, + observer: Arc, + ) { + *self.inner.settle_unpublished_observer.lock() = Some(observer); + } + + /// Test-only observation after a publisher copied its fence and before it + /// locks it. + #[cfg(any(test, feature = "workspace-io-fault"))] + pub fn inject_publisher_copy_observer_for_test(&self, observer: Arc) { + *self.inner.publisher_copy_observer.lock() = Some(observer); + } + + /// Test-only observation at the entry of a retention-mode guest commit, + /// before the token state is read. A test can hold a publisher permit on + /// the exact token while the guest reaches `tool_commit`. + #[cfg(any(test, feature = "workspace-io-fault"))] + pub fn inject_commit_attempt_observer_for_test( + &self, + observer: Arc, + ) { + *self.inner.commit_attempt_observer.lock() = Some(observer); + } + + /// Test-only observation immediately after a retention-mode guest commit + /// is decided and before the guest receives its envelope. + #[cfg(any(test, feature = "workspace-io-fault"))] + pub fn inject_commit_decision_observer_for_test( + &self, + observer: Arc, + ) { + *self.inner.commit_decision_observer.lock() = Some(observer); + } + + /// Explicit RAII abort of one open token. + /// + /// This is the managed/pinned call's abort primitive, not a cancellation + /// or settlement signal. In the default/base mode every open token is + /// interrupted and its resources are released, exactly as before. Only the + /// MCP retention mode keeps an already published or publishing token open + /// for the owner's canonical settlement; recovery and publication also + /// observe the exclusive recovery claim so an abort can never race them. fn interrupt_token(&self, token: &str) -> Result<(), LifecycleError> { let mut states = self.inner.token_states.lock(); - let call_id = match states.get(token) { - Some(TokenState::Open { claims, .. }) => claims.call_id.clone(), + let (call_id, fence) = match states.get(token) { + Some(TokenState::Open { claims, fence, .. }) => { + (claims.call_id.clone(), Arc::clone(fence)) + } + // A terminal write already owns this token; an abort cannot undo + // or interrupt the decision in progress. + Some(TokenState::PendingWrite(_)) => return Ok(()), Some(TokenState::Interrupted { .. } | TokenState::Committed { .. }) => return Ok(()), None => return Err(LifecycleError::TokenUnknown), }; - let resources = match states.insert( - token.to_string(), - TokenState::Interrupted { - call_id: call_id.clone(), - }, - ) { - Some(TokenState::Open { resources, .. }) => resources, - _ => Vec::new(), + // Serialize the phase decision with the publication fence. A + // retention-mode effect that already crossed (or is crossing) the + // fence keeps its right to settle. + let mut fence_state = fence.lock(); + if self.retains_published_tokens() && fence_state.phase != PublicationPhase::Unpublished { + return Ok(()); + } + fence_state.closed = true; + drop(fence_state); + let Some(TokenState::Open { + claims, + resources, + fence, + }) = states.remove(token) + else { + return Ok(()); }; + // The abort is a real terminal write: it takes the same pending state + // as a call-wide decision instead of marking the token terminal before + // durable I/O. A concurrent settler therefore observes retained + // ownership (never a premature NoOp), and a failed abort reopens the + // token with its resources so the lease owner still owes the retry. + let owner = PendingTerminalWrite::new( + self, + vec![( + token.to_string(), + PendingTerminal { + call_id: call_id.clone(), + retry: None, + claims, + resources, + fence, + published: false, + }, + )], + ); + owner.install(&mut states); drop(states); - release_resources(resources); - self.inner.durable.interrupt(&call_id) + match self.inner.durable.interrupt(&call_id) { + Ok(()) => { + let mut resources = Vec::new(); + for (_, pending) in owner.finish(PendingTerminalState::Interrupted) { + resources.extend(pending.resources); + } + release_resources(resources); + Ok(()) + } + Err(error) => { + owner.reopen(); + Err(error) + } + } } } @@ -1020,6 +4192,15 @@ fn json_size(value: &Value) -> usize { .unwrap_or(usize::MAX) } +fn recovery_failure_result( + code: &str, + message: &str, + data: Value, + output_budget: usize, +) -> ToolResult { + ToolResult::failure_with(code, message, "", data, false).compact_to_bytes(output_budget) +} + fn should_rollback_unpublished(error: &LifecycleError) -> bool { matches!( error, @@ -1056,6 +4237,15 @@ pub(crate) fn validate_canonical_result(result: &Value) -> Result<(), LifecycleE )); } } + // A success carrying a typed error is contradictory. Normalizing it + // (either dropping the error or keeping a success with an error) would + // persist a payload that a strict typed replay cannot round-trip as it + // was accepted, so reject the raw shape instead. + if object.get("error").is_some_and(|error| !error.is_null()) { + return Err(LifecycleError::InvalidMetadata( + "success result must not carry an `error`".to_string(), + )); + } } else { let error = object.get("error").and_then(Value::as_object); match error.and_then(|error| error.get("code")) { @@ -1116,3 +4306,7 @@ fn validate_optional_result_fields( } Ok(()) } + +#[cfg(test)] +#[path = "lifecycle_settlement_tests.rs"] +mod lifecycle_settlement_tests; diff --git a/src/capabilities/lifecycle_settlement_tests.rs b/src/capabilities/lifecycle_settlement_tests.rs new file mode 100644 index 00000000..476a3ae9 --- /dev/null +++ b/src/capabilities/lifecycle_settlement_tests.rs @@ -0,0 +1,456 @@ +//! Settlement ownership at the durable boundary. +//! +//! Every case drives the real call-wide terminal decision. The durable double +//! either panics or fails exactly at the acknowledged write, so the assertions +//! cover the state a concurrent settler and the lease owner observe after the +//! write did not complete. + +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Condvar, Mutex}; +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; + +use super::{CapabilityLifecycle, PublishedTokenPolicy, TokenOwnedResource}; +use crate::ToolResult; +use crate::capabilities::{ + AllowAllApproval, CapabilityOwner, CapabilityRisk, DurableStarted, DurableToolLifecycle, + LifecycleClock, LifecycleError, LifecycleLimits, NeverCancelled, PrepareMetadata, + PrepareOutcome, SystemClock, TokenIssuer, UuidIssuer, +}; + +static NEXT_ROOT: AtomicU64 = AtomicU64::new(0); + +fn workspace(label: &str) -> PathBuf { + let sequence = NEXT_ROOT.fetch_add(1, Ordering::Relaxed); + let root = std::env::temp_dir().join(format!( + "lifecycle-settlement-{label}-{}-{sequence}", + std::process::id() + )); + std::fs::create_dir_all(&root).expect("create workspace"); + root +} + +fn owner() -> CapabilityOwner { + CapabilityOwner::new("sol-lifecycle", "session", "run").expect("owner") +} + +fn lifecycle( + root: &std::path::Path, + owner: &CapabilityOwner, + durable: Arc, +) -> CapabilityLifecycle { + CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry") + .workspace(root) + .limits(LifecycleLimits { + max_tool_calls: 8, + max_output_bytes: 8192, + max_summary_bytes: 256, + }) + .deadline_ms(SystemClock.now_ms().saturating_add(60_000)) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(durable) + .approval(Arc::new(AllowAllApproval) as Arc) + .cancellation(Arc::new(NeverCancelled) as Arc) + .published_token_policy(PublishedTokenPolicy::RetainForSettlement) + .build() + .expect("lifecycle") +} + +fn prepare(lifecycle: &CapabilityLifecycle, owner: &CapabilityOwner, call_id: &str) -> String { + match lifecycle + .prepare( + owner, + PrepareMetadata { + run_id: owner.run().to_string(), + call_id: call_id.to_string(), + tool_name: "fixture_tool".to_string(), + argument_digest: "digest".to_string(), + registry_identity: "registry".to_string(), + risk_class: CapabilityRisk::Read, + summary: "fixture".to_string(), + }, + ) + .expect("prepare") + { + PrepareOutcome::Execute { + execution_token, .. + } => execution_token, + other => panic!("expected execute, got {other:?}"), + } +} + +fn success_receipt() -> Value { + json!({"ok": true, "content": "receipt", "data": {}}) +} + +/// Blocking gate whose "started" signal fires at the durable seam under test. +#[derive(Default)] +struct Gate { + started: (Mutex, Condvar), + release: (Mutex, Condvar), +} + +impl Gate { + fn block(&self) { + *self + .started + .0 + .lock() + .unwrap_or_else(|error| error.into_inner()) = true; + self.started.1.notify_all(); + let mut released = self + .release + .0 + .lock() + .unwrap_or_else(|error| error.into_inner()); + while !*released { + released = self + .release + .1 + .wait(released) + .unwrap_or_else(|error| error.into_inner()); + } + } + + fn wait_started(&self) { + let mut started = self + .started + .0 + .lock() + .unwrap_or_else(|error| error.into_inner()); + let deadline = Instant::now() + Duration::from_secs(10); + while !*started { + let remaining = deadline.saturating_duration_since(Instant::now()); + assert!(!remaining.is_zero(), "durable seam was never entered"); + let (guard, _) = self + .started + .1 + .wait_timeout(started, remaining) + .unwrap_or_else(|error| error.into_inner()); + started = guard; + } + } + + fn release(&self) { + *self + .release + .0 + .lock() + .unwrap_or_else(|error| error.into_inner()) = true; + self.release.1.notify_all(); + } +} + +struct CountingResource(AtomicUsize); + +impl TokenOwnedResource for CountingResource { + fn release(&self) { + self.0.fetch_add(1, Ordering::SeqCst); + } +} + +#[derive(Default)] +struct BoundaryDurable { + commits: AtomicUsize, + interrupts: AtomicUsize, + panic_next_commit: AtomicBool, + fail_next_interrupt: AtomicBool, + interrupt_gate: Mutex>>, +} + +impl BoundaryDurable { + fn panic_next_commit(&self) { + self.panic_next_commit.store(true, Ordering::SeqCst); + } + + fn fail_next_interrupt(&self) { + self.fail_next_interrupt.store(true, Ordering::SeqCst); + } + + fn stall_interrupt(&self, gate: Arc) { + *self + .interrupt_gate + .lock() + .unwrap_or_else(|error| error.into_inner()) = Some(gate); + } + + fn commit_count(&self) -> usize { + self.commits.load(Ordering::SeqCst) + } + + fn interrupt_count(&self) -> usize { + self.interrupts.load(Ordering::SeqCst) + } +} + +impl DurableToolLifecycle for BoundaryDurable { + fn assert_active_run(&self, _run_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } + + fn prepare_parent( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result<(), LifecycleError> { + Ok(()) + } + + fn replay_result( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result, LifecycleError> { + Ok(None) + } + + fn commit_started(&self, _record: &DurableStarted) -> Result<(), LifecycleError> { + Ok(()) + } + + fn commit_result(&self, _call_id: &str, result: &Value) -> Result { + if self.panic_next_commit.swap(false, Ordering::SeqCst) { + panic!("injected panic inside the durable commit callback"); + } + self.commits.fetch_add(1, Ordering::SeqCst); + Ok(result.clone()) + } + + fn interrupt(&self, _call_id: &str) -> Result<(), LifecycleError> { + self.interrupts.fetch_add(1, Ordering::SeqCst); + let gate = self + .interrupt_gate + .lock() + .unwrap_or_else(|error| error.into_inner()) + .clone(); + if let Some(gate) = gate { + gate.block(); + } + if self.fail_next_interrupt.swap(false, Ordering::SeqCst) { + return Err(LifecycleError::ResultCommitFailed( + "injected interrupt storage failure".to_string(), + )); + } + Ok(()) + } +} + +#[test] +fn panicking_commit_callback_reopens_the_pending_write_with_its_resources() { + let root = workspace("panic-commit"); + let owner = owner(); + let durable = Arc::new(BoundaryDurable::default()); + let lifecycle = lifecycle( + &root, + &owner, + Arc::clone(&durable) as Arc, + ); + let token = prepare(&lifecycle, &owner, "panic-commit-call"); + lifecycle + .enter_publication(&token) + .expect("publication") + .published_effect(super::NativeEffectRecord::artifact_store( + super::NativeArtifactIdentity { + id: "panic-commit-effect".to_string(), + len: 4, + hash: "hash".to_string(), + }, + )); + let resource = Arc::new(CountingResource(AtomicUsize::new(0))); + lifecycle + .register_resource(&token, Arc::clone(&resource) as Arc) + .expect("register owned resource"); + durable.panic_next_commit(); + + let unwound = catch_unwind(AssertUnwindSafe(|| { + lifecycle.settle_call_with_receipt("panic-commit-call", Some(&success_receipt())) + })); + assert!( + unwound.is_err(), + "the injected durable panic must reach the caller" + ); + assert_eq!( + lifecycle.open_token_count(), + 1, + "an unwound pending write must restore the open token, not strand it" + ); + assert_eq!(lifecycle.committed_token_count(), 0); + assert_eq!(lifecycle.interrupted_token_count(), 0); + assert_eq!( + resource.0.load(Ordering::SeqCst), + 0, + "the reopened token must keep the resource the write never released" + ); + assert_eq!(durable.commit_count(), 0); + + let retried = lifecycle + .settle_call_with_receipt("panic-commit-call", Some(&success_receipt())) + .expect("the reopened token must still be retryable"); + assert_eq!(retried.committed, 1); + assert_eq!(retried.retained, 0); + assert_eq!(lifecycle.open_token_count(), 0); + assert_eq!(lifecycle.committed_token_count(), 1); + assert_eq!(durable.commit_count(), 1); + assert_eq!( + resource.0.load(Ordering::SeqCst), + 0, + "a published token keeps its resources with the native capability" + ); +} + +#[test] +fn failed_interrupt_write_reopens_with_the_resources_its_retry_needs() { + let root = workspace("failed-interrupt"); + let owner = owner(); + let durable = Arc::new(BoundaryDurable::default()); + let lifecycle = lifecycle( + &root, + &owner, + Arc::clone(&durable) as Arc, + ); + let token = prepare(&lifecycle, &owner, "failed-interrupt-call"); + let resource = Arc::new(CountingResource(AtomicUsize::new(0))); + lifecycle + .register_resource(&token, Arc::clone(&resource) as Arc) + .expect("register owned resource"); + durable.fail_next_interrupt(); + + let error = lifecycle + .settle_call_with_receipt("failed-interrupt-call", None) + .expect_err("the injected interrupt failure must surface"); + assert!(matches!(error, LifecycleError::ResultCommitFailed(_))); + assert_eq!( + lifecycle.open_token_count(), + 1, + "a failed durable interrupt must leave the token open and retryable" + ); + assert_eq!(lifecycle.interrupted_token_count(), 0); + assert_eq!( + resource.0.load(Ordering::SeqCst), + 0, + "resources may only be released after the durable interrupt acknowledges" + ); + assert_eq!(durable.interrupt_count(), 1); + + let retried = lifecycle + .settle_call_with_receipt("failed-interrupt-call", None) + .expect("the reopened token must retry the interrupt"); + assert_eq!(retried.interrupted, 1); + assert_eq!(lifecycle.open_token_count(), 0); + assert_eq!(lifecycle.interrupted_token_count(), 1); + assert_eq!(durable.interrupt_count(), 2); + assert_eq!( + resource.0.load(Ordering::SeqCst), + 1, + "the successful retry releases the resource exactly once" + ); +} + +#[test] +fn lease_abort_is_a_pending_write_not_a_premature_terminal_state() { + let root = workspace("lease-abort"); + let owner = owner(); + let durable = Arc::new(BoundaryDurable::default()); + let lifecycle = lifecycle( + &root, + &owner, + Arc::clone(&durable) as Arc, + ); + let token = prepare(&lifecycle, &owner, "lease-abort-call"); + let gate = Arc::new(Gate::default()); + durable.stall_interrupt(Arc::clone(&gate)); + let aborter = { + let lifecycle = lifecycle.clone(); + let token = token.clone(); + std::thread::spawn(move || lifecycle.interrupt_token(&token)) + }; + gate.wait_started(); + + let concurrent = lifecycle + .settle_call_terminal("lease-abort-call", super::CallTerminalRequest::Derived) + .expect("concurrent settlement during the abort"); + assert_eq!( + concurrent.decision, + super::CallTerminalDecision::Retained, + "an abort whose durable interrupt is in flight is not terminal: {concurrent:?}" + ); + assert_eq!(concurrent.retained, 1); + assert_eq!( + lifecycle.interrupted_token_count(), + 0, + "the token must not be marked interrupted before the durable write acknowledges" + ); + let blocked = match lifecycle.enter_publication(&token) { + Ok(_) => panic!("publishers must be fenced while the abort write is pending"), + Err(error) => error, + }; + assert!( + matches!(blocked, LifecycleError::Interrupted), + "{blocked:?}" + ); + + gate.release(); + aborter + .join() + .expect("aborter") + .expect("the abort must succeed"); + assert_eq!(lifecycle.open_token_count(), 0); + assert_eq!(lifecycle.interrupted_token_count(), 1); + let after = lifecycle + .settle_call_terminal("lease-abort-call", super::CallTerminalRequest::Derived) + .expect("post-acknowledgement settlement"); + assert_eq!(after.decision, super::CallTerminalDecision::NoOp); + assert_eq!(after.retained, 0); +} + +#[test] +fn prepared_receipt_without_a_ledger_version_cannot_bind_a_live_publisher() { + let root = workspace("prepared-authority"); + let owner = owner(); + let durable = Arc::new(BoundaryDurable::default()); + let lifecycle = lifecycle( + &root, + &owner, + Arc::clone(&durable) as Arc, + ); + let token = prepare(&lifecycle, &owner, "prepared-authority-call"); + lifecycle + .enter_publication(&token) + .expect("publication") + .published_effect(super::NativeEffectRecord::artifact_store( + super::NativeArtifactIdentity { + id: "prepared-authority-effect".to_string(), + len: 4, + hash: "hash".to_string(), + }, + )); + // Bytes that were never read from the ledger carry no ledger version. A + // prepared settlement must not use them to close a live published token. + let receipt = super::CallReceipt::new( + ToolResult::success("forged", json!({})), + super::ReceiptBinding::Authoritative, + ); + + let settlement = lifecycle + .settle_call_with_call_receipt("prepared-authority-call", &receipt) + .expect("prepared settlement"); + assert_eq!( + settlement.decision, + super::CallTerminalDecision::Retained, + "an unbound receipt must never settle a live publisher: {settlement:?}" + ); + assert_eq!( + durable.commit_count(), + 0, + "nothing may be written from bytes that the ledger never produced" + ); + assert_eq!(lifecycle.open_token_count(), 1); +} diff --git a/src/capabilities/mod.rs b/src/capabilities/mod.rs index 705e8c22..132ba731 100644 --- a/src/capabilities/mod.rs +++ b/src/capabilities/mod.rs @@ -21,15 +21,32 @@ pub use host::{ capability_error_envelope, error_envelope, parse_prepare_metadata, tool_commit, tool_prepare, }; pub use lifecycle::{ - AllowAllApproval, ApprovalGate, CancellationFlag, CapabilityLifecycle, - CapabilityLifecycleBuilder, DurableToolLifecycle, ExecutionLease, GuardianApprovalGate, - LifecycleClock, NeverCancelled, SystemClock, TokenIssuer, UuidIssuer, positive_duration_ms, + AllowAllApproval, AllowAllCallCancellation, ApprovalGate, CallCancellationSource, + CallCancellationState, CallReceipt, CallSettlement, CallTerminalDecision, CallTerminalRequest, + CancellationFlag, CapabilityLifecycle, CapabilityLifecycleBuilder, DurableToolLifecycle, + ExecutionLease, GuardianApprovalGate, LifecycleClock, NativeArtifactIdentity, + NativeEffectError, NativeEffectKind, NativeEffectOutcome, NativeEffectRecord, + NativeEffectStatus, NativeIndeterminateEvidence, NativeObservedFileType, + NativeObservedIdentity, NativeProcessOutcome, NativeProcessState, NativeWriteOutcome, + NeverCancelled, PublicationPermit, PublishedTokenPolicy, SystemClock, TokenIssuer, UuidIssuer, + positive_duration_ms, }; pub(crate) use process::ManagedReapProof; +#[cfg(all(unix, any(test, feature = "workspace-io-fault")))] +pub use process::hold_reap_serial_for_test; pub use process::{ - ProcessCapability, ProcessLimits, ProcessLogCursor, ProcessSnapshot, ProcessSpawn, + ProcessCapability, ProcessCleanupProof, ProcessLimits, ProcessLogCursor, ProcessSnapshot, + ProcessSpawn, ProcessTableLimits, sweep_spawned_children, }; +#[cfg(any(test, feature = "workspace-io-fault"))] +pub use process::{clear_sweep_group_observer_for_test, set_sweep_group_observer_for_test}; +#[cfg(any(test, feature = "workspace-io-fault"))] +pub use process::{registered_child_for_test, sweep_registered_child_for_test}; pub use types::{ CapabilityError, CapabilityOwner, CapabilityRisk, CommitOutcome, DurableStarted, LifecycleError, LifecycleLimits, PrepareMetadata, PrepareOutcome, TokenClaims, }; +#[cfg(all(unix, any(test, feature = "workspace-io-fault")))] +pub use vm_io::bounded_process::pause_retained_reaper_for_test; +#[cfg(target_os = "linux")] +pub use vm_io::run_exec_gate_if_requested; diff --git a/src/capabilities/process.rs b/src/capabilities/process.rs index 2f478dbf..d37653d5 100644 --- a/src/capabilities/process.rs +++ b/src/capabilities/process.rs @@ -4,7 +4,7 @@ //! does not embed terminal or process public-tool dispatch policy. use std::{ - collections::HashMap, + collections::{HashMap, VecDeque}, sync::{ Arc, Mutex, Weak, atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}, @@ -21,7 +21,7 @@ use crate::capabilities::vm_io::{ }; use super::{ - lifecycle::{CapabilityLifecycle, TokenOwnedResource}, + lifecycle::{CapabilityLifecycle, NativeEffectRecord, NativeProcessState, TokenOwnedResource}, types::{CapabilityError, CapabilityOwner, CapabilityRisk, TokenClaims}, }; @@ -61,6 +61,55 @@ impl Default for ProcessLimits { } } +/// Retained process-record and cleanup bounds. +/// +/// These extend the per-spawn [`ProcessLimits`] with the table-wide admission +/// and teardown ceilings that the terminal/process tools already configure via +/// `ProcessToolConfig`. Legacy constructors default to no table cap. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct ProcessTableLimits { + /// Maximum retained process records in one table. + pub max_processes: usize, + /// Maximum retained records for one owner key. + pub max_processes_per_owner: usize, + /// One shared deadline for shutdown/drop cleanup. + pub cleanup_timeout: Duration, +} + +impl Default for ProcessTableLimits { + fn default() -> Self { + Self { + max_processes: usize::MAX, + max_processes_per_owner: usize::MAX, + cleanup_timeout: Duration::from_secs(2), + } + } +} + +impl ProcessTableLimits { + pub fn new( + max_processes: usize, + max_processes_per_owner: usize, + cleanup_timeout: Duration, + ) -> Result { + if max_processes == 0 + || max_processes_per_owner == 0 + || max_processes_per_owner > max_processes + || cleanup_timeout.is_zero() + { + return Err(CapabilityError::new( + "invalid_configuration", + "process table limits must be positive and per-owner must not exceed the table cap", + )); + } + Ok(Self { + max_processes, + max_processes_per_owner, + cleanup_timeout, + }) + } +} + /// Opaque handle returned by spawn. #[derive(Clone, Debug, Eq, PartialEq)] pub struct ProcessSpawn { @@ -68,6 +117,32 @@ pub struct ProcessSpawn { pub pid: u32, } +/// Result of one bounded, proof-carrying process-table teardown. +/// +/// `Clean` is reported only when every owned child was confirmed terminal, +/// reaped, drain-joined and its stdin worker joined under the caller's single +/// absolute cutoff. `TimedOut`/`Failed` retain ownership for a retry; they are +/// never a false Clean. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum ProcessCleanupProof { + Clean, + TimedOut { retained: usize }, + Failed { retained: usize, code: String }, +} + +impl ProcessCleanupProof { + pub fn is_clean(&self) -> bool { + matches!(self, Self::Clean) + } + + pub fn retained(&self) -> usize { + match self { + Self::Clean => 0, + Self::TimedOut { retained } | Self::Failed { retained, .. } => *retained, + } + } +} + /// Result of one bounded managed reaping pass. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum ManagedReapProof { @@ -114,11 +189,114 @@ struct OwnedProcess { generation: u64, handle: BoundedProcessHandle, cancel: ProcessCancel, + /// True for records whose public receipt exposes a process handle. Such + /// records stay addressable until the bounded table cleanup; foreground + /// records whose receipt exposes no handle are retired at their final + /// terminal snapshot. + background: bool, +} + +/// Atomic capacity accounting for one process table. +/// +/// Reservations consume capacity before the OS spawn and are converted to a +/// record exactly once on success. A losing concurrent spawn therefore never +/// executes a child, and every failure/cancel path releases its reservation +/// through RAII. +#[derive(Default)] +struct ProcessTable { + records: HashMap, + reservations: HashMap, +} + +impl ProcessTable { + fn owner_record_count(&self, owner_key: &str) -> usize { + self.records + .values() + .filter(|process| process.owner_key == owner_key) + .count() + + self + .reservations + .values() + .filter(|owner| owner.as_str() == owner_key) + .count() + } + + fn capacity_exhausted(&self, limits: ProcessTableLimits, owner_key: &str) -> bool { + self.records.len() + self.reservations.len() >= limits.max_processes + || self.owner_record_count(owner_key) >= limits.max_processes_per_owner + } +} + +/// Reserved table capacity. Exactly one success may convert it into a record; +/// every other exit removes the placeholder. +struct SpawnReservation<'a> { + capability: &'a ProcessCapability, + id: Option, +} + +struct SpawnConversion { + id: String, + closing: bool, +} + +impl SpawnReservation<'_> { + /// Converts the reservation into the exact record once. + /// + /// The record insert and the reservation removal share one table lock, so + /// a concurrent cleanup always observes at least one owned entry: it can + /// never see an empty table between the reservation and the child record. + /// When the table is closing the record is still inserted (the cleanup + /// loop owns it from then on), but its ID is for internal ownership only: + /// the caller must refuse the spawn and terminate the child promptly. + /// The record receives its own cleanup grace measured from conversion, + /// bounded by any teardown cutoff that is still live. An elapsed cutoff + /// from teardown that waited for this spawn does not shorten that grace. + fn convert(mut self, record: OwnedProcess) -> SpawnConversion { + let id = self.id.take().expect("reservation converted once"); + let now = Instant::now(); + let conversion_cutoff = now + .checked_add(self.capability.inner.table_limits.cleanup_timeout) + .unwrap_or(now); + let closing_cutoff = self + .capability + .cleanup_cutoff() + .filter(|stored| *stored > now) + .map_or(conversion_cutoff, |stored| stored.min(conversion_cutoff)); + let mut table = self + .capability + .inner + .table + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let closing = self.capability.is_closing(); + if closing { + record.handle.note_cleanup_cutoff(closing_cutoff); + } + table.records.insert(id.clone(), record); + table.reservations.remove(&id); + SpawnConversion { id, closing } + } +} + +impl Drop for SpawnReservation<'_> { + fn drop(&mut self) { + let Some(id) = self.id.take() else { + return; + }; + self.capability + .inner + .table + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .reservations + .remove(&id); + } } struct ProcessReaper { inner: Weak, id: String, + generation: u64, handle: BoundedProcessHandle, cancel: ProcessCancel, released: AtomicBool, @@ -131,13 +309,50 @@ impl ProcessReaper { } self.cancel.cancel(); if let Some(inner) = self.inner.upgrade() { - let _ = inner - .table - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) - .remove(&self.id); + // A closing table has already performed (or is retaining) its own + // bounded cleanup proof. A token-resource release must not remove + // a record whose reap was never proven, or the cleanup result + // would be silently upgraded to Clean by an emptied table. + if !inner.closing.load(Ordering::SeqCst) { + let cutoff = Instant::now() + .checked_add(inner.table_limits.cleanup_timeout) + .unwrap_or_else(Instant::now); + if matches!(self.handle.shutdown_within(cutoff), Ok(Some(_))) { + let mut table = inner + .table + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let matches_generation = table + .records + .get(&self.id) + .is_some_and(|owned| owned.generation == self.generation); + if matches_generation { + table.records.remove(&self.id); + } + } + return; + } } - let _ = self.handle.shutdown(); + let _ = self.handle.shutdown_within( + // A closing table fixes one absolute cutoff before it acquires its + // teardown mutex. That cutoff is stored on the table and on every + // retained handle; a release racing the shutdown therefore never + // starts a fresh ordinary grace. + self.handle + .cleanup_cutoff() + .or_else(|| { + self.inner + .upgrade() + .and_then(|inner| inner.cleanup_cutoff()) + }) + .unwrap_or_else(|| { + Instant::now() + .checked_add(self.inner.upgrade().map_or(WRITE_CLEANUP_TIMEOUT, |inner| { + inner.table_limits.cleanup_timeout + })) + .unwrap_or_else(Instant::now) + }), + ); } } @@ -169,9 +384,10 @@ struct ProcessInner { lifecycle: CapabilityLifecycle, owner: CapabilityOwner, host_limits: ProcessLimits, + table_limits: ProcessTableLimits, root: ConfinedFsRoot, workspace: Option>, - table: Mutex>, + table: Mutex, closing: AtomicBool, generation: AtomicU64, /// Actual OS spawn attempts for this run, cumulative across calls and never @@ -188,20 +404,107 @@ struct ProcessInner { write_blocked_hook: Mutex>, before_write_cycle_hook: Mutex>, before_os_spawn_hook: Mutex>, + /// Fires inside the per-call publication fence immediately before the OS + /// spawn. A cancellation requested while it blocks loses to the already + /// started publication. + before_publication_hook: Mutex>, + /// Fires when a completed OS spawn converts its reservation into the + /// table after the table began closing. The record is already visible at + /// this point; the hook only lets a test hold that transition open. + after_closing_conversion_hook: Mutex>, + /// Persistent observation point immediately before the OS spawn syscall. + os_spawn_observer: Mutex>, after_os_spawn_hook: Mutex>, stdin_workers: AtomicUsize, + /// Test-only deterministic withholding of the reap proof so a short cleanup + /// cutoff can be exercised without a permissive wall-clock window. + cleanup_proof_withheld: AtomicBool, + /// Test-only: every subsequent spawn keeps its tree-cleanup proof pending + /// after the real kill, so one absolute cutoff can be measured through the + /// teardown and the destructor. + stall_tree_cleanup: AtomicBool, + /// Linux-only: spawn through the pre-exec gate. Set once during packaged + /// server construction, before the capability is shared. + exec_gate: AtomicBool, + /// Test-only observation point for an ordinary drain join already in + /// progress on an owned handle. + drain_join_observer: Mutex>, + /// The single absolute cutoff used by the last/bounded teardown. Drop uses + /// this same instant instead of starting a fresh ordinary reap grace. + final_cutoff: Mutex>, + /// Observation of the cutoff each stdin worker actually waited against. + /// Kept by handle id after the table record is proven and removed so a + /// teardown assertion can inspect the worker, not only the table clock. + /// The retention is bounded: production must not accumulate one entry per + /// handle it ever observed. + stdin_close_cutoffs: Mutex, +} + +impl ProcessInner { + fn cleanup_cutoff(&self) -> Option { + *self + .final_cutoff + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + } +} + +/// Bounded observation record for stdin-worker cutoffs. +/// +/// The per-handle observation exists for teardown assertions, but it outlives +/// the table record. Keeping one entry per handle ever spawned would grow +/// without bound in a long-lived production process, so only the newest +/// [`MAX_STDIN_CLOSE_OBSERVATIONS`] handles are retained. +const MAX_STDIN_CLOSE_OBSERVATIONS: usize = 64; + +#[derive(Default)] +struct StdinCloseObservations { + order: VecDeque, + cutoffs: HashMap, +} + +impl StdinCloseObservations { + fn record(&mut self, handle: String, cutoff: Instant) { + if !self.cutoffs.contains_key(&handle) { + while self.order.len() >= MAX_STDIN_CLOSE_OBSERVATIONS { + let Some(oldest) = self.order.pop_front() else { + break; + }; + self.cutoffs.remove(&oldest); + } + self.order.push_back(handle.clone()); + } + self.cutoffs.insert(handle, cutoff); + } + + fn get(&self, handle: &str) -> Option { + self.cutoffs.get(handle).copied() + } } impl Drop for ProcessInner { fn drop(&mut self) { - let mut table = self - .table + let stored = *self + .final_cutoff .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); - for owned in table.values() { - terminate_owned(owned); + let cutoff = stored.unwrap_or_else(|| { + Instant::now() + .checked_add(self.table_limits.cleanup_timeout) + .unwrap_or_else(Instant::now) + }); + let records: Vec = { + let mut table = self + .table + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + table.reservations.clear(); + table.records.drain().map(|(_, process)| process).collect() + }; + for owned in records { + owned.cancel.cancel(); + let _ = owned.handle.shutdown_within(cutoff); } - table.clear(); } } @@ -250,9 +553,112 @@ impl ProcessCapability { lifecycle, owner, host_limits, + table_limits: ProcessTableLimits::default(), + root, + workspace: None, + table: Mutex::new(ProcessTable::default()), + closing: AtomicBool::new(false), + generation: AtomicU64::new(1), + spawn_attempts: AtomicUsize::new(0), + #[cfg(test)] + kill_signals: AtomicUsize::new(0), + #[cfg(test)] + reject_reap_proof: AtomicBool::new(false), + after_running_poll_hook: Mutex::new(None), + write_blocked_hook: Mutex::new(None), + before_write_cycle_hook: Mutex::new(None), + before_os_spawn_hook: Mutex::new(None), + before_publication_hook: Mutex::new(None), + after_closing_conversion_hook: Mutex::new(None), + os_spawn_observer: Mutex::new(None), + after_os_spawn_hook: Mutex::new(None), + stdin_workers: AtomicUsize::new(0), + cleanup_proof_withheld: AtomicBool::new(false), + stall_tree_cleanup: AtomicBool::new(false), + exec_gate: AtomicBool::new(false), + drain_join_observer: Mutex::new(None), + final_cutoff: Mutex::new(None), + stdin_close_cutoffs: Mutex::new(StdinCloseObservations::default()), + }), + call: None, + ledger: Arc::new(Mutex::new(CallProcessLedger::default())), + }) + } + + /// Constructs a run-scoped process table with retained-record and shared + /// cleanup bounds derived from the validated process-tool configuration. + pub fn new_with_table_limits( + lifecycle: CapabilityLifecycle, + owner: CapabilityOwner, + host_limits: ProcessLimits, + table_limits: ProcessTableLimits, + ) -> Result { + if table_limits.max_processes == 0 + || table_limits.max_processes_per_owner == 0 + || table_limits.max_processes_per_owner > table_limits.max_processes + || table_limits.cleanup_timeout.is_zero() + { + return Err(CapabilityError::new( + "invalid_configuration", + "process table limits must be positive and per-owner must not exceed the table cap", + )); + } + let mut capability = Self::new(lifecycle, owner, host_limits)?; + let inner = Arc::get_mut(&mut capability.inner).ok_or_else(|| { + CapabilityError::new( + "invalid_configuration", + "new process capability unexpectedly shared", + ) + })?; + inner.table_limits = table_limits; + Ok(capability) + } + + /// Constructs a run-scoped process table from one already-admitted + /// retained workspace root. The root is adopted, never reopened from the + /// lifecycle workspace pathname, so a concurrent pathname replacement + /// cannot give filesystem and process capabilities different identities. + pub(crate) fn new_with_table_limits_and_root( + lifecycle: CapabilityLifecycle, + owner: CapabilityOwner, + host_limits: ProcessLimits, + table_limits: ProcessTableLimits, + root: &Arc, + ) -> Result { + if host_limits.timeout_ms == 0 + || host_limits.stdout_limit == 0 + || host_limits.stderr_limit == 0 + || host_limits.total_limit == 0 + || host_limits.stdin_limit == 0 + || host_limits.log_limit == 0 + { + return Err(CapabilityError::new( + "invalid_configuration", + "process limits must be positive", + )); + } + if table_limits.max_processes == 0 + || table_limits.max_processes_per_owner == 0 + || table_limits.max_processes_per_owner > table_limits.max_processes + || table_limits.cleanup_timeout.is_zero() + { + return Err(CapabilityError::new( + "invalid_configuration", + "process table limits must be positive and per-owner must not exceed the table cap", + )); + } + let root = root + .adopt(root.limits()) + .map_err(|error| CapabilityError::new("workspace_denied", error.to_string()))?; + Ok(Self { + inner: Arc::new(ProcessInner { + lifecycle, + owner, + host_limits, + table_limits, root, workspace: None, - table: Mutex::new(HashMap::new()), + table: Mutex::new(ProcessTable::default()), closing: AtomicBool::new(false), generation: AtomicU64::new(1), spawn_attempts: AtomicUsize::new(0), @@ -264,15 +670,33 @@ impl ProcessCapability { write_blocked_hook: Mutex::new(None), before_write_cycle_hook: Mutex::new(None), before_os_spawn_hook: Mutex::new(None), + before_publication_hook: Mutex::new(None), + after_closing_conversion_hook: Mutex::new(None), + os_spawn_observer: Mutex::new(None), after_os_spawn_hook: Mutex::new(None), stdin_workers: AtomicUsize::new(0), + cleanup_proof_withheld: AtomicBool::new(false), + stall_tree_cleanup: AtomicBool::new(false), + exec_gate: AtomicBool::new(false), + drain_join_observer: Mutex::new(None), + final_cutoff: Mutex::new(None), + stdin_close_cutoffs: Mutex::new(StdinCloseObservations::default()), }), call: None, ledger: Arc::new(Mutex::new(CallProcessLedger::default())), }) } - /// Constructs a run-scoped process table by adopting a live workspace root. + /// Enables the Linux pre-exec gate for every spawn this capability makes. + /// + /// Used only by the packaged `tools serve` server, whose hard exit cannot + /// join a worker parked between the OS spawn and the pid record. It is a + /// no-op on non-Linux builds, and managed/agent callers never enable it. + #[doc(hidden)] + pub fn enable_exec_gate(&self) { + self.inner.exec_gate.store(true, Ordering::Relaxed); + } + pub(crate) fn new_adopted( lifecycle: CapabilityLifecycle, owner: CapabilityOwner, @@ -310,9 +734,10 @@ impl ProcessCapability { lifecycle, owner, host_limits, + table_limits: ProcessTableLimits::default(), root, workspace: Some(workspace), - table: Mutex::new(HashMap::new()), + table: Mutex::new(ProcessTable::default()), closing: AtomicBool::new(false), generation: AtomicU64::new(1), spawn_attempts: AtomicUsize::new(0), @@ -324,8 +749,17 @@ impl ProcessCapability { write_blocked_hook: Mutex::new(None), before_write_cycle_hook: Mutex::new(None), before_os_spawn_hook: Mutex::new(None), + before_publication_hook: Mutex::new(None), + after_closing_conversion_hook: Mutex::new(None), + os_spawn_observer: Mutex::new(None), after_os_spawn_hook: Mutex::new(None), stdin_workers: AtomicUsize::new(0), + cleanup_proof_withheld: AtomicBool::new(false), + stall_tree_cleanup: AtomicBool::new(false), + exec_gate: AtomicBool::new(false), + drain_join_observer: Mutex::new(None), + final_cutoff: Mutex::new(None), + stdin_close_cutoffs: Mutex::new(StdinCloseObservations::default()), }), call: None, ledger: Arc::new(Mutex::new(CallProcessLedger::default())), @@ -466,6 +900,7 @@ impl ProcessCapability { .table .lock() .unwrap_or_else(|p| p.into_inner()) + .records .remove(id); } if self.active_stdin_workers() != 0 { @@ -514,12 +949,14 @@ impl ProcessCapability { .table .lock() .unwrap_or_else(|p| p.into_inner()) + .records .values() .map(|owned| OwnedProcess { owner_key: owned.owner_key.clone(), generation: owned.generation, handle: owned.handle.clone(), cancel: owned.cancel.clone(), + background: owned.background, }) .collect(); if owned.is_empty() { @@ -576,6 +1013,7 @@ impl ProcessCapability { .table .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) + .records .values() .map(|process| process.handle.clone()) .collect(); @@ -634,6 +1072,50 @@ impl ProcessCapability { env_names: &[String], limits: ProcessLimits, stdin: Option<&[u8]>, + ) -> Result { + self.spawn_inner(token, argv, cwd, env_names, limits, stdin, false, false) + } + + /// Test-only entry point that forces a native setup failure after the OS + /// spawn succeeded. It exercises the real post-spawn abort path and the + /// real publication boundary; production callers use [`Self::spawn`]. + #[doc(hidden)] + pub fn spawn_with_post_spawn_failure_for_test( + &self, + token: &str, + argv: &[String], + cwd: &str, + env_names: &[String], + limits: ProcessLimits, + ) -> Result { + self.spawn_inner(token, argv, cwd, env_names, limits, None, true, false) + } + + /// Test-only entry point that forces a real stderr-drainer setup failure + /// after the OS spawn and the stdout drainer succeeded. + #[doc(hidden)] + pub fn spawn_with_stderr_drainer_failure_for_test( + &self, + token: &str, + argv: &[String], + cwd: &str, + env_names: &[String], + limits: ProcessLimits, + ) -> Result { + self.spawn_inner(token, argv, cwd, env_names, limits, None, false, true) + } + + #[allow(clippy::too_many_arguments)] + fn spawn_inner( + &self, + token: &str, + argv: &[String], + cwd: &str, + env_names: &[String], + limits: ProcessLimits, + stdin: Option<&[u8]>, + post_spawn_failure: bool, + stderr_drainer_failure: bool, ) -> Result { let claims = self.authorize(token, CapabilityRisk::Execute)?; let _operation = self.enter_managed_operation( @@ -686,6 +1168,15 @@ impl ProcessCapability { .with_timeout(Duration::from_millis(limits.timeout_ms.max(1))) .with_output_limits(limits.stdout_limit, limits.stderr_limit, limits.total_limit) .with_cancellation_token(cancel.clone()); + if self.inner.exec_gate.load(Ordering::Relaxed) { + // Packaged hard-exit servers gate the direct child before exec so + // no tool code can run before the pid is recorded. Legacy managed + // callers leave this off. + request = request.with_exec_gate(); + } + if self.inner.stall_tree_cleanup.load(Ordering::SeqCst) { + request = request.with_tree_cleanup_stall_for_test(); + } for name in env_names { if !ALLOWED_ENV.contains(&name.as_str()) { return Err(CapabilityError::new( @@ -710,7 +1201,10 @@ impl ProcessCapability { if self.is_closing() { return Err(closing_error()); } - let fence = self.inner.generation.load(Ordering::SeqCst); + // Reserve table and per-owner capacity atomically before the OS spawn. + // A losing concurrent caller never reaches the syscall, and every + // failure/cancel path releases the placeholder through RAII. + let reservation = self.reserve_spawn_slot(&claims.owner.key())?; if managed_call.is_some() { // The run's spawn budget is cumulative across every call and an // attempt is charged before the syscall, never refunded. @@ -730,40 +1224,163 @@ impl ProcessCapability { .unwrap_or_else(|p| p.into_inner()) .attempts += 1; } - let process = BoundedProcess::spawn(request).map_err(map_process_error)?; + if post_spawn_failure { + request = request.with_post_spawn_failure_for_test(); + } + if stderr_drainer_failure { + request = request.with_stderr_drainer_failure_for_test(); + } + // The fence is entered by a one-shot hook that runs inside + // `BoundedProcess::spawn` after every fallible validation and cwd/env + // setup, immediately before the OS spawn syscall. A refused fence + // therefore cannot strand a token whose spawn never became possible. + let permit_slot: Arc>> = + Arc::new(Mutex::new(None)); + let before_slot = Arc::clone(&permit_slot); + let spawned_slot = Arc::clone(&permit_slot); + let pid_slot: Arc>> = Arc::new(Mutex::new(None)); + let pid_record_slot = Arc::clone(&pid_slot); + let lifecycle = self.inner.lifecycle.clone(); + let token_owned = token.to_string(); + let inner = Arc::clone(&self.inner); + let background = !limits.close_after_initial; + request = request.with_before_spawn(Arc::new(move || { + fire_hook(&inner.before_publication_hook); + fire_observer(&inner.os_spawn_observer); + let permit = lifecycle + .enter_publication(&token_owned) + .map_err(BoundedProcessError::Publication)?; + *before_slot + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(permit); + Ok(()) + })); + request = request.with_on_spawned(Arc::new(move |pid| { + *pid_record_slot + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(pid); + if let Some(permit) = spawned_slot + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .take() + { + permit.published_effect(NativeEffectRecord::process_spawn(pid, background)); + } + })); + // The setup-failure sink keeps the real OS child owned by the table + // until a bounded reap and worker exit are independently proven. + let retain_sink: Arc>> = Arc::new(Mutex::new(None)); + request = request.with_setup_failure_sink(Arc::clone(&retain_sink)); + let process = match BoundedProcess::spawn(request) { + Ok(process) => process, + Err(error) => { + if let Some(handle) = retain_sink + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .take() + { + let SpawnConversion { id, closing } = reservation.convert(OwnedProcess { + owner_key: claims.owner.key(), + generation: claims.generation, + handle: handle.clone(), + cancel: cancel.clone(), + background: !limits.close_after_initial, + }); + if !closing { + let cutoff = Instant::now() + .checked_add(self.inner.table_limits.cleanup_timeout) + .unwrap_or_else(Instant::now); + let proven = !self.inner.cleanup_proof_withheld.load(Ordering::SeqCst) + && matches!(handle.shutdown_within(cutoff), Ok(Some(_))); + if proven { + let mut table = self + .inner + .table + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let matches_generation = table + .records + .get(&id) + .is_some_and(|record| record.generation == claims.generation); + if matches_generation { + table.records.remove(&id); + } + } + } + } + let mapped = map_process_error(error); + if let Some(pid) = *pid_slot + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + { + self.inner.lifecycle.note_process_failure( + token, + pid, + mapped.code(), + Some(mapped.message()), + None, + ); + } + return Err(mapped); + } + }; + fire_hook(&self.inner.after_os_spawn_hook); + if let Some(observer) = self + .inner + .drain_join_observer + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .clone() + { + process.set_drain_join_observer_for_test(observer); + } fire_hook(&self.inner.after_os_spawn_hook); let handle = process.lifecycle_handle(); let write_handle = handle.clone(); let pid = handle.pid(); - let id = uuid::Uuid::new_v4().simple().to_string(); + let SpawnConversion { id, closing } = reservation.convert(OwnedProcess { + owner_key: claims.owner.key(), + generation: claims.generation, + handle: handle.clone(), + cancel: cancel.clone(), + background: !limits.close_after_initial, + }); if managed_call.is_some() { + // A closing refusal still owes settlement for the child that + // actually started. Only a usable background spawn is handed off. let mut ledger = self.ledger.lock().unwrap_or_else(|p| p.into_inner()); - ledger - .handles - .push((id.clone(), process.lifecycle_handle())); - ledger.transferred |= managed_background; + ledger.handles.push((id.clone(), handle.clone())); + ledger.transferred |= managed_background && !closing; } + if closing { + // The record remains owned by the table for cleanup proof. Use + // its conversion grace, not an already elapsed table cutoff. + fire_hook(&self.inner.after_closing_conversion_hook); + let cutoff = write_handle.cleanup_cutoff().unwrap_or_else(|| { + Instant::now() + .checked_add(self.inner.table_limits.cleanup_timeout) + .unwrap_or_else(Instant::now) + }); + let _ = write_handle.shutdown_within(cutoff); + return Err(closing_error()); + } + // Observe the actual cutoff this handle's stdin worker waits against. + // The observation outlives the table record so a bounded teardown can + // prove the worker used the same absolute instant as the table. { - let mut table = self - .inner - .table - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - if self.is_closing() || self.inner.generation.load(Ordering::SeqCst) != fence { - drop(table); - let _ = handle.shutdown(); - return Err(closing_error()); - } - table.insert( - id.clone(), - OwnedProcess { - owner_key: claims.owner.key(), - generation: claims.generation, - handle: handle.clone(), - cancel: cancel.clone(), - }, - ); + let inner = Arc::downgrade(&self.inner); + let observed_id = id.clone(); + write_handle.set_stdin_close_observer(Arc::new(move |cutoff| { + if let Some(inner) = inner.upgrade() { + inner + .stdin_close_cutoffs + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .record(observed_id.clone(), cutoff); + } + })); } + // A managed background child outlives this call's token: the run // registry (this capability) owns termination, so no token-scoped // reaper may kill it when the producing call's lease is released. @@ -771,6 +1388,7 @@ impl ProcessCapability { let reaper = Arc::new(ProcessReaper { inner: Arc::downgrade(&self.inner), id: id.clone(), + generation: claims.generation, handle, cancel, released: AtomicBool::new(false), @@ -845,17 +1463,39 @@ impl ProcessCapability { let poll_result = owned.handle.poll(); let mut snap = snapshot(&owned.handle, handle, None, None); match poll_result { - Ok(_) => {} + Ok(_) => { + self.inner.lifecycle.note_process_state( + token, + owned.handle.pid(), + native_process_state(&snap), + ); + } Err(BoundedProcessError::DeadlineElapsed) => { snap.deadline_elapsed = true; + self.inner.lifecycle.note_process_failure( + token, + owned.handle.pid(), + "deadline_elapsed", + Some("process deadline elapsed"), + Some(native_process_state(&snap)), + ); } Err(BoundedProcessError::Cancelled) => { snap.cancelled = true; + self.inner.lifecycle.note_process_failure( + token, + owned.handle.pid(), + "cancelled", + Some("process was cancelled"), + Some(native_process_state(&snap)), + ); } Err(error) => return Err(map_process_error(error)), } if snap.running { fire_hook(&self.inner.after_running_poll_hook); + } else { + self.retire_terminal_record(&owned, handle); } Ok(snap) } @@ -883,7 +1523,13 @@ impl ProcessCapability { match owned.handle.poll() { Ok(_) => { let mut snap = snapshot(&owned.handle, handle, None, None); + self.inner.lifecycle.note_process_state( + token, + owned.handle.pid(), + native_process_state(&snap), + ); if !snap.running { + self.retire_terminal_record(&owned, handle); return Ok(snap); } if wait_deadline.is_some_and(|deadline| Instant::now() >= deadline) { @@ -895,8 +1541,29 @@ impl ProcessCapability { Err(BoundedProcessError::DeadlineElapsed) => { let mut snap = snapshot(&owned.handle, handle, None, None); snap.deadline_elapsed = true; + self.inner.lifecycle.note_process_failure( + token, + owned.handle.pid(), + "deadline_elapsed", + Some("process deadline elapsed"), + Some(native_process_state(&snap)), + ); + if !snap.running { + self.retire_terminal_record(&owned, handle); + } return Ok(snap); } + Err(BoundedProcessError::Cancelled) => { + let snap = snapshot(&owned.handle, handle, None, None); + self.inner.lifecycle.note_process_failure( + token, + owned.handle.pid(), + "cancelled", + Some("process was cancelled"), + Some(native_process_state(&snap)), + ); + return Err(map_process_error(BoundedProcessError::Cancelled)); + } Err(error) => return Err(map_process_error(error)), } } @@ -908,14 +1575,52 @@ impl ProcessCapability { .table .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) + .records .len() } + /// Atomically reserves one table slot and one per-owner slot before the OS + /// spawn. The returned reservation either converts into the exact record + /// once or releases its placeholder on drop. + fn reserve_spawn_slot(&self, owner_key: &str) -> Result, CapabilityError> { + let mut table = self + .inner + .table + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if table.capacity_exhausted(self.inner.table_limits, owner_key) { + return Err(CapabilityError::new( + "process_limit", + "process table or per-owner capacity is exhausted", + )); + } + let id = uuid::Uuid::new_v4().simple().to_string(); + table.reservations.insert(id.clone(), owner_key.to_string()); + drop(table); + Ok(SpawnReservation { + capability: self, + id: Some(id), + }) + } + /// Test-only count of stdin write workers spawned but not joined. pub fn active_stdin_workers(&self) -> usize { self.inner.stdin_workers.load(Ordering::SeqCst) } + /// Test-only count of handles whose initial-stdin writer is still stalled. + #[doc(hidden)] + pub fn pending_initial_stdin_writers_for_test(&self) -> usize { + self.inner + .table + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .records + .values() + .filter(|owned| owned.handle.initial_stdin_pending_for_test()) + .count() + } + /// Test-only view of the exact owned handles, so a producer-level /// observation can inspect the real group it already owns. #[cfg(all(test, unix))] @@ -924,6 +1629,7 @@ impl ProcessCapability { .table .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) + .records .values() .map(|process| process.handle.clone()) .collect() @@ -944,11 +1650,49 @@ impl ProcessCapability { .table .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) + .records .values() .map(|owned| owned.handle.pid()) .collect() } + /// Test-only: handle ids currently recorded in the process table. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn handle_ids_for_test(&self) -> Vec { + self.inner + .table + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .records + .keys() + .cloned() + .collect() + } + + /// Test-only: run the ordinary non-blocking reap path of one recorded + /// handle without managed authorization. + /// + /// This is the exact `harvest` path a normal `poll`/`wait` uses, including + /// its tree cleanup and final `try_wait`. A test uses it to race an exit + /// sweep against a real ordinary reap of the same root. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn reap_handle_for_test(&self, handle: &str) -> bool { + let handle = self + .inner + .table + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .records + .get(handle) + .map(|owned| owned.handle.clone()); + match handle { + Some(handle) => handle.try_wait().is_ok_and(|status| status.is_some()), + None => false, + } + } + /// Test barrier: fires once after a successful poll of a still-running child. pub fn set_after_running_poll_hook(&self, hook: Arc) { *self @@ -985,6 +1729,16 @@ impl ProcessCapability { .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(hook); } + /// Test barrier: fires after a closing table received the converted child + /// record and before the caller terminates that child. + pub fn set_after_closing_conversion_hook(&self, hook: Arc) { + *self + .inner + .after_closing_conversion_hook + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(hook); + } + /// Test barrier: fires after OS spawn and before table insert. pub fn set_after_os_spawn_hook(&self, hook: Arc) { *self @@ -994,6 +1748,81 @@ impl ProcessCapability { .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(hook); } + /// Test barrier: fires inside the per-call publication fence, immediately + /// before the OS spawn syscall. A cancellation requested while it blocks + /// loses to the already-started publication. + pub fn set_before_publication_hook(&self, hook: Arc) { + *self + .inner + .before_publication_hook + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(hook); + } + + /// Persistent observation point that fires for every admitted OS spawn + /// immediately before the syscall, after capacity was reserved and the + /// publication fence was crossed. Concurrent admission tests count it to + /// prove no child beyond the configured slots ever executes. + pub fn set_os_spawn_observer(&self, hook: Arc) { + *self + .inner + .os_spawn_observer + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(hook); + } + + /// Test-only deterministic withholding of the bounded cleanup proof. The + /// child is still killed, but the reaping proof is not reported until the + /// flag is cleared, so a short cutoff can be exercised exactly. + pub fn withhold_cleanup_proof_for_test(&self) { + self.inner + .cleanup_proof_withheld + .store(true, Ordering::SeqCst); + } + + /// Test-only: allow the bounded cleanup proof again for a retry. + pub fn allow_cleanup_proof_for_test(&self) { + self.inner + .cleanup_proof_withheld + .store(false, Ordering::SeqCst); + } + + /// Test-only: keep every subsequent child's tree-cleanup proof pending + /// after the real kill. + #[doc(hidden)] + pub fn stall_tree_cleanup_for_test(&self) { + self.inner.stall_tree_cleanup.store(true, Ordering::SeqCst); + } + + /// Test-only: removes one record from the table and returns its owned + /// handle, so a handle destructor can be exercised without the table + /// teardown reaping the child first. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn take_handle_for_test(&self, pid: u32) -> Option { + let mut table = self + .inner + .table + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let id = table + .records + .iter() + .find(|(_, owned)| owned.handle.pid() == pid) + .map(|(id, _)| id.clone())?; + table.records.remove(&id).map(|owned| owned.handle) + } + + /// Test-only: observe the ordinary drain join of every subsequent child. + #[doc(hidden)] + pub fn set_drain_join_observer_for_test(&self, observer: ProcessOpHook) { + *self + .inner + .drain_join_observer + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(observer); + } + /// Returns a bounded log window. pub fn log( &self, @@ -1076,6 +1905,7 @@ impl ProcessCapability { owned.handle.terminal_status(), Some(ProcessStatus::Exited { .. } | ProcessStatus::Signaled { .. }) ) { + self.retire_terminal_record(&owned, handle); return Ok(()); } #[cfg(test)] @@ -1117,12 +1947,14 @@ impl ProcessCapability { .table .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) + .records .values() .map(|owned| OwnedProcess { owner_key: owned.owner_key.clone(), generation: owned.generation, handle: owned.handle.clone(), cancel: owned.cancel.clone(), + background: owned.background, }) .collect(); for process in owned { @@ -1136,9 +1968,94 @@ impl ProcessCapability { /// OS process created after the fence. Run cleanup must drain committed /// background residue; `cancel_all` kills the process tree but leaves /// handles observable in the table. - /// Seals managed admissions without touching the owner generation or the - /// handle table. Managed cleanup calls this first, then proves each child - /// reap and output drain under its own grace bound. + /// Begins the irreversible closing fence and installs one absolute cutoff + /// on the table and on every already-retained handle while that instant is + /// still live. A child converted after the fence gets its own grace at + /// conversion, so an expired table instant never strands it. + /// + /// The executor calls this before it acquires its own teardown mutex, so a + /// stdin writer close, a token-resource release, and the destructor all + /// observe the same deadline instead of starting a fresh ordinary grace. + pub(crate) fn begin_shutdown_with(&self, cutoff: Instant) { + // Store the absolute cutoff before exposing `closing`. A spawn that + // observes the closing fence must never find `closing = true` with no + // cutoff installed and fall back to an ordinary grace. + { + let mut stored = self + .inner + .final_cutoff + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if stored.is_none_or(|existing| cutoff < existing) { + *stored = Some(cutoff); + } + } + let effective = self.cleanup_cutoff().unwrap_or(cutoff); + let now = Instant::now(); + self.inner.closing.store(true, Ordering::SeqCst); + let handles: Vec = self + .inner + .table + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .records + .values() + .map(|owned| owned.handle.clone()) + .collect(); + // An already-elapsed instant cannot bound any wait. Propagating it + // would overwrite the later per-record deadline of a child that was + // converted after the fence, leaving that child unprovable. Only a + // live teardown instant is installed on the retained handles. + if effective > now { + for handle in handles { + handle.note_cleanup_cutoff(effective); + } + } + } + + /// Absolute cutoff installed by [`Self::begin_shutdown_with`], if any. + pub(crate) fn cleanup_cutoff(&self) -> Option { + *self + .inner + .final_cutoff + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + } + + /// Test-only: absolute cleanup cutoff visible to every participant. + #[doc(hidden)] + pub fn cleanup_cutoff_for_test(&self) -> Option { + self.cleanup_cutoff() + } + + /// Test-only: install the absolute teardown cutoff without starting the + /// kill/close loop, so a concurrent foreground writer can be observed + /// against exactly that instant. + #[doc(hidden)] + pub fn begin_shutdown_for_test(&self, cutoff: Instant) { + self.begin_shutdown_with(cutoff); + } + + /// Test-only: the absolute cutoff the stdin worker of `handle` actually + /// waited against during its last bounded close. + #[doc(hidden)] + pub fn stdin_close_cutoff_for_test(&self, handle: &str) -> Option { + self.inner + .stdin_close_cutoffs + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .get(handle) + } + + /// Test-only: make the next `count` pidfd acquisitions fail, including the + /// original spawn attempt and the retained handle's lazy retry. + #[doc(hidden)] + pub fn fail_pidfd_opens_for_test(&self, count: usize) { + crate::capabilities::vm_io::fail_next_pidfd_opens_for_test(count); + } + + /// Managed cleanup calls this first, then proves each child reap and + /// output drain under its own grace bound. pub(crate) fn begin_managed_shutdown(&self) { self.inner.closing.store(true, Ordering::SeqCst); } @@ -1153,11 +2070,16 @@ impl ProcessCapability { if self.inner.reject_reap_proof.load(Ordering::SeqCst) { return ManagedReapProof::Pending; } + let reservations = self.reservation_count(); + if reservations != 0 { + return ManagedReapProof::Pending; + } let owned: Vec<(String, u64, BoundedProcessHandle)> = self .inner .table .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) + .records .iter() .map(|(id, process)| (id.clone(), process.generation, process.handle.clone())) .collect(); @@ -1171,10 +2093,11 @@ impl ProcessCapability { .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); let matches = table + .records .get(&id) .is_some_and(|owned| owned.generation == generation); if matches { - table.remove(&id); + table.records.remove(&id); } } Ok(None) => return ManagedReapProof::Pending, @@ -1193,7 +2116,10 @@ impl ProcessCapability { /// Advance the owner generation only after every handle was reaped, both /// output streams joined and all stdin workers returned. pub(crate) fn complete_managed_shutdown(&self) -> bool { - if self.table_len() == 0 && self.active_stdin_workers() == 0 { + if self.table_len() == 0 + && self.reservation_count() == 0 + && self.active_stdin_workers() == 0 + { self.inner.closing.store(true, Ordering::SeqCst); self.inner.generation.fetch_add(1, Ordering::SeqCst); true @@ -1202,19 +2128,128 @@ impl ProcessCapability { } } - pub fn shutdown_all(&self) { - self.inner.closing.store(true, Ordering::SeqCst); + fn reservation_count(&self) -> usize { + self.inner + .table + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .reservations + .len() + } + + pub fn shutdown_all(&self) -> ProcessCleanupProof { + let cutoff = Instant::now() + .checked_add(self.inner.table_limits.cleanup_timeout) + .unwrap_or_else(Instant::now); + self.shutdown_all_within(cutoff) + } + + /// Terminates every owned child under one executor-wide cleanup deadline. + /// + /// Ownership is retained until each record is confirmed reaped and its + /// output/stdin workers are joined, or until the same absolute `cutoff` + /// expires. Tree kill, stdin close, drainer joins and the final reap all + /// receive that one cutoff; the destructor later reuses it instead of + /// starting a fresh ordinary reap grace. A record that was converted after + /// the table's fence already expired carries its own grace measured from + /// that conversion, bounded by this call's `cutoff`; the expired table + /// instant never shortens it. + pub fn shutdown_all_within(&self, cutoff: Instant) -> ProcessCleanupProof { + // This call's own budget. It bounds every record below, including one + // that carries a later conversion deadline. + let call_cutoff = cutoff; + self.begin_shutdown_with(cutoff); + // The table stores the earliest absolute cutoff of every teardown in + // progress; a later argument must not replace it for the kill, close, + // reap or drain participants. + let cutoff = self.cleanup_cutoff().unwrap_or(cutoff); self.inner.generation.fetch_add(1, Ordering::SeqCst); - let owned: Vec = { - let mut table = self - .inner - .table - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - table.drain().map(|(_, process)| process).collect() - }; - for process in owned { - terminate_owned(&process); + loop { + let (owned, reservations) = { + let table = self + .inner + .table + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let owned: Vec<(String, OwnedProcess)> = table + .records + .iter() + .map(|(id, owned)| { + ( + id.clone(), + OwnedProcess { + owner_key: owned.owner_key.clone(), + generation: owned.generation, + handle: owned.handle.clone(), + cancel: owned.cancel.clone(), + background: owned.background, + }, + ) + }) + .collect(); + (owned, table.reservations.len()) + }; + if owned.is_empty() && reservations == 0 && self.active_stdin_workers() == 0 { + return ProcessCleanupProof::Clean; + } + let mut failed: Option = None; + for (id, process) in &owned { + process.cancel.cancel(); + // A child converted after the table's fence already expired + // was never covered by that budget: it carries its own full + // grace measured from conversion. The expired table instant + // must not shorten it, while a still-live teardown instant + // still bounds this call, as does the caller's own cutoff. + let now = Instant::now(); + let live_table_cutoff = (cutoff > now).then_some(cutoff); + let record_cutoff = [ + Some(call_cutoff), + process.handle.cleanup_cutoff(), + live_table_cutoff, + ] + .into_iter() + .flatten() + .min() + .unwrap_or(call_cutoff); + let result = process.handle.shutdown_within(record_cutoff); + if self.inner.cleanup_proof_withheld.load(Ordering::SeqCst) { + // The child was still terminated, but the proof is + // deliberately withheld so the caller observes a typed + // timeout instead of a false clean. + let _ = result; + continue; + } + match result { + Ok(Some(_)) => { + let mut table = self + .inner + .table + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let matches = table + .records + .get(id) + .is_some_and(|record| record.generation == process.generation); + if matches { + table.records.remove(id); + } + } + Ok(None) => {} + Err(error) => failed = Some(map_process_error(error).code().to_string()), + } + } + let retained = self.table_len() + reservations + self.active_stdin_workers(); + if let Some(code) = failed { + return ProcessCleanupProof::Failed { retained, code }; + } + if self.table_len() == 0 && reservations == 0 && self.active_stdin_workers() == 0 { + return ProcessCleanupProof::Clean; + } + let now = Instant::now(); + if now >= cutoff { + return ProcessCleanupProof::TimedOut { retained }; + } + thread::sleep(WAIT_POLL_SLICE.min(cutoff.saturating_duration_since(now))); } } @@ -1276,6 +2311,53 @@ impl ProcessCapability { } } + /// Retires a terminal record whose public receipt never exposed a handle. + /// + /// Foreground `terminal` receipts carry only output/status, so keeping the + /// record would consume the bounded table forever. Background handles stay + /// addressable until the bounded table cleanup because the public process + /// API exposes them. + fn retire_terminal_record(&self, owned: &OwnedProcess, handle: &str) { + if owned.background { + return; + } + let terminal = matches!( + owned.handle.terminal_status(), + Some( + crate::capabilities::vm_io::ProcessStatus::Exited { .. } + | crate::capabilities::vm_io::ProcessStatus::Signaled { .. } + ) + ); + if !terminal { + return; + } + if self.inner.cleanup_proof_withheld.load(Ordering::SeqCst) { + // The test seam holds the proof exactly like a stalled real + // drainer; ownership must stay visible for the cleanup retry. + return; + } + let cutoff = Instant::now() + .checked_add(self.inner.table_limits.cleanup_timeout) + .unwrap_or_else(Instant::now); + let proven = matches!(owned.handle.shutdown_within(cutoff), Ok(Some(_))); + if !proven { + // A terminal child whose drain/stdin proof could not be completed + // stays owned. Removing it here would let a later shutdown report + // `Clean` over an unproven record. + return; + } + let removed = self + .inner + .table + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .records + .remove(handle); + if let Some(removed) = removed { + removed.cancel.cancel(); + } + } + fn lookup(&self, token: &str, handle: &str) -> Result { if self.is_closing() { return Err(closing_error()); @@ -1286,7 +2368,7 @@ impl ProcessCapability { .table .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); - let owned = table.get(handle).ok_or_else(|| { + let owned = table.records.get(handle).ok_or_else(|| { CapabilityError::new("process_not_found", "process handle is unknown") })?; if owned.owner_key != claims.owner.key() || owned.generation != claims.generation { @@ -1300,18 +2382,51 @@ impl ProcessCapability { generation: owned.generation, handle: owned.handle.clone(), cancel: owned.cancel.clone(), + background: owned.background, }) } fn remove_and_terminate(&self, handle: &str) { - if let Some(owned) = self + let owned = self .inner .table .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) - .remove(handle) - { - terminate_owned(&owned); + .records + .get(handle) + .map(|owned| OwnedProcess { + owner_key: owned.owner_key.clone(), + generation: owned.generation, + handle: owned.handle.clone(), + cancel: owned.cancel.clone(), + background: owned.background, + }); + let Some(owned) = owned else { + return; + }; + owned.cancel.cancel(); + // Reuse the one absolute cutoff installed by a teardown. Starting a + // fresh ordinary grace here would let an interrupted stdin worker + // outlive the shutdown budget it belongs to. + let cutoff = self.inner.cleanup_cutoff().unwrap_or_else(|| { + Instant::now() + .checked_add(self.inner.table_limits.cleanup_timeout) + .unwrap_or_else(Instant::now) + }); + let proven = matches!(owned.handle.shutdown_within(cutoff), Ok(Some(_))); + if proven { + let mut table = self + .inner + .table + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let matches_generation = table + .records + .get(handle) + .is_some_and(|record| record.generation == owned.generation); + if matches_generation { + table.records.remove(handle); + } } } @@ -1329,20 +2444,37 @@ impl ProcessCapability { let (tx, rx) = mpsc::sync_channel(1); let writer = handle.clone(); let payload = bytes.to_vec(); - let worker = thread::Builder::new() + // The worker itself releases its ownership count when it really + // returns. A stalled worker therefore stays visible to shutdown even + // when its join is abandoned at the cutoff. + self.inner.stdin_workers.fetch_add(1, Ordering::SeqCst); + let inner = Arc::clone(&self.inner); + let worker = match thread::Builder::new() .name("process-cap-write".to_string()) .spawn(move || { - let _ = tx.send(writer.write_stdin(&payload)); - }) - .map_err(|_| { - CapabilityError::new("process_failed", "stdin write worker failed to start") - })?; - self.inner.stdin_workers.fetch_add(1, Ordering::SeqCst); - let workers = &self.inner.stdin_workers; + let result = writer.write_stdin(&payload); + let _ = tx.send(result); + inner.stdin_workers.fetch_sub(1, Ordering::SeqCst); + }) { + Ok(worker) => worker, + Err(_) => { + self.inner.stdin_workers.fetch_sub(1, Ordering::SeqCst); + return Err(CapabilityError::new( + "process_failed", + "stdin write worker failed to start", + )); + } + }; loop { fire_hook(&self.inner.before_write_cycle_hook); if let Err(error) = self.authorize(token, CapabilityRisk::Execute) { - return interrupt_write_worker(handle, worker, &rx, error, workers); + return interrupt_write_worker( + handle, + worker, + &rx, + error, + self.stdin_cleanup_cutoff(), + ); } let now = Instant::now(); if now >= deadline { @@ -1351,24 +2483,24 @@ impl ProcessCapability { worker, &rx, CapabilityError::new("deadline_elapsed", "process deadline elapsed"), - workers, + self.stdin_cleanup_cutoff(), ); } let slice = WRITE_POLL_SLICE.min(deadline.saturating_duration_since(now)); match rx.recv_timeout(slice) { Ok(Ok(wrote)) => { - join_write_worker(worker, workers); + join_write_worker(worker); return Ok(wrote); } Ok(Err(error)) => { - join_write_worker(worker, workers); + join_write_worker(worker); return Err(map_process_error(error)); } Err(RecvTimeoutError::Timeout) => { fire_hook(&self.inner.write_blocked_hook); } Err(RecvTimeoutError::Disconnected) => { - join_write_worker(worker, workers); + join_write_worker(worker); return Err(CapabilityError::new( "process_failed", "stdin write worker ended", @@ -1378,6 +2510,24 @@ impl ProcessCapability { } } + /// The single absolute cutoff for this call's stdin-worker cleanup: the + /// teardown cutoff when one is already stored, otherwise one bounded + /// ordinary write grace. A stored cutoff is never shortened by a local + /// floor, so every participant waits on the same instant. + fn stdin_cleanup_cutoff(&self) -> Instant { + match *self + .inner + .final_cutoff + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + { + Some(cutoff) => cutoff, + None => Instant::now() + .checked_add(WRITE_CLEANUP_TIMEOUT) + .unwrap_or_else(Instant::now), + } + } + fn clamp_limits(&self, caller: ProcessLimits, claims: &TokenClaims) -> ProcessLimits { let host = self.inner.host_limits; let remaining_ms = u64::try_from( @@ -1414,6 +2564,71 @@ fn fire_hook(slot: &Mutex>) { } } +/// Persistent observation point: unlike [`fire_hook`], the installed callback +/// is retained and runs for every admitted operation. +fn fire_observer(slot: &Mutex>) { + let hook = slot + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .clone(); + if let Some(hook) = hook { + hook(); + } +} + +/// Signals and reaps every OS child this process spawned that is still +/// registered, including a child whose worker is parked before converting its +/// spawn reservation into a process-table record. The parent binary calls this +/// immediately before exiting, because exit removes the only worker that could +/// otherwise convert and kill that child. +/// +/// Returns the number of children whose disappearance could not be proven +/// before `deadline`. +pub fn sweep_spawned_children(deadline: Instant) -> usize { + crate::capabilities::vm_io::bounded_process::sweep_spawned_children(deadline) +} + +/// Test-only: signals and reaps one registered child by pid, leaving children +/// owned by concurrent tests untouched. +#[cfg(any(test, feature = "workspace-io-fault"))] +#[doc(hidden)] +pub fn sweep_registered_child_for_test(pid: u32, deadline: Instant) -> bool { + crate::capabilities::vm_io::bounded_process::sweep_registered_child_for_test(pid, deadline) +} + +/// Test-only: whether `pid` still has a live exit-sweep registration. +#[cfg(any(test, feature = "workspace-io-fault"))] +#[doc(hidden)] +pub fn registered_child_for_test(pid: u32) -> bool { + crate::capabilities::vm_io::bounded_process::registered_child_for_test(pid) +} + +/// Test-only: observe the exit sweep while it holds the reap serialization +/// lock, after its `WNOWAIT` check and before its numeric group signal. +#[cfg(any(test, feature = "workspace-io-fault"))] +#[doc(hidden)] +pub fn set_sweep_group_observer_for_test(observer: Arc) { + crate::capabilities::vm_io::bounded_process::set_sweep_group_observer_for_test(Some(observer)); +} + +/// Test-only: remove the exit-sweep group observer. +#[cfg(any(test, feature = "workspace-io-fault"))] +#[doc(hidden)] +pub fn clear_sweep_group_observer_for_test() { + crate::capabilities::vm_io::bounded_process::set_sweep_group_observer_for_test(None); +} + +/// Test-only: hold the process-wide reap serialization lock. +/// +/// A test holds this to model a concurrent reaper that owns the group +/// decision while an ordinary cleanup runs against a short cutoff. The +/// cleanup must then leave the tree pending instead of reporting it clean. +#[cfg(all(unix, any(test, feature = "workspace-io-fault")))] +#[doc(hidden)] +pub fn hold_reap_serial_for_test() -> std::sync::MutexGuard<'static, ()> { + crate::capabilities::vm_io::bounded_process::hold_reap_serial_for_test() +} + fn closing_error() -> CapabilityError { CapabilityError::new("capability_unavailable", "process capability is closing") } @@ -1423,20 +2638,31 @@ fn interrupt_write_worker( worker: thread::JoinHandle<()>, rx: &mpsc::Receiver>, interrupt: CapabilityError, - workers: &AtomicUsize, + cutoff: Instant, ) -> Result { - let _ = handle.close_stdin(); - let outcome = match rx.recv_timeout(WRITE_CLEANUP_TIMEOUT) { - Ok(Ok(wrote)) => Ok(wrote), - Ok(Err(_)) | Err(_) => Err(interrupt), + let _ = handle.close_stdin_within(cutoff); + let now = Instant::now(); + let remaining = cutoff.saturating_duration_since(now); + let (outcome, finished) = if remaining.is_zero() { + (Err(interrupt), false) + } else { + match rx.recv_timeout(remaining) { + Ok(Ok(wrote)) => (Ok(wrote), true), + Ok(Err(_)) => (Err(interrupt), true), + Err(_) => (Err(interrupt), false), + } }; - join_write_worker(worker, workers); + if finished { + // The worker signalled completion before the cutoff; joining it now is + // an immediate no-op. A worker that missed the cutoff is left owned by + // its own counter instead of an unbounded join here. + join_write_worker(worker); + } outcome } -fn join_write_worker(worker: thread::JoinHandle<()>, workers: &AtomicUsize) { +fn join_write_worker(worker: thread::JoinHandle<()>) { let _ = worker.join(); - workers.fetch_sub(1, Ordering::SeqCst); } fn terminate_owned(owned: &OwnedProcess) { @@ -1444,6 +2670,22 @@ fn terminate_owned(owned: &OwnedProcess) { let _ = owned.handle.shutdown(); } +fn native_process_state(snap: &ProcessSnapshot) -> NativeProcessState { + if snap.running { + NativeProcessState::Running + } else if snap.signaled { + NativeProcessState::Signaled { + signal: snap.signal.unwrap_or(0), + } + } else if snap.unknown { + NativeProcessState::Unknown + } else { + NativeProcessState::Exited { + code: snap.exit_code, + } + } +} + fn snapshot( handle: &BoundedProcessHandle, id: &str, @@ -1520,7 +2762,47 @@ fn map_process_error(error: BoundedProcessError) -> CapabilityError { BoundedProcessError::InvalidRequest(_) => "invalid_request", BoundedProcessError::StdinClosed => "stdin_closed", BoundedProcessError::StdinTooLarge => "budget_exceeded", + BoundedProcessError::ShuttingDown => "closing", + BoundedProcessError::Publication(error) => return CapabilityError::from(error), _ => "process_failed", }; CapabilityError::new(code, error.to_string()) } + +#[cfg(test)] +mod stdin_close_observation_tests { + use super::*; + + #[test] + fn observation_retention_is_bounded_and_fifo() { + let mut observations = StdinCloseObservations::default(); + let base = Instant::now(); + for index in 0..MAX_STDIN_CLOSE_OBSERVATIONS + 8 { + observations.record( + format!("handle-{index}"), + base + Duration::from_millis(index as u64), + ); + } + assert_eq!( + observations.cutoffs.len(), + MAX_STDIN_CLOSE_OBSERVATIONS, + "the observation record must stay bounded" + ); + assert!( + observations.get("handle-0").is_none(), + "the oldest observation must be evicted first" + ); + assert!( + observations + .get(&format!("handle-{}", MAX_STDIN_CLOSE_OBSERVATIONS + 7)) + .is_some(), + "the newest observation must be retained" + ); + observations.record("handle-7".to_string(), base); + assert_eq!( + observations.cutoffs.len(), + MAX_STDIN_CLOSE_OBSERVATIONS, + "updating an existing observation must not grow the record" + ); + } +} diff --git a/src/capabilities/types.rs b/src/capabilities/types.rs index 571c0828..43ca85bf 100644 --- a/src/capabilities/types.rs +++ b/src/capabilities/types.rs @@ -167,6 +167,10 @@ pub enum LifecycleError { StartedCommitFailed(String), ResultCommitFailed(String), ResultTooLarge, + /// A guest `tool_commit` was refused because a publisher still owns the + /// call. The token stays open; the owner settles the native receipt once + /// the publisher finishes. + CommitRetained, Interrupted, RegistryMismatch, InvalidMetadata(String), @@ -191,6 +195,7 @@ impl LifecycleError { Self::StartedCommitFailed(_) => "started_commit_failed", Self::ResultCommitFailed(_) => "result_commit_failed", Self::ResultTooLarge => "result_too_large", + Self::CommitRetained => "commit_retained", Self::Interrupted => "interrupted", Self::RegistryMismatch => "registry_mismatch", Self::InvalidMetadata(_) => "invalid_metadata", @@ -223,6 +228,9 @@ impl LifecycleError { message.clone() } Self::ResultTooLarge => "tool result exceeds output budget".to_string(), + Self::CommitRetained => { + "guest commit retained until the in-flight publisher settles".to_string() + } Self::Interrupted => "execution was interrupted".to_string(), Self::RegistryMismatch => { "registry identity does not match frozen snapshot".to_string() diff --git a/src/capabilities/vm_io/bounded_process.rs b/src/capabilities/vm_io/bounded_process.rs index f6f15cd1..f5b1c10f 100644 --- a/src/capabilities/vm_io/bounded_process.rs +++ b/src/capabilities/vm_io/bounded_process.rs @@ -16,54 +16,2134 @@ use std::io::{Read, Write}; use std::ops::Deref; use std::path::PathBuf; use std::process::{Child, ExitStatus, Stdio}; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Condvar, Mutex, MutexGuard}; use std::thread::{self, JoinHandle}; use std::time::{Duration, Instant}; use super::confined_fs::ConfinedDirectory; +#[cfg(target_os = "linux")] +use super::exec_gate; + +use crate::capabilities::types::LifecycleError; + +#[cfg(windows)] +use super::windows_process_tree::ProcessJob; +#[cfg(unix)] +use std::os::unix::process::CommandExt; +#[cfg(unix)] +use std::os::unix::process::ExitStatusExt; +#[cfg(windows)] +use std::os::windows::process::CommandExt; + +/// Maximum number of argv entries accepted by [`BoundedProcessRequest`]. +pub const MAX_ARG_COUNT: usize = 256; +/// Maximum byte length of one argv entry. +pub const MAX_ARG_ITEM_BYTES: usize = 16 * 1024; +/// Maximum combined byte length of all argv entries. +pub const MAX_ARG_TOTAL_BYTES: usize = 256 * 1024; +/// Maximum number of explicitly supplied environment entries. +pub const MAX_ENV_COUNT: usize = 128; +/// Maximum byte length of an environment key. +pub const MAX_ENV_KEY_BYTES: usize = 256; +/// Maximum byte length of an environment value. +pub const MAX_ENV_VALUE_BYTES: usize = 16 * 1024; +/// Maximum combined byte length of environment keys and values. +pub const MAX_ENV_TOTAL_BYTES: usize = 256 * 1024; +/// Maximum initial stdin payload. +pub const MAX_STDIN_BYTES: usize = 16 * 1024 * 1024; +/// Maximum one-shot stdin write payload. +pub const MAX_STDIN_WRITE_BYTES: usize = 16 * 1024 * 1024; +/// Maximum accepted timeout or relative deadline. +pub const MAX_TIMEOUT: Duration = Duration::from_secs(60 * 60); +/// Maximum retained output across both streams. +pub const MAX_OUTPUT_BYTES: usize = 16 * 1024 * 1024; +/// Default request timeout. +pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30); +/// Default per-stream and total output limit. +pub const DEFAULT_OUTPUT_BYTES: usize = 1024 * 1024; +/// Polling slice used by cancellable stdin/drainer/wait loops. +const WAIT_SLICE: Duration = Duration::from_millis(5); +/// Bound for joining workers and reaping a killed child after SIGKILL/Job. +const CLEANUP_GRACE: Duration = Duration::from_millis(200); +/// Absolute extension of the caller's sweep deadline during which a +/// reservation that publishes late is still drained, signalled and reaped. +/// The spawn fence is already latched, so the registry reaches quiescence at +/// the latest when every pre-fence reservation has published or dropped. +const LATE_PUBLISHER_GRACE: Duration = Duration::from_secs(1); +/// Poll slice used by the sweep while it waits for a late publication. +const LATE_PUBLISHER_POLL: Duration = Duration::from_millis(5); + +static NEXT_PROCESS_HANDLE: AtomicU64 = AtomicU64::new(1); + +/// Serializes every numeric process-group signal, and the `waitid(WNOWAIT)` +/// observation that decides whether the signal is safe, against every other +/// reaper of the same root. +/// +/// `signal_owned_group` observes a root without reaping it and then signals the +/// numeric group `-pid`. If an ordinary `try_wait` reaped that same root in +/// between, the kernel could already have recycled the pid and, with it, the +/// group id, so the signal could hit an unrelated process. Both the exit sweep +/// and the ordinary cleanup path therefore take this lock around the whole +/// observation-plus-signal decision, and the sweep reaps the root inside the +/// same critical section. +static REAP_SERIAL: Mutex<()> = Mutex::new(()); + +/// How long an ownership-checked group signal waits for the reap lock. +/// +/// The lock is only ever held across two syscalls. A caller that cannot take it +/// before its cleanup cutoff must not block past that cutoff: another reaper +/// owns the decision and signals the group itself. +fn reap_serial_before(cutoff: Instant) -> Option> { + loop { + match REAP_SERIAL.try_lock() { + Ok(guard) => return Some(guard), + // Poisoning is irrelevant: the lock protects ordering, not state. + Err(std::sync::TryLockError::Poisoned(poisoned)) => return Some(poisoned.into_inner()), + Err(std::sync::TryLockError::WouldBlock) => { + let now = Instant::now(); + if now >= cutoff { + return None; + } + thread::sleep(Duration::from_millis(1).min(cutoff.saturating_duration_since(now))); + } + } + } +} + +/// Outcome of one ownership-checked group decision. +/// +/// The four cases are disjoint on purpose: "the lock was not taken", "the +/// observation was inconclusive" and "the observation proved the root +/// released" must never collapse into one boolean. Only a proven `Signalled` +/// or `Released` decision may be used as the tree-cleanup proof. +#[cfg(unix)] +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum GroupDecision { + /// The reap lock was not acquired before the caller's cutoff. No + /// observation and no signal were performed. + NotDecided, + /// The non-reaping observation proved the exact root was still our + /// unreaped child, so the numeric process-group signal was delivered. + Signalled, + /// The observation proved `ECHILD`: no unreaped child with this exact + /// identity remains, so no numeric group signal was delivered. + Released, + /// The observation proved nothing (for example `EINTR`, or a pid that + /// cannot be represented). No numeric group signal may be delivered, and + /// the tree must stay pending for a later bounded attempt. + Inconclusive, +} + +/// What one non-reaping `waitid(WNOWAIT)` observation proved about a root. +#[cfg(unix)] +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum RootOwnership { + /// The unreaped child still exists (running or zombie), so its numeric pid + /// and process-group id are still reserved. + Unreaped, + /// `ECHILD`: no unreaped child with this exact identity remains. + Released, + /// Any other result (for example `EINTR`) proved nothing. No numeric group + /// operation may follow an unknown observation. + Unknown, +} + +/// Test-only: the one pid whose next ownership observation must appear +/// inconclusive. +/// +/// Kept in-process next to the observation itself, so the forced result is +/// one-shot, bound to the fixture's own root and can never affect another +/// process. It is only compiled for in-crate tests. +#[cfg(all(test, unix))] +static INCONCLUSIVE_GROUP_OBSERVATION: Mutex> = Mutex::new(None); + +/// Test-only: make the next `waitid(WNOWAIT)` observation of `pid` report +/// `Unknown`, as an interrupted syscall would. +#[cfg(all(test, unix))] +fn force_inconclusive_group_observation_once_for_test(pid: u32) { + *INCONCLUSIVE_GROUP_OBSERVATION + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(pid); +} + +/// Test-only: consume the one-shot inconclusive observation for this exact +/// pid, if it was armed. +#[cfg(all(test, unix))] +fn take_inconclusive_group_observation_for_test(pid: libc::pid_t) -> bool { + let Ok(pid) = u32::try_from(pid) else { + return false; + }; + let mut armed = INCONCLUSIVE_GROUP_OBSERVATION + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if armed.as_ref() == Some(&pid) { + *armed = None; + true + } else { + false + } +} + +/// One non-reaping ownership observation, exact through a pidfd on Linux when +/// one is available. +#[cfg(unix)] +fn observe_root_ownership( + pid: libc::pid_t, + pidfd: Option, +) -> RootOwnership { + #[cfg(all(test, unix))] + if take_inconclusive_group_observation_for_test(pid) { + // Forces the same state an interrupted `waitid` produces: nothing was + // proven, so no numeric group operation may follow. + return RootOwnership::Unknown; + } + #[cfg(target_os = "linux")] + let (idtype, id) = match pidfd { + Some(pidfd) => (libc::P_PIDFD, pidfd as libc::id_t), + None => (libc::P_PID, pid as libc::id_t), + }; + #[cfg(not(target_os = "linux"))] + let (idtype, id) = { + let _ = pidfd; + (libc::P_PID, pid as libc::id_t) + }; + let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() }; + // SAFETY: `info` is a valid out-pointer. WNOHANG|WNOWAIT neither blocks + // nor releases the child. + let result = unsafe { + libc::waitid( + idtype, + id, + &mut info, + libc::WEXITED | libc::WNOHANG | libc::WNOWAIT, + ) + }; + if result == 0 { + return RootOwnership::Unreaped; + } + match std::io::Error::last_os_error().raw_os_error() { + Some(libc::ECHILD) => RootOwnership::Released, + _ => RootOwnership::Unknown, + } +} + +/// The single place a process-group signal is sent, with the reap lock already +/// held. +/// +/// The exit sweep and the ordinary process reaper both call this through +/// [`signal_owned_group`]. `waitid(WNOWAIT)` proves ownership: only a pid that +/// is still our unreaped child may name the group, because reaping the root +/// frees the pid and the kernel may then reuse the number for an unrelated +/// group. On Linux the observation uses the exact pidfd when one exists, so a +/// recycled numeric pid can never satisfy it. `ECHILD` therefore skips the +/// numeric signal; an unknown result (for example `EINTR`) also skips it +/// because nothing was proven. The pidfd signal is exact and is always +/// attempted, so a root released by another owner is still killed. +#[cfg(unix)] +fn signal_owned_group_locked(pid: u32, pidfd: Option) -> GroupDecision { + signal_owned_group_locked_with(pid, pidfd, true) +} + +/// [`signal_owned_group_locked`] for the atomic worker/retained attempts. +/// +/// Those attempts hold the registry lock as well as the reap lock, so the +/// test-only group observer is deferred until both locks have dropped. The +/// ordinary sweep and reclaim paths keep the pre-existing immediate +/// observation, whose blocking test depends on it. +#[cfg(unix)] +fn signal_owned_group_locked_quiet( + pid: u32, + pidfd: Option, +) -> GroupDecision { + signal_owned_group_locked_with(pid, pidfd, false) +} + +#[cfg(unix)] +fn signal_owned_group_locked_with( + pid: u32, + pidfd: Option, + notify_observer: bool, +) -> GroupDecision { + let Ok(raw) = libc::pid_t::try_from(pid) else { + // A pid that cannot be represented proves nothing about the tree. + // Never let cleanup treat this as a completed decision. + return GroupDecision::Inconclusive; + }; + #[cfg(not(any(test, feature = "workspace-io-fault")))] + let _ = notify_observer; + let ownership = observe_root_ownership(raw, pidfd); + let owned = ownership == RootOwnership::Unreaped; + if owned { + #[cfg(any(test, feature = "workspace-io-fault"))] + if notify_observer { + note_group_signal_observed_for_test(pid); + } + // SAFETY: a negative pid names the process group created for this + // child; ESRCH is expected if the group is already empty. The WNOWAIT + // observation above proved this is still our unreaped child, and the + // reap lock keeps it unreaped until this signal has been delivered. + unsafe { + libc::kill(-raw, libc::SIGKILL); + } + // Without a pidfd the exact per-pid signal is the only fallback on + // platforms that do not have one. + #[cfg(not(target_os = "linux"))] + unsafe { + libc::kill(raw, libc::SIGKILL); + } + } + #[cfg(target_os = "linux")] + if let Some(pidfd) = pidfd { + // SAFETY: `pidfd` is an owned handle to this exact process; a recycled + // pid cannot be signalled through it. + unsafe { + libc::syscall( + libc::SYS_pidfd_send_signal, + pidfd, + libc::SIGKILL, + std::ptr::null::(), + 0, + ); + } + } + #[cfg(not(target_os = "linux"))] + let _ = pidfd; + match ownership { + RootOwnership::Unreaped => GroupDecision::Signalled, + RootOwnership::Released => GroupDecision::Released, + RootOwnership::Unknown => GroupDecision::Inconclusive, + } +} + +/// [`signal_owned_group_locked`] under the reap lock. +/// +/// Returns the decision so a caller can tell "not owned" and "could not +/// observe" from a real signal or release. +#[cfg(unix)] +fn signal_owned_group( + pid: u32, + pidfd: Option, + cutoff: Instant, +) -> GroupDecision { + let Some(_serial) = reap_serial_before(cutoff) else { + return GroupDecision::NotDecided; + }; + signal_owned_group_locked(pid, pidfd) +} + +/// Result of one nonblocking, identity-checked reap observation. +#[cfg(unix)] +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum ReapObservation { + /// The exact child is gone: this call reaped it, or `ECHILD` proved that + /// no unreaped child with this identity remains. + Reaped, + /// The child still exists, or the wait proved nothing (`EINTR` and every + /// error other than `ECHILD`). Ownership must be kept. + Unproven, +} + +/// One nonblocking reap observation, exact through a pidfd on Linux when one +/// is available. +/// +/// Only a real status result for this exact identity, or `ECHILD`, counts as +/// proof. `EINTR` is retried a bounded number of times and is never proof by +/// itself. +#[cfg(unix)] +fn wait_reaped_once(pid: u32, pidfd: Option) -> ReapObservation { + #[cfg(target_os = "linux")] + if let Some(pidfd) = pidfd { + let mut attempts = 0u8; + loop { + let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() }; + // SAFETY: `info` is a valid out-pointer. WEXITED|WNOHANG reaps a + // terminal child through the exact pidfd without blocking. + let result = unsafe { + libc::waitid( + libc::P_PIDFD, + pidfd as libc::id_t, + &mut info, + libc::WEXITED | libc::WNOHANG, + ) + }; + if result == 0 { + return if unsafe { info.si_pid() } > 0 { + ReapObservation::Reaped + } else { + ReapObservation::Unproven + }; + } + match std::io::Error::last_os_error().raw_os_error() { + Some(libc::ECHILD) => return ReapObservation::Reaped, + Some(libc::EINTR) if attempts < 8 => attempts += 1, + _ => return ReapObservation::Unproven, + } + } + } + let Ok(raw) = libc::pid_t::try_from(pid) else { + return ReapObservation::Unproven; + }; + #[cfg(not(target_os = "linux"))] + let _ = pidfd; + let mut attempts = 0u8; + loop { + let mut status: libc::c_int = 0; + // SAFETY: `raw` was recorded as our child; WNOHANG never blocks. + let result = unsafe { libc::waitpid(raw, &mut status, libc::WNOHANG) }; + if result == raw { + return ReapObservation::Reaped; + } + if result == 0 { + return ReapObservation::Unproven; + } + match std::io::Error::last_os_error().raw_os_error() { + Some(libc::ECHILD) => return ReapObservation::Reaped, + Some(libc::EINTR) if attempts < 8 => attempts += 1, + _ => return ReapObservation::Unproven, + } + } +} + +/// Test-only: invoked by `signal_owned_group` while the reap serialization +/// lock is held, immediately before the numeric group signal. +/// +/// Both the sweep and the ordinary reaper call it, so a test can count the +/// numeric group signals a root really received and prove that a group id which +/// was not proven ours was never signalled. +#[cfg(any(test, feature = "workspace-io-fault"))] +type SweepGroupObserver = Arc; + +#[cfg(any(test, feature = "workspace-io-fault"))] +static SWEEP_GROUP_OBSERVER: Mutex> = Mutex::new(None); + +#[cfg(any(test, feature = "workspace-io-fault"))] +fn note_group_signal_observed_for_test(pid: u32) { + let observer = SWEEP_GROUP_OBSERVER + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .clone(); + if let Some(observer) = observer { + observer(pid); + } +} + +/// Test-only: install the group-observation observer. `None` clears it. +#[cfg(any(test, feature = "workspace-io-fault"))] +#[doc(hidden)] +pub fn set_sweep_group_observer_for_test(observer: Option) { + *SWEEP_GROUP_OBSERVER + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = observer; +} + +/// Process-wide record of every OS child between the spawn syscall and the +/// owning handle's drop. +/// +/// The process table can legitimately show only a reservation while a worker +/// owns a just-spawned child, and `process::exit` cannot wait for that worker +/// to convert the reservation into a killable record. This registry is the +/// independent guarantee: each pid (with a Linux pidfd, so a recycled pid can +/// never be signalled) is recorded at the OS spawn, and the exit sweep can +/// signal and reap it directly. +/// +/// The registry is also the spawn fence. A worker reserves an in-flight slot +/// before the syscall, records the pid immediately after it, and publishes the +/// reservation once the child is fully owned. Every reservation carries one +/// explicit state record under one lock, so the sweep, the publisher and the +/// destructor always agree about who owns a child. The sweep latches `closing`, +/// waits for every in-flight reservation to record or publish, drains the +/// recorded children, and only then signals them. A spawn that starts after the +/// latch never reaches the syscall, and a child that exists is always visible +/// to the sweep before it exits. +mod spawn_registry { + // `Registry` and its reservation map are platform-independent state; only + // the pidfd/entry helpers are Unix-gated. Keeping this import unconditional + // is what lets the Windows build use the same registry. + use std::collections::HashMap; + #[cfg(any(test, feature = "workspace-io-fault"))] + use std::io::Write; + use std::sync::{Condvar, OnceLock}; + use std::time::{Duration, Instant}; + + #[cfg(all(test, unix))] + use super::AtomicUsize; + #[cfg(unix)] + use super::MutexGuard; + use super::{AtomicU64, Mutex, Ordering, thread}; + + #[cfg(target_os = "linux")] + use std::os::fd::{FromRawFd, OwnedFd}; + + /// Test-only: announce that the exit sweep reached the registry. + /// + /// The fault feature gates the hook; a production build never compiles a + /// file write into the sweep. + #[cfg(any(test, feature = "workspace-io-fault"))] + pub(super) fn note_sweep_started_for_test() { + if let Some(path) = std::env::var_os("RUSTSCRIPT_AGENT_TEST_SWEEP_MARKER") { + let _ = std::fs::write(path, b"started"); + } + } + + /// Test-only: park a worker between the successful OS spawn and the + /// recording of its pid. + /// + /// This is the narrowest ownership window: the child exists but the + /// registry cannot name it yet. The hook is inert unless the process was + /// started with the park-file environment variable. + #[cfg(any(test, feature = "workspace-io-fault"))] + pub(crate) fn pause_between_spawn_and_record_for_test(pid: u32) { + let Some(park) = std::env::var_os("RUSTSCRIPT_AGENT_TEST_SPAWN_BEFORE_RECORD_PARK_FILE") + else { + return; + }; + // One-shot, like the post-record hook, so later spawns of the same + // process proceed normally. + if std::path::Path::new(&park).exists() { + return; + } + if std::fs::write(&park, pid.to_string()).is_err() { + return; + } + let Some(release) = + std::env::var_os("RUSTSCRIPT_AGENT_TEST_SPAWN_BEFORE_RECORD_RELEASE_FILE") + else { + return; + }; + let deadline = Instant::now() + Duration::from_secs(30); + while !std::path::Path::new(&release).exists() && Instant::now() < deadline { + thread::sleep(Duration::from_millis(5)); + } + } + + /// Test-only: park a worker after its pid is recorded and before the + /// pre-exec gate is released. + /// + /// This is the registration-to-release seam: the exit sweep can drain the + /// reservation and terminate the still-parked gate, after which the + /// worker's release write fails. The worker must not signal or reap a + /// reservation the sweep owns. Inert unless the process was started with + /// the park-file variable. + #[cfg(all(target_os = "linux", any(test, feature = "workspace-io-fault")))] + pub(crate) fn pause_between_record_and_release_for_test(pid: u32) { + let Some(park) = std::env::var_os("RUSTSCRIPT_AGENT_TEST_SPAWN_BEFORE_RELEASE_PARK_FILE") + else { + return; + }; + // One-shot, like the other spawn hooks, so later spawns proceed. + if std::path::Path::new(&park).exists() { + return; + } + if std::fs::write(&park, pid.to_string()).is_err() { + return; + } + let Some(release) = + std::env::var_os("RUSTSCRIPT_AGENT_TEST_SPAWN_BEFORE_RELEASE_RELEASE_FILE") + else { + return; + }; + let deadline = Instant::now() + Duration::from_secs(30); + while !std::path::Path::new(&release).exists() && Instant::now() < deadline { + thread::sleep(Duration::from_millis(5)); + } + } + + /// Test-only: park a worker after its pid is recorded and before it + /// publishes the reservation. + /// + /// This is the window in which the exit sweep can drain and reap the child + /// while the worker still holds an unpublished reservation. The hook is + /// inert unless the process was started with the park-file environment + /// variable. + #[cfg(any(test, feature = "workspace-io-fault"))] + pub(crate) fn pause_between_spawn_and_publish_for_test(pid: u32) { + let Some(park) = std::env::var_os("RUSTSCRIPT_AGENT_TEST_SPAWN_PARK_FILE") else { + return; + }; + // One-shot: the first spawn parks, later spawns of the same process + // proceed. That lets a test park one reservation while still starting + // ordinary children that must be visible to the sweep. + if std::path::Path::new(&park).exists() { + return; + } + if std::fs::write(&park, pid.to_string()).is_err() { + return; + } + let Some(release) = std::env::var_os("RUSTSCRIPT_AGENT_TEST_SPAWN_RELEASE_FILE") else { + return; + }; + let deadline = Instant::now() + Duration::from_secs(15); + while !std::path::Path::new(&release).exists() && Instant::now() < deadline { + thread::sleep(Duration::from_millis(5)); + } + } + + /// Test-only: park a worker after it observed that it still owned the + /// exact reservation, but before the atomic ownership-checked reap + /// decision. + /// + /// This reproduces the inverse ordering: the worker was eligible first, + /// and only then did the exit sweep claim the record. The atomic attempt + /// must revalidate and leave the sweep's still-unreaped child untouched. + /// Inert unless the process was started with the park-file variables. + #[cfg(any(test, feature = "workspace-io-fault"))] + fn pause_between_eligibility_and_cleanup_for_test(pid: u32) { + let Some(park) = std::env::var_os("RUSTSCRIPT_AGENT_TEST_OWNED_CLEANUP_PARK_FILE") else { + return; + }; + // One-shot, like the other spawn hooks, so later spawns proceed. + if std::path::Path::new(&park).exists() { + return; + } + if std::fs::write(&park, pid.to_string()).is_err() { + return; + } + let Some(release) = std::env::var_os("RUSTSCRIPT_AGENT_TEST_OWNED_CLEANUP_RELEASE_FILE") + else { + return; + }; + let deadline = Instant::now() + Duration::from_secs(30); + while !std::path::Path::new(&release).exists() && Instant::now() < deadline { + thread::sleep(Duration::from_millis(5)); + } + } + + /// Where one spawn reservation is in the ownership lifecycle. + /// + /// A reservation moves in one direction. The state is the single source of + /// truth for who owns the child, so "in flight", "recorded but not + /// published" and "sweepable" can never disagree the way separate counters + /// and sets did. + #[derive(Clone, Copy, Debug, Eq, PartialEq)] + enum ReservationState { + /// The fence admitted the spawn. The syscall may still be running, and + /// no pid is recorded yet. + InFlight, + /// The pid is recorded and sweep-visible; the worker has not published. + Recorded, + /// The worker published. Its registration owns the child. + Published, + /// The sweep drained this pid and owns the tombstone. A late publisher + /// must neither recreate the entry nor reopen a pidfd for a pid that + /// may already have been recycled. + Drained, + /// The final drain gave up on this reservation before it recorded a + /// pid. Only its publisher can still name the child, so the publisher + /// owns the cleanup. + Abandoned, + } + + /// One reservation's complete ownership record. + struct Reservation { + state: ReservationState, + pid: Option, + #[cfg(target_os = "linux")] + pidfd: Option, + } + + impl Reservation { + fn new() -> Self { + Self { + state: ReservationState::InFlight, + pid: None, + #[cfg(target_os = "linux")] + pidfd: None, + } + } + + /// Records the just-spawned pid without changing an already abandoned + /// disposition. + fn record_pid(&mut self, pid: u32) { + self.pid = Some(pid); + #[cfg(target_os = "linux")] + { + // Keep the pidfd opened at the spawn; only retry a handle whose + // acquisition failed. + if self.pidfd.is_none() { + self.pidfd = open_pidfd(pid); + } + } + if self.state == ReservationState::InFlight { + self.state = ReservationState::Recorded; + } + } + + /// Turns this record into a drained tombstone and returns the exact + /// child the caller must signal and reap. + #[cfg(unix)] + fn take_entry(&mut self) -> Option { + self.state = ReservationState::Drained; + let pid = self.pid.take()?; + Some(Entry { + pid, + #[cfg(target_os = "linux")] + pidfd: self.pidfd.take(), + }) + } + + fn has_live_pid(&self) -> bool { + self.pid.is_some() + && matches!( + self.state, + ReservationState::Recorded | ReservationState::Published + ) + } + } + + /// Why [`SpawnReservation::publish`] stopped owning the child. + enum PublishDisposition { + Published, + /// The record was already a drained tombstone. + AlreadyDrained, + /// The final drain abandoned the reservation; publish terminates the + /// child it can name. + CleanUpHere, + } + + struct Registry { + /// One ownership record per reservation. A drained record stays as a + /// tombstone until its publisher observes it or its registration drops. + reservations: HashMap, + /// Latched by the first exit sweep. No later spawn may cross the + /// syscall once this is set. + closing: bool, + } + + impl Registry { + /// Takes every sweepable pid out of its record, leaving a tombstone. + #[cfg(unix)] + fn drain_recorded(&mut self) -> Vec { + let mut entries = Vec::new(); + for record in self.reservations.values_mut() { + if !matches!( + record.state, + ReservationState::Recorded | ReservationState::Published + ) { + continue; + } + if let Some(entry) = record.take_entry() { + entries.push(entry); + } + } + entries + } + + /// True when no record still owns a live child or an unrecorded + /// reservation. Tombstones are dispositions, not owners. + #[cfg(unix)] + fn is_quiescent(&self) -> bool { + self.reservations.values().all(|record| { + matches!( + record.state, + ReservationState::Drained | ReservationState::Abandoned + ) + }) + } + + /// The hard-cap drain: every recorded pid is drained, every reservation + /// that never recorded one is abandoned, and each reservation receives + /// exactly one disposition. + #[cfg(unix)] + fn drain_and_abandon(&mut self) -> (Vec, usize) { + let entries = self.drain_recorded(); + let mut abandoned = 0usize; + for record in self.reservations.values_mut() { + if record.state == ReservationState::InFlight { + record.state = ReservationState::Abandoned; + abandoned = abandoned.saturating_add(1); + } + } + (entries, abandoned) + } + } + + #[cfg(unix)] + struct Entry { + pid: u32, + #[cfg(target_os = "linux")] + pidfd: Option, + } + + pub(crate) struct SpawnRegistration { + id: u64, + } + + /// What this worker did with a child whose gate release failed. + #[cfg(unix)] + #[derive(Clone, Copy, Debug, Eq, PartialEq)] + pub(crate) enum FailedReleaseCleanup { + /// This worker owned the exact reservation and proved the reap. + Reaped, + /// This worker owned it but could not prove the reap; the record and + /// child were handed to the retained reaper and remain sweep-visible. + Retained, + /// Another owner already held the exact reservation. This worker must + /// not signal or reap it. + Transferred, + } + + /// Whether these record fields still name the exact child this worker is + /// allowed to clean up. + #[cfg(unix)] + fn recorded_child_is_owned( + state: ReservationState, + recorded_pid: Option, + pid: u32, + ) -> bool { + state == ReservationState::Recorded && recorded_pid == Some(pid) + } + + /// Whether these record fields still name the exact published child this + /// retained reclaimer is allowed to touch. + #[cfg(unix)] + fn published_child_is_owned( + state: ReservationState, + recorded_pid: Option, + pid: u32, + ) -> bool { + state == ReservationState::Published && recorded_pid == Some(pid) + } + + /// The exact pidfd a registry record owns, if this platform has one. + #[cfg(all(unix, target_os = "linux"))] + fn record_pidfd(record: &Reservation) -> Option { + record.pidfd.as_ref().map(std::os::fd::AsRawFd::as_raw_fd) + } + + /// Non-Linux Unix has no pidfd; numeric fallbacks are gated here. + #[cfg(all(unix, not(target_os = "linux")))] + fn record_pidfd(_record: &Reservation) -> Option { + None + } + + /// Result of one atomic ownership-checked reap attempt. + /// + /// The worker and the retained reclaimer share this protocol: take the + /// reap serialization lock first, then the registry lock, revalidate the + /// exact reservation, perform only nonblocking syscalls, and transition + /// the registry before either lock drops. + #[cfg(unix)] + #[derive(Clone, Copy, Debug, Eq, PartialEq)] + enum OwnedReapAttempt { + /// This attempt owned the exact record, proved the child gone and + /// retired the record in the same critical section. + Reaped, + /// Another owner (normally the exit sweep) already claimed the exact + /// record. No numeric group signal and no reap were performed. + NotOwned, + /// The exact record was still owned, but the attempt could not prove + /// the reap. The record keeps ownership so it can be published into + /// the retained reclaimer or claimed by the sweep. + Unproven, + } + + /// One atomic nonblocking reap attempt for a gate-failure worker. + /// + /// Lock order is fixed: `REAP_SERIAL` then the spawn registry. The exit + /// sweep may claim a record while holding only the registry lock, but no + /// path takes `REAP_SERIAL` while holding that lock: `drain_entries` + /// returns its batch before signalling, and `publish`, `clean_up_abandoned` + /// and `sweep_pid` all drop the registry guard before their cleanup. + /// Holding both locks therefore excludes a sweep claim from the exact + /// revalidation through the nonblocking signal, the wait and the + /// transition below. + /// + /// A proven reap removes the record before either lock drops, so a sweep + /// can never inherit a stale record. An unproven attempt leaves the record + /// `Recorded`. A lost record performs no numeric operation at all. No + /// wait, sleep, callback or test hook runs under either lock. + #[cfg(unix)] + fn attempt_recorded_reap(id: u64, pid: u32, cutoff: Instant) -> OwnedReapAttempt { + let (outcome, group_signalled) = { + let Some(pair) = acquire_reap_pair(cutoff) else { + return OwnedReapAttempt::Unproven; + }; + let _serial = pair._serial; + let mut state = pair.state; + let Some(record) = state.reservations.get_mut(&id) else { + return OwnedReapAttempt::NotOwned; + }; + if !recorded_child_is_owned(record.state, record.pid, pid) { + return OwnedReapAttempt::NotOwned; + } + let pidfd = record_pidfd(record); + let decision = super::signal_owned_group_locked_quiet(pid, pidfd); + let outcome = if decision == super::GroupDecision::Released + || (decision == super::GroupDecision::Signalled + && super::wait_reaped_once(pid, pidfd) == super::ReapObservation::Reaped) + { + state.reservations.remove(&id); + OwnedReapAttempt::Reaped + } else { + OwnedReapAttempt::Unproven + }; + (outcome, decision == super::GroupDecision::Signalled) + }; + #[cfg(any(test, feature = "workspace-io-fault"))] + if group_signalled { + super::note_group_signal_observed_for_test(pid); + } + #[cfg(not(any(test, feature = "workspace-io-fault")))] + let _ = group_signalled; + outcome + } + + /// A spawn that crossed the fence and may already own an OS child. + /// + /// The reservation becomes sweep-visible at [`Self::record_spawned`], + /// immediately after the syscall and before any callback or publication, + /// so a worker that never reaches [`Self::publish`] cannot hide a live + /// child from the exit sweep. + pub(crate) struct SpawnReservation { + id: u64, + published: bool, + } + + static NEXT_REGISTRATION: AtomicU64 = AtomicU64::new(1); + static REGISTRY: OnceLock> = OnceLock::new(); + static WAKE: Condvar = Condvar::new(); + + fn registry() -> &'static Mutex { + REGISTRY.get_or_init(|| { + Mutex::new(Registry { + reservations: HashMap::new(), + closing: false, + }) + }) + } + + /// Number of times a reap-pair acquisition found the registry held and + /// released the reap lock instead of blocking under it. + #[cfg(all(test, unix))] + static REAP_PAIR_CONTENTIONS: AtomicUsize = AtomicUsize::new(0); + + /// The fixed `REAP_SERIAL` -> spawn registry lock pair, held together. + /// + /// The registry guard is intentionally declared first so it is released + /// first when the pair drops. + #[cfg(unix)] + struct ReapPair { + state: MutexGuard<'static, Registry>, + _serial: MutexGuard<'static, ()>, + } + + /// Acquires the reap serialization lock and then the registry, never + /// blocking on the registry while the reap lock is held. + /// + /// The registry may be held by a publisher or the exit sweep for longer + /// than this attempt's cutoff. Blocking on it under `REAP_SERIAL` would + /// stall every other group decision, so a contended registry drops the + /// reap lock first and the pair is retried under the original cutoff. + /// `None` means the cutoff expired without both locks; no record, signal + /// or reap was touched. Poisoning is irrelevant on either lock: both + /// protect ordering and records, not invariants that a panic can break. + #[cfg(unix)] + fn acquire_reap_pair(cutoff: Instant) -> Option { + loop { + let serial = super::reap_serial_before(cutoff)?; + match registry().try_lock() { + Ok(state) => { + return Some(ReapPair { + state, + _serial: serial, + }); + } + Err(std::sync::TryLockError::Poisoned(poisoned)) => { + return Some(ReapPair { + state: poisoned.into_inner(), + _serial: serial, + }); + } + Err(std::sync::TryLockError::WouldBlock) => { + #[cfg(all(test, unix))] + REAP_PAIR_CONTENTIONS.fetch_add(1, Ordering::SeqCst); + // Drop the reap lock before any wait: a contender on the + // registry must never block the shared group decision. + drop(serial); + let now = Instant::now(); + if now >= cutoff { + return None; + } + thread::sleep( + Duration::from_millis(1).min(cutoff.saturating_duration_since(now)), + ); + } + } + } + } + + /// Reserves one in-flight spawn slot, or returns `None` when the exit + /// sweep already closed the fence. + pub(crate) fn begin_spawn() -> Option { + let mut state = registry() + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if state.closing { + return None; + } + let id = NEXT_REGISTRATION.fetch_add(1, Ordering::Relaxed); + state.reservations.insert(id, Reservation::new()); + Some(SpawnReservation { + id, + published: false, + }) + } + + impl SpawnReservation { + /// Makes the just-spawned pid visible to the exit sweep. + /// + /// Runs immediately after `child.id()` and before any `on_spawned` + /// callback or publication, so the sweep can signal and reap the raw + /// child even while this worker is parked and never publishes. + /// + /// When the final drain already gave up on this reservation, the child + /// is terminated here instead: the reservation is `Abandoned`, and this + /// publisher is the only owner that can still name it. + #[cfg(unix)] + pub(crate) fn record_spawned(&mut self, pid: u32) -> bool { + let abandoned = { + let mut state = registry() + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let Some(record) = state.reservations.get_mut(&self.id) else { + // The record was drained or released while this worker was + // outside the registry. Never recreate an entry from a pid + // this reservation no longer owns. + return false; + }; + record.record_pid(pid); + record.state == ReservationState::Abandoned + }; + if abandoned { + self.clean_up_abandoned(); + false + } else { + WAKE.notify_all(); + true + } + } + + #[cfg(not(unix))] + pub(crate) fn record_spawned(&mut self, _pid: u32) -> bool { + true + } + + /// Removes this reservation's record after its child was reaped by + /// this same owner (a failed exec before publication). + /// + /// The child never published, so no other owner can still name it. A + /// tombstone left by a concurrent final drain is removed here too. + pub(crate) fn discard(mut self) { + registry() + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .reservations + .remove(&self.id); + self.published = true; + } + + /// A pure eligibility precheck, never authority for a numeric + /// operation. + /// + /// The atomic attempt below revalidates the same reservation under the + /// reap and registry locks, so a sweep claim between this snapshot and + /// that attempt wins without any numeric signal or reap. + #[cfg(unix)] + fn reservation_still_recorded(&self, pid: u32) -> bool { + registry() + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .reservations + .get(&self.id) + .is_some_and(|record| recorded_child_is_owned(record.state, record.pid, pid)) + } + + /// Cleans up the child after its gate release failed. + /// + /// The eligibility snapshot above only decides whether an attempt + /// starts. The attempt itself is one atomic protocol under the reap and + /// registry locks: it revalidates the exact reservation id/state/pid, + /// performs only nonblocking syscalls, and retires a proven record + /// before either lock drops. A drained record transfers the child to + /// the exit sweep, and this worker must neither signal the numeric + /// group nor reap it. When an owned attempt cannot prove the reap, the + /// record is published into a registration and the child is handed to + /// the retained reaper, so the sweep can still name it. + #[cfg(unix)] + pub(crate) fn clean_up_failed_release( + mut self, + pid: u32, + child: super::Child, + cutoff: Instant, + ) -> FailedReleaseCleanup { + if !self.reservation_still_recorded(pid) { + // The drain took this exact record. Absence alone never proves + // a reap, but the tombstone is enough to know another owner is + // responsible. Do not recreate the entry. + self.discard(); + return FailedReleaseCleanup::Transferred; + } + #[cfg(any(test, feature = "workspace-io-fault"))] + pause_between_eligibility_and_cleanup_for_test(pid); + match attempt_recorded_reap(self.id, pid, cutoff) { + OwnedReapAttempt::Reaped => { + // The atomic attempt retired the record before either lock + // dropped. This marker only suppresses Drop's registry + // work for the already-removed reservation. + self.published = true; + FailedReleaseCleanup::Reaped + } + OwnedReapAttempt::NotOwned => { + // The sweep claimed the exact record; no numeric operation + // was performed and its ownership is intact. + self.discard(); + FailedReleaseCleanup::Transferred + } + OwnedReapAttempt::Unproven => match self.publish(pid) { + Some(registration) => { + retain_unproven(pid, child, registration); + FailedReleaseCleanup::Retained + } + // The sweep drained the record between the unproven + // attempt and this publication; it owns the child now. + None => FailedReleaseCleanup::Transferred, + }, + } + } + + /// Terminates a child whose reservation the final drain abandoned. + #[cfg(unix)] + fn clean_up_abandoned(&self) { + let entry = { + let mut state = registry() + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + match state.reservations.get_mut(&self.id) { + Some(record) if record.state == ReservationState::Abandoned => { + record.take_entry() + } + _ => None, + } + }; + if let Some(entry) = entry { + let cutoff = Instant::now() + super::CLEANUP_GRACE; + signal_entry(&entry, cutoff); + let _ = reap_entry(&entry, cutoff); + } + WAKE.notify_all(); + } + + /// Publishes the just-spawned pid and converts the reservation into a + /// registry entry. + /// + /// The pid is already recorded, so the sweep observes the child whether + /// or not this publisher ever runs. + /// + /// `None` means this reservation no longer owns the child: either the + /// sweep drained it (a tombstone stays behind, so publish never + /// recreates the entry or reopens a pidfd for a possibly recycled pid) + /// or the final drain abandoned it and this publisher terminates the + /// child before returning. + pub(crate) fn publish(mut self, pid: u32) -> Option { + let mut state = registry() + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + self.published = true; + let Some(record) = state.reservations.get_mut(&self.id) else { + drop(state); + WAKE.notify_all(); + return None; + }; + let disposition = match record.state { + ReservationState::Drained => PublishDisposition::AlreadyDrained, + ReservationState::Abandoned => { + record.record_pid(pid); + PublishDisposition::CleanUpHere + } + _ => { + record.record_pid(pid); + record.state = ReservationState::Published; + PublishDisposition::Published + } + }; + #[cfg(unix)] + let unswept = matches!(disposition, PublishDisposition::CleanUpHere) + .then(|| record.take_entry()) + .flatten(); + drop(state); + WAKE.notify_all(); + match disposition { + PublishDisposition::Published => Some(SpawnRegistration { id: self.id }), + PublishDisposition::AlreadyDrained => None, + PublishDisposition::CleanUpHere => { + #[cfg(unix)] + if let Some(entry) = unswept { + let cutoff = Instant::now() + super::CLEANUP_GRACE; + signal_entry(&entry, cutoff); + let _ = reap_entry(&entry, cutoff); + } + None + } + } + } + } + + impl Drop for SpawnReservation { + fn drop(&mut self) { + if self.published { + return; + } + let mut state = registry() + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + match state.reservations.get(&self.id).map(|record| record.state) { + // Nothing was recorded and no child is known: the marker and + // its counter disappear in the same critical section. + Some(ReservationState::InFlight) => { + state.reservations.remove(&self.id); + } + // A recorded pid names a real OS child. The record stays + // sweepable; only the reservation marker is gone, and it was + // never counted anywhere else. + Some(ReservationState::Recorded) => {} + // Published, drained and abandoned records are owned by their + // registration, the sweep or the publisher. + _ => { + state.reservations.remove(&self.id); + } + } + drop(state); + WAKE.notify_all(); + } + } + + impl Drop for SpawnRegistration { + fn drop(&mut self) { + registry() + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .reservations + .remove(&self.id); + } + } + + #[cfg(target_os = "linux")] + fn open_pidfd(pid: u32) -> Option { + let pid = libc::pid_t::try_from(pid).ok()?; + // SAFETY: `pid` is a live child just returned by the OS spawn; flags 0 + // request a new pidfd owned exclusively by the caller. + let fd = unsafe { libc::syscall(libc::SYS_pidfd_open, pid, 0) }; + if fd < 0 { + return None; + } + let fd = i32::try_from(fd).ok()?; + // SAFETY: `fd` is a newly opened pidfd; from_raw_fd takes ownership. + Some(unsafe { OwnedFd::from_raw_fd(fd) }) + } + + /// Removes every visible entry. The caller signals them before waiting. + /// + /// Each drained record becomes a tombstone, so a publisher that arrives + /// later observes the drain instead of recreating the entry. + #[cfg(unix)] + fn drain_entries() -> Vec { + registry() + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .drain_recorded() + } + + /// True when no entry and no in-flight reservation remains. + /// + /// Re-read after every wait: a reservation can publish while the sweep is + /// waiting for another root, so a snapshot taken before that wait never + /// proves quiescence. + #[cfg(unix)] + fn is_quiescent() -> bool { + registry() + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .is_quiescent() + } + + /// Removes every visible entry and abandons every still-unrecorded + /// reservation in one critical section. + /// + /// A publisher therefore either recorded its pid before this drain (and is + /// in the returned batch, which the caller signals) or observes an + /// `Abandoned` record and becomes the child's own cleanup owner. There is + /// no third state in which a recorded pid is dropped unseen, and each + /// reservation receives exactly one disposition. + /// + /// The returned count is the number of reservations that were abandoned + /// without ever recording a pid: those are the only children this drain + /// cannot name. + #[cfg(unix)] + fn drain_and_abandon() -> (Vec, usize) { + registry() + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .drain_and_abandon() + } + + /// The pidfd a registry entry owns, if this platform has one. + #[cfg(unix)] + fn entry_pidfd(entry: &Entry) -> Option { + #[cfg(target_os = "linux")] + { + entry.pidfd.as_ref().map(std::os::fd::AsRawFd::as_raw_fd) + } + #[cfg(not(target_os = "linux"))] + { + let _ = entry; + None + } + } + + /// Signals one entry through the single ownership-checked helper. + #[cfg(unix)] + fn signal_entry(entry: &Entry, cutoff: Instant) { + signal_owned(entry.pid, entry_pidfd(entry), cutoff); + } + + /// Signals one already-proved child. + /// + /// The pidfd, when present, is the exact process handle; the numeric group + /// signal is additionally guarded by the reap-lock ownership proof in + /// [`super::signal_owned_group`]. + #[cfg(unix)] + fn signal_owned(pid: u32, pidfd: Option, cutoff: Instant) { + let _ = super::signal_owned_group(pid, pidfd, cutoff); + } + + /// Waits, bounded, for one signalled entry to disappear. + /// + /// Each iteration re-proves ownership and reaps the root under one + /// acquisition of the reap lock, so no ordinary reaper can release the pid + /// between a proof and the group signal, and this reap can never land in + /// another reaper's proof window. + #[cfg(unix)] + fn reap_entry(entry: &Entry, cutoff: Instant) -> bool { + reap_owned(entry.pid, entry_pidfd(entry), cutoff) + } + + /// Waits, bounded, for one already-signalled child to disappear. + /// + /// Each iteration re-proves ownership and reaps the root under one + /// acquisition of the reap lock, so no ordinary reaper can release the pid + /// between a proof and the group signal, and this reap can never land in + /// another reaper's proof window. A pidfd observation is exact where the + /// platform has one, and only a real status or `ECHILD` counts as proof. + #[cfg(unix)] + fn reap_owned(pid: u32, pidfd: Option, cutoff: Instant) -> bool { + loop { + #[cfg(any(test, feature = "workspace-io-fault"))] + pause_sweep_reap_for_test(pid); + let Some(_serial) = super::reap_serial_before(cutoff) else { + return false; + }; + let signal = super::signal_owned_group_locked(pid, pidfd); + let reaped = signal == super::GroupDecision::Released + || (signal == super::GroupDecision::Signalled + && super::wait_reaped_once(pid, pidfd) == super::ReapObservation::Reaped); + drop(_serial); + if reaped { + // `pid` (reaped), or ECHILD (another owner already reaped + // it): either way no child of this exact identity remains. + return true; + } + let now = Instant::now(); + if now >= cutoff { + return false; + } + thread::sleep(Duration::from_millis(5).min(cutoff.saturating_duration_since(now))); + } + } + + /// Signals and reaps every registered child. Returns the number whose + /// disappearance could not be proven before the sweep's hard cap. + /// + /// The first call latches the spawn fence: new spawns are refused before + /// their syscall, and reservations that already crossed the fence are + /// waited for until they publish. The loop signals the entire visible batch + /// *before* it waits on any root, then re-drains after the wait, so a + /// reservation that publishes while one root is being reaped is signalled + /// by the same loop instead of being counted and dropped. Quiescence is + /// re-read after the wait, never taken from the pre-wait snapshot. + /// + /// At the hard cap `deadline + LATE_PUBLISHER_GRACE` one final drain runs + /// under the registry lock: everything visible is signalled and reaped + /// under a short grace before it is counted, and the latch hands any still + /// unpublished reservation to its own publisher. A published pid is + /// therefore never left unsignalled by this sweep. + pub fn sweep(deadline: Instant) -> usize { + #[cfg(any(test, feature = "workspace-io-fault"))] + note_sweep_started_for_test(); + #[cfg(unix)] + { + let hard_deadline = deadline + super::LATE_PUBLISHER_GRACE; + { + let mut state = registry() + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + state.closing = true; + WAKE.notify_all(); + } + let mut unproven = 0usize; + loop { + let entries = drain_entries(); + // Signal the whole visible batch first. A wait on one root must + // never delay the kill of another visible child. + let signal_cutoff = Instant::now() + super::CLEANUP_GRACE; + for entry in &entries { + signal_entry(entry, signal_cutoff); + } + let now = Instant::now(); + let reap_cutoff = if now < hard_deadline { + hard_deadline + } else { + now + super::CLEANUP_GRACE + }; + for entry in &entries { + if !reap_entry(entry, reap_cutoff) { + unproven = unproven.saturating_add(1); + } + } + if is_quiescent() { + break; + } + let now = Instant::now(); + if now >= hard_deadline { + // The cap bounds waiting, not cleanup. A reservation that + // published or recorded a pid during the wait above is + // drained here and signalled before anything is counted. + // + // Every visible root is signalled first and only then + // reaped: an early root's reap wait must not consume the + // shared grace before a later root has been signalled. + let (late, unrecorded) = drain_and_abandon(); + let late_cutoff = Instant::now() + super::CLEANUP_GRACE; + for entry in &late { + signal_entry(entry, late_cutoff); + } + for entry in &late { + if !reap_entry(entry, late_cutoff) { + unproven = unproven.saturating_add(1); + } + } + // A reservation that never recorded a pid cannot be + // signalled here; its publisher cleans it up on publish. + unproven = unproven.saturating_add(unrecorded); + break; + } + let wait = hard_deadline + .saturating_duration_since(now) + .min(super::LATE_PUBLISHER_POLL); + let state = registry() + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let _ = WAKE + .wait_timeout(state, wait) + .unwrap_or_else(|poisoned| poisoned.into_inner()); + } + unproven + } + #[cfg(not(unix))] + { + let _ = deadline; + 0 + } + } + + #[cfg(unix)] + pub fn sweep_pid(pid: u32, deadline: Instant) -> bool { + let entry = { + let mut state = registry() + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let id = state + .reservations + .iter() + .find(|(_, record)| record.pid == Some(pid) && record.has_live_pid()) + .map(|(id, _)| *id); + id.and_then(|id| state.reservations.get_mut(&id)) + .and_then(Reservation::take_entry) + }; + entry.is_some_and(|entry| { + signal_entry(&entry, deadline); + reap_entry(&entry, deadline) + }) + } + + #[cfg(not(unix))] + pub fn sweep_pid(_pid: u32, _deadline: Instant) -> bool { + false + } + + /// A child whose owner could not prove its tree gone, retained together + /// with the exact exit-sweep record that keeps naming it. + /// + /// The record is the ownership token: it is dropped only after a later + /// bounded reaper proves the root gone, so a long-lived managed caller + /// cannot accumulate unreachable forgotten registrations and the exit + /// sweep can still see the tree until that proof exists. + #[cfg(unix)] + struct RetainedChild { + pid: u32, + child: super::Child, + registration: SpawnRegistration, + } + + /// One atomic nonblocking reap attempt for a retained child. + /// + /// This is the same protocol and lock order as [`attempt_recorded_reap`], + /// but it revalidates the retained entry's exact `Published` registration + /// id and pid. A sweep claim leaves a `Drained` tombstone, so the + /// reclaimer performs no numeric signal and no reap and then drops the + /// retained entry without disturbing the sweep's local ownership. A proven + /// reap retires the record before either lock drops. No wait, sleep, + /// callback or test hook runs under either lock. + #[cfg(unix)] + fn attempt_retained_reap(entry: &RetainedChild, cutoff: Instant) -> OwnedReapAttempt { + let (outcome, group_signalled) = { + let Some(pair) = acquire_reap_pair(cutoff) else { + return OwnedReapAttempt::Unproven; + }; + let _serial = pair._serial; + let mut state = pair.state; + let id = entry.registration.id; + let Some(record) = state.reservations.get_mut(&id) else { + return OwnedReapAttempt::NotOwned; + }; + if !published_child_is_owned(record.state, record.pid, entry.pid) { + return OwnedReapAttempt::NotOwned; + } + let pidfd = record_pidfd(record); + let decision = super::signal_owned_group_locked_quiet(entry.pid, pidfd); + let outcome = if decision == super::GroupDecision::Released + || (decision == super::GroupDecision::Signalled + && super::wait_reaped_once(entry.pid, pidfd) == super::ReapObservation::Reaped) + { + state.reservations.remove(&id); + OwnedReapAttempt::Reaped + } else { + OwnedReapAttempt::Unproven + }; + (outcome, decision == super::GroupDecision::Signalled) + }; + #[cfg(any(test, feature = "workspace-io-fault"))] + if group_signalled { + super::note_group_signal_observed_for_test(entry.pid); + } + #[cfg(not(any(test, feature = "workspace-io-fault")))] + let _ = group_signalled; + outcome + } + + #[cfg(unix)] + static RETAINED: Mutex> = Mutex::new(Vec::new()); + #[cfg(unix)] + static RETAINED_WAKE: Condvar = Condvar::new(); + #[cfg(unix)] + static RETAINED_REAPER: OnceLock<()> = OnceLock::new(); + /// Test-only: hold the reclaimer off a deterministically observable + /// retained entry. + #[cfg(all(unix, any(test, feature = "workspace-io-fault")))] + static RETAINED_REAPER_PAUSED: super::AtomicBool = super::AtomicBool::new(false); + + /// Test-only: pause or resume the retained-child reclaimer. + #[cfg(all(unix, any(test, feature = "workspace-io-fault")))] + pub fn pause_retained_reaper_for_test(paused: bool) { + RETAINED_REAPER_PAUSED.store(paused, Ordering::SeqCst); + RETAINED_WAKE.notify_all(); + } + + /// Test-only: park the retained reclaimer after it selected one exact + /// retained entry and before its atomic ownership-checked attempt. + /// + /// This is the retained-reaper equivalent of the worker eligibility seam: + /// the reclaimer held a live registration first, and only then did the + /// exit sweep claim the record. The atomic attempt must revalidate and + /// leave the sweep's still-unreaped child untouched. Inert unless the + /// process was started with the park-file variables. + #[cfg(all(unix, any(test, feature = "workspace-io-fault")))] + fn pause_retained_decision_for_test(pid: u32) { + let Some(park) = std::env::var_os("RUSTSCRIPT_AGENT_TEST_RETAINED_DECISION_PARK_FILE") + else { + return; + }; + // One-shot, like the other ownership seams. + if std::path::Path::new(&park).exists() { + return; + } + if std::fs::write(&park, pid.to_string()).is_err() { + return; + } + let Some(release) = + std::env::var_os("RUSTSCRIPT_AGENT_TEST_RETAINED_DECISION_RELEASE_FILE") + else { + return; + }; + let deadline = Instant::now() + Duration::from_secs(30); + while !std::path::Path::new(&release).exists() && Instant::now() < deadline { + thread::sleep(Duration::from_millis(5)); + } + } -#[cfg(windows)] -use super::windows_process_tree::ProcessJob; -#[cfg(unix)] -use std::os::unix::process::CommandExt; -#[cfg(unix)] -use std::os::unix::process::ExitStatusExt; -#[cfg(windows)] -use std::os::windows::process::CommandExt; + /// Test-only: record one retained attempt's ownership disposition. + #[cfg(all(unix, any(test, feature = "workspace-io-fault")))] + fn note_retained_attempt_for_test(pid: u32, disposition: &str) { + let Some(path) = std::env::var_os("RUSTSCRIPT_AGENT_TEST_RETAINED_ATTEMPT_MARKER") else { + return; + }; + if let Ok(mut file) = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(path) + { + let _ = writeln!(file, "{pid} {disposition}"); + } + } -/// Maximum number of argv entries accepted by [`BoundedProcessRequest`]. -pub const MAX_ARG_COUNT: usize = 256; -/// Maximum byte length of one argv entry. -pub const MAX_ARG_ITEM_BYTES: usize = 16 * 1024; -/// Maximum combined byte length of all argv entries. -pub const MAX_ARG_TOTAL_BYTES: usize = 256 * 1024; -/// Maximum number of explicitly supplied environment entries. -pub const MAX_ENV_COUNT: usize = 128; -/// Maximum byte length of an environment key. -pub const MAX_ENV_KEY_BYTES: usize = 256; -/// Maximum byte length of an environment value. -pub const MAX_ENV_VALUE_BYTES: usize = 16 * 1024; -/// Maximum combined byte length of environment keys and values. -pub const MAX_ENV_TOTAL_BYTES: usize = 256 * 1024; -/// Maximum initial stdin payload. -pub const MAX_STDIN_BYTES: usize = 16 * 1024 * 1024; -/// Maximum one-shot stdin write payload. -pub const MAX_STDIN_WRITE_BYTES: usize = 16 * 1024 * 1024; -/// Maximum accepted timeout or relative deadline. -pub const MAX_TIMEOUT: Duration = Duration::from_secs(60 * 60); -/// Maximum retained output across both streams. -pub const MAX_OUTPUT_BYTES: usize = 16 * 1024 * 1024; -/// Default request timeout. -pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30); -/// Default per-stream and total output limit. -pub const DEFAULT_OUTPUT_BYTES: usize = 1024 * 1024; -/// Polling slice used by cancellable stdin/drainer/wait loops. -const WAIT_SLICE: Duration = Duration::from_millis(5); -/// Bound for joining workers and reaping a killed child after SIGKILL/Job. -const CLEANUP_GRACE: Duration = Duration::from_millis(200); + /// Starts the retained-child reclaimer exactly once after a successful + /// start. + /// + /// A failed thread start must not latch: the entries stay in `RETAINED` + /// (the exit sweep can still name them) and the next unproven teardown + /// retries. The start mutex keeps concurrent first teardowns from spawning + /// two reapers. + #[cfg(unix)] + fn start_reaper_once(once: &OnceLock<()>, start: impl FnOnce() -> std::io::Result<()>) -> bool { + static START: Mutex<()> = Mutex::new(()); + if once.get().is_some() { + return true; + } + let _serial = START + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if once.get().is_some() { + return true; + } + match start() { + Ok(()) => { + let _ = once.set(()); + true + } + Err(_) => false, + } + } -static NEXT_PROCESS_HANDLE: AtomicU64 = AtomicU64::new(1); + /// Hands an unproven child and its exit-sweep record to the reclaimer. + /// + /// The reclaimer retries the same ownership-checked group signal and reap + /// as the exit sweep; the record and child disappear only after the root + /// is proven gone. If the reclaimer thread cannot be started, the entries + /// stay in the list and remain owned by the exit sweep; the next unproven + /// teardown retries the start. + #[cfg(unix)] + pub(super) fn retain_unproven(pid: u32, child: super::Child, registration: SpawnRegistration) { + RETAINED + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .push(RetainedChild { + pid, + child, + registration, + }); + start_reaper_once(&RETAINED_REAPER, || { + thread::Builder::new() + .name("bounded-process-retained-reaper".to_string()) + .spawn(reap_retained_children) + .map(|_| ()) + }); + RETAINED_WAKE.notify_all(); + } + + #[cfg(unix)] + fn reap_retained_children() { + loop { + let mut retained = RETAINED + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if retained.is_empty() { + let _ = RETAINED_WAKE + .wait_timeout(retained, Duration::from_millis(50)) + .unwrap_or_else(|poisoned| poisoned.into_inner()); + continue; + } + #[cfg(any(test, feature = "workspace-io-fault"))] + if RETAINED_REAPER_PAUSED.load(Ordering::SeqCst) { + drop(retained); + thread::sleep(Duration::from_millis(10)); + continue; + } + let batch = std::mem::take(&mut *retained); + drop(retained); + let mut survivors = Vec::new(); + for entry in batch { + #[cfg(any(test, feature = "workspace-io-fault"))] + pause_retained_decision_for_test(entry.pid); + // One bounded atomic attempt per entry: revalidation, the + // group decision, the signal and the nonblocking reap all stay + // under the shared reap serialization and registry locks. + let attempt = attempt_retained_reap(&entry, Instant::now() + super::CLEANUP_GRACE); + #[cfg(any(test, feature = "workspace-io-fault"))] + note_retained_attempt_for_test( + entry.pid, + match attempt { + OwnedReapAttempt::Reaped => "reaped", + OwnedReapAttempt::NotOwned => "swept", + OwnedReapAttempt::Unproven => "retained", + }, + ); + match attempt { + // Proven gone, or the exit sweep claimed the exact record + // and now owns the child. Dropping this entry releases the + // registration (a no-op or a tombstone removal) and the + // retained pipes without any numeric process operation. + OwnedReapAttempt::Reaped | OwnedReapAttempt::NotOwned => drop(entry), + OwnedReapAttempt::Unproven => survivors.push(entry), + } + } + let mut retained = RETAINED + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + retained.extend(survivors); + let pending = !retained.is_empty(); + drop(retained); + if pending { + // Do not spin on a root that is still dying or stuck. + thread::sleep(Duration::from_millis(100)); + } + } + } + + /// Whether `pid` still has a live exit-sweep record. + pub fn contains(pid: u32) -> bool { + registry() + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .reservations + .values() + .any(|record| record.pid == Some(pid) && record.has_live_pid()) + } + + /// Test-only: park the sweep inside the reap wait for `pid`. + /// + /// This reproduces the window where one root consumes the sweep's remaining + /// budget while another reservation publishes. Inert unless the process was + /// started with the park-file variable. + #[cfg(any(test, feature = "workspace-io-fault"))] + fn pause_sweep_reap_for_test(pid: u32) { + let Some(marker) = std::env::var_os("RUSTSCRIPT_AGENT_TEST_SWEEP_REAP_PARK_FILE") else { + return; + }; + // One-shot: an ordinary reaper sharing this helper must observe that + // the sweep already owns the deterministic reap window instead of + // parking on the same release. Existing single-reaper tests are + // unaffected. + if std::path::Path::new(&marker).exists() { + return; + } + if std::fs::write(&marker, pid.to_string()).is_err() { + return; + } + let Some(release) = std::env::var_os("RUSTSCRIPT_AGENT_TEST_SWEEP_REAP_RELEASE_FILE") + else { + return; + }; + let deadline = Instant::now() + Duration::from_secs(30); + while !std::path::Path::new(&release).exists() && Instant::now() < deadline { + thread::sleep(Duration::from_millis(5)); + } + } + + #[cfg(all(test, unix))] + mod release_cleanup_tests { + use super::*; + + #[test] + fn only_a_still_recorded_exact_pid_may_be_cleaned_up() { + assert!(recorded_child_is_owned( + ReservationState::Recorded, + Some(7), + 7 + )); + assert!(!recorded_child_is_owned( + ReservationState::Drained, + Some(7), + 7 + )); + assert!(!recorded_child_is_owned( + ReservationState::Published, + Some(7), + 7 + )); + assert!(!recorded_child_is_owned( + ReservationState::Abandoned, + Some(7), + 7 + )); + assert!(!recorded_child_is_owned( + ReservationState::Recorded, + Some(8), + 7 + )); + assert!(!recorded_child_is_owned( + ReservationState::Recorded, + None, + 7 + )); + } + + #[test] + fn only_a_still_published_exact_pid_belongs_to_the_retained_reclaimer() { + assert!(published_child_is_owned( + ReservationState::Published, + Some(7), + 7 + )); + assert!(!published_child_is_owned( + ReservationState::Recorded, + Some(7), + 7 + )); + assert!(!published_child_is_owned( + ReservationState::Drained, + Some(7), + 7 + )); + assert!(!published_child_is_owned( + ReservationState::Abandoned, + Some(7), + 7 + )); + assert!(!published_child_is_owned( + ReservationState::Published, + Some(8), + 7 + )); + assert!(!published_child_is_owned( + ReservationState::Published, + None, + 7 + )); + } + + #[test] + fn a_failed_reaper_start_does_not_latch_and_retries_once() { + let once = OnceLock::new(); + assert!(!start_reaper_once(&once, || Err(std::io::Error::from( + std::io::ErrorKind::Other + )))); + assert!( + once.get().is_none(), + "a failed start must leave the reaper retryable" + ); + assert!(start_reaper_once(&once, || Ok(()))); + assert!(once.get().is_some(), "the successful start must latch"); + assert!(start_reaper_once(&once, || panic!( + "a started reaper must never be spawned twice" + ))); + } + } + + /// Both losing actors share one bounded lock-pair acquisition. A held + /// registry must end an attempt at its cutoff, while the contender must + /// never hold `REAP_SERIAL` across that wait. + #[cfg(all(test, unix))] + mod reap_pair_tests { + use super::*; + use std::os::unix::process::CommandExt; + use std::process::{Child, Command, Stdio}; + + /// Serializes the two tests that hold the process-global registry. + static TEST_SERIAL: Mutex<()> = Mutex::new(()); + + fn spawn_group_child() -> Child { + let mut command = Command::new("/bin/sleep"); + command + .arg("30") + .process_group(0) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + command.spawn().expect("spawn a grouped reap-pair child") + } + + fn reset_contention() { + REAP_PAIR_CONTENTIONS.store(0, Ordering::SeqCst); + } + + fn wait_for_contention() { + let deadline = Instant::now() + Duration::from_secs(2); + while REAP_PAIR_CONTENTIONS.load(Ordering::SeqCst) == 0 { + assert!( + Instant::now() < deadline, + "the attempt never observed the held registry" + ); + thread::sleep(Duration::from_millis(1)); + } + } + + /// The contender may only hold the shared reap lock for the brief + /// try-lock itself. If it blocks on the registry under that lock, this + /// loop cannot acquire it while the registry stays held. + fn assert_reap_lock_free_while_registry_held() { + let deadline = Instant::now() + Duration::from_millis(750); + loop { + match super::super::REAP_SERIAL.try_lock() { + Ok(guard) => { + drop(guard); + return; + } + Err(std::sync::TryLockError::Poisoned(poisoned)) => { + drop(poisoned.into_inner()); + return; + } + Err(std::sync::TryLockError::WouldBlock) => { + assert!( + Instant::now() < deadline, + "the contending attempt blocked the shared reap lock while the \ + registry was held" + ); + } + } + thread::sleep(Duration::from_millis(1)); + } + } + + fn process_exists(pid: u32) -> bool { + unsafe { libc::kill(pid as libc::pid_t, 0) == 0 } + } + + fn assert_reaped(t: &str, pid: u32) { + assert!( + !process_exists(pid), + "the retry must reap the owned child through {t}: pid={pid}" + ); + } + + #[test] + fn recorded_actor_returns_bounded_on_a_held_registry_and_keeps_the_record() { + let _test_serial = TEST_SERIAL + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let Some(mut reservation) = begin_spawn() else { + return; + }; + let mut child = spawn_group_child(); + let pid = child.id(); + assert!(reservation.record_spawned(pid), "the child must record"); + let id = reservation.id; + + let held = registry() + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + reset_contention(); + let cutoff = Instant::now() + Duration::from_millis(200); + let (tx, rx) = std::sync::mpsc::channel(); + let worker = thread::spawn(move || { + let started = Instant::now(); + let attempt = attempt_recorded_reap(id, pid, cutoff); + let _ = tx.send((attempt, started.elapsed())); + }); + wait_for_contention(); + assert_reap_lock_free_while_registry_held(); + let (attempt, elapsed) = rx + .recv_timeout(Duration::from_secs(2)) + .expect("a held registry must end the attempt at its cutoff"); + assert_eq!( + attempt, + OwnedReapAttempt::Unproven, + "a timed-out pair must keep the record, never report a reap" + ); + assert!( + elapsed < Duration::from_millis(900), + "the held-registry attempt escaped its cutoff: {elapsed:?}" + ); + let record = held + .reservations + .get(&id) + .expect("the recorded reservation must survive the timed-out attempt"); + assert_eq!(record.state, ReservationState::Recorded); + assert_eq!(record.pid, Some(pid)); + worker.join().expect("recorded attempt thread"); + + drop(held); + let retry_deadline = Instant::now() + Duration::from_secs(2); + let mut retried = OwnedReapAttempt::Unproven; + while Instant::now() < retry_deadline { + retried = + attempt_recorded_reap(id, pid, Instant::now() + Duration::from_millis(200)); + if retried == OwnedReapAttempt::Reaped { + break; + } + thread::sleep(Duration::from_millis(5)); + } + assert_eq!( + retried, + OwnedReapAttempt::Reaped, + "the bounded retry must reap the still-owned record" + ); + assert!( + !registry() + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .reservations + .contains_key(&id), + "a proven reap must retire the record" + ); + assert_reaped("the worker attempt", pid); + drop(reservation); + let _ = child.wait(); + } + + #[test] + fn retained_actor_returns_bounded_on_a_held_registry_and_keeps_the_record() { + let _test_serial = TEST_SERIAL + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let Some(mut reservation) = begin_spawn() else { + return; + }; + let child = spawn_group_child(); + let pid = child.id(); + assert!(reservation.record_spawned(pid), "the child must record"); + let registration = reservation + .publish(pid) + .expect("the retained child must publish"); + let registration_id = registration.id; + let entry = RetainedChild { + pid, + child, + registration, + }; + + let held = registry() + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + reset_contention(); + let cutoff = Instant::now() + Duration::from_millis(200); + let (tx, rx) = std::sync::mpsc::channel(); + let worker = thread::spawn(move || { + let started = Instant::now(); + let attempt = attempt_retained_reap(&entry, cutoff); + let elapsed = started.elapsed(); + let _ = tx.send((attempt, elapsed)); + entry + }); + wait_for_contention(); + assert_reap_lock_free_while_registry_held(); + let (attempt, elapsed) = rx + .recv_timeout(Duration::from_secs(2)) + .expect("a held registry must end the attempt at its cutoff"); + assert_eq!( + attempt, + OwnedReapAttempt::Unproven, + "a timed-out pair must keep the retained record, never report a reap" + ); + assert!( + elapsed < Duration::from_millis(900), + "the held-registry retained attempt escaped its cutoff: {elapsed:?}" + ); + let record = held + .reservations + .get(®istration_id) + .expect("the published reservation must survive the timed-out attempt"); + assert_eq!(record.state, ReservationState::Published); + assert_eq!(record.pid, Some(pid)); + + drop(held); + let entry = worker.join().expect("retained attempt thread"); + let retry_deadline = Instant::now() + Duration::from_secs(2); + let mut retried = OwnedReapAttempt::Unproven; + while Instant::now() < retry_deadline { + retried = + attempt_retained_reap(&entry, Instant::now() + Duration::from_millis(200)); + if retried == OwnedReapAttempt::Reaped { + break; + } + thread::sleep(Duration::from_millis(5)); + } + assert_eq!( + retried, + OwnedReapAttempt::Reaped, + "the bounded retry must reap the still-published record" + ); + assert!( + !registry() + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .reservations + .contains_key(®istration_id), + "a proven retained reap must retire the record" + ); + assert_reaped("the retained attempt", pid); + drop(entry); + } + } +} + +pub(crate) use spawn_registry::SpawnRegistration; +#[cfg(all(unix, any(test, feature = "workspace-io-fault")))] +pub use spawn_registry::pause_retained_reaper_for_test; + +/// Test-only: hold the process-wide reap serialization lock. +/// +/// Every ownership-checked group signal and every ordinary reap takes this +/// lock. A test that holds it models another reaper that owns the group +/// decision while an ordinary cleanup runs; the cleanup must then leave the +/// tree pending instead of reporting it clean. +#[cfg(all(unix, any(test, feature = "workspace-io-fault")))] +#[doc(hidden)] +pub fn hold_reap_serial_for_test() -> MutexGuard<'static, ()> { + REAP_SERIAL + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) +} + +/// Signals and reaps every child this process spawned that is still +/// registered, including one whose owning worker is parked before converting +/// its spawn reservation into a process-table record. Returns the number of +/// children whose disappearance could not be proven before `deadline`. +/// +/// This is the final exit guarantee: callers run it immediately before +/// `std::process::exit`, which cannot join the worker that would otherwise +/// convert and kill the child. +pub fn sweep_spawned_children(deadline: Instant) -> usize { + spawn_registry::sweep(deadline) +} + +/// Test-only: signals and reaps one registered child by pid without touching +/// children spawned by concurrent tests. Returns true when it is gone. +#[cfg(any(test, feature = "workspace-io-fault"))] +#[doc(hidden)] +pub fn sweep_registered_child_for_test(pid: u32, deadline: Instant) -> bool { + spawn_registry::sweep_pid(pid, deadline) +} + +/// Test-only: whether `pid` still has a live exit-sweep registration. +#[cfg(any(test, feature = "workspace-io-fault"))] +#[doc(hidden)] +pub fn registered_child_for_test(pid: u32) -> bool { + spawn_registry::contains(pid) +} + +#[cfg(target_os = "linux")] +static PIDFD_OPEN_FAILURES: AtomicUsize = AtomicUsize::new(0); + +/// Test-only: make the next `count` pidfd acquisitions fail. This covers the +/// initial acquisition at spawn and the retained handle's lazy retry, so the +/// wait-status fallback can be exercised deterministically. +#[doc(hidden)] +pub fn fail_next_pidfd_opens_for_test(count: usize) { + #[cfg(target_os = "linux")] + PIDFD_OPEN_FAILURES.store(count, Ordering::SeqCst); + #[cfg(not(target_os = "linux"))] + let _ = count; +} /// Cooperative cancellation shared by a request and its owner. #[derive(Clone, Debug)] @@ -131,6 +2211,39 @@ pub struct BoundedProcessRequest { pub total_limit: usize, /// Optional owner cancellation token. pub cancellation_token: Option, + /// One-shot boundary that runs after every fallible request validation and + /// cwd/environment setup, immediately before the OS spawn syscall itself. + /// + /// The owning capability enters its publication fence here, so a fence can + /// never be consumed before the syscall can actually happen and cannot + /// regress after the `on_spawned` hook recorded it. + pub before_spawn: Option Result<(), BoundedProcessError> + Send + Sync>>, + /// Optional sink that receives the partially initialized child when a + /// post-spawn setup step fails. The caller keeps ownership and can only + /// release it after an independently proven reap and worker exit. + pub retain_on_setup_failure: Option>>>, + /// One-shot native publication boundary. It runs immediately after the OS + /// spawn syscall succeeded and before any capture/setup step that can fail, + /// so an owner can record the irreversible point exactly. The exact OS pid + /// is passed out. + pub on_spawned: Option>, + /// Test-only deterministic failure after the OS spawn succeeded. The child + /// is still terminated through the ordinary abort path. + pub post_spawn_failure: bool, + /// Test-only deterministic failure while starting the stderr drainer. The + /// already-started stdout drainer and the child are retained. + pub stderr_drainer_failure: bool, + /// Test-only: withhold the tree-cleanup proof after the kill so a bounded + /// teardown and the destructor can be measured against one cutoff. + pub stall_tree_cleanup: bool, + /// Linux-only: launch through the pre-exec gate so the direct child cannot + /// execute tool code before the spawn registry records its pid. + /// + /// This is enabled only by the packaged `tools serve` path, whose + /// `std::process::exit` cannot join a worker parked in the + /// spawn-before-record window. Every other caller keeps the legacy direct + /// spawn, and non-Linux builds ignore the flag. + pub exec_gate: bool, } impl fmt::Debug for BoundedProcessRequest { @@ -150,6 +2263,10 @@ impl fmt::Debug for BoundedProcessRequest { .field("stderr_limit", &self.stderr_limit) .field("total_limit", &self.total_limit) .field("cancellation_present", &self.cancellation_token.is_some()) + .field("on_spawned_present", &self.on_spawned.is_some()) + .field("post_spawn_failure", &self.post_spawn_failure) + .field("stall_tree_cleanup", &self.stall_tree_cleanup) + .field("exec_gate", &self.exec_gate) .finish() } } @@ -205,9 +2322,26 @@ impl BoundedProcessRequest { stderr_limit: DEFAULT_OUTPUT_BYTES, total_limit: DEFAULT_OUTPUT_BYTES, cancellation_token: None, + before_spawn: None, + retain_on_setup_failure: None, + on_spawned: None, + post_spawn_failure: false, + stderr_drainer_failure: false, + stall_tree_cleanup: false, + exec_gate: false, } } + /// Enables the Linux pre-exec gate for this request. + /// + /// Only the packaged `tools serve` server enables this; it is a no-op on + /// every non-Linux build. + #[doc(hidden)] + pub fn with_exec_gate(mut self) -> Self { + self.exec_gate = true; + self + } + pub fn with_cwd(mut self, cwd: impl Into) -> Self { self.cwd = Some(cwd.into()); self @@ -243,6 +2377,60 @@ impl BoundedProcessRequest { self } + /// Installs the one-shot fence boundary. The hook runs once, after request + /// validation and cwd/environment setup, immediately before the OS spawn + /// syscall. Returning an error prevents the spawn entirely. + pub fn with_before_spawn( + mut self, + before_spawn: Arc Result<(), BoundedProcessError> + Send + Sync>, + ) -> Self { + self.before_spawn = Some(before_spawn); + self + } + + /// Installs the one-shot native publication boundary. The hook runs once, + /// immediately after the OS spawn syscall succeeded, before pidfd/job, + /// stdio capture, drainer or stdin-worker setup can fail. + pub fn with_on_spawned(mut self, on_spawned: Arc) -> Self { + self.on_spawned = Some(on_spawned); + self + } + + /// Installs the ownership sink used when a post-spawn setup step fails. + #[doc(hidden)] + pub fn with_setup_failure_sink( + mut self, + sink: Arc>>, + ) -> Self { + self.retain_on_setup_failure = Some(sink); + self + } + + /// Test-only: force a setup failure after the OS spawn succeeded. Production + /// callers never set it; the abort path and publication boundary stay the + /// same as a real post-spawn setup failure. + #[doc(hidden)] + pub fn with_post_spawn_failure_for_test(mut self) -> Self { + self.post_spawn_failure = true; + self + } + + /// Test-only: fail the stderr drainer setup after the stdout drainer + /// started, retaining both the child and the unfinished drainer. + #[doc(hidden)] + pub fn with_stderr_drainer_failure_for_test(mut self) -> Self { + self.stderr_drainer_failure = true; + self + } + + /// Test-only: after the kill, leave the tree-cleanup proof pending. The + /// child is really killed; only the proof wait is withheld. + #[doc(hidden)] + pub fn with_tree_cleanup_stall_for_test(mut self) -> Self { + self.stall_tree_cleanup = true; + self + } + pub fn with_output_limits( mut self, stdout_limit: usize, @@ -536,12 +2724,23 @@ pub enum BoundedProcessError { Spawn(SpawnError), DeadlineElapsed, Cancelled, - WaitFailed { os_code: Option }, + WaitFailed { + os_code: Option, + }, StdinClosed, StdinTooLarge, - StdinWriteFailed { os_code: Option }, - DrainFailed { stream: LogStream }, + StdinWriteFailed { + os_code: Option, + }, + DrainFailed { + stream: LogStream, + }, WorkerFailed, + /// The per-call publication fence refused the spawn before the syscall. + Publication(LifecycleError), + /// The exit sweep already latched the process-wide spawn fence, so no new + /// child may be created. No syscall and no native effect occurred. + ShuttingDown, } impl fmt::Display for BoundedProcessError { @@ -559,6 +2758,12 @@ impl fmt::Display for BoundedProcessError { } Self::DrainFailed { stream } => write!(formatter, "{} drain failed", stream.name()), Self::WorkerFailed => formatter.write_str("process worker failed"), + Self::Publication(error) => { + write!(formatter, "publication refused: {}", error.message()) + } + Self::ShuttingDown => { + formatter.write_str("process spawn refused: the exit sweep is closing") + } } } } @@ -593,6 +2798,65 @@ fn spawn_error(error: &std::io::Error) -> SpawnError { } } +/// The typed failure for a gate release that did not confirm a clean exec. +/// +/// A confirmed exec errno or a release that was never written always remains a +/// typed spawn failure, regardless of who owned the reservation when cleanup +/// ran. Only an ambiguous post-release result that has already been transferred +/// to the exit sweep keeps the existing shutdown classification; the ambiguous +/// result may still have executed the tool and keeps its effect separately. +#[cfg(target_os = "linux")] +fn gate_release_failure_error( + failure: &exec_gate::GateReleaseError, + cleanup: spawn_registry::FailedReleaseCleanup, +) -> BoundedProcessError { + if failure.may_have_reached_tool() + && cleanup == spawn_registry::FailedReleaseCleanup::Transferred + { + BoundedProcessError::ShuttingDown + } else { + BoundedProcessError::Spawn(spawn_error(failure.io())) + } +} + +/// Test-only: report the typed gate-failure decision through a file marker. +/// +/// The marker is written only when the process was started with the marker +/// variable; it lets a packaged test inspect the ownership disposition and the +/// effect decision without treating a successful exit as proof. +#[cfg(all(target_os = "linux", any(test, feature = "workspace-io-fault")))] +fn note_gate_release_failure_for_test( + pid: u32, + failure: &exec_gate::GateReleaseError, + cleanup: spawn_registry::FailedReleaseCleanup, + keep_effect: bool, +) { + let Some(path) = std::env::var_os("RUSTSCRIPT_AGENT_TEST_GATE_RELEASE_FAILURE_MARKER") else { + return; + }; + let category = match failure { + exec_gate::GateReleaseError::NotReleased(_) => "not_released", + exec_gate::GateReleaseError::ExecFailed(_) => "exec_failed", + exec_gate::GateReleaseError::Ambiguous(_) => "ambiguous", + }; + let disposition = match cleanup { + spawn_registry::FailedReleaseCleanup::Reaped => "reaped", + spawn_registry::FailedReleaseCleanup::Retained => "retained", + spawn_registry::FailedReleaseCleanup::Transferred => "swept", + }; + let line = format!( + "{pid} {category} {disposition} effect={}\n", + u8::from(keep_effect) + ); + if let Ok(mut file) = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(path) + { + let _ = file.write_all(line.as_bytes()); + } +} + /// Terminal status retained by a [`BoundedProcess`] after reaping. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ProcessStatus { @@ -866,6 +3130,8 @@ impl Drop for DrainFinish { } } +type StdinCloseObserver = Arc; + struct StdinState { writer: InterruptibleWriter, #[cfg(windows)] @@ -878,6 +3144,12 @@ struct StdinState { cancellation: CancellationToken, deadline: Instant, done: Arc, + /// The handle's one absolute teardown cutoff. The close wait re-observes + /// it on every iteration so a late-installed instant shortens a parked + /// close instead of letting its captured ordinary grace run out. + final_cutoff: Arc>>, + /// Observation of the absolute cutoff the close join really used. + close_observer: Mutex>, } #[cfg(not(windows))] @@ -892,6 +3164,7 @@ impl StdinState { close_after_initial: bool, cancellation: CancellationToken, deadline: Instant, + final_cutoff: Arc>>, ) -> Result, std::io::Error> { #[cfg(unix)] super::shared::set_pipe_nonblocking(&writer)?; @@ -915,6 +3188,8 @@ impl StdinState { cancellation, deadline, done, + final_cutoff, + close_observer: Mutex::new(None), }); if !initial.is_empty() { let worker_state = Arc::clone(&state); @@ -951,6 +3226,13 @@ impl StdinState { self.windows_write.close(); } + fn cleanup_cutoff(&self) -> Option { + *self + .final_cutoff + .lock() + .unwrap_or_else(|error| error.into_inner()) + } + fn has_initial_payload(&self) -> bool { self.initial_payload } @@ -996,14 +3278,62 @@ impl StdinState { } fn close(&self) -> Result<(), BoundedProcessError> { + self.close_until(Instant::now() + CLEANUP_GRACE, false) + } + + fn close_within(&self, cutoff: Instant) -> Result<(), BoundedProcessError> { + // A bounded teardown already fixed one absolute cutoff. Waiting on a + // shorter local floor here would make the stdin proof fail before that + // cutoff and disagree with every other cleanup participant. + self.close_until(cutoff, true) + } + + /// Closes stdin and joins the initial writer only when it really finished. + /// + /// The ordinary path (`require_proof == false`) keeps its historical + /// success: a slow worker is not an IO failure. A bounded teardown + /// (`require_proof == true`) reports `WorkerFailed` instead of claiming a + /// completed close it could not prove. In both cases a worker that missed + /// the deadline keeps its join handle here: it stays owned (the caller's + /// worker accounting is unchanged) and the destructor can never block on a + /// detached timed-out join. + fn close_until( + &self, + wait_deadline: Instant, + require_proof: bool, + ) -> Result<(), BoundedProcessError> { + if let Some(observer) = self + .close_observer + .lock() + .unwrap_or_else(|error| error.into_inner()) + .clone() + { + observer(wait_deadline); + } self.closed.store(true, Ordering::Release); self.force_close_writer(); - self.done.wait_until(Instant::now() + CLEANUP_GRACE); - let _ = self + // Re-observe the handle's shared cutoff on every iteration. A teardown + // may install it after this ordinary close already started, and that + // shorter instant must end the wait exactly as it ends every other + // cleanup participant. + if !self + .done + .wait_until_observed(wait_deadline, &|| self.cleanup_cutoff()) + { + return if require_proof { + Err(BoundedProcessError::WorkerFailed) + } else { + Ok(()) + }; + } + if let Some(handle) = self .initial_writer .lock() .unwrap_or_else(|error| error.into_inner()) - .take(); + .take() + { + let _ = handle.join(); + } if let Some(error) = self .initial_error .lock() @@ -1020,7 +3350,8 @@ impl Drop for StdinState { fn drop(&mut self) { self.closed.store(true, Ordering::Release); self.force_close_writer(); - self.done.wait_until(Instant::now() + CLEANUP_GRACE); + self.done + .wait_until_observed(Instant::now() + CLEANUP_GRACE, &|| self.cleanup_cutoff()); let _ = self .initial_writer .get_mut() @@ -1032,6 +3363,7 @@ impl Drop for StdinState { #[cfg(target_os = "linux")] mod linux_pidfd { use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; + use std::sync::atomic::Ordering; use super::ProcessStatus; @@ -1041,6 +3373,15 @@ mod linux_pidfd { impl PidFd { pub(super) fn open(pid: u32) -> std::io::Result { + #[cfg(target_os = "linux")] + if super::PIDFD_OPEN_FAILURES + .try_update(Ordering::SeqCst, Ordering::SeqCst, |remaining| { + (remaining > 0).then(|| remaining - 1) + }) + .is_ok() + { + return Err(std::io::Error::from_raw_os_error(libc::EAGAIN)); + } let pid = libc::pid_t::try_from(pid).map_err(|_| { std::io::Error::new(std::io::ErrorKind::InvalidInput, "pid out of range") })?; @@ -1061,6 +3402,11 @@ mod linux_pidfd { }) } + /// The raw pidfd, for the shared ownership-checked group signal. + pub(super) fn raw_fd(&self) -> std::os::unix::io::RawFd { + self.fd.as_raw_fd() + } + pub(super) fn send_signal(&self, signal: libc::c_int) -> std::io::Result<()> { // SAFETY: `self.fd` is a live pidfd we exclusively own. A null // siginfo with flags 0 sends `signal` to that process. @@ -1123,7 +3469,13 @@ fn waitid_wnowait( })) } -#[cfg(all(unix, not(target_os = "linux")))] +/// Observes whether `pid` exited, without reaping it. +/// +/// `waitid(WNOWAIT)` keeps the root an owned zombie, so its process-group id +/// stays reserved for the ownership-checked group signal that follows. A +/// reaping observation here would free the pid and force the group decision to +/// skip its signal (`ECHILD`), leaving the descendants alive. +#[cfg(unix)] fn observe_pid_wnowait(pid: u32) -> std::io::Result> { let pid = libc::pid_t::try_from(pid) .map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidInput, "pid out of range"))?; @@ -1186,18 +3538,33 @@ impl DrainDone { } fn wait_until(&self, deadline: Instant) -> bool { + self.wait_until_observed(deadline, &|| None) + } + + /// Waits until `deadline`, but re-observes a stored absolute cutoff on + /// every iteration. A teardown that installs its cutoff while this waiter + /// is parked must shorten the wait instead of letting the original grace + /// run to completion. + fn wait_until_observed(&self, deadline: Instant, stored_cutoff: &F) -> bool + where + F: Fn() -> Option, + { if self.is_completed() { return true; } let mut done = self.lock.lock().unwrap_or_else(|error| error.into_inner()); while !*done { let now = Instant::now(); + let deadline = stored_cutoff().map_or(deadline, |cutoff| deadline.min(cutoff)); if now >= deadline { return false; } let (guard, timed) = self .cv - .wait_timeout(done, deadline.saturating_duration_since(now)) + .wait_timeout( + done, + deadline.saturating_duration_since(now).min(WAIT_SLICE), + ) .unwrap_or_else(|error| error.into_inner()); done = guard; if timed.timed_out() && Instant::now() >= deadline { @@ -1420,34 +3787,86 @@ fn spawn_drainer( }) } -fn join_stream_drainers(drainers: &mut [StreamDrainer]) -> Result<(), BoundedProcessError> { - let wait_deadline = Instant::now() + CLEANUP_GRACE; +/// Joins whatever drainers completed by `cutoff` and returns the unfinished +/// ones so ownership stays with the caller for a later proof attempt. +/// +/// `stored_cutoff` is re-read before every wait so a teardown cutoff installed +/// after the join started still bounds it. +fn join_stream_drainers( + drainers: Vec, + cutoff: Option, + stored_cutoff: F, +) -> (Result<(), BoundedProcessError>, Vec) +where + F: Fn() -> Option, +{ + // One teardown owns exactly one absolute instant. A shorter local floor + // here would make a pending drainer report `WorkerFailed` before the + // shared budget expired and disagree with every other cleanup participant. let mut result = Ok(()); - for drainer in drainers.iter_mut() { - if !drainer.done.wait_until(wait_deadline) { + let mut remaining = Vec::new(); + for mut drainer in drainers { + let wait_deadline = match stored_cutoff() { + Some(stored) => cutoff + .unwrap_or_else(|| Instant::now() + CLEANUP_GRACE) + .min(stored), + None => cutoff.unwrap_or_else(|| Instant::now() + CLEANUP_GRACE), + }; + if !drainer + .done + .wait_until_observed(wait_deadline, &stored_cutoff) + { drainer.close(); - if !drainer.done.wait_until(Instant::now() + CLEANUP_GRACE) && result.is_ok() { - result = Err(BoundedProcessError::WorkerFailed); + let close_deadline = match stored_cutoff() { + Some(stored) => cutoff + .unwrap_or_else(|| Instant::now() + CLEANUP_GRACE) + .min(stored), + None => cutoff.unwrap_or_else(|| Instant::now() + CLEANUP_GRACE), + }; + if !drainer + .done + .wait_until_observed(close_deadline, &stored_cutoff) + { + if result.is_ok() { + result = Err(BoundedProcessError::WorkerFailed); + } + remaining.push(drainer); continue; } } - if drainer.done.is_completed() - && let Some(join) = drainer.join.take() - && join.join().is_err() - && result.is_ok() - { - result = Err(BoundedProcessError::WorkerFailed); + if drainer.done.is_completed() { + if let Some(join) = drainer.join.take() + && join.join().is_err() + && result.is_ok() + { + result = Err(BoundedProcessError::WorkerFailed); + } + } else { + remaining.push(drainer); } } - result + (result, remaining) } fn wait_child_until( + process: &ProcessInner, child: &mut Child, deadline: Instant, ) -> Result { loop { - match child.try_wait() { + // A late teardown cutoff owns this wait too: re-observe the one shared + // instant every iteration rather than keeping the captured grace. + let deadline = process.effective_deadline(deadline); + let observed = { + // The reap frees the pid; the exit sweep's group observation and + // numeric group signal are serialized against it. Never block past + // this wait's own deadline for that ordering. + let Some(_serial) = reap_serial_before(deadline) else { + return Err(BoundedProcessError::DeadlineElapsed); + }; + child.try_wait() + }; + match observed { Ok(Some(status)) => return Ok(ProcessStatus::from_exit_status(status)), Ok(None) => { let now = Instant::now(); @@ -1465,15 +3884,6 @@ fn wait_child_until( } } -fn abort_spawned_child(mut child: Child, pid: u32) { - terminate_process_tree(pid); - let _ = child.kill(); - match wait_child_until(&mut child, Instant::now() + CLEANUP_GRACE) { - Ok(_) => {} - Err(_) => std::mem::forget(child), - } -} - fn allocate_process_handle() -> ProcessHandle { loop { let id = NEXT_PROCESS_HANDLE.fetch_add(1, Ordering::Relaxed); @@ -1490,6 +3900,27 @@ enum TreeCleanup { Cleaned, } +/// Typed result of one attempt at the process tree's group decision. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum TreeCleanupOutcome { + /// The group decision completed (signalled, or proven not to be ours) and + /// the tree is `Cleaned`. + Cleaned, + /// The reap lock could not be taken before this attempt's cutoff, so no + /// group decision was possible. The tree stays `Pending` and the root + /// stays unreaped for a later attempt; this is never reported as clean. + DecisionTimedOut, + /// The ownership observation proved nothing (for example `EINTR`), so the + /// numeric group signal was skipped. The tree stays `Pending` and the root + /// stays unreaped for a later bounded attempt; this is never reported as + /// clean, even though an exact pidfd signal may have been delivered. + DecisionInconclusive, + /// This attempt produced no proof: another owner is still cleaning the + /// tree, or the test-only stall withheld the `Cleaned` proof after a real + /// kill. The tree is not reported clean. + Deferred, +} + struct ChildState { child: Option, terminal: Option, @@ -1507,27 +3938,83 @@ struct TreeCleanupTestHooks { last_tree_kill_retained_zombie: AtomicBool, } +struct DrainJoinState { + joining: bool, + /// A *completed* proof. A pending/timed-out attempt is never cached, so a + /// later bounded cleanup can still establish the real proof. + result: Option>, +} + struct ProcessInner { handle: ProcessHandle, pid: u32, + /// Exit-time visibility for this OS child, independent of the process + /// table. Dropped with the last handle clone. + spawn_registration: Option, #[cfg(windows)] job: Option, #[cfg(target_os = "linux")] - pidfd: Option, + pidfd: Mutex>, deadline: Instant, child: Mutex, child_wake: Condvar, logs: Arc>, - stdin: Arc, + stdin: Option>, drainers: Mutex>, - drainers_result: OnceLock>, + drainer_join: Mutex, + drainer_join_wake: Condvar, drain_stop: Arc, cancellation: CancellationToken, + /// The single absolute cutoff of the teardown that owns this handle. The + /// destructor reuses it instead of starting a fresh ordinary grace; the + /// stdin close wait observes it through the same shared cell. + final_cutoff: Arc>>, + /// Test-only proof withholding after a real tree kill. + stall_tree_cleanup: bool, + /// Test-only: force the destructor's final reap observation to look + /// unproven after a successful group decision. + #[cfg(any(test, feature = "workspace-io-fault"))] + destructor_reap_unproven: AtomicBool, + /// Test-only observation point for the ordinary (unbounded) drain join, so + /// a concurrent bounded teardown can be measured while it is in progress. + drain_join_observer: Mutex>>, + /// Test-only synchronization point fired from the foreground wait loop + /// immediately before it parks. A test installs a late cutoff only after + /// this fires, so the waiter is provably already inside the wait. + #[cfg(test)] + wait_loop_observer: Mutex>>, #[cfg(all(test, unix))] test_hooks: TreeCleanupTestHooks, } impl ProcessInner { + fn note_cutoff(&self, cutoff: Instant) { + let mut stored = self + .final_cutoff + .lock() + .unwrap_or_else(|error| error.into_inner()); + if stored.is_none_or(|existing| cutoff < existing) { + *stored = Some(cutoff); + } + } + + fn cleanup_cutoff(&self) -> Option { + *self + .final_cutoff + .lock() + .unwrap_or_else(|error| error.into_inner()) + } + /// Earliest of the caller's deadline and the absolute teardown cutoff + /// currently stored on this handle. + /// + /// Wait loops call this on every iteration: a cutoff installed by a + /// concurrent teardown must shorten a wait that already started, including + /// an ordinary harvest or drainer join. + fn effective_deadline(&self, deadline: Instant) -> Instant { + self.cleanup_cutoff() + .map_or(deadline, |cutoff| deadline.min(cutoff)) + } + fn map_wait_error(error: std::io::Error) -> BoundedProcessError { BoundedProcessError::WaitFailed { os_code: error.raw_os_error(), @@ -1536,16 +4023,32 @@ impl ProcessInner { fn observe_root_exit_locked( &self, - child: Option<&Child>, + child: Option<&mut Child>, ) -> Result, BoundedProcessError> { #[cfg(target_os = "linux")] { let _ = child; - let pidfd = self - .pidfd - .as_ref() - .ok_or(BoundedProcessError::WaitFailed { os_code: None })?; - pidfd.observe_exit_wnowait().map_err(Self::map_wait_error) + let mut pidfd = self.pidfd.lock().unwrap_or_else(|error| error.into_inner()); + if pidfd.is_none() { + // Retained handles remember the already acquired pidfd. If it + // could not be obtained, retry once lazily here; a failed + // retry degrades to the ordinary wait-status observation. + *pidfd = linux_pidfd::PidFd::open(self.pid).ok(); + } + if let Some(pidfd) = pidfd.as_ref() { + return pidfd.observe_exit_wnowait().map_err(Self::map_wait_error); + } + drop(pidfd); + // No pidfd is usable. The observation must still be non-reaping: + // `waitid(WNOWAIT)` reports the exit while the root stays an owned + // zombie, so the following group signal can still prove ownership + // and kill the descendants. `Child::try_wait` is deliberately not + // used here because it reaps the root, after which the group + // decision sees `ECHILD` and must skip the signal. + let Some(_serial) = reap_serial_before(self.effective_deadline(self.deadline)) else { + return Ok(None); + }; + observe_pid_wnowait(self.pid).map_err(Self::map_wait_error) } #[cfg(all(unix, not(target_os = "linux")))] { @@ -1571,38 +4074,43 @@ impl ProcessInner { fn wait_while_cleaning<'a>( &'a self, mut state: MutexGuard<'a, ChildState>, + cutoff: Instant, ) -> MutexGuard<'a, ChildState> { if state.tree_cleanup == TreeCleanup::Cleaning { #[cfg(all(test, unix))] self.run_on_wait_for_cleanup_hook(); } + let deadline = self.effective_deadline(self.deadline.min(cutoff)); while state.tree_cleanup == TreeCleanup::Cleaning { - let remaining = self.deadline.saturating_duration_since(Instant::now()); + // Re-observe the stored cutoff each iteration so a teardown that + // installs it while this waiter is parked shortens the wait. + let deadline = self.effective_deadline(deadline); + let remaining = deadline.saturating_duration_since(Instant::now()); if remaining.is_zero() { break; } let (guard, wait_result) = self .child_wake - .wait_timeout(state, remaining) + .wait_timeout(state, remaining.min(WAIT_SLICE)) .unwrap_or_else(|error| error.into_inner()); state = guard; - if wait_result.timed_out() && Instant::now() >= self.deadline { + if wait_result.timed_out() && Instant::now() >= deadline { break; } } state } - fn cleanup_tree_once(&self) { + fn cleanup_tree_once(&self, cutoff: Instant) -> TreeCleanupOutcome { { let mut state = self.lock_child(); loop { match state.tree_cleanup { - TreeCleanup::Cleaned => return, + TreeCleanup::Cleaned => return TreeCleanupOutcome::Cleaned, TreeCleanup::Cleaning => { - state = self.wait_while_cleaning(state); + state = self.wait_while_cleaning(state, cutoff); if state.tree_cleanup != TreeCleanup::Cleaned { - return; + return TreeCleanupOutcome::Deferred; } } TreeCleanup::Pending => { @@ -1615,10 +4123,6 @@ impl ProcessInner { self.drain_stop.store(true, Ordering::Release); #[cfg(all(test, unix))] self.run_before_group_kill_hook(); - #[cfg(target_os = "linux")] - if let Some(pidfd) = &self.pidfd { - let _ = pidfd.send_signal(libc::SIGKILL); - } #[cfg(windows)] if let Some(job) = &self.job { job.terminate(); @@ -1632,19 +4136,68 @@ impl ProcessInner { .last_tree_kill_retained_zombie .store(proc_is_our_zombie(self.pid), Ordering::Release); } - super::shared::terminate_process_group(self.pid); + // Every process-group signal goes through the one + // ownership-checked helper. It takes the reap lock, proves with + // `waitid(WNOWAIT)` that this pid still names our unreaped child, + // signals the numeric group only then, and always delivers the + // exact pidfd signal. The exit sweep may already have reaped this + // root; its old group number must never be signalled then. + #[cfg(target_os = "linux")] + let pidfd = self + .pidfd + .lock() + .unwrap_or_else(|error| error.into_inner()) + .as_ref() + .map(linux_pidfd::PidFd::raw_fd); + #[cfg(not(target_os = "linux"))] + let pidfd = None; + let decision = signal_owned_group(self.pid, pidfd, cutoff); + match decision { + GroupDecision::NotDecided => { + // Another reaper holds the reap lock past this cutoff. No + // group decision was taken, so the tree cannot be called + // clean: keep it Pending (and the root unreaped) so a later + // bounded attempt can still decide, and report the reason. + let mut state = self.lock_child(); + state.tree_cleanup = TreeCleanup::Pending; + self.child_wake.notify_all(); + return TreeCleanupOutcome::DecisionTimedOut; + } + GroupDecision::Inconclusive => { + // The observation proved nothing about this root's group. + // The exact pidfd (when present) may have been signalled, + // but the numeric group was deliberately skipped because + // the pid might no longer name our group. The tree stays + // Pending and the leader unreaped so a later bounded + // attempt can verify ownership and kill the descendants. + let mut state = self.lock_child(); + state.tree_cleanup = TreeCleanup::Pending; + self.child_wake.notify_all(); + return TreeCleanupOutcome::DecisionInconclusive; + } + GroupDecision::Signalled | GroupDecision::Released => {} + } } let mut state = self.lock_child(); if let Some(child) = state.child.as_mut() { let _ = child.kill(); } + if self.stall_tree_cleanup { + self.child_wake.notify_all(); + return TreeCleanupOutcome::Deferred; + } state.tree_cleanup = TreeCleanup::Cleaned; self.child_wake.notify_all(); + TreeCleanupOutcome::Cleaned } - fn harvest_if_exited(&self) -> Result, BoundedProcessError> { + fn harvest_if_exited( + &self, + cutoff: Instant, + ) -> Result, BoundedProcessError> { + let cutoff = self.effective_deadline(cutoff); { - let state = self.lock_child(); + let mut state = self.lock_child(); if let Some(status) = state.terminal { return Ok(Some(status)); } @@ -1652,13 +4205,13 @@ impl ProcessInner { return Ok(None); } if self - .observe_root_exit_locked(state.child.as_ref())? + .observe_root_exit_locked(state.child.as_mut())? .is_none() { return Ok(None); } } - self.cleanup_tree_once(); + let _ = self.cleanup_tree_once(self.effective_deadline(cutoff)); let mut state = self.lock_child(); if let Some(status) = state.terminal { return Ok(Some(status)); @@ -1666,7 +4219,7 @@ impl ProcessInner { if state.reaping { return Ok(None); } - state = self.wait_while_cleaning(state); + state = self.wait_while_cleaning(state, self.effective_deadline(cutoff)); if state.tree_cleanup != TreeCleanup::Cleaned { return Ok(None); } @@ -1678,9 +4231,20 @@ impl ProcessInner { } #[cfg(all(test, unix))] self.run_on_reap_hook(); - let reaped = match state.child.as_mut() { - Some(child) => child.try_wait().map_err(Self::map_wait_error)?, - None => return Ok(state.terminal), + // Reap under the group-signal serialization lock: the exit sweep's + // WNOWAIT observation and numeric group signal must not interleave + // with this reap, which frees the pid and with it the group id. + let reaped = { + let Some(_serial) = reap_serial_before(self.effective_deadline(cutoff)) else { + // Another reaper owns the group-signal decision past this + // cutoff. Leaving the root for a later poll is safer than + // blocking the cleanup past its own boundary. + return Ok(None); + }; + match state.child.as_mut() { + Some(child) => child.try_wait().map_err(Self::map_wait_error)?, + None => return Ok(state.terminal), + } }; let Some(status) = reaped.map(ProcessStatus::from_exit_status) else { return Ok(None); @@ -1693,9 +4257,21 @@ impl ProcessInner { } fn try_wait(&self) -> Result, BoundedProcessError> { - let status = self.harvest_if_exited()?; + // A teardown that owns this handle fixes one absolute cutoff. Harvest + // and the drainer join re-observe it on every wait, so a cutoff + // installed after this call started still shortens both. + let status = self.harvest_if_exited(self.deadline)?; if status.is_some() { - let _ = self.join_drainers(); + // Re-read after harvesting: the cutoff may have arrived while the + // waiter was parked inside harvest. + match self.cleanup_cutoff() { + Some(cutoff) => { + let _ = self.join_drainers_before(cutoff); + } + None => { + let _ = self.join_drainers(); + } + } } Ok(status) } @@ -1718,7 +4294,7 @@ impl ProcessInner { deadline: Instant, ) -> Result, BoundedProcessError> { let status = { - let state = self.lock_child(); + let mut state = self.lock_child(); if let Some(status) = state.terminal { // An authorized path already reaped this handle. Some(status) @@ -1727,7 +4303,7 @@ impl ProcessInner { // observation neither waits on it nor interferes with it. return Ok(None); } else { - self.observe_root_exit_locked(state.child.as_ref())? + self.observe_root_exit_locked(state.child.as_mut())? } }; let Some(status) = status else { @@ -1763,7 +4339,8 @@ impl ProcessInner { }; let mut completed = true; for done in &done_handles { - if !done.wait_until(deadline) { + let effective = self.effective_deadline(deadline); + if !done.wait_until_observed(effective, &|| self.cleanup_cutoff()) { completed = false; } } @@ -1793,10 +4370,14 @@ impl ProcessInner { /// cleanup drain join closes its exact output drainers within the existing /// cleanup grace. A signaled group therefore still ends as a real reap /// instead of remaining candidate proof forever. - fn cleanup_proof_terminal(&self) -> Result, BoundedProcessError> { - let status = self.harvest_if_exited()?; + fn cleanup_proof_terminal( + &self, + cutoff: Instant, + ) -> Result, BoundedProcessError> { + self.note_cutoff(cutoff); + let status = self.harvest_if_exited(cutoff)?; if status.is_some() { - self.join_drainers()?; + self.join_drainers_before(cutoff)?; } Ok(status) } @@ -1804,7 +4385,7 @@ impl ProcessInner { fn poll(&self) -> Result, BoundedProcessError> { if self.cancellation.is_cancelled() { self.kill_process_tree()?; - let _ = self.reap(); + let _ = self.reap_after_stop(); return Err(BoundedProcessError::Cancelled); } if Instant::now() >= self.deadline { @@ -1817,7 +4398,7 @@ impl ProcessInner { } drop(state); self.kill_process_tree()?; - let _ = self.reap(); + let _ = self.reap_after_stop(); return Err(BoundedProcessError::DeadlineElapsed); } if let Some(status) = self.try_wait()? { @@ -1835,41 +4416,67 @@ impl ProcessInner { F: Fn() -> bool, { loop { + // A teardown may install its absolute cutoff while this waiter is + // parked. Re-observe it every iteration instead of trusting the + // caller's captured deadline; the sleep is sliced so the new + // instant is noticed within one wait slice. + let deadline = self.effective_deadline(deadline); if self.cancellation.is_cancelled() || is_cancelled() { self.kill_process_tree()?; - let _ = self.reap(); + let _ = self.reap_after_stop(); return Err(BoundedProcessError::Cancelled); } let now = Instant::now(); if now >= deadline { self.kill_process_tree()?; - let _ = self.reap(); + let _ = self.reap_after_stop(); return Err(BoundedProcessError::DeadlineElapsed); } if let Some(status) = self.try_wait()? { self.reap()?; return Ok(status); } + #[cfg(test)] + if let Some(observer) = self + .wait_loop_observer + .lock() + .unwrap_or_else(|error| error.into_inner()) + .as_ref() + { + observer(); + } thread::sleep(deadline.saturating_duration_since(now).min(WAIT_SLICE)); } } fn reap(&self) -> Result { - self.cleanup_tree_once(); + // Once a teardown fixed the absolute cutoff, the ordinary reap is + // that teardown's wait: its tree-cleaner contention, terminal + // observation, stdin close and drainer join all stay inside the one + // stored instant. + if let Some(cutoff) = self.cleanup_cutoff() { + return self.reap_within(cutoff); + } + self.cleanup_tree_once(self.effective_deadline(self.deadline)); let status = loop { + // A teardown may install its cutoff while this ordinary reap is + // already running; every wait in this iteration observes that + // same instant, and a cutoff shorter than the process deadline + // ends the loop instead of starting a fresh ordinary grace. + let deadline = self.effective_deadline(self.deadline); { let state = self.child.lock().unwrap_or_else(|error| error.into_inner()); if let Some(status) = state.terminal { break status; } if state.reaping { - let remaining = self.deadline.saturating_duration_since(Instant::now()); + let remaining = deadline.saturating_duration_since(Instant::now()); let (guard, wait_result) = self .child_wake - .wait_timeout(state, remaining.max(WAIT_SLICE)) + .wait_timeout(state, remaining.min(WAIT_SLICE)) .unwrap_or_else(|error| error.into_inner()); drop(guard); - if wait_result.timed_out() && Instant::now() >= self.deadline { + if wait_result.timed_out() && Instant::now() >= deadline { return Err(BoundedProcessError::DeadlineElapsed); } continue; @@ -1879,22 +4486,22 @@ impl ProcessInner { if self.cancellation.is_cancelled() { self.kill_process_tree()?; } - if Instant::now() >= self.deadline { + if Instant::now() >= deadline { self.kill_process_tree()?; } - if let Some(status) = self.harvest_if_exited()? { + if let Some(status) = self.harvest_if_exited(deadline)? { break status; } - if Instant::now() >= self.deadline { + if Instant::now() >= deadline { let child = { let mut state = self.lock_child(); if let Some(status) = state.terminal { break status; } if state.tree_cleanup == TreeCleanup::Cleaning { - state = self.wait_while_cleaning(state); + state = self.wait_while_cleaning(state, deadline); } if let Some(status) = state.terminal { break status; @@ -1903,13 +4510,13 @@ impl ProcessInner { return Err(BoundedProcessError::DeadlineElapsed); } if state.reaping { - let remaining = self.deadline.saturating_duration_since(Instant::now()); + let remaining = deadline.saturating_duration_since(Instant::now()); let (guard, wait_result) = self .child_wake - .wait_timeout(state, remaining.max(WAIT_SLICE)) + .wait_timeout(state, remaining.min(WAIT_SLICE)) .unwrap_or_else(|error| error.into_inner()); drop(guard); - if wait_result.timed_out() && Instant::now() >= self.deadline { + if wait_result.timed_out() && Instant::now() >= deadline { return Err(BoundedProcessError::DeadlineElapsed); } continue; @@ -1918,7 +4525,11 @@ impl ProcessInner { state.child.take() }; if let Some(mut child) = child { - let result = wait_child_until(&mut child, Instant::now() + CLEANUP_GRACE); + let result = wait_child_until( + self, + &mut child, + self.effective_deadline(Instant::now() + CLEANUP_GRACE), + ); let mut state = self.child.lock().unwrap_or_else(|error| error.into_inner()); state.reaping = false; match result { @@ -1937,15 +4548,77 @@ impl ProcessInner { } thread::sleep( - self.deadline + deadline .saturating_duration_since(Instant::now()) .min(WAIT_SLICE), ); }; - let stdin_result = self.stdin.close(); + // The reap may itself have observed a cutoff installed by a concurrent + // teardown. Close stdin and join drainers against that stored instant + // instead of starting an ordinary grace beyond it. + let cutoff = self.cleanup_cutoff(); + let stdin_result = match (&self.stdin, cutoff) { + (Some(stdin), Some(cutoff)) => stdin.close_within(cutoff), + (Some(stdin), None) => stdin.close(), + (None, _) => Ok(()), + }; + self.drain_stop.store(true, Ordering::Release); + let drain_result = match cutoff { + Some(cutoff) => self.join_drainers_before(cutoff), + None => self.join_drainers(), + }; + match (stdin_result, drain_result) { + (Err(error), _) => Err(error), + (Ok(()), Err(error)) => Err(error), + (Ok(()), Ok(())) => Ok(status), + } + } + + /// Reaps after a foreground wait observed a stop. A teardown that already + /// fixed the one absolute cleanup cutoff owns that wait: an ordinary reap + /// would start fresh stdin and drainer grace beyond the cutoff the rest of + /// the teardown is measured against. + fn reap_after_stop(&self) -> Result { + match self.cleanup_cutoff() { + Some(cutoff) => self.reap_within(cutoff), + None => self.reap(), + } + } + + /// Bounded reap used by the destructor and by cleanup after its ordinary + /// deadline already passed. Every wait uses the caller's absolute cutoff; + /// a kill and a non-blocking exit observation are still attempted so a + /// killed child is reaped when the kernel already has its status. + fn reap_within(&self, cutoff: Instant) -> Result { + self.note_cutoff(cutoff); + // Another teardown may already have fixed an earlier instant. Use the + // stored minimum, not the later argument that happened to arrive here. + let cutoff = self.cleanup_cutoff().unwrap_or(cutoff); + self.cleanup_tree_once(cutoff); + let status = loop { + // Re-observe the one shared instant on every iteration so a + // cutoff installed while this reap is parked shortens its wait. + let cutoff = self.effective_deadline(cutoff); + if let Some(status) = self.lock_child().terminal { + break status; + } + if let Some(status) = self.harvest_if_exited(cutoff)? { + break status; + } + let now = Instant::now(); + if now >= cutoff { + return Err(BoundedProcessError::DeadlineElapsed); + } + thread::sleep(cutoff.saturating_duration_since(now).min(WAIT_SLICE)); + }; + let cutoff = self.cleanup_cutoff().unwrap_or(cutoff); + let stdin_result = match &self.stdin { + Some(stdin) => stdin.close_within(cutoff), + None => Ok(()), + }; self.drain_stop.store(true, Ordering::Release); - let drain_result = self.join_drainers(); + let drain_result = self.join_drainers_before(cutoff); match (stdin_result, drain_result) { (Err(error), _) => Err(error), (Ok(()), Err(error)) => Err(error), @@ -1954,36 +4627,132 @@ impl ProcessInner { } fn join_drainers(&self) -> Result<(), BoundedProcessError> { + self.join_drainers_until(None) + } + + /// Joins the output drainers under the caller's absolute cutoff: a bounded + /// cleanup never starts a fresh ordinary grace after the cutoff, and it + /// never blocks on another owner's unbounded join. + fn join_drainers_before(&self, cutoff: Instant) -> Result<(), BoundedProcessError> { + self.note_cutoff(cutoff); + self.join_drainers_until(Some(cutoff)) + } + + fn join_drainers_until(&self, cutoff: Option) -> Result<(), BoundedProcessError> { self.drain_stop.store(true, Ordering::Release); - self.drainers_result - .get_or_init(|| { - let mut drainers = self - .drainers - .lock() - .unwrap_or_else(|error| error.into_inner()) - .drain(..) - .collect::>(); - let mut result = join_stream_drainers(&mut drainers); - if result.is_ok() { - for stream in [LogStream::Stdout, LogStream::Stderr] { - if self - .logs - .lock() + let mut state = self + .drainer_join + .lock() + .unwrap_or_else(|error| error.into_inner()); + if let Some(result) = &state.result { + return result.clone(); + } + if state.joining { + // One waiter owns the join. Another owner may already be inside it; + // wait for that handoff without a bound while no cutoff exists, and + // immediately switch to the stored absolute cutoff if a teardown + // installs one while this waiter is parked. + loop { + if let Some(result) = &state.result { + return result.clone(); + } + if !state.joining { + break; + } + let bound = cutoff.into_iter().chain(self.cleanup_cutoff()).min(); + match bound { + None => { + state = self + .drainer_join_wake + .wait_timeout(state, WAIT_SLICE) .unwrap_or_else(|error| error.into_inner()) - .has_error(stream) - { - result = Err(BoundedProcessError::DrainFailed { stream }); - break; + .0; + } + Some(bound) => { + let now = Instant::now(); + if now >= bound { + return Err(BoundedProcessError::WorkerFailed); + } + let (guard, timed_out) = self + .drainer_join_wake + .wait_timeout( + state, + bound.saturating_duration_since(now).min(WAIT_SLICE), + ) + .unwrap_or_else(|error| error.into_inner()); + state = guard; + if let Some(result) = &state.result { + return result.clone(); + } + if timed_out.timed_out() && Instant::now() >= bound { + return Err(BoundedProcessError::WorkerFailed); } } } - result - }) - .clone() + } + } + state.joining = true; + drop(state); + if cutoff.is_none() && self.cleanup_cutoff().is_none() { + let observer = self + .drain_join_observer + .lock() + .unwrap_or_else(|error| error.into_inner()) + .clone(); + if let Some(observer) = observer { + observer(); + } + } + let taken = self + .drainers + .lock() + .unwrap_or_else(|error| error.into_inner()) + .drain(..) + .collect::>(); + let (mut result, remaining) = join_stream_drainers(taken, cutoff, || self.cleanup_cutoff()); + if result.is_ok() { + for stream in [LogStream::Stdout, LogStream::Stderr] { + if self + .logs + .lock() + .unwrap_or_else(|error| error.into_inner()) + .has_error(stream) + { + result = Err(BoundedProcessError::DrainFailed { stream }); + break; + } + } + } + let pending = !remaining.is_empty(); + { + let mut state = self + .drainer_join + .lock() + .unwrap_or_else(|error| error.into_inner()); + state.joining = false; + if !pending && !matches!(result, Err(BoundedProcessError::WorkerFailed)) { + state.result = Some(result.clone()); + } + if pending { + self.drainers + .lock() + .unwrap_or_else(|error| error.into_inner()) + .extend(remaining); + } + self.drainer_join_wake.notify_all(); + } + if pending { + return Err(BoundedProcessError::WorkerFailed); + } + result } fn kill_process_tree(&self) -> Result<(), BoundedProcessError> { - self.cleanup_tree_once(); + // A stored teardown cutoff owns this wait too: waiting for another + // tree cleaner must not extend past the absolute instant the whole + // teardown is measured against. + let cutoff = self.cleanup_cutoff().unwrap_or(self.deadline); + self.cleanup_tree_once(cutoff); Ok(()) } @@ -2023,22 +4792,101 @@ impl ProcessInner { impl Drop for ProcessInner { fn drop(&mut self) { + // Never start a fresh ordinary grace here: when a teardown already + // stored its absolute cutoff, the destructor must finish inside that + // same budget (an expired cutoff means no further waiting). + let cutoff = self + .cleanup_cutoff() + .unwrap_or_else(|| Instant::now() + CLEANUP_GRACE); + self.note_cutoff(cutoff); self.cancellation.cancel(); self.drain_stop.store(true, Ordering::Release); - let _ = self.kill_process_tree(); - let _ = self.stdin.close(); - let _ = self.reap(); + let _ = self.cleanup_tree_once(cutoff); + if let Some(stdin) = &self.stdin { + let _ = stdin.close_within(cutoff); + } + // Test-only: the unproven-observation seam still performs the real + // group decision, but neither harvests nor reaps the leader here, so + // the decided-but-unproven branch below is exercised before the + // bounded reclaimer takes over. + #[cfg(any(test, feature = "workspace-io-fault"))] + let force_unproven_teardown = self.destructor_reap_unproven.load(Ordering::SeqCst); + #[cfg(not(any(test, feature = "workspace-io-fault")))] + let force_unproven_teardown = false; + if !force_unproven_teardown { + let _ = self.reap_within(cutoff); + } let state = self .child .get_mut() .unwrap_or_else(|error| error.into_inner()); + // The destructor obeys the same decision-before-reap rule as every + // other reaper. Releasing the leader frees its pid and with it the + // process-group id, so a trial wait may only run after the group + // decision proved the tree ours and signalled it. + let decided = state.tree_cleanup == TreeCleanup::Cleaned; + let mut unreaped_child = None; if let Some(mut child) = state.child.take() { - match child.try_wait() { - Ok(Some(_)) => {} - _ => std::mem::forget(child), + if !decided { + // No group decision was taken: descendants may still be alive. + // Keep the leader unreaped so the group id stays reserved. + unreaped_child = Some(child); + } else { + // Serialize the final reap with the exit sweep's group + // observation and numeric group signal, bounded by this + // teardown's cutoff. A successful decision proves the tree was + // signalled, not that this owner observed the reap: if the + // wait cannot prove it, the handle keeps true ownership below + // instead of reporting a clean tree. + let observed = if force_unproven_teardown { + None + } else { + reap_serial_before(cutoff).map(|_serial| child.try_wait()) + }; + match observed { + Some(Ok(Some(_))) => {} + _ => unreaped_child = Some(child), + } + } + } + // On every unproven branch the child and its exit-sweep registration + // are handed to the bounded reclaimer together. The registration is + // what keeps the sweep able to name the tree; dropping it on an + // unproven teardown would forget a live child. The reclaimer drops it + // only after an independently proven disappearance, so a long-lived + // caller does not accumulate unreachable records. + #[cfg(unix)] + match (unreaped_child, self.spawn_registration.take()) { + (Some(child), Some(registration)) => { + spawn_registry::retain_unproven(self.pid, child, registration); + } + // Defensive: an unproven child without a registration can only be + // kept alive by leaking its handle, exactly as before. + (Some(child), None) => std::mem::forget(child), + (None, Some(registration)) => drop(registration), + (None, None) => {} + } + // Non-Unix keeps its pre-existing cleanup semantics: there is no + // process-group registration to reclaim, so an unproven leader is + // leaked to keep its group id reserved, and the registration is + // forgotten exactly when no group decision was taken. + #[cfg(not(unix))] + match (unreaped_child, self.spawn_registration.take()) { + (Some(child), Some(registration)) => { + if !decided { + std::mem::forget(registration); + } + std::mem::forget(child); + } + (Some(child), None) => std::mem::forget(child), + (None, Some(registration)) => { + if !decided { + std::mem::forget(registration); + } } + (None, None) => {} } - let _ = self.join_drainers(); + let _ = self.join_drainers_before(cutoff); } } @@ -2202,7 +5050,7 @@ impl BoundedProcess { } fn spawn_internal( - request: BoundedProcessRequest, + mut request: BoundedProcessRequest, close_after_initial: bool, ) -> Result { request @@ -2221,8 +5069,46 @@ impl BoundedProcess { let confined_cwd = request.confined_cwd.clone(); #[cfg(unix)] let mut confined_cwd_descriptor = None; - let mut command = std::process::Command::new(&request.argv[0]); - command.args(&request.argv[1..]); + // The packaged `tools serve` path may end with `std::process::exit`, + // which cannot join a worker parked between the successful spawn and + // its pid record. On that path the direct child is a pre-exec gate + // that cannot run tool code until the registry has recorded its pid. + #[cfg(target_os = "linux")] + let mut gate_channel = if request.exec_gate { + Some( + exec_gate::GateChannel::open() + .map_err(|error| BoundedProcessError::Spawn(spawn_error(&error)))?, + ) + } else { + None + }; + #[cfg(target_os = "linux")] + let mut command = if let Some(channel) = &gate_channel { + let mut command = std::process::Command::new("/proc/self/exe"); + // The gate receives the exact target argv after a fixed prefix and + // execs it in place. Its environment is the target environment and + // its cwd is the target cwd, both already configured below. + // + // The control endpoint keeps the number the socketpair assigned; + // `pre_exec` only clears `CLOEXEC` on this child's copy, so no + // fixed descriptor (and no stdio/error-pipe slot) is assumed. + command + .arg(exec_gate::EXEC_GATE_ARG) + .arg(channel.child_fd().to_string()) + .arg("--"); + command.args(&request.argv); + command + } else { + let mut command = std::process::Command::new(&request.argv[0]); + command.args(&request.argv[1..]); + command + }; + #[cfg(not(target_os = "linux"))] + let mut command = { + let mut command = std::process::Command::new(&request.argv[0]); + command.args(&request.argv[1..]); + command + }; if let Some(directory) = &confined_cwd { #[cfg(unix)] { @@ -2260,116 +5146,279 @@ impl BoundedProcess { command.process_group(0); #[cfg(windows)] command.creation_flags(windows_sys::Win32::System::Threading::CREATE_SUSPENDED); + #[cfg(target_os = "linux")] + if let Some(channel) = &gate_channel { + let child_fd = channel.child_fd(); + // SAFETY: the closure runs in the forked child between `fork` and + // `exec` and performs only async-signal-safe descriptor operations. + // It remaps the gate's control endpoint to a fixed descriptor so a + // concurrent spawn can never inherit a non-`CLOEXEC` copy. + unsafe { + command.pre_exec(move || exec_gate::prepare_gate_child(child_fd)); + } + } - let mut child = command - .spawn() - .map_err(|error| BoundedProcessError::Spawn(spawn_error(&error)))?; + // The fence boundary runs after every fallible request validation and + // cwd/environment setup, immediately before the syscall. A refusal here + // leaves no child and no publication, so the caller may still + // interrupt the token as unpublished. + if let Some(before_spawn) = request.before_spawn.take() { + before_spawn()?; + } + // Cross the exit-sweep fence immediately before the syscall. Once the + // sweep latches `closing`, no new child may be created; a reservation + // that wins this check is waited for by the sweep until it publishes. + let Some(mut spawn_reservation) = spawn_registry::begin_spawn() else { + return Err(BoundedProcessError::ShuttingDown); + }; + let mut child = match command.spawn() { + Ok(child) => child, + Err(error) => { + // Release the in-flight slot before returning: a waiting + // sweep must not time out on a spawn that never happened. + drop(spawn_reservation); + return Err(BoundedProcessError::Spawn(spawn_error(&error))); + } + }; + #[cfg(target_os = "linux")] + if let Some(channel) = gate_channel.as_mut() { + // The parent must not keep the child endpoint open, or the + // exec-success EOF can never be observed after the release. + channel.close_child_end(); + } #[cfg(unix)] drop(confined_cwd_descriptor); drop(confined_cwd); let pid = child.id(); + // Irreversible native boundary: the OS child exists from this point on. + // + // This is the narrowest ownership window: the child exists but the + // registry cannot name it yet. A test parks a worker exactly here to + // prove the exit sweep accounts for a reservation that never records + // its pid. + #[cfg(any(test, feature = "workspace-io-fault"))] + spawn_registry::pause_between_spawn_and_record_for_test(pid); + // The pid becomes visible to the exit sweep here, before `on_spawned` + // and before publication. A worker that is parked or dies between the + // syscall and its publication therefore cannot hide a live child: the + // sweep signals and reaps the recorded root directly, even when this + // thread is gone by the time the process exits. + // + // `false` means the sweep's final drain already abandoned this + // reservation; it terminated and reaped the pre-exec gate, so no tool + // code can ever run under this spawn and no handle may be handed out. + // The existing refusal flow still runs: the OS effect is recorded and + // `publish` observes the tombstone. + let recorded = spawn_reservation.record_spawned(pid); #[cfg(target_os = "linux")] - let pidfd = match linux_pidfd::PidFd::open(pid) { - Ok(pidfd) => Some(pidfd), - Err(error) => { - abort_spawned_child(child, pid); - return Err(BoundedProcessError::Spawn(spawn_error(&error))); + if recorded { + if let Some(mut channel) = gate_channel.take() { + // Test-only: park at the registration-to-release seam, where + // the exit sweep can drain and reap the exact reservation + // before the release write. + #[cfg(any(test, feature = "workspace-io-fault"))] + spawn_registry::pause_between_record_and_release_for_test(pid); + // Release the gate only after the registry names its pid. The + // confirmation distinguishes a real `exec` (EOF), a typed exec + // failure, a release that was never delivered, and an + // ambiguous post-release result. + match channel.release_and_confirm(pid) { + Ok(()) => {} + Err(failure) => { + // The release may have reached the tool only when the + // confirmation is ambiguous. A typed exec errno or a + // failed write proves that no tool code ran and must + // stay a spawn error even when the sweep owns the + // exact reservation. + let keep_effect = failure.may_have_reached_tool(); + let cleanup = spawn_reservation.clean_up_failed_release( + pid, + child, + Instant::now() + CLEANUP_GRACE, + ); + if keep_effect { + // The tool may have executed. Preserve the + // ledger's real-effect record even though this + // call fails. + if let Some(on_spawned) = request.on_spawned.take() { + on_spawned(pid); + } + } + #[cfg(any(test, feature = "workspace-io-fault"))] + note_gate_release_failure_for_test(pid, &failure, cleanup, keep_effect); + return Err(gate_release_failure_error(&failure, cleanup)); + } + } } + } else { + // The abandoned gate was killed and reaped by `record_spawned`. + // Dropping the channel must never release it. + drop(gate_channel.take()); + } + // Record the real effect before any branch that can return. The OS + // child existed, so a setup failure, a refused publication or an exit + // sweep that already abandoned this reservation must all leave the + // spawn recorded instead of reporting a call that never had an effect. + // In the gated abandoned case the effect names the killed pre-exec + // gate, which never ran tool code. + if let Some(on_spawned) = request.on_spawned.take() { + on_spawned(pid); + } + #[cfg(any(test, feature = "workspace-io-fault"))] + spawn_registry::pause_between_spawn_and_publish_for_test(pid); + // `None` means the exit sweep already abandoned this reservation: the + // child was signalled and reaped by the sweep's final drain (or by this + // publisher when its record landed after that drain), so this spawn + // must refuse instead of handing out a dead handle. + let Some(spawn_registration) = spawn_reservation.publish(pid) else { + return Err(BoundedProcessError::ShuttingDown); }; + + let logs = Arc::new(Mutex::new(LogStore::new( + request.stdout_limit, + request.stderr_limit, + request.total_limit, + ))); + let cancellation = request.cancellation_token.unwrap_or_default(); + let drain_stop = Arc::new(AtomicBool::new(false)); + // One absolute teardown instant is shared with the stdin writer, so a + // cutoff installed while its close wait is parked shortens that wait + // instead of letting the captured ordinary grace run out. + let final_cutoff: Arc>> = Arc::new(Mutex::new(None)); + let mut stdin_state: Option> = None; + let mut drainers: Vec = Vec::with_capacity(2); + let retain_sink = request.retain_on_setup_failure.clone(); + let stall_tree_cleanup = request.stall_tree_cleanup; + #[cfg(target_os = "linux")] + let mut acquired_pidfd: Option = None; + + // Every failure below retains the real OS child (and any drainer that + // already exists) through the caller's ownership sink. The child is + // never forgotten: only an independently proven reap and worker exit + // may release it. + macro_rules! setup_failure { + ($error:expr) => {{ + if let Some(sink) = &retain_sink { + let inner = ProcessInner { + handle: allocate_process_handle(), + pid, + spawn_registration: Some(spawn_registration), + #[cfg(windows)] + job: None, + #[cfg(target_os = "linux")] + pidfd: Mutex::new(acquired_pidfd.take()), + deadline, + child: Mutex::new(ChildState { + child: Some(child), + terminal: None, + reaped_before_deadline: false, + reaping: false, + tree_cleanup: TreeCleanup::Pending, + }), + child_wake: Condvar::new(), + logs: Arc::clone(&logs), + stdin: stdin_state.clone(), + drainers: Mutex::new(std::mem::take(&mut drainers)), + drainer_join: Mutex::new(DrainJoinState { + joining: false, + result: None, + }), + drainer_join_wake: Condvar::new(), + drain_stop: Arc::clone(&drain_stop), + cancellation: cancellation.clone(), + final_cutoff: Arc::clone(&final_cutoff), + stall_tree_cleanup, + #[cfg(any(test, feature = "workspace-io-fault"))] + destructor_reap_unproven: AtomicBool::new(false), + drain_join_observer: Mutex::new(None), + #[cfg(test)] + wait_loop_observer: Mutex::new(None), + #[cfg(all(test, unix))] + test_hooks: TreeCleanupTestHooks::default(), + }; + *sink.lock().unwrap_or_else(|error| error.into_inner()) = + Some(BoundedProcessHandle { + process: Arc::new(inner), + }); + } + return Err($error); + }}; + } + + if request.post_spawn_failure { + setup_failure!(BoundedProcessError::Spawn(SpawnError { + kind: SpawnErrorKind::Other, + os_code: None, + })); + } + #[cfg(target_os = "linux")] + match linux_pidfd::PidFd::open(pid) { + Ok(pidfd) => acquired_pidfd = Some(pidfd), + Err(error) => setup_failure!(BoundedProcessError::Spawn(spawn_error(&error))), + } #[cfg(windows)] let job = match ProcessJob::attach_and_resume(&child) { Ok(job) => Some(job), - Err(error) => { - abort_spawned_child(child, pid); - return Err(BoundedProcessError::Spawn(spawn_error(&error))); - } + Err(error) => setup_failure!(BoundedProcessError::Spawn(spawn_error(&error))), }; let stdin = match child.stdin.take() { Some(stdin) => stdin, - None => { - abort_spawned_child(child, pid); - return Err(BoundedProcessError::Spawn(SpawnError { - kind: SpawnErrorKind::Other, - os_code: None, - })); - } + None => setup_failure!(BoundedProcessError::Spawn(SpawnError { + kind: SpawnErrorKind::Other, + os_code: None, + })), }; let stdout = match child.stdout.take() { Some(stdout) => stdout, - None => { - abort_spawned_child(child, pid); - return Err(BoundedProcessError::Spawn(SpawnError { - kind: SpawnErrorKind::Other, - os_code: None, - })); - } + None => setup_failure!(BoundedProcessError::Spawn(SpawnError { + kind: SpawnErrorKind::Other, + os_code: None, + })), }; let stderr = match child.stderr.take() { Some(stderr) => stderr, - None => { - abort_spawned_child(child, pid); - return Err(BoundedProcessError::Spawn(SpawnError { - kind: SpawnErrorKind::Other, - os_code: None, - })); - } + None => setup_failure!(BoundedProcessError::Spawn(SpawnError { + kind: SpawnErrorKind::Other, + os_code: None, + })), }; #[cfg(unix)] if let Err(error) = super::shared::set_pipe_nonblocking(&stdout) { - abort_spawned_child(child, pid); - return Err(BoundedProcessError::Spawn(spawn_error(&error))); + setup_failure!(BoundedProcessError::Spawn(spawn_error(&error))); } #[cfg(unix)] if let Err(error) = super::shared::set_pipe_nonblocking(&stderr) { - abort_spawned_child(child, pid); - return Err(BoundedProcessError::Spawn(spawn_error(&error))); + setup_failure!(BoundedProcessError::Spawn(spawn_error(&error))); } #[cfg(windows)] let stdout = match super::windows_stdio::CancellableRead::from_stdout(stdout) { Ok(stdout) => stdout, - Err(error) => { - abort_spawned_child(child, pid); - return Err(BoundedProcessError::Spawn(spawn_error(&error))); - } + Err(error) => setup_failure!(BoundedProcessError::Spawn(spawn_error(&error))), }; #[cfg(windows)] let stderr = match super::windows_stdio::CancellableRead::from_stderr(stderr) { Ok(stderr) => stderr, - Err(error) => { - abort_spawned_child(child, pid); - return Err(BoundedProcessError::Spawn(spawn_error(&error))); - } + Err(error) => setup_failure!(BoundedProcessError::Spawn(spawn_error(&error))), }; #[cfg(not(any(unix, windows)))] { - abort_spawned_child(child, pid); - return Err(BoundedProcessError::Spawn(SpawnError { + setup_failure!(BoundedProcessError::Spawn(SpawnError { kind: SpawnErrorKind::Other, os_code: None, })); } - let cancellation = request.cancellation_token.unwrap_or_default(); - let drain_stop = Arc::new(AtomicBool::new(false)); - let stdin_state = match StdinState::new( + stdin_state = match StdinState::new( stdin, request.stdin, close_after_initial, cancellation.clone(), deadline, + Arc::clone(&final_cutoff), ) { - Ok(state) => state, - Err(error) => { - abort_spawned_child(child, pid); - return Err(BoundedProcessError::Spawn(spawn_error(&error))); - } + Ok(state) => Some(state), + Err(error) => setup_failure!(BoundedProcessError::Spawn(spawn_error(&error))), }; - let logs = Arc::new(Mutex::new(LogStore::new( - request.stdout_limit, - request.stderr_limit, - request.total_limit, - ))); - let mut drainers = Vec::with_capacity(2); match spawn_drainer( "bounded-process-stdout", stdout, @@ -2380,11 +5429,16 @@ impl BoundedProcess { deadline, ) { Ok(drainer) => drainers.push(drainer), - Err(error) => { - abort_spawned_child(child, pid); - let _ = stdin_state.close(); - return Err(BoundedProcessError::Spawn(spawn_error(&error))); - } + Err(error) => setup_failure!(BoundedProcessError::Spawn(spawn_error(&error))), + } + if request.stderr_drainer_failure { + let (_, remaining) = + join_stream_drainers(drainers, Some(Instant::now() + CLEANUP_GRACE), || None); + drainers = remaining; + setup_failure!(BoundedProcessError::Spawn(SpawnError { + kind: SpawnErrorKind::Other, + os_code: None, + })); } match spawn_drainer( "bounded-process-stderr", @@ -2397,21 +5451,23 @@ impl BoundedProcess { ) { Ok(drainer) => drainers.push(drainer), Err(error) => { - drain_stop.store(true, Ordering::Release); - abort_spawned_child(child, pid); - let _ = stdin_state.close(); - let _ = join_stream_drainers(&mut drainers); - return Err(BoundedProcessError::Spawn(spawn_error(&error))); + // Retain the drainer that already started instead of dropping + // its join handle: the retained handle's cleanup proves it. + let (_, remaining) = + join_stream_drainers(drainers, Some(Instant::now() + CLEANUP_GRACE), || None); + drainers = remaining; + setup_failure!(BoundedProcessError::Spawn(spawn_error(&error))); } } let inner = Arc::new(ProcessInner { handle: allocate_process_handle(), pid, + spawn_registration: Some(spawn_registration), #[cfg(windows)] job, #[cfg(target_os = "linux")] - pidfd, + pidfd: Mutex::new(acquired_pidfd), deadline, child: Mutex::new(ChildState { child: Some(child), @@ -2424,9 +5480,20 @@ impl BoundedProcess { logs, stdin: stdin_state, drainers: Mutex::new(drainers), - drainers_result: OnceLock::new(), + drainer_join: Mutex::new(DrainJoinState { + joining: false, + result: None, + }), + drainer_join_wake: Condvar::new(), drain_stop, cancellation, + final_cutoff, + stall_tree_cleanup, + #[cfg(any(test, feature = "workspace-io-fault"))] + destructor_reap_unproven: AtomicBool::new(false), + drain_join_observer: Mutex::new(None), + #[cfg(test)] + wait_loop_observer: Mutex::new(None), #[cfg(all(test, unix))] test_hooks: TreeCleanupTestHooks::default(), }); @@ -2474,6 +5541,48 @@ impl BoundedProcessHandle { self.process.deadline } + /// Absolute cleanup cutoff stored by a bounded teardown, if any. + pub(crate) fn cleanup_cutoff(&self) -> Option { + self.process.cleanup_cutoff() + } + + /// Installs the table's absolute shutdown cutoff on this retained handle. + pub(crate) fn note_cleanup_cutoff(&self, cutoff: Instant) { + self.process.note_cutoff(cutoff); + } + + /// Installs an observation point for the cutoff this handle's stdin worker + /// actually waits against. + #[doc(hidden)] + pub fn set_stdin_close_observer(&self, observer: StdinCloseObserver) { + if let Some(stdin) = self.process.stdin.as_ref() { + *stdin + .close_observer + .lock() + .unwrap_or_else(|error| error.into_inner()) = Some(observer); + } + } + + /// True while this handle's initial-stdin writer has not completed. + #[doc(hidden)] + pub fn initial_stdin_pending_for_test(&self) -> bool { + self.process + .stdin + .as_ref() + .is_some_and(|stdin| !stdin.done.is_completed()) + } + + /// Test-only: force the destructor's final reap observation to look + /// unproven after a successful group decision, so the retained-ownership + /// branch is exercised deterministically. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn force_destructor_reap_unproven_for_test(&self) { + self.process + .destructor_reap_unproven + .store(true, Ordering::SeqCst); + } + pub fn try_wait(&self) -> Result, BoundedProcessError> { self.process.try_wait() } @@ -2547,17 +5656,43 @@ impl BoundedProcessHandle { { return Err(BoundedProcessError::StdinClosed); } - self.process.stdin.write(bytes) + match &self.process.stdin { + Some(stdin) => stdin.write(bytes), + None => Err(BoundedProcessError::StdinClosed), + } } pub fn close_stdin(&self) -> Result<(), BoundedProcessError> { - self.process.stdin.close() + match &self.process.stdin { + Some(stdin) => stdin.close(), + None => Ok(()), + } + } + + /// Closes stdin under the caller's absolute cleanup cutoff, reusing the + /// earliest cutoff already stored on this handle. + pub(crate) fn close_stdin_within(&self, cutoff: Instant) -> Result<(), BoundedProcessError> { + self.process.note_cutoff(cutoff); + let cutoff = self.process.cleanup_cutoff().unwrap_or(cutoff); + match &self.process.stdin { + Some(stdin) => stdin.close_within(cutoff), + None => Ok(()), + } } pub fn kill_process_tree(&self) -> Result<(), BoundedProcessError> { self.process.kill_process_tree() } + /// Kills the process tree, bounding any wait for another cleaner by the + /// same absolute cutoff used by the caller's cleanup proof. + fn kill_process_tree_within(&self, cutoff: Instant) -> Result<(), BoundedProcessError> { + // A timed-out group decision leaves the tree Pending; the caller's + // bounded proof then reports `Ok(None)` instead of a false clean. + let _ = self.process.cleanup_tree_once(cutoff); + Ok(()) + } + pub fn cancel(&self) { self.process.cancellation.cancel(); let _ = self.process.kill_process_tree(); @@ -2565,7 +5700,13 @@ impl BoundedProcessHandle { pub fn shutdown(&self) -> Result<(), BoundedProcessError> { self.cancel(); - let close_result = self.close_stdin(); + // A teardown that already stored its absolute cutoff owns the stdin + // close as well; the ordinary close would start a fresh 200 ms grace + // beyond that instant. + let close_result = match self.process.cleanup_cutoff() { + Some(cutoff) => self.close_stdin_within(cutoff), + None => self.close_stdin(), + }; let reap_result = self.reap(); match (close_result, reap_result) { (_, Err(error)) => Err(error), @@ -2585,19 +5726,31 @@ impl BoundedProcessHandle { &self, cutoff: Instant, ) -> Result, BoundedProcessError> { - self.kill_process_tree()?; - match self.close_stdin() { + self.process.note_cutoff(cutoff); + // `note_cutoff` keeps the earliest absolute cutoff already stored on + // this handle. Every participant below must use that single stored + // instant, not the later argument that happened to arrive here. + let cutoff = self.process.cleanup_cutoff().unwrap_or(cutoff); + self.kill_process_tree_within(cutoff)?; + match self.close_stdin_within(cutoff) { Ok(()) | Err(BoundedProcessError::StdinClosed) | Err(BoundedProcessError::StdinWriteFailed { .. }) => {} Err(error) => return Err(error), } loop { + // A concurrent teardown can install an earlier absolute cutoff + // after this loop fixed its first value. The inner proof helpers + // observe the stored minimum on every call, so the outer retry + // must re-read it too instead of waiting for a deadline that the + // helper already rejected. + let cutoff = self.process.cleanup_cutoff().unwrap_or(cutoff); // This authorized path really reaps the child its kill produced: // the drain join happens exactly when that terminal status is // observed, and a drain/worker failure is propagated as a failed - // proof instead of being recorded as clean. - if let Some(status) = self.process.cleanup_proof_terminal()? { + // proof instead of being recorded as clean. Every wait uses the + // same absolute cutoff. + if let Some(status) = self.process.cleanup_proof_terminal(cutoff)? { return Ok(Some(status)); } let now = Instant::now(); @@ -2608,6 +5761,17 @@ impl BoundedProcessHandle { } } + /// Test-only: withhold the tree-cleanup proof after the kill so a bounded + /// teardown and the destructor can be measured against the same cutoff. + #[doc(hidden)] + pub fn set_drain_join_observer_for_test(&self, observer: Arc) { + *self + .process + .drain_join_observer + .lock() + .unwrap_or_else(|error| error.into_inner()) = Some(observer); + } + /// Test-only deterministic drain failure bound to this already-owned /// handle. The real drainer thread records the failure when the child /// reaches EOF. @@ -2710,7 +5874,11 @@ where } Err(error) => return Err(BoundedExecError::Spawn(error)), }; - if !process.inner().stdin.has_initial_payload() + if process + .inner() + .stdin + .as_ref() + .is_some_and(|stdin| !stdin.has_initial_payload()) && let Err(error) = process.close_stdin() { return Err(BoundedExecError::Failed(error)); @@ -2759,7 +5927,8 @@ where fn terminate_process_tree(process_id: u32) { #[cfg(all(test, unix))] record_tree_kill_identity(process_id); - super::shared::terminate_process_group(process_id); + #[cfg(unix)] + let _ = signal_owned_group(process_id, None, Instant::now() + CLEANUP_GRACE); } #[cfg(all(test, unix))] @@ -3105,3 +6274,766 @@ mod held_cwd_tests { ); } } + +#[cfg(all(test, target_os = "linux"))] +mod drainer_handoff_tests { + use super::*; + + #[test] + fn pending_ordinary_join_is_taken_over_instead_of_parking_forever() { + let request = BoundedProcessRequest::new(vec![ + "/bin/sh".to_string(), + "-c".to_string(), + "sleep 1; printf handed-off".to_string(), + ]) + .with_cwd(std::env::temp_dir()); + let process = BoundedProcess::spawn(request).expect("spawn"); + let handle = process.lifecycle_handle(); + + // Model an ordinary join owner that has taken the join and will return + // pending without caching a result. + { + let mut state = handle + .process + .drainer_join + .lock() + .unwrap_or_else(|error| error.into_inner()); + state.joining = true; + } + + let (tx, rx) = std::sync::mpsc::channel(); + let waiter = { + let handle = handle.clone(); + std::thread::spawn(move || { + let result = handle.process.join_drainers(); + let _ = tx.send(result.is_err()); + }) + }; + + // Give the waiter time to observe `joining` and block on the wake + // condvar, then finish the owner as pending (clear `joining`, no + // result) and notify exactly as the production join does. + std::thread::sleep(Duration::from_millis(50)); + { + let mut state = handle + .process + .drainer_join + .lock() + .unwrap_or_else(|error| error.into_inner()); + state.joining = false; + handle.process.drainer_join_wake.notify_all(); + } + + let outcome = rx.recv_timeout(Duration::from_secs(3)); + assert!( + outcome.is_ok(), + "the waiter parked forever after the pending handoff" + ); + let _ = waiter.join(); + + handle.kill_process_tree().expect("kill"); + let _ = handle.shutdown(); + } + + #[test] + fn foreground_wait_cancel_reaps_within_the_stored_teardown_cutoff() { + let request = BoundedProcessRequest::new(vec![ + "/bin/sh".to_string(), + "-c".to_string(), + "sleep 5".to_string(), + ]) + .with_cwd(std::env::temp_dir()); + let process = BoundedProcess::spawn(request).expect("spawn"); + let handle = process.lifecycle_handle(); + // A teardown already fixed this one absolute cutoff. A foreground wait + // that observes the cancellation afterwards must reap inside it, not + // start fresh stdin/drainer grace beyond it. + let cutoff = Instant::now() + Duration::from_millis(120); + handle.note_cleanup_cutoff(cutoff); + // This drainer never completes on its own; the ordinary reap would + // burn two fresh 200ms graces on it after the cutoff. + let done = DrainDone::new(); + handle + .process + .drainers + .lock() + .unwrap_or_else(|error| error.into_inner()) + .push(StreamDrainer { + join: None, + done, + closer: Arc::new(|| {}), + }); + handle.process.cancellation.cancel(); + let started = Instant::now(); + let result = handle.wait_forever(); + let elapsed = started.elapsed(); + assert!( + matches!(result, Err(BoundedProcessError::Cancelled)), + "the foreground wait must report its cancellation: {result:?}" + ); + assert!( + elapsed < Duration::from_millis(350), + "foreground cancellation reap escaped the stored cutoff: {elapsed:?}" + ); + let _ = handle.shutdown(); + } + + #[test] + fn tree_cleaner_contention_waits_only_against_the_stored_teardown_cutoff() { + let request = BoundedProcessRequest::new(vec![ + "/bin/sh".to_string(), + "-c".to_string(), + "sleep 5".to_string(), + ]) + .with_cwd(std::env::temp_dir()) + .with_timeout(Duration::from_secs(1)); + let process = BoundedProcess::spawn(request).expect("spawn"); + let handle = process.lifecycle_handle(); + let cutoff = Instant::now() + Duration::from_millis(120); + handle.note_cleanup_cutoff(cutoff); + // Another owner is already inside the tree cleanup and has not + // published its proof yet. The teardown that arrives later must wait + // for it only until its own stored cutoff, not the process deadline. + { + let mut state = handle.process.lock_child(); + state.tree_cleanup = TreeCleanup::Cleaning; + } + handle.process.cancellation.cancel(); + let started = Instant::now(); + let result = handle.poll(); + let elapsed = started.elapsed(); + assert!( + matches!(result, Err(BoundedProcessError::Cancelled)), + "the cancelled poll must still report cancellation: {result:?}" + ); + assert!( + elapsed < Duration::from_millis(500), + "tree-cleaner contention escaped the stored cutoff: {elapsed:?}" + ); + // Release the modelled cleaner and complete the real teardown. + { + let mut state = handle.process.lock_child(); + state.tree_cleanup = TreeCleanup::Pending; + handle.process.child_wake.notify_all(); + } + handle + .process + .cleanup_tree_once(Instant::now() + Duration::from_secs(1)); + let _ = handle + .process + .reap_within(Instant::now() + Duration::from_secs(1)); + } + + #[test] + fn normal_exit_after_teardown_joins_and_reaps_within_the_stored_cutoff() { + let request = BoundedProcessRequest::new(vec![ + "/bin/sh".to_string(), + "-c".to_string(), + "printf ready".to_string(), + ]) + .with_cwd(std::env::temp_dir()) + .with_timeout(Duration::from_secs(5)); + let process = BoundedProcess::spawn(request).expect("spawn"); + let handle = process.lifecycle_handle(); + let cutoff = Instant::now() + Duration::from_millis(120); + handle.note_cleanup_cutoff(cutoff); + // This drainer never completes on its own. The ordinary exit branch + // would join it without any bound after the teardown fixed its cutoff. + let done = DrainDone::new(); + handle + .process + .drainers + .lock() + .unwrap_or_else(|error| error.into_inner()) + .push(StreamDrainer { + join: None, + done: Arc::clone(&done), + closer: Arc::new(|| {}), + }); + let (tx, rx) = std::sync::mpsc::channel(); + let started = Instant::now(); + let waiter = { + let handle = handle.clone(); + std::thread::spawn(move || { + let _ = tx.send(handle.wait_forever()); + }) + }; + let result = rx.recv_timeout(Duration::from_secs(3)); + let elapsed = started.elapsed(); + assert!( + result.is_ok(), + "the normal-exit branch parked beyond the stored teardown cutoff" + ); + assert!( + matches!( + result.expect("waiter result"), + Err(BoundedProcessError::WorkerFailed) + ), + "a drainer that misses the cutoff must be retained as pending" + ); + assert!( + elapsed < Duration::from_millis(500), + "normal-exit reap escaped the stored cutoff: {elapsed:?}" + ); + done.signal(); + waiter.join().expect("waiter"); + let _ = handle.shutdown(); + } + + /// Raises when a test hook entered; the test can install a cutoff after + /// the wait already started. + #[derive(Default)] + struct Signal { + fired: (Mutex, Condvar), + } + + impl Signal { + fn raise(&self) { + *self + .fired + .0 + .lock() + .unwrap_or_else(|error| error.into_inner()) = true; + self.fired.1.notify_all(); + } + + fn wait(&self) { + let mut fired = self + .fired + .0 + .lock() + .unwrap_or_else(|error| error.into_inner()); + let deadline = Instant::now() + Duration::from_secs(10); + while !*fired { + let remaining = deadline.saturating_duration_since(Instant::now()); + assert!(!remaining.is_zero(), "hook was never entered"); + let (guard, _) = self + .fired + .1 + .wait_timeout(fired, remaining) + .unwrap_or_else(|error| error.into_inner()); + fired = guard; + } + } + } + + #[test] + fn late_cutoff_shortens_an_in_progress_harvest_wait() { + let request = BoundedProcessRequest::new(vec![ + "/bin/sh".to_string(), + "-c".to_string(), + "exit 0".to_string(), + ]) + .with_cwd(std::env::temp_dir()) + .with_timeout(Duration::from_secs(5)); + let process = BoundedProcess::spawn(request).expect("spawn"); + let handle = process.lifecycle_handle(); + // Let the root exit, then model another owner still cleaning its tree. + std::thread::sleep(Duration::from_millis(100)); + { + let mut state = handle.process.lock_child(); + state.tree_cleanup = TreeCleanup::Cleaning; + } + let entered = Arc::new(Signal::default()); + *handle + .process + .test_hooks + .on_wait_for_cleanup + .lock() + .unwrap_or_else(|error| error.into_inner()) = Some({ + let entered = Arc::clone(&entered); + Arc::new(move || entered.raise()) + }); + let (tx, rx) = std::sync::mpsc::channel(); + let waiter = { + let handle = handle.clone(); + std::thread::spawn(move || { + let _ = tx.send(handle.try_wait()); + }) + }; + entered.wait(); + // The waiter is already parked in `wait_while_cleaning` against its + // ordinary five-second process deadline. A teardown now installs a much + // shorter absolute cutoff. + let started = Instant::now(); + handle.note_cleanup_cutoff(Instant::now() + Duration::from_millis(50)); + let result = rx.recv_timeout(Duration::from_millis(1_000)); + // Release the modelled cleaner so a regressed waiter can finish. + { + let mut state = handle.process.lock_child(); + state.tree_cleanup = TreeCleanup::Pending; + handle.process.child_wake.notify_all(); + } + let elapsed = started.elapsed(); + assert!( + result.is_ok(), + "the harvest waited on its old deadline instead of the late cutoff" + ); + assert_eq!( + result.expect("harvest result"), + Ok(None), + "an unproven tree cleanup stays pending" + ); + assert!( + elapsed < Duration::from_millis(300), + "a late-installed cutoff must shorten an in-progress harvest: {elapsed:?}" + ); + waiter.join().expect("waiter"); + handle + .process + .cleanup_tree_once(Instant::now() + Duration::from_secs(1)); + let _ = handle + .process + .reap_within(Instant::now() + Duration::from_secs(1)); + } + + #[test] + fn late_cutoff_shortens_an_in_progress_ordinary_join() { + let request = BoundedProcessRequest::new(vec![ + "/bin/sh".to_string(), + "-c".to_string(), + "exit 0".to_string(), + ]) + .with_cwd(std::env::temp_dir()) + .with_timeout(Duration::from_secs(5)); + let process = BoundedProcess::spawn(request).expect("spawn"); + let handle = process.lifecycle_handle(); + // This drainer never completes; the ordinary exit path joins it with + // a fresh 200 ms grace. + let done = DrainDone::new(); + handle + .process + .drainers + .lock() + .unwrap_or_else(|error| error.into_inner()) + .push(StreamDrainer { + join: None, + done: Arc::clone(&done), + closer: Arc::new(|| {}), + }); + let entered = Arc::new(Signal::default()); + let hook_entered = Arc::clone(&entered); + *handle + .process + .drain_join_observer + .lock() + .unwrap_or_else(|error| error.into_inner()) = + Some(Arc::new(move || hook_entered.raise())); + let (tx, rx) = std::sync::mpsc::channel(); + let waiter = { + let handle = handle.clone(); + std::thread::spawn(move || { + let _ = tx.send(handle.wait_forever()); + }) + }; + entered.wait(); + // The join already computed its ordinary grace. Installing a shorter + // absolute cutoff now must end it at that instant, not after the full + // 200 ms grace. + let started = Instant::now(); + handle.note_cleanup_cutoff(Instant::now() + Duration::from_millis(40)); + let result = rx.recv_timeout(Duration::from_millis(1_000)); + done.signal(); + let elapsed = started.elapsed(); + assert!( + result.is_ok(), + "the ordinary join ignored the late cutoff: {elapsed:?}" + ); + assert!( + matches!( + result.expect("join result"), + Err(BoundedProcessError::WorkerFailed) + ), + "a drainer that misses the late cutoff must stay pending" + ); + assert!( + elapsed < Duration::from_millis(200), + "a late-installed cutoff must shorten an in-progress ordinary join: {elapsed:?}" + ); + waiter.join().expect("waiter"); + let _ = handle.shutdown(); + } + + #[test] + fn shutdown_routes_stdin_close_through_the_stored_cutoff() { + let request = BoundedProcessRequest::new(vec![ + "/bin/sh".to_string(), + "-c".to_string(), + "sleep 30".to_string(), + ]) + .with_cwd(std::env::temp_dir()) + .with_timeout(Duration::from_secs(5)) + // A large payload into a child that never reads it stalls the initial + // stdin writer inside its pipe. + .with_stdin(vec![b'x'; 512 * 1024]); + let process = BoundedProcess::spawn_internal(request, true).expect("spawn"); + let handle = process.lifecycle_handle(); + let deadline = Instant::now() + Duration::from_secs(5); + while handle + .process + .stdin + .as_ref() + .is_some_and(|stdin| stdin.done.is_completed()) + { + assert!(Instant::now() < deadline, "stdin writer never started"); + std::thread::sleep(Duration::from_millis(5)); + } + assert!( + handle.process.stdin.is_some(), + "the fixture must own an initial stdin writer" + ); + // Observe the exact wait deadline the stdin close actually used. + let (tx, rx) = std::sync::mpsc::channel(); + handle.set_stdin_close_observer(Arc::new(move |wait_deadline| { + let _ = tx.send(wait_deadline); + })); + // A teardown already fixed its absolute cutoff. The ordinary close + // would start a fresh 200 ms grace instead of using this instant. + let cutoff = Instant::now() + Duration::from_millis(40); + handle.note_cleanup_cutoff(cutoff); + let result = handle.shutdown(); + let observed = rx + .recv_timeout(Duration::from_secs(5)) + .expect("stdin close observer must fire"); + assert_eq!( + observed, cutoff, + "shutdown must route the stdin close through the stored cutoff" + ); + let _ = result; + } + + #[test] + fn late_cutoff_shortens_an_already_parked_foreground_wait() { + let request = BoundedProcessRequest::new(vec![ + "/bin/sh".to_string(), + "-c".to_string(), + "sleep 30".to_string(), + ]) + .with_cwd(std::env::temp_dir()) + .with_timeout(Duration::from_secs(5)); + let process = BoundedProcess::spawn(request).expect("spawn"); + let handle = process.lifecycle_handle(); + let (entered_tx, entered_rx) = std::sync::mpsc::channel(); + *handle + .process + .wait_loop_observer + .lock() + .unwrap_or_else(|error| error.into_inner()) = Some(Arc::new(move || { + let _ = entered_tx.send(()); + })); + let (tx, rx) = std::sync::mpsc::channel(); + let waiter = { + let handle = handle.clone(); + std::thread::spawn(move || { + let deadline = Instant::now() + Duration::from_secs(5); + let _ = tx.send(handle.wait_until(deadline)); + }) + }; + // The waiter has entered the foreground wait loop: do not install the + // cutoff until that synchronization point fired. + entered_rx + .recv_timeout(Duration::from_secs(5)) + .expect("waiter must enter its wait loop"); + let started = Instant::now(); + handle.note_cleanup_cutoff(Instant::now() + Duration::from_millis(50)); + let result = rx.recv_timeout(Duration::from_millis(500)); + let elapsed = started.elapsed(); + assert!( + result.is_ok(), + "the already-parked foreground wait ignored the late cutoff: {elapsed:?}" + ); + assert!( + matches!( + result.expect("foreground wait result"), + Err(BoundedProcessError::DeadlineElapsed) + ), + "the stored cutoff must end the wait" + ); + assert!( + elapsed < Duration::from_millis(250), + "a late-installed cutoff must shorten an already-parked wait: {elapsed:?}" + ); + waiter.join().expect("foreground waiter"); + let _ = handle.shutdown(); + } + + #[test] + fn outer_cleanup_retry_reobserves_a_shortened_absolute_cutoff() { + let request = BoundedProcessRequest::new(vec![ + "/bin/sh".to_string(), + "-c".to_string(), + "sleep 30".to_string(), + ]) + .with_cwd(std::env::temp_dir()) + .with_timeout(Duration::from_secs(5)) + .with_tree_cleanup_stall_for_test(); + let process = BoundedProcess::spawn(request).expect("spawn"); + let handle = process.lifecycle_handle(); + let outer_cutoff = Instant::now() + Duration::from_millis(1_200); + let shortened = Instant::now() + Duration::from_millis(120); + let installer = { + let handle = handle.clone(); + std::thread::spawn(move || { + // The outer loop has already captured its first cutoff here; + // a concurrent teardown installs the shorter one. + std::thread::sleep(Duration::from_millis(20)); + handle.note_cleanup_cutoff(shortened); + }) + }; + let started = Instant::now(); + let proof = handle + .shutdown_within(outer_cutoff) + .expect("bounded cleanup proof"); + let elapsed = started.elapsed(); + installer.join().expect("cutoff installer"); + assert!(proof.is_none(), "the child is still alive at the cutoff"); + assert!( + elapsed < Duration::from_millis(600), + "the outer retry kept waiting for its first cutoff after the inner proof observed the shorter one: {elapsed:?}" + ); + let _ = handle.shutdown(); + } +} + +#[cfg(test)] +mod drainer_join_tests { + use super::*; + use std::sync::atomic::AtomicBool; + + /// The output-drain join is a separate cleanup participant from the stdin + /// writer. It must wait against the one stored teardown cutoff instead of + /// closing a pending drainer on a shorter local floor and reporting + /// `WorkerFailed` before the shared budget expired. + #[test] + fn pending_drainer_joins_against_the_single_stored_cutoff() { + let done = DrainDone::new(); + let closed = Arc::new(AtomicBool::new(false)); + let thread_done = Arc::clone(&done); + let thread_closed = Arc::clone(&closed); + let join = thread::spawn(move || { + while !thread_closed.load(Ordering::Acquire) { + thread::sleep(Duration::from_millis(2)); + } + thread_done.signal(); + }); + let drainer = StreamDrainer { + join: Some(join), + done: Arc::clone(&done), + closer: Arc::new(move || closed.store(true, Ordering::Release)), + }; + let cutoff = Instant::now() + Duration::from_millis(600); + let started = Instant::now(); + let (result, remaining) = join_stream_drainers(vec![drainer], Some(cutoff), || None); + let elapsed = started.elapsed(); + assert!( + elapsed >= Duration::from_millis(550), + "the drain join closed a pending drainer before the stored cutoff: {elapsed:?}" + ); + assert!( + elapsed < Duration::from_millis(1_000), + "the drain join escaped the stored cutoff: {elapsed:?}" + ); + assert!( + matches!(result, Err(BoundedProcessError::WorkerFailed)), + "a drainer that could not finish inside the cutoff must be retained: {result:?}" + ); + assert_eq!( + remaining.len(), + 1, + "the unfinished drainer must stay owned for a later proof" + ); + } +} + +#[cfg(all(test, target_os = "linux"))] +mod gate_release_failure_tests { + use super::*; + use crate::capabilities::vm_io::exec_gate::GateReleaseError; + + use spawn_registry::FailedReleaseCleanup; + + #[test] + fn a_confirmed_exec_errno_is_a_spawn_failure_without_an_effect() { + let failure = GateReleaseError::ExecFailed(std::io::Error::from_raw_os_error(libc::ENOENT)); + assert!(!failure.may_have_reached_tool()); + for cleanup in [ + FailedReleaseCleanup::Reaped, + FailedReleaseCleanup::Retained, + FailedReleaseCleanup::Transferred, + ] { + let error = gate_release_failure_error(&failure, cleanup); + assert!( + matches!( + error, + BoundedProcessError::Spawn(SpawnError { + kind: SpawnErrorKind::NotFound, + .. + }) + ), + "a confirmed exec errno must stay a typed spawn failure for {cleanup:?}: {error:?}" + ); + } + } + + #[test] + fn a_failed_release_write_is_a_spawn_failure_without_an_effect() { + let failure = + GateReleaseError::NotReleased(std::io::Error::from(std::io::ErrorKind::BrokenPipe)); + assert!(!failure.may_have_reached_tool()); + for cleanup in [ + FailedReleaseCleanup::Reaped, + FailedReleaseCleanup::Retained, + FailedReleaseCleanup::Transferred, + ] { + let error = gate_release_failure_error(&failure, cleanup); + assert!( + matches!(error, BoundedProcessError::Spawn(_)), + "a release that was never delivered must not become a shutdown error: {error:?}" + ); + } + } + + #[test] + fn an_ambiguous_release_keeps_its_effect_and_the_swept_result_stays_closing() { + let failure = + GateReleaseError::Ambiguous(std::io::Error::from(std::io::ErrorKind::InvalidData)); + assert!(failure.may_have_reached_tool()); + let transferred = gate_release_failure_error(&failure, FailedReleaseCleanup::Transferred); + assert!( + matches!(transferred, BoundedProcessError::ShuttingDown), + "an ambiguous result transferred to the sweep keeps the existing closing result: {transferred:?}" + ); + for cleanup in [FailedReleaseCleanup::Reaped, FailedReleaseCleanup::Retained] { + let error = gate_release_failure_error(&failure, cleanup); + assert!( + matches!(error, BoundedProcessError::Spawn(_)), + "an ambiguous result cleaned up by its owner is a spawn failure: {error:?}" + ); + } + } +} + +/// The ordinary cleanup path may only report a tree clean after a real +/// ownership decision. +/// +/// An inconclusive `waitid(WNOWAIT)` (the shape an interrupted syscall +/// produces) proves nothing about the root, so the numeric group signal must +/// be skipped. The attempt must keep the tree `Pending` and the leader +/// unreaped/owned, and a later bounded attempt with a real observation must +/// terminate the owned tree, descendants included. +#[cfg(all(test, unix))] +mod group_decision_tests { + use super::*; + + fn wait_for_pid_file(path: &std::path::Path) -> u32 { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + if let Ok(text) = std::fs::read_to_string(path) + && let Ok(pid) = text.trim().parse::() + { + return pid; + } + assert!( + Instant::now() < deadline, + "pid file never appeared: {}", + path.display() + ); + thread::sleep(Duration::from_millis(5)); + } + } + + fn process_exists(pid: u32) -> bool { + unsafe { libc::kill(pid as libc::pid_t, 0) == 0 } + } + + fn wait_gone(pid: u32, what: &str) { + let deadline = Instant::now() + Duration::from_secs(5); + while process_exists(pid) { + assert!( + Instant::now() < deadline, + "{what} must be terminated by the bounded retry: pid={pid}" + ); + thread::sleep(Duration::from_millis(10)); + } + } + + #[test] + fn inconclusive_group_observation_keeps_the_tree_pending_until_a_bounded_retry() { + let base = std::env::temp_dir().join(format!( + "bounded-inconclusive-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("clock after epoch") + .as_nanos() + )); + std::fs::create_dir_all(&base).expect("inconclusive base"); + // The root leads its own process group; the shell keeps a live + // descendant in that same group. + let request = BoundedProcessRequest::new(vec![ + "/bin/sh".to_string(), + "-c".to_string(), + "sleep 300 & printf '%s' $! > desc.pid; printf '%s' $$ > root.pid; wait".to_string(), + ]) + .with_cwd(base.clone()); + let process = BoundedProcess::spawn(request).expect("spawn owned fixture"); + let handle = process.lifecycle_handle(); + let root = wait_for_pid_file(&base.join("root.pid")); + let descendant = wait_for_pid_file(&base.join("desc.pid")); + assert!( + process_exists(root) && process_exists(descendant), + "the owned fixture must be alive before the attempt: root={root} descendant={descendant}" + ); + + // Exactly one observation of this exact root is forced to prove + // nothing. No other process can consume it. + force_inconclusive_group_observation_once_for_test(root); + let first = handle + .process + .cleanup_tree_once(Instant::now() + Duration::from_secs(1)); + assert_eq!( + first, + TreeCleanupOutcome::DecisionInconclusive, + "an inconclusive observation must not report a cleaned tree" + ); + { + let state = handle.process.lock_child(); + assert_eq!( + state.tree_cleanup, + TreeCleanup::Pending, + "the tree must stay pending for a bounded retry" + ); + assert!( + state.child.is_some(), + "the leader must stay unreaped and owned after an inconclusive observation" + ); + } + assert!( + process_exists(root), + "the leader must not be released after an inconclusive observation: pid={root}" + ); + assert!( + process_exists(descendant), + "the descendant must stay owned by a pending tree: pid={descendant}" + ); + + // The bounded retry now observes the real (unreaped) root, signals + // the numeric group and only then reports the tree clean. + let second = handle + .process + .cleanup_tree_once(Instant::now() + Duration::from_secs(2)); + assert_eq!( + second, + TreeCleanupOutcome::Cleaned, + "a real observation on the bounded retry must decide the tree" + ); + let _ = handle + .process + .reap_within(Instant::now() + Duration::from_secs(2)); + wait_gone(descendant, "the owned descendant"); + wait_gone(root, "the owned leader"); + + let _ = handle.shutdown(); + let _ = std::fs::remove_dir_all(&base); + } +} diff --git a/src/capabilities/vm_io/confined_fs.rs b/src/capabilities/vm_io/confined_fs.rs index 9406d2be..ed03c458 100644 --- a/src/capabilities/vm_io/confined_fs.rs +++ b/src/capabilities/vm_io/confined_fs.rs @@ -288,6 +288,16 @@ pub enum ConfinedPublicationState { /// Observed staging identity, if the entry could be read. staging: Option, }, + /// A successful exchange was followed by a proven reverse exchange that + /// restored the destination directory. The net effect is unpublished, but + /// the irreversible exchange did happen and is reported explicitly rather + /// than as a pre-publication failure. + RestoredAfterExchange { + /// Observed restored destination (the displaced directory). + destination: Option, + /// Observed staging entry before its owned link was removed. + staging: Option, + }, } impl ConfinedPublicationState { @@ -379,6 +389,16 @@ impl ConfinedFsError { ) } + /// Sentinel for a capability-owned publication boundary that refused the + /// effect. The capability replaces it with its precise typed refusal. + pub(crate) fn publication_refused() -> Self { + Self::new( + ConfinedFsErrorKind::RaceDetected, + "fs::write_file", + "publication boundary refused", + ) + } + #[cfg_attr(not(target_os = "linux"), allow(dead_code))] fn with_publication(mut self, publication: ConfinedPublicationState) -> Self { self.publication = publication; @@ -714,7 +734,6 @@ impl ConfinedDirectory { } /// A securely created temporary file and its retained parent directory. -#[derive(Debug)] pub struct ConfinedTempFile { #[cfg(unix)] parent: OwnedFd, @@ -732,6 +751,11 @@ pub struct ConfinedTempFile { written: usize, #[cfg(unix)] completed: bool, + /// Publication boundary callback, run after every fallible pre-publication + /// check and immediately before the destination entry is created. The + /// write helpers install the capability's per-call fence here so that a + /// refusal cannot leave a published effect behind. + before_publish: Option Result<(), ConfinedFsError> + Send>>, } impl ConfinedTempFile { @@ -1373,6 +1397,25 @@ impl ConfinedFsRoot { &self, path: &str, data: &[u8], + ) -> Result { + self.write_file_with_hooks(path, data, None, None) + } + + /// Writes a regular file with a staging observation point and a publication + /// boundary callback. + /// + /// `during_staging` runs once the temporary content is written and flushed + /// but before it is synchronized or published. `before_publish` runs after + /// every fallible pre-publication check and immediately before the + /// destination entry is created; returning an error leaves the workspace + /// unchanged and removes the temporary. Production callers use + /// [`Self::write_file`] and install no hooks. + pub fn write_file_with_hooks( + &self, + path: &str, + data: &[u8], + during_staging: Option>, + before_publish: Option Result<(), ConfinedFsError> + Send>>, ) -> Result { let path = validate_relative_path(path, "fs::write_file")?; let parent = &path.components[..path.components.len() - 1]; @@ -1380,7 +1423,11 @@ impl ConfinedFsRoot { let mut temp = self.create_temp_in_components(parent, ".rustscript-tmp")?; temp.write_all(data)?; temp.flush()?; + if let Some(mut during_staging) = during_staging { + during_staging(); + } temp.sync_all()?; + temp.before_publish = before_publish; self.atomic_replace(temp, destination) } } @@ -2197,6 +2244,7 @@ mod unix { max_write_bytes, written: 0, completed: false, + before_publish: None, }) } @@ -2320,6 +2368,14 @@ mod unix { }, }; + // The per-call publication fence is entered here: every fallible + // pre-publication check is done, and the following staging link plus + // `renameat2` are the irreversible publication itself. A refusal runs + // before any destination or staging entry exists. + if let Some(before_publish) = temp.before_publish.as_mut() { + before_publish()?; + } + let staging_name = link_temp_inode(temp, current_identity)?; let staging_bytes = staging_name.as_bytes(); let source_identity_after_link = @@ -2383,10 +2439,36 @@ mod unix { destination.as_bytes(), ); - let destination_entry = observe_entry(temp.parent.as_raw_fd(), destination.as_bytes()) - .map_err(|error| ConfinedFsError::os("fs::replace", &error))?; - let staging_entry = observe_entry(temp.parent.as_raw_fd(), staging_bytes) - .map_err(|error| ConfinedFsError::os("fs::replace", &error))?; + // From this point on the destination name may already contain the new + // inode. `temp.completed` prevents the temporary guard from treating + // the published file as an unfinished staging artifact, and every error + // is classified as Published/Indeterminate: a plain `NotPublished` + // failure here would make the caller drop its permit and roll back a + // destination that really changed. + temp.completed = true; + let destination_entry = match observe_entry(temp.parent.as_raw_fd(), destination.as_bytes()) + { + Ok(entry) => entry, + Err(error) => { + return Err(ConfinedFsError::os("fs::replace", &error).with_publication( + ConfinedPublicationState::Indeterminate { + destination: None, + staging: None, + }, + )); + } + }; + let staging_entry = match observe_entry(temp.parent.as_raw_fd(), staging_bytes) { + Ok(entry) => entry, + Err(error) => { + return Err(ConfinedFsError::os("fs::replace", &error).with_publication( + ConfinedPublicationState::Indeterminate { + destination: destination_entry.as_ref().map(observed_identity), + staging: None, + }, + )); + } + }; let dest_is_ours = destination_entry .as_ref() .is_some_and(|entry| entry.identity == current_identity && entry.metadata.is_file()); @@ -2402,7 +2484,11 @@ mod unix { ConfinedFsErrorKind::RaceDetected, "fs::replace", "replacement destination does not contain the retained inode", - )); + ) + .with_publication(ConfinedPublicationState::Indeterminate { + destination: destination_entry.as_ref().map(observed_identity), + staging: staging_entry.as_ref().map(observed_identity), + })); } let staging_cleaned = match publish_mode { @@ -2436,7 +2522,10 @@ mod unix { current_identity, staging.identity, ) { - ReverseDirectoryOutcome::DirectoryRestored => { + ReverseDirectoryOutcome::DirectoryRestored { + destination: observed_destination, + staging: observed_staging, + } => { let _ = unlink_exact( temp.parent.as_raw_fd(), staging_bytes, @@ -2447,6 +2536,12 @@ mod unix { ConfinedFsErrorKind::RaceDetected, "fs::replace", "replacement destination changed to a directory during publication", + ) + .with_publication( + ConfinedPublicationState::RestoredAfterExchange { + destination: observed_destination, + staging: observed_staging, + }, )); } ReverseDirectoryOutcome::DestinationPublished => false, @@ -2484,6 +2579,24 @@ mod unix { #[cfg(target_os = "linux")] fn observe_entry(parent_fd: RawFd, name: &[u8]) -> Result, io::Error> { + #[cfg(test)] + { + let index = POST_RENAME_OBSERVE_INDEX.with(|counter| { + let index = counter.get(); + counter.set(index.saturating_add(1)); + index + }); + let target = FAIL_POST_RENAME_OBSERVE_AT.with(|target| target.replace(None)); + if target == Some(index) { + // Deterministic seam for the post-rename readback failure: the + // rename already succeeded, so the caller must classify the + // effect as published/indeterminate rather than roll it back. + POST_RENAME_OBSERVE_INDEX.with(|counter| counter.set(0)); + return Err(io::Error::from_raw_os_error(libc::EIO)); + } else { + FAIL_POST_RENAME_OBSERVE_AT.with(|slot| slot.set(target)); + } + } match metadata_at(parent_fd, name) { Err(error) if error.raw_os_error() == Some(libc::ENOENT) => Ok(None), Err(error) => Err(error), @@ -2494,10 +2607,36 @@ mod unix { } } + #[cfg(all(test, target_os = "linux"))] + thread_local! { + /// 0-based index of the post-rename observation that must fail. + static FAIL_POST_RENAME_OBSERVE_AT: Cell> = const { Cell::new(None) }; + static POST_RENAME_OBSERVE_INDEX: Cell = const { Cell::new(0) }; + } + + /// Test-only: fail exactly the next post-rename destination/staging + /// observation with `EIO`. + #[cfg(all(test, target_os = "linux"))] + pub(super) fn fail_next_post_rename_observe() { + fail_post_rename_observe_at(0); + } + + /// Test-only: fail the 0-based `index`-th post-rename observation with + /// `EIO`. Index 0 is the destination readback; index 1 is the staging + /// readback that must retain the already observed destination identity. + #[cfg(all(test, target_os = "linux"))] + pub(super) fn fail_post_rename_observe_at(index: usize) { + POST_RENAME_OBSERVE_INDEX.with(|counter| counter.set(0)); + FAIL_POST_RENAME_OBSERVE_AT.with(|slot| slot.set(Some(index))); + } + #[cfg(target_os = "linux")] enum ReverseDirectoryOutcome { DestinationPublished, - DirectoryRestored, + DirectoryRestored { + destination: Option, + staging: Option, + }, Indeterminate { destination: Option, staging: Option, @@ -2560,7 +2699,10 @@ mod unix { .as_ref() .is_some_and(|entry| entry.identity == displaced_directory && entry.metadata.is_dir()) { - ReverseDirectoryOutcome::DirectoryRestored + ReverseDirectoryOutcome::DirectoryRestored { + destination: destination_entry.as_ref().map(observed_identity), + staging: staging_entry.as_ref().map(observed_identity), + } } else { ReverseDirectoryOutcome::Indeterminate { destination: destination_entry.as_ref().map(observed_identity), @@ -3185,3 +3327,328 @@ mod unix { } } } + +#[cfg(all(test, target_os = "linux"))] +pub(crate) fn fail_post_rename_observe_at_for_test(index: usize) { + unix::fail_post_rename_observe_at(index); +} + +#[cfg(all(test, target_os = "linux"))] +mod tests { + use std::fs; + use std::path::PathBuf; + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + + use serde_json::{Value, json}; + + use super::fail_post_rename_observe_at_for_test; + use super::{ + ConfinedFsLimits, ConfinedFsRoot, + unix::{DestinationReplaceHookGuard, PostRenameHookGuard, fail_next_post_rename_observe}, + }; + use crate::capabilities::{ + AllowAllApproval, CallCancellationSource, CallCancellationState, CancellationFlag, + CapabilityLifecycle, CapabilityOwner, CapabilityRisk, DurableStarted, DurableToolLifecycle, + FilesystemCapability, FilesystemLimits, LifecycleClock, LifecycleError, LifecycleLimits, + NeverCancelled, PrepareMetadata, PrepareOutcome, SystemClock, TokenIssuer, UuidIssuer, + }; + + static NEXT_FIXTURE: AtomicU64 = AtomicU64::new(0); + + fn fixture_root(label: &str) -> PathBuf { + let path = std::env::temp_dir().join(format!( + "confined-post-rename-{label}-{}-{}", + std::process::id(), + NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&path).expect("fixture root"); + path + } + + #[test] + fn post_rename_readback_failure_is_classified_indeterminate() { + let root = fixture_root("readback"); + let confined = + ConfinedFsRoot::with_limits(&root, ConfinedFsLimits::default()).expect("confined root"); + fail_next_post_rename_observe(); + let error = confined + .write_file_with_hooks("out.txt", b"new-content\n", None, None) + .expect_err("the injected readback failure must surface"); + assert_ne!( + error.publication_state(), + super::ConfinedPublicationState::NotPublished, + "a failure after the rename must never be reported as unpublished: {error:?}" + ); + assert_eq!( + fs::read_to_string(root.join("out.txt")).expect("published destination"), + "new-content\n" + ); + let _ = fs::remove_dir_all(&root); + } + + fn unlink_destination(parent: libc::c_int, _staging: &[u8], destination: &[u8]) { + let Ok(name) = std::ffi::CString::new(destination.to_vec()) else { + return; + }; + // SAFETY: parent is the retained directory fd and name is a valid + // NUL-terminated single component. + let _ = unsafe { libc::unlinkat(parent, name.as_ptr(), 0) }; + } + + #[test] + fn staging_readback_failure_retains_the_observed_destination_identity() { + let root = fixture_root("staging-readback"); + let confined = + ConfinedFsRoot::with_limits(&root, ConfinedFsLimits::default()).expect("confined root"); + fail_post_rename_observe_at_for_test(1); + let error = confined + .write_file_with_hooks("out.txt", b"new-content\n", None, None) + .expect_err("the injected staging readback failure must surface"); + match error.publication_state() { + super::ConfinedPublicationState::Indeterminate { + destination: Some(destination), + staging: None, + } => { + assert_eq!(destination.file_type(), super::ConfinedFileType::File); + assert!(destination.inode() > 0); + } + state => panic!("expected retained destination identity, got {state:?}"), + } + assert_eq!( + fs::read_to_string(root.join("out.txt")).expect("published destination"), + "new-content\n" + ); + let _ = fs::remove_dir_all(&root); + } + + fn replace_destination_with_directory(parent: libc::c_int, destination: &[u8]) { + let Ok(name) = std::ffi::CString::new(destination.to_vec()) else { + return; + }; + // SAFETY: parent is a retained directory fd and name is a valid + // NUL-terminated single component. + let _ = unsafe { libc::unlinkat(parent, name.as_ptr(), 0) }; + let _ = unsafe { libc::mkdirat(parent, name.as_ptr(), 0o755) }; + } + + #[test] + fn proven_directory_restoration_is_an_explicit_restored_outcome() { + let root = fixture_root("restored"); + fs::write(root.join("out.txt"), b"old-content\n").expect("destination file"); + let confined = + ConfinedFsRoot::with_limits(&root, ConfinedFsLimits::default()).expect("confined root"); + let _hook = DestinationReplaceHookGuard::new(replace_destination_with_directory); + let error = confined + .write_file_with_hooks("out.txt", b"new-content\n", None, None) + .expect_err("the directory exchange race must surface"); + match error.publication_state() { + super::ConfinedPublicationState::RestoredAfterExchange { + destination: Some(destination), + staging: Some(staging), + } => { + assert_eq!(destination.file_type(), super::ConfinedFileType::Directory); + assert_eq!(staging.file_type(), super::ConfinedFileType::File); + } + state => panic!("expected an explicit restored exchange outcome, got {state:?}"), + } + assert!( + root.join("out.txt").is_dir(), + "the original destination directory must be restored" + ); + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn post_rename_destination_race_is_classified_indeterminate() { + let root = fixture_root("race"); + let confined = + ConfinedFsRoot::with_limits(&root, ConfinedFsLimits::default()).expect("confined root"); + let _hook = PostRenameHookGuard::new(unlink_destination); + let error = confined + .write_file_with_hooks("out.txt", b"new-content\n", None, None) + .expect_err("the removed destination must be classified"); + assert!( + matches!( + error.publication_state(), + super::ConfinedPublicationState::Indeterminate { .. } + ), + "an observed post-rename race must be indeterminate, not unpublished: {error:?}" + ); + } + + struct ManualCall(Arc); + + impl CallCancellationSource for ManualCall { + fn call_state(&self, _call_id: &str) -> CallCancellationState { + if self.0.load(Ordering::SeqCst) { + CallCancellationState::Cancelled + } else { + CallCancellationState::Active + } + } + } + + #[derive(Default)] + struct MemoryDurable; + + impl DurableToolLifecycle for MemoryDurable { + fn assert_active_run(&self, _run_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } + + fn prepare_parent( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result<(), LifecycleError> { + Ok(()) + } + + fn replay_result( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result, LifecycleError> { + Ok(None) + } + + fn commit_started(&self, _record: &DurableStarted) -> Result<(), LifecycleError> { + Ok(()) + } + + fn commit_result(&self, _call_id: &str, result: &Value) -> Result { + Ok(result.clone()) + } + + fn interrupt(&self, _call_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } + } + + fn lifecycle( + root: &std::path::Path, + cancel: Arc, + ) -> (CapabilityLifecycle, CapabilityOwner) { + let owner = CapabilityOwner::new("confined-fs-test", "session", "run").expect("owner"); + let lifecycle = CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry") + .workspace(root) + .limits(LifecycleLimits { + max_tool_calls: 8, + max_output_bytes: 8192, + max_summary_bytes: 256, + }) + .deadline_ms(SystemClock.now_ms().saturating_add(60_000)) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(Arc::new(MemoryDurable) as Arc) + .approval(Arc::new(AllowAllApproval) as Arc) + .cancellation(Arc::new(NeverCancelled) as Arc) + .call_cancellation(Arc::new(ManualCall(cancel)) as Arc) + .build() + .expect("lifecycle"); + (lifecycle, owner) + } + + fn prepare(lifecycle: &CapabilityLifecycle, owner: &CapabilityOwner, call_id: &str) -> String { + match lifecycle + .prepare( + owner, + PrepareMetadata { + run_id: owner.run().to_string(), + call_id: call_id.to_string(), + tool_name: "write_file".to_string(), + argument_digest: "digest".to_string(), + registry_identity: "registry".to_string(), + risk_class: CapabilityRisk::Write, + summary: "write".to_string(), + }, + ) + .expect("prepare") + { + PrepareOutcome::Execute { + execution_token, .. + } => execution_token, + other => panic!("expected execute, got {other:?}"), + } + } + + #[test] + fn indeterminate_write_keeps_the_permit_published_for_settlement() { + let root = fixture_root("settle"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle(&root, Arc::clone(&cancel)); + let filesystem = FilesystemCapability::new( + lifecycle.clone(), + owner.clone(), + FilesystemLimits::default(), + ) + .expect("filesystem"); + let token = prepare(&lifecycle, &owner, "indeterminate-write"); + fail_next_post_rename_observe(); + let error = filesystem + .write_atomic(&token, "out.txt", "*", b"new-content\n") + .expect_err("the injected readback failure must surface"); + assert_eq!(error.code(), "publication_indeterminate", "{error:?}"); + assert!(lifecycle.request_call_cancellation("indeterminate-write")); + let receipt = json!({ + "ok": false, + "content": "", + "data": {"publication": "indeterminate"}, + "error": {"code": "publication_indeterminate", "message": "unknown"}, + "truncated": false, + "artifacts": [] + }); + let settlement = lifecycle + .settle_call_with_receipt("indeterminate-write", Some(&receipt)) + .expect("settle"); + assert_eq!( + settlement.interrupted, 0, + "an indeterminate post-rename effect must never be interrupted as unpublished" + ); + assert_eq!(settlement.committed, 1); + assert_eq!( + fs::read_to_string(root.join("out.txt")).expect("published destination"), + "new-content\n" + ); + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn cancellation_immediately_before_the_rename_loses_to_the_fence() { + let root = fixture_root("before-rename"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle(&root, Arc::clone(&cancel)); + let filesystem = FilesystemCapability::new( + lifecycle.clone(), + owner.clone(), + FilesystemLimits::default(), + ) + .expect("filesystem"); + let token = prepare(&lifecycle, &owner, "before-rename"); + // The hook runs inside the already-entered fence, immediately before + // the rename. A cancellation requested at that exact point can no + // longer refuse the irreversible effect. + filesystem.inject_before_publish({ + let cancel = Arc::clone(&cancel); + Arc::new(move || cancel.store(true, Ordering::SeqCst)) + }); + let write = filesystem + .write_atomic(&token, "out.txt", "*", b"new-content\n") + .expect("an already-entered publication must still rename"); + assert_eq!(write.len, "new-content\n".len()); + assert!( + cancel.load(Ordering::SeqCst), + "the hook must have requested the cancellation at the rename boundary" + ); + assert_eq!( + fs::read_to_string(root.join("out.txt")).expect("published destination"), + "new-content\n" + ); + let _ = fs::remove_dir_all(&root); + } +} diff --git a/src/capabilities/vm_io/exec_gate.rs b/src/capabilities/vm_io/exec_gate.rs new file mode 100644 index 00000000..8a5c08c6 --- /dev/null +++ b/src/capabilities/vm_io/exec_gate.rs @@ -0,0 +1,414 @@ +//! Linux-only pre-execution gate for the packaged MCP stdio tool path. +//! +//! The packaged `tools serve` path ends with `std::process::exit`, which cannot +//! join a worker parked between the successful OS spawn and the exit sweep's +//! pid record. This module closes that window without blocking +//! [`std::process::Command::spawn`]: the direct child is a small gate that +//! blocks on a parent-bound control socket before it executes any tool code. +//! +//! The parent records the gate's pid in the spawn registry and only then +//! writes the release byte. The gate replaces itself with the exact tool argv +//! (`exec` in place), so the recorded pid, pidfd, process group, cwd, closed +//! environment and stdio all stay valid. If the parent disappears before the +//! release, the socket reaches EOF and the gate exits without executing +//! anything: no unregistered process can have user-code descendants. +//! +//! Descriptor discipline: the control socket is created `CLOEXEC`. The child +//! end survives only as descriptor 3, remapped inside `pre_exec` so concurrent +//! spawns in the multithreaded parent never inherit a non-`CLOEXEC` copy. The +//! parent endpoint stays `CLOEXEC` and is closed with the channel. +//! +//! Exec failure semantics are preserved: the gate marks its control descriptor +//! `CLOEXEC` immediately before `exec`, so the parent reads EOF when the tool +//! really executed and a bounded errno payload when it did not. + +use std::ffi::{OsStr, OsString}; +use std::io; +use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd}; +use std::os::unix::process::CommandExt; + +/// Internal argv marker that switches the packaged binary into gate mode. +/// +/// It is parsed before the public CLI, so it never appears in help or in the +/// admitted invocation set. +pub const EXEC_GATE_ARG: &str = "--rustscript-agent-exec-gate-v1"; + +/// The only value that releases the gate. +const GATE_RELEASE_BYTE: u8 = b'G'; +/// Exit code used when the gate is denied (EOF, short read, no parent). +const GATE_DENIED_EXIT: i32 = 126; +/// Exit code used after a real exec failure was reported. +const GATE_EXEC_FAILED_EXIT: i32 = 127; + +/// One parent-bound control channel for a gated spawn. +pub struct GateChannel { + /// The parent's endpoint: it writes the release byte and reads the exec + /// result. + parent: OwnedFd, + /// The child's endpoint until `close_child_end` runs after the spawn. The + /// parent must not keep this open, or the exec-success EOF can never be + /// observed. + child: Option, +} + +/// Why a released gate did not confirm a successful exec. +/// +/// The distinction is part of the effect contract: a confirmed errno or a +/// release that was never delivered proves that no tool code ran, while an +/// ambiguous confirmation must conservatively assume that `exec` may have +/// reached the tool. +#[derive(Debug)] +pub enum GateReleaseError { + /// The release byte could not be written. The gate never received it, so + /// no tool code can have run. + NotReleased(io::Error), + /// The gate reported the exact errno from a failed `exec`. + ExecFailed(io::Error), + /// The release byte was written but the confirmation was neither a clean + /// exec EOF nor a complete errno payload. + Ambiguous(io::Error), +} + +impl GateReleaseError { + /// The underlying transport or exec error. + pub fn io(&self) -> &io::Error { + match self { + Self::NotReleased(error) | Self::ExecFailed(error) | Self::Ambiguous(error) => error, + } + } + + /// Whether the release may have reached the tool. + /// + /// Only an ambiguous post-release result qualifies. A write failure and a + /// typed exec errno both prove that no tool code executed. + pub fn may_have_reached_tool(&self) -> bool { + matches!(self, Self::Ambiguous(_)) + } +} + +/// Classifies a completed confirmation payload. +/// +/// A zero errno can only be a protocol violation: the gate writes an errno +/// only after a failed `exec`. +fn classify_confirmation( + payload: &[u8; std::mem::size_of::()], + filled: usize, +) -> Result<(), GateReleaseError> { + if filled == 0 { + // Exec succeeded: the gate's `CLOEXEC` descriptor closed. + return Ok(()); + } + if filled < payload.len() { + // A partial payload can never be a real exec error. + return Err(GateReleaseError::Ambiguous(io::Error::from( + io::ErrorKind::InvalidData, + ))); + } + // The native endianness is shared by both ends of this same-host channel. + let errno = i32::from_ne_bytes(*payload); + if errno == 0 { + return Err(GateReleaseError::Ambiguous(io::Error::from( + io::ErrorKind::InvalidData, + ))); + } + Err(GateReleaseError::ExecFailed(io::Error::from_raw_os_error( + errno, + ))) +} + +impl GateChannel { + /// Creates a connected, `CLOEXEC` control channel. + pub fn open() -> io::Result { + let mut fds = [0 as RawFd; 2]; + // SAFETY: `fds` is a valid two-element out-array; `SOCK_CLOEXEC` makes + // both endpoints close-on-exec atomically. + let result = unsafe { + libc::socketpair( + libc::AF_UNIX, + libc::SOCK_STREAM | libc::SOCK_CLOEXEC, + 0, + fds.as_mut_ptr(), + ) + }; + if result != 0 { + return Err(io::Error::last_os_error()); + } + // SAFETY: socketpair returned two fresh owned descriptors. + let parent = unsafe { OwnedFd::from_raw_fd(fds[0]) }; + // SAFETY: same as above for the second descriptor. + let child = unsafe { OwnedFd::from_raw_fd(fds[1]) }; + // Keep both endpoints out of the stdio remapping range: std installs + // piped stdio on 0..=2 before it runs our pre-exec closure. + Ok(Self { + parent: raise_above_stdio(parent)?, + child: Some(raise_above_stdio(child)?), + }) + } + + /// The descriptor number the gate must receive. + pub fn child_fd(&self) -> RawFd { + self.child + .as_ref() + .expect("gate child end is open until after spawn") + .as_raw_fd() + } + + /// Drops the parent's copy of the child endpoint after a successful spawn. + pub fn close_child_end(&mut self) { + self.child.take(); + } + + /// Releases the gate and waits for its exec confirmation. + /// + /// `Ok(())` means the gate reached `exec` (its `CLOEXEC` control + /// descriptor closed). [`GateReleaseError`] preserves the difference + /// between a confirmed exec errno, a release that was never delivered, and + /// an ambiguous post-release result; the caller decides how to retain or + /// discard the child. + pub fn release_and_confirm(&mut self, pid: u32) -> Result<(), GateReleaseError> { + #[cfg(not(any(test, feature = "workspace-io-fault")))] + let _ = pid; + write_all(self.parent.as_raw_fd(), &[GATE_RELEASE_BYTE]) + .map_err(GateReleaseError::NotReleased)?; + #[cfg(any(test, feature = "workspace-io-fault"))] + { + pause_after_release_for_test(pid); + if std::env::var_os("RUSTSCRIPT_AGENT_TEST_GATE_FORCE_AMBIGUOUS").is_some() { + // Fault injection for the post-release confirmation only: the + // release byte was really written, so the tool may execute. + return Err(GateReleaseError::Ambiguous(io::Error::from( + io::ErrorKind::InvalidData, + ))); + } + } + let mut payload = [0u8; std::mem::size_of::()]; + let mut filled = 0; + while filled < payload.len() { + // SAFETY: the destination is inside `payload` and the length is the + // remaining capacity. + let read = unsafe { + libc::read( + self.parent.as_raw_fd(), + payload[filled..].as_mut_ptr().cast(), + payload.len() - filled, + ) + }; + if read == 0 { + return classify_confirmation(&payload, filled); + } + if read < 0 { + let error = io::Error::last_os_error(); + if error.kind() == io::ErrorKind::Interrupted { + continue; + } + // The release was written, so an unreadable confirmation is + // ambiguous rather than proof that the tool did not run. + return Err(GateReleaseError::Ambiguous(error)); + } + filled += read as usize; + } + classify_confirmation(&payload, filled) + } +} + +/// Test-only: park the releasing worker after the release byte was written and +/// before the confirmation is read. +/// +/// This is the seam where the exit sweep can drain and reap the exact +/// reservation: a later failure cleanup must not signal or reap it. Inert +/// unless the process was started with the park-file variable. +#[cfg(any(test, feature = "workspace-io-fault"))] +fn pause_after_release_for_test(pid: u32) { + let Some(park) = std::env::var_os("RUSTSCRIPT_AGENT_TEST_GATE_AFTER_RELEASE_PARK_FILE") else { + return; + }; + if std::path::Path::new(&park).exists() { + return; + } + // The worker writes its child pid so the test can inspect the exact + // process that the sweep owns. + if std::fs::write(&park, pid.to_string()).is_err() { + return; + } + let Some(release) = std::env::var_os("RUSTSCRIPT_AGENT_TEST_GATE_AFTER_RELEASE_RELEASE_FILE") + else { + return; + }; + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + while !std::path::Path::new(&release).exists() && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(5)); + } +} + +/// Descriptor-remapping helper for the gated child. +/// +/// The caller passes the exact endpoint number in the gate's argv, so no fixed +/// descriptor is assumed: the child only clears `CLOEXEC` on its own forked +/// copy. Every concurrent spawn still sees the parent's `CLOEXEC` original, so +/// no non-`CLOEXEC` copy can leak into an unrelated child. `fcntl` is +/// async-signal-safe. +pub fn prepare_gate_child(fd: RawFd) -> io::Result<()> { + // SAFETY: `fcntl` with `F_SETFD` only changes this descriptor's flags. + if unsafe { libc::fcntl(fd, libc::F_SETFD, 0) } < 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) +} + +/// Runs the gate when this process was started in gate mode. +/// +/// Returns `None` for every ordinary invocation, so the public CLI is parsed +/// exactly as before. +pub fn run_if_requested() -> Option { + let args: Vec = std::env::args_os().collect(); + if args.get(1).map(OsString::as_os_str) != Some(OsStr::new(EXEC_GATE_ARG)) { + return None; + } + Some(run_gate(&args)) +} + +fn run_gate(args: &[OsString]) -> i32 { + let Some(control) = args + .get(2) + .and_then(|value| value.to_str()) + .and_then(|value| value.parse::().ok()) + else { + return GATE_DENIED_EXIT; + }; + if args.get(3).map(OsString::as_os_str) != Some(OsStr::new("--")) || args.len() < 5 { + return GATE_DENIED_EXIT; + } + if args[4].is_empty() { + return GATE_DENIED_EXIT; + } + + // EOF-denies: nothing below this point can run unless the parent that + // recorded this process wrote the single release byte. + let mut release = [0u8; 1]; + loop { + // SAFETY: `release` is a valid one-byte destination on `control`. + let read = unsafe { libc::read(control, release.as_mut_ptr().cast(), 1) }; + if read == 1 { + break; + } + if read < 0 { + let error = io::Error::last_os_error(); + if error.kind() == io::ErrorKind::Interrupted { + continue; + } + } + // EOF, a read error, or a short read: the parent is gone or never + // granted ownership. + return GATE_DENIED_EXIT; + } + if release[0] != GATE_RELEASE_BYTE { + return GATE_DENIED_EXIT; + } + + // A successful exec closes this descriptor; an exec failure writes its + // errno so the parent can return a typed spawn error instead of an + // ambiguous ordinary tool exit. + // SAFETY: `fcntl` with `F_SETFD` only changes this descriptor's flags. + if unsafe { libc::fcntl(control, libc::F_SETFD, libc::FD_CLOEXEC) } < 0 { + return GATE_EXEC_FAILED_EXIT; + } + + // The cwd, environment and stdio were configured by the parent on this + // process; `exec` inherits all of them unchanged. `Command::exec` also + // performs the same `PATH` resolution and passes the exact `argv[0]` the + // parent supplied. + let error = std::process::Command::new(&args[4]).args(&args[5..]).exec(); + let errno = error.raw_os_error().unwrap_or(libc::EIO); + let payload = errno.to_ne_bytes(); + // SAFETY: best-effort bounded error report on the owned control socket. + unsafe { + libc::write(control, payload.as_ptr().cast(), payload.len()); + } + GATE_EXEC_FAILED_EXIT +} + +fn raise_above_stdio(fd: OwnedFd) -> io::Result { + if fd.as_raw_fd() > libc::STDERR_FILENO { + return Ok(fd); + } + // SAFETY: `F_DUPFD_CLOEXEC` returns a new owned descriptor above stdio. + let raised = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_DUPFD_CLOEXEC, 3) }; + if raised < 0 { + return Err(io::Error::last_os_error()); + } + // SAFETY: `raised` is a fresh owned descriptor. + Ok(unsafe { OwnedFd::from_raw_fd(raised) }) +} + +fn write_all(fd: RawFd, mut bytes: &[u8]) -> io::Result<()> { + while !bytes.is_empty() { + // SAFETY: `bytes` is a valid readable slice for the given length. + let written = unsafe { libc::write(fd, bytes.as_ptr().cast(), bytes.len()) }; + if written < 0 { + let error = io::Error::last_os_error(); + if error.kind() == io::ErrorKind::Interrupted { + continue; + } + return Err(error); + } + if written == 0 { + return Err(io::Error::from(io::ErrorKind::WriteZero)); + } + bytes = &bytes[written as usize..]; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn confirmation_classifies_eof_as_exec_success() { + assert!(classify_confirmation(&[0u8; 4], 0).is_ok()); + } + + #[test] + fn confirmation_classifies_a_complete_errno_as_a_confirmed_exec_failure() { + let errno = libc::ENOENT; + let result = classify_confirmation(&errno.to_ne_bytes(), 4); + let failure = result.expect_err("a complete errno must not confirm exec success"); + assert!( + matches!(failure, GateReleaseError::ExecFailed(ref error) if error.raw_os_error() == Some(errno)), + "unexpected classification: {failure:?}" + ); + assert!(!failure.may_have_reached_tool()); + } + + #[test] + fn confirmation_classifies_partial_and_zero_payloads_as_ambiguous() { + let payload = libc::ENOENT.to_ne_bytes(); + for filled in [1usize, 2, 3] { + let failure = classify_confirmation(&payload, filled) + .expect_err("a partial payload cannot be a real exec error"); + assert!( + matches!(failure, GateReleaseError::Ambiguous(_)), + "a partial payload must stay ambiguous: {failure:?}" + ); + assert!(failure.may_have_reached_tool()); + } + let failure = + classify_confirmation(&0i32.to_ne_bytes(), 4).expect_err("errno zero is not an error"); + assert!( + matches!(failure, GateReleaseError::Ambiguous(_)), + "errno zero can only be a protocol violation: {failure:?}" + ); + assert!(failure.may_have_reached_tool()); + } + + #[test] + fn a_failed_release_write_is_never_treated_as_released() { + let failure = GateReleaseError::NotReleased(io::Error::from(io::ErrorKind::BrokenPipe)); + assert!(!failure.may_have_reached_tool()); + assert_eq!( + failure.io().kind(), + io::ErrorKind::BrokenPipe, + "the exact transport error must be preserved" + ); + } +} diff --git a/src/capabilities/vm_io/mod.rs b/src/capabilities/vm_io/mod.rs index 6fcdf271..e5425551 100644 --- a/src/capabilities/vm_io/mod.rs +++ b/src/capabilities/vm_io/mod.rs @@ -8,14 +8,19 @@ pub mod bounded_process; pub mod confined_fs; +#[cfg(target_os = "linux")] +pub mod exec_gate; mod shared; pub use bounded_process::{ BoundedProcess, BoundedProcessError, BoundedProcessHandle, BoundedProcessRequest, CancellationToken, LogSnapshot, MAX_OUTPUT_BYTES, MAX_STDIN_BYTES, MAX_TIMEOUT, ProcessStatus, + fail_next_pidfd_opens_for_test, }; pub use confined_fs::{ ConfinedFileType, ConfinedFsError, ConfinedFsErrorKind, ConfinedFsLimits, ConfinedFsRoot, - ConfinedMetadata, ConfinedPublicationState, MAX_COMPONENT_BYTES, MAX_ENUM_ENTRIES, - MAX_READ_BYTES, MAX_WRITE_BYTES, + ConfinedMetadata, ConfinedObservedIdentity, ConfinedPublicationState, MAX_COMPONENT_BYTES, + MAX_ENUM_ENTRIES, MAX_READ_BYTES, MAX_WRITE_BYTES, }; +#[cfg(target_os = "linux")] +pub use exec_gate::run_if_requested as run_exec_gate_if_requested; diff --git a/src/capabilities/vm_io/shared.rs b/src/capabilities/vm_io/shared.rs index 6883c6af..68dea2d0 100644 --- a/src/capabilities/vm_io/shared.rs +++ b/src/capabilities/vm_io/shared.rs @@ -1,4 +1,8 @@ //! Pipe and process-group helpers used by the vendored bounded-process backend. +//! +//! Process-group signalling lives in `bounded_process` itself: every numeric +//! group signal must pass the shared ownership check, so there is deliberately +//! no helper here that could bypass it. #[cfg(unix)] pub(super) fn set_pipe_nonblocking(pipe: &impl std::os::fd::AsRawFd) -> std::io::Result<()> { @@ -25,17 +29,3 @@ pub(super) fn set_pipe_nonblocking( "Windows child pipes require cancellable I/O rather than PIPE_NOWAIT", )) } - -#[cfg(unix)] -pub(crate) fn terminate_process_group(process_id: u32) { - if let Ok(pid) = libc::pid_t::try_from(process_id) { - unsafe { - libc::kill(-pid, libc::SIGKILL); - } - } -} - -#[cfg(not(unix))] -pub(crate) fn terminate_process_group(process_id: u32) { - let _ = process_id; -} diff --git a/src/cli.rs b/src/cli.rs index ca77b779..6d7ab631 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -2,11 +2,14 @@ use std::error::Error; use std::ffi::OsString; use std::fmt::{Display, Formatter}; use std::path::PathBuf; +use std::time::Duration; use rustscript_vm::Value; use crate::AgentPaths; use crate::auth::host::{AuthHost, ConfigPathHost}; +use crate::mcp::ToolProfile; +use crate::mcp::executor::McpToolExecutorConfig; use crate::runtime::{AuthCommandInput, AuthEntryError, AuthEntryRunner, RunCancellation}; const MAX_STATUS_BYTES: usize = 256 * 1024; @@ -21,11 +24,62 @@ pub enum CliInvocation { }, Auth(AuthCommandInput), ConfigPath(AuthCommandInput), + ToolsServe(ToolsServeOptions), +} + +/// Parsed `tools serve --stdio` invocation. +/// +/// Every bound is optional; an omitted bound keeps the standalone executor's +/// own default. The workspace is validated for shape here (absolute, bounded, +/// NUL-free) and for existence by the tool server before it starts serving. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ToolsServeOptions { + pub workspace: PathBuf, + pub profile: ToolProfile, + pub max_tool_calls: Option, + pub max_output_bytes: Option, + pub call_timeout: Option, + pub server_lifetime: Option, + pub max_processes: Option, + pub max_processes_per_owner: Option, + pub process_cleanup_timeout: Option, +} + +impl ToolsServeOptions { + /// Builds the executor configuration, leaving defaults in place for every + /// omitted bound. + pub fn executor_config(&self) -> McpToolExecutorConfig { + let mut config = + McpToolExecutorConfig::new(self.workspace.clone()).with_profile(self.profile); + if let Some(max_tool_calls) = self.max_tool_calls { + config = config.with_max_tool_calls(max_tool_calls); + } + if let Some(max_output_bytes) = self.max_output_bytes { + config = config.with_max_output_bytes(max_output_bytes); + } + if let Some(call_timeout) = self.call_timeout { + config = config.with_call_timeout(call_timeout); + } + if let Some(server_lifetime) = self.server_lifetime { + config = config.with_server_lifetime(server_lifetime); + } + if let Some(max_processes) = self.max_processes { + config = config.with_max_processes(max_processes); + } + if let Some(max_processes_per_owner) = self.max_processes_per_owner { + config = config.with_max_processes_per_owner(max_processes_per_owner); + } + if let Some(process_cleanup_timeout) = self.process_cleanup_timeout { + config = config.with_process_cleanup_timeout(process_cleanup_timeout); + } + config + } } #[derive(Debug, PartialEq, Eq)] pub enum CliError { InvalidArguments, + InvalidWorkspace, InvalidHome, OutputInvalid, OutputTooLarge, @@ -35,6 +89,7 @@ impl CliError { pub const fn code(&self) -> &'static str { match self { Self::InvalidArguments => "cli_arguments_invalid", + Self::InvalidWorkspace => "cli_workspace_invalid", Self::InvalidHome => "cli_home_invalid", Self::OutputInvalid => "cli_output_invalid", Self::OutputTooLarge => "cli_output_too_large", @@ -182,7 +237,7 @@ fn unsafe_report_control(value: &str) -> bool { } pub fn cli_usage() -> &'static str { - "Usage:\n rustscript-agent --script PATH --allow-host HOST [--allow-host HOST ...]\n rustscript-agent run --script PATH --allow-host HOST [--allow-host HOST ...]\n rustscript-agent auth login PROVIDER\n rustscript-agent auth status [PROVIDER]\n rustscript-agent auth logout ID\n rustscript-agent config path\n rustscript-agent config check" + "Usage:\n rustscript-agent --script PATH --allow-host HOST [--allow-host HOST ...]\n rustscript-agent run --script PATH --allow-host HOST [--allow-host HOST ...]\n rustscript-agent auth login PROVIDER\n rustscript-agent auth status [PROVIDER]\n rustscript-agent auth logout ID\n rustscript-agent config path\n rustscript-agent config check\n rustscript-agent tools serve --stdio --workspace PATH [--profile coding|read-only] [--read-only] [--max-tool-calls N] [--max-output-bytes N] [--call-timeout-ms N] [--server-lifetime-ms N] [--max-processes N] [--max-processes-per-owner N] [--process-cleanup-timeout-ms N]" } pub fn parse_cli_args(args: impl IntoIterator) -> Result { @@ -195,6 +250,7 @@ pub fn parse_cli_args(args: impl IntoIterator) -> Result parse_run(&args[1..]), Some("auth") => parse_auth(&args[1..]), Some("config") => parse_config(&args[1..]), + Some("tools") => parse_tools(&args[1..]), _ => parse_run(&args), } } @@ -238,6 +294,159 @@ fn parse_run(args: &[OsString]) -> Result { }) } +fn parse_tools(args: &[OsString]) -> Result { + match args.first().and_then(|value| value.to_str()) { + Some("--help" | "-h") if args.len() == 1 => Ok(CliInvocation::Help), + Some("serve") => parse_tools_serve(&args[1..]), + _ => Err(CliError::InvalidArguments), + } +} + +fn parse_tools_serve(args: &[OsString]) -> Result { + let mut stdio = false; + let mut workspace = None; + let mut profile = None; + let mut max_tool_calls = None; + let mut max_output_bytes = None; + let mut call_timeout = None; + let mut server_lifetime = None; + let mut max_processes = None; + let mut max_processes_per_owner = None; + let mut process_cleanup_timeout = None; + + let mut index = 0; + while index < args.len() { + let flag = args[index].to_str().ok_or(CliError::InvalidArguments)?; + match flag { + "--help" | "-h" => return Ok(CliInvocation::Help), + "--stdio" => { + if stdio { + return Err(CliError::InvalidArguments); + } + stdio = true; + index += 1; + } + "--workspace" => { + let value = args.get(index + 1).ok_or(CliError::InvalidArguments)?; + if workspace.is_some() { + return Err(CliError::InvalidArguments); + } + workspace = Some(validated_workspace(value)?); + index += 2; + } + "--profile" => { + if profile.is_some() { + return Err(CliError::InvalidArguments); + } + let value = args.get(index + 1).ok_or(CliError::InvalidArguments)?; + profile = Some(match value.to_str() { + Some(ToolProfile::CODING) => ToolProfile::Coding, + Some(ToolProfile::READ_ONLY) => ToolProfile::ReadOnly, + _ => return Err(CliError::InvalidArguments), + }); + index += 2; + } + "--read-only" => { + if profile.is_some() { + return Err(CliError::InvalidArguments); + } + profile = Some(ToolProfile::ReadOnly); + index += 1; + } + "--max-tool-calls" => { + if max_tool_calls.is_some() { + return Err(CliError::InvalidArguments); + } + max_tool_calls = Some(bounded_count(&mut index, args)?); + } + "--max-output-bytes" => { + if max_output_bytes.is_some() { + return Err(CliError::InvalidArguments); + } + max_output_bytes = Some(bounded_size(&mut index, args)?); + } + "--call-timeout-ms" => { + if call_timeout.is_some() { + return Err(CliError::InvalidArguments); + } + call_timeout = Some(milliseconds(&mut index, args)?); + } + "--server-lifetime-ms" => { + if server_lifetime.is_some() { + return Err(CliError::InvalidArguments); + } + server_lifetime = Some(milliseconds(&mut index, args)?); + } + "--max-processes" => { + if max_processes.is_some() { + return Err(CliError::InvalidArguments); + } + max_processes = Some(bounded_size(&mut index, args)?); + } + "--max-processes-per-owner" => { + if max_processes_per_owner.is_some() { + return Err(CliError::InvalidArguments); + } + max_processes_per_owner = Some(bounded_size(&mut index, args)?); + } + "--process-cleanup-timeout-ms" => { + if process_cleanup_timeout.is_some() { + return Err(CliError::InvalidArguments); + } + process_cleanup_timeout = Some(milliseconds(&mut index, args)?); + } + _ => return Err(CliError::InvalidArguments), + } + } + + if !stdio { + return Err(CliError::InvalidArguments); + } + Ok(CliInvocation::ToolsServe(ToolsServeOptions { + workspace: workspace.ok_or(CliError::InvalidArguments)?, + profile: profile.unwrap_or(ToolProfile::Coding), + max_tool_calls, + max_output_bytes, + call_timeout, + server_lifetime, + max_processes, + max_processes_per_owner, + process_cleanup_timeout, + })) +} + +fn validated_workspace(value: &OsString) -> Result { + if value.is_empty() { + return Err(CliError::InvalidWorkspace); + } + let path = PathBuf::from(value); + if path.to_string_lossy().contains('\0') || !path.is_absolute() { + return Err(CliError::InvalidWorkspace); + } + Ok(path) +} + +fn bounded_count(index: &mut usize, args: &[OsString]) -> Result { + let value = args.get(*index + 1).ok_or(CliError::InvalidArguments)?; + let text = value.to_str().ok_or(CliError::InvalidArguments)?; + let parsed = text + .parse::() + .map_err(|_| CliError::InvalidArguments)?; + if parsed == 0 { + return Err(CliError::InvalidArguments); + } + *index += 2; + Ok(parsed) +} + +fn bounded_size(index: &mut usize, args: &[OsString]) -> Result { + usize::try_from(bounded_count(index, args)?).map_err(|_| CliError::InvalidArguments) +} + +fn milliseconds(index: &mut usize, args: &[OsString]) -> Result { + Ok(Duration::from_millis(bounded_count(index, args)?)) +} + fn parse_auth(args: &[OsString]) -> Result { let operation = args.first().and_then(|value| value.to_str()); let input = match operation { diff --git a/src/effects/broker.rs b/src/effects/broker.rs index 90df3875..635476c3 100644 --- a/src/effects/broker.rs +++ b/src/effects/broker.rs @@ -5516,7 +5516,9 @@ impl ManagedCallContext { .swap(false, Ordering::SeqCst) { let process_owner = Arc::clone(&processes); - processes.set_after_os_spawn_hook(Arc::new(move || process_owner.shutdown_all())); + processes.set_after_os_spawn_hook(Arc::new(move || { + let _ = process_owner.shutdown_all(); + })); } binding.check()?; #[cfg(test)] diff --git a/src/effects/managed_authority_tests.rs b/src/effects/managed_authority_tests.rs index 785c3b62..9da38ffb 100644 --- a/src/effects/managed_authority_tests.rs +++ b/src/effects/managed_authority_tests.rs @@ -340,6 +340,7 @@ async fn fresh_host_rejects_wrong_risk_name_arguments_and_registry_then_same_vm_ artifacts: host.artifacts.clone(), leases: Default::default(), control_hook: None, + commit_observer: None, pinned_tool: host.pinned_tool.clone(), allow_stateless_pin: false, expected_call: None, diff --git a/src/lib.rs b/src/lib.rs index 31fec657..41098064 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -19,6 +19,7 @@ pub mod events; pub mod gateway; #[cfg(any(test, feature = "config-fixture"))] mod host_opaque; +pub mod mcp; pub mod metrics; pub mod plugins; pub mod prompt; @@ -77,10 +78,10 @@ pub use registry::{ }; pub use runtime::cancellation::{CancellationReason, CancellationToken}; pub use runtime::rss_runner::{ - AgentConfig, AgentError, AgentRunner, MAX_AGENT_SOURCE_BYTES, RUN_EPOCH_CHECK_INTERVAL, - RUN_EPOCH_DEADLINE_TICKS, Result, RunCancellation, RunDeliveryError, RunError, RunEventSink, - RunnerPrepareFault, bundled_agent_main_path, bundled_tool_entries, bundled_tool_registry, - set_after_snapshot_hook, + AgentConfig, AgentError, AgentRunner, MAX_AGENT_SOURCE_BYTES, ProviderMode, + RUN_EPOCH_CHECK_INTERVAL, RUN_EPOCH_DEADLINE_TICKS, Result, RunCancellation, RunDeliveryError, + RunError, RunEventSink, RunnerPrepareFault, bundled_agent_main_path, bundled_tool_entries, + bundled_tool_registry, set_after_snapshot_hook, }; pub use runtime::{ AgentHostBridges, AgentProviderHost, ControlCheckHook, ScriptedProvider, agent_host_catalog, diff --git a/src/mcp/catalog.rs b/src/mcp/catalog.rs new file mode 100644 index 00000000..13d5df74 --- /dev/null +++ b/src/mcp/catalog.rs @@ -0,0 +1,149 @@ +//! Exact registry-to-MCP tool mapping. +//! +//! The admitted [`ToolRegistrySnapshot`] is the only schema source. Mapping +//! reads each [`ToolDescriptor`] directly and never declares a second copy of +//! a tool schema. Tool annotations and `_meta` risk/toolset values are +//! presentation hints only; the executor's profile and capability policy stay +//! authoritative. + +use std::sync::Arc; + +use rmcp::model::{JsonObject, MetaObject, Tool, ToolAnnotations}; +use serde_json::{Map, json}; + +use super::ToolProfile; +use crate::registry::ToolRegistrySnapshot; +use crate::tool_schema::{RiskClass, ToolDescriptor, Toolset}; + +/// `_meta` key carrying the admitted RustScript risk class. +pub const RISK_META_KEY: &str = "org.rustscript/risk_class"; +/// `_meta` key carrying the admitted RustScript toolset. +pub const TOOLSET_META_KEY: &str = "org.rustscript/toolset"; + +/// Typed catalog export failure. These are mapping failures, not tool-call +/// failures: a value that the registry policy cannot represent is never +/// exported to MCP. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum McpCatalogError { + UnsupportedRiskClass { name: String, value: String }, + UnsupportedToolset { name: String, value: String }, + ObjectSchemaRequired { name: String }, + ProfileViolation { name: String, risk_class: String }, +} + +impl std::fmt::Display for McpCatalogError { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::UnsupportedRiskClass { name, value } => { + write!( + formatter, + "tool {name} uses unsupported risk class {value:?}" + ) + } + Self::UnsupportedToolset { name, value } => { + write!(formatter, "tool {name} uses unsupported toolset {value:?}") + } + Self::ObjectSchemaRequired { name } => { + write!(formatter, "tool {name} input schema must be an object") + } + Self::ProfileViolation { name, risk_class } => write!( + formatter, + "tool {name} ({risk_class}) cannot be exported by the selected profile" + ), + } + } +} + +impl std::error::Error for McpCatalogError {} + +/// Maps an admitted registry snapshot for one profile. +/// +/// Order is the deterministic registry order; read-only filtering only drops +/// descriptors the profile does not admit. +pub fn catalog_from_registry( + snapshot: &ToolRegistrySnapshot, + profile: ToolProfile, +) -> Result, McpCatalogError> { + catalog_from_descriptors(snapshot.descriptors(), profile) +} + +/// Maps descriptors for one profile. Used by the registry path and by focused +/// policy tests; both resolve to the same exact descriptor-to-tool function. +pub fn catalog_from_descriptors( + descriptors: &[ToolDescriptor], + profile: ToolProfile, +) -> Result, McpCatalogError> { + let mut tools = Vec::new(); + for descriptor in descriptors { + if !profile.admits_name(&descriptor.name) { + continue; + } + let tool = tool_from_descriptor(descriptor)?; + let risk = RiskClass::try_from(descriptor.risk_class.as_str()) + .expect("tool_from_descriptor validated the risk class"); + if !profile.admits_risk(risk) { + return Err(McpCatalogError::ProfileViolation { + name: descriptor.name.clone(), + risk_class: descriptor.risk_class.clone(), + }); + } + tools.push(tool); + } + Ok(tools) +} + +/// Converts one admitted descriptor to an MCP tool. +/// +/// The name, description, and input schema are copied exactly from the +/// descriptor. Annotations and risk/toolset metadata are derived hints. +pub fn tool_from_descriptor(descriptor: &ToolDescriptor) -> Result { + let risk = RiskClass::try_from(descriptor.risk_class.as_str()).map_err(|_| { + McpCatalogError::UnsupportedRiskClass { + name: descriptor.name.clone(), + value: descriptor.risk_class.clone(), + } + })?; + Toolset::try_from(descriptor.toolset.as_str()).map_err(|_| { + McpCatalogError::UnsupportedToolset { + name: descriptor.name.clone(), + value: descriptor.toolset.clone(), + } + })?; + let schema: JsonObject = descriptor.schema.as_object().cloned().ok_or_else(|| { + McpCatalogError::ObjectSchemaRequired { + name: descriptor.name.clone(), + } + })?; + + let mut meta = Map::new(); + meta.insert(RISK_META_KEY.to_string(), json!(descriptor.risk_class)); + meta.insert(TOOLSET_META_KEY.to_string(), json!(descriptor.toolset)); + + Ok(Tool::new( + descriptor.name.clone(), + descriptor.description.clone(), + Arc::new(schema), + ) + .with_annotations(annotations_for(risk)) + .with_meta(MetaObject(meta))) +} + +fn annotations_for(risk: RiskClass) -> ToolAnnotations { + match risk { + RiskClass::Read => ToolAnnotations::new() + .read_only(true) + .destructive(false) + .idempotent(true) + .open_world(false), + RiskClass::Write => ToolAnnotations::new() + .read_only(false) + .destructive(true) + .idempotent(false) + .open_world(false), + RiskClass::Execute => ToolAnnotations::new() + .read_only(false) + .destructive(true) + .idempotent(false) + .open_world(true), + } +} diff --git a/src/mcp/executor.rs b/src/mcp/executor.rs new file mode 100644 index 00000000..24d7f144 --- /dev/null +++ b/src/mcp/executor.rs @@ -0,0 +1,3070 @@ +//! Standalone RSS tool executor for the provider-free MCP tool server. +//! +//! The executor compiles the existing bundled `rss/tools/dispatch_entry.rss` +//! closed bundle once, freezes the admitted six-tool registry identity once, +//! and binds the same capability lifecycle, filesystem, process, and artifact +//! primitives used by the gateway run path. It validates every tool name, +//! profile admission, argument schema, and call identity before RSS dispatch, +//! then returns only the canonical [`ToolResult`] carried by the existing +//! dispatch envelope. +//! +//! This module deliberately does not depend on `AgentService`, provider +//! adapters, auth configuration, the provider loop, or `rss/agent/main.rss`. +//! The tool dispatch program never imports a provider call; the executor's +//! frozen runners are constructed provider-disabled, so a reachable +//! `agent::provider_call` returns a typed `provider_disabled` envelope instead +//! of instantiating the RSS provider adapter or loading credentials. A +//! server-scoped executor has no durable effect journal, so it never claims +//! cross-restart replay: duplicate call IDs within one executor lifetime are +//! rejected instead. + +use std::collections::{HashMap, HashSet}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard, OnceLock, TryLockError}; +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; +use uuid::Uuid; + +use super::ToolProfile; +use crate::capabilities::vm_io::{ + ConfinedFsLimits, ConfinedFsRoot, MAX_COMPONENT_BYTES, MAX_ENUM_ENTRIES, MAX_READ_BYTES, + MAX_WRITE_BYTES, +}; +use crate::capabilities::{ + ArtifactCapability, ArtifactLimits, CallCancellationSource, CallCancellationState, CallReceipt, + CallTerminalDecision, CallTerminalRequest, CapabilityLifecycle, CapabilityOwner, + DurableStarted, DurableToolLifecycle, FilesystemCapability, FilesystemLimits, LifecycleClock, + LifecycleError, LifecycleLimits, ProcessCapability, ProcessCleanupProof, ProcessLimits, + ProcessTableLimits, PublishedTokenPolicy, SystemClock, UuidIssuer, positive_duration_ms, +}; +use crate::config::{ + DEFAULT_TOOL_OUTPUT_BYTES, FileToolConfig, MAX_TOOL_OUTPUT_BYTES, ProcessToolConfig, +}; +use crate::domain::{json_to_vm_value, vm_value_to_json}; +use crate::registry::ToolRegistrySnapshot; +#[cfg(any(test, feature = "workspace-io-fault"))] +use crate::runtime::CommitObserver; +use crate::runtime::{ + AgentConfig, AgentHostBridges, AgentRunner, RunCancellation, RunDeliveryError, RunEventSink, + rss_runner::ProviderMode, +}; +use crate::tool_result::ToolResult; +use rustscript_vm::Value as VmValue; + +/// Maximum UTF-8 bytes accepted for an explicit MCP call identity. +pub const MAX_CALL_ID_BYTES: usize = 128; + +/// Minimum output cap that can carry a minimal committed effect receipt. +/// +/// Measured canonical success receipts at the minimal shape are: `write_file` +/// 166 bytes, `patch` 257 bytes, foreground `terminal` 360 bytes (status, +/// exit, cursor and EOF fields), background `terminal` 164 bytes. +/// +/// The compact RSS terminal receipt keeps the outcome, error code/message +/// (48/96 JSON-encoded bytes), terminal status/exit/signal, and one canonical +/// 36-byte artifact ID. Including escaping, that shape is at most 346 bytes. +/// 512 admits both this fallback and the measured success receipts. Smaller +/// coding caps are rejected before a tool can publish. +pub const MIN_EFFECT_TOOL_OUTPUT_BYTES: usize = 512; + +/// Minimum output cap for the read-only profile. +/// +/// Measured canonical read receipts are 106 bytes for a short file and 200 +/// bytes for the compact large-output artifact summary. 256 bytes is the +/// smallest power-of-two bound that admits both without forcing a truncation +/// of the short-result path. This profile cannot dispatch process tools. +pub const MIN_READ_ONLY_TOOL_OUTPUT_BYTES: usize = 256; + +/// Default executor lifetime. A server-scoped process is intentionally +/// bounded; it never outlives this deadline. +pub const DEFAULT_SERVER_LIFETIME: Duration = Duration::from_secs(60 * 60); + +/// Hard upper bound for one executor lifetime, matching the process-tool +/// timeout ceiling that every admitted execute tool must respect. +pub const MAX_EXECUTOR_LIFETIME: Duration = crate::config::MAX_PROCESS_TOOL_TIMEOUT; + +/// Hard bound on retained call identities and admitted calls per executor. +pub const MAX_EXECUTOR_TOOL_CALLS: u64 = crate::config::RunLimits::MAX_TOOL_CALLS; + +/// Hard bound on cancellation intents recorded for call identities that have +/// not reached admission yet. Reaching it closes admission instead of +/// forgetting an intent, so a cancelled call can never execute later. +const MAX_PRE_ADMISSION_CANCELLATIONS: usize = MAX_EXECUTOR_TOOL_CALLS as usize; + +/// Test-only observer invoked before a call reaches admission. +#[cfg(any(test, feature = "workspace-io-fault"))] +type PreAdmissionObserver = Arc; + +/// Test-only observer invoked while the admission lock is held, before the +/// cancellation intent and request-scoped source are consulted. +#[cfg(any(test, feature = "workspace-io-fault"))] +type AdmissionObserver = Arc; + +/// Request-scoped cancellation source observed atomically at admission. +/// +/// The server binds this to the transport request token. `admit_call` checks it +/// under the admission lock, so a cancellation that races a queued worker is +/// linearized: either the intent/token is visible before the identity is +/// burned, or the admitted call is registered before the cancellation can take +/// the admission lock and is signalled through the call registry instead. +#[derive(Clone)] +pub struct AdmissionCancellation(Arc bool + Send + Sync>); + +impl AdmissionCancellation { + /// Wraps a request-scoped cancellation source. + pub fn new(source: impl Fn() -> bool + Send + Sync + 'static) -> Self { + Self(Arc::new(source)) + } + + /// True when the owning request has already been cancelled. + pub fn is_cancelled(&self) -> bool { + (self.0)() + } +} + +impl std::fmt::Debug for AdmissionCancellation { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("AdmissionCancellation") + .field("cancelled", &self.is_cancelled()) + .finish() + } +} + +/// Default bound for one tool dispatch. +pub const DEFAULT_CALL_TIMEOUT: Duration = Duration::from_secs(60 * 60); + +/// Default number of tool calls admitted over one executor lifetime. +pub const DEFAULT_MAX_TOOL_CALLS: u64 = 10_000; + +const MAX_ERROR_BYTES: usize = 512; +const MCP_PROFILE_LABEL: &str = "mcp"; +const MCP_SESSION_DEFAULT: &str = "stdio"; +const MCP_RUN_LABEL: &str = "tools"; + +/// Typed executor configuration. `workspace_root` is canonicalized and +/// validated before any capability is constructed. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct McpToolExecutorConfig { + pub workspace_root: PathBuf, + /// Tool exposure profile. Defaults to the coding profile. + pub profile: ToolProfile, + /// Stable session label used for capability ownership. Defaults to + /// `stdio`; an MCP server may set it to the transport session identity. + pub session_id: String, + /// Tool calls admitted over the whole executor lifetime. + pub max_tool_calls: u64, + /// Canonical model-visible output budget. Must be positive and within the + /// existing project ceiling; capability budgets are aligned to this value. + pub max_output_bytes: usize, + /// Bound for one tool dispatch. + pub call_timeout: Duration, + /// Bound for the whole executor lifetime. + pub server_lifetime: Duration, + /// Maximum retained process records in the executor table. + pub max_processes: usize, + /// Maximum retained process records for this executor's owner. + pub max_processes_per_owner: usize, + /// One shared shutdown/drop cleanup deadline for owned children. + pub process_cleanup_timeout: Duration, + /// Linux-only: the packaged server may `std::process::exit`, so children + /// are launched through the pre-exec gate that cannot run tool code before + /// its pid is recorded. Test and in-process executors leave this off. + pub exec_gate: bool, + /// Test-only VM epoch check interval override. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub epoch_check_interval_for_test: Option, +} + +impl McpToolExecutorConfig { + /// Returns the default coding profile rooted at `workspace_root`. + pub fn new(workspace_root: impl Into) -> Self { + let workspace_root = workspace_root.into(); + let process_defaults = ProcessToolConfig::for_workspace(workspace_root.clone()); + Self { + workspace_root, + profile: ToolProfile::Coding, + session_id: MCP_SESSION_DEFAULT.to_string(), + max_tool_calls: DEFAULT_MAX_TOOL_CALLS, + max_output_bytes: DEFAULT_TOOL_OUTPUT_BYTES, + call_timeout: DEFAULT_CALL_TIMEOUT, + server_lifetime: DEFAULT_SERVER_LIFETIME, + max_processes: process_defaults.max_processes, + max_processes_per_owner: process_defaults.max_processes_per_owner, + process_cleanup_timeout: process_defaults.cleanup_timeout, + exec_gate: false, + #[cfg(any(test, feature = "workspace-io-fault"))] + epoch_check_interval_for_test: None, + } + } + + pub fn with_profile(mut self, profile: ToolProfile) -> Self { + self.profile = profile; + self + } + + pub fn with_session_id(mut self, session_id: impl Into) -> Self { + self.session_id = session_id.into(); + self + } + + pub fn with_max_tool_calls(mut self, max_tool_calls: u64) -> Self { + self.max_tool_calls = max_tool_calls; + self + } + + pub fn with_max_output_bytes(mut self, max_output_bytes: usize) -> Self { + self.max_output_bytes = max_output_bytes; + self + } + + pub fn with_call_timeout(mut self, call_timeout: Duration) -> Self { + self.call_timeout = call_timeout; + self + } + + pub fn with_server_lifetime(mut self, server_lifetime: Duration) -> Self { + self.server_lifetime = server_lifetime; + self + } + + pub fn with_max_processes(mut self, max_processes: usize) -> Self { + self.max_processes = max_processes; + self + } + + pub fn with_max_processes_per_owner(mut self, max_processes_per_owner: usize) -> Self { + self.max_processes_per_owner = max_processes_per_owner; + self + } + + pub fn with_process_cleanup_timeout(mut self, process_cleanup_timeout: Duration) -> Self { + self.process_cleanup_timeout = process_cleanup_timeout; + self + } + + /// Linux-only: launch children through the pre-exec gate. + /// + /// The packaged `tools serve` path enables this because its hard exit + /// cannot join a worker parked between the OS spawn and the pid record. + #[doc(hidden)] + pub fn with_exec_gate(mut self) -> Self { + self.exec_gate = true; + self + } + + /// Test-only: make VM cancellation observation deterministic. + #[doc(hidden)] + #[cfg(any(test, feature = "workspace-io-fault"))] + pub fn with_epoch_check_interval_for_test(mut self, interval: u32) -> Self { + self.epoch_check_interval_for_test = Some(interval); + self + } +} + +/// Typed construction and execution failure of the standalone executor. +/// +/// Tool-level failures are not errors here: they are returned as canonical +/// [`ToolResult`] values with `ok == false` and the existing error code. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum McpToolExecutorError { + /// Configuration or workspace validation failed before any effect. + InvalidConfig { message: String }, + /// The bundled registry could not be admitted. + RegistryUnavailable { message: String }, + /// The bundled dispatch entry could not be compiled. + DispatchUnavailable { message: String }, + /// A capability primitive could not be constructed. + CapabilityUnavailable { code: String, message: String }, + /// The executor was shut down. + Closed, + /// The tool name is not part of the admitted registry. + UnknownTool { name: String }, + /// The tool exists but the selected profile does not admit it. + DisabledTool { name: String, risk_class: String }, + /// Arguments do not match the admitted descriptor schema. + InvalidArguments { message: String }, + /// An explicit call identity is empty, too long, or contains controls. + InvalidCallId { message: String }, + /// The same call identity was already used in this executor lifetime. + DuplicateCallId { call_id: String }, + /// The call was cancelled before it reached admission. No prepare, + /// dispatch, or effect can follow. + Cancelled { call_id: String }, + /// The hard lifetime admission quota is exhausted. + CallQuotaExhausted { limit: u64 }, + /// The executor lifetime deadline elapsed. + LifetimeElapsed, + /// The RSS dispatch failed before producing a canonical result. + DispatchFailed { message: String }, + /// The dispatch envelope did not carry a valid canonical tool result. + InvalidDispatchOutput { message: String }, + /// The host refused the guest commit because a publisher still owns the + /// call. The call is retained with the native ledger disposition; the + /// refusal bytes are never the caller's terminal result. + Retained { call_id: String }, +} + +impl McpToolExecutorError { + /// Stable machine-readable code for later MCP protocol error mapping. + pub fn code(&self) -> &'static str { + match self { + Self::InvalidConfig { .. } => "invalid_config", + Self::RegistryUnavailable { .. } => "registry_unavailable", + Self::DispatchUnavailable { .. } => "dispatch_unavailable", + Self::CapabilityUnavailable { .. } => "capability_unavailable", + Self::Closed => "executor_closed", + Self::UnknownTool { .. } => "unknown_tool", + Self::DisabledTool { .. } => "disabled_tool", + Self::InvalidArguments { .. } => "invalid_arguments", + Self::InvalidCallId { .. } => "invalid_call_id", + Self::DuplicateCallId { .. } => "duplicate_call_id", + Self::Cancelled { .. } => "cancelled", + Self::CallQuotaExhausted { .. } => "call_quota_exhausted", + Self::LifetimeElapsed => "lifetime_elapsed", + Self::DispatchFailed { .. } => "dispatch_failed", + Self::InvalidDispatchOutput { .. } => "invalid_dispatch_output", + Self::Retained { .. } => "retained", + } + } +} + +impl std::fmt::Display for McpToolExecutorError { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::InvalidConfig { message } => { + write!(formatter, "invalid executor configuration: {message}") + } + Self::RegistryUnavailable { message } => { + write!(formatter, "tool registry is unavailable: {message}") + } + Self::DispatchUnavailable { message } => { + write!(formatter, "tool dispatch is unavailable: {message}") + } + Self::CapabilityUnavailable { code, message } => { + write!(formatter, "capability is unavailable ({code}): {message}") + } + Self::Closed => formatter.write_str("tool executor is closed"), + Self::UnknownTool { name } => write!(formatter, "unknown tool: {name}"), + Self::DisabledTool { name, risk_class } => { + write!( + formatter, + "tool {name} ({risk_class}) is disabled by this profile" + ) + } + Self::InvalidArguments { message } => { + write!(formatter, "invalid tool arguments: {message}") + } + Self::InvalidCallId { message } => write!(formatter, "invalid tool call id: {message}"), + Self::DuplicateCallId { call_id } => { + write!(formatter, "duplicate tool call id: {call_id}") + } + Self::Cancelled { call_id } => { + write!( + formatter, + "tool call {call_id} was cancelled before admission" + ) + } + Self::CallQuotaExhausted { limit } => { + write!( + formatter, + "tool call admission quota exhausted (limit {limit})" + ) + } + Self::LifetimeElapsed => formatter.write_str("tool executor lifetime elapsed"), + Self::DispatchFailed { message } => { + write!(formatter, "tool dispatch failed: {message}") + } + Self::InvalidDispatchOutput { message } => { + write!(formatter, "tool dispatch output is invalid: {message}") + } + Self::Retained { call_id } => { + write!( + formatter, + "tool call {call_id} is retained until its in-flight publisher settles" + ) + } + } + } +} + +impl std::error::Error for McpToolExecutorError {} + +struct DiscardSink; + +impl RunEventSink for DiscardSink { + fn deliver(&mut self, _value: VmValue) -> Result<(), RunDeliveryError> { + Ok(()) + } +} + +/// In-memory, server-lifetime durable lifecycle. +/// +/// The MCP tool process owns no effect journal and no cross-restart replay. +/// Each call still passes through the existing prepare/started/commit +/// validation; committed canonical results are retained in memory for the +/// lifetime of the executor so the owner can read the exact payload back after +/// the guest committed but before the VM returned. +#[derive(Default)] +struct InMemoryDurableLifecycle { + committed: Mutex>, + /// Every acknowledged `commit_result`. Test diagnostic only: a call must + /// write exactly one durable receipt even when several settlements race. + commits: AtomicUsize, + /// Every acknowledged `prepare_parent` (the durable prepare boundary). + /// Test diagnostic only: a cancelled call must not reach prepare at all, + /// which a commit counter cannot prove. + prepares: AtomicUsize, + /// Test-only one-shot commit rejection at the real durable boundary. + #[cfg(any(test, feature = "workspace-io-fault"))] + fail_next_commit: AtomicBool, +} + +impl InMemoryDurableLifecycle { + fn new() -> Self { + Self::default() + } + + fn commit_count(&self) -> usize { + self.commits.load(Ordering::SeqCst) + } + + fn prepare_count(&self) -> usize { + self.prepares.load(Ordering::SeqCst) + } + + #[cfg(any(test, feature = "workspace-io-fault"))] + fn fail_next_commit(&self) { + self.fail_next_commit.store(true, Ordering::SeqCst); + } +} + +impl DurableToolLifecycle for InMemoryDurableLifecycle { + fn assert_active_run(&self, _run_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } + + fn prepare_parent( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result<(), LifecycleError> { + self.prepares.fetch_add(1, Ordering::SeqCst); + Ok(()) + } + + fn replay_result( + &self, + _run_id: &str, + call_id: &str, + _tool_name: &str, + ) -> Result, LifecycleError> { + Ok(self + .committed + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .get(call_id) + .cloned()) + } + + fn commit_started(&self, _record: &DurableStarted) -> Result<(), LifecycleError> { + Ok(()) + } + + fn commit_result(&self, call_id: &str, result: &Value) -> Result { + #[cfg(any(test, feature = "workspace-io-fault"))] + if self.fail_next_commit.swap(false, Ordering::SeqCst) { + return Err(LifecycleError::ResultCommitFailed( + "injected durable commit failure".to_string(), + )); + } + self.commits.fetch_add(1, Ordering::SeqCst); + self.committed + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .insert(call_id.to_string(), result.clone()); + Ok(result.clone()) + } + + fn interrupt(&self, _call_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } +} + +/// One admitted call's authoritative RSS control root. +struct CallState { + cancellation: RunCancellation, + /// The transport request's cancellation source, retained from admission. + /// + /// Retaining it makes the publication fence observe the request token + /// itself: a cancellation that lands after admission's last check but + /// before the handler receives its select branch is already visible to + /// [`CallRegistry::call_state`], so no prepare or publication can slip + /// through in that window. + request_cancellation: Option, + /// Exact retry the guard retained when settlement could not close the + /// call. Keeping the call registered (and this disposition with it) is + /// what makes the executor shutdown retry the same token instead of + /// orphaning it. + retained_receipt: Mutex>, +} + +/// Disposition the shutdown retry must present for one retained call. +#[derive(Clone)] +enum RetryDisposition { + /// Reuse the exact receipt a retained decision returned. + Receipt(Box), + /// Settlement produced no decided receipt (it errored or retained before + /// binding one); the retry re-derives the authoritative receipt. + Derived, +} + +/// Active admitted calls, keyed by the exact bounded call identity. +struct CallRegistry { + entries: Mutex>>, + /// The terminal transport latch, installed once by the server. + /// + /// The publication fence reads it directly, so a call that was admitted + /// but is not (or not yet) cancel-requested still refuses to prepare once + /// protocol input became terminal. + gate: OnceLock>, +} + +impl CallRegistry { + fn new() -> Self { + Self { + entries: Mutex::new(HashMap::new()), + gate: OnceLock::new(), + } + } + + /// Installs the terminal input latch read by the publication fence. + fn set_gate(&self, gate: Arc) { + let _ = self.gate.set(gate); + } + + fn gate_latched(&self) -> bool { + self.gate + .get() + .is_some_and(|gate| gate.load(Ordering::SeqCst)) + } + + /// A snapshot of every registered call, used by the overflow latch to + /// cancel exactly the calls that were registered before it. + fn snapshot(&self) -> Vec<(String, Arc)> { + self.entries + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .iter() + .map(|(call_id, state)| (call_id.clone(), Arc::clone(state))) + .collect() + } + + fn insert(&self, call_id: String, state: Arc) { + self.entries + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .insert(call_id, state); + } + + fn remove(&self, call_id: &str) { + self.entries + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .remove(call_id); + } + + /// Records the retry a retained settlement must present. Returns false + /// when the call is no longer registered (another owner finished it). + fn retain_settlement(&self, call_id: &str, retry: RetryDisposition) -> bool { + let state = self + .entries + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .get(call_id) + .cloned(); + match state { + Some(state) => { + *state + .retained_receipt + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(retry); + true + } + None => false, + } + } + + /// Calls that still own a retained settlement retry. + fn retained_settlements(&self) -> Vec<(String, RetryDisposition)> { + let entries: Vec<(String, Arc)> = self + .entries + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .iter() + .map(|(call_id, state)| (call_id.clone(), Arc::clone(state))) + .collect(); + entries + .into_iter() + .filter_map(|(call_id, state)| { + state + .retained_receipt + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .clone() + .map(|retry| (call_id, retry)) + }) + .collect() + } + + /// Registered calls, whether their guard is still running or their + /// settlement was retained. Zero is required before a close may report + /// clean. + fn registered_count(&self) -> usize { + self.entries + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .len() + } + + fn cancel(&self, call_id: &str) -> bool { + let state = self + .entries + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .get(call_id) + .cloned(); + match state { + Some(state) => { + state + .cancellation + .request(crate::CancellationReason::Requested); + true + } + None => false, + } + } + + /// Whether the call's epoch watcher really advanced the VM epoch. + #[cfg(any(test, feature = "workspace-io-fault"))] + fn epoch_advanced(&self, call_id: &str) -> Option { + self.entries + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .get(call_id) + .map(|state| state.cancellation.epoch_advanced()) + } + + fn cancel_all(&self) { + let states: Vec> = self + .entries + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .values() + .cloned() + .collect(); + for state in states { + state + .cancellation + .request(crate::CancellationReason::Requested); + } + } +} + +impl CallCancellationSource for CallRegistry { + fn call_state(&self, call_id: &str) -> CallCancellationState { + // Terminal protocol input is a cancellation source of its own. It is + // read here, at the publication fence, so a call whose cancellation + // request has not reached the registry yet cannot prepare or publish + // after the reader queue overflowed. + if self.gate_latched() { + return CallCancellationState::Cancelled; + } + let state = self + .entries + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .get(call_id) + .cloned(); + match state { + Some(state) if state.cancellation.requested().is_some() => { + if state.cancellation.requested() == Some(crate::CancellationReason::Deadline) { + CallCancellationState::DeadlineElapsed + } else { + CallCancellationState::Cancelled + } + } + // The request token is a second, independent source. The handler + // may not have reached `cancel_call` yet, so the publication fence + // must read the token retained at admission directly. + Some(state) + if state + .request_cancellation + .as_ref() + .is_some_and(AdmissionCancellation::is_cancelled) => + { + CallCancellationState::Cancelled + } + Some(state) if state.cancellation.deadline_passed() => { + CallCancellationState::DeadlineElapsed + } + _ => CallCancellationState::Active, + } + } +} + +/// Executor-wide shutdown flag consumed by the lifecycle cancellation check. +struct ExecutorShutdownFlag(AtomicBool); + +impl crate::capabilities::CancellationFlag for ExecutorShutdownFlag { + fn is_cancelled(&self) -> bool { + self.0.load(Ordering::SeqCst) + } +} + +#[derive(Default)] +struct AdmissionState { + ids: HashSet, + admitted: u64, + /// Identities burned by a cancellation instead of an admission. They are + /// charged to the same lifetime quota as `admitted`, so sequential + /// cancel-then-call cycles cannot grow `ids` past the advertised bound. + retained_identities: u64, + closed: bool, + /// Cancellations recorded for call identities that have not reached + /// admission. `admit_call` consumes the entry under this same lock and + /// refuses before any prepare or effect, so a worker that starts after a + /// cancelled handler observed cancellation cannot run the call. + /// + /// An accepted intent is never erased by a failed attempt: a later valid + /// attempt with the same explicit identity must still be refused. It is + /// only consumed by admission (or counted as burned when it refuses the + /// call); reaching the ledger bound closes admission instead of dropping + /// one. + pre_admission_cancels: HashSet, +} + +struct AdmittedCall { + call_id: String, + state: Arc, +} + +/// Unregisters the call and settles its lifecycle token on every exit path, +/// including `?`/panic unwinding after admission. +/// +/// Every path calls [`CapabilityLifecycle::settle_call_terminal`]: the guard +/// either reuses the terminal decision `execute_tool` already took, or takes +/// the one decision here when unwinding never reached it. A retained decision +/// keeps the call registered with the exact disposition the decision returned +/// so shutdown retries the same call instead of orphaning a token. +struct ActiveCallGuard<'a> { + executor: &'a McpToolExecutor, + call_id: String, + receipt: Option, + /// Set when `execute_tool` already took the call-wide terminal decision. + settled: bool, + retained: usize, +} + +impl Drop for ActiveCallGuard<'_> { + fn drop(&mut self) { + if !self.settled { + // The synthetic candidate is part of the decision request, so the + // terminal function binds it to the ledger snapshot under the same + // critical section that reads it. A publisher that finishes after + // this decision can therefore only make the disposition stale, + // never inherit freshly published ledger bytes. + let fallback = json!(ToolResult::failure( + "internal_error", + "tool call ended without a canonical result", + )); + let settlement = match self.receipt.as_ref() { + Some(receipt) => self + .executor + .lifecycle + .settle_call_terminal(&self.call_id, CallTerminalRequest::Prepared(receipt)), + None => self + .executor + .lifecycle + .settle_call_terminal(&self.call_id, CallTerminalRequest::Synthetic(&fallback)), + }; + match settlement { + Ok(settlement) => { + self.retained = settlement.retained; + if let Some(receipt) = settlement.result { + self.receipt = Some(receipt); + } + } + Err(_) => { + // The decision owns the reopened token. Keep this call + // registered under an explicit retry disposition so + // shutdown retries it instead of dropping ownership. + self.retained = self.retained.max(1); + } + } + } + if self.retained == 0 { + self.executor.calls.remove(&self.call_id); + return; + } + let retry = match self.receipt.clone() { + Some(receipt) => RetryDisposition::Receipt(Box::new(receipt)), + None => RetryDisposition::Derived, + }; + self.executor.calls.retain_settlement(&self.call_id, retry); + } +} + +fn shared_registry_snapshot() -> Result<&'static ToolRegistrySnapshot, String> { + static SNAPSHOT: OnceLock> = OnceLock::new(); + SNAPSHOT + .get_or_init(|| { + crate::runtime::rss_runner::bundled_tool_registry() + .map(|registry| registry.snapshot()) + .map_err(|error| bounded(&error, MAX_ERROR_BYTES)) + }) + .as_ref() + .map_err(Clone::clone) +} + +fn shared_dispatch_runner() -> Result<&'static AgentRunner, String> { + static RUNNER: OnceLock> = OnceLock::new(); + RUNNER + .get_or_init(|| { + AgentRunner::from_bundled_provider_disabled( + "rss/tools/dispatch_entry.rss", + "run", + AgentConfig::default(), + ) + .map_err(|error| bounded(&error.to_string(), MAX_ERROR_BYTES)) + }) + .as_ref() + .map_err(Clone::clone) +} + +/// Acquires `mutex` without waiting beyond `cutoff`. +/// +/// Poisoned guards are recovered: teardown state is authoritative even after a +/// panicking owner. `None` means the absolute cutoff elapsed first. +fn lock_until<'a, T>(mutex: &'a Mutex, cutoff: Instant) -> Option> { + loop { + match mutex.try_lock() { + Ok(guard) => return Some(guard), + Err(TryLockError::Poisoned(poisoned)) => return Some(poisoned.into_inner()), + Err(TryLockError::WouldBlock) => { + let now = Instant::now(); + if now >= cutoff { + return None; + } + std::thread::sleep( + Duration::from_millis(1).min(cutoff.saturating_duration_since(now)), + ); + } + } + } +} + +/// Executor-wide shutdown state shared with the lifetime watchdog. The +/// watchdog holds only a `Weak` reference, so it can never keep the executor +/// alive and dropping/shutting down can always stop and join it. +struct ShutdownCore { + closed: AtomicBool, + shutdown_flag: Arc, + admission: Mutex, + calls: Arc, + processes: Arc, + /// The settlement owner retried by shutdown for retained calls. + lifecycle: Arc, + cleanup_timeout: Duration, + cleanup_proof: Mutex>, + /// Serializes concurrent teardowns so every attempt observes one complete + /// process-table proof instead of interleaving with another. + teardown: Mutex<()>, + /// Absolute teardown cutoff fixed by the first shutdown. Lock acquisition, + /// every retry, the destructor, the reaper and the stdin writer all share + /// this one instant instead of starting a fresh grace period. + cutoff: Mutex>, + /// Terminal transport latch, when this executor serves an MCP transport. + /// + /// Admission reads it under the admission lock: a worker that was queued + /// before the protocol input became terminal is refused even if it starts + /// before the watchdog's teardown closes admission. It is set once at + /// assembly and never replaced. + admission_gate: OnceLock>, + /// Test-only seam immediately before a proof candidate takes the proof + /// gate, so a test can pause a contender that already sampled ownership. + #[cfg(any(test, feature = "workspace-io-fault"))] + proof_observer: Mutex>>, +} + +/// Outcome of the retained-settlement pass that runs inside a teardown. +struct RetainedSettlement { + /// Calls that still own a token (running guard or retained receipt). + remaining_calls: usize, + /// A retained receipt's retry reached a durable owner conflict. + failed: bool, +} + +impl ShutdownCore { + /// Runs one bounded teardown and returns its typed proof. + /// + /// The latest outcome is cached for diagnostics. Every attempt retries the + /// settlement of a retained call under this teardown's ownership before the + /// cleanup outcome is published, so a retained token is never orphaned. + fn shutdown(&self) -> ProcessCleanupProof { + self.closed.store(true, Ordering::SeqCst); + self.shutdown_flag.0.store(true, Ordering::SeqCst); + // The clock starts before the teardown mutex: waiting for a concurrent + // owner is part of the same cleanup budget, and every retry (including + // the destructor's) reuses the first absolute cutoff rather than + // starting a fresh grace period. + let cutoff = { + let mut stored = self + .cutoff + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + *stored.get_or_insert_with(|| { + Instant::now() + .checked_add(self.cleanup_timeout) + .unwrap_or_else(Instant::now) + }) + }; + // Hand one absolute cutoff to the process table and every retained + // participant before the teardown mutex is acquired. A lock timeout, a + // closing reaper, an interrupted stdin writer, a token settlement and a + // spawn converted while closing all share this same deadline instead of + // starting a fresh ordinary grace after the lock or after cancel_all. + self.processes.begin_shutdown_with(cutoff); + let Some(_teardown) = lock_until(&self.teardown, cutoff) else { + let proof = ProcessCleanupProof::TimedOut { + // A contender that could not acquire the teardown gate still + // observes the ownership it leaves behind. Registered calls + // include running guards and retained receipts; omitting them + // would let this attempt publish a lower count than the owner + // it failed to join. + retained: self.retained_records() + self.calls.registered_count(), + }; + // The returned value and the published proof are the same merged + // decision. A contender that lost the gate to an owner which then + // proved Clean must observe that Clean, not its own stale timeout. + return self.record_proof(proof); + }; + { + let mut admission = self + .admission + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + admission.closed = true; + // A worker that has not reached admission will observe `closed` + // before prepare; the recorded intents are no longer needed. + admission.pre_admission_cancels.clear(); + } + self.calls.cancel_all(); + let process_proof = if self + .cleanup_proof + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .as_ref() + .is_some_and(ProcessCleanupProof::is_clean) + && self.processes.table_len() == 0 + && self.processes.active_stdin_workers() == 0 + { + ProcessCleanupProof::Clean + } else { + self.processes.shutdown_all_within(cutoff) + }; + let proof = self.finish_with_retained_settlements(process_proof); + self.record_proof(proof) + } + + /// Retries every retained settlement under this teardown's single owner, + /// then combines the process proof with the settlement ownership that is + /// still live. A call whose guard is still running also keeps the close + /// non-clean: its token has not been settled yet. + fn finish_with_retained_settlements(&self, proof: ProcessCleanupProof) -> ProcessCleanupProof { + let settlement = self.retry_retained_settlements(); + let extra = settlement.remaining_calls; + match proof { + ProcessCleanupProof::Failed { retained, code } => ProcessCleanupProof::Failed { + retained: retained.saturating_add(extra), + code, + }, + ProcessCleanupProof::TimedOut { retained } => ProcessCleanupProof::TimedOut { + retained: retained.saturating_add(extra), + }, + ProcessCleanupProof::Clean if settlement.failed => ProcessCleanupProof::Failed { + retained: extra, + code: "settlement_failed".to_string(), + }, + ProcessCleanupProof::Clean if extra > 0 => { + ProcessCleanupProof::TimedOut { retained: extra } + } + ProcessCleanupProof::Clean => ProcessCleanupProof::Clean, + } + } + + /// One bounded settlement retry for every call that retained a receipt, + /// followed by the live registered count. A successful retry unregisters + /// the call; a still-retained or conflicting settlement keeps it owned. + fn retry_retained_settlements(&self) -> RetainedSettlement { + let mut failed = false; + for (call_id, retry) in self.calls.retained_settlements() { + match self.settle_retained_call(&call_id, &retry) { + Ok(true) => self.calls.remove(&call_id), + Ok(false) => {} + Err(_) => failed = true, + } + } + RetainedSettlement { + remaining_calls: self.calls.registered_count(), + failed, + } + } + + /// The bounded terminal-disposition attempt for one retained call. + /// + /// A receipt disposition is retried first because it is the only payload + /// the caller observed. If a publisher advanced the ledger past that + /// snapshot, the same call-wide terminal function is asked once more with + /// a live derivation. A call retained without a decided receipt is + /// re-derived directly. A call whose publisher never produced an effect + /// has nothing to derive: that second decision interrupts its open tokens + /// so the retained call reaches an explicit indeterminate terminal state + /// instead of being retried forever. Settlement is idempotent once a call + /// committed, so no attempt can write a second durable result. + fn settle_retained_call( + &self, + call_id: &str, + retry: &RetryDisposition, + ) -> Result { + if let RetryDisposition::Receipt(receipt) = retry { + let retried = self + .lifecycle + .settle_call_terminal(call_id, CallTerminalRequest::Prepared(receipt))?; + if retried.retained == 0 { + return Ok(true); + } + } + let fresh = self + .lifecycle + .settle_call_terminal(call_id, CallTerminalRequest::Derived)?; + Ok(fresh.retained == 0) + } + + /// Records the latest combined teardown outcome under the one proof gate. + /// + /// Teardown ownership can grow after an earlier clean pass (a call guard + /// may still settle a token), and a contender that lost the teardown lock + /// still observed registered calls. A `TimedOut` candidate's retained + /// count is re-sampled here, under the proof gate itself, so a contender + /// that paused between observation and publication cannot overwrite a + /// proven `Clean` with a stale nonzero count. A proven `Clean` otherwise + /// survives every pending observation. + fn record_proof(&self, proof: ProcessCleanupProof) -> ProcessCleanupProof { + #[cfg(any(test, feature = "workspace-io-fault"))] + let observer = self + .proof_observer + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .clone(); + #[cfg(any(test, feature = "workspace-io-fault"))] + if let Some(observer) = observer { + observer(); + } + let mut stored = self + .cleanup_proof + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let proof = match proof { + ProcessCleanupProof::TimedOut { .. } => ProcessCleanupProof::TimedOut { + retained: self.retained_records() + self.calls.registered_count(), + }, + other => other, + }; + let merged = match stored.take() { + None => proof, + Some(previous) => merge_cleanup_proofs(previous, proof), + }; + *stored = Some(merged.clone()); + merged + } + + fn retained_records(&self) -> usize { + self.processes.table_len() + self.processes.active_stdin_workers() + } + + /// Last typed teardown outcome, if a teardown already ran. + fn cleanup_outcome(&self) -> Option { + self.cleanup_proof + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .clone() + } +} + +/// Conservative merge of two teardown proofs observed under different +/// ownership. Failure outranks every other result, retained counts combine by +/// maximum, and Clean survives unless the candidate observed retained work. +fn merge_cleanup_proofs( + previous: ProcessCleanupProof, + candidate: ProcessCleanupProof, +) -> ProcessCleanupProof { + match (previous, candidate) { + ( + ProcessCleanupProof::Failed { retained: a, code }, + ProcessCleanupProof::Failed { retained: b, .. }, + ) => ProcessCleanupProof::Failed { + retained: a.max(b), + code, + }, + (ProcessCleanupProof::Failed { retained, code }, other) => ProcessCleanupProof::Failed { + retained: retained.max(retained_of(&other)), + code, + }, + (other, ProcessCleanupProof::Failed { retained, code }) => ProcessCleanupProof::Failed { + retained: retained_of(&other).max(retained), + code, + }, + (ProcessCleanupProof::Clean, ProcessCleanupProof::Clean) => ProcessCleanupProof::Clean, + // A proven Clean is terminal: a later pending observation sampled its + // retained state before it owned the proof gate and must not replace + // evidence that the whole teardown already completed. + (ProcessCleanupProof::Clean, ProcessCleanupProof::TimedOut { .. }) => { + ProcessCleanupProof::Clean + } + (ProcessCleanupProof::TimedOut { .. }, ProcessCleanupProof::Clean) => { + // A later owner proved the whole cleanup; that is stronger than + // the earlier pending observation. + ProcessCleanupProof::Clean + } + ( + ProcessCleanupProof::TimedOut { retained: a }, + ProcessCleanupProof::TimedOut { retained: b }, + ) => ProcessCleanupProof::TimedOut { retained: a.max(b) }, + } +} + +fn retained_of(proof: &ProcessCleanupProof) -> usize { + match proof { + ProcessCleanupProof::Clean => 0, + ProcessCleanupProof::TimedOut { retained } + | ProcessCleanupProof::Failed { retained, .. } => *retained, + } +} + +/// One bounded lifetime watchdog. It owns no executor state: the worker holds +/// only a `Weak` and a stop condvar, so the destructor or an +/// explicit shutdown can always stop and join it without leaking a thread. +struct IdleWatchdog { + stop: Arc<(Mutex, std::sync::Condvar)>, + handle: Option>, +} + +impl IdleWatchdog { + fn spawn(core: std::sync::Weak, lifetime: Duration) -> std::io::Result { + let stop = Arc::new((Mutex::new(false), std::sync::Condvar::new())); + let signal = Arc::clone(&stop); + let handle = std::thread::Builder::new() + .name("mcp-executor-lifetime".to_string()) + .spawn(move || { + let (lock, condvar) = &*signal; + let deadline = Instant::now() + lifetime; + let mut stopped = lock.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + while !*stopped { + let now = Instant::now(); + if now >= deadline { + break; + } + let (guard, _) = condvar + .wait_timeout(stopped, deadline.saturating_duration_since(now)) + .unwrap_or_else(|poisoned| poisoned.into_inner()); + stopped = guard; + } + let expired = !*stopped; + drop(stopped); + if expired && let Some(core) = core.upgrade() { + // This is the configured lifetime boundary itself: an idle + // executor with owned children cancels admissions and + // performs bounded process cleanup without any later call. + let _ = core.shutdown(); + } + })?; + Ok(Self { + stop, + handle: Some(handle), + }) + } + + fn stop_and_join(&mut self) { + let (lock, condvar) = &*self.stop; + *lock.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = true; + condvar.notify_all(); + let Some(handle) = self.handle.take() else { + return; + }; + if handle.thread().id() == std::thread::current().id() { + // The watchdog itself reached the lifetime boundary; letting the + // already-returning thread finish is harmless and avoids + // self-join. + drop(handle); + } else { + let _ = handle.join(); + } + } +} + +/// One executor rooted at a validated canonical workspace. +pub struct McpToolExecutor { + workspace: PathBuf, + profile: ToolProfile, + registry: ToolRegistrySnapshot, + runner: AgentRunner, + host: AgentHostBridges, + /// Test-only observation point after a successful durable `tool_commit` + /// and before the guest receives the commit result. + #[cfg(any(test, feature = "workspace-io-fault"))] + commit_observer: Mutex>, + /// Test-only observation point at the very start of `execute_tool`, + /// before admission. Lets a test hold a queued worker and cancel it while + /// it has no call state yet. + #[cfg(any(test, feature = "workspace-io-fault"))] + pre_admission_observer: Mutex>, + /// Test-only observation point inside `admit_call` while the admission + /// lock is held, before any cancellation source is consulted. + #[cfg(any(test, feature = "workspace-io-fault"))] + admission_observer: Mutex>, + dispatch_config: Value, + owner: CapabilityOwner, + lifecycle: Arc, + /// Test-only handle to the executor's real durable boundary. + #[cfg(any(test, feature = "workspace-io-fault"))] + durable: Arc, + calls: Arc, + processes: Arc, + clock: Arc, + deadline_ms: u64, + max_tool_calls: u64, + call_timeout: Duration, + /// Executor-scoped MCP call identity sequence. Sharing it here means two + /// server wrappers over one executor cannot allocate the same identity. + call_sequence: AtomicU64, + #[cfg(any(test, feature = "workspace-io-fault"))] + epoch_check_interval_for_test: Option, + core: Arc, + watchdog: Mutex>, +} + +impl McpToolExecutor { + /// Validates the workspace and constructs the shared registry, dispatch + /// program, lifecycle, and capability hosts for one server lifetime. + pub fn new(config: McpToolExecutorConfig) -> Result { + Self::new_with_optional_workspace_hook(config, None) + } + + /// Test seam for the workspace-adoption race: `workspace_hook` runs after + /// the filesystem capability adopted the authoritative retained root and + /// before the process capability adopts the same root. Production callers + /// use [`Self::new`] and never install a hook. + pub fn new_with_workspace_hook( + config: McpToolExecutorConfig, + workspace_hook: Arc, + ) -> Result { + Self::new_with_optional_workspace_hook(config, Some(workspace_hook)) + } + + fn new_with_optional_workspace_hook( + config: McpToolExecutorConfig, + workspace_hook: Option>, + ) -> Result { + let workspace = validate_workspace(&config.workspace_root)?; + validate_config_numbers(&config)?; + + let registry = shared_registry_snapshot() + .map_err(|message| McpToolExecutorError::RegistryUnavailable { message })? + .clone(); + let runner = shared_dispatch_runner() + .map_err(|message| McpToolExecutorError::DispatchUnavailable { message })? + .clone(); + + let max_output_bytes = config.max_output_bytes.clamp(1, MAX_TOOL_OUTPUT_BYTES); + let mut file_config = FileToolConfig::for_workspace(workspace.clone()); + file_config.apply_admitted_output_cap(max_output_bytes); + file_config + .validate() + .map_err(|message| McpToolExecutorError::InvalidConfig { + message: bounded(&message, MAX_ERROR_BYTES), + })?; + let mut process_config = ProcessToolConfig::for_workspace(workspace.clone()); + process_config.max_processes = config.max_processes; + process_config.max_processes_per_owner = config.max_processes_per_owner; + process_config.cleanup_timeout = config.process_cleanup_timeout; + process_config.apply_admitted_output_cap(max_output_bytes); + let process_config = + process_config + .validated() + .map_err(|message| McpToolExecutorError::InvalidConfig { + message: bounded(&message, MAX_ERROR_BYTES), + })?; + + let owner = + CapabilityOwner::new(MCP_PROFILE_LABEL, config.session_id.clone(), MCP_RUN_LABEL) + .map_err(|message| McpToolExecutorError::InvalidConfig { + message: bounded(&message, MAX_ERROR_BYTES), + })?; + let clock: Arc = Arc::new(SystemClock); + let calls = Arc::new(CallRegistry::new()); + let shutdown_flag = Arc::new(ExecutorShutdownFlag(AtomicBool::new(false))); + let lifetime_ms = positive_duration_ms(config.server_lifetime); + let deadline_ms = SystemClock.now_ms().saturating_add(lifetime_ms); + let durable = Arc::new(InMemoryDurableLifecycle::new()); + let lifecycle = CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity(registry.identity()) + .workspace(workspace.clone()) + .limits(LifecycleLimits { + max_tool_calls: config.max_tool_calls, + max_output_bytes, + max_summary_bytes: 4096, + }) + .deadline_ms(deadline_ms) + .clock(Arc::clone(&clock)) + .tokens(Arc::new(UuidIssuer)) + .durable(Arc::clone(&durable) as Arc) + .approval(Arc::new(crate::capabilities::AllowAllApproval)) + .cancellation( + Arc::clone(&shutdown_flag) as Arc + ) + .call_cancellation(Arc::clone(&calls) as Arc) + // This executor settles every call through `ActiveCallGuard`; a + // per-run host-state abort lease must never interrupt a published + // effect before that guard commits its canonical receipt. + .defer_lease_abort(true) + // This executor settles published effects through the exact + // receipt its `ActiveCallGuard` returns. Published-token retention + // is MCP-only; the managed/agent-run default keeps base abort + // semantics. + .published_token_policy(PublishedTokenPolicy::RetainForSettlement) + .build() + .map_err(|error| McpToolExecutorError::CapabilityUnavailable { + code: error.code().to_string(), + message: bounded(&error.message(), MAX_ERROR_BYTES), + })?; + let lifecycle = Arc::new(lifecycle); + + // One authoritative retained workspace root for every capability. Both + // filesystem and process adopt this descriptor; neither reopens the + // workspace pathname, so a replacement between the two construction + // steps cannot split their identities. + let workspace_root = Arc::new( + ConfinedFsRoot::with_limits( + &workspace, + ConfinedFsLimits { + max_read_bytes: MAX_READ_BYTES, + max_write_bytes: file_config.max_write_bytes.min(MAX_WRITE_BYTES), + max_entries: MAX_ENUM_ENTRIES, + max_entry_name_bytes: MAX_COMPONENT_BYTES, + max_temp_attempts: 32, + }, + ) + .map_err(|error| McpToolExecutorError::CapabilityUnavailable { + code: "workspace_denied".to_string(), + message: bounded(&error.to_string(), MAX_ERROR_BYTES), + })?, + ); + let filesystem = FilesystemCapability::new_with_root( + lifecycle.as_ref().clone(), + owner.clone(), + FilesystemLimits { + max_read_bytes: file_config.max_read_bytes, + max_write_bytes: file_config.max_write_bytes, + max_list_entries: file_config.max_search_files.max(1), + }, + &workspace_root, + ) + .map_err(|error| McpToolExecutorError::CapabilityUnavailable { + code: error.code().to_string(), + message: bounded(error.message(), MAX_ERROR_BYTES), + })?; + if let Some(hook) = &workspace_hook { + hook(); + } + let processes = Arc::new( + ProcessCapability::new_with_table_limits_and_root( + lifecycle.as_ref().clone(), + owner.clone(), + ProcessLimits { + timeout_ms: u64::try_from(process_config.max_timeout.as_millis()) + .unwrap_or(u64::MAX), + stdout_limit: process_config.max_stream_bytes, + stderr_limit: process_config.max_stream_bytes, + total_limit: process_config.max_stream_bytes, + stdin_limit: process_config.max_stdin_bytes, + log_limit: process_config.max_output_bytes.max(1), + close_after_initial: false, + }, + ProcessTableLimits::new( + process_config.max_processes, + process_config.max_processes_per_owner, + process_config.cleanup_timeout, + ) + .map_err(|error| McpToolExecutorError::CapabilityUnavailable { + code: error.code().to_string(), + message: bounded(error.message(), MAX_ERROR_BYTES), + })?, + &workspace_root, + ) + .map_err(|error| McpToolExecutorError::CapabilityUnavailable { + code: error.code().to_string(), + message: bounded(error.message(), MAX_ERROR_BYTES), + })?, + ); + if config.exec_gate { + // The packaged `tools serve` process ends in `std::process::exit`, + // so every process tool spawns through the pre-exec gate that + // cannot run tool code before its pid is in the spawn registry. + processes.enable_exec_gate(); + } + let artifacts = ArtifactCapability::new( + lifecycle.as_ref().clone(), + owner.clone(), + ArtifactLimits { + max_object_bytes: file_config.artifact_store.max_object_bytes, + max_total_bytes: file_config.artifact_store.max_total_bytes, + max_objects: file_config.artifact_store.max_objects.max(1), + }, + ) + .map_err(|error| McpToolExecutorError::CapabilityUnavailable { + code: error.code().to_string(), + message: bounded(error.message(), MAX_ERROR_BYTES), + })?; + + let host = AgentHostBridges { + lifecycle: Some(Arc::clone(&lifecycle)), + capability_owner: Some(owner.clone()), + filesystem: Some(Arc::new(filesystem)), + processes: Some(Arc::clone(&processes)), + artifacts: Some(Arc::new(artifacts)), + ..AgentHostBridges::default() + }; + let dispatch_config = + build_dispatch_config(&workspace, &file_config, &process_config, max_output_bytes); + let core = Arc::new(ShutdownCore { + closed: AtomicBool::new(false), + shutdown_flag, + admission: Mutex::new(AdmissionState::default()), + calls: Arc::clone(&calls), + processes: Arc::clone(&processes), + lifecycle: Arc::clone(&lifecycle), + cleanup_timeout: config.process_cleanup_timeout, + cleanup_proof: Mutex::new(None), + teardown: Mutex::new(()), + cutoff: Mutex::new(None), + admission_gate: OnceLock::new(), + #[cfg(any(test, feature = "workspace-io-fault"))] + proof_observer: Mutex::new(None), + }); + let watchdog = IdleWatchdog::spawn(Arc::downgrade(&core), config.server_lifetime).map_err( + |error| McpToolExecutorError::InvalidConfig { + message: bounded( + &format!("executor lifetime watchdog could not start: {error}"), + MAX_ERROR_BYTES, + ), + }, + )?; + + Ok(Self { + workspace, + profile: config.profile, + registry, + runner, + host, + #[cfg(any(test, feature = "workspace-io-fault"))] + commit_observer: Mutex::new(None), + #[cfg(any(test, feature = "workspace-io-fault"))] + pre_admission_observer: Mutex::new(None), + #[cfg(any(test, feature = "workspace-io-fault"))] + admission_observer: Mutex::new(None), + dispatch_config, + owner, + lifecycle, + #[cfg(any(test, feature = "workspace-io-fault"))] + durable, + calls, + processes, + clock, + deadline_ms, + max_tool_calls: config.max_tool_calls, + call_timeout: config.call_timeout, + call_sequence: AtomicU64::new(0), + #[cfg(any(test, feature = "workspace-io-fault"))] + epoch_check_interval_for_test: config.epoch_check_interval_for_test, + core, + watchdog: Mutex::new(Some(watchdog)), + }) + } + + /// Canonical workspace root bound to every capability. + pub fn workspace(&self) -> &Path { + &self.workspace + } + + /// Selected tool exposure profile. + pub fn profile(&self) -> ToolProfile { + self.profile + } + + /// Deterministic admitted registry identity frozen at construction. + pub fn registry_identity(&self) -> &str { + self.registry.identity() + } + + /// Frozen admitted registry snapshot. + pub fn registry(&self) -> &ToolRegistrySnapshot { + &self.registry + } + + /// True after [`Self::shutdown`] or the first process-table teardown. + pub fn is_closed(&self) -> bool { + self.core.closed.load(Ordering::Acquire) + } + + /// Installs the transport's terminal-input latch for this executor. + /// + /// The latch is supplied by the MCP server and set only on a terminal + /// reader-queue overflow. Admission consults it under the admission lock, + /// so a request queued before the overflow is refused even when its worker + /// runs before the watchdog's teardown does. The first latch wins; later + /// calls are ignored because every server view shares the same executor. + /// The registry receives the same latch so the publication fence reads it. + pub fn set_admission_gate(&self, gate: Arc) { + self.calls.set_gate(Arc::clone(&gate)); + let _ = self.core.admission_gate.set(gate); + } + + /// Whether the terminal transport latch has closed. + /// + /// Callers must hold the admission lock for this to be a linearizable + /// check against registration. + fn gate_latched(&self) -> bool { + self.core + .admission_gate + .get() + .is_some_and(|gate| gate.load(Ordering::SeqCst)) + } + + /// Requests cancellation of every admitted call without closing admission + /// or the executor. + /// + /// The server calls this when protocol input becomes terminal: in-flight + /// work stops at its next cancellation check and at the publication + /// fence, while queued work is refused by the admission gate. + /// + /// The snapshot is taken under the admission lock, the same lock that + /// registration holds across its final gate check. A call is therefore + /// either registered before this snapshot (and is cancelled here) or + /// observes the closed latch at registration (and is refused); there is no + /// window in which a worker registers after the gate check and escapes + /// both. The lifecycle is told too, so a call that has not prepared yet is + /// recorded against its prepare fence. + pub fn cancel_active_calls(&self) { + let admission = self + .core + .admission + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + // Re-store the one-way latch under the same lock that registration + // holds: a worker that already passed its gate read cannot register + // unseen, and a worker that has not yet read it sees the closed latch. + if let Some(gate) = self.core.admission_gate.get() { + gate.store(true, Ordering::SeqCst); + } + let calls = self.calls.snapshot(); + for (call_id, state) in calls { + state + .cancellation + .request(crate::CancellationReason::Requested); + self.lifecycle.request_call_cancellation(&call_id); + } + drop(admission); + } + + /// Provider access policy of the frozen dispatch runner. + pub fn provider_mode(&self) -> ProviderMode { + self.runner.provider_mode() + } + + /// Calls admitted against the hard lifetime quota. + pub fn admitted_call_count(&self) -> u64 { + self.core + .admission + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .admitted + } + + /// Allocates the next executor-scoped MCP call identity. + /// + /// The sequence is shared by every server wrapper over this executor, so + /// two `RustScriptToolServer::from_executor` instances cannot collide. + pub fn next_call_id(&self) -> String { + format!( + "mcp-call-{}", + self.call_sequence.fetch_add(1, Ordering::Relaxed) + ) + } + + /// One shared teardown deadline for owned children. + pub fn cleanup_timeout(&self) -> Duration { + self.core.cleanup_timeout + } + + /// Absolute teardown cutoff fixed by the first [`Self::shutdown`], if one + /// already started. Callers can derive their own bounded waits from it. + pub fn cleanup_cutoff(&self) -> Option { + *self + .core + .cutoff + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + } + + /// Call identities retained for duplicate detection. + pub fn retained_call_id_count(&self) -> usize { + self.core + .admission + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .ids + .len() + } + + /// Test-only: cancellation intents that have not been consumed by + /// admission yet. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn pending_pre_admission_cancellations_for_test(&self) -> usize { + self.core + .admission + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .pre_admission_cancels + .len() + } + + /// Live process records currently retained by the shared process table. + pub fn process_table_len(&self) -> usize { + self.processes.table_len() + } + + /// Test-only: absolute cleanup cutoff visible to the process capability. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn process_cleanup_cutoff_for_test(&self) -> Option { + self.processes.cleanup_cutoff_for_test() + } + + /// Test-only: absolute teardown cutoff fixed by the first shutdown. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn executor_cleanup_cutoff_for_test(&self) -> Option { + *self + .core + .cutoff + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + } + + /// Test-only: retained handles whose initial-stdin writer is still stalled. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn pending_initial_stdin_writers_for_test(&self) -> usize { + self.processes.pending_initial_stdin_writers_for_test() + } + + /// Open native execution tokens (settlement diagnostic). + pub fn open_token_count(&self) -> usize { + self.lifecycle.open_token_count() + } + + /// Test-only: this executor is the MCP owner that retains published tokens + /// for canonical settlement. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn retains_published_tokens_for_test(&self) -> bool { + self.lifecycle.retains_published_tokens() + } + + /// Tokens settled by a canonical committed receipt (diagnostic). + pub fn committed_token_count(&self) -> usize { + self.lifecycle.committed_token_count() + } + + /// Tokens interrupted without a committed receipt (diagnostic). + pub fn interrupted_token_count(&self) -> usize { + self.lifecycle.interrupted_token_count() + } + + /// Cancels one call, durably. + /// + /// The lifecycle fence is updated first, so a cancellation that races an + /// irreversible publication is linearized against it: a not-yet-published + /// call is refused, while an already publishing/published call keeps its + /// right to settle the receipt and only its later operations are stopped. + /// + /// The admission ledger then records the intent under the admission lock. + /// If the call is still queued (or its blocking worker has not reached + /// admission), the cancellation is stored rather than dropped, and + /// [`Self::execute_tool`] refuses the call with + /// [`McpToolExecutorError::Cancelled`] before prepare or any effect. That + /// makes cancellation independent of the handler's bounded wait. + /// + /// The lifecycle gate is updated after the admission lock is released. It + /// is call-scoped and never takes that lock, so it can wait at most for + /// this call's own prepare boundary and can never block admission, another + /// call's prepare or another call's cancellation behind durable I/O. + pub fn cancel_call(&self, call_id: &str) -> bool { + let mut admission = self + .core + .admission + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if admission.ids.contains(call_id) { + // Already admitted in this lifetime. Record the cancellation in the + // call registry while still holding the same admission lock that + // registered the call, so admission and cancellation cannot + // interleave: a prepare that observes the admitted call also + // observes this cancellation before it can publish. + let signalled = self.calls.cancel(call_id); + drop(admission); + // The lifecycle ledger is updated outside the admission lock: a + // durable prepare of THIS call may be in flight, but no other call + // waits on it and admission stays free. + let fenced = self.lifecycle.request_call_cancellation(call_id); + return signalled || fenced; + } + if admission.closed || self.core.closed.load(Ordering::SeqCst) { + return false; + } + // An identity that cannot be admitted cannot be cancelled durably; + // admission will reject it before any effect anyway. + if validate_call_id(call_id).is_err() { + return false; + } + if admission.pre_admission_cancels.len() >= MAX_PRE_ADMISSION_CANCELLATIONS { + // Never forget an accepted cancellation: stop admitting new work + // so no later worker can execute a call whose intent was dropped. + admission.closed = true; + self.core.closed.store(true, Ordering::SeqCst); + self.core.shutdown_flag.0.store(true, Ordering::SeqCst); + return false; + } + admission.pre_admission_cancels.insert(call_id.to_string()); + true + } + + /// Test-only: whether the admitted call's epoch watcher acknowledged the + /// VM epoch jump. Releasing a synchronous artifact gate before this is true + /// races the watcher and can let the guest reach `tool_commit`. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn call_epoch_advanced_for_test(&self, call_id: &str) -> Option { + self.calls.epoch_advanced(call_id) + } + + /// Stops admitting calls, cancels every in-flight call, and terminates + /// every process owned by this executor under one cleanup deadline. + /// + /// Returns the typed cleanup proof for that teardown. A non-clean proof + /// retains ownership of every record it could not prove, so a later call + /// may retry; a clean proof short-circuits repeat calls. + pub fn shutdown(&self) -> ProcessCleanupProof { + let proof = self.core.shutdown(); + if let Some(mut watchdog) = self + .watchdog + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .take() + { + watchdog.stop_and_join(); + } + proof + } + + /// Last typed teardown outcome, if a teardown already ran. + pub fn cleanup_outcome(&self) -> Option { + self.core.cleanup_outcome() + } + + /// Test-only: deterministically withhold the process cleanup proof. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn withhold_process_cleanup_proof_for_test(&self) { + self.processes.withhold_cleanup_proof_for_test(); + } + + /// Test-only: allow the process cleanup proof again for a retry. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn allow_process_cleanup_proof_for_test(&self) { + self.processes.allow_cleanup_proof_for_test(); + } + + /// Test-only: the shared filesystem capability owned by this executor. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn filesystem_for_test(&self) -> &Arc { + self.host + .filesystem + .as_ref() + .expect("executor always installs a filesystem capability") + } + + /// Test-only: the shared artifact capability owned by this executor. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn artifacts_for_test(&self) -> &Arc { + self.host + .artifacts + .as_ref() + .expect("executor always installs an artifact capability") + } + + /// Test-only: the lifecycle this executor settles every call through. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn lifecycle_for_test(&self) -> &Arc { + &self.lifecycle + } + + /// Test-only: number of durable `commit_result` writes this executor's + /// durable boundary acknowledged. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn durable_commit_count_for_test(&self) -> usize { + self.durable.commit_count() + } + + /// Test-only: number of durable `prepare_parent` acknowledgements. A + /// cancelled call must not reach this prepare boundary; the commit count + /// alone cannot prove that. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn durable_prepare_count_for_test(&self) -> usize { + self.durable.prepare_count() + } + + /// Test-only: run the same bounded retained-settlement retry teardown uses. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn settle_retained_for_test(&self) { + let _ = self.core.retry_retained_settlements(); + } + + /// Test-only: observe a successful durable commit before the guest resumes. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn set_commit_observer_for_test(&self, observer: CommitObserver) { + *self + .commit_observer + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(observer); + } + + /// Test-only: run `observer` at the start of `execute_tool`, before the + /// call reaches admission. Production callers never install it. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn set_pre_admission_observer_for_test(&self, observer: Arc) { + *self + .pre_admission_observer + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(observer); + } + + /// Test-only: run `observer` while `admit_call` holds the admission lock, + /// before the pre-admission intent and the request-scoped cancellation + /// source are consulted. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn set_admission_observer_for_test(&self, observer: Arc) { + *self + .admission_observer + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(observer); + } + + /// Test-only: identities burned by a cancellation rather than admitted. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn retained_identity_count_for_test(&self) -> u64 { + self.core + .admission + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .retained_identities + } + + /// Test-only: read back the durable payload committed for `call_id`. + /// + /// This is the only accessor that reads the durable commit itself. An + /// assertion made through it proves that the settlement path wrote the + /// snapshot; a ledger-derived receipt cannot satisfy the readback. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn durable_committed_receipt_for_test(&self, call_id: &str) -> Option { + let committed = self.lifecycle.committed_result(call_id).ok().flatten()?; + serde_json::from_value(committed).ok() + } + + /// Test-only: read back the settled receipt for `call_id`, preferring a + /// durable guest commit and otherwise falling back to the native ledger. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn committed_receipt_for_test(&self, call_id: &str) -> Option { + self.settlement_receipt(call_id) + .ok() + .flatten() + .map(|receipt| receipt.result().clone()) + } + + /// Test-only: reject the next durable `commit_result` at the real + /// `DurableToolLifecycle` boundary. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn fail_next_durable_commit_for_test(&self) { + self.durable.fail_next_commit(); + } + + /// Test-only: the shared process capability owned by this executor. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn processes_for_test(&self) -> &Arc { + &self.processes + } + + /// Test-only: the absolute cutoff that the interrupted stdin worker of + /// `handle` actually used for its bounded close join. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn stdin_worker_cutoff_for_test(&self, handle: &str) -> Option { + self.processes.stdin_close_cutoff_for_test(handle) + } + + /// Test-only: hold the teardown mutex to measure lock acquisition against + /// the absolute cleanup budget. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn hold_teardown_for_test(&self) -> MutexGuard<'_, ()> { + self.core + .teardown + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + } + + /// Executes one admitted tool through the existing bundled RSS dispatch. + /// + /// `call_id` is the MCP request identity when the transport exposes one. + /// `None` generates a bounded unique id. The identity must be used at most + /// once per executor lifetime. + pub fn execute_tool( + &self, + call_id: Option<&str>, + tool_name: &str, + arguments: &Value, + ) -> Result { + self.execute_tool_with_cancellation(call_id, tool_name, arguments, None) + } + + /// Executes one tool while observing a request-scoped cancellation source + /// at admission. + /// + /// The source is checked inside `admit_call` under the admission lock, + /// both before and after the call is registered. A request cancelled while + /// its blocking worker is queued can therefore never admit or prepare an + /// effect, even when the cancellation reaches the source only after the + /// first check. + pub fn execute_tool_with_cancellation( + &self, + call_id: Option<&str>, + tool_name: &str, + arguments: &Value, + request_cancellation: Option, + ) -> Result { + if self.is_closed() { + return Err(McpToolExecutorError::Closed); + } + #[cfg(any(test, feature = "workspace-io-fault"))] + { + let observer = self + .pre_admission_observer + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .clone(); + if let Some(observer) = observer { + observer(call_id.unwrap_or("")); + } + } + let descriptor = match self.registry.descriptor(tool_name) { + Some(descriptor) => descriptor, + None => { + return Err(McpToolExecutorError::UnknownTool { + name: diagnostic_text(tool_name, 128), + }); + } + }; + if !self.profile.admits_descriptor(descriptor) { + return Err(McpToolExecutorError::DisabledTool { + name: descriptor.name.clone(), + risk_class: descriptor.risk_class.clone(), + }); + } + if !arguments.is_object() { + return Err(McpToolExecutorError::InvalidArguments { + message: "tool arguments must be a JSON object".to_string(), + }); + } + if let Err(message) = self.registry.validate_arguments(tool_name, arguments) { + return Err(McpToolExecutorError::InvalidArguments { message }); + } + + let admitted = self.admit_call(call_id, request_cancellation.as_ref())?; + let mut guard = ActiveCallGuard { + executor: self, + call_id: admitted.call_id.clone(), + receipt: None, + settled: false, + retained: 0, + }; + let input = json!({ + "call": { + "id": admitted.call_id, + "name": tool_name, + "arguments": arguments, + }, + "registry": self.registry.schemas(), + "registry_identity": self.registry.identity(), + "run_id": self.owner.run(), + "config": self.dispatch_config, + }); + let cancellation = admitted.state.cancellation.clone(); + let mut sink = DiscardSink; + #[cfg_attr(not(any(test, feature = "workspace-io-fault")), allow(unused_mut))] + let mut host = self.host.clone(); + #[cfg(any(test, feature = "workspace-io-fault"))] + { + host.commit_observer = self + .commit_observer + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .clone(); + } + #[cfg_attr(not(any(test, feature = "workspace-io-fault")), allow(unused_mut))] + let mut runner = self.runner.clone(); + #[cfg(any(test, feature = "workspace-io-fault"))] + if let Some(interval) = self.epoch_check_interval_for_test { + runner = runner.with_epoch_check_interval_for_test(interval); + } + let output = runner.with_host(host).run_with_context_and_events( + json_to_vm_value(&input), + &mut sink, + &cancellation, + ); + match output { + Ok(output) => match canonical_dispatch_outcome(&vm_value_to_json(&output))? { + DispatchOutcome::Result(result) => { + let encoded = serde_json::to_value(&result).unwrap_or(Value::Null); + // Dispatch output is never caller authority. Only the + // guest's own durable `tool_commit` freezes a canonical + // receipt; a plain dispatch envelope is therefore + // submitted as fallback bytes, which a later publication + // always outranks: the decision either commits the native + // receipt derived from the live ledger or retains the + // call, and synthetic bytes are never written over an + // effect. + match self.lifecycle.settle_call_terminal( + &admitted.call_id, + CallTerminalRequest::Synthetic(&encoded), + ) { + Ok(settlement) => { + guard.settled = true; + guard.retained = settlement.retained; + guard.receipt = settlement.result.clone(); + if let Some(receipt) = settlement.result { + return Ok(receipt.result().clone()); + } + } + Err(_) => { + // The decision owns the reopened token. Keep the + // call registered under a derived retry; no second + // ledger read may rebind these caller bytes. + guard.retained = guard.retained.max(1); + } + } + Ok(result) + } + DispatchOutcome::GuestCommitRetained => { + // The host refused to freeze the guest commit because a + // publisher still owns the call. Those refusal bytes are + // a disposition, not a terminal result. Settle from the + // live ledger: once the publisher finishes this commits + // the native receipt; while it is still in flight the + // call stays retained and the caller observes that + // disposition instead of a premature refusal. + match self + .lifecycle + .settle_call_terminal(&admitted.call_id, CallTerminalRequest::Derived) + { + Ok(settlement) => { + guard.settled = true; + guard.retained = settlement.retained; + guard.receipt = settlement.result.clone(); + match settlement.decision { + CallTerminalDecision::Committed | CallTerminalDecision::NoOp + if settlement.result.is_some() => + { + let receipt = settlement.result.expect("checked above"); + Ok(receipt.result().clone()) + } + CallTerminalDecision::Retained => { + Err(McpToolExecutorError::Retained { + call_id: admitted.call_id.clone(), + }) + } + _ => Err(McpToolExecutorError::DispatchFailed { + message: "the retained guest commit settled without a receipt" + .to_string(), + }), + } + } + Err(_) => { + // The decision owns the reopened token and the + // guard keeps it registered under a derived retry. + guard.settled = true; + guard.retained = guard.retained.max(1); + Err(McpToolExecutorError::Retained { + call_id: admitted.call_id.clone(), + }) + } + } + } + }, + Err(_) => { + let cancelled = json!(ToolResult::failure("cancelled", "tool call was cancelled")); + let deadline = json!(ToolResult::failure( + "deadline_elapsed", + "tool call deadline elapsed" + )); + let request = if cancellation.requested().is_some() { + CallTerminalRequest::Synthetic(&cancelled) + } else if cancellation.deadline_passed() { + CallTerminalRequest::Synthetic(&deadline) + } else { + CallTerminalRequest::Derived + }; + match self + .lifecycle + .settle_call_terminal(&admitted.call_id, request) + { + Ok(settlement) => { + guard.settled = true; + guard.retained = settlement.retained; + guard.receipt = settlement.result.clone(); + match settlement.result { + // A committed guest result or a published effect + // decided the real bytes; synthetic cancellation + // never overwrites it. + Some(receipt) => Ok(receipt.result().clone()), + None => Err(McpToolExecutorError::DispatchFailed { + message: "tool dispatch stopped without a committed result" + .to_string(), + }), + } + } + Err(error) => Err(McpToolExecutorError::DispatchFailed { + message: bounded(&error.message(), MAX_ERROR_BYTES), + }), + } + } + } + } + + /// Authoritative one-read receipt for a call whose VM stopped before the + /// caller received a result. + /// + /// A committed token is read back through the durable boundary; otherwise + /// the typed native ledger is the only source of truth. This accessor is + /// test instrumentation; the execution path uses the one terminal + /// decision instead. + #[cfg(any(test, feature = "workspace-io-fault"))] + fn settlement_receipt( + &self, + call_id: &str, + ) -> Result, McpToolExecutorError> { + self.lifecycle + .derive_call_receipt(call_id) + .map_err(|error| McpToolExecutorError::DispatchFailed { + message: bounded(&error.message(), MAX_ERROR_BYTES), + }) + } + + fn admit_call( + &self, + explicit_call_id: Option<&str>, + request_cancellation: Option<&AdmissionCancellation>, + ) -> Result { + let mut admission = self + .core + .admission + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + // The terminal transport latch is consulted inside admission, under + // the same lock that registers calls. A request that was already + // queued when the reader queue overflowed is therefore refused even + // when its worker starts before the watchdog's teardown sets `closed`. + let gate_latched = self + .core + .admission_gate + .get() + .is_some_and(|gate| gate.load(Ordering::SeqCst)); + if admission.closed || self.core.closed.load(Ordering::SeqCst) || gate_latched { + if gate_latched { + admission.closed = true; + self.core.closed.store(true, Ordering::SeqCst); + self.core.shutdown_flag.0.store(true, Ordering::SeqCst); + } + return Err(McpToolExecutorError::Closed); + } + #[cfg(any(test, feature = "workspace-io-fault"))] + { + let observer = self + .admission_observer + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .clone(); + if let Some(observer) = observer { + observer(explicit_call_id.unwrap_or("")); + } + } + if self.clock.now_ms() >= self.deadline_ms { + admission.closed = true; + self.core.closed.store(true, Ordering::SeqCst); + self.core.shutdown_flag.0.store(true, Ordering::SeqCst); + return Err(McpToolExecutorError::LifetimeElapsed); + } + let call_id = match explicit_call_id { + Some(call_id) => { + validate_call_id(call_id)?; + if admission.ids.contains(call_id) { + return Err(McpToolExecutorError::DuplicateCallId { + call_id: bounded(call_id, MAX_CALL_ID_BYTES), + }); + } + call_id.to_string() + } + None => loop { + let generated = format!("mcp-call-{}", Uuid::new_v4()); + if !admission.ids.contains(&generated) { + break generated; + } + }, + }; + // The quota bounds every burned identity, admitted or cancelled. The + // check happens before the identity is inserted and before any prepare, + // so a refused call leaves `ids` at the advertised hard bound. + if admission + .admitted + .saturating_add(admission.retained_identities) + >= self.max_tool_calls + { + return Err(McpToolExecutorError::CallQuotaExhausted { + limit: self.max_tool_calls, + }); + } + // Both cancellation sources are consulted under the admission lock. + // The request source is consumed twice: here, before the identity is + // registered, and again after registration below. A cancellation that + // arrives between the two is therefore recorded against the registered + // call before this function returns, so no prepare can ever observe an + // admitted call that missed its cancellation. + let request_cancelled = + request_cancellation.is_some_and(AdmissionCancellation::is_cancelled); + let recorded_cancel = admission.pre_admission_cancels.remove(&call_id); + if request_cancelled || recorded_cancel { + admission.ids.insert(call_id.clone()); + admission.retained_identities += 1; + return Err(McpToolExecutorError::Cancelled { + call_id: bounded(&call_id, MAX_CALL_ID_BYTES), + }); + } + // Re-read the terminal latch at registration. The check at the top of + // this function and the registration below are one admission critical + // section, and the overflow latch takes this same lock before it + // cancels its snapshot, so a worker parked between the two can no + // longer miss both. + if self.gate_latched() { + admission.closed = true; + self.core.closed.store(true, Ordering::SeqCst); + self.core.shutdown_flag.0.store(true, Ordering::SeqCst); + return Err(McpToolExecutorError::Closed); + } + admission.ids.insert(call_id.clone()); + admission.admitted += 1; + let remaining_ms = self.deadline_ms.saturating_sub(self.clock.now_ms()); + let timeout = self + .call_timeout + .min(Duration::from_millis(remaining_ms.max(1))); + let state = Arc::new(CallState { + cancellation: RunCancellation::with_timeout(timeout), + // Retain the transport token itself: the publication fence reads + // this source directly, so a cancellation that arrives after the + // checks below but before the handler's select branch is still + // visible before any prepare or publication. + request_cancellation: request_cancellation.cloned(), + retained_receipt: Mutex::new(None), + }); + // Insert under the admission lock so shutdown's `cancel_all` either + // observes this call or the admission itself observes `closed`. + self.calls.insert(call_id.clone(), Arc::clone(&state)); + // A request cancellation can arrive after the pre-registration check + // above. Consume it here, still under the same admission lock that + // registered the call: record it in the call registry, unregister the + // call before any prepare can observe it, and keep the identity burned + // and charged. No cancellation can therefore fall between the token + // check and the publication fence. + if request_cancellation.is_some_and(AdmissionCancellation::is_cancelled) { + self.calls.cancel(&call_id); + self.calls.remove(&call_id); + admission.admitted = admission.admitted.saturating_sub(1); + admission.retained_identities += 1; + return Err(McpToolExecutorError::Cancelled { + call_id: bounded(&call_id, MAX_CALL_ID_BYTES), + }); + } + drop(admission); + Ok(AdmittedCall { call_id, state }) + } + + /// Burns a request identity that was cancelled before a worker was ever + /// enqueued and returns the typed refusal. + /// + /// The identity is charged to the same lifetime quota as an admitted call, + /// so a request cancelled before `spawn_blocking` cannot be re-used and + /// cannot grow the identity ledger without bound. No prepare or effect is + /// performed. + pub fn refuse_cancelled_call(&self, call_id: &str) -> McpToolExecutorError { + if let Err(error) = validate_call_id(call_id) { + return error; + } + let mut admission = self + .core + .admission + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if admission.closed || self.core.closed.load(Ordering::SeqCst) { + return McpToolExecutorError::Closed; + } + if admission.ids.contains(call_id) { + return McpToolExecutorError::DuplicateCallId { + call_id: bounded(call_id, MAX_CALL_ID_BYTES), + }; + } + if admission + .admitted + .saturating_add(admission.retained_identities) + >= self.max_tool_calls + { + return McpToolExecutorError::CallQuotaExhausted { + limit: self.max_tool_calls, + }; + } + admission.ids.insert(call_id.to_string()); + admission.retained_identities += 1; + McpToolExecutorError::Cancelled { + call_id: bounded(call_id, MAX_CALL_ID_BYTES), + } + } +} + +impl Drop for McpToolExecutor { + fn drop(&mut self) { + let _ = self.shutdown(); + } +} + +fn validate_workspace(workspace_root: &Path) -> Result { + if workspace_root.as_os_str().is_empty() { + return Err(McpToolExecutorError::InvalidConfig { + message: "workspace root must not be empty".to_string(), + }); + } + if workspace_root.to_string_lossy().contains('\0') { + return Err(McpToolExecutorError::InvalidConfig { + message: "workspace root must not contain NUL".to_string(), + }); + } + if !workspace_root.is_absolute() { + return Err(McpToolExecutorError::InvalidConfig { + message: "workspace root must be absolute".to_string(), + }); + } + let canonical = std::fs::canonicalize(workspace_root).map_err(|error| { + McpToolExecutorError::InvalidConfig { + message: bounded( + &format!("workspace root cannot be resolved: {error}"), + MAX_ERROR_BYTES, + ), + } + })?; + if !canonical.is_dir() { + return Err(McpToolExecutorError::InvalidConfig { + message: "workspace root must be a directory".to_string(), + }); + } + Ok(canonical) +} + +fn validate_config_numbers(config: &McpToolExecutorConfig) -> Result<(), McpToolExecutorError> { + if config.session_id.is_empty() || config.session_id.contains('\0') { + return Err(McpToolExecutorError::InvalidConfig { + message: "session id must be non-empty and contain no NUL".to_string(), + }); + } + if config.session_id.len() > 128 { + return Err(McpToolExecutorError::InvalidConfig { + message: "session id exceeds the 128-byte bound".to_string(), + }); + } + if config.max_tool_calls == 0 { + return Err(McpToolExecutorError::InvalidConfig { + message: "max_tool_calls must be positive".to_string(), + }); + } + if config.max_tool_calls > MAX_EXECUTOR_TOOL_CALLS { + return Err(McpToolExecutorError::InvalidConfig { + message: format!( + "max_tool_calls exceeds the {MAX_EXECUTOR_TOOL_CALLS}-call lifetime ceiling" + ), + }); + } + if config.max_output_bytes == 0 || config.max_output_bytes > MAX_TOOL_OUTPUT_BYTES { + return Err(McpToolExecutorError::InvalidConfig { + message: "max_output_bytes must be positive and within the project ceiling".to_string(), + }); + } + let minimum_output = match config.profile { + ToolProfile::ReadOnly => MIN_READ_ONLY_TOOL_OUTPUT_BYTES, + ToolProfile::Coding => MIN_EFFECT_TOOL_OUTPUT_BYTES, + }; + if config.max_output_bytes < minimum_output { + return Err(McpToolExecutorError::InvalidConfig { + message: format!( + "max_output_bytes must be at least {minimum_output} bytes for the {:?} profile's canonical receipt", + config.profile + ), + }); + } + if config.call_timeout.is_zero() + || config.call_timeout > crate::runtime::rss_runner::MAX_RUN_TIMEOUT + { + return Err(McpToolExecutorError::InvalidConfig { + message: "call_timeout must be positive and within the run-timeout ceiling".to_string(), + }); + } + if config.server_lifetime.is_zero() || config.server_lifetime > MAX_EXECUTOR_LIFETIME { + return Err(McpToolExecutorError::InvalidConfig { + message: "server_lifetime must be positive and within the process-tool timeout ceiling" + .to_string(), + }); + } + Ok(()) +} + +fn validate_call_id(call_id: &str) -> Result<(), McpToolExecutorError> { + if call_id.is_empty() { + return Err(McpToolExecutorError::InvalidCallId { + message: "call id must not be empty".to_string(), + }); + } + if call_id.len() > MAX_CALL_ID_BYTES { + return Err(McpToolExecutorError::InvalidCallId { + message: format!("call id exceeds the {MAX_CALL_ID_BYTES}-byte bound"), + }); + } + if call_id + .chars() + .any(|character| character == '\0' || character.is_control()) + { + return Err(McpToolExecutorError::InvalidCallId { + message: "call id must not contain control characters".to_string(), + }); + } + Ok(()) +} + +/// One dispatch result that may not be a caller-visible terminal result. +enum DispatchOutcome { + /// A canonical typed tool result. + Result(ToolResult), + /// The host refused the guest commit because a publisher still owns the + /// call. These bytes are a retained disposition, never a receipt. + GuestCommitRetained, +} + +fn canonical_dispatch_outcome(output: &Value) -> Result { + let payload = output + .pointer("/content_block/result") + .cloned() + .ok_or_else(|| McpToolExecutorError::InvalidDispatchOutput { + message: "dispatch envelope has no canonical tool result".to_string(), + })?; + // The host's `commit_retained` code travels through the RSS commit-failure + // path as a tool error. It is a disposition, not a result: flattening it + // into the caller's terminal result would freeze a refusal that the live + // ledger can still outrank. + if payload + .get("error") + .and_then(|error| error.get("code")) + .and_then(Value::as_str) + == Some("commit_retained") + { + return Ok(DispatchOutcome::GuestCommitRetained); + } + serde_json::from_value(payload) + .map(DispatchOutcome::Result) + .map_err(|error| McpToolExecutorError::InvalidDispatchOutput { + message: bounded( + &format!("canonical tool result is invalid: {error}"), + MAX_ERROR_BYTES, + ), + }) +} + +fn build_dispatch_config( + workspace: &Path, + files: &FileToolConfig, + processes: &ProcessToolConfig, + max_output_bytes: usize, +) -> Value { + json!({ + "workspace_root": workspace.to_string_lossy(), + "max_read_bytes": files.max_read_bytes, + "max_read_lines": files.max_read_lines, + "max_write_bytes": files.max_write_bytes, + "max_search_files": files.max_search_files, + "max_search_scanned_bytes": files.max_search_scanned_bytes, + "max_search_depth": files.max_search_depth, + "max_search_matches": files.max_search_matches, + "max_search_output_bytes": files.max_search_output_bytes, + "max_search_wall_time_ms": positive_duration_ms(files.max_search_wall_time), + "max_patch_bytes": files.max_patch_bytes, + "max_patch_preview_bytes": files.max_patch_preview_bytes, + "max_tool_output_bytes": max_output_bytes, + "max_output_bytes": max_output_bytes, + // Only the MCP dispatch configuration selects the lossless overflow + // ladder. The managed/agent path keeps the historical envelope. + "overflow_lossless": true, + "max_timeout_ms": positive_duration_ms(processes.max_timeout), + "default_timeout_ms": positive_duration_ms(processes.default_timeout), + "max_stream_bytes": processes.max_stream_bytes, + "max_stdin_bytes": processes.max_stdin_bytes, + }) +} + +fn bounded(value: &str, limit: usize) -> String { + if value.len() <= limit { + return value.to_string(); + } + let mut end = limit; + while !value.is_char_boundary(end) { + end -= 1; + } + value[..end].to_string() +} + +/// Bounded diagnostic text with control characters escaped so a rejected tool +/// name cannot inject terminal/control sequences into an MCP error. +fn diagnostic_text(value: &str, limit: usize) -> String { + let bounded = bounded(value, limit); + let mut escaped = String::with_capacity(bounded.len()); + for character in bounded.chars() { + if character.is_control() { + escaped.push_str(&format!("\\u{{{:x}}}", character as u32)); + } else { + escaped.push(character); + } + } + escaped +} + +#[cfg(test)] +mod round10_retained_settlement_tests { + use super::*; + use crate::capabilities::{ + CapabilityRisk, NativeArtifactIdentity, NativeEffectRecord, PrepareMetadata, PrepareOutcome, + }; + + #[test] + fn retained_settlement_stays_registered_and_shutdown_retries_it() { + let root = std::env::temp_dir().join(format!( + "mcp-executor-retained-{}-{}", + std::process::id(), + Uuid::new_v4() + )); + std::fs::create_dir_all(&root).expect("fixture root"); + let executor = McpToolExecutor::new( + McpToolExecutorConfig::new(&root) + .with_process_cleanup_timeout(Duration::from_millis(200)) + .with_server_lifetime(Duration::from_millis(500)), + ) + .expect("executor"); + let call_id = "r10-retained-unit"; + let _admitted = executor.admit_call(Some(call_id), None).expect("admit"); + let token = match executor + .lifecycle + .prepare( + &executor.owner, + PrepareMetadata { + run_id: executor.owner.run().to_string(), + call_id: call_id.to_string(), + tool_name: "fixture_tool".to_string(), + argument_digest: "digest".to_string(), + registry_identity: executor.registry.identity().to_string(), + risk_class: CapabilityRisk::Read, + summary: "fixture".to_string(), + }, + ) + .expect("prepare") + { + PrepareOutcome::Execute { + execution_token, .. + } => execution_token, + other => panic!("expected execute, got {other:?}"), + }; + executor + .lifecycle + .enter_publication(&token) + .expect("publication") + .published_effect(NativeEffectRecord::artifact_store(NativeArtifactIdentity { + id: "retained-artifact".to_string(), + len: 3, + hash: "hash".to_string(), + })); + // A later publisher is admitted before the receipt read so its version + // is part of the receipt, then held open while the guard settles. + let later = executor + .lifecycle + .enter_publication(&token) + .expect("later publisher"); + let receipt = executor + .lifecycle + .derive_call_receipt(call_id) + .expect("derive receipt") + .expect("published receipt"); + drop(ActiveCallGuard { + executor: &executor, + call_id: call_id.to_string(), + receipt: Some(receipt.clone()), + settled: false, + retained: 0, + }); + assert_eq!( + executor.calls.registered_count(), + 1, + "a retained settlement must keep the call registered" + ); + assert_eq!(executor.calls.retained_settlements().len(), 1); + assert_eq!(executor.lifecycle.open_token_count(), 1); + // The publisher retires without recording an effect, so the ledger + // version still matches the receipt the guard retained. + drop(later); + let proof = executor.shutdown(); + assert_eq!( + proof, + ProcessCleanupProof::Clean, + "shutdown must retry and settle the retained call: {proof:?}" + ); + assert_eq!(executor.lifecycle.open_token_count(), 0); + assert_eq!(executor.lifecycle.committed_token_count(), 1); + assert_eq!(executor.calls.registered_count(), 0); + let committed = executor + .lifecycle + .committed_result(call_id) + .expect("read committed payload") + .expect("committed payload"); + assert_eq!( + committed, + receipt.encoded().clone(), + "the retry must commit the exact retained receipt bytes" + ); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn superseded_retained_receipt_is_re_derived_and_committed_once_by_shutdown() { + let root = std::env::temp_dir().join(format!( + "mcp-executor-superseded-{}-{}", + std::process::id(), + Uuid::new_v4() + )); + std::fs::create_dir_all(&root).expect("fixture root"); + let executor = McpToolExecutor::new( + McpToolExecutorConfig::new(&root) + .with_process_cleanup_timeout(Duration::from_millis(200)) + .with_server_lifetime(Duration::from_millis(800)), + ) + .expect("executor"); + let call_id = "r11-superseded-retained"; + let _admitted = executor.admit_call(Some(call_id), None).expect("admit"); + let token = match executor + .lifecycle + .prepare( + &executor.owner, + PrepareMetadata { + run_id: executor.owner.run().to_string(), + call_id: call_id.to_string(), + tool_name: "fixture_tool".to_string(), + argument_digest: "digest".to_string(), + registry_identity: executor.registry.identity().to_string(), + risk_class: CapabilityRisk::Read, + summary: "fixture".to_string(), + }, + ) + .expect("prepare") + { + PrepareOutcome::Execute { + execution_token, .. + } => execution_token, + other => panic!("expected execute, got {other:?}"), + }; + executor + .lifecycle + .enter_publication(&token) + .expect("publication") + .published_effect(NativeEffectRecord::artifact_store(NativeArtifactIdentity { + id: "r11-superseded-artifact".to_string(), + len: 3, + hash: "hash".to_string(), + })); + let stale = executor + .lifecycle + .derive_call_receipt(call_id) + .expect("derive receipt") + .expect("published receipt"); + // A later publisher advances the ledger version and retires without + // recording an effect. The retained receipt's version is now stale. + drop( + executor + .lifecycle + .enter_publication(&token) + .expect("later publication"), + ); + drop(ActiveCallGuard { + executor: &executor, + call_id: call_id.to_string(), + receipt: Some(stale), + settled: false, + retained: 0, + }); + assert_eq!(executor.calls.registered_count(), 1); + assert_eq!(executor.lifecycle.open_token_count(), 1); + assert!( + executor + .durable_committed_receipt_for_test(call_id) + .is_none() + ); + let proof = executor.shutdown(); + assert_eq!( + proof, + ProcessCleanupProof::Clean, + "shutdown must re-derive and settle the superseded receipt: {proof:?}" + ); + assert_eq!(executor.calls.registered_count(), 0); + assert_eq!(executor.lifecycle.open_token_count(), 0); + let committed = executor + .durable_committed_receipt_for_test(call_id) + .expect("durable committed result"); + assert!(committed.ok, "the canonical published receipt must win"); + assert_eq!( + committed.artifacts, + vec!["r11-superseded-artifact".to_string()], + "the re-derived receipt must describe the real published effect" + ); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn retained_synthetic_receipt_for_a_retired_publisher_reaches_a_terminal() { + let root = std::env::temp_dir().join(format!( + "mcp-executor-synthetic-{}-{}", + std::process::id(), + Uuid::new_v4() + )); + std::fs::create_dir_all(&root).expect("fixture root"); + let executor = McpToolExecutor::new( + McpToolExecutorConfig::new(&root) + .with_process_cleanup_timeout(Duration::from_millis(200)) + .with_server_lifetime(Duration::from_millis(800)), + ) + .expect("executor"); + let call_id = "r11-synthetic-retained"; + let _admitted = executor.admit_call(Some(call_id), None).expect("admit"); + let token = match executor + .lifecycle + .prepare( + &executor.owner, + PrepareMetadata { + run_id: executor.owner.run().to_string(), + call_id: call_id.to_string(), + tool_name: "fixture_tool".to_string(), + argument_digest: "digest".to_string(), + registry_identity: executor.registry.identity().to_string(), + risk_class: CapabilityRisk::Read, + summary: "fixture".to_string(), + }, + ) + .expect("prepare") + { + PrepareOutcome::Execute { + execution_token, .. + } => execution_token, + other => panic!("expected execute, got {other:?}"), + }; + // The publisher owns the fence but never records an effect. The empty + // read produces a synthetic cancellation receipt. + let permit = executor + .lifecycle + .enter_publication(&token) + .expect("publication"); + let synthetic = executor.lifecycle.bind_synthetic_result( + call_id, + ToolResult::failure("cancelled", "tool call was cancelled"), + ); + drop(ActiveCallGuard { + executor: &executor, + call_id: call_id.to_string(), + receipt: Some(synthetic), + settled: false, + retained: 0, + }); + assert_eq!(executor.calls.registered_count(), 1); + assert_eq!(executor.lifecycle.open_token_count(), 1); + // The publisher retires without producing an effect. Shutdown must + // record the explicit interrupted terminal instead of retrying the + // synthetic bytes forever. + drop(permit); + let proof = executor.shutdown(); + assert_eq!(proof, ProcessCleanupProof::Clean, "{proof:?}"); + assert_eq!(executor.calls.registered_count(), 0); + assert_eq!(executor.lifecycle.open_token_count(), 0); + assert_eq!(executor.lifecycle.interrupted_token_count(), 1); + assert!( + executor + .durable_committed_receipt_for_test(call_id) + .is_none(), + "a publisher that never produced an effect must not commit synthetic bytes" + ); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn guard_durable_commit_failure_keeps_retry_ownership() { + let root = std::env::temp_dir().join(format!( + "mcp-executor-guard-durable-{}-{}", + std::process::id(), + Uuid::new_v4() + )); + std::fs::create_dir_all(&root).expect("fixture root"); + let executor = McpToolExecutor::new( + McpToolExecutorConfig::new(&root) + .with_process_cleanup_timeout(Duration::from_millis(200)) + .with_server_lifetime(Duration::from_millis(800)), + ) + .expect("executor"); + let call_id = "r13-guard-durable"; + let _admitted = executor.admit_call(Some(call_id), None).expect("admit"); + let token = match executor + .lifecycle + .prepare( + &executor.owner, + PrepareMetadata { + run_id: executor.owner.run().to_string(), + call_id: call_id.to_string(), + tool_name: "fixture_tool".to_string(), + argument_digest: "digest".to_string(), + registry_identity: executor.registry.identity().to_string(), + risk_class: CapabilityRisk::Read, + summary: "fixture".to_string(), + }, + ) + .expect("prepare") + { + PrepareOutcome::Execute { + execution_token, .. + } => execution_token, + other => panic!("expected execute, got {other:?}"), + }; + executor + .lifecycle + .enter_publication(&token) + .expect("publication") + .published_effect(NativeEffectRecord::artifact_store(NativeArtifactIdentity { + id: "r13-guard-effect".to_string(), + len: 4, + hash: "hash".to_string(), + })); + executor.fail_next_durable_commit_for_test(); + // The guard's terminal decision commits the native receipt; the + // durable boundary rejects it. The guard must keep the call registered + // under an explicit retry disposition instead of removing it with a + // zero retained count. + drop(ActiveCallGuard { + executor: &executor, + call_id: call_id.to_string(), + receipt: None, + settled: false, + retained: 0, + }); + assert_eq!( + executor.calls.registered_count(), + 1, + "a failed durable write must keep the call registered" + ); + assert_eq!( + executor.calls.retained_settlements().len(), + 1, + "the guard must publish an explicit retry disposition" + ); + assert_eq!(executor.lifecycle.open_token_count(), 1); + assert_eq!(executor.lifecycle.committed_token_count(), 0); + let proof = executor.shutdown(); + assert_eq!(proof, ProcessCleanupProof::Clean, "{proof:?}"); + assert_eq!(executor.calls.registered_count(), 0); + assert_eq!(executor.lifecycle.committed_token_count(), 1); + let committed = executor + .durable_committed_receipt_for_test(call_id) + .expect("the retry must commit the true receipt"); + assert!(committed.ok, "{committed:?}"); + assert_eq!(committed.artifacts, vec!["r13-guard-effect".to_string()]); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn timed_out_teardown_contender_counts_registered_calls() { + let root = std::env::temp_dir().join(format!( + "mcp-executor-contender-count-{}-{}", + std::process::id(), + Uuid::new_v4() + )); + std::fs::create_dir_all(&root).expect("fixture root"); + let executor = Arc::new( + McpToolExecutor::new( + McpToolExecutorConfig::new(&root) + .with_process_cleanup_timeout(Duration::from_millis(120)) + .with_server_lifetime(Duration::from_millis(800)), + ) + .expect("executor"), + ); + let _admitted = executor + .admit_call(Some("r11-contender-call"), None) + .expect("admit"); + let gate = executor.hold_teardown_for_test(); + let contender = { + let executor = Arc::clone(&executor); + std::thread::spawn(move || executor.shutdown()) + }; + std::thread::sleep(Duration::from_millis(220)); + drop(gate); + let proof = contender.join().expect("contender"); + assert!( + matches!(proof, ProcessCleanupProof::TimedOut { retained } if retained >= 1), + "a contender that lost the gate must still count the registered call: {proof:?}" + ); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn timed_out_contender_does_not_overwrite_a_proven_clean_proof() { + let root = std::env::temp_dir().join(format!( + "mcp-executor-contender-merge-{}-{}", + std::process::id(), + Uuid::new_v4() + )); + std::fs::create_dir_all(&root).expect("fixture root"); + let executor = Arc::new( + McpToolExecutor::new( + McpToolExecutorConfig::new(&root) + .with_process_cleanup_timeout(Duration::from_millis(120)) + .with_server_lifetime(Duration::from_millis(800)), + ) + .expect("executor"), + ); + // A previous owner proved the teardown clean. + executor.core.record_proof(ProcessCleanupProof::Clean); + assert_eq!(executor.cleanup_outcome(), Some(ProcessCleanupProof::Clean)); + // The contender observes the registered call, then parks at the proof + // gate with that (soon stale) nonzero count. + let _admitted = executor + .admit_call(Some("r12-stale-contender"), None) + .expect("admit"); + let (entered_tx, entered_rx) = std::sync::mpsc::channel(); + let release = Arc::new((Mutex::new(false), std::sync::Condvar::new())); + let entered = AtomicBool::new(false); + *executor + .core + .proof_observer + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(Arc::new({ + let release = Arc::clone(&release); + move || { + if entered.swap(true, Ordering::SeqCst) { + return; + } + let _ = entered_tx.send(()); + let (lock, condvar) = &*release; + let mut released = lock.lock().unwrap_or_else(|error| error.into_inner()); + while !*released { + released = condvar + .wait(released) + .unwrap_or_else(|error| error.into_inner()); + } + } + })); + let teardown = executor.hold_teardown_for_test(); + let contender = { + let executor = Arc::clone(&executor); + std::thread::spawn(move || executor.shutdown()) + }; + entered_rx + .recv_timeout(Duration::from_secs(5)) + .expect("contender must reach the proof gate"); + // The call finishes while the contender is parked, then the owner + // publishes the proven Clean proof. + executor.calls.remove("r12-stale-contender"); + executor.core.record_proof(ProcessCleanupProof::Clean); + assert_eq!( + executor.cleanup_outcome(), + Some(ProcessCleanupProof::Clean), + "the owner must publish Clean before the contender resumes" + ); + drop(teardown); + let (lock, condvar) = &*release; + *lock.lock().unwrap_or_else(|error| error.into_inner()) = true; + condvar.notify_all(); + let contender_proof = contender.join().expect("contender"); + assert_eq!( + contender_proof, + ProcessCleanupProof::Clean, + "the contender's returned value must be the same merged Clean proof it published" + ); + assert_eq!( + executor.cleanup_outcome(), + Some(ProcessCleanupProof::Clean), + "a timed-out contender with a stale nonzero observation must not downgrade Clean" + ); + let _ = std::fs::remove_dir_all(&root); + } +} diff --git a/src/mcp/mod.rs b/src/mcp/mod.rs new file mode 100644 index 00000000..ad215b21 --- /dev/null +++ b/src/mcp/mod.rs @@ -0,0 +1,92 @@ +//! Provider-free MCP tool-provider boundary. +//! +//! This module owns the standalone RSS tool executor and the exact mapping +//! from the admitted RustScript tool registry to MCP tools and results. It +//! never constructs the gateway `AgentService`, loads provider credentials, +//! invokes a provider adapter/credential host, or compiles +//! `rss/agent/main.rss`. A provider call that becomes reachable in its frozen +//! runners fails closed with a canonical `provider_disabled` error. +//! +//! A later MCP stdio service drives [`executor::McpToolExecutor`] through +//! [`catalog`] and [`result`]; the capability policy in the executor remains +//! authoritative, while MCP annotations are presentation hints only. + +pub mod catalog; +pub mod executor; +pub mod result; +pub mod server; + +use crate::tool_schema::{RiskClass, ToolDescriptor, Toolset}; + +/// The six public tools admitted by the current coding profile. +pub const CODING_TOOL_NAMES: &[&str] = &[ + "read_file", + "search_files", + "write_file", + "patch", + "terminal", + "process", +]; + +/// The read-only profile admits exactly these two read-risk tools. +pub const READ_ONLY_TOOL_NAMES: &[&str] = &["read_file", "search_files"]; + +/// The tool exposure profile selected by the standalone tool server. +/// +/// This is policy at the MCP boundary, not authorization inside RSS: the +/// executor rejects a tool that the selected profile does not admit before +/// any lifecycle prepare or effect, and the existing workspace/process +/// capability bounds stay in force for every admitted tool. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ToolProfile { + Coding, + ReadOnly, +} + +impl ToolProfile { + pub const CODING: &'static str = "coding"; + pub const READ_ONLY: &'static str = "read-only"; + + pub const fn as_str(self) -> &'static str { + match self { + Self::Coding => Self::CODING, + Self::ReadOnly => Self::READ_ONLY, + } + } + + /// Name-level admission, independent of descriptor validation. + pub fn admits_name(self, name: &str) -> bool { + match self { + Self::Coding => CODING_TOOL_NAMES.contains(&name), + Self::ReadOnly => READ_ONLY_TOOL_NAMES.contains(&name), + } + } + + /// Risk-level admission. The read-only profile admits only `read`. + pub const fn admits_risk(self, risk: RiskClass) -> bool { + matches!(self, Self::Coding) || matches!(risk, RiskClass::Read) + } + + /// Full admission check for an already validated registry descriptor. + /// + /// Unknown risk/toolset values fail closed: they are never admitted even + /// when their name happens to be in the profile allowlist. + pub fn admits_descriptor(self, descriptor: &ToolDescriptor) -> bool { + if !self.admits_name(&descriptor.name) { + return false; + } + let Ok(risk) = RiskClass::try_from(descriptor.risk_class.as_str()) else { + return false; + }; + if !self.admits_risk(risk) { + return false; + } + Toolset::try_from(descriptor.toolset.as_str()).is_ok() + } +} + +impl std::fmt::Display for ToolProfile { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(self.as_str()) + } +} diff --git a/src/mcp/result.rs b/src/mcp/result.rs new file mode 100644 index 00000000..3c8d53b1 --- /dev/null +++ b/src/mcp/result.rs @@ -0,0 +1,57 @@ +//! Canonical [`ToolResult`] to MCP result conversion. +//! +//! Conversion is lossless over the current canonical result fields: text, +//! structured data, `is_error`, truncation, and artifact references. MCP has +//! no dedicated truncation or artifact field, so both are retained as +//! namespaced `_meta` values while the typed error code is retained alongside +//! the human-readable error text. These values are presentation data; the +//! executor's capability policy remains authoritative. + +use rmcp::model::{CallToolResult, ContentBlock, MetaObject}; +use serde_json::{Map, json}; + +use crate::tool_result::ToolResult; + +/// `_meta` key recording the canonical truncation flag. +pub const TRUNCATED_META_KEY: &str = "org.rustscript/truncated"; +/// `_meta` key retaining the canonical artifact reference list. +pub const ARTIFACTS_META_KEY: &str = "org.rustscript/artifacts"; +/// `_meta` key retaining the canonical error code when present. +pub const ERROR_CODE_META_KEY: &str = "org.rustscript/error_code"; + +/// Converts one canonical tool result to an MCP tool result. +pub fn to_call_tool_result(result: &ToolResult) -> CallToolResult { + let mut content = Vec::new(); + if !result.content.is_empty() { + content.push(ContentBlock::text(result.content.clone())); + } + if let Some(error) = &result.error { + let text = match (error.code.is_empty(), error.message.is_empty()) { + (true, true) => String::new(), + (false, true) => error.code.clone(), + (true, false) => error.message.clone(), + (false, false) => format!("{}: {}", error.code, error.message), + }; + if !text.is_empty() { + content.push(ContentBlock::text(text)); + } + } + + let mut converted = if result.ok { + CallToolResult::success(content) + } else { + CallToolResult::error(content) + }; + converted.structured_content = Some(result.data.clone()); + + let mut meta = Map::new(); + meta.insert(TRUNCATED_META_KEY.to_string(), json!(result.truncated)); + meta.insert(ARTIFACTS_META_KEY.to_string(), json!(result.artifacts)); + if let Some(error) = &result.error + && !error.code.is_empty() + { + meta.insert(ERROR_CODE_META_KEY.to_string(), json!(error.code)); + } + converted.meta = Some(MetaObject(meta)); + converted +} diff --git a/src/mcp/server.rs b/src/mcp/server.rs new file mode 100644 index 00000000..48362c36 --- /dev/null +++ b/src/mcp/server.rs @@ -0,0 +1,1582 @@ +//! MCP stdio service over the provider-free RustScript tool executor. +//! +//! The service is a thin protocol shell around [`McpToolExecutor`]: +//! +//! - `initialize` advertises exactly one capability, `tools`; +//! - `tools/list` is the admitted registry catalog for the selected profile; +//! - `tools/call` runs the executor and converts its canonical result through +//! [`super::result`]; +//! - executor refusals are protocol errors carrying the typed +//! `org.rustscript/error_code` value, so a caller can distinguish a policy +//! refusal from a tool failure. +//! +//! Transport handling is delegated to `rmcp`'s server lifecycle and its +//! newline-delimited stdio transport. This module never folds, frames, or +//! parses JSON-RPC itself. stdout carries protocol bytes only; every +//! diagnostic is a bounded, single-line write to stderr. +//! +//! A retained call ([`McpToolExecutorError::Retained`]) is deliberately mapped +//! to a nonterminal protocol error. It is not a tool failure: the effect may +//! still settle under the executor's own publication ownership, and replaying +//! the call would be a second effect. The wire error therefore says +//! `terminal: false` and `replay: false`. + +use std::collections::VecDeque; +use std::future::Future; +use std::io::Write as _; +use std::path::{Path, PathBuf}; +use std::pin::Pin; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex as StdMutex, OnceLock}; +use std::task::{Context, Poll}; +use std::time::Duration; + +use rmcp::model::{ + CallToolRequestParams, CallToolResponse, ErrorCode, Implementation, InitializeResult, + JsonObject, ListToolsResult, PaginatedRequestParams, ServerCapabilities, ServerConfig, Tool, +}; +use rmcp::service::{ + QuitReason, RequestContext, RoleServer, RunningServiceCancellationToken, RxJsonRpcMessage, + TxJsonRpcMessage, +}; +use rmcp::transport::Transport; +use rmcp::transport::async_rw::AsyncRwTransport; +use rmcp::{ServerHandler, ServiceExt}; +use serde_json::{Value, json}; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, ReadBuf}; +use tokio::sync::{Notify, mpsc, watch}; + +use super::ToolProfile; +use super::catalog; +use super::executor::{ + AdmissionCancellation, DEFAULT_SERVER_LIFETIME, McpToolExecutor, McpToolExecutorConfig, + McpToolExecutorError, +}; +use super::result::to_call_tool_result; +use crate::capabilities::ProcessCleanupProof; +use crate::tool_result::ToolResult; + +/// Stable MCP server name advertised at initialization. +pub const SERVER_NAME: &str = "rustscript-agent-tools"; + +/// Hard bound for any single stderr diagnostic line. +pub const MAX_DIAGNOSTIC_BYTES: usize = 512; + +/// Bounded grace for one cancelled call to stop before the handler answers. +pub const CANCEL_GRACE: Duration = Duration::from_secs(5); + +/// JSON-RPC error code for a retained (nonterminal) call disposition. +/// +/// `-32000..=-32099` is the implementation-defined server-error range. This +/// code is not a tool failure: the effect is owned by a publisher that has not +/// settled yet. +pub const RETAINED_ERROR_CODE: i32 = -32010; + +/// MCP `RequestCancelled` code used when a cancelled call does not stop in +/// time to produce its own receipt. +pub const CANCELLED_ERROR_CODE: i32 = -32800; + +/// JSON-RPC error data key carrying the stable executor error code. +pub const ERROR_CODE_DATA_KEY: &str = "org.rustscript/error_code"; +/// JSON-RPC error data key recording whether the disposition is terminal. +pub const TERMINAL_DATA_KEY: &str = "org.rustscript/terminal"; +/// JSON-RPC error data key recording whether the caller may replay the call. +pub const REPLAY_DATA_KEY: &str = "org.rustscript/replay"; + +const MAX_ERROR_MESSAGE_BYTES: usize = 512; +const IN_FLIGHT_POLL_INTERVAL: Duration = Duration::from_millis(10); +/// Bound for the reader pump's pre-read queue. A peer that keeps writing while +/// rmcp is blocked on stdout is drained (and its excess discarded) so EOF is +/// still observed; the protocol is already unusable in that state. +const INPUT_QUEUE_CHUNKS: usize = 64; +/// One reader-pump chunk. +const INPUT_CHUNK_BYTES: usize = 8 * 1024; +/// Bound for queued stderr diagnostics. A stalled sink fills the queue and +/// later lines are dropped instead of blocking the server. +const DIAGNOSTIC_QUEUE_LINES: usize = 32; +/// Bound for draining the diagnostic queue at shutdown. +const DIAGNOSTIC_FLUSH_BOUND: Duration = Duration::from_millis(500); +/// Extra grace, after the executor's absolute cleanup cutoff, allowed for the +/// rmcp service task to close its transport before the transport is aborted. +const EOF_TASK_GRACE: Duration = Duration::from_secs(1); +/// Brief opportunity for rmcp to report its own handshake verdict before an +/// observed EOF is allowed to abort the initialize writer. +const INIT_EOF_GRACE: Duration = Duration::from_secs(1); +/// Test-only readiness line emitted before serving starts, and the +/// file-based readiness signal used by packaged-process tests. Both are inert +/// unless the corresponding environment variable is set; they are available in +/// default builds so the bounded-teardown regression runs without the fault +/// feature. +const READY_DIAGNOSTIC: &str = "rustscript-agent tools serve ready"; +/// Fixed, peer-free warning emitted when a stalled peer keeps rmcp from +/// closing the transport within the cleanup deadline. +const TRANSPORT_CLOSE_TIMEOUT_DIAGNOSTIC: &str = + "rustscript-agent tools serve: transport close timed out"; + +/// Typed tool-server construction or lifecycle failure. +/// +/// Every message is bounded and free of credentials; the code is the +/// machine-readable value the CLI writes to stderr before exiting. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum ToolServerError { + WorkspaceEmpty, + WorkspaceNotAbsolute, + WorkspaceUnresolvable { + message: String, + }, + WorkspaceNotDirectory, + InvalidConfiguration { + message: String, + }, + CatalogUnavailable { + message: String, + }, + /// rmcp rejected the initialization handshake. The variant carries no + /// peer-derived detail on purpose: the received message can contain + /// free-form metadata, and only the stable code may reach stderr. + Initialization, +} + +impl ToolServerError { + pub const fn code(&self) -> &'static str { + match self { + Self::WorkspaceEmpty => "tools_workspace_empty", + Self::WorkspaceNotAbsolute => "tools_workspace_not_absolute", + Self::WorkspaceUnresolvable { .. } => "tools_workspace_unresolvable", + Self::WorkspaceNotDirectory => "tools_workspace_not_directory", + Self::InvalidConfiguration { .. } => "tools_config_invalid", + Self::CatalogUnavailable { .. } => "tools_catalog_invalid", + Self::Initialization => "tools_initialize_failed", + } + } + + /// Bounded detail for a stderr diagnostic, if the variant carries one. + pub fn message(&self) -> Option<&str> { + match self { + Self::WorkspaceUnresolvable { message } + | Self::InvalidConfiguration { message } + | Self::CatalogUnavailable { message } => Some(message), + Self::WorkspaceEmpty + | Self::WorkspaceNotAbsolute + | Self::WorkspaceNotDirectory + | Self::Initialization => None, + } + } +} + +impl std::fmt::Display for ToolServerError { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self.message() { + Some(message) => write!(formatter, "{}: {message}", self.code()), + None => formatter.write_str(self.code()), + } + } +} + +impl std::error::Error for ToolServerError {} + +/// Why the service stopped. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ToolServerQuit { + /// The peer closed stdin (or the transport reported EOF). + Closed, + /// An external shutdown request or signal stopped the service. + Cancelled, + /// The executor lifetime bound elapsed. + LifetimeElapsed, + /// The reader queue overflowed, so protocol input can no longer be framed + /// and the service stopped forwarding it. + InputTerminated, + /// The rmcp service task aborted unexpectedly. + Aborted, +} + +impl ToolServerQuit { + pub const fn as_str(self) -> &'static str { + match self { + Self::Closed => "closed", + Self::Cancelled => "cancelled", + Self::LifetimeElapsed => "lifetime_elapsed", + Self::InputTerminated => "input_terminated", + Self::Aborted => "aborted", + } + } +} + +/// Typed proof returned after the service and its executor stopped. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ToolServerOutcome { + pub profile: ToolProfile, + pub quit: ToolServerQuit, + pub cleanup: ProcessCleanupProof, + pub admitted_calls: u64, +} + +impl ToolServerOutcome { + /// Single bounded stderr line describing the teardown and its proof. + pub fn diagnostic(&self) -> String { + let (cleanup, retained) = match &self.cleanup { + ProcessCleanupProof::Clean => ("clean", 0), + ProcessCleanupProof::TimedOut { retained } => ("timed_out", *retained), + ProcessCleanupProof::Failed { retained, .. } => ("failed", *retained), + }; + let mut line = format!( + "rustscript-agent tools serve stopped: profile={} quit={} cleanup={cleanup} retained={retained} admitted_calls={}", + self.profile, + self.quit.as_str(), + self.admitted_calls + ); + if let ProcessCleanupProof::Failed { code, .. } = &self.cleanup { + line.push_str(" code="); + line.push_str(code); + } + truncate_diagnostic(&line) + } +} + +/// One in-process MCP tool server over a shared executor. +/// +/// The server never takes exclusive ownership of the executor: embedders and +/// tests may keep an `Arc` handle for lifecycle assertions. Construction +/// canonicalizes the workspace before any capability exists. +#[derive(Clone)] +pub struct RustScriptToolServer { + executor: Arc, + tools: Arc>, + info: InitializeResult, + profile: ToolProfile, + lifetime: Duration, + cancel_grace: Duration, + in_flight: Arc, + /// Handlers that outlived `cancel_grace` and answered with the synthetic + /// cancelled error instead of a worker receipt. + cancelled_after_grace: Arc, + /// Latched once the reader queue overflows. The protocol input is then + /// unusable: no further byte may be forwarded, and new calls are refused. + input: Arc, +} + +impl RustScriptToolServer { + /// Validates the workspace, constructs the executor, and freezes the + /// catalog for the configured profile before serving. + pub fn new(config: McpToolExecutorConfig) -> Result { + let profile = config.profile; + let lifetime = config.server_lifetime; + let mut config = config; + config.workspace_root = canonical_workspace(&config.workspace_root)?; + let executor = + Arc::new(McpToolExecutor::new(config).map_err(|error| invalid_configuration(&error))?); + Self::assemble(executor, profile, lifetime) + } + + /// Builds a server over an existing executor. + /// + /// The executor already owns workspace validation and its lifetime bound. + /// The serve-side lifetime fallback is the executor's documented default; + /// the executor's own watchdog remains authoritative. + pub fn from_executor(executor: Arc) -> Result { + let profile = executor.profile(); + Self::assemble(executor, profile, DEFAULT_SERVER_LIFETIME) + } + + fn assemble( + executor: Arc, + profile: ToolProfile, + lifetime: Duration, + ) -> Result { + let tools = + catalog::catalog_from_registry(executor.registry(), profile).map_err(|error| { + ToolServerError::CatalogUnavailable { + message: truncate_diagnostic(&error.to_string()), + } + })?; + let capabilities = ServerCapabilities::builder().enable_tools().build(); + let info = InitializeResult::new(capabilities) + .with_server_info(Implementation::new(SERVER_NAME, env!("CARGO_PKG_VERSION"))) + .with_instructions( + "RustScript workspace tools. The configured workspace and capability bounds are authoritative.", + ); + let input = Arc::new(InputTermination::new()); + // Admission reads the exact latch the reader pump closes, so a request + // that was already queued when the queue overflowed is refused even + // when its worker starts before the watchdog's teardown. The hook + // cancels every active call the moment the latch closes instead of + // waiting for that task to be scheduled. + executor.set_admission_gate(input.latch()); + let cancel_executor = Arc::clone(&executor); + input.set_on_terminate(Box::new(move || cancel_executor.cancel_active_calls())); + Ok(Self { + executor, + tools: Arc::new(tools), + info, + profile, + lifetime, + cancel_grace: CANCEL_GRACE, + in_flight: Arc::new(AtomicUsize::new(0)), + cancelled_after_grace: Arc::new(AtomicUsize::new(0)), + input, + }) + } + + /// Test-only: shorten the handler grace so a held worker can prove the + /// timeout branch deterministically. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn with_cancel_grace_for_test(mut self, grace: Duration) -> Self { + self.cancel_grace = grace; + self + } + + /// Test-only: handlers that answered with the synthetic cancelled error + /// after `cancel_grace` elapsed. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn cancelled_after_grace_for_test(&self) -> usize { + self.cancelled_after_grace.load(Ordering::SeqCst) + } + + /// Test-only: whether the reader queue overflowed and made protocol input + /// terminal. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn input_terminated_for_test(&self) -> bool { + self.input.is_terminated() + } + + /// Test-only: close the terminal input latch exactly as a reader-queue + /// overflow does, including the active-call cancellation hook. + #[cfg(any(test, feature = "workspace-io-fault"))] + #[doc(hidden)] + pub fn terminate_input_for_test(&self) { + self.input.terminate(); + } + + /// The shared executor this server drives. + pub fn executor(&self) -> &Arc { + &self.executor + } + + /// The exact catalog advertised by `tools/list`. + pub fn tools(&self) -> &[Tool] { + self.tools.as_slice() + } + + /// The initialization result, including the advertised capability shape. + pub fn info(&self) -> &InitializeResult { + &self.info + } + + /// Serves the MCP stdio transport until stdin closes, the executor + /// lifetime elapses, or SIGINT requests shutdown. + pub async fn serve_stdio(self) -> Result { + let (stop_tx, stop_rx) = watch::channel(false); + tokio::spawn(async move { + if tokio::signal::ctrl_c().await.is_ok() { + let _ = stop_tx.send(true); + } + }); + let (reader, writer) = rmcp::transport::stdio_pipes(); + let outcome = self + .serve_with_shutdown(reader, writer, Some(stop_rx)) + .await; + if let Err(error) = &outcome { + // Serve-time failures can originate in a peer-influenced handshake; + // only the stable code is emitted. + emit_diagnostic(&format!( + "rustscript-agent tools serve failed: {}", + error.code() + )); + flush_diagnostics(DIAGNOSTIC_FLUSH_BOUND); + } + outcome + } + + /// Serves any newline-delimited JSON-RPC stream. + /// + /// A dedicated reader pump owns the input and observes EOF independently + /// of whether rmcp is currently polling `receive`. That matters when rmcp + /// is blocked flushing an invalid-request response (or the initialize + /// response) into a stalled stdout: the peer can close stdin while no + /// `poll_read` is outstanding, and the watchdog still starts the same + /// bounded cleanup as an ordinary orderly close. + /// + /// Every wait is bounded by the executor's absolute cleanup cutoff. If + /// rmcp cannot close the transport in that window (a stalled peer can hold + /// the writer lock), the transport is aborted and abandoned. Diagnostics + /// are queued to a bounded sink, so a stalled stderr cannot extend the + /// bound. The returned proof is authoritative. + pub async fn serve_with_shutdown( + self, + reader: R, + writer: W, + shutdown: Option>, + ) -> Result + where + R: AsyncRead + Send + Unpin + 'static, + W: AsyncWrite + Send + Unpin + 'static, + { + // The watchdog is installed before the first log record and before + // any fallible startup step. A stalled stderr sink can then never + // delay the only bounded teardown owner. + let deadline = tokio::time::Instant::now() + self.lifetime; + let eof_seen = Arc::new(AtomicBool::new(false)); + let eof_notify = Arc::new(Notify::new()); + let input_termination = Arc::clone(&self.input); + + let (stop_tx, mut stop_rx) = watch::channel::>(None); + let cause_slot = Arc::new(StdMutex::new(None::)); + let init_complete = Arc::new(AtomicBool::new(false)); + let transport_abort = TransportAbort::new(); + let (cancel_tx, mut cancel_rx) = mpsc::channel::(1); + + // The watchdog owns the deadline, the EOF signal, and the terminal + // input latch. It runs before `serve` is created and therefore covers + // the initialize handshake, where rmcp can be blocked in `send` before + // ever polling the reader. + let mut watchdog = { + let abort = transport_abort.clone(); + let cause = Arc::clone(&cause_slot); + let executor = Arc::clone(&self.executor); + let eof_seen = Arc::clone(&eof_seen); + let eof_notify = Arc::clone(&eof_notify); + let init_complete = Arc::clone(&init_complete); + let input_termination = Arc::clone(&input_termination); + let mut shutdown = shutdown; + tokio::spawn(async move { + let stop = tokio::select! { + _ = tokio::time::sleep_until(deadline) => StopCause::Lifetime, + _ = wait_for_eof(&eof_seen, &eof_notify) => StopCause::Eof, + _ = wait_for_input_termination(&input_termination) => StopCause::InputOverflow, + _ = wait_shutdown_requested(&mut shutdown) => StopCause::Requested, + }; + *cause + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(stop); + let _ = stop_tx.send(Some(stop)); + // The service token is registered after initialization. If it + // arrived first, cancel it; otherwise the post-init loop sees + // the stop watch and cancels it there. + if let Ok(token) = cancel_rx.try_recv() { + token.cancel(); + } + // An EOF during the handshake is given a brief, bounded chance + // to surface rmcp's own protocol verdict (for example a + // rejected non-initialize message) before the abort is + // blamed for the close. Cleanup starts right after that + // window, so the total bound stays finite. + if stop == StopCause::Eof && !init_complete.load(Ordering::SeqCst) { + tokio::time::sleep(INIT_EOF_GRACE).await; + } + abort.abort(); + // No join here: the bounded teardown runs on the blocking + // pool and the serving path waits for its proof under the + // same absolute cutoff instead of joining it synchronously. + drop(tokio::task::spawn_blocking(move || executor.shutdown())); + }) + }; + + // From here on every record, including startup, is written through + // the bounded non-blocking sink. + install_redacting_tracing(); + tracing::debug!( + profile = %self.profile, + "rustscript-agent tool server starting" + ); + if std::env::var_os("RUSTSCRIPT_AGENT_TEST_READY_MARKER").is_some() { + emit_diagnostic(READY_DIAGNOSTIC); + flush_diagnostics(Duration::from_millis(100)); + } + // A file-based readiness signal, independent of the (possibly + // stalled) stderr sink. Test processes use it to apply a tight + // post-readiness teardown bound. Inert unless the variable is set, so + // it is part of default builds too. The write is deliberately + // non-blocking and failure-tolerant: the path may be a FIFO with no + // reader, and a readiness marker must never be able to stop the + // serving future from reaching its bounded exit. + if let Some(path) = std::env::var_os("RUSTSCRIPT_AGENT_TEST_READY_FILE") { + write_readiness_file(&path); + } + + let (input, pump) = PumpReader::spawn( + reader, + Arc::clone(&eof_seen), + Arc::clone(&eof_notify), + input_termination, + ); + + let transport = AbortableTransport::new(input, writer, transport_abort.clone()); + let serve = self.clone().serve(transport); + tokio::pin!(serve); + + let init = tokio::select! { + result = &mut serve => InitOutcome::Served(Box::new(result)), + _ = stop_requested(&mut stop_rx) => { + // The watchdog gives an EOF during the handshake a bounded + // protocol-verdict window before it aborts the transport. + // Wait for that same window plus the teardown grace. + match tokio::time::timeout( + INIT_EOF_GRACE + EOF_TASK_GRACE, + &mut serve, + ) + .await + { + Ok(result) => InitOutcome::Served(Box::new(result)), + Err(_) => InitOutcome::Stalled, + } + } + }; + init_complete.store(true, Ordering::SeqCst); + + let running = match init { + InitOutcome::Served(result) => match *result { + Ok(running) => running, + Err(error) => { + pump.abort(); + watchdog.abort(); + let cleanup = self + .bounded_shutdown(self.cleanup_deadline(EOF_TASK_GRACE)) + .await; + let quit = match &error { + rmcp::service::ServerInitializeError::ConnectionClosed(_) => Some( + read_cause(&cause_slot) + .map(StopCause::into_quit) + .unwrap_or(ToolServerQuit::Closed), + ), + rmcp::service::ServerInitializeError::Cancelled => Some( + read_cause(&cause_slot) + .map(StopCause::into_quit) + .unwrap_or(ToolServerQuit::Cancelled), + ), + // A transport error caused by our own bounded abort of + // a stalled handshake write is not a protocol + // rejection: the recorded stop cause (EOF, lifetime, + // requested shutdown, or terminal input) is + // authoritative. Only an unrecorded transport failure + // is the initialization error. + rmcp::service::ServerInitializeError::TransportError { .. } => { + read_cause(&cause_slot).map(StopCause::into_quit) + } + _ => None, + }; + flush_diagnostics(DIAGNOSTIC_FLUSH_BOUND); + let Some(quit) = quit else { + return Err(ToolServerError::Initialization); + }; + let outcome = self.outcome(quit, cleanup); + emit_guaranteed_diagnostic(&outcome.diagnostic()); + flush_diagnostics(DIAGNOSTIC_FLUSH_BOUND); + return Ok(outcome); + } + }, + InitOutcome::Stalled => { + pump.abort(); + let deadline = self.cleanup_deadline(EOF_TASK_GRACE); + let _ = tokio::time::timeout_at(deadline, &mut watchdog).await; + watchdog.abort(); + let cleanup = self.bounded_shutdown(deadline).await; + let outcome = self.outcome(quit_for_cause(read_cause(&cause_slot)), cleanup); + emit_guaranteed_diagnostic(&outcome.diagnostic()); + flush_diagnostics(DIAGNOSTIC_FLUSH_BOUND); + return Ok(outcome); + } + }; + + let mut cancel_token = Some(running.cancellation_token()); + let _ = cancel_tx.try_send(running.cancellation_token()); + let mut waiting = Box::pin(running.waiting()); + let quit = loop { + if stop_requested_now(&stop_rx) { + if let Some(token) = cancel_token.take() { + token.cancel(); + } + match tokio::time::timeout_at(self.cleanup_deadline(EOF_TASK_GRACE), &mut waiting) + .await + { + Ok(result) => break quit_from_result(result, &cause_slot), + Err(_) => { + // A pending response write is most likely holding + // rmcp's writer lock while the peer is not reading. + // Abort the transport so every send future releases + // that lock and `close` can finish instead of waiting + // on it. + emit_diagnostic(TRANSPORT_CLOSE_TIMEOUT_DIAGNOSTIC); + transport_abort.abort(); + match tokio::time::timeout(EOF_TASK_GRACE, &mut waiting).await { + Ok(result) => break quit_from_result(result, &cause_slot), + Err(_) => break quit_for_cause(read_cause(&cause_slot)), + } + } + } + } + tokio::select! { + result = &mut waiting => break quit_from_result(result, &cause_slot), + _ = stop_requested(&mut stop_rx) => { + if let Some(token) = cancel_token.take() { + token.cancel(); + } + } + } + }; + + let in_flight_deadline = (tokio::time::Instant::now() + self.cancel_grace) + .min(self.cleanup_deadline(EOF_TASK_GRACE)); + self.wait_for_in_flight(in_flight_deadline).await; + let _ = tokio::time::timeout_at(self.cleanup_deadline(EOF_TASK_GRACE), &mut watchdog).await; + watchdog.abort(); + pump.abort(); + let cleanup = self + .bounded_shutdown(self.cleanup_deadline(EOF_TASK_GRACE)) + .await; + // Test-only: fill the diagnostic queue exactly before the teardown + // proof, modelling TRACE pressure at the moment the proof is emitted. + #[cfg(any(test, feature = "workspace-io-fault"))] + flood_diagnostics_for_test(); + let outcome = self.outcome(quit, cleanup); + emit_guaranteed_diagnostic(&outcome.diagnostic()); + flush_diagnostics(DIAGNOSTIC_FLUSH_BOUND); + Ok(outcome) + } + + /// Runs one executor teardown on the blocking pool and waits for its proof + /// only until `deadline`. + /// + /// The teardown itself is internally bounded by the executor's fixed + /// cleanup cutoff, but joining it from the serving thread must not add a + /// second, unbounded wait. If the join cannot complete in time, the proof + /// already recorded by that teardown (or a conservative timeout) is + /// returned instead, and the blocking work keeps running under its own + /// cutoff. + async fn bounded_shutdown(&self, deadline: tokio::time::Instant) -> ProcessCleanupProof { + let executor = Arc::clone(&self.executor); + let join = tokio::task::spawn_blocking(move || executor.shutdown()); + match tokio::time::timeout_at(deadline, join).await { + Ok(Ok(proof)) => proof, + Ok(Err(_)) => self + .executor + .cleanup_outcome() + .unwrap_or(ProcessCleanupProof::Failed { + retained: 1, + code: "cleanup_join_failed".to_string(), + }), + Err(_) => self + .executor + .cleanup_outcome() + .unwrap_or(ProcessCleanupProof::TimedOut { retained: 1 }), + } + } + + fn outcome(&self, quit: ToolServerQuit, cleanup: ProcessCleanupProof) -> ToolServerOutcome { + ToolServerOutcome { + profile: self.profile, + quit, + cleanup, + admitted_calls: self.executor.admitted_call_count(), + } + } + + /// Absolute deadline derived from the executor's fixed cleanup cutoff (or + /// the configured cleanup timeout before teardown starts), plus `extra`. + fn cleanup_deadline(&self, extra: Duration) -> tokio::time::Instant { + let cutoff = self + .executor + .cleanup_cutoff() + .map(tokio::time::Instant::from_std) + .unwrap_or_else(|| tokio::time::Instant::now() + self.executor.cleanup_timeout()); + cutoff + extra + } + + async fn wait_for_in_flight(&self, deadline: tokio::time::Instant) { + while self.in_flight.load(Ordering::SeqCst) > 0 && tokio::time::Instant::now() < deadline { + tokio::time::sleep(IN_FLIGHT_POLL_INTERVAL).await; + } + } +} + +impl ServerHandler for RustScriptToolServer { + fn get_info(&self) -> ServerConfig { + self.info.clone() + } + + async fn list_tools( + &self, + _request: Option, + _context: RequestContext, + ) -> Result { + Ok(ListToolsResult::with_all_items(self.tools.as_ref().clone())) + } + + async fn call_tool( + &self, + request: CallToolRequestParams, + context: RequestContext, + ) -> Result { + // A queue overflow lost the framing of the input stream. No byte after + // it can be trusted, so no new call may be admitted into this session. + if self.input.is_terminated() { + return Err(input_terminated_error()); + } + self.in_flight.fetch_add(1, Ordering::SeqCst); + let _in_flight = InFlightGuard(Arc::clone(&self.in_flight)); + + let call_id = self.executor.next_call_id(); + // An already-cancelled request never reaches the blocking pool: the + // identity is burned under the admission lock (charged to the same + // quota as an admitted call) and the typed refusal is returned without + // spawning or queueing any work. + if context.ct.is_cancelled() { + let error = self.executor.refuse_cancelled_call(&call_id); + return Err(executor_error_to_mcp_error(&error)); + } + let tool_name = request.name.to_string(); + let arguments = request + .arguments + .map(Value::Object) + .unwrap_or_else(|| Value::Object(JsonObject::new())); + let request_token = context.ct.clone(); + let request_cancellation = AdmissionCancellation::new(move || request_token.is_cancelled()); + let executor = Arc::clone(&self.executor); + let blocking_id = call_id.clone(); + let mut task = tokio::task::spawn_blocking(move || { + executor.execute_tool_with_cancellation( + Some(&blocking_id), + &tool_name, + &arguments, + Some(request_cancellation), + ) + }); + + tokio::select! { + joined = &mut task => finish_call(joined), + _ = context.ct.cancelled() => { + // Durable before the wait: if the worker has not reached + // admission yet, the executor records the intent and refuses + // the call there instead of executing it after this handler + // gives up. `admit_call` additionally re-checks the cancelled + // request token under the admission lock. + let _ = self.executor.cancel_call(&call_id); + match tokio::time::timeout(self.cancel_grace, &mut task).await { + Ok(joined) => finish_call(joined), + Err(_) => { + self.cancelled_after_grace.fetch_add(1, Ordering::SeqCst); + Err(cancelled_error(&call_id)) + } + } + } + } + } +} + +struct InFlightGuard(Arc); + +impl Drop for InFlightGuard { + fn drop(&mut self) { + self.0.fetch_sub(1, Ordering::SeqCst); + } +} + +/// Maps one executor refusal to its protocol error. +/// +/// Retention is the one nonterminal executor disposition: it keeps +/// `terminal: false`, names the executor error code, and forbids replay. +pub fn executor_error_to_mcp_error(error: &McpToolExecutorError) -> rmcp::ErrorData { + let mut data = json!({ + ERROR_CODE_DATA_KEY: error.code(), + TERMINAL_DATA_KEY: true, + REPLAY_DATA_KEY: false, + }); + let (wire_code, message) = match error { + McpToolExecutorError::UnknownTool { name } => { + (ErrorCode::INVALID_PARAMS.0, format!("unknown tool: {name}")) + } + McpToolExecutorError::DisabledTool { name, risk_class } => ( + ErrorCode::INVALID_PARAMS.0, + format!("tool {name} ({risk_class}) is disabled by the selected profile"), + ), + McpToolExecutorError::InvalidArguments { message } => ( + ErrorCode::INVALID_PARAMS.0, + format!("invalid tool arguments: {message}"), + ), + McpToolExecutorError::InvalidCallId { message } => ( + ErrorCode::INVALID_PARAMS.0, + format!("invalid tool call id: {message}"), + ), + McpToolExecutorError::DuplicateCallId { call_id } => ( + ErrorCode::INVALID_PARAMS.0, + format!("duplicate tool call id: {call_id}"), + ), + McpToolExecutorError::Cancelled { call_id } => { + data[TERMINAL_DATA_KEY] = json!(false); + data["call_id"] = json!(call_id); + ( + CANCELLED_ERROR_CODE, + format!("tool call {call_id} was cancelled before admission"), + ) + } + McpToolExecutorError::Retained { call_id } => { + data[TERMINAL_DATA_KEY] = json!(false); + data["call_id"] = json!(call_id); + ( + RETAINED_ERROR_CODE, + format!( + "tool call {call_id} is retained until its publisher settles; do not re-execute" + ), + ) + } + McpToolExecutorError::CallQuotaExhausted { limit } => ( + ErrorCode::INTERNAL_ERROR.0, + format!("tool call admission quota exhausted (limit {limit})"), + ), + McpToolExecutorError::Closed => (ErrorCode::INTERNAL_ERROR.0, error.to_string()), + McpToolExecutorError::LifetimeElapsed => (ErrorCode::INTERNAL_ERROR.0, error.to_string()), + McpToolExecutorError::InvalidConfig { .. } + | McpToolExecutorError::RegistryUnavailable { .. } + | McpToolExecutorError::DispatchUnavailable { .. } + | McpToolExecutorError::CapabilityUnavailable { .. } + | McpToolExecutorError::DispatchFailed { .. } + | McpToolExecutorError::InvalidDispatchOutput { .. } => { + (ErrorCode::INTERNAL_ERROR.0, error.to_string()) + } + }; + rmcp::ErrorData::new( + ErrorCode(wire_code), + truncate_error_message(&message), + Some(data), + ) +} + +fn input_terminated_error() -> rmcp::ErrorData { + rmcp::ErrorData::new( + ErrorCode::INTERNAL_ERROR, + "tool server input is no longer usable", + Some(json!({ + ERROR_CODE_DATA_KEY: "input_terminated", + TERMINAL_DATA_KEY: true, + REPLAY_DATA_KEY: false, + })), + ) +} + +fn cancelled_error(call_id: &str) -> rmcp::ErrorData { + rmcp::ErrorData::new( + ErrorCode(CANCELLED_ERROR_CODE), + "tool call cancelled before it settled", + Some(json!({ + ERROR_CODE_DATA_KEY: "cancelled", + TERMINAL_DATA_KEY: false, + REPLAY_DATA_KEY: false, + "call_id": call_id, + })), + ) +} + +fn finish_call( + joined: Result, tokio::task::JoinError>, +) -> Result { + match joined { + Ok(Ok(result)) => Ok(to_call_tool_result(&result).into()), + Ok(Err(error)) => Err(executor_error_to_mcp_error(&error)), + Err(_) => Err(rmcp::ErrorData::new( + ErrorCode::INTERNAL_ERROR, + "tool call task failed", + Some(json!({ + ERROR_CODE_DATA_KEY: "task_failed", + TERMINAL_DATA_KEY: false, + REPLAY_DATA_KEY: false, + })), + )), + } +} + +/// One-way abort shared with the wrapper transport. +/// +/// Once aborted, every pending `send` future returns an error instead of +/// waiting for rmcp's writer lock, and `close` stops waiting for that lock. +#[derive(Clone)] +struct TransportAbort { + aborted: Arc, + notify: Arc, +} + +impl TransportAbort { + fn new() -> Self { + Self { + aborted: Arc::new(AtomicBool::new(false)), + notify: Arc::new(Notify::new()), + } + } + + fn abort(&self) { + if !self.aborted.swap(true, Ordering::SeqCst) { + self.notify.notify_waiters(); + } + } + + fn is_aborted(&self) -> bool { + self.aborted.load(Ordering::SeqCst) + } + + async fn cancelled(&self) { + loop { + if self.is_aborted() { + return; + } + let notified = self.notify.notified(); + if self.is_aborted() { + return; + } + notified.await; + } + } +} + +/// rmcp transport wrapper that can be aborted when a peer stops reading. +struct AbortableTransport { + inner: AsyncRwTransport, + abort: TransportAbort, +} + +impl AbortableTransport +where + R: AsyncRead + Send + Unpin + 'static, + W: AsyncWrite + Send + Unpin + 'static, +{ + fn new(reader: R, writer: W, abort: TransportAbort) -> Self { + Self { + inner: AsyncRwTransport::new(reader, writer), + abort, + } + } +} + +impl Transport for AbortableTransport +where + R: AsyncRead + Send + Unpin + 'static, + W: AsyncWrite + Send + Unpin + 'static, +{ + type Error = std::io::Error; + + fn send( + &mut self, + item: TxJsonRpcMessage, + ) -> impl Future> + Send + 'static { + let send = self.inner.send(item); + let abort = self.abort.clone(); + async move { + tokio::select! { + result = send => result, + _ = abort.cancelled() => Err(std::io::Error::new( + std::io::ErrorKind::NotConnected, + "tool server transport aborted", + )), + } + } + } + + async fn receive(&mut self) -> Option> { + tokio::select! { + message = self.inner.receive() => message, + _ = self.abort.cancelled() => None, + } + } + + async fn close(&mut self) -> Result<(), Self::Error> { + if self.abort.is_aborted() { + // A blocked response write must not keep rmcp waiting on the + // writer lock during teardown. + return Ok(()); + } + self.inner.close().await + } +} + +/// Async reader fed by a dedicated pump task that owns the peer input. +/// +/// The pump reads regardless of whether rmcp is polling this reader. EOF is +/// therefore observed while rmcp is blocked in `send` (initialize response) or +/// in the transport's own invalid-request flush inside `receive`. +/// +/// Overflow of the pre-read queue is terminal for protocol input. Bytes are +/// never discarded and forwarding resumed: a parser that lost an arbitrary +/// chunk could silently drop a cancellation or accept a spliced request. The +/// pump instead latches [`InputTermination`], stops forwarding, refuses new +/// calls, starts bounded cleanup, and keeps reading only to observe EOF. +struct PumpReader { + chunks: mpsc::Receiver>, + current: Vec, + offset: usize, + eof_seen: Arc, +} + +impl PumpReader { + fn spawn( + mut reader: R, + eof_seen: Arc, + eof_notify: Arc, + termination: Arc, + ) -> (Self, tokio::task::JoinHandle<()>) + where + R: AsyncRead + Send + Unpin + 'static, + { + let (sender, chunks) = mpsc::channel::>(INPUT_QUEUE_CHUNKS); + let pump_eof = Arc::clone(&eof_seen); + let task = tokio::spawn(async move { + let mut buffer = vec![0u8; INPUT_CHUNK_BYTES]; + loop { + match reader.read(&mut buffer).await { + Ok(0) => break, + Ok(filled) => { + if termination.is_terminated() { + // Framing is already lost. Keep draining the peer + // so EOF stays observable, but never forward + // another byte to the parser. + continue; + } + match sender.try_send(buffer[..filled].to_vec()) { + Ok(()) => {} + // The parser fell far enough behind that the + // bounded queue is full: the transport input is + // terminal, not merely backpressured. + Err(mpsc::error::TrySendError::Full(_)) => { + termination.terminate(); + } + Err(mpsc::error::TrySendError::Closed(_)) => return, + } + } + Err(_) => break, + } + } + pump_eof.store(true, Ordering::SeqCst); + eof_notify.notify_one(); + }); + ( + Self { + chunks, + current: Vec::new(), + offset: 0, + eof_seen, + }, + task, + ) + } +} + +impl AsyncRead for PumpReader { + fn poll_read( + mut self: Pin<&mut Self>, + context: &mut Context<'_>, + buffer: &mut ReadBuf<'_>, + ) -> Poll> { + if buffer.remaining() == 0 { + return Poll::Ready(Ok(())); + } + loop { + if self.offset < self.current.len() { + let remaining = &self.current[self.offset..]; + let take = remaining.len().min(buffer.remaining()); + buffer.put_slice(&remaining[..take]); + self.offset += take; + return Poll::Ready(Ok(())); + } + match self.chunks.poll_recv(context) { + Poll::Ready(Some(chunk)) => { + self.current = chunk; + self.offset = 0; + } + // The pump dropped its sender: the stream ended (cleanly or + // with an I/O error, both are terminal here). + Poll::Ready(None) => return Poll::Ready(Ok(())), + Poll::Pending => { + if self.eof_seen.load(Ordering::SeqCst) { + // The pump observed EOF but this channel currently has + // no queued chunk; deliver the zero-length read. + return Poll::Ready(Ok(())); + } + return Poll::Pending; + } + } + } + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum StopCause { + Requested, + Lifetime, + Eof, + InputOverflow, +} + +impl StopCause { + const fn into_quit(self) -> ToolServerQuit { + match self { + Self::Requested => ToolServerQuit::Cancelled, + Self::Lifetime => ToolServerQuit::LifetimeElapsed, + Self::Eof => ToolServerQuit::Closed, + Self::InputOverflow => ToolServerQuit::InputTerminated, + } + } +} + +/// One-way latch for a terminal protocol-input overflow. +/// +/// The reader pump, the watchdog, every call handler, and the executor's +/// admission path share it. Setting it is non-blocking and idempotent: the +/// pump stops forwarding bytes, the watchdog starts the same bounded cleanup +/// as an orderly close, every active call is cancelled through the installed +/// hook, and new calls are refused at admission instead of being admitted +/// into a stream that lost framing. +struct InputTermination { + terminated: Arc, + notify: Notify, + /// Runs once when the latch first closes. The server installs the + /// executor's `cancel_active_calls` here so in-flight work stops without + /// waiting for the watchdog task to be scheduled. + on_terminate: OnceLock>, +} + +impl InputTermination { + fn new() -> Self { + Self { + terminated: Arc::new(AtomicBool::new(false)), + notify: Notify::new(), + on_terminate: OnceLock::new(), + } + } + + /// The exact latch the executor's admission path reads. + fn latch(&self) -> Arc { + Arc::clone(&self.terminated) + } + + fn set_on_terminate(&self, hook: Box) { + let _ = self.on_terminate.set(hook); + } + + fn terminate(&self) { + if !self.terminated.swap(true, Ordering::SeqCst) { + if let Some(hook) = self.on_terminate.get() { + hook(); + } + self.notify.notify_waiters(); + } + } + + fn is_terminated(&self) -> bool { + self.terminated.load(Ordering::SeqCst) + } + + async fn wait_terminated(&self) { + loop { + if self.is_terminated() { + return; + } + let notified = self.notify.notified(); + if self.is_terminated() { + return; + } + notified.await; + } + } +} + +async fn wait_for_input_termination(termination: &InputTermination) { + termination.wait_terminated().await; +} + +type ToolServerInit = Result< + rmcp::service::RunningService, + rmcp::service::ServerInitializeError, +>; + +enum InitOutcome { + Served(Box), + Stalled, +} + +fn read_cause(slot: &StdMutex>) -> Option { + *slot.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) +} + +fn quit_for_cause(cause: Option) -> ToolServerQuit { + match cause { + Some(cause) => cause.into_quit(), + None => ToolServerQuit::Aborted, + } +} + +fn quit_from_result( + result: Result, + cause_slot: &StdMutex>, +) -> ToolServerQuit { + match result { + // A stop cause recorded before the service closed is authoritative: + // the watchdog aborts the transport, so rmcp reports `Closed` even + // when the cause was the lifetime bound or an external shutdown. + Ok(QuitReason::Closed) => match read_cause(cause_slot) { + Some(cause) => cause.into_quit(), + None => ToolServerQuit::Closed, + }, + Ok(QuitReason::Cancelled) => match read_cause(cause_slot) { + Some(cause) => cause.into_quit(), + None => ToolServerQuit::Cancelled, + }, + Ok(_) | Err(_) => ToolServerQuit::Aborted, + } +} + +async fn wait_for_eof(eof_seen: &AtomicBool, notify: &Notify) { + loop { + if eof_seen.load(Ordering::SeqCst) { + return; + } + notify.notified().await; + } +} + +async fn wait_shutdown_requested(shutdown: &mut Option>) { + match shutdown.as_mut() { + Some(receiver) => watch_requested(receiver).await, + None => std::future::pending::<()>().await, + } +} + +fn stop_requested_now(receiver: &watch::Receiver>) -> bool { + receiver.borrow().is_some() +} + +async fn stop_requested(receiver: &mut watch::Receiver>) { + loop { + if receiver.borrow().is_some() { + return; + } + if receiver.changed().await.is_err() { + std::future::pending::<()>().await; + } + } +} + +async fn watch_requested(receiver: &mut watch::Receiver) { + loop { + let requested = *receiver.borrow(); + if requested { + return; + } + if receiver.changed().await.is_err() { + std::future::pending::<()>().await; + } + } +} + +fn canonical_workspace(workspace: &Path) -> Result { + if workspace.as_os_str().is_empty() { + return Err(ToolServerError::WorkspaceEmpty); + } + if workspace.to_string_lossy().contains('\0') { + return Err(ToolServerError::WorkspaceUnresolvable { + message: "workspace path contains NUL".to_string(), + }); + } + if !workspace.is_absolute() { + return Err(ToolServerError::WorkspaceNotAbsolute); + } + let canonical = std::fs::canonicalize(workspace).map_err(|error| { + ToolServerError::WorkspaceUnresolvable { + message: truncate_diagnostic(&error.to_string()), + } + })?; + if !canonical.is_dir() { + return Err(ToolServerError::WorkspaceNotDirectory); + } + Ok(canonical) +} + +fn invalid_configuration(error: &McpToolExecutorError) -> ToolServerError { + ToolServerError::InvalidConfiguration { + message: truncate_diagnostic(&error.to_string()), + } +} + +fn truncate_error_message(value: &str) -> String { + truncate_to(value, MAX_ERROR_MESSAGE_BYTES) +} + +fn sanitize_diagnostic(value: &str) -> String { + value + .chars() + .map(|character| { + if character == '\n' || character == '\t' || character.is_control() { + ' ' + } else { + character + } + }) + .collect() +} + +fn truncate_diagnostic(value: &str) -> String { + truncate_to(value, MAX_DIAGNOSTIC_BYTES) +} + +fn truncate_to(value: &str, limit: usize) -> String { + let sanitized = sanitize_diagnostic(value); + if sanitized.len() <= limit { + return sanitized; + } + let mut end = limit; + while !sanitized.is_char_boundary(end) { + end -= 1; + } + sanitized[..end].to_string() +} + +fn emit_diagnostic(line: &str) { + enqueue_diagnostic(truncate_diagnostic(line), false); +} + +/// Writes the readiness marker without ever blocking the serving path. +/// +/// The marker path is environment-selected, so it can be a FIFO whose reader +/// never opens it; a blocking `open`/`write` there would stop the serving +/// future before the reader pump even starts and keep the process alive past +/// its watchdog. Unix opens the path with `O_NONBLOCK` (which fails fast with +/// `ENXIO` on a reader-less FIFO) and ignores every error. Windows has no +/// blocking FIFO semantics for a plain file write, so it keeps the direct +/// write and still ignores the result. +fn write_readiness_file(path: &std::ffi::OsStr) { + #[cfg(unix)] + { + use std::io::Write as _; + use std::os::unix::fs::OpenOptionsExt as _; + + let opened = std::fs::OpenOptions::new() + .write(true) + .create(true) + .custom_flags(libc::O_NONBLOCK) + .open(path); + if let Ok(mut file) = opened { + let _ = file.write_all(READY_DIAGNOSTIC.as_bytes()); + } + } + #[cfg(not(unix))] + { + let _ = std::fs::write(path, READY_DIAGNOSTIC); + } +} + +/// Emits a line that must not be lost to TRACE pressure. +/// +/// The queue always keeps one slot free for these lines, and a guaranteed +/// line is accepted even when every normal slot is occupied (evicting the +/// oldest normal line instead). The teardown proof and constructor failures +/// use this path; a stalled sink still bounds delivery by [`flush_diagnostics`]. +fn emit_guaranteed_diagnostic(line: &str) { + enqueue_diagnostic(truncate_diagnostic(line), true); +} + +/// Enqueues one bounded diagnostic line without blocking. +fn enqueue_diagnostic(line: String, guaranteed: bool) { + let sink = diagnostic_sink(); + let mut queue = sink + .queue + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if guaranteed { + // The reserved slot: accept even at capacity, evicting the oldest + // normal line so the queue stays inside its documented bound. The + // evicted line will never be written, so its pending credit is + // released here; otherwise a flush could spend its whole budget + // waiting for a line that no longer exists. + if queue.len() >= DIAGNOSTIC_QUEUE_LINES { + queue.pop_front(); + sink.pending.fetch_sub(1, Ordering::SeqCst); + } + } else if queue.len() >= DIAGNOSTIC_QUEUE_LINES.saturating_sub(1) { + // Keep one slot free for the guaranteed cleanup proof. + return; + } + sink.pending.fetch_add(1, Ordering::SeqCst); + queue.push_back(line); + drop(queue); + sink.wake.notify_one(); +} + +/// `MakeWriter` that routes every tracing record through the bounded, +/// non-blocking diagnostic sink. +/// +/// tracing-subscriber formats each event into an in-memory buffer and then +/// calls `write_all` once on this writer. The writer only appends to its own +/// buffer; dropping it enqueues one bounded line with `try_send`. No caller, +/// including the serving thread during startup, can ever block on stderr. +#[derive(Clone, Copy, Default)] +struct DiagnosticMakeWriter; + +impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for DiagnosticMakeWriter { + type Writer = DiagnosticLineWriter; + + fn make_writer(&'a self) -> Self::Writer { + DiagnosticLineWriter::default() + } +} + +#[derive(Default)] +struct DiagnosticLineWriter { + line: Vec, +} + +impl std::io::Write for DiagnosticLineWriter { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + let room = MAX_DIAGNOSTIC_BYTES.saturating_sub(self.line.len()); + if room > 0 { + self.line.extend_from_slice(&bytes[..bytes.len().min(room)]); + } + Ok(bytes.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + if !self.line.is_empty() { + let line = String::from_utf8_lossy(&self.line); + emit_diagnostic(&line); + self.line.clear(); + } + Ok(()) + } +} + +impl Drop for DiagnosticLineWriter { + fn drop(&mut self) { + let _ = self.flush(); + } +} + +/// Bounded, non-blocking diagnostic sink. +/// +/// The writer thread is the only caller of `stderr`; a peer that stalls the +/// stderr pipe blocks that thread, never the server. Normal lines are dropped +/// once the queue is full, except that one slot is reserved for guaranteed +/// lines (the teardown proof and constructor failures), which are never lost +/// to TRACE pressure. +struct DiagnosticSink { + queue: StdMutex>, + wake: std::sync::Condvar, + pending: Arc, +} + +fn diagnostic_sink() -> &'static DiagnosticSink { + static SINK: OnceLock> = OnceLock::new(); + SINK.get_or_init(|| { + let sink = Arc::new(DiagnosticSink { + queue: StdMutex::new(VecDeque::new()), + wake: std::sync::Condvar::new(), + pending: Arc::new(AtomicUsize::new(0)), + }); + let writer = Arc::clone(&sink); + let _ = std::thread::Builder::new() + .name("mcp-diagnostics".to_string()) + .spawn(move || diagnostic_writer(writer)); + sink + }) + .as_ref() +} + +/// Drains the bounded queue to stderr. The only stderr writer in the server. +fn diagnostic_writer(sink: Arc) { + loop { + let line = { + let mut queue = sink + .queue + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + loop { + if let Some(line) = queue.pop_front() { + break line; + } + queue = sink + .wake + .wait(queue) + .unwrap_or_else(|poisoned| poisoned.into_inner()); + } + }; + let mut stderr = std::io::stderr().lock(); + let _ = stderr.write_all(line.as_bytes()); + let _ = stderr.write_all(b"\n"); + let _ = stderr.flush(); + sink.pending.fetch_sub(1, Ordering::SeqCst); + } +} + +/// Waits, bounded, for already-queued diagnostics to reach the sink. +fn flush_diagnostics(bound: Duration) { + let sink = diagnostic_sink(); + let deadline = std::time::Instant::now() + bound; + while sink.pending.load(Ordering::SeqCst) > 0 && std::time::Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(1)); + } +} + +/// Test-only: fill the diagnostic queue to simulate TRACE pressure right +/// before the teardown proof. Inert unless the flood variable is set. +#[cfg(any(test, feature = "workspace-io-fault"))] +fn flood_diagnostics_for_test() { + if std::env::var_os("RUSTSCRIPT_AGENT_TEST_DIAGNOSTIC_FLOOD").is_none() { + return; + } + for index in 0..(DIAGNOSTIC_QUEUE_LINES * 2) { + emit_diagnostic(&format!("diagnostic flood line {index}")); + } +} + +/// Installs the bounded stderr writer and the redacting subscriber. +/// +/// The CLI calls this before any fallible server construction, so constructor +/// failures use the same non-blocking writer as the serving path instead of a +/// synchronous `eprintln!` that a stalled stderr pipe could block forever. +pub fn install_tool_server_diagnostics() { + let _ = diagnostic_sink(); + install_redacting_tracing(); +} + +/// Writes one constructor failure through the guaranteed diagnostic slot. +pub fn write_construction_diagnostic(error: &ToolServerError) { + emit_guaranteed_diagnostic(&error.to_string()); + flush_diagnostics(DIAGNOSTIC_FLUSH_BOUND); +} + +/// Writes the exit sweep result, which is otherwise visible only in the exit +/// status. Uses the guaranteed slot so TRACE pressure cannot drop it. +pub fn write_exit_sweep_diagnostic(retained: usize) { + emit_guaranteed_diagnostic(&format!( + "rustscript-agent tools serve exit sweep: retained={retained}" + )); + flush_diagnostics(DIAGNOSTIC_FLUSH_BOUND); +} + +/// Installs the tool server's stderr subscriber unless the embedding process +/// already installed one. +/// +/// The `rmcp` target is disabled at every level. rmcp's service and transport +/// log full peer requests, notifications, and malformed lines at debug/info; +/// with no subscriber those events are inert, but an embedding subscriber that +/// enables them would otherwise copy peer payloads into its own logs. Payloads +/// are never logged by this server: the only enabled rmcp events are the +/// peer-free ones this crate itself emits. +pub fn install_redacting_tracing() { + static INSTALL: std::sync::Once = std::sync::Once::new(); + INSTALL.call_once(|| { + let default = if std::env::var_os("RUSTSCRIPT_AGENT_TOOLS_TRACE").is_some() { + tracing::level_filters::LevelFilter::TRACE + } else { + tracing::level_filters::LevelFilter::WARN + }; + let filter = tracing_subscriber::filter::Targets::new() + .with_default(default) + .with_target("rmcp", tracing::level_filters::LevelFilter::OFF); + let layer = tracing_subscriber::fmt::layer() + .with_writer(DiagnosticMakeWriter) + .with_ansi(false) + .with_filter(filter); + use tracing_subscriber::Layer as _; + use tracing_subscriber::layer::SubscriberExt as _; + let subscriber = tracing_subscriber::registry().with(layer); + let _ = tracing::subscriber::set_global_default(subscriber); + }); +} diff --git a/src/runtime/agent_host.rs b/src/runtime/agent_host.rs index dd9c443b..daa9ef84 100644 --- a/src/runtime/agent_host.rs +++ b/src/runtime/agent_host.rs @@ -691,6 +691,8 @@ pub trait AgentProviderHost: Send + Sync { } pub type ControlCheckHook = Arc; +/// Test-only observation point invoked after a successful durable tool commit. +pub type CommitObserver = Arc; pub type AuthHostFactory = Arc std::result::Result + Send + Sync>; @@ -1756,6 +1758,10 @@ pub struct AgentHostBridges { /// Optional test hook invoked from `agent::control_check` before reading /// cancellation/deadline. Production callers leave this unset. pub control_hook: Option, + /// Optional test observation point invoked after a successful durable + /// `tool_commit` and before the guest receives the commit envelope. + /// Production callers leave this unset. + pub commit_observer: Option, /// Callable program retained for this run. Absent until admission pins one. pub pinned_tool: Option, /// Set only by a Native host that is explicitly stateless. A missing pin @@ -2241,6 +2247,7 @@ pub struct AgentHostState { pub artifacts: Option>, pub(crate) leases: Arc>>, pub(crate) control_hook: Option, + pub(crate) commit_observer: Option, pub(crate) pinned_tool: Option, pub(crate) allow_stateless_pin: bool, pub(crate) expected_call: Option, @@ -2447,6 +2454,12 @@ impl AgentHostState { .map(|grant| grant.outcome.lock().unwrap_or_else(|p| p.into_inner())); if envelope.get("ok") == Some(&JsonValue::Bool(true)) && envelope.get("kind") == Some(&JsonValue::String("execute".to_string())) + // A lifecycle that owns authoritative settlement (the standalone + // MCP executor) must not receive a host-state abort lease: a + // per-run drop would otherwise interrupt a published effect before + // its guard commits the canonical receipt. Managed/gateway + // lifecycles keep their existing RAII abort semantics. + && !lifecycle.defers_lease_abort() && let Some(token) = envelope.get("execution_token").and_then(JsonValue::as_str) && let Ok(lease) = lifecycle.lease(token) { @@ -2752,6 +2765,7 @@ impl AgentHostState { processes: None, artifacts: None, control_hook: None, + commit_observer: None, pinned_tool: None, allow_stateless_pin: false, }; @@ -3258,6 +3272,7 @@ impl AgentHostState { processes: self.processes.clone(), artifacts: self.artifacts.clone(), control_hook: self.control_hook.clone(), + commit_observer: None, pinned_tool: None, allow_stateless_pin: false, }; @@ -5227,6 +5242,14 @@ fn tool_commit_adapter(vm: &mut Vm, args: &[Value]) -> VmResult { Ok(result) => state.capability_commit_value(&token, &json_to_vm_value(&result)), Err(error) => error, }; + // Test-only observation point: the durable commit already happened, but the + // guest has not yet received the commit envelope. + if envelope.get("ok") == Some(&JsonValue::Bool(true)) + && envelope.get("kind").and_then(JsonValue::as_str) == Some("committed") + && let Some(observer) = &state.commit_observer + { + observer(&token); + } return_declared( vm, &super::host_types::AgentToolEnvelope::host_type_schema(), @@ -6726,6 +6749,7 @@ pub fn b1_send( artifacts: None, leases: Arc::new(Mutex::new(HashMap::new())), control_hook: None, + commit_observer: None, pinned_tool: None, allow_stateless_pin: false, expected_call: None, @@ -7556,6 +7580,7 @@ pub fn run() -> map { artifacts: None, leases: Arc::new(Mutex::new(HashMap::new())), control_hook: None, + commit_observer: None, pinned_tool: None, allow_stateless_pin: false, expected_call: None, @@ -7713,6 +7738,7 @@ mod guardian_real_entry_tests { artifacts: None, leases: Arc::new(Mutex::new(HashMap::new())), control_hook: None, + commit_observer: None, pinned_tool: None, allow_stateless_pin: false, expected_call: None, diff --git a/src/runtime/agent_host/option_text_tests.rs b/src/runtime/agent_host/option_text_tests.rs index daaf8aaf..66e526ed 100644 --- a/src/runtime/agent_host/option_text_tests.rs +++ b/src/runtime/agent_host/option_text_tests.rs @@ -151,6 +151,7 @@ fn probe_vm(provider: Arc) -> Vm { artifacts: None, leases: Arc::new(Mutex::new(HashMap::new())), control_hook: None, + commit_observer: None, pinned_tool: None, allow_stateless_pin: false, expected_call: None, @@ -527,6 +528,7 @@ fn main_loop_vm(provider: Arc) -> Vm { artifacts: None, leases: Arc::new(Mutex::new(HashMap::new())), control_hook: None, + commit_observer: None, pinned_tool: None, allow_stateless_pin: true, expected_call: None, diff --git a/src/runtime/agent_host/preview_tests.rs b/src/runtime/agent_host/preview_tests.rs index fbef17f3..e111da0c 100644 --- a/src/runtime/agent_host/preview_tests.rs +++ b/src/runtime/agent_host/preview_tests.rs @@ -195,6 +195,7 @@ fn probe_vm(provider: Arc) -> Vm { artifacts: None, leases: Arc::new(Mutex::new(HashMap::new())), control_hook: None, + commit_observer: None, pinned_tool: None, allow_stateless_pin: false, expected_call: None, @@ -448,6 +449,7 @@ fn main_loop_vm(provider: Arc, fixture: &LifecycleFixture artifacts: None, leases: Arc::new(Mutex::new(HashMap::new())), control_hook: None, + commit_observer: None, pinned_tool: None, allow_stateless_pin: true, expected_call: None, diff --git a/src/runtime/mod.rs b/src/runtime/mod.rs index c0af453c..e4cbbc0e 100644 --- a/src/runtime/mod.rs +++ b/src/runtime/mod.rs @@ -14,7 +14,8 @@ pub(crate) mod native_tools; pub mod rss_runner; pub use agent_host::{ - AgentHostBridges, AgentProviderHost, ControlCheckHook, ScriptedProvider, agent_host_catalog, + AgentHostBridges, AgentProviderHost, CommitObserver, ControlCheckHook, ScriptedProvider, + agent_host_catalog, }; pub use auth_runner::{AuthCommandInput, AuthEntryError, AuthEntryRunner}; pub use rss_runner::{ diff --git a/src/runtime/rss_runner.rs b/src/runtime/rss_runner.rs index eaf5f9bf..e8496f4b 100644 --- a/src/runtime/rss_runner.rs +++ b/src/runtime/rss_runner.rs @@ -502,8 +502,12 @@ pub fn bundled_tool_registry() -> std::result::Result { } fn load_bundled_tool_registry() -> std::result::Result { - let runner = AgentRunner::from_bundled("rss/tools/registry.rss", AgentConfig::default()) - .map_err(|error| error.to_string())?; + let runner = AgentRunner::from_bundled_provider_disabled( + "rss/tools/registry.rss", + "run", + AgentConfig::default(), + ) + .map_err(|error| error.to_string())?; let result = runner .run_with_context(json_to_vm_value( &json!({"kind": "descriptors", "config": {}}), @@ -780,6 +784,9 @@ struct RunCancellationInner { token: CancellationToken, /// Set when a timeout/deadline cannot be represented as `Instant`. deadline_overflow: AtomicBool, + /// Set by the watcher after it really jumped the VM epoch. A test can wait + /// for this acknowledgment instead of racing the watcher's schedule. + epoch_advanced: Arc, } /// RAII guard that disarms the epoch watcher on every exit path, including panic. @@ -833,6 +840,7 @@ impl RunCancellation { stop: Arc::new(AtomicBool::new(false)), token: CancellationToken::new(), deadline_overflow: AtomicBool::new(false), + epoch_advanced: Arc::new(AtomicBool::new(false)), }), } } @@ -888,6 +896,15 @@ impl RunCancellation { self.inner.watcher.lock().expect("watcher lock").is_some() } + /// True once the armed watcher really advanced the VM epoch after a + /// request/deadline. Waiting on this acknowledgment makes a pre-commit + /// stop deterministic; waiting on `requested()` alone does not, because the + /// watcher runs on its own schedule. + #[doc(hidden)] + pub fn epoch_advanced(&self) -> bool { + self.inner.epoch_advanced.load(Ordering::SeqCst) + } + pub fn request(&self, reason: CancellationReason) { let mut requested = self.inner.requested.lock().expect("requested lock"); if requested.is_none() { @@ -940,6 +957,7 @@ impl RunCancellation { deadline_overflow: AtomicBool::new( self.inner.deadline_overflow.load(Ordering::SeqCst), ), + epoch_advanced: Arc::new(AtomicBool::new(false)), }), } } @@ -958,6 +976,7 @@ impl RunCancellation { let requested = Arc::clone(&self.inner.requested); let deadline = Arc::clone(&self.inner.deadline); let token = self.inner.token.clone(); + let epoch_advanced = Arc::clone(&self.inner.epoch_advanced); let watcher = thread::Builder::new() .name("run-epoch-watcher".to_string()) .spawn(move || { @@ -970,6 +989,7 @@ impl RunCancellation { if fire { token.cancel(); epoch.increment_by(RUN_EPOCH_DEADLINE_TICKS); + epoch_advanced.store(true, Ordering::SeqCst); return; } thread::sleep(Duration::from_millis(1)); @@ -994,6 +1014,18 @@ impl Default for RunCancellation { } } +/// Whether an [`AgentRunner`] may reach the default provider bridge. +/// +/// Legacy construction stays provider-enabled. The provider-free MCP tool +/// core uses [`AgentRunner::from_bundled_provider_disabled`] so registry +/// compilation/loading and tool dispatch fail closed without constructing +/// `RssAdapterProvider` or loading native auth credentials. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ProviderMode { + Enabled, + Disabled, +} + /// Compiles and drives one exported `run(context)` callable per run. #[derive(Clone)] pub struct AgentRunner { @@ -1003,7 +1035,11 @@ pub struct AgentRunner { config: AgentConfig, registry: Arc, host: AgentHostBridges, + provider_mode: ProviderMode, prepare_fault: RunnerPrepareFault, + /// Test-only override of the VM epoch check interval. Production runners + /// keep the standard interval. + epoch_check_interval: Option, snapshot_digest: String, /// Private origin metadata of a bundled runner: the chosen catalog key, /// the requested logical export, and the exact root callable. `None` for @@ -1256,6 +1292,18 @@ impl AgentRunner { Self::from_program(program, config, digest) } + /// Compiles one source without any provider or native auth bridge. + /// + /// The runner still compiles the full restricted host catalog, so an + /// `agent::provider_call` that becomes reachable fails closed with a + /// canonical `provider_disabled` envelope instead of constructing the + /// default RSS provider adapter or loading credentials. + pub fn from_source_provider_disabled(source: &str, config: AgentConfig) -> Result { + let mut runner = Self::from_source(source, config)?; + runner.provider_mode = ProviderMode::Disabled; + Ok(runner) + } + pub fn from_file(path: impl AsRef, config: AgentConfig) -> Result { let (program, digest) = compiled_file_program(path.as_ref())?; Self::from_program(program, config, digest) @@ -1282,7 +1330,9 @@ impl AgentRunner { config, registry: Arc::new(registry), host: AgentHostBridges::default(), + provider_mode: ProviderMode::Enabled, prepare_fault: RunnerPrepareFault::None, + epoch_check_interval: None, snapshot_digest, bundled_origin, expected_call: None, @@ -1312,6 +1362,27 @@ impl AgentRunner { Self::from_program_with_origin(program, config, identity, Some(origin)) } + /// Compiles one verified bundled resource without any provider bridge. + /// + /// This is the narrow provider-free execution path used by the standalone + /// MCP tool registry/dispatch runners. It never reads provider credentials + /// and never instantiates the default RSS provider adapter. + pub fn from_bundled_provider_disabled( + resource_key: &str, + entry_export: &str, + config: AgentConfig, + ) -> Result { + let mut runner = Self::from_bundled_named(resource_key, entry_export, config)?; + runner.provider_mode = ProviderMode::Disabled; + Ok(runner) + } + + /// Provider access policy fixed at construction. Legacy callers remain + /// [`ProviderMode::Enabled`]. + pub fn provider_mode(&self) -> ProviderMode { + self.provider_mode + } + /// The embedded catalog key this runner was compiled from, or `None` for a /// legacy source/file runner. Consumed by service integration. #[allow(dead_code)] @@ -1337,6 +1408,14 @@ impl AgentRunner { self } + /// Test-only deterministic control over how often the VM observes armed + /// cancellation. Production runners keep [`RUN_EPOCH_CHECK_INTERVAL`]. + #[doc(hidden)] + pub fn with_epoch_check_interval_for_test(mut self, interval: u32) -> Self { + self.epoch_check_interval = Some(interval.max(1)); + self + } + /// Installs a scripted or custom provider for the serial loop host bridge. pub fn with_provider(mut self, provider: Arc) -> Self { self.host.provider = Some(provider); @@ -1345,7 +1424,8 @@ impl AgentRunner { /// Replaces the full host-bridge bundle for one run. pub fn with_host(mut self, host: AgentHostBridges) -> Self { - if host.provider.is_none() + if self.provider_mode == ProviderMode::Enabled + && host.provider.is_none() && host.auth_host_factory.is_some() && self .program @@ -1601,10 +1681,17 @@ impl AgentRunner { self.registry .bind_vm_cached(&mut vm) .map_err(RunError::Setup)?; - let provider: Arc = - self.host.provider.clone().unwrap_or_else(|| { + if self.provider_mode == ProviderMode::Disabled && self.host.auth_host_factory.is_some() { + return Err(RunError::Setup(VmError::HostError( + "provider-disabled runner cannot install an auth host factory".to_string(), + ))); + } + let provider: Arc = match self.provider_mode { + ProviderMode::Disabled => Arc::new(ProviderDisabledHost), + ProviderMode::Enabled => self.host.provider.clone().unwrap_or_else(|| { new_default_agent_provider_host(self.host.auth_host_factory.clone(), None) - }); + }), + }; vm.host_context().set_module_state(AgentHostState { provider, cancellation: cancellation @@ -1621,6 +1708,7 @@ impl AgentRunner { artifacts: self.host.artifacts.clone(), leases: Arc::new(Mutex::new(HashMap::new())), control_hook: self.host.control_hook.clone(), + commit_observer: self.host.commit_observer.clone(), pinned_tool: self.host.pinned_tool.clone(), allow_stateless_pin: self.host.allow_stateless_pin, expected_call: self.expected_call.clone(), @@ -1660,8 +1748,11 @@ impl AgentRunner { None }; if let Some(cancellation) = cancellation { - vm.set_epoch_check_interval(RUN_EPOCH_CHECK_INTERVAL) - .map_err(RunError::Setup)?; + vm.set_epoch_check_interval( + self.epoch_check_interval + .unwrap_or(RUN_EPOCH_CHECK_INTERVAL), + ) + .map_err(RunError::Setup)?; vm.set_epoch_deadline(RUN_EPOCH_DEADLINE_TICKS) .map_err(RunError::Setup)?; cancellation.arm(vm.epoch_handle()); @@ -2058,6 +2149,37 @@ fn new_default_agent_provider_host( }) } +/// Fail-closed provider bridge for provider-free runners. +/// +/// It owns no adapter, auth factory, credential store, or network client. A +/// reachable `agent::provider_call` receives the canonical typed failure. +struct ProviderDisabledHost; + +impl AgentProviderHost for ProviderDisabledHost { + fn call( + &self, + _request: &serde_json::Value, + _cancellation: &RunCancellation, + ) -> serde_json::Value { + super::agent_host::typed_fail( + "provider_disabled", + "provider access is disabled for this runner", + ) + } + + fn approval_storage( + &self, + _operation: &str, + _payload: &serde_json::Value, + _cancellation: &RunCancellation, + ) -> serde_json::Value { + super::agent_host::typed_fail( + "provider_disabled", + "provider access is disabled for this runner", + ) + } +} + struct RssAdapterProvider { /// Native auth host factory injected into the child VM. `None` fails closed. factory: Option, @@ -2209,7 +2331,9 @@ pub(crate) fn invoke_retained_tool_with_child( config: AgentConfig::default(), registry: Arc::clone(registry), host, + provider_mode: ProviderMode::Enabled, prepare_fault: RunnerPrepareFault::None, + epoch_check_interval: None, snapshot_digest: "pinned-tool".to_string(), bundled_origin: None, expected_call, @@ -2248,7 +2372,9 @@ pub(crate) fn invoke_retained_child( config: AgentConfig::default(), registry: Arc::clone(registry), host, + provider_mode: ProviderMode::Enabled, prepare_fault: RunnerPrepareFault::None, + epoch_check_interval: None, snapshot_digest: "pinned-child".to_string(), bundled_origin: None, expected_call: None, diff --git a/src/service.rs b/src/service.rs index d18e6584..6c3a8bb0 100644 --- a/src/service.rs +++ b/src/service.rs @@ -45,8 +45,8 @@ use uuid::Uuid; use crate::capabilities::{ ArtifactCapability, ArtifactLimits, CancellationFlag, CapabilityLifecycle, CapabilityOwner, DurableStarted, DurableToolLifecycle, FilesystemCapability, FilesystemLimits, - GuardianApprovalGate, LifecycleError, LifecycleLimits, ProcessCapability, ProcessLimits, - SystemClock, UuidIssuer, + GuardianApprovalGate, LifecycleError, LifecycleLimits, ProcessCapability, ProcessCleanupProof, + ProcessLimits, SystemClock, UuidIssuer, }; use crate::config::{ ADMISSION_IDEMPOTENCY_SCOPE, ADMISSION_RUN_COL_ID, ADMISSION_RUN_COL_INPUT_JSON, @@ -100,6 +100,21 @@ pub enum CleanupOutcome { Failed, } +/// One close's outcome merged with the outcome already published beside its +/// snapshot. A proven `Clean` and a retained `Failed` are never downgraded; +/// `Timeout` upgrades as later evidence proves settlement or failure. +fn merge_cleanup_outcomes( + previous: Option, + candidate: CleanupOutcome, +) -> CleanupOutcome { + match previous { + None => candidate, + Some(CleanupOutcome::Clean) => CleanupOutcome::Clean, + Some(CleanupOutcome::Failed) => CleanupOutcome::Failed, + Some(CleanupOutcome::Timeout) => candidate, + } +} + /// Private tagged agent entry route. `File` keeps the original live-tree /// compile/freshness behavior (fixed install path only). `Bundled` names an /// embedded catalog key admitted by the RSS source policy; it is compiled @@ -292,7 +307,15 @@ pub struct RunHandle { occupancy: AtomicBool, /// One transport scheduling claim for a newly restored admission. restore_worker_started: Option, - cleanup_outcome: Mutex>, + /// Test-only observation point at the exact moment a closed snapshot and + /// its outcome are published, so a concurrent observer can be proven + /// consistent rather than checked only after the release returns. + #[cfg(test)] + close_publish_observer: Mutex>>, + /// First capability-recovery failure observed by a stop/halt path. It is + /// never silently discarded: the value is retained for diagnosis and the + /// typed cleanup outcome is downgraded to `Failed`. + capability_stop_error: Mutex>, /// Sealed tool program for this run. Never reconstructed from request JSON. pinned_tool: Option, native_disposition: Option, @@ -354,6 +377,16 @@ struct CapabilityHostState { filesystem: Option>, processes: Option>, artifacts: Arc, + /// Typed result of the one process-table teardown. A repeated cleanup + /// reports this retained proof instead of inferring Clean from an emptied + /// table. + cleanup_proof: Mutex>, + /// Recovery error retained by the one capability teardown. A failed + /// recovery is never reported as a silent clean close. + recovery_error: Mutex>, + /// Open execution tokens a successful-but-partial recovery left behind. + /// They stay owned for a retry, so this teardown must never report Clean. + open_tokens: Mutex, } /// Two-phase capability-host slot. The handle lock is never held across @@ -363,12 +396,96 @@ enum CapabilityHostPhase { Empty, Initializing, Ready(Arc), + /// Teardown began and its typed proof is not yet published. A concurrent + /// release must report an unknown/pending outcome, never Clean. + Closing, Closed(Option), } #[derive(Clone)] struct ClosedCapabilityHost { processes: Option>, + /// Lifecycle retained with the open tokens so a later close retry can + /// settle them instead of reporting the same `Timeout` forever. + lifecycle: Option>, + /// Recovery failure retained by this close, if any. + recovery_error: Option, + /// Proof recorded by the one capability-host teardown. `None` means the + /// teardown did not complete, so a repeated release can never claim Clean. + proof: Option, + /// Open tokens a partial recovery left owned for a retry. + open_tokens: usize, + /// Serializes the settlement retry with the snapshot write-back. Two + /// concurrent releases must not clone the same snapshot, retry against + /// different recovery states and overwrite each other's result. + retry: Arc>, + /// Caller-visible outcome published with this exact snapshot under the + /// same phase gate. A concurrent release reads both together instead of + /// observing refreshed state next to an older outcome cache. + outcome: CleanupOutcome, +} + +impl ClosedCapabilityHost { + /// Terminal snapshot for a close that owned no capability host at all. + /// The process proof is a real `Clean` (nothing was ever owned), so the + /// accessor and the caller observe the same outcome instead of `None`. + fn without_host() -> Self { + Self { + processes: None, + lifecycle: None, + recovery_error: None, + proof: Some(ProcessCleanupProof::Clean), + open_tokens: 0, + retry: Arc::new(Mutex::new(())), + outcome: CleanupOutcome::Clean, + } + } + + /// Retries the settlement a partial close left owned by this host. A + /// successful retry clears the retained-token outcome; a publisher that is + /// still in flight leaves it pending for the next close attempt. + fn retry_settlement(&mut self) { + if self.open_tokens == 0 { + return; + } + let Some(lifecycle) = self.lifecycle.as_ref() else { + return; + }; + match lifecycle.recover_open_tokens() { + Ok(_) => { + // Re-read the live count: a concurrent owner may have settled + // one token while this retry was running. + self.open_tokens = lifecycle.open_token_count(); + } + Err(error) => { + self.recovery_error = Some(error.message()); + } + } + } + + fn outcome(&mut self) -> CleanupOutcome { + self.retry_settlement(); + if self.recovery_error.is_some() { + return CleanupOutcome::Failed; + } + if self.open_tokens != 0 { + return CleanupOutcome::Timeout; + } + match &self.proof { + Some(ProcessCleanupProof::Clean) + if self + .processes + .as_ref() + .is_none_or(|processes| processes.table_len() == 0) => + { + CleanupOutcome::Clean + } + Some(ProcessCleanupProof::Clean) => CleanupOutcome::Timeout, + Some(ProcessCleanupProof::TimedOut { .. }) => CleanupOutcome::Timeout, + Some(ProcessCleanupProof::Failed { .. }) => CleanupOutcome::Failed, + None => CleanupOutcome::Timeout, + } + } } /// Restores a retriable `Empty` phase if initialization panics or returns @@ -415,40 +532,158 @@ impl CapabilityHostState { fn shutdown_with_grace(&self, grace: Duration) -> CleanupOutcome { if self.cleaned.swap(true, Ordering::SeqCst) { - return if self - .processes - .as_ref() - .is_none_or(|processes| processes.table_len() == 0) - { - CleanupOutcome::Clean - } else { - CleanupOutcome::Timeout - }; + return self.retained_cleanup_outcome(); } if let Some(observer) = &self.shutdown_entered { observer(); } + let deadline = Instant::now() + .checked_add(grace) + .unwrap_or_else(Instant::now); if let Some(release) = &self.uncooperative { - let started = Instant::now(); - while !release.load(Ordering::SeqCst) && started.elapsed() < grace { + while !release.load(Ordering::SeqCst) && Instant::now() < deadline { thread::sleep(Duration::from_millis(10)); } if !release.load(Ordering::SeqCst) { + *self + .cleanup_proof + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = + Some(ProcessCleanupProof::TimedOut { + retained: self + .processes + .as_ref() + .map_or(0, |processes| processes.table_len()), + }); return CleanupOutcome::Timeout; } } - if let Some(processes) = &self.processes { - processes.shutdown_all(); + let proof = match &self.processes { + Some(processes) => processes.shutdown_all_within(deadline), + None => ProcessCleanupProof::Clean, + }; + *self + .cleanup_proof + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(proof.clone()); + // An unproven cleanup keeps its token and process ownership for a + // retry; only a clean proof may retire the open resources. A recovery + // failure is never discarded: it is retained on this host and the + // close is reported as failed. + let mut recovery_failed = false; + let mut retained_tokens = 0usize; + if proof.is_clean() { + match self.lifecycle.recover_open_tokens() { + Ok(_) => { + // A successful return may still have skipped a call whose + // publisher was in flight. Its token stays open for the + // owner's retry, so this close is not clean. + retained_tokens = self.lifecycle.open_token_count(); + } + Err(error) => { + recovery_failed = true; + // Record the ownership the failed settlement left behind. + // The closed host keeps this count so a later release can + // retry the same tokens instead of skipping the retry. + *self + .open_tokens + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = + self.lifecycle.open_token_count(); + *self + .recovery_error + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(error.message()); + tracing::error!( + error = %error.message(), + "capability token recovery failed during cleanup" + ); + } + } + } + if recovery_failed { + return CleanupOutcome::Failed; } - let _ = self.lifecycle.recover_open_tokens(); - if self - .processes - .as_ref() - .is_some_and(|processes| processes.table_len() > 0) + if retained_tokens != 0 { + *self + .open_tokens + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = retained_tokens; + return CleanupOutcome::Timeout; + } + match proof { + ProcessCleanupProof::Clean => CleanupOutcome::Clean, + ProcessCleanupProof::TimedOut { .. } => CleanupOutcome::Timeout, + ProcessCleanupProof::Failed { .. } => CleanupOutcome::Failed, + } + } + + /// Recovery error retained by the one teardown, if any. + fn recovery_error(&self) -> Option { + self.recovery_error + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .clone() + } + + /// Repeated cleanup observes the typed proof recorded by the one teardown. + /// It never upgrades an unproven/partial result to Clean. + fn retained_cleanup_outcome(&self) -> CleanupOutcome { + // A failed recovery is part of the teardown's typed result. It must + // stay failed for every later observer; only a proof that never saw a + // recovery failure may be evaluated below. + if self.recovery_error().is_some() { + return CleanupOutcome::Failed; + } + if *self + .open_tokens + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + != 0 { - CleanupOutcome::Timeout - } else { - CleanupOutcome::Clean + return CleanupOutcome::Timeout; + } + let proof = self + .cleanup_proof + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .clone(); + match proof { + Some(ProcessCleanupProof::Clean) => { + if self + .processes + .as_ref() + .is_some_and(|processes| processes.table_len() > 0) + { + CleanupOutcome::Timeout + } else { + CleanupOutcome::Clean + } + } + Some(ProcessCleanupProof::TimedOut { .. }) => CleanupOutcome::Timeout, + Some(ProcessCleanupProof::Failed { .. }) => CleanupOutcome::Failed, + None => CleanupOutcome::Timeout, + } + } + + /// Snapshot of everything a closed host retains for a later close retry, + /// including the caller-visible outcome the same teardown produced. + fn close_snapshot(&self, outcome: CleanupOutcome) -> ClosedCapabilityHost { + ClosedCapabilityHost { + processes: self.processes.clone(), + lifecycle: Some(Arc::clone(&self.lifecycle)), + recovery_error: self.recovery_error(), + proof: self + .cleanup_proof + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .clone(), + open_tokens: *self + .open_tokens + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()), + retry: Arc::new(Mutex::new(())), + outcome, } } @@ -470,6 +705,7 @@ impl CapabilityHostState { processes: self.processes.clone(), artifacts: Some(Arc::clone(&self.artifacts)), control_hook: None, + commit_observer: None, pinned_tool: None, allow_stateless_pin: false, } @@ -535,11 +771,28 @@ impl RunHandle { if let Some(processes) = processes { processes.cancel_all(); } - if let Some(lifecycle) = lifecycle { - let _ = lifecycle.recover_open_tokens(); + if let Some(lifecycle) = lifecycle + && let Err(error) = lifecycle.recover_open_tokens() + { + tracing::error!( + error = %error.message(), + "capability token recovery failed while stopping the run" + ); + *self + .capability_stop_error + .lock() + .expect("capability stop error lock") = Some(error.message()); } } + /// First capability-recovery failure observed by a stop/halt path. + pub fn capability_stop_error(&self) -> Option { + self.capability_stop_error + .lock() + .expect("capability stop error lock") + .clone() + } + fn capability_host_closed(&self) -> bool { matches!( *self.capability_host.lock().expect("capability host lock"), @@ -552,36 +805,128 @@ impl RunHandle { if let Some(authority) = &self.workspace_authority { authority.release(); } + let mut retained_closed: Option = None; + let mut concurrent_close = false; let state = { let mut phase = self.capability_host.lock().expect("capability host lock"); - match std::mem::replace(&mut *phase, CapabilityHostPhase::Closed(None)) { + match std::mem::replace(&mut *phase, CapabilityHostPhase::Closing) { CapabilityHostPhase::Ready(state) => { - *phase = CapabilityHostPhase::Closed(Some(ClosedCapabilityHost { - processes: state.processes.clone(), - })); self.capability_host_cv.notify_all(); Some(state) } CapabilityHostPhase::Closed(existing) => { - *phase = CapabilityHostPhase::Closed(existing); + // A snapshot without a host must still carry its Clean + // outcome; never republish `Closed(None)`. + retained_closed = + Some(existing.unwrap_or_else(ClosedCapabilityHost::without_host)); + *phase = CapabilityHostPhase::Closed(retained_closed.clone()); + self.capability_host_cv.notify_all(); + None + } + CapabilityHostPhase::Closing => { + concurrent_close = true; + *phase = CapabilityHostPhase::Closing; self.capability_host_cv.notify_all(); None } CapabilityHostPhase::Empty | CapabilityHostPhase::Initializing => { + // There is no host to tear down, but the close is still a + // terminal Clean observation. Publishing the snapshot is + // what makes `cleanup_outcome()` agree with the returned + // outcome and lets managed restore accept the run. + retained_closed = Some(ClosedCapabilityHost::without_host()); + *phase = CapabilityHostPhase::Closed(retained_closed.clone()); self.capability_host_cv.notify_all(); None } } }; - let outcome = match state { - Some(state) => state.shutdown(), - None => CleanupOutcome::Clean, + if concurrent_close { + return CleanupOutcome::Timeout; + } + match state { + Some(state) => { + let outcome = state.shutdown(); + let closed = state.close_snapshot(outcome); + // One gate publishes the refreshed snapshot together with the + // caller-visible outcome. A concurrent observer can no longer + // see a settled snapshot next to an older Timeout cache. + self.publish_close_snapshot(closed); + outcome + } + None => match retained_closed { + Some(closed) => { + // The host is closed, but a token a partial recovery left + // owned may have become settleable since. Retrying here is + // what turns a repeated Timeout into eventual recovery. + self.retry_closed_capability_host(closed) + } + None => CleanupOutcome::Clean, + }, + } + } + + /// Retries the settlement of a closed host under its exclusive retry gate + /// and publishes the refreshed snapshot together with its outcome. The + /// phase is re-read after the gate is acquired, so a concurrent release + /// that already replaced the snapshot cannot be overwritten by an older + /// clone. The merge never downgrades a proven `Clean` or a retained + /// `Failed`; only new evidence can upgrade `Timeout`. + fn retry_closed_capability_host(&self, closed: ClosedCapabilityHost) -> CleanupOutcome { + let gate = Arc::clone(&closed.retry); + let _retry = gate.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let mut closed = { + let phase = self.capability_host.lock().expect("capability host lock"); + match &*phase { + CapabilityHostPhase::Closed(Some(current)) + if Arc::ptr_eq(¤t.retry, &gate) => + { + current.clone() + } + _ => closed, + } }; - let mut retained = self.cleanup_outcome.lock().expect("cleanup outcome lock"); - if retained.is_none() || outcome != CleanupOutcome::Clean { - *retained = Some(outcome); + let fresh = closed.outcome(); + let merged = merge_cleanup_outcomes(Some(closed.outcome), fresh); + closed.outcome = merged; + self.publish_close_snapshot(closed); + merged + } + + /// Publishes one closed snapshot and the outcome stored with it under the + /// same phase gate. + fn publish_close_snapshot(&self, closed: ClosedCapabilityHost) { + *self.capability_host.lock().expect("capability host lock") = + CapabilityHostPhase::Closed(Some(closed)); + self.capability_host_cv.notify_all(); + #[cfg(test)] + if let Some(observer) = self + .close_publish_observer + .lock() + .expect("close publication observer lock") + .clone() + { + observer(); + } + } + + /// Last caller-visible cleanup outcome, stored with the closed snapshot it + /// describes. `None` means no close has published a result yet. + fn cleanup_outcome(&self) -> Option { + match &*self.capability_host.lock().expect("capability host lock") { + CapabilityHostPhase::Closed(Some(closed)) => Some(closed.outcome), + _ => None, } - retained.unwrap_or(CleanupOutcome::Failed) + } + + /// Test-only: observe the exact publication of a closed snapshot and its + /// outcome. + #[cfg(test)] + fn set_close_publish_observer_for_test(&self, observer: Arc) { + *self + .close_publish_observer + .lock() + .expect("close publication observer lock") = Some(observer); } fn capability_host_retained(&self) -> bool { @@ -4323,7 +4668,10 @@ impl AgentService { ) -> Result>, RunContextError> { loop { let mut phase = handle.capability_host.lock().expect("capability host lock"); - if matches!(*phase, CapabilityHostPhase::Closed(_)) { + if matches!( + *phase, + CapabilityHostPhase::Closed(_) | CapabilityHostPhase::Closing + ) { return Ok(None); } if let CapabilityHostPhase::Ready(state) = &*phase { @@ -4629,6 +4977,9 @@ impl AgentService { filesystem, processes, artifacts, + cleanup_proof: Mutex::new(None), + recovery_error: Mutex::new(None), + open_tokens: Mutex::new(0), }) } @@ -4663,6 +5014,7 @@ impl AgentService { .map_or(0, |processes| processes.table_len()), CapabilityHostPhase::Empty | CapabilityHostPhase::Initializing + | CapabilityHostPhase::Closing | CapabilityHostPhase::Closed(None) => 0, } } @@ -4686,6 +5038,7 @@ impl AgentService { .map_or_else(Vec::new, |processes| processes.live_pids()), CapabilityHostPhase::Empty | CapabilityHostPhase::Initializing + | CapabilityHostPhase::Closing | CapabilityHostPhase::Closed(None) => Vec::new(), } } @@ -5190,7 +5543,9 @@ impl AgentService { coding_system_prompt: Arc::from(prompt), occupancy: AtomicBool::new(false), restore_worker_started: None, - cleanup_outcome: Mutex::new(None), + #[cfg(test)] + close_publish_observer: Mutex::new(None), + capability_stop_error: Mutex::new(None), pinned_tool, native_disposition, }); @@ -5240,6 +5595,7 @@ impl AgentService { CapabilityHostPhase::Ready(state) => Some(state.artifacts.stored_ids()), CapabilityHostPhase::Empty | CapabilityHostPhase::Initializing + | CapabilityHostPhase::Closing | CapabilityHostPhase::Closed(_) => None, } } @@ -7950,7 +8306,9 @@ impl AgentService { coding_system_prompt: Arc::from(coding_system_prompt), occupancy: AtomicBool::new(false), restore_worker_started: is_restore.then(|| AtomicBool::new(false)), - cleanup_outcome: Mutex::new(None), + #[cfg(test)] + close_publish_observer: Mutex::new(None), + capability_stop_error: Mutex::new(None), pinned_tool: Some(admitted_pin), native_disposition: Some(native_disposition), }); @@ -9245,6 +9603,7 @@ impl AgentService { processes, artifacts, control_hook: None, + commit_observer: None, pinned_tool: handle.pinned_tool.clone(), allow_stateless_pin: matches!( handle.native_disposition, @@ -11206,7 +11565,7 @@ pub(crate) fn canonical_tool_result(result: &JsonValue) -> Result Result<(), LifecycleError> { + Ok(()) + } + + fn prepare_parent( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result<(), LifecycleError> { + Ok(()) + } + + fn replay_result( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result, LifecycleError> { + Ok(None) + } + + fn commit_started(&self, _record: &DurableStarted) -> Result<(), LifecycleError> { + Ok(()) + } + + fn commit_result(&self, _call_id: &str, result: &Value) -> Result { + Ok(result.clone()) + } + + fn interrupt(&self, _call_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } + } + + fn state( + root: &std::path::Path, + processes: Arc, + lifecycle: Arc, + owner: CapabilityOwner, + grace: Duration, + ) -> CapabilityHostState { + CapabilityHostState { + cleaned: AtomicBool::new(false), + shutdown_entered: None, + cleanup_grace: grace, + uncooperative: None, + lifecycle, + capability_owner: owner, + filesystem: None, + processes: Some(processes), + artifacts: Arc::new( + ArtifactCapability::new( + CapabilityLifecycle::builder() + .owner(CapabilityOwner::new("service", "session", "run").expect("owner")) + .registry_identity("registry") + .workspace(root) + .limits(LifecycleLimits { + max_tool_calls: 1, + max_output_bytes: 4096, + max_summary_bytes: 128, + }) + .deadline_ms(SystemClock.now_ms().saturating_add(60_000)) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(Arc::new(NoopDurable) as Arc) + .approval(Arc::new(AllowAllApproval) + as Arc) + .cancellation(Arc::new(NeverCancelled) as Arc) + .build() + .expect("artifact lifecycle"), + CapabilityOwner::new("service", "session", "run").expect("owner"), + ArtifactLimits::default(), + ) + .expect("artifacts"), + ), + cleanup_proof: Mutex::new(None), + recovery_error: Mutex::new(None), + open_tokens: Mutex::new(0), + } + } + + fn retained_handle(state: CapabilityHostState) -> Arc { + Arc::new(RunHandle { + cancel: crate::RunCancellation::with_timeout(Duration::from_secs(5)), + terminal_at: Mutex::new(None), + permit: Mutex::new(None), + started_at: Instant::now(), + terminal: AtomicBool::new(false), + cancel_reason: Mutex::new(None), + subscribers: Mutex::new(SubscriberState { + count: 0, + notified: false, + }), + disconnect_policy: crate::config::ClientDisconnectPolicy::KeepRunning, + tool_cancel: crate::runtime::cancellation::CancellationToken::new(), + capability_host: Mutex::new(CapabilityHostPhase::Ready(Arc::new(state))), + capability_host_cv: Condvar::new(), + workspace_authority: None, + legacy_workspace_root: None, + coding_system_prompt: Arc::from(""), + occupancy: AtomicBool::new(false), + restore_worker_started: None, + #[cfg(test)] + close_publish_observer: Mutex::new(None), + capability_stop_error: Mutex::new(None), + pinned_tool: None, + native_disposition: None, + }) + } + + fn empty_handle() -> Arc { + Arc::new(RunHandle { + cancel: crate::RunCancellation::with_timeout(Duration::from_secs(5)), + terminal_at: Mutex::new(None), + permit: Mutex::new(None), + started_at: Instant::now(), + terminal: AtomicBool::new(false), + cancel_reason: Mutex::new(None), + subscribers: Mutex::new(SubscriberState { + count: 0, + notified: false, + }), + disconnect_policy: crate::config::ClientDisconnectPolicy::KeepRunning, + tool_cancel: crate::runtime::cancellation::CancellationToken::new(), + capability_host: Mutex::new(CapabilityHostPhase::Empty), + capability_host_cv: Condvar::new(), + workspace_authority: None, + legacy_workspace_root: None, + coding_system_prompt: Arc::from(""), + occupancy: AtomicBool::new(false), + restore_worker_started: None, + #[cfg(test)] + close_publish_observer: Mutex::new(None), + capability_stop_error: Mutex::new(None), + pinned_tool: None, + native_disposition: None, + }) + } + + #[test] + fn close_without_a_capability_host_publishes_and_reports_clean() { + let handle = empty_handle(); + let outcome = handle.release_capability_host(); + assert_eq!( + outcome, + CleanupOutcome::Clean, + "a close that owned no host is a proven clean teardown" + ); + assert_eq!( + handle.cleanup_outcome(), + Some(CleanupOutcome::Clean), + "the accessor must agree with the returned outcome; a managed restore reads it" + ); + assert_eq!( + closed_snapshot(&handle).outcome, + CleanupOutcome::Clean, + "the published snapshot carries the same outcome" + ); + } + + #[test] + fn canonical_result_does_not_reintroduce_a_default_failure_message() { + let result = canonical_tool_result(&json!({ + "ok": false, + "content": "", + "data": {"status": "signaled", "signal": 9}, + "error": {"code": "deadline_elapsed"}, + "truncated": true, + "artifacts": [] + })) + .expect("canonical compact result"); + assert!( + result + .error + .as_ref() + .is_some_and(|error| error.message.is_empty()), + "an omitted message must stay omitted: {result:?}" + ); + assert_eq!( + result.error.as_ref().map(|error| error.code.as_str()), + Some("deadline_elapsed") + ); + let encoded = serde_json::to_value(&result).expect("serialize typed result"); + assert_eq!(encoded["error"], json!({"code": "deadline_elapsed"})); + } + + #[test] + fn recovery_failure_downgrades_the_close_and_is_retained() { + struct FailingCommitDurable; + + impl DurableToolLifecycle for FailingCommitDurable { + fn assert_active_run(&self, _run_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } + + fn prepare_parent( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result<(), LifecycleError> { + Ok(()) + } + + fn replay_result( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result, LifecycleError> { + Ok(None) + } + + fn commit_started(&self, _record: &DurableStarted) -> Result<(), LifecycleError> { + Ok(()) + } + + fn commit_result( + &self, + _call_id: &str, + _result: &Value, + ) -> Result { + Err(LifecycleError::ResultCommitFailed( + "forced recovery failure".to_string(), + )) + } + + fn interrupt(&self, _call_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } + } + + let root = std::env::temp_dir().join(format!( + "service-recovery-error-{}-{}", + std::process::id(), + uuid::Uuid::new_v4() + )); + std::fs::create_dir_all(&root).expect("fixture root"); + let owner = CapabilityOwner::new("service", "session", "recovery").expect("owner"); + let lifecycle = Arc::new( + CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry") + .workspace(&root) + .limits(LifecycleLimits { + max_tool_calls: 8, + max_output_bytes: 4096, + max_summary_bytes: 128, + }) + .deadline_ms(SystemClock.now_ms().saturating_add(60_000)) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(Arc::new(FailingCommitDurable) as Arc) + .approval(Arc::new(AllowAllApproval) as Arc) + .cancellation(Arc::new(NeverCancelled) as Arc) + // Recovery only writes a receipt (and can observe the forced + // commit failure) in the settlement mode. The default managed + // policy interrupts a published token instead, as + // `e9da5dc` did and `0c6c8f2` restored. + .published_token_policy( + crate::capabilities::PublishedTokenPolicy::RetainForSettlement, + ) + .build() + .expect("lifecycle"), + ); + let token = match lifecycle + .prepare( + &owner, + PrepareMetadata { + run_id: owner.run().to_string(), + call_id: "recovery-error".to_string(), + tool_name: "fixture_tool".to_string(), + argument_digest: "digest".to_string(), + registry_identity: "registry".to_string(), + risk_class: CapabilityRisk::Read, + summary: "fixture".to_string(), + }, + ) + .expect("prepare") + { + PrepareOutcome::Execute { + execution_token, .. + } => execution_token, + other => panic!("expected execute, got {other:?}"), + }; + let permit = lifecycle.enter_publication(&token).expect("publication"); + permit.published_effect(crate::capabilities::NativeEffectRecord::artifact_store( + crate::capabilities::NativeArtifactIdentity { + id: "recovered-artifact".to_string(), + len: 3, + hash: "hash".to_string(), + }, + )); + let artifacts = Arc::new( + ArtifactCapability::new( + lifecycle.as_ref().clone(), + owner.clone(), + ArtifactLimits::default(), + ) + .expect("artifacts"), + ); + let state = CapabilityHostState { + cleaned: AtomicBool::new(false), + shutdown_entered: None, + cleanup_grace: Duration::from_millis(100), + uncooperative: None, + lifecycle: Arc::clone(&lifecycle), + capability_owner: owner, + filesystem: None, + processes: None, + artifacts, + cleanup_proof: Mutex::new(None), + recovery_error: Mutex::new(None), + open_tokens: Mutex::new(0), + }; + assert_eq!( + state.shutdown_with_grace(Duration::from_millis(100)), + CleanupOutcome::Failed, + "a failed recovery must never be reported as a silent clean close" + ); + assert_eq!( + state.recovery_error().as_deref(), + Some("forced recovery failure"), + "the stop error must be retained instead of discarded" + ); + assert_eq!( + lifecycle.open_token_count(), + 1, + "the failed settlement must leave the token owned for a later retry" + ); + // A repeated close observes the same retained teardown result. It must + // never upgrade a failed recovery to Clean. + assert_eq!( + state.shutdown_with_grace(Duration::from_millis(100)), + CleanupOutcome::Failed, + "a repeated close must keep the failed recovery outcome" + ); + // The closed snapshot the service retains is the path a later release + // observes, so it must carry the same failure. + let mut closed = state.close_snapshot(state.retained_cleanup_outcome()); + assert_eq!( + closed.outcome(), + CleanupOutcome::Failed, + "the retained closed snapshot must keep the failed recovery outcome" + ); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn a_partial_recovery_with_an_open_token_is_never_reported_clean() { + let root = std::env::temp_dir().join(format!( + "service-open-token-{}-{}", + std::process::id(), + uuid::Uuid::new_v4() + )); + std::fs::create_dir_all(&root).expect("fixture root"); + let owner = CapabilityOwner::new("service", "session", "open-token").expect("owner"); + let lifecycle = Arc::new( + CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry") + .workspace(&root) + .limits(LifecycleLimits { + max_tool_calls: 8, + max_output_bytes: 4096, + max_summary_bytes: 128, + }) + .deadline_ms(SystemClock.now_ms().saturating_add(60_000)) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(Arc::new(NoopDurable) as Arc) + .approval(Arc::new(AllowAllApproval) as Arc) + .cancellation(Arc::new(NeverCancelled) as Arc) + .published_token_policy( + crate::capabilities::PublishedTokenPolicy::RetainForSettlement, + ) + .build() + .expect("lifecycle"), + ); + let token = match lifecycle + .prepare( + &owner, + PrepareMetadata { + run_id: owner.run().to_string(), + call_id: "open-token".to_string(), + tool_name: "fixture_tool".to_string(), + argument_digest: "digest".to_string(), + registry_identity: "registry".to_string(), + risk_class: CapabilityRisk::Read, + summary: "fixture".to_string(), + }, + ) + .expect("prepare") + { + PrepareOutcome::Execute { + execution_token, .. + } => execution_token, + other => panic!("expected execute, got {other:?}"), + }; + // The retention mode leaves this live publisher for its own worker, so + // recovery returns success while the token stays open. + let permit = lifecycle.enter_publication(&token).expect("publication"); + let state = CapabilityHostState { + cleaned: AtomicBool::new(false), + shutdown_entered: None, + cleanup_grace: Duration::from_millis(100), + uncooperative: None, + lifecycle: Arc::clone(&lifecycle), + capability_owner: owner.clone(), + filesystem: None, + processes: None, + artifacts: Arc::new( + ArtifactCapability::new( + CapabilityLifecycle::builder() + .owner(CapabilityOwner::new("service", "session", "run").expect("owner")) + .registry_identity("registry") + .workspace(&root) + .limits(LifecycleLimits { + max_tool_calls: 1, + max_output_bytes: 4096, + max_summary_bytes: 128, + }) + .deadline_ms(SystemClock.now_ms().saturating_add(60_000)) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(Arc::new(NoopDurable) as Arc) + .approval(Arc::new(AllowAllApproval) + as Arc) + .cancellation(Arc::new(NeverCancelled) as Arc) + .build() + .expect("artifact lifecycle"), + CapabilityOwner::new("service", "session", "run").expect("owner"), + ArtifactLimits::default(), + ) + .expect("artifacts"), + ), + cleanup_proof: Mutex::new(None), + recovery_error: Mutex::new(None), + open_tokens: Mutex::new(0), + }; + assert_eq!( + state.shutdown_with_grace(Duration::from_millis(100)), + CleanupOutcome::Timeout, + "a successful-but-partial recovery must never close as clean" + ); + assert_eq!( + lifecycle.open_token_count(), + 1, + "the unclaimed token must stay owned for the owner's retry" + ); + assert_eq!( + state.shutdown_with_grace(Duration::from_millis(100)), + CleanupOutcome::Timeout, + "a repeated close must keep the retained-token outcome" + ); + drop(permit); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn a_retained_token_settles_on_a_later_close_retry() { + let root = std::env::temp_dir().join(format!( + "service-retained-retry-{}-{}", + std::process::id(), + uuid::Uuid::new_v4() + )); + std::fs::create_dir_all(&root).expect("fixture root"); + let owner = CapabilityOwner::new("service", "session", "retry").expect("owner"); + let lifecycle = Arc::new( + CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry") + .workspace(&root) + .limits(LifecycleLimits { + max_tool_calls: 8, + max_output_bytes: 4096, + max_summary_bytes: 128, + }) + .deadline_ms(SystemClock.now_ms().saturating_add(60_000)) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(Arc::new(NoopDurable) as Arc) + .approval(Arc::new(AllowAllApproval) as Arc) + .cancellation(Arc::new(NeverCancelled) as Arc) + .published_token_policy( + crate::capabilities::PublishedTokenPolicy::RetainForSettlement, + ) + .build() + .expect("lifecycle"), + ); + let token = match lifecycle + .prepare( + &owner, + PrepareMetadata { + run_id: owner.run().to_string(), + call_id: "retained-retry".to_string(), + tool_name: "fixture_tool".to_string(), + argument_digest: "digest".to_string(), + registry_identity: "registry".to_string(), + risk_class: CapabilityRisk::Read, + summary: "fixture".to_string(), + }, + ) + .expect("prepare") + { + PrepareOutcome::Execute { + execution_token, .. + } => execution_token, + other => panic!("expected execute, got {other:?}"), + }; + // The retention mode leaves this live publisher for its own worker, so + // the first close reports a partial recovery. + let permit = lifecycle.enter_publication(&token).expect("publication"); + let state = CapabilityHostState { + cleaned: AtomicBool::new(false), + shutdown_entered: None, + cleanup_grace: Duration::from_millis(100), + uncooperative: None, + lifecycle: Arc::clone(&lifecycle), + capability_owner: owner.clone(), + filesystem: None, + processes: None, + artifacts: Arc::new( + ArtifactCapability::new( + lifecycle.as_ref().clone(), + owner, + ArtifactLimits::default(), + ) + .expect("artifacts"), + ), + cleanup_proof: Mutex::new(None), + recovery_error: Mutex::new(None), + open_tokens: Mutex::new(0), + }; + let handle = retained_handle(state); + assert_eq!( + handle.release_capability_host(), + CleanupOutcome::Timeout, + "a live publisher must not be claimed by the first close" + ); + let closed = closed_snapshot(&handle); + assert_eq!(closed.open_tokens, 1); + assert_eq!( + handle.release_capability_host(), + CleanupOutcome::Timeout, + "a repeated close must not invent a clean result while the publisher is live" + ); + // The publisher retires without a receipt. The closed host still owns + // the lifecycle, so the next close retry settles the retained token + // instead of reporting the same timeout forever. + drop(permit); + assert_eq!( + handle.release_capability_host(), + CleanupOutcome::Clean, + "a closed host must retry settlement of a token retained by its first close" + ); + assert_eq!( + handle.cleanup_outcome(), + Some(CleanupOutcome::Clean), + "a proven clean retry must replace the cached Timeout" + ); + let closed = closed_snapshot(&handle); + assert_eq!(closed.open_tokens, 0); + assert_eq!(lifecycle.open_token_count(), 0); + assert_eq!(lifecycle.interrupted_token_count(), 1); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn timeout_to_failed_is_published_with_the_closed_snapshot() { + struct FailingCommitDurable; + + impl DurableToolLifecycle for FailingCommitDurable { + fn assert_active_run(&self, _run_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } + + fn prepare_parent( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result<(), LifecycleError> { + Ok(()) + } + + fn replay_result( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result, LifecycleError> { + Ok(None) + } + + fn commit_started(&self, _record: &DurableStarted) -> Result<(), LifecycleError> { + Ok(()) + } + + fn commit_result( + &self, + _call_id: &str, + _result: &Value, + ) -> Result { + Err(LifecycleError::ResultCommitFailed( + "forced recovery failure".to_string(), + )) + } + + fn interrupt(&self, _call_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } + } + + let root = std::env::temp_dir().join(format!( + "service-timeout-failed-{}-{}", + std::process::id(), + uuid::Uuid::new_v4() + )); + std::fs::create_dir_all(&root).expect("fixture root"); + let owner = CapabilityOwner::new("service", "session", "timeout-failed").expect("owner"); + let lifecycle = Arc::new( + CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry") + .workspace(&root) + .limits(LifecycleLimits { + max_tool_calls: 8, + max_output_bytes: 4096, + max_summary_bytes: 128, + }) + .deadline_ms(SystemClock.now_ms().saturating_add(60_000)) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(Arc::new(FailingCommitDurable) as Arc) + .approval(Arc::new(AllowAllApproval) as Arc) + .cancellation(Arc::new(NeverCancelled) as Arc) + .published_token_policy( + crate::capabilities::PublishedTokenPolicy::RetainForSettlement, + ) + .build() + .expect("lifecycle"), + ); + let token = match lifecycle + .prepare( + &owner, + PrepareMetadata { + run_id: owner.run().to_string(), + call_id: "timeout-failed".to_string(), + tool_name: "fixture_tool".to_string(), + argument_digest: "digest".to_string(), + registry_identity: "registry".to_string(), + risk_class: CapabilityRisk::Read, + summary: "fixture".to_string(), + }, + ) + .expect("prepare") + { + PrepareOutcome::Execute { + execution_token, .. + } => execution_token, + other => panic!("expected execute, got {other:?}"), + }; + // The first close cannot claim a live publisher and reports Timeout. + let permit = lifecycle.enter_publication(&token).expect("publication"); + let state = CapabilityHostState { + cleaned: AtomicBool::new(false), + shutdown_entered: None, + cleanup_grace: Duration::from_millis(100), + uncooperative: None, + lifecycle: Arc::clone(&lifecycle), + capability_owner: owner.clone(), + filesystem: None, + processes: None, + artifacts: Arc::new( + ArtifactCapability::new( + lifecycle.as_ref().clone(), + owner.clone(), + ArtifactLimits::default(), + ) + .expect("artifacts"), + ), + cleanup_proof: Mutex::new(None), + recovery_error: Mutex::new(None), + open_tokens: Mutex::new(0), + }; + let handle = retained_handle(state); + assert_eq!( + handle.release_capability_host(), + CleanupOutcome::Timeout, + "a live publisher must leave a retained token" + ); + assert_eq!(closed_snapshot(&handle).open_tokens, 1); + // The publisher publishes, then the next close retries settlement and + // hits a durable recovery error. Failed must replace the cached + // Timeout instead of hiding behind it. + permit.published_effect(crate::capabilities::NativeEffectRecord::artifact_store( + crate::capabilities::NativeArtifactIdentity { + id: "timeout-failed-artifact".to_string(), + len: 3, + hash: "hash".to_string(), + }, + )); + assert_eq!( + handle.release_capability_host(), + CleanupOutcome::Failed, + "Timeout must not mask the stronger Failed outcome" + ); + assert_eq!( + handle.cleanup_outcome(), + Some(CleanupOutcome::Failed), + "the closed snapshot and the caller-visible outcome must agree" + ); + let closed = closed_snapshot(&handle); + assert_eq!(closed.open_tokens, 1); + assert_eq!( + closed.recovery_error.as_deref(), + Some("forced recovery failure") + ); + assert_eq!( + handle.release_capability_host(), + CleanupOutcome::Failed, + "a retained recovery failure stays failed for later observers" + ); + let _ = std::fs::remove_dir_all(&root); + } + + fn closed_snapshot(handle: &RunHandle) -> ClosedCapabilityHost { + match &*handle.capability_host.lock().expect("capability host lock") { + CapabilityHostPhase::Closed(Some(closed)) => closed.clone(), + _ => panic!("expected a closed capability host"), + } + } + + #[test] + fn concurrent_closed_host_retries_are_serialized_and_keep_the_clean_snapshot() { + let root = std::env::temp_dir().join(format!( + "service-retained-concurrent-{}-{}", + std::process::id(), + uuid::Uuid::new_v4() + )); + std::fs::create_dir_all(&root).expect("fixture root"); + let owner = CapabilityOwner::new("service", "session", "concurrent").expect("owner"); + let lifecycle = Arc::new( + CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry") + .workspace(&root) + .limits(LifecycleLimits { + max_tool_calls: 8, + max_output_bytes: 4096, + max_summary_bytes: 128, + }) + .deadline_ms(SystemClock.now_ms().saturating_add(60_000)) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(Arc::new(NoopDurable) as Arc) + .approval(Arc::new(AllowAllApproval) as Arc) + .cancellation(Arc::new(NeverCancelled) as Arc) + .published_token_policy( + crate::capabilities::PublishedTokenPolicy::RetainForSettlement, + ) + .build() + .expect("lifecycle"), + ); + let token = match lifecycle + .prepare( + &owner, + PrepareMetadata { + run_id: owner.run().to_string(), + call_id: "retained-concurrent".to_string(), + tool_name: "fixture_tool".to_string(), + argument_digest: "digest".to_string(), + registry_identity: "registry".to_string(), + risk_class: CapabilityRisk::Read, + summary: "fixture".to_string(), + }, + ) + .expect("prepare") + { + PrepareOutcome::Execute { + execution_token, .. + } => execution_token, + other => panic!("expected execute, got {other:?}"), + }; + let permit = lifecycle.enter_publication(&token).expect("publication"); + let state = CapabilityHostState { + cleaned: AtomicBool::new(false), + shutdown_entered: None, + cleanup_grace: Duration::from_millis(100), + uncooperative: None, + lifecycle: Arc::clone(&lifecycle), + capability_owner: owner.clone(), + filesystem: None, + processes: None, + artifacts: Arc::new( + ArtifactCapability::new( + lifecycle.as_ref().clone(), + owner, + ArtifactLimits::default(), + ) + .expect("artifacts"), + ), + cleanup_proof: Mutex::new(None), + recovery_error: Mutex::new(None), + open_tokens: Mutex::new(0), + }; + let handle = retained_handle(state); + assert_eq!( + handle.release_capability_host(), + CleanupOutcome::Timeout, + "the live publisher must leave a retained token" + ); + // Count how many recovery attempts are inside `recover_open_tokens` at + // once. A serialized retry never overlaps another; an unserialized one + // lets both clones retry and overwrite each other's snapshot. + let active = Arc::new(AtomicUsize::new(0)); + let maximum = Arc::new(AtomicUsize::new(0)); + lifecycle.inject_recovery_entry_observer_for_test({ + let active = Arc::clone(&active); + let maximum = Arc::clone(&maximum); + Arc::new(move || { + let entered = active.fetch_add(1, Ordering::SeqCst) + 1; + maximum.fetch_max(entered, Ordering::SeqCst); + thread::sleep(Duration::from_millis(150)); + active.fetch_sub(1, Ordering::SeqCst); + }) + }); + drop(permit); + let barrier = Arc::new(std::sync::Barrier::new(3)); + let first = { + let handle = Arc::clone(&handle); + let barrier = Arc::clone(&barrier); + thread::spawn(move || { + barrier.wait(); + handle.release_capability_host() + }) + }; + let second = { + let handle = Arc::clone(&handle); + let barrier = Arc::clone(&barrier); + thread::spawn(move || { + barrier.wait(); + handle.release_capability_host() + }) + }; + barrier.wait(); + let first = first.join().expect("first retry"); + let second = second.join().expect("second retry"); + assert_eq!( + maximum.load(Ordering::SeqCst), + 1, + "two retained retries must not interleave into a lost snapshot update" + ); + assert_eq!(first, CleanupOutcome::Clean); + assert_eq!(second, CleanupOutcome::Clean); + assert_eq!( + handle.cleanup_outcome(), + Some(CleanupOutcome::Clean), + "the settled clean outcome must survive both releases" + ); + assert_eq!(closed_snapshot(&handle).open_tokens, 0); + assert_eq!(lifecycle.open_token_count(), 0); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn concurrent_observer_reads_the_outcome_with_the_published_snapshot() { + let root = std::env::temp_dir().join(format!( + "service-close-observer-{}-{}", + std::process::id(), + uuid::Uuid::new_v4() + )); + std::fs::create_dir_all(&root).expect("fixture root"); + let owner = CapabilityOwner::new("service", "session", "close-observer").expect("owner"); + let lifecycle = Arc::new( + CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry") + .workspace(&root) + .limits(LifecycleLimits { + max_tool_calls: 8, + max_output_bytes: 4096, + max_summary_bytes: 128, + }) + .deadline_ms(SystemClock.now_ms().saturating_add(60_000)) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(Arc::new(NoopDurable) as Arc) + .approval(Arc::new(AllowAllApproval) as Arc) + .cancellation(Arc::new(NeverCancelled) as Arc) + .published_token_policy( + crate::capabilities::PublishedTokenPolicy::RetainForSettlement, + ) + .build() + .expect("lifecycle"), + ); + let token = match lifecycle + .prepare( + &owner, + PrepareMetadata { + run_id: owner.run().to_string(), + call_id: "close-observer".to_string(), + tool_name: "fixture_tool".to_string(), + argument_digest: "digest".to_string(), + registry_identity: "registry".to_string(), + risk_class: CapabilityRisk::Read, + summary: "fixture".to_string(), + }, + ) + .expect("prepare") + { + PrepareOutcome::Execute { + execution_token, .. + } => execution_token, + other => panic!("expected execute, got {other:?}"), + }; + let permit = lifecycle.enter_publication(&token).expect("publication"); + let state = CapabilityHostState { + cleaned: AtomicBool::new(false), + shutdown_entered: None, + cleanup_grace: Duration::from_millis(100), + uncooperative: None, + lifecycle: Arc::clone(&lifecycle), + capability_owner: owner.clone(), + filesystem: None, + processes: None, + artifacts: Arc::new( + ArtifactCapability::new( + lifecycle.as_ref().clone(), + owner, + ArtifactLimits::default(), + ) + .expect("artifacts"), + ), + cleanup_proof: Mutex::new(None), + recovery_error: Mutex::new(None), + open_tokens: Mutex::new(0), + }; + let handle = retained_handle(state); + assert_eq!( + handle.release_capability_host(), + CleanupOutcome::Timeout, + "the live publisher must leave a retained token" + ); + + // Park the retrying release at the exact snapshot publication seam. + // A concurrent observer then reads the pair while the release is still + // inside the publication, not after it returned. + let entered = Arc::new((Mutex::new(false), Condvar::new())); + let released = Arc::new((Mutex::new(false), Condvar::new())); + handle.set_close_publish_observer_for_test({ + let entered = Arc::clone(&entered); + let released = Arc::clone(&released); + Arc::new(move || { + *entered + .0 + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = true; + entered.1.notify_all(); + let mut released_flag = released + .0 + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + while !*released_flag { + released_flag = released + .1 + .wait(released_flag) + .unwrap_or_else(|poisoned| poisoned.into_inner()); + } + }) + }); + // The publisher retires without an effect, so the next release retries + // settlement and proves the token settled. + drop(permit); + let retrying = { + let handle = Arc::clone(&handle); + thread::spawn(move || handle.release_capability_host()) + }; + let (entered_lock, entered_cv) = &*entered; + let mut entered_flag = entered_lock + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let deadline = Instant::now() + Duration::from_secs(5); + while !*entered_flag { + let remaining = deadline.saturating_duration_since(Instant::now()); + assert!( + !remaining.is_zero(), + "close publication observer was never entered" + ); + entered_flag = entered_cv + .wait_timeout(entered_flag, remaining) + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .0; + } + drop(entered_flag); + let snapshot = closed_snapshot(&handle); + assert_eq!(snapshot.open_tokens, 0, "the refreshed snapshot is settled"); + assert_eq!( + handle.cleanup_outcome(), + Some(CleanupOutcome::Clean), + "the outcome must be stored with the published snapshot, not cached after it" + ); + *released + .0 + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = true; + released.1.notify_all(); + assert_eq!( + retrying.join().expect("retrying release"), + CleanupOutcome::Clean + ); + assert_eq!(handle.cleanup_outcome(), Some(CleanupOutcome::Clean)); + assert_eq!(closed_snapshot(&handle).open_tokens, 0); + assert_eq!(lifecycle.open_token_count(), 0); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn failed_recovery_records_retained_ownership_for_the_later_retry() { + struct FailOnceDurable { + attempts: AtomicUsize, + } + + impl DurableToolLifecycle for FailOnceDurable { + fn assert_active_run(&self, _run_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } + + fn prepare_parent( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result<(), LifecycleError> { + Ok(()) + } + + fn replay_result( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result, LifecycleError> { + Ok(None) + } + + fn commit_started(&self, _record: &DurableStarted) -> Result<(), LifecycleError> { + Ok(()) + } + + fn commit_result( + &self, + _call_id: &str, + result: &Value, + ) -> Result { + if self.attempts.fetch_add(1, Ordering::SeqCst) == 0 { + Err(LifecycleError::ResultCommitFailed( + "forced recovery failure".to_string(), + )) + } else { + Ok(result.clone()) + } + } + + fn interrupt(&self, _call_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } + } + + let root = std::env::temp_dir().join(format!( + "service-retained-failure-{}-{}", + std::process::id(), + uuid::Uuid::new_v4() + )); + std::fs::create_dir_all(&root).expect("fixture root"); + let owner = CapabilityOwner::new("service", "session", "retained-failure").expect("owner"); + let lifecycle = Arc::new( + CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry") + .workspace(&root) + .limits(LifecycleLimits { + max_tool_calls: 8, + max_output_bytes: 4096, + max_summary_bytes: 128, + }) + .deadline_ms(SystemClock.now_ms().saturating_add(60_000)) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(Arc::new(FailOnceDurable { + attempts: AtomicUsize::new(0), + }) as Arc) + .approval(Arc::new(AllowAllApproval) as Arc) + .cancellation(Arc::new(NeverCancelled) as Arc) + .published_token_policy( + crate::capabilities::PublishedTokenPolicy::RetainForSettlement, + ) + .build() + .expect("lifecycle"), + ); + let token = match lifecycle + .prepare( + &owner, + PrepareMetadata { + run_id: owner.run().to_string(), + call_id: "retained-failure".to_string(), + tool_name: "fixture_tool".to_string(), + argument_digest: "digest".to_string(), + registry_identity: "registry".to_string(), + risk_class: CapabilityRisk::Read, + summary: "fixture".to_string(), + }, + ) + .expect("prepare") + { + PrepareOutcome::Execute { + execution_token, .. + } => execution_token, + other => panic!("expected execute, got {other:?}"), + }; + lifecycle + .enter_publication(&token) + .expect("publication") + .published_effect(crate::capabilities::NativeEffectRecord::artifact_store( + crate::capabilities::NativeArtifactIdentity { + id: "retained-failure-artifact".to_string(), + len: 3, + hash: "hash".to_string(), + }, + )); + let state = CapabilityHostState { + cleaned: AtomicBool::new(false), + shutdown_entered: None, + cleanup_grace: Duration::from_millis(100), + uncooperative: None, + lifecycle: Arc::clone(&lifecycle), + capability_owner: owner.clone(), + filesystem: None, + processes: None, + artifacts: Arc::new( + ArtifactCapability::new( + lifecycle.as_ref().clone(), + owner, + ArtifactLimits::default(), + ) + .expect("artifacts"), + ), + cleanup_proof: Mutex::new(None), + recovery_error: Mutex::new(None), + open_tokens: Mutex::new(0), + }; + let handle = retained_handle(state); + assert_eq!( + handle.release_capability_host(), + CleanupOutcome::Failed, + "a failed recovery must never be reported as a silent clean close" + ); + let closed = closed_snapshot(&handle); + assert_eq!( + closed.open_tokens, 1, + "the failed recovery must record the token it retained" + ); + assert_eq!( + closed.recovery_error.as_deref(), + Some("forced recovery failure"), + "the stop error must be retained instead of discarded" + ); + assert_eq!(lifecycle.open_token_count(), 1); + // The later release retries the recorded ownership and settles it, but + // the close still reports the retained failure from 1618b58. + assert_eq!( + handle.release_capability_host(), + CleanupOutcome::Failed, + "a repeated close must keep the failed recovery outcome" + ); + assert_eq!( + lifecycle.open_token_count(), + 0, + "the retry must settle the ownership recorded by the failed close" + ); + let closed = closed_snapshot(&handle); + assert_eq!(closed.open_tokens, 0); + assert_eq!( + closed.recovery_error.as_deref(), + Some("forced recovery failure"), + "the retained error string must survive the successful retry" + ); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn withheld_process_reap_proof_is_never_reported_clean() { + let root = std::env::temp_dir().join(format!( + "service-cleanup-proof-{}-{}", + std::process::id(), + uuid::Uuid::new_v4() + )); + std::fs::create_dir_all(&root).expect("fixture root"); + let owner = CapabilityOwner::new("service", "session", "run").expect("owner"); + let lifecycle = Arc::new( + CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry") + .workspace(&root) + .limits(LifecycleLimits { + max_tool_calls: 8, + max_output_bytes: 4096, + max_summary_bytes: 128, + }) + .deadline_ms(SystemClock.now_ms().saturating_add(60_000)) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(Arc::new(NoopDurable) as Arc) + .approval(Arc::new(AllowAllApproval) as Arc) + .cancellation(Arc::new(NeverCancelled) as Arc) + .build() + .expect("lifecycle"), + ); + let processes = Arc::new( + ProcessCapability::new_with_table_limits( + lifecycle.as_ref().clone(), + owner.clone(), + ProcessLimits::default(), + ProcessTableLimits::new(2, 2, Duration::from_millis(150)).expect("table limits"), + ) + .expect("processes"), + ); + let token = match lifecycle + .prepare( + &owner, + PrepareMetadata { + run_id: owner.run().to_string(), + call_id: "service-cleanup".to_string(), + tool_name: "fixture_tool".to_string(), + argument_digest: "digest".to_string(), + registry_identity: "registry".to_string(), + risk_class: CapabilityRisk::Execute, + summary: "fixture".to_string(), + }, + ) + .expect("prepare") + { + PrepareOutcome::Execute { + execution_token, .. + } => execution_token, + other => panic!("expected execute, got {other:?}"), + }; + processes + .spawn( + &token, + &["/bin/sleep".to_string(), "30".to_string()], + "", + &[], + ProcessLimits { + timeout_ms: 10_000, + close_after_initial: false, + ..ProcessLimits::default() + }, + ) + .expect("spawn live child"); + processes.withhold_cleanup_proof_for_test(); + + let first_cleanup = state( + &root, + Arc::clone(&processes), + Arc::clone(&lifecycle), + owner.clone(), + Duration::from_millis(150), + ); + let started = Instant::now(); + assert_eq!( + first_cleanup.shutdown_with_grace(Duration::from_millis(150)), + CleanupOutcome::Timeout, + "an unproven reap must never be reported clean" + ); + let elapsed = started.elapsed(); + assert!( + elapsed < Duration::from_millis(1_200), + "legacy cleanup must stay tied to the configured cutoff: {elapsed:?}" + ); + assert_eq!( + processes.table_len(), + 1, + "a timed-out cleanup must retain process ownership" + ); + assert_eq!( + first_cleanup.shutdown_with_grace(Duration::from_millis(150)), + CleanupOutcome::Timeout, + "a repeated cleanup must keep the typed timeout" + ); + + processes.allow_cleanup_proof_for_test(); + let retry = state( + &root, + Arc::clone(&processes), + lifecycle, + owner, + Duration::from_secs(1), + ); + assert_eq!( + retry.shutdown_with_grace(Duration::from_secs(1)), + CleanupOutcome::Clean + ); + assert_eq!( + processes.table_len(), + 0, + "a proved reap may retire the table" + ); + drop(retry); + drop(first_cleanup); + let _ = std::fs::remove_dir_all(&root); + } +} diff --git a/src/service/managed_checkpoints.rs b/src/service/managed_checkpoints.rs index 718cd867..8466cbd5 100644 --- a/src/service/managed_checkpoints.rs +++ b/src/service/managed_checkpoints.rs @@ -648,8 +648,7 @@ impl AgentService { std::thread::sleep(Duration::from_millis(5)); } if !handle.terminal.load(Ordering::Acquire) - || *handle.cleanup_outcome.lock().expect("cleanup outcome lock") - != Some(CleanupOutcome::Clean) + || handle.cleanup_outcome() != Some(CleanupOutcome::Clean) { return Err(failure("managed_restore_busy")); } diff --git a/src/service/managed_effects_tests.rs b/src/service/managed_effects_tests.rs index 4221a9f3..55df7a20 100644 --- a/src/service/managed_effects_tests.rs +++ b/src/service/managed_effects_tests.rs @@ -2562,7 +2562,8 @@ async fn guard_contract_471_r467_1_stateless_absent_or_mismatched_proof_refuses_ coding_system_prompt: std::sync::Arc::from(""), occupancy: std::sync::atomic::AtomicBool::new(false), restore_worker_started: None, - cleanup_outcome: std::sync::Mutex::new(None), + close_publish_observer: std::sync::Mutex::new(None), + capability_stop_error: std::sync::Mutex::new(None), pinned_tool: pinned, native_disposition: disposition, } @@ -5082,7 +5083,7 @@ pub fn run(context: map) -> map { assert_eq!( service .handle(run_id) - .and_then(|handle| { *handle.cleanup_outcome.lock().unwrap() }), + .and_then(|handle| { handle.cleanup_outcome() }), Some(crate::CleanupOutcome::Clean), "run {run_id} must retain a Clean capability-host cleanup outcome" ); @@ -5374,7 +5375,7 @@ pub fn run(context: map) -> map { let cleanup_facts = failing_run_id.as_ref().map(|run_id| LeafCleanupFacts { cleanup_outcome: service .handle(run_id) - .and_then(|handle| *handle.cleanup_outcome.lock().unwrap()), + .and_then(|handle| handle.cleanup_outcome()), host_closed: service.capability_host_closed(run_id), host_retained: service.capability_host_retained(run_id), process_owners: service.process_owner_count(run_id), @@ -5894,7 +5895,7 @@ pub fn run(context: map) -> map { let cleanup_facts = ( service .handle(&run.run_id) - .and_then(|handle| *handle.cleanup_outcome.lock().unwrap()), + .and_then(|handle| handle.cleanup_outcome()), service.capability_host_closed(&run.run_id), service.capability_host_retained(&run.run_id), service.process_owner_count(&run.run_id), @@ -6684,7 +6685,8 @@ async fn guard_contract_519_mismatched_memory_proof_refuses_receipt() { coding_system_prompt: std::sync::Arc::from(""), occupancy: std::sync::atomic::AtomicBool::new(false), restore_worker_started: None, - cleanup_outcome: std::sync::Mutex::new(None), + close_publish_observer: std::sync::Mutex::new(None), + capability_stop_error: std::sync::Mutex::new(None), pinned_tool: Some(pin_zero), native_disposition: Some(proof_one), }; @@ -6832,7 +6834,8 @@ async fn guard_contract_521_seal_after_eviction_leaves_no_orphan_proof() { coding_system_prompt: std::sync::Arc::from(""), occupancy: std::sync::atomic::AtomicBool::new(false), restore_worker_started: None, - cleanup_outcome: std::sync::Mutex::new(None), + close_publish_observer: std::sync::Mutex::new(None), + capability_stop_error: std::sync::Mutex::new(None), pinned_tool: Some(real_pin.clone()), native_disposition: Some(real_disposition.clone()), }; @@ -6890,7 +6893,8 @@ async fn guard_contract_521_seal_after_eviction_leaves_no_orphan_proof() { coding_system_prompt: std::sync::Arc::from(""), occupancy: std::sync::atomic::AtomicBool::new(false), restore_worker_started: None, - cleanup_outcome: std::sync::Mutex::new(None), + close_publish_observer: std::sync::Mutex::new(None), + capability_stop_error: std::sync::Mutex::new(None), pinned_tool: Some(real_pin), native_disposition: Some(real_disposition), }; diff --git a/src/tool_result.rs b/src/tool_result.rs index fce517cb..9ed6318e 100644 --- a/src/tool_result.rs +++ b/src/tool_result.rs @@ -70,9 +70,38 @@ pub struct ToolResult { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct ToolError { pub code: String, + /// Presentation text. Compact receipts may omit it; the + /// canonical code remains authoritative. An omitted message stays omitted + /// when the typed result is serialized again, so a compact durable receipt + /// cannot grow past its configured byte bound on replay. + #[serde(default, skip_serializing_if = "String::is_empty")] pub message: String, } +/// JSON-encoded size of one string's contribution inside a JSON string, +/// including escaping and excluding the surrounding quotes. +fn json_string_contribution(text: &str) -> usize { + serde_json::to_vec(text) + .map(|encoded| encoded.len().saturating_sub(2)) + .unwrap_or(usize::MAX) +} + +/// Truncate `text` to at most `limit` JSON-encoded bytes, on a character +/// boundary. +fn truncate_json_bytes(text: &str, limit: usize) -> String { + let mut used = 0usize; + let mut end = 0usize; + for (index, character) in text.char_indices() { + let contribution = json_string_contribution(&character.to_string()); + if used.saturating_add(contribution) > limit { + break; + } + used += contribution; + end = index + character.len_utf8(); + } + text[..end].to_string() +} + impl ToolResult { pub fn success(content: impl Into, data: Value) -> Self { Self { @@ -121,4 +150,74 @@ impl ToolResult { replayed: false, } } + + /// Exact fully serialized UTF-8 byte length of this typed result. + pub fn encoded_len(&self) -> usize { + serde_json::to_vec(self) + .map(|encoded| encoded.len()) + .unwrap_or(usize::MAX) + } + + /// Compact a native settlement receipt, without changing its error code + /// or dropping terminal facts or the primary artifact identity. + /// If even the compact receipt exceeds the budget, settlement must reject + /// it as too large rather than commit a receipt that misstates the effect. + pub fn compact_to_bytes(&self, cap: usize) -> Self { + if self.encoded_len() <= cap { + return self.clone(); + } + let mut compact = self.clone(); + compact.truncated = true; + compact.content.clear(); + compact.artifacts.truncate(1); + if let Some(error) = compact.error.as_mut() { + error.message = truncate_json_bytes(&error.message, 96); + } + if compact.encoded_len() <= cap { + return compact; + } + if let Some(error) = compact.error.as_mut() { + error.message.clear(); + } + if compact.encoded_len() <= cap { + return compact; + } + + // The ledger keeps the complete native evidence. If the full data + // won't fit, project once without losing the effect's disposition or + // a process's terminal facts. An unknown shape still has to pass the + // caller's size check; never turn it into an empty success receipt. + if let Some(data) = self.data.as_object() { + let keys: &[&str] = match data.get("effect").and_then(Value::as_str) { + Some("artifact_store") => &["effect", "artifact", "len"], + Some("atomic_write") => &[ + "effect", + "publication", + "len", + "hash", + "durable", + "staging_cleaned", + "temp_completed", + ], + Some("process_spawn") => &[ + "effect", + "pid", + "background", + "status", + "process_state", + "exit_code", + "signal", + ], + _ => &["status", "process_state", "exit_code", "signal"], + }; + let projected: serde_json::Map<_, _> = keys + .iter() + .filter_map(|&key| data.get(key).map(|value| (key.to_owned(), value.clone()))) + .collect(); + if !projected.is_empty() { + compact.data = Value::Object(projected); + } + } + compact + } } diff --git a/tests/capability_lifecycle_tests.rs b/tests/capability_lifecycle_tests.rs index 1fc67618..73e86a3a 100644 --- a/tests/capability_lifecycle_tests.rs +++ b/tests/capability_lifecycle_tests.rs @@ -7,13 +7,14 @@ use std::collections::HashMap; use std::panic::{AssertUnwindSafe, catch_unwind}; use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Barrier, Mutex}; use std::time::Instant; use rustscript_agent::capabilities::{ ApprovalGate, CancellationFlag, CapabilityLifecycle, CapabilityOwner, CapabilityRisk, DurableStarted, DurableToolLifecycle, ExecutionLease, GuardianApprovalGate, LifecycleClock, - LifecycleError, LifecycleLimits, PrepareMetadata, PrepareOutcome, TokenIssuer, + LifecycleError, LifecycleLimits, NativeArtifactIdentity, NativeEffectRecord, PrepareMetadata, + PrepareOutcome, PublishedTokenPolicy, TokenIssuer, }; use rustscript_agent::{AgentConfig, AgentHostBridges, AgentRunner}; use rustscript_vm::Value as VmValue; @@ -286,6 +287,14 @@ fn metadata(call_id: &str, name: &str) -> PrepareMetadata { } fn engine(log: Arc, durable: Arc) -> CapabilityLifecycle { + engine_with_policy(log, durable, PublishedTokenPolicy::Abort) +} + +fn engine_with_policy( + log: Arc, + durable: Arc, + policy: PublishedTokenPolicy, +) -> CapabilityLifecycle { CapabilityLifecycle::builder() .owner(owner()) .registry_identity("registry-a") @@ -301,6 +310,7 @@ fn engine(log: Arc, durable: Arc) -> CapabilityLifec .durable(durable as Arc) .approval(Arc::new(AllowAll) as Arc) .generation(1) + .published_token_policy(policy) .build() .expect("lifecycle") } @@ -1394,3 +1404,373 @@ fn prepare_pair_cancelled_no_persist_no_token() { ); assert!(durable.started_records().is_empty()); } + +/// Blocks the durable interrupt after the recovery claim is taken, so the test +/// can prove that publication, abort and a second recovery all observe it. +struct GatedInterruptDurable { + inner: Arc, + entered: Arc, + release: Arc, +} + +impl GatedInterruptDurable { + fn new(inner: Arc) -> Arc { + Arc::new(Self { + inner, + entered: Arc::new(Barrier::new(2)), + release: Arc::new(Barrier::new(2)), + }) + } + + fn wait_claimed(&self) { + self.entered.wait(); + } + + fn release(&self) { + self.release.wait(); + } +} + +impl DurableToolLifecycle for GatedInterruptDurable { + fn assert_active_run(&self, run_id: &str) -> Result<(), LifecycleError> { + self.inner.assert_active_run(run_id) + } + + fn prepare_parent( + &self, + run_id: &str, + call_id: &str, + tool_name: &str, + ) -> Result<(), LifecycleError> { + self.inner.prepare_parent(run_id, call_id, tool_name) + } + + fn replay_result( + &self, + run_id: &str, + call_id: &str, + tool_name: &str, + ) -> Result, LifecycleError> { + self.inner.replay_result(run_id, call_id, tool_name) + } + + fn commit_started(&self, record: &DurableStarted) -> Result<(), LifecycleError> { + self.inner.commit_started(record) + } + + fn commit_result(&self, call_id: &str, result: &Value) -> Result { + self.inner.commit_result(call_id, result) + } + + fn interrupt(&self, call_id: &str) -> Result<(), LifecycleError> { + self.entered.wait(); + self.release.wait(); + self.inner.interrupt(call_id) + } +} + +#[test] +fn recovery_claim_excludes_publication_abort_and_a_second_recovery() { + let log = SequenceLog::new(); + let durable = MemoryDurable::new(Arc::clone(&log)); + let gated = GatedInterruptDurable::new(Arc::clone(&durable)); + let lifecycle = CapabilityLifecycle::builder() + .owner(owner()) + .registry_identity("registry-a") + .workspace("/tmp/workspace-a") + .limits(LifecycleLimits { + max_tool_calls: 8, + max_output_bytes: 4096, + max_summary_bytes: 256, + }) + .deadline_ms(10_000) + .clock(Arc::clone(&ScriptedClock::new(1_000)) as Arc) + .tokens(LoggingIssuer::new(Arc::clone(&log)) as Arc) + .durable(Arc::clone(&gated) as Arc) + .approval(Arc::new(AllowAll) as Arc) + .generation(1) + .build() + .expect("lifecycle"); + let token = token_of( + lifecycle + .prepare(&owner(), metadata("call-claim", "fixture_only_tool")) + .expect("prepare"), + ); + let recovery = { + let lifecycle = lifecycle.clone(); + std::thread::spawn(move || lifecycle.recover_open_tokens()) + }; + gated.wait_claimed(); + + let refused = match lifecycle.enter_publication(&token) { + Ok(_) => panic!("publication must be refused while recovery owns the call"), + Err(error) => error, + }; + assert!( + matches!(refused, LifecycleError::Interrupted), + "a recovery claim must look like an interrupted token: {refused:?}" + ); + + // The managed/default recovery ordering transitions the token before the + // gated durable write, so the abort lease can no longer find it open. It + // observes the interruption instead of retracting a call owned by + // recovery. + let lease_error = match lifecycle.lease(&token) { + Ok(_) => panic!("the base ordering already interrupted this token"), + Err(error) => error, + }; + assert!( + matches!(lease_error, LifecycleError::Interrupted), + "the abort lease must observe the interruption: {lease_error:?}" + ); + assert_eq!( + lifecycle.open_token_count(), + 0, + "the transition already ran before the gated durable I/O" + ); + assert_eq!(lifecycle.interrupted_token_count(), 1); + + // A second recovery must skip the already claimed call instead of writing + // a second interrupt for it. + let second = lifecycle + .recover_open_tokens() + .expect("a competing recovery must not fail"); + assert!( + second.is_empty(), + "a claimed call must be skipped by a second recovery: {second:?}" + ); + + gated.release(); + let recovered = recovery + .join() + .expect("recovery thread") + .expect("recovery must finish"); + assert_eq!(recovered, vec!["call-claim".to_string()]); + assert_eq!(lifecycle.open_token_count(), 0); + assert_eq!(lifecycle.interrupted_token_count(), 1); + assert_eq!(durable.interrupted(), vec!["call-claim".to_string()]); +} + +#[test] +fn managed_recovery_batches_every_token_before_the_first_durable_interrupt() { + struct FailFirstInterruptDurable { + inner: Arc, + lifecycle: Mutex>>, + observed_open: Mutex>, + attempts: Mutex, + } + + impl FailFirstInterruptDurable { + fn new(inner: Arc) -> Arc { + Arc::new(Self { + inner, + lifecycle: Mutex::new(None), + observed_open: Mutex::new(None), + attempts: Mutex::new(0), + }) + } + + fn attempts(&self) -> usize { + *self.attempts.lock().expect("attempts") + } + } + + impl DurableToolLifecycle for FailFirstInterruptDurable { + fn assert_active_run(&self, run_id: &str) -> Result<(), LifecycleError> { + self.inner.assert_active_run(run_id) + } + + fn prepare_parent( + &self, + run_id: &str, + call_id: &str, + tool_name: &str, + ) -> Result<(), LifecycleError> { + self.inner.prepare_parent(run_id, call_id, tool_name) + } + + fn replay_result( + &self, + run_id: &str, + call_id: &str, + tool_name: &str, + ) -> Result, LifecycleError> { + self.inner.replay_result(run_id, call_id, tool_name) + } + + fn commit_started(&self, record: &DurableStarted) -> Result<(), LifecycleError> { + self.inner.commit_started(record) + } + + fn commit_result(&self, call_id: &str, result: &Value) -> Result { + self.inner.commit_result(call_id, result) + } + + fn interrupt(&self, call_id: &str) -> Result<(), LifecycleError> { + let mut attempts = self.attempts.lock().expect("attempts"); + *attempts += 1; + if *attempts == 1 { + // Observe the token state at the first durable interrupt. The + // managed base batch must have transitioned every token here. + let lifecycle = self.lifecycle.lock().expect("lifecycle").clone(); + *self.observed_open.lock().expect("observed") = + lifecycle.map(|lifecycle| lifecycle.open_token_count()); + return Err(LifecycleError::ResultCommitFailed( + "injected interrupt failure".to_string(), + )); + } + drop(attempts); + self.inner.interrupt(call_id) + } + } + + let log = SequenceLog::new(); + let inner = MemoryDurable::new(Arc::clone(&log)); + let durable = FailFirstInterruptDurable::new(Arc::clone(&inner)); + let lifecycle = engine_with_durable( + Arc::clone(&log), + Arc::clone(&durable) as Arc, + ); + *durable.lifecycle.lock().expect("lifecycle") = Some(Arc::new(lifecycle.clone())); + let _first = token_of( + lifecycle + .prepare(&owner(), metadata("batch-call-a", "fixture_only_tool")) + .expect("first prepare"), + ); + let _second = token_of( + lifecycle + .prepare(&owner(), metadata("batch-call-b", "fixture_only_tool")) + .expect("second prepare"), + ); + let error = lifecycle + .recover_open_tokens() + .expect_err("the first durable interrupt must fail"); + assert!(matches!(error, LifecycleError::ResultCommitFailed(_))); + assert_eq!( + lifecycle.open_token_count(), + 0, + "the managed batch must transition every token before the first durable interrupt" + ); + assert_eq!(lifecycle.interrupted_token_count(), 2); + assert_eq!( + *durable.observed_open.lock().expect("observed"), + Some(0), + "the durable interrupt must observe no remaining open token" + ); + assert_eq!( + durable.attempts(), + 1, + "base stops the interrupt loop at the first write failure" + ); + assert!( + inner.interrupted().is_empty(), + "the failed first write must not record an interrupt" + ); + let retried = lifecycle + .recover_open_tokens() + .expect("no open token remains to retry"); + assert!( + retried.is_empty(), + "a later close must not retry a failed managed interrupt: {retried:?}" + ); + assert_eq!(durable.attempts(), 1); +} + +#[test] +fn default_managed_abort_interrupts_a_published_token_like_base() { + let log = SequenceLog::new(); + let durable = MemoryDurable::new(Arc::clone(&log)); + let lifecycle = engine(Arc::clone(&log), Arc::clone(&durable)); + let token = token_of( + lifecycle + .prepare(&owner(), metadata("call-abort", "fixture_only_tool")) + .expect("prepare"), + ); + lifecycle + .enter_publication(&token) + .expect("publication permit") + .published_effect(NativeEffectRecord::artifact_store(NativeArtifactIdentity { + id: "artifact-id".to_string(), + len: 4, + hash: "hash".to_string(), + })); + + drop(lifecycle.lease(&token).expect("abort lease")); + assert_eq!( + lifecycle.interrupted_token_count(), + 1, + "the managed base mode must interrupt a published token on abort" + ); + assert_eq!(lifecycle.open_token_count(), 0); + assert_eq!(durable.interrupted(), vec!["call-abort".to_string()]); +} + +#[test] +fn managed_recovery_interrupts_a_publishing_token_like_base() { + let log = SequenceLog::new(); + let durable = MemoryDurable::new(Arc::clone(&log)); + let lifecycle = engine(Arc::clone(&log), Arc::clone(&durable)); + let token = token_of( + lifecycle + .prepare(&owner(), metadata("call-publishing", "fixture_only_tool")) + .expect("prepare"), + ); + // The effect worker is inside the publication fence. Base recovery did not + // assume quiescence: it interrupted the token and released its resources. + let permit = lifecycle.enter_publication(&token).expect("publication"); + + let recovered = lifecycle + .recover_open_tokens() + .expect("managed recovery must interrupt a publishing token"); + assert_eq!( + recovered, + vec!["call-publishing".to_string()], + "the managed base mode must not leave a publishing token for later" + ); + assert_eq!(lifecycle.open_token_count(), 0); + assert_eq!(lifecycle.interrupted_token_count(), 1); + assert_eq!(durable.interrupted(), vec!["call-publishing".to_string()]); + + // The worker's own exit path still runs after the interrupt and must not + // resurrect the call. + drop(permit); + assert_eq!(lifecycle.open_token_count(), 0); + assert_eq!(lifecycle.interrupted_token_count(), 1); +} + +#[test] +fn retention_mode_keeps_a_published_token_open_for_settlement() { + let log = SequenceLog::new(); + let durable = MemoryDurable::new(Arc::clone(&log)); + let lifecycle = engine_with_policy( + Arc::clone(&log), + Arc::clone(&durable), + PublishedTokenPolicy::RetainForSettlement, + ); + let token = token_of( + lifecycle + .prepare(&owner(), metadata("call-retain", "fixture_only_tool")) + .expect("prepare"), + ); + lifecycle + .enter_publication(&token) + .expect("publication permit") + .published_effect(NativeEffectRecord::artifact_store(NativeArtifactIdentity { + id: "artifact-id".to_string(), + len: 4, + hash: "hash".to_string(), + })); + + drop(lifecycle.lease(&token).expect("abort lease")); + assert_eq!( + lifecycle.open_token_count(), + 1, + "MCP retention mode must keep the published token open" + ); + assert_eq!(lifecycle.interrupted_token_count(), 0); + let settlement = lifecycle + .settle_call_with_receipt("call-retain", Some(&json!({"ok": true, "content": "done"}))) + .expect("settle retained token"); + assert_eq!(settlement.committed, 1); + assert_eq!(lifecycle.open_token_count(), 0); +} diff --git a/tests/capability_tests.rs b/tests/capability_tests.rs index d0f5c047..46b0d626 100644 --- a/tests/capability_tests.rs +++ b/tests/capability_tests.rs @@ -22,7 +22,7 @@ use rustscript_agent::{ CapabilityLifecycle, CapabilityOwner, CapabilityRisk, DurableStarted, DurableToolLifecycle, FilesystemCapability, FilesystemLimits, LifecycleClock, LifecycleError, LifecycleLimits, NeverCancelled, PrepareMetadata, PrepareOutcome, ProcessCapability, ProcessLimits, - SystemClock, TokenIssuer, + PublishedTokenPolicy, SystemClock, TokenIssuer, }, }; use rustscript_vm::{HostTypeSchema, Value as VmValue}; @@ -221,6 +221,10 @@ fn token_of(outcome: PrepareOutcome) -> String { impl Fixture { fn new(label: &str) -> Self { + Self::with_policy(label, PublishedTokenPolicy::Abort) + } + + fn with_policy(label: &str, policy: PublishedTokenPolicy) -> Self { let root = tmp_root(label); let owner = owner(); let clock = ScriptedClock::new(1_000); @@ -241,6 +245,7 @@ impl Fixture { .approval(Arc::new(AllowAll) as Arc) .cancellation(Arc::clone(&cancel) as Arc) .generation(1) + .published_token_policy(policy) .build() .expect("lifecycle"); Self { @@ -920,7 +925,15 @@ fn process_spawn_with_stdin_writes_before_return() { .wait(&token, &spawned.handle, Some(2_000)) .expect("wait"); assert!(snapshot.stdout.contains("from-spawn")); - processes.kill(&token, &spawned.handle).expect("kill"); + assert_eq!( + processes.table_len(), + 0, + "a foreground wait's final snapshot must retire its handle-less record" + ); + let error = processes + .kill(&token, &spawned.handle) + .expect_err("a retired foreground record has no later operation to serve"); + assert_eq!(error_code(&error), "process_not_found"); } #[test] @@ -1976,7 +1989,13 @@ fn result_artifact_is_retracted_on_commit_storage_failure() { #[test] fn result_artifact_is_retracted_on_interrupt_and_reservation_is_released() { let fixture = Fixture::new("artifact-interrupt"); - let artifacts = fixture.artifacts(default_artifact_limits()); + // The total quota exactly fits the first payload. A retained charge would + // reject the republish below. + let artifacts = fixture.artifacts(ArtifactLimits { + max_object_bytes: 1024, + max_total_bytes: 7, + max_objects: 8, + }); let token = fixture.token(CapabilityRisk::Read); let published = artifacts .put_result(&token, b"payload", &json!({})) @@ -1985,6 +2004,8 @@ fn result_artifact_is_retracted_on_interrupt_and_reservation_is_released() { fixture.lifecycle.recover_open_tokens().expect("recover"); assert!(artifacts.stored(&published.id).is_none()); assert_eq!(artifacts.stored_len(), 0); + // The quota charge was released with the object, so the next call can + // publish again under the same store limits. let token2 = fixture.token(CapabilityRisk::Read); let again = artifacts .put_result(&token2, b"again", &json!({})) @@ -2014,6 +2035,52 @@ fn result_artifact_is_retracted_on_cancel_after_publication() { assert_eq!(artifacts.stored_len(), 0); } +#[test] +fn result_artifact_is_retracted_on_deadline_after_publication() { + let fixture = Fixture::new("artifact-deadline"); + let artifacts = fixture.artifacts(default_artifact_limits()); + let token = fixture.token(CapabilityRisk::Read); + let published = artifacts + .put_result(&token, b"payload", &json!({})) + .expect("put"); + fixture.clock.set_now_ms(60_000); + let error = fixture + .lifecycle + .commit( + &fixture.owner, + &token, + json!({"ok": true, "content": "done"}), + ) + .expect_err("deadline elapsed"); + assert!(matches!(error, LifecycleError::DeadlineElapsed)); + assert!(artifacts.stored(&published.id).is_none()); + assert_eq!(artifacts.stored_len(), 0); +} + +#[test] +fn result_artifact_survives_cancel_after_publication_in_mcp_retention_mode() { + let fixture = Fixture::with_policy( + "artifact-cancel-mcp", + PublishedTokenPolicy::RetainForSettlement, + ); + let artifacts = fixture.artifacts(default_artifact_limits()); + let token = fixture.token(CapabilityRisk::Read); + let published = artifacts + .put_result(&token, b"payload", &json!({})) + .expect("put"); + fixture.cancel.cancel(); + fixture + .lifecycle + .commit( + &fixture.owner, + &token, + json!({"ok": true, "content": "done"}), + ) + .expect("a retained published artifact still settles after a late cancellation"); + assert!(artifacts.stored(&published.id).is_some()); + assert_eq!(artifacts.stored_len(), 1); +} + #[test] fn successful_commit_retains_result_artifact_for_replay() { let fixture = Fixture::new("artifact-keep"); @@ -2038,28 +2105,22 @@ fn successful_commit_retains_result_artifact_for_replay() { } #[test] -fn concurrent_result_artifacts_rollback_only_failed_call() { +fn concurrent_result_artifacts_roll_back_only_the_unpublished_call() { let fixture = Fixture::new("artifact-concurrent"); let artifacts = Arc::new(fixture.artifacts(default_artifact_limits())); let token_ok = fixture.token(CapabilityRisk::Read); let token_fail = fixture.token(CapabilityRisk::Read); - thread::scope(|scope| { - let artifacts_ok = Arc::clone(&artifacts); - let artifacts_fail = Arc::clone(&artifacts); - let token_ok = token_ok.clone(); - let token_fail = token_fail.clone(); - scope.spawn(move || { - artifacts_ok - .put_result(&token_ok, b"ok-payload", &json!({})) - .expect("put ok"); - }); - scope.spawn(move || { - artifacts_fail - .put_result(&token_fail, b"fail-payload", &json!({})) - .expect("put fail"); - }); - }); - assert_eq!(artifacts.stored_len(), 2); + let artifacts_ok = Arc::clone(&artifacts); + let token_ok_clone = token_ok.clone(); + thread::spawn(move || { + artifacts_ok + .put_result(&token_ok_clone, b"ok-payload", &json!({})) + .expect("put ok"); + }) + .join() + .expect("publisher ok"); + assert_eq!(artifacts.stored_len(), 1); + fixture .lifecycle .commit( @@ -2069,14 +2130,10 @@ fn concurrent_result_artifacts_rollback_only_failed_call() { ) .expect("commit ok"); fixture.cancel.cancel(); - fixture - .lifecycle - .commit( - &fixture.owner, - &token_fail, - json!({"ok": true, "content": "done"}), - ) - .expect_err("cancelled fail call"); + let unpublished = artifacts + .put_result(&token_fail, b"fail-payload", &json!({})) + .expect_err("cancellation before publication must add no artifact"); + assert_eq!(error_code(&unpublished), "cancelled"); assert_eq!(artifacts.stored_len(), 1); } @@ -2695,7 +2752,26 @@ fn process_shutdown_all_terminates_uncommitted_os_process() { .expect("spawn thread") .expect_err("uncommitted handle must not insert after close"); assert_eq!(error_code(&error), "capability_unavailable"); + // The OS spawn really happened, so the converted record stays owned by the + // closing table until its reap/drain proof; it is never silently dropped. + assert_eq!( + processes.table_len(), + 1, + "a converted child must keep a visible owner until cleanup proof" + ); + let retained_pids = processes.live_pids(); + assert_eq!( + processes.shutdown_all_within(std::time::Instant::now() + Duration::from_secs(2)), + rustscript_agent::capabilities::ProcessCleanupProof::Clean, + "a later cleanup must prove the retained converted record" + ); assert_eq!(processes.table_len(), 0); + assert!( + retained_pids + .into_iter() + .all(|pid| !Path::new(&format!("/proc/{pid}")).exists()), + "the retained converted child must be reaped" + ); let later = processes.spawn( &fixture.token(CapabilityRisk::Execute), &["/bin/echo".to_string(), "late".to_string()], diff --git a/tests/cases/rss_file_tool_tests.rs b/tests/cases/rss_file_tool_tests.rs index 50eced50..71445509 100644 --- a/tests/cases/rss_file_tool_tests.rs +++ b/tests/cases/rss_file_tool_tests.rs @@ -2582,7 +2582,7 @@ fn search_fake_clock_overflow_uses_nested_capability_error_envelope() { } #[test] -fn published_result_artifact_is_retracted_when_commit_fails() { +fn published_result_artifact_is_retained_when_commit_fails() { let fixture = Fixture::new("artifact-rollback"); fs::write(fixture.root.join("wide.txt"), "你好世界".repeat(80)).unwrap(); let mut config = fixture.config(); @@ -2608,7 +2608,7 @@ fn published_result_artifact_is_retracted_when_commit_fails() { assert_eq!(rss.result["error"]["code"], json!("result_commit_failed")); assert_eq!( rss.artifacts.as_ref().expect("rss store").stored_len(), - 0, - "commit failure must not leave a visible result artifact" + 1, + "an artifact that crossed the publication fence must not be retracted by a later commit-storage failure" ); } diff --git a/tests/cases/rss_mutating_file_tool_tests.rs b/tests/cases/rss_mutating_file_tool_tests.rs index af37fa1c..03aac5c2 100644 --- a/tests/cases/rss_mutating_file_tool_tests.rs +++ b/tests/cases/rss_mutating_file_tool_tests.rs @@ -2561,3 +2561,104 @@ fn nested_and_swapped_parent_symlink_race_does_not_touch_outside_secret() { "inside\n" ); } + +/// Runs one mutating tool through a shared filesystem capability whose +/// pre-publication hook replaces the destination file with a directory. The +/// exchange then steals the new file into staging, and the proven reverse +/// exchange restores the original directory: the tool receives the explicit +/// `publication_restored` outcome. +fn run_restored_publication_tool( + fixture: &Fixture, + module: &'static str, + tool_name: &'static str, + arguments: Value, + call_id: &'static str, +) -> RssRun { + let config = fixture.config(); + let durable = MemoryDurable::new(); + let lifecycle = Arc::new(build_lifecycle( + &fixture.root, + Arc::clone(&durable), + Arc::new(AllowAll), + Arc::new(NeverCancelled), + Arc::new(SystemClock), + SystemClock.now_ms() + 60_000, + )); + let filesystem = Arc::new( + FilesystemCapability::new( + lifecycle.as_ref().clone(), + owner(), + filesystem_limits(&config), + ) + .expect("filesystem capability"), + ); + let destination = fixture.root.join("out.txt"); + filesystem.inject_before_publish(Arc::new(move || { + fs::remove_file(&destination).expect("replace the destination file"); + fs::create_dir(&destination).expect("plant a directory at the destination"); + })); + let mut exec = mutation_exec(module, tool_name, arguments, durable, call_id); + exec.shared_lifecycle = Some(lifecycle); + exec.shared_filesystem = Some(filesystem); + run_rss_exec(fixture, &config, exec) +} + +#[test] +fn round5_restored_write_reports_restored_publication() { + let fixture = Fixture::new("r5-restored-write"); + fs::write(fixture.root.join("out.txt"), "old\n").expect("destination file"); + let run = run_restored_publication_tool( + &fixture, + "write_file_entry.rss", + "write_file", + json!({"path": "out.txt", "content": "new\n"}), + "call-r5-restored-write", + ); + assert_eq!(run.result["ok"], json!(false), "rss={}", run.result); + assert_eq!( + run.result["error"]["code"], + json!("publication_restored"), + "rss={}", + run.result + ); + assert_eq!( + run.result["data"]["publication"], + json!("restored"), + "a restored exchange must report its truthful publication state: {}", + run.result + ); + assert!( + fixture.root.join("out.txt").is_dir(), + "the proven reverse exchange must restore the original directory" + ); +} + +#[test] +fn round5_restored_patch_reports_restored_publication() { + let fixture = Fixture::new("r5-restored-patch"); + fs::write(fixture.root.join("out.txt"), "old\n").expect("destination file"); + let run = run_restored_publication_tool( + &fixture, + "patch_entry.rss", + "patch", + json!({"path": "out.txt", "old_string": "old\n", "new_string": "new\n"}), + "call-r5-restored-patch", + ); + assert_eq!(run.result["ok"], json!(false), "rss={}", run.result); + assert_eq!( + run.result["error"]["code"], + json!("publication_restored"), + "rss={}", + run.result + ); + assert_eq!( + run.result["data"]["publication"], + json!("restored"), + "a restored exchange must report its truthful publication state: {}", + run.result + ); + assert!( + fixture.root.join("out.txt").is_dir(), + "the proven reverse exchange must restore the original directory" + ); +} diff --git a/tests/mcp_catalog_tests.rs b/tests/mcp_catalog_tests.rs new file mode 100644 index 00000000..255533aa --- /dev/null +++ b/tests/mcp_catalog_tests.rs @@ -0,0 +1,254 @@ +//! Pure registry-to-MCP catalog and canonical result conversion. +//! +//! These tests do not execute tools or open a transport. They pin the exact +//! mapping from the admitted `ToolRegistrySnapshot` to `rmcp` models and back +//! from a canonical `ToolResult` to an MCP tool result. + +use rustscript_agent::ToolResult; +use rustscript_agent::mcp::ToolProfile; +use rustscript_agent::mcp::catalog::{ + McpCatalogError, RISK_META_KEY, TOOLSET_META_KEY, catalog_from_descriptors, + catalog_from_registry, +}; +use rustscript_agent::mcp::result::{ + ARTIFACTS_META_KEY, ERROR_CODE_META_KEY, TRUNCATED_META_KEY, to_call_tool_result, +}; +use rustscript_agent::registry::ToolRegistrySnapshot; +use rustscript_agent::tool_schema::{ToolDescriptor, Toolset}; +use serde_json::{Value, json}; + +fn snapshot() -> ToolRegistrySnapshot { + rustscript_agent::bundled_tool_registry() + .expect("bundled registry") + .snapshot() +} + +fn descriptor(name: &str, risk_class: &str, toolset: &str) -> ToolDescriptor { + ToolDescriptor::new( + name, + "test descriptor", + toolset, + risk_class, + json!({ + "type": "object", + "properties": {"path": {"type": "string"}}, + "required": ["path"], + "additionalProperties": false + }), + ) +} + +#[test] +fn catalog_matches_the_registry_exactly_in_deterministic_order() { + let snapshot = snapshot(); + let coding = catalog_from_registry(&snapshot, ToolProfile::Coding).expect("coding catalog"); + let coding_again = + catalog_from_registry(&snapshot, ToolProfile::Coding).expect("coding catalog again"); + + let names: Vec<&str> = coding.iter().map(|tool| tool.name.as_ref()).collect(); + let expected: Vec<&str> = snapshot.names().iter().map(String::as_str).collect(); + assert_eq!(names, expected, "catalog order must follow the registry"); + assert_eq!( + serde_json::to_value(&coding).expect("serialize catalog"), + serde_json::to_value(&coding_again).expect("serialize catalog again"), + "catalog output must be deterministic" + ); + + for (tool, descriptor) in coding.iter().zip(snapshot.descriptors()) { + assert_eq!(tool.name.as_ref(), descriptor.name); + assert_eq!( + tool.description.as_deref(), + Some(descriptor.description.as_str()) + ); + assert_eq!( + tool.schema_as_json_value(), + descriptor.schema, + "tool {} must reuse the admitted descriptor schema", + descriptor.name + ); + let meta = tool.meta.as_ref().expect("risk metadata"); + assert_eq!(meta.0[RISK_META_KEY], json!(descriptor.risk_class)); + assert_eq!(meta.0[TOOLSET_META_KEY], json!(descriptor.toolset)); + let annotations = tool.annotations.as_ref().expect("annotations"); + match descriptor.risk_class.as_str() { + "read" => { + assert_eq!(annotations.read_only_hint, Some(true)); + assert_eq!(annotations.destructive_hint, Some(false)); + assert_eq!(annotations.idempotent_hint, Some(true)); + assert_eq!(annotations.open_world_hint, Some(false)); + } + "write" => { + assert_eq!(annotations.read_only_hint, Some(false)); + assert_eq!(annotations.destructive_hint, Some(true)); + assert_eq!(annotations.idempotent_hint, Some(false)); + assert_eq!(annotations.open_world_hint, Some(false)); + } + "execute" => { + assert_eq!(annotations.read_only_hint, Some(false)); + assert_eq!(annotations.destructive_hint, Some(true)); + assert_eq!(annotations.idempotent_hint, Some(false)); + assert_eq!(annotations.open_world_hint, Some(true)); + } + other => panic!("unexpected admitted risk class {other}"), + } + } +} + +#[test] +fn read_only_catalog_exports_only_the_two_read_tools() { + let catalog = + catalog_from_registry(&snapshot(), ToolProfile::ReadOnly).expect("read-only catalog"); + let names: Vec<&str> = catalog.iter().map(|tool| tool.name.as_ref()).collect(); + assert_eq!(names, ["read_file", "search_files"]); + for tool in &catalog { + let annotations = tool.annotations.as_ref().expect("annotations"); + assert_eq!(annotations.read_only_hint, Some(true)); + assert_eq!(annotations.destructive_hint, Some(false)); + let meta = tool.meta.as_ref().expect("risk metadata"); + assert_eq!(meta.0[RISK_META_KEY], json!("read")); + } +} + +#[test] +fn unsupported_registry_risk_toolset_and_profile_mismatch_cannot_be_exported() { + let unknown_risk = catalog_from_descriptors( + &[descriptor("read_file", "network", Toolset::CODING)], + ToolProfile::Coding, + ) + .expect_err("unknown risk class must not be exported"); + assert!( + matches!( + unknown_risk, + McpCatalogError::UnsupportedRiskClass { ref name, ref value } + if name == "read_file" && value == "network" + ), + "error={unknown_risk:?}" + ); + + let unknown_toolset = catalog_from_descriptors( + &[descriptor("read_file", "read", "network")], + ToolProfile::Coding, + ) + .expect_err("unknown toolset must not be exported"); + assert!( + matches!( + unknown_toolset, + McpCatalogError::UnsupportedToolset { ref name, ref value } + if name == "read_file" && value == "network" + ), + "error={unknown_toolset:?}" + ); + + let profile_mismatch = catalog_from_descriptors( + &[descriptor("read_file", "write", Toolset::CODING)], + ToolProfile::ReadOnly, + ) + .expect_err("read-only profile must reject a write-risk read_file"); + assert!( + matches!( + profile_mismatch, + McpCatalogError::ProfileViolation { ref name, ref risk_class } + if name == "read_file" && risk_class == "write" + ), + "error={profile_mismatch:?}" + ); + + let boolean_schema = ToolDescriptor::new( + "read_file", + "test descriptor", + Toolset::CODING, + "read", + json!(true), + ); + let non_object_schema = catalog_from_descriptors(&[boolean_schema], ToolProfile::Coding) + .expect_err("MCP inputSchema must be an object"); + assert!( + matches!( + non_object_schema, + McpCatalogError::ObjectSchemaRequired { ref name } if name == "read_file" + ), + "error={non_object_schema:?}" + ); +} + +#[test] +fn canonical_success_result_preserves_text_data_truncation_and_artifacts() { + let mut result = ToolResult::success("exact text\n", json!({"path": "a.txt", "count": 2})); + result.truncated = true; + result.artifacts = vec!["artifact-abc".to_string()]; + + let converted = to_call_tool_result(&result); + + assert_eq!(converted.is_error, Some(false)); + assert_eq!(converted.content.len(), 1); + assert_eq!( + converted.content[0].as_text().expect("text block").text, + "exact text\n" + ); + assert_eq!( + converted.structured_content, + Some(json!({"path": "a.txt", "count": 2})) + ); + let meta = converted.meta.as_ref().expect("result metadata"); + assert_eq!(meta.0[TRUNCATED_META_KEY], json!(true)); + assert_eq!(meta.0[ARTIFACTS_META_KEY], json!(["artifact-abc"])); + assert!(!meta.0.contains_key(ERROR_CODE_META_KEY)); +} + +#[test] +fn canonical_failure_result_preserves_error_state_and_bounded_content() { + let result = ToolResult::failure_with( + "path_denied", + "workspace path denied", + "partial text", + json!({"path": "../outside"}), + true, + ); + + let converted = to_call_tool_result(&result); + + assert_eq!(converted.is_error, Some(true)); + let texts: Vec<&str> = converted + .content + .iter() + .map(|block| block.as_text().expect("text block").text.as_str()) + .collect(); + assert_eq!( + texts, + ["partial text", "path_denied: workspace path denied"], + "both canonical text and the typed error message must survive" + ); + assert_eq!( + converted.structured_content, + Some(json!({"path": "../outside"})) + ); + let meta = converted.meta.as_ref().expect("result metadata"); + assert_eq!(meta.0[TRUNCATED_META_KEY], json!(true)); + assert_eq!(meta.0[ARTIFACTS_META_KEY], json!([])); + assert_eq!(meta.0[ERROR_CODE_META_KEY], json!("path_denied")); +} + +#[test] +fn empty_failure_content_still_carries_the_typed_error_message() { + let converted = to_call_tool_result(&ToolResult::failure("budget_exceeded", "too large")); + + assert_eq!(converted.is_error, Some(true)); + assert_eq!(converted.content.len(), 1); + assert_eq!( + converted.content[0].as_text().expect("text block").text, + "budget_exceeded: too large" + ); + assert_eq!( + converted.structured_content, + Some(Value::Object(Default::default())) + ); +} + +#[test] +fn empty_success_content_stays_empty_while_structured_data_survives() { + let converted = to_call_tool_result(&ToolResult::success("", json!({"ok": 1}))); + + assert_eq!(converted.is_error, Some(false)); + assert!(converted.content.is_empty()); + assert_eq!(converted.structured_content, Some(json!({"ok": 1}))); +} diff --git a/tests/mcp_executor_hardening_tests.rs b/tests/mcp_executor_hardening_tests.rs new file mode 100644 index 00000000..3c880b0d --- /dev/null +++ b/tests/mcp_executor_hardening_tests.rs @@ -0,0 +1,846 @@ +//! Sol blocker regressions for the provider-free MCP tool core. +//! +//! These tests exercise the public executor and capability surfaces without +//! provider configuration. They cover lifetime admission bounds, process +//! table bounds, shutdown/effect cancellation, output-cap safety, and the +//! retained-workspace binding. + +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Condvar, Mutex}; +use std::time::{Duration, Instant}; + +use rustscript_agent::capabilities::{ + ApprovalGate, CancellationFlag, CapabilityLifecycle, CapabilityOwner, CapabilityRisk, + DurableStarted, DurableToolLifecycle, FilesystemCapability, FilesystemLimits, LifecycleClock, + LifecycleError, LifecycleLimits, NeverCancelled, PrepareMetadata, PrepareOutcome, SystemClock, + TokenIssuer, UuidIssuer, +}; +use rustscript_agent::mcp::ToolProfile; +use rustscript_agent::mcp::executor::{ + McpToolExecutor, McpToolExecutorConfig, McpToolExecutorError, +}; +use serde_json::json; + +static NEXT_FIXTURE: AtomicU64 = AtomicU64::new(0); + +struct Fixture { + parent: PathBuf, + root: PathBuf, +} + +impl Fixture { + fn new(label: &str) -> Self { + let sequence = NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed); + let parent = std::env::temp_dir().join(format!( + "mcp-hardening-{label}-{}-{sequence}", + std::process::id() + )); + let root = parent.join("workspace"); + fs::create_dir_all(&root).expect("create hardening fixture"); + Self { parent, root } + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.parent); + } +} + +fn executor(root: &Path) -> McpToolExecutor { + McpToolExecutor::new(McpToolExecutorConfig::new(root)) + .unwrap_or_else(|error| panic!("construct executor: {error}")) +} + +fn read( + executor: &McpToolExecutor, + call_id: &str, +) -> Result { + executor.execute_tool(Some(call_id), "read_file", &json!({"path": "hello.txt"})) +} + +#[test] +fn invalid_requests_do_not_consume_call_identities() { + let fixture = Fixture::new("invalid-ids"); + fs::write(fixture.root.join("hello.txt"), "hello\n").expect("write hello"); + let executor = executor(&fixture.root); + + let unknown = executor + .execute_tool(Some("reusable-id"), "not_a_tool", &json!({})) + .expect_err("unknown tool"); + assert!(matches!(unknown, McpToolExecutorError::UnknownTool { .. })); + + let invalid = executor + .execute_tool(Some("reusable-id"), "read_file", &json!({})) + .expect_err("invalid arguments"); + assert!(matches!( + invalid, + McpToolExecutorError::InvalidArguments { .. } + )); + + let read_only = McpToolExecutor::new( + McpToolExecutorConfig::new(&fixture.root).with_profile(ToolProfile::ReadOnly), + ) + .expect("read-only executor"); + let disabled = read_only + .execute_tool( + Some("reusable-id"), + "write_file", + &json!({"path": "x", "content": "y"}), + ) + .expect_err("disabled tool"); + assert!(matches!( + disabled, + McpToolExecutorError::DisabledTool { .. } + )); + + let accepted = read(&executor, "reusable-id").expect("schema-valid request may reuse the id"); + assert!(accepted.ok, "result={accepted:?}"); +} + +#[test] +fn lifetime_quota_rejection_does_not_retain_the_rejected_call_id() { + let fixture = Fixture::new("quota-id"); + fs::write(fixture.root.join("hello.txt"), "hello\n").expect("write hello"); + let executor = + McpToolExecutor::new(McpToolExecutorConfig::new(&fixture.root).with_max_tool_calls(1)) + .expect("construct executor"); + let first = read(&executor, "admitted-call").expect("first admitted call"); + assert!(first.ok); + + let over = read(&executor, "quota-call").expect_err("hard admission quota must reject"); + assert_eq!(over.code(), "call_quota_exhausted", "error={over:?}"); + let retry = read(&executor, "quota-call").expect_err("rejected id must stay reusable"); + assert_eq!( + retry.code(), + "call_quota_exhausted", + "rejected call id must not become a duplicate: {retry:?}" + ); +} + +#[test] +fn concurrent_admission_never_exceeds_the_lifetime_bound() { + let fixture = Fixture::new("concurrent-admission"); + fs::write(fixture.root.join("hello.txt"), "hello\n").expect("write hello"); + let executor = Arc::new( + McpToolExecutor::new(McpToolExecutorConfig::new(&fixture.root).with_max_tool_calls(2)) + .expect("construct executor"), + ); + + let mut handles = Vec::new(); + for index in 0..8 { + let executor = Arc::clone(&executor); + handles.push(std::thread::spawn(move || { + read(&executor, &format!("concurrent-{index}")).is_ok() + })); + } + let successes = handles + .into_iter() + .map(|handle| handle.join().expect("join admission thread")) + .filter(|admitted| *admitted) + .count(); + assert_eq!(successes, 2, "lifetime quota over-admitted calls"); +} + +#[test] +fn call_deadline_stops_a_running_process_and_settles() { + let fixture = Fixture::new("call-deadline"); + let executor = McpToolExecutor::new( + McpToolExecutorConfig::new(&fixture.root).with_call_timeout(Duration::from_millis(100)), + ) + .expect("construct executor"); + let result = executor + .execute_tool( + Some("deadline-call"), + "terminal", + &json!({ + "argv": ["/bin/sleep", "5"], + "timeout_ms": 30000, + }), + ) + .expect("deadline returns a canonical result"); + assert!(!result.ok, "deadline result={result:?}"); + assert_eq!( + result.error.as_ref().map(|error| error.code.as_str()), + Some("deadline_elapsed") + ); + assert_eq!(executor.open_token_count(), 0); +} + +#[test] +fn unknown_tool_diagnostics_escape_control_characters() { + let fixture = Fixture::new("control-name"); + let executor = executor(&fixture.root); + let error = executor + .execute_tool(Some("control-call"), "bad\u{1b}[31mtool", &json!({})) + .expect_err("unknown tool"); + match error { + McpToolExecutorError::UnknownTool { name } => { + assert_eq!(name, "bad\\u{1b}[31mtool"); + } + other => panic!("expected unknown tool, got {other:?}"), + } +} + +#[test] +fn process_table_per_owner_bound_rejects_new_children() { + let fixture = Fixture::new("process-bound"); + let executor = executor(&fixture.root); + for index in 0..9 { + let result = executor + .execute_tool( + Some(&format!("spawn-{index}")), + "terminal", + &json!({"argv": ["/bin/sleep", "30"], "background": true}), + ) + .expect("terminal dispatch"); + if index < 8 { + assert!(result.ok, "spawn {index} result={result:?}"); + assert!( + result.data.get("process_id").is_some(), + "spawn {index} result={result:?}" + ); + } else { + assert!( + !result.ok, + "ninth child exceeded the per-owner process bound: {result:?}" + ); + } + } + executor.shutdown(); +} + +#[test] +fn shutdown_cancels_an_admitted_foreground_process_call() { + let fixture = Fixture::new("shutdown-cancel"); + let executor = Arc::new(executor(&fixture.root)); + let (sender, receiver) = std::sync::mpsc::channel(); + let worker = { + let executor = Arc::clone(&executor); + std::thread::spawn(move || { + let result = executor.execute_tool( + Some("shutdown-cancel-call"), + "terminal", + &json!({ + "argv": ["/bin/sh", "-c", "sleep 2; printf leaked > leaked.txt"], + "timeout_ms": 30000, + }), + ); + let _ = sender.send(result); + }) + }; + std::thread::sleep(Duration::from_millis(300)); + let started = Instant::now(); + executor.shutdown(); + let result = receiver + .recv_timeout(Duration::from_secs(10)) + .expect("shutdown must cancel the admitted call"); + assert!( + started.elapsed() < Duration::from_secs(5), + "shutdown took {:?}", + started.elapsed() + ); + worker.join().expect("worker"); + let result = result.expect("cancelled call returns a canonical result"); + assert!(!result.ok, "shutdown-cancelled call must fail: {result:?}"); + let code = result + .error + .as_ref() + .map(|error| error.code.as_str()) + .unwrap_or(""); + assert!( + code == "cancelled" || code == "deadline_elapsed", + "expected typed cancellation, got {code:?}: {result:?}" + ); + std::thread::sleep(Duration::from_millis(2_200)); + assert!( + !fixture.root.join("leaked.txt").exists(), + "cancelled process call must not publish a later filesystem effect" + ); +} + +#[test] +fn impossible_output_cap_is_rejected_before_an_effect_publishes() { + let fixture = Fixture::new("small-output"); + let config = McpToolExecutorConfig::new(&fixture.root).with_max_output_bytes(64); + match McpToolExecutor::new(config) { + Err(error) => { + assert_eq!(error.code(), "invalid_config", "error={error:?}"); + } + Ok(executor) => { + let _ = executor.execute_tool( + Some("small-cap-write"), + "write_file", + &json!({"path": "small-cap.txt", "content": "payload\n"}), + ); + assert!( + !fixture.root.join("small-cap.txt").exists(), + "an impossible receipt cap must reject before publication" + ); + } + } +} + +#[test] +fn minimum_safe_output_cap_preserves_committed_receipts_and_truncation() { + let fixture = Fixture::new("min-output"); + fs::write( + fixture.root.join("large.txt"), + "abcdefghijklmnopqrstuvwxyz".repeat(128), + ) + .expect("write large fixture"); + let executor = + McpToolExecutor::new(McpToolExecutorConfig::new(&fixture.root).with_max_output_bytes(512)) + .expect("minimum safe cap constructs"); + let written = executor + .execute_tool( + Some("min-cap-write"), + "write_file", + &json!({"path": "small.txt", "content": "receipt\n"}), + ) + .expect("write dispatch"); + assert!(written.ok, "committed receipt must survive: {written:?}"); + assert_eq!( + fs::read_to_string(fixture.root.join("small.txt")).expect("read written file"), + "receipt\n" + ); + + let truncated = executor + .execute_tool( + Some("min-cap-read"), + "read_file", + &json!({"path": "large.txt"}), + ) + .expect("large read dispatch"); + assert!( + truncated.ok, + "truncation is a successful bounded result: {truncated:?}" + ); + assert!(truncated.truncated, "artifact receipt must mark truncation"); + assert_eq!( + truncated.artifacts.len(), + 1, + "large output must publish exactly one artifact: {truncated:?}" + ); + assert!( + truncated.content.starts_with("artifact "), + "artifact receipt content must be canonical: {truncated:?}" + ); +} + +#[test] +fn minimum_safe_output_cap_supports_process_receipts() { + let fixture = Fixture::new("min-process-output"); + let executor = + McpToolExecutor::new(McpToolExecutorConfig::new(&fixture.root).with_max_output_bytes(512)) + .expect("minimum safe cap constructs"); + let terminal = executor + .execute_tool( + Some("min-cap-terminal"), + "terminal", + &json!({"argv": ["/bin/echo", "hello"]}), + ) + .expect("terminal dispatch"); + assert!( + terminal.ok, + "terminal receipt must fit the minimum cap: {terminal:?}" + ); + assert!(terminal.content.contains("hello"), "result={terminal:?}"); + let background = executor + .execute_tool( + Some("min-cap-background"), + "terminal", + &json!({"argv": ["/bin/sleep", "30"], "background": true}), + ) + .expect("background dispatch"); + assert!(background.ok, "background receipt must fit: {background:?}"); + let process_id = background.data["process_id"] + .as_str() + .expect("background process id") + .to_string(); + let killed = executor + .execute_tool( + Some("min-cap-kill"), + "process", + &json!({"action": "kill", "process_id": process_id}), + ) + .expect("process kill dispatch"); + assert!(killed.ok, "process receipt must fit: {killed:?}"); + executor.shutdown(); +} + +#[test] +fn workspace_path_replacement_cannot_redirect_the_retained_root() { + let fixture = Fixture::new("workspace-replace"); + fs::write(fixture.root.join("original.txt"), "original\n").expect("write original"); + let executor = executor(&fixture.root); + let moved = fixture.parent.join("workspace-moved"); + fs::rename(&fixture.root, &moved).expect("move workspace"); + let evil = fixture.parent.join("evil"); + fs::create_dir_all(&evil).expect("create evil workspace"); + fs::write(evil.join("original.txt"), "evil\n").expect("write evil file"); + std::os::unix::fs::symlink(&evil, &fixture.root).expect("replace workspace with symlink"); + + let result = executor + .execute_tool( + Some("retained-root-read"), + "read_file", + &json!({"path": "original.txt"}), + ) + .expect("read through retained root"); + assert!( + !result.ok, + "a replaced workspace path must fail closed instead of redirecting: {result:?}" + ); + assert_ne!( + result.content, "evil\n", + "replacement must not redirect the root" + ); +} + +#[test] +fn lifetime_expiry_rejects_without_retaining_a_call_identity() { + let fixture = Fixture::new("lifetime-expiry"); + fs::write(fixture.root.join("hello.txt"), "hello\n").expect("write hello"); + let executor = McpToolExecutor::new( + McpToolExecutorConfig::new(&fixture.root).with_server_lifetime(Duration::from_millis(50)), + ) + .expect("construct executor"); + std::thread::sleep(Duration::from_millis(100)); + let error = read(&executor, "expired-call").expect_err("expired lifetime rejects"); + assert!( + matches!(error.code(), "lifetime_elapsed" | "executor_closed"), + "expired lifetime must close admission: {error:?}" + ); + assert_eq!(executor.admitted_call_count(), 0); + assert_eq!(executor.retained_call_id_count(), 0); + let later = read(&executor, "expired-call").expect_err("closed executor rejects"); + assert_eq!(later.code(), "executor_closed"); +} + +#[test] +fn shutdown_after_lifetime_expiry_still_reaps_owned_processes() { + let fixture = Fixture::new("lifetime-expiry-shutdown"); + let executor = McpToolExecutor::new( + McpToolExecutorConfig::new(&fixture.root) + .with_server_lifetime(Duration::from_secs(5)) + .with_process_cleanup_timeout(Duration::from_millis(500)), + ) + .expect("construct executor"); + let spawn = executor + .execute_tool( + Some("expiry-live-child"), + "terminal", + &json!({"argv": ["/bin/sleep", "30"], "background": true}), + ) + .expect("terminal dispatch"); + assert!(spawn.ok, "spawn result={spawn:?}"); + assert_eq!(executor.process_table_len(), 1); + std::thread::sleep(Duration::from_millis(5_500)); + + let expired = read(&executor, "expiry-probe").expect_err("expired lifetime rejects"); + assert!( + matches!(expired.code(), "lifetime_elapsed" | "executor_closed"), + "expired lifetime must close admission: {expired:?}" + ); + assert!(executor.is_closed()); + + let started = Instant::now(); + executor.shutdown(); + assert!( + started.elapsed() < Duration::from_secs(2), + "post-expiry shutdown exceeded the shared deadline: {:?}", + started.elapsed() + ); + assert_eq!( + executor.process_table_len(), + 0, + "shutdown after lifetime expiry must still drain owned processes" + ); +} + +#[test] +fn cancel_call_stops_a_running_process_without_a_late_effect() { + let fixture = Fixture::new("cancel-call"); + let executor = Arc::new(executor(&fixture.root)); + let (sender, receiver) = std::sync::mpsc::channel(); + let worker = { + let executor = Arc::clone(&executor); + std::thread::spawn(move || { + let result = executor.execute_tool( + Some("cancelled-call"), + "terminal", + &json!({ + "argv": ["/bin/sh", "-c", "sleep 2; printf leaked > late.txt"], + "timeout_ms": 30000, + }), + ); + let _ = sender.send(result); + }) + }; + std::thread::sleep(Duration::from_millis(300)); + assert!( + executor.cancel_call("cancelled-call"), + "admitted call must be cancellable" + ); + let result = receiver + .recv_timeout(Duration::from_secs(10)) + .expect("cancelled call returns"); + worker.join().expect("worker"); + let result = result.expect("cancellation returns a canonical result"); + assert!(!result.ok, "cancelled result={result:?}"); + let code = result + .error + .as_ref() + .map(|error| error.code.as_str()) + .unwrap_or(""); + assert!( + code == "cancelled" || code == "deadline_elapsed", + "expected typed cancellation, got {code:?}" + ); + assert_eq!(executor.open_token_count(), 0, "cancelled call must settle"); + std::thread::sleep(Duration::from_millis(2_200)); + assert!(!fixture.root.join("late.txt").exists()); +} + +#[test] +fn process_table_bound_is_configurable_and_cleanup_is_bounded() { + let fixture = Fixture::new("process-table-bound"); + let executor = McpToolExecutor::new( + McpToolExecutorConfig::new(&fixture.root) + .with_max_processes(2) + .with_max_processes_per_owner(2) + .with_process_cleanup_timeout(Duration::from_millis(200)), + ) + .expect("construct executor"); + for index in 0..2 { + let result = executor + .execute_tool( + Some(&format!("bounded-spawn-{index}")), + "terminal", + &json!({"argv": ["/bin/sleep", "30"], "background": true}), + ) + .expect("terminal dispatch"); + assert!(result.ok, "spawn {index} result={result:?}"); + } + assert_eq!(executor.process_table_len(), 2); + let over = executor + .execute_tool( + Some("bounded-spawn-over"), + "terminal", + &json!({"argv": ["/bin/sleep", "30"], "background": true}), + ) + .expect("terminal dispatch"); + assert!(!over.ok, "table cap must reject a third record: {over:?}"); + assert_eq!(executor.process_table_len(), 2); + + let started = Instant::now(); + executor.shutdown(); + assert!( + started.elapsed() < Duration::from_secs(2), + "shutdown exceeded the shared cleanup deadline: {:?}", + started.elapsed() + ); + assert_eq!(executor.process_table_len(), 0); +} + +#[test] +fn shutdown_and_drop_reap_live_children_with_a_barrier() { + for drop_mode in [false, true] { + let fixture = Fixture::new(if drop_mode { + "drop-child" + } else { + "shutdown-child" + }); + let executor = Arc::new(executor(&fixture.root)); + let spawn = executor + .execute_tool( + Some("live-child"), + "terminal", + &json!({ + "argv": ["/bin/sh", "-c", "echo $$ > shell.pid; exec sleep 30"], + "background": true, + }), + ) + .expect("terminal dispatch"); + assert!(spawn.ok, "spawn result={spawn:?}"); + let pid = wait_for_pid(&fixture.root.join("shell.pid")); + let barrier = Arc::new(std::sync::Barrier::new(2)); + let worker_executor = if drop_mode { + executor + } else { + Arc::clone(&executor) + }; + let worker = { + let barrier = Arc::clone(&barrier); + std::thread::spawn(move || { + barrier.wait(); + if drop_mode { + drop(worker_executor); + } else { + worker_executor.shutdown(); + } + }) + }; + barrier.wait(); + worker.join().expect("cleanup worker"); + let deadline = Instant::now() + Duration::from_secs(3); + while Path::new(&format!("/proc/{pid}")).exists() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(20)); + } + assert!( + !Path::new(&format!("/proc/{pid}")).exists(), + "live child {pid} survived {}", + if drop_mode { "drop" } else { "shutdown" } + ); + } +} + +fn wait_for_pid(path: &Path) -> i32 { + let deadline = Instant::now() + Duration::from_secs(5); + while Instant::now() < deadline { + if let Ok(text) = fs::read_to_string(path) + && let Ok(pid) = text.trim().parse::() + { + return pid; + } + std::thread::sleep(Duration::from_millis(20)); + } + panic!("child did not publish its pid at {}", path.display()); +} + +#[test] +fn concurrent_lifecycle_prepare_never_oversubscribes_the_call_limit() { + let workspace = Fixture::new("lifecycle-quota"); + let owner = CapabilityOwner::new("profile", "session", "run").expect("owner"); + let gate = Arc::new(SynchronizingApproval::new(2)); + let durable = Arc::new(CountingDurable::default()); + let lifecycle = Arc::new( + CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry") + .workspace(&workspace.root) + .limits(LifecycleLimits { + max_tool_calls: 1, + max_output_bytes: 4096, + max_summary_bytes: 128, + }) + .deadline_ms(u64::MAX) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(durable.clone() as Arc) + .approval(gate as Arc) + .cancellation(Arc::new(NeverCancelled) as Arc) + .build() + .expect("lifecycle"), + ); + let start = Arc::new(std::sync::Barrier::new(2)); + let mut handles = Vec::new(); + for index in 0..2 { + let lifecycle = Arc::clone(&lifecycle); + let owner = owner.clone(); + let start = Arc::clone(&start); + handles.push(std::thread::spawn(move || { + start.wait(); + lifecycle.prepare( + &owner, + PrepareMetadata { + run_id: "run".to_string(), + call_id: format!("call-{index}"), + tool_name: "fixture_tool".to_string(), + argument_digest: format!("digest-{index}"), + registry_identity: "registry".to_string(), + risk_class: CapabilityRisk::Read, + summary: "fixture".to_string(), + }, + ) + })); + } + let outcomes: Vec<_> = handles + .into_iter() + .map(|handle| handle.join().expect("join prepare")) + .collect(); + let executed = outcomes + .iter() + .filter(|outcome| matches!(outcome, Ok(PrepareOutcome::Execute { .. }))) + .count(); + let limited = outcomes + .iter() + .filter(|outcome| matches!(outcome, Err(LifecycleError::LimitExceeded))) + .count(); + assert_eq!(executed, 1, "outcomes={outcomes:?}"); + assert_eq!(limited, 1, "outcomes={outcomes:?}"); + assert_eq!(durable.started.load(Ordering::SeqCst), 1); +} + +#[test] +fn cancelled_admitted_file_effect_is_not_published() { + let fixture = Fixture::new("file-cancel"); + let cancel = Arc::new(AtomicBool::new(false)); + let owner = CapabilityOwner::new("profile", "session", "run").expect("owner"); + let lifecycle = CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry") + .workspace(&fixture.root) + .limits(LifecycleLimits { + max_tool_calls: 8, + max_output_bytes: 4096, + max_summary_bytes: 128, + }) + .deadline_ms(u64::MAX) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(Arc::new(CountingDurable::default()) as Arc) + .approval(Arc::new(AllowAllApproval) as Arc) + .cancellation(Arc::new(ManualCancel(Arc::clone(&cancel))) as Arc) + .build() + .expect("lifecycle"); + let token = match lifecycle + .prepare( + &owner, + PrepareMetadata { + run_id: "run".to_string(), + call_id: "cancel-file".to_string(), + tool_name: "fixture_tool".to_string(), + argument_digest: "digest".to_string(), + registry_identity: "registry".to_string(), + risk_class: CapabilityRisk::Write, + summary: "fixture".to_string(), + }, + ) + .expect("prepare") + { + PrepareOutcome::Execute { + execution_token, .. + } => execution_token, + other => panic!("expected execute, got {other:?}"), + }; + let filesystem = FilesystemCapability::new( + lifecycle.clone(), + owner, + FilesystemLimits { + max_read_bytes: 64, + max_write_bytes: 64, + max_list_entries: 4, + }, + ) + .expect("filesystem"); + filesystem.inject_before_write({ + let cancel = Arc::clone(&cancel); + Arc::new(move |_path, _bytes| { + cancel.store(true, Ordering::SeqCst); + Ok(()) + }) + }); + let error = filesystem + .write_atomic(&token, "late.txt", "*", b"late\n") + .expect_err("cancellation must stop publication"); + assert_eq!(error.code(), "cancelled"); + assert!(!fixture.root.join("late.txt").exists()); +} + +struct ManualCancel(Arc); + +impl CancellationFlag for ManualCancel { + fn is_cancelled(&self) -> bool { + self.0.load(Ordering::SeqCst) + } +} + +struct AllowAllApproval; + +impl ApprovalGate for AllowAllApproval { + fn authorize(&self, metadata: &PrepareMetadata) -> Result { + Ok(metadata.risk_class) + } +} + +struct SynchronizingApproval { + count: Mutex, + ready: Condvar, + expected: usize, +} + +impl SynchronizingApproval { + fn new(expected: usize) -> Self { + Self { + count: Mutex::new(0), + ready: Condvar::new(), + expected, + } + } +} + +impl ApprovalGate for SynchronizingApproval { + fn authorize(&self, metadata: &PrepareMetadata) -> Result { + Ok(metadata.risk_class) + } + + fn authorize_at( + &self, + metadata: &PrepareMetadata, + _generation: u64, + _now_ms: u64, + ) -> Result { + let mut count = self.count.lock().expect("approval count"); + *count += 1; + self.ready.notify_all(); + let deadline = Instant::now() + Duration::from_millis(150); + while *count < self.expected && Instant::now() < deadline { + let (guard, _) = self + .ready + .wait_timeout(count, Duration::from_millis(20)) + .expect("approval wait"); + count = guard; + } + Ok(metadata.risk_class) + } +} + +#[derive(Default)] +struct CountingDurable { + started: std::sync::atomic::AtomicUsize, +} + +impl DurableToolLifecycle for CountingDurable { + fn assert_active_run(&self, _run_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } + + fn prepare_parent( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result<(), LifecycleError> { + Ok(()) + } + + fn replay_result( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result, LifecycleError> { + Ok(None) + } + + fn commit_started(&self, _record: &DurableStarted) -> Result<(), LifecycleError> { + self.started.fetch_add(1, Ordering::SeqCst); + Ok(()) + } + + fn commit_result( + &self, + _call_id: &str, + result: &serde_json::Value, + ) -> Result { + Ok(result.clone()) + } + + fn interrupt(&self, _call_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } +} diff --git a/tests/mcp_provider_isolation_tests.rs b/tests/mcp_provider_isolation_tests.rs new file mode 100644 index 00000000..83550443 --- /dev/null +++ b/tests/mcp_provider_isolation_tests.rs @@ -0,0 +1,165 @@ +//! Provider-isolation proof for the provider-free MCP tool core. +//! +//! The MCP executor and the bundled registry/dispatch runners must never +//! instantiate the default RSS provider adapter, load provider credentials, or +//! invoke `agent::provider_call` through a provider-enabled runner. These are +//! static source proofs plus a runtime fail-closed proof for the narrow +//! provider-disabled runner path. + +use std::fs; +use std::path::{Path, PathBuf}; + +use rustscript_agent::AgentRunner; +use rustscript_agent::runtime::rss_runner::ProviderMode; +use rustscript_agent::{AgentConfig, mcp::executor::McpToolExecutorConfig}; +use rustscript_vm::Value as VmValue; + +fn manifest(relative: &str) -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join(relative) +} + +fn source(relative: &str) -> String { + fs::read_to_string(manifest(relative)) + .unwrap_or_else(|error| panic!("read {relative}: {error}")) +} + +fn function_body(source: &str, signature: &str) -> String { + let start = source + .find(signature) + .unwrap_or_else(|| panic!("missing function signature: {signature}")); + let rest = &source[start..]; + let end = rest + .find("\n}\n") + .map(|offset| offset + 3) + .unwrap_or(rest.len()); + rest[..end].to_string() +} + +fn code_lines(source: &str) -> String { + source + .lines() + .filter(|line| { + let trimmed = line.trim_start(); + !trimmed.starts_with("//") + }) + .collect::>() + .join("\n") +} + +#[test] +fn executor_source_uses_only_the_provider_disabled_dispatch_runner() { + let executor = source("src/mcp/executor.rs"); + let code = code_lines(&executor); + assert!( + code.contains("from_bundled_provider_disabled"), + "executor must construct the provider-disabled dispatch runner" + ); + for forbidden in [ + "RssAdapterProvider", + "new_default_agent_provider_host", + "default_agent_provider_host", + "AgentService", + "rss/agent/main.rss", + ] { + assert!( + !code.contains(forbidden), + "executor source must not reference {forbidden}" + ); + } +} + +#[test] +fn bundled_registry_loader_uses_the_provider_disabled_runner() { + let runner = source("src/runtime/rss_runner.rs"); + let registry = function_body(&runner, "fn load_bundled_tool_registry()"); + assert!( + registry.contains("from_bundled_provider_disabled"), + "registry loader must not use the provider-enabled default runner: {registry}" + ); + assert!( + !registry.contains("from_bundled(\"rss/tools/registry.rss\""), + "registry loader still uses the legacy provider-enabled constructor" + ); +} + +#[test] +fn bundled_tool_programs_do_not_import_provider_dispatch() { + for resource in [ + "rss/tools/registry.rss", + "rss/tools/dispatch_entry.rss", + "rss/tools/dispatch.rss", + ] { + let text = source(resource); + assert!( + !text.contains("provider_call"), + "{resource} must not import or call agent::provider_call" + ); + } +} + +#[test] +fn provider_disabled_runner_fails_closed_without_provider_or_credentials() { + let source = r#" + use agent; + pub fn run(context: map) -> map { + let request: string = context["request"]; + agent::provider_call(request) + } + "#; + let runner = AgentRunner::from_source_provider_disabled(source, AgentConfig::default()) + .expect("compile provider-disabled probe"); + assert_eq!(runner.provider_mode(), ProviderMode::Disabled); + let result = runner + .run_with_context(VmValue::map(vec![( + VmValue::string("request"), + VmValue::string("{}"), + )])) + .expect("provider-disabled run has a typed envelope, not a setup failure"); + assert_eq!(map_get(&result, "ok"), Some(&VmValue::Bool(false))); + let error = map_get(&result, "error").expect("error envelope"); + let VmValue::String(encoded) = error else { + panic!("expected encoded provider error, got {error:?}"); + }; + let error: serde_json::Value = + serde_json::from_str(encoded.as_str()).expect("provider error JSON"); + assert_eq!(error["code"], "provider_disabled"); +} + +fn map_get<'a>(value: &'a VmValue, key: &str) -> Option<&'a VmValue> { + let VmValue::Map(fields) = value else { + return None; + }; + fields + .iter() + .find(|(field, _)| matches!(field, VmValue::String(name) if name.as_str() == key)) + .map(|(_, value)| value) +} + +#[test] +fn legacy_runner_construction_remains_provider_enabled() { + let runner = AgentRunner::from_source( + "pub fn run(context: map) -> bool { true }", + AgentConfig::default(), + ) + .expect("compile legacy runner"); + assert_eq!(runner.provider_mode(), ProviderMode::Enabled); +} + +#[test] +fn executor_reports_a_provider_disabled_runner() { + let fixture = std::env::temp_dir().join(format!( + "mcp-provider-isolation-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|duration| duration.as_nanos()) + .unwrap_or(0) + )); + fs::create_dir_all(&fixture).expect("create workspace"); + let executor = + rustscript_agent::mcp::executor::McpToolExecutor::new(McpToolExecutorConfig::new(&fixture)) + .expect("construct executor"); + assert_eq!(executor.provider_mode(), ProviderMode::Disabled); + drop(executor); + let _ = fs::remove_dir_all(&fixture); +} diff --git a/tests/mcp_sol_lifecycle_tests.rs b/tests/mcp_sol_lifecycle_tests.rs new file mode 100644 index 00000000..b0b097d5 --- /dev/null +++ b/tests/mcp_sol_lifecycle_tests.rs @@ -0,0 +1,4896 @@ +//! Third-review lifecycle blockers: canonical receipts across the publication +//! boundary, ownership visibility during cleanup, one teardown cutoff, and the +//! minimum output cap contract. +//! +//! Every case drives a real production path: the MCP executor's own +//! cancel/shutdown/VM flow, the confined filesystem/process capabilities, or +//! the bounded process teardown. None of them call `commit`/`settle` directly +//! to simulate the outcome under test. + +use std::fs; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::time::{Duration, Instant}; + +use rustscript_agent::ToolResult; +use rustscript_agent::capabilities::{ + AllowAllApproval, ArtifactCapability, ArtifactLimits, CallCancellationSource, + CallCancellationState, CallTerminalDecision, CallTerminalRequest, CancellationFlag, + CapabilityLifecycle, CapabilityOwner, CapabilityRisk, DurableStarted, DurableToolLifecycle, + FilesystemCapability, FilesystemLimits, LifecycleClock, LifecycleError, LifecycleLimits, + NativeArtifactIdentity, NativeEffectKind, NativeEffectRecord, NativeEffectStatus, + NeverCancelled, PrepareMetadata, PrepareOutcome, ProcessCapability, ProcessCleanupProof, + ProcessLimits, ProcessTableLimits, SystemClock, TokenIssuer, UuidIssuer, +}; +use rustscript_agent::mcp::executor::{McpToolExecutor, McpToolExecutorConfig}; +use serde_json::{Value, json}; +use std::sync::atomic::AtomicBool; +use std::sync::{Condvar, Mutex}; + +static NEXT_FIXTURE: AtomicU64 = AtomicU64::new(0); + +struct Fixture { + parent: PathBuf, + root: PathBuf, +} + +impl Fixture { + fn new(label: &str) -> Self { + let sequence = NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed); + let parent = std::env::temp_dir().join(format!( + "mcp-sol-lifecycle-{label}-{}-{sequence}", + std::process::id() + )); + let root = parent.join("workspace"); + fs::create_dir_all(&root).expect("create fixture workspace"); + Self { parent, root } + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.parent); + } +} + +/// Waits until `condition` holds, failing with `label` after ten seconds. +fn wait_until(label: &str, mut condition: impl FnMut() -> bool) { + let deadline = Instant::now() + Duration::from_secs(10); + while !condition() { + assert!(Instant::now() < deadline, "timed out waiting for {label}"); + std::thread::sleep(Duration::from_millis(10)); + } +} + +/// A blocking gate whose "started" signal fires at the exact seam under test. +#[derive(Default)] +struct SeamGate { + started: (Mutex, Condvar), + release: (Mutex, Condvar), +} + +impl SeamGate { + fn block(&self) { + *self + .started + .0 + .lock() + .unwrap_or_else(|error| error.into_inner()) = true; + self.started.1.notify_all(); + let mut released = self + .release + .0 + .lock() + .unwrap_or_else(|error| error.into_inner()); + while !*released { + released = self + .release + .1 + .wait(released) + .unwrap_or_else(|error| error.into_inner()); + } + } + + fn wait_started(&self) { + let mut started = self + .started + .0 + .lock() + .unwrap_or_else(|error| error.into_inner()); + let deadline = Instant::now() + Duration::from_secs(10); + while !*started { + let remaining = deadline.saturating_duration_since(Instant::now()); + assert!(!remaining.is_zero(), "seam gate was never entered"); + let (guard, _) = self + .started + .1 + .wait_timeout(started, remaining) + .unwrap_or_else(|error| error.into_inner()); + started = guard; + } + } + + fn release(&self) { + *self + .release + .0 + .lock() + .unwrap_or_else(|error| error.into_inner()) = true; + self.release.1.notify_all(); + } +} + +struct ManualCall(Arc); + +impl CallCancellationSource for ManualCall { + fn call_state(&self, _call_id: &str) -> CallCancellationState { + if self.0.load(Ordering::SeqCst) { + CallCancellationState::Cancelled + } else { + CallCancellationState::Active + } + } +} + +/// Run-wide cancellation flag shared with the lifecycle's effect boundary. +struct FlagCancelled(Arc); + +impl CancellationFlag for FlagCancelled { + fn is_cancelled(&self) -> bool { + self.0.load(Ordering::SeqCst) + } +} + +#[derive(Default)] +struct NoopDurable; + +impl DurableToolLifecycle for NoopDurable { + fn assert_active_run(&self, _run_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } + + fn prepare_parent( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result<(), LifecycleError> { + Ok(()) + } + + fn replay_result( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result, LifecycleError> { + Ok(None) + } + + fn commit_started(&self, _record: &DurableStarted) -> Result<(), LifecycleError> { + Ok(()) + } + + fn commit_result(&self, _call_id: &str, result: &Value) -> Result { + Ok(result.clone()) + } + + fn interrupt(&self, _call_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } +} + +fn lifecycle_with_call_cancel( + root: &std::path::Path, + cancel: Arc, +) -> (CapabilityLifecycle, CapabilityOwner) { + lifecycle_with_call_cancel_and_policy( + root, + cancel, + rustscript_agent::capabilities::PublishedTokenPolicy::Abort, + ) +} + +fn lifecycle_with_call_cancel_and_policy( + root: &std::path::Path, + cancel: Arc, + policy: rustscript_agent::capabilities::PublishedTokenPolicy, +) -> (CapabilityLifecycle, CapabilityOwner) { + let owner = CapabilityOwner::new("sol-lifecycle", "session", "run").expect("owner"); + let lifecycle = CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry") + .workspace(root) + .limits(LifecycleLimits { + max_tool_calls: 32, + max_output_bytes: 8192, + max_summary_bytes: 256, + }) + .deadline_ms(SystemClock.now_ms().saturating_add(60_000)) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(Arc::new(NoopDurable) as Arc) + .approval( + Arc::new(AllowAllApproval) as Arc + ) + .cancellation(Arc::new(NeverCancelled) as Arc) + .call_cancellation(Arc::new(ManualCall(cancel)) as Arc) + .published_token_policy(policy) + .build() + .expect("lifecycle"); + (lifecycle, owner) +} + +fn prepare_token( + lifecycle: &CapabilityLifecycle, + owner: &CapabilityOwner, + call_id: &str, + risk: CapabilityRisk, +) -> String { + match lifecycle + .prepare( + owner, + PrepareMetadata { + run_id: owner.run().to_string(), + call_id: call_id.to_string(), + tool_name: "fixture_tool".to_string(), + argument_digest: "digest".to_string(), + registry_identity: "registry".to_string(), + risk_class: risk, + summary: "fixture".to_string(), + }, + ) + .expect("prepare") + { + PrepareOutcome::Execute { + execution_token, .. + } => execution_token, + other => panic!("expected execute, got {other:?}"), + } +} + +fn success_receipt() -> Value { + json!({"ok": true, "content": "receipt", "data": {}}) +} + +fn typed_success_receipt() -> Value { + json!({ + "ok": true, + "content": "receipt", + "data": {}, + "error": null, + "truncated": false, + "artifacts": [] + }) +} + +#[derive(Default)] +struct RecordingDurable { + results: Mutex>, + commits: AtomicUsize, + starts: AtomicUsize, +} + +impl RecordingDurable { + fn result(&self, call_id: &str) -> Option { + self.results + .lock() + .unwrap_or_else(|error| error.into_inner()) + .iter() + .rev() + .find(|(call, _)| call == call_id) + .map(|(_, result)| result.clone()) + } + + fn commit_count(&self) -> usize { + self.commits.load(Ordering::SeqCst) + } + + fn start_count(&self) -> usize { + self.starts.load(Ordering::SeqCst) + } +} + +impl DurableToolLifecycle for RecordingDurable { + fn assert_active_run(&self, _run_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } + + fn prepare_parent( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result<(), LifecycleError> { + Ok(()) + } + + fn replay_result( + &self, + _run_id: &str, + call_id: &str, + _tool_name: &str, + ) -> Result, LifecycleError> { + Ok(self.result(call_id)) + } + + fn commit_started(&self, _record: &DurableStarted) -> Result<(), LifecycleError> { + self.starts.fetch_add(1, Ordering::SeqCst); + Ok(()) + } + + fn commit_result(&self, call_id: &str, result: &Value) -> Result { + self.commits.fetch_add(1, Ordering::SeqCst); + self.results + .lock() + .unwrap_or_else(|error| error.into_inner()) + .push((call_id.to_string(), result.clone())); + Ok(result.clone()) + } + + fn interrupt(&self, _call_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } +} + +/// Durable whose terminal writes can be parked after they are entered, so a +/// concurrent settlement observes the exact pending-write window. +#[derive(Default)] +struct StallingDurable { + results: Mutex>, + commits: AtomicUsize, + interrupts: AtomicUsize, + commit_gate: Mutex>>, + interrupt_gate: Mutex>>, + /// Fail the interrupt that parked on the gate, so a concurrent settler + /// observes the pending window and the owner then observes the reopen. + fail_interrupt_after_gate: AtomicBool, +} + +impl StallingDurable { + fn new() -> Self { + Self::default() + } + + fn stall_commit(&self, gate: Arc) { + *self.commit_gate.lock().unwrap_or_else(|e| e.into_inner()) = Some(gate); + } + + fn stall_interrupt(&self, gate: Arc) { + *self + .interrupt_gate + .lock() + .unwrap_or_else(|e| e.into_inner()) = Some(gate); + } + + fn fail_interrupt_after_gate(&self) { + self.fail_interrupt_after_gate.store(true, Ordering::SeqCst); + } + + fn result(&self, call_id: &str) -> Option { + self.results + .lock() + .unwrap_or_else(|error| error.into_inner()) + .iter() + .rev() + .find(|(call, _)| call == call_id) + .map(|(_, result)| result.clone()) + } + + fn commit_count(&self) -> usize { + self.commits.load(Ordering::SeqCst) + } + + fn interrupt_count(&self) -> usize { + self.interrupts.load(Ordering::SeqCst) + } +} + +impl DurableToolLifecycle for StallingDurable { + fn assert_active_run(&self, _run_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } + + fn prepare_parent( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result<(), LifecycleError> { + Ok(()) + } + + fn replay_result( + &self, + _run_id: &str, + call_id: &str, + _tool_name: &str, + ) -> Result, LifecycleError> { + Ok(self.result(call_id)) + } + + fn commit_started(&self, _record: &DurableStarted) -> Result<(), LifecycleError> { + Ok(()) + } + + fn commit_result(&self, call_id: &str, result: &Value) -> Result { + self.commits.fetch_add(1, Ordering::SeqCst); + let gate = self + .commit_gate + .lock() + .unwrap_or_else(|error| error.into_inner()) + .clone(); + if let Some(gate) = gate { + gate.block(); + } + self.results + .lock() + .unwrap_or_else(|error| error.into_inner()) + .push((call_id.to_string(), result.clone())); + Ok(result.clone()) + } + + fn interrupt(&self, _call_id: &str) -> Result<(), LifecycleError> { + self.interrupts.fetch_add(1, Ordering::SeqCst); + let gate = self + .interrupt_gate + .lock() + .unwrap_or_else(|error| error.into_inner()) + .clone(); + if let Some(gate) = gate { + gate.block(); + } + if self.fail_interrupt_after_gate.swap(false, Ordering::SeqCst) { + return Err(LifecycleError::ResultCommitFailed( + "injected interrupt failure after the pending window".to_string(), + )); + } + Ok(()) + } +} + +fn lifecycle_with_durable( + root: &std::path::Path, + durable: Arc, + policy: rustscript_agent::capabilities::PublishedTokenPolicy, +) -> (CapabilityLifecycle, CapabilityOwner) { + let owner = CapabilityOwner::new("sol-lifecycle", "session", "run").expect("owner"); + let lifecycle = CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry") + .workspace(root) + .limits(LifecycleLimits { + max_tool_calls: 32, + max_output_bytes: 8192, + max_summary_bytes: 256, + }) + .deadline_ms(SystemClock.now_ms().saturating_add(60_000)) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(durable) + .approval( + Arc::new(AllowAllApproval) as Arc + ) + .cancellation(Arc::new(NeverCancelled) as Arc) + .published_token_policy(policy) + .build() + .expect("lifecycle"); + (lifecycle, owner) +} + +#[test] +fn later_artifact_only_appends_to_the_primary_write_record() { + let fixture = Fixture::new("p1-append"); + let owner = CapabilityOwner::new("sol-lifecycle", "session", "append").expect("owner"); + let lifecycle = CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry") + .workspace(&fixture.root) + .limits(LifecycleLimits { + max_tool_calls: 8, + max_output_bytes: 8192, + max_summary_bytes: 256, + }) + .deadline_ms(SystemClock.now_ms().saturating_add(60_000)) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(Arc::new(NoopDurable) as Arc) + .approval( + Arc::new(AllowAllApproval) as Arc + ) + .cancellation(Arc::new(NeverCancelled) as Arc) + .build() + .expect("lifecycle"); + let filesystem = FilesystemCapability::new( + lifecycle.clone(), + owner.clone(), + FilesystemLimits::default(), + ) + .expect("filesystem"); + let artifacts = + ArtifactCapability::new(lifecycle.clone(), owner.clone(), ArtifactLimits::default()) + .expect("artifacts"); + let token = prepare_token(&lifecycle, &owner, "append-call", CapabilityRisk::Write); + filesystem + .write_atomic(&token, "out.txt", "*", b"written\n") + .expect("published write"); + let stored = artifacts + .put(&token, b"later artifact\n", &json!({})) + .expect("later artifact store"); + let outcome = lifecycle + .call_native_outcome("append-call") + .expect("native outcome"); + assert_eq!(outcome.record.effect, NativeEffectKind::AtomicWrite); + assert_eq!(outcome.record.status, NativeEffectStatus::Ok); + assert_eq!( + outcome.record.write.as_ref().map(|write| write.len), + Some(b"written\n".len()), + "the primary write identity must survive: {outcome:?}" + ); + assert!( + outcome + .artifacts + .iter() + .any(|artifact| artifact.id == stored.id), + "the later artifact must append to the same record: {outcome:?}" + ); + let result = lifecycle + .native_effect_result("append-call") + .expect("typed result"); + assert!(result.ok); + assert_eq!(result.data["publication"], json!("published")); + assert_eq!(result.artifacts, vec![stored.id]); +} + +#[test] +fn artifact_store_keeps_the_published_object_when_the_token_closes_before_registration() { + let fixture = Fixture::new("r6-register-window"); + let owner = CapabilityOwner::new("sol-lifecycle", "session", "window").expect("owner"); + let durable = Arc::new(RecordingDurable::default()); + let lifecycle = CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry") + .workspace(&fixture.root) + .limits(LifecycleLimits { + max_tool_calls: 8, + max_output_bytes: 8192, + max_summary_bytes: 256, + }) + .deadline_ms(SystemClock.now_ms().saturating_add(60_000)) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(durable.clone() as Arc) + .approval( + Arc::new(AllowAllApproval) as Arc + ) + .cancellation(Arc::new(NeverCancelled) as Arc) + .build() + .expect("lifecycle"); + let artifacts = + ArtifactCapability::new(lifecycle.clone(), owner.clone(), ArtifactLimits::default()) + .expect("artifacts"); + let token = prepare_token(&lifecycle, &owner, "window-call", CapabilityRisk::Read); + let gate = Arc::new(SeamGate::default()); + artifacts.inject_after_store_for_test({ + let gate = Arc::clone(&gate); + Arc::new(move || gate.block()) + }); + let worker = { + let artifacts = artifacts.clone(); + let token = token.clone(); + std::thread::spawn(move || artifacts.put_result(&token, b"published object\n", &json!({}))) + }; + gate.wait_started(); + // The object insertion already crossed the fence. Closing the token in + // this exact window must settle the call, never retract the stored object. + lifecycle + .settle_call_with_receipt("window-call", Some(&success_receipt())) + .expect("settle in the registration window"); + gate.release(); + let stored = worker.join().expect("worker").expect("stored artifact"); + assert_eq!( + artifacts.stored_ids(), + vec![stored.id.clone()], + "the published artifact must survive the token-registration error path" + ); + assert_eq!(artifacts.stored_len(), 1); +} + +#[test] +fn managed_read_file_overflow_registration_survives_a_stop_in_the_first_publishing_permit() { + let fixture = Fixture::new("r8-overflow-registration-stop"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle_with_call_cancel(&fixture.root, cancel); + let artifacts = + ArtifactCapability::new(lifecycle.clone(), owner.clone(), ArtifactLimits::default()) + .expect("artifacts"); + // A read_file overflow publishes its oversized envelope through the Read + // result-artifact primitive. + let token = prepare_token(&lifecycle, &owner, "r8-overflow", CapabilityRisk::Read); + let gate = Arc::new(SeamGate::default()); + artifacts.inject_before_publish({ + let gate = Arc::clone(&gate); + Arc::new(move || gate.block()) + }); + let (tx, rx) = std::sync::mpsc::channel(); + let worker = { + let artifacts = artifacts.clone(); + let token = token.clone(); + std::thread::spawn(move || { + let payload = vec![b'x'; 4096]; + let _ = tx.send(artifacts.put_result(&token, &payload, &json!({}))); + }) + }; + gate.wait_started(); + // The first Publishing permit is active and has not registered its + // artifact guard yet. The managed stop interrupts this token exactly as a + // base abort would. + drop(lifecycle.lease(&token).expect("stop lease")); + let started = Instant::now(); + gate.release(); + let result = rx + .recv_timeout(Duration::from_secs(5)) + .expect("managed overflow registration must finish instead of deadlocking"); + let elapsed = started.elapsed(); + let error = result.expect_err("an interrupted publication must not store an artifact"); + assert_eq!(error.code(), "interrupted", "{error:?}"); + assert!( + elapsed < Duration::from_secs(2), + "managed overflow registration exceeded its bounded completion: {elapsed:?}" + ); + assert_eq!(lifecycle.interrupted_token_count(), 1); + assert_eq!(artifacts.stored_len(), 0); + worker.join().expect("worker"); +} + +#[test] +fn recovery_refuses_a_publishing_worker_and_settles_it_after_publication() { + let fixture = Fixture::new("r6-publishing"); + let cancel = Arc::new(AtomicBool::new(false)); + let owner = CapabilityOwner::new("sol-lifecycle", "session", "publishing").expect("owner"); + let durable = Arc::new(RecordingDurable::default()); + let lifecycle = CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry") + .workspace(&fixture.root) + .limits(LifecycleLimits { + max_tool_calls: 8, + max_output_bytes: 8192, + max_summary_bytes: 256, + }) + .deadline_ms(SystemClock.now_ms().saturating_add(60_000)) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(durable.clone() as Arc) + .approval( + Arc::new(AllowAllApproval) as Arc + ) + .cancellation(Arc::new(NeverCancelled) as Arc) + .call_cancellation(Arc::new(ManualCall(cancel)) as Arc) + .published_token_policy( + rustscript_agent::capabilities::PublishedTokenPolicy::RetainForSettlement, + ) + .build() + .expect("lifecycle"); + let filesystem = FilesystemCapability::new( + lifecycle.clone(), + owner.clone(), + FilesystemLimits::default(), + ) + .expect("filesystem"); + let token = prepare_token(&lifecycle, &owner, "publishing-call", CapabilityRisk::Write); + let gate = Arc::new(SeamGate::default()); + filesystem.inject_before_publish({ + let gate = Arc::clone(&gate); + Arc::new(move || gate.block()) + }); + let worker = { + let filesystem = filesystem.clone(); + let token = token.clone(); + std::thread::spawn(move || { + filesystem.write_atomic(&token, "publishing.txt", "*", b"published\n") + }) + }; + gate.wait_started(); + // The effect worker is inside the publication fence. Recovery must not + // guess an outcome or interrupt it; the call is left for its own thread. + let recovered = lifecycle + .recover_open_tokens() + .expect("recovery must refuse a live publishing worker"); + assert!( + recovered.is_empty(), + "a publishing call must not be claimed while its worker is registered: {recovered:?}" + ); + assert_eq!( + lifecycle.open_token_count(), + 1, + "the publishing token must stay open for its worker" + ); + assert!( + durable.result("publishing-call").is_none(), + "recovery must not write a synthetic outcome for a live publisher" + ); + gate.release(); + let write = worker + .join() + .expect("worker") + .expect("the rename still completes"); + assert_eq!(write.len, b"published\n".len()); + assert_eq!( + fs::read_to_string(fixture.root.join("publishing.txt")).expect("published file"), + "published\n" + ); + + // Once the worker retired, the MCP retention mode settles the exact + // published effect instead of inventing an indeterminate one. + let recovered = lifecycle + .recover_open_tokens() + .expect("recovery must settle the retired publisher"); + assert_eq!(recovered, vec!["publishing-call".to_string()]); + assert_eq!(lifecycle.open_token_count(), 0); + let committed = durable.result("publishing-call").expect("durable outcome"); + assert_eq!( + committed["ok"], + json!(true), + "the retired publisher's real success must settle: {committed}" + ); + assert_eq!( + committed["data"]["effect"], + json!("atomic_write"), + "the recovered receipt must carry the real native effect: {committed}" + ); +} + +#[test] +fn recovery_settles_a_published_token_within_the_configured_byte_cap() { + for cap in [256, 512] { + assert_published_artifact_recovery_fits(cap); + } +} + +fn assert_published_artifact_recovery_fits(cap: usize) { + let fixture = Fixture::new("published-cap"); + let owner = CapabilityOwner::new("sol-lifecycle", "session", "cap").expect("owner"); + let durable = Arc::new(RecordingDurable::default()); + let lifecycle = CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry") + .workspace(&fixture.root) + .limits(LifecycleLimits { + max_tool_calls: 8, + max_output_bytes: cap, + max_summary_bytes: 128, + }) + .deadline_ms(SystemClock.now_ms().saturating_add(60_000)) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(durable.clone() as Arc) + .approval( + Arc::new(AllowAllApproval) as Arc + ) + .cancellation(Arc::new(NeverCancelled) as Arc) + .published_token_policy( + rustscript_agent::capabilities::PublishedTokenPolicy::RetainForSettlement, + ) + .build() + .expect("lifecycle"); + let artifacts = + ArtifactCapability::new(lifecycle.clone(), owner.clone(), ArtifactLimits::default()) + .expect("artifacts"); + let token = prepare_token(&lifecycle, &owner, "cap-call", CapabilityRisk::Read); + let stored = artifacts + .put_result(&token, b"a published result artifact\n", &json!({})) + .expect("published artifact"); + let recovered = lifecycle + .recover_open_tokens() + .expect("recovery must settle within the configured cap"); + assert_eq!(recovered, vec!["cap-call".to_string()]); + assert_eq!(lifecycle.open_token_count(), 0); + let committed = durable.result("cap-call").expect("durable outcome"); + let encoded = serde_json::to_vec(&committed).expect("serialize recovered receipt"); + assert!( + encoded.len() <= cap, + "the recovered receipt must fit the configured cap ({} bytes): {committed}", + encoded.len() + ); + assert_eq!( + committed["ok"], + json!(true), + "the published artifact outcome must settle as its real success: {committed}" + ); + assert_eq!(committed["artifacts"], json!([stored.id])); + assert_eq!(committed["data"]["effect"], "artifact_store"); + assert_eq!(committed["data"]["artifact"], stored.id); +} + +#[test] +fn artifact_only_ok_cannot_mask_a_failed_spawn_terminal() { + let fixture = Fixture::new("p1-mask"); + let owner = CapabilityOwner::new("sol-lifecycle", "session", "mask").expect("owner"); + let durable = Arc::new(RecordingDurable::default()); + let lifecycle = CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry") + .workspace(&fixture.root) + .limits(LifecycleLimits { + max_tool_calls: 8, + max_output_bytes: 8192, + max_summary_bytes: 256, + }) + .deadline_ms(SystemClock.now_ms().saturating_add(60_000)) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(durable.clone() as Arc) + .approval( + Arc::new(AllowAllApproval) as Arc + ) + .cancellation(Arc::new(NeverCancelled) as Arc) + .build() + .expect("lifecycle"); + let processes = Arc::new( + ProcessCapability::new_with_table_limits( + lifecycle.clone(), + owner.clone(), + ProcessLimits::default(), + ProcessTableLimits::new(1, 1, Duration::from_millis(300)).expect("table limits"), + ) + .expect("processes"), + ); + let artifacts = + ArtifactCapability::new(lifecycle.clone(), owner.clone(), ArtifactLimits::default()) + .expect("artifacts"); + let token = prepare_token(&lifecycle, &owner, "mask-call", CapabilityRisk::Execute); + processes.withhold_cleanup_proof_for_test(); + let error = processes + .spawn_with_post_spawn_failure_for_test( + &token, + &["/bin/sleep".to_string(), "30".to_string()], + "", + &[], + ProcessLimits { + timeout_ms: 5_000, + close_after_initial: false, + ..ProcessLimits::default() + }, + ) + .expect_err("the real setup failure must surface"); + assert_eq!(error.code(), "process_failed", "{error:?}"); + assert_eq!(processes.table_len(), 1, "the child stays owned"); + let stored = artifacts + .put_result(&token, b"overflow after failed terminal\n", &json!({})) + .expect("a later artifact store still crosses the same fence"); + let outcome = lifecycle + .call_native_outcome("mask-call") + .expect("the call has a typed native outcome"); + assert_eq!( + outcome.record.effect, + NativeEffectKind::ProcessSpawn, + "the failed spawn terminal must stay authoritative" + ); + assert_eq!(outcome.record.status, NativeEffectStatus::Failed); + assert_eq!( + outcome + .record + .error + .as_ref() + .map(|error| error.code.as_str()), + Some("process_failed") + ); + assert!( + outcome + .artifacts + .iter() + .any(|artifact| artifact.id == stored.id), + "the later artifact must still append to the same outcome" + ); + + // Finding 1 supersedes settlement-side re-derivation: settlement commits + // the caller's snapshot verbatim, and the executor is the single decision + // point. This test now computes the snapshot exactly as the executor does + // (the typed ledger outcome) and proves that an artifact-only OK record + // still cannot become the committed result. + let ledger = lifecycle + .native_effect_result("mask-call") + .expect("the typed ledger snapshot"); + let snapshot = serde_json::to_value(&ledger).expect("serialize ledger snapshot"); + let settlement = lifecycle + .settle_call_with_receipt("mask-call", Some(&snapshot)) + .expect("settle"); + assert_eq!(settlement.committed, 1); + let committed = durable.result("mask-call").expect("durable result"); + assert_eq!( + committed, snapshot, + "settlement must commit the executor's failed snapshot verbatim: {committed}" + ); + assert_eq!( + committed["ok"], + json!(false), + "an artifact-only OK record must not become the committed result: {committed}" + ); + assert_eq!(committed["error"]["code"], json!("process_failed")); + assert_eq!( + committed["artifacts"].as_array().map(Vec::len), + Some(1), + "the stored artifact identity must not disappear: {committed}" + ); + + processes.allow_cleanup_proof_for_test(); + assert_eq!( + processes.shutdown_all_within(Instant::now() + Duration::from_secs(2)), + ProcessCleanupProof::Clean + ); +} + +#[test] +fn executor_cancellation_after_process_publication_commits_exactly_one_receipt() { + let fixture = Fixture::new("p1-cancel"); + let executor = Arc::new( + McpToolExecutor::new(McpToolExecutorConfig::new(&fixture.root)).expect("executor"), + ); + let worker = { + let executor = Arc::clone(&executor); + std::thread::spawn(move || { + executor.execute_tool( + Some("sol-p1-cancel"), + "terminal", + &json!({ + "argv": ["/bin/sh", "-c", "printf ready; exec sleep 30"], + "timeout_ms": 20_000 + }), + ) + }) + }; + + // The child exists in the owned table only after the OS-spawn publication + // boundary was crossed and the record became visible. + wait_until("published process record", || { + executor.process_table_len() == 1 + }); + assert!( + executor.cancel_call("sol-p1-cancel"), + "the active call must accept cancellation" + ); + + let result = worker.join().expect("worker thread").expect("receipt"); + assert!(!result.ok, "a cancelled call must fail: {result:?}"); + let code = result + .error + .as_ref() + .map(|error| error.code.as_str()) + .unwrap_or(""); + assert!( + code == "cancelled" || code == "deadline_elapsed", + "expected typed cancellation, got {code:?}: {result:?}" + ); + assert_eq!( + result.data["effect"], + json!("process_spawn"), + "a published spawn must settle with its complete typed effect: {result:?}" + ); + assert!( + result.data["pid"].as_u64().is_some_and(|pid| pid > 0), + "the settled receipt must carry the real OS pid: {result:?}" + ); + assert!( + result.data["process_state"].is_string(), + "the settled receipt must carry the observed process state: {result:?}" + ); + assert_eq!( + executor.open_token_count(), + 0, + "the published call must be settled, not left open" + ); + assert_eq!( + executor.committed_token_count(), + 1, + "an effect that crossed the publication boundary must commit exactly one canonical receipt" + ); + assert_eq!( + executor.interrupted_token_count(), + 0, + "cancellation must not interrupt an already published effect" + ); + executor.shutdown(); +} + +#[test] +fn committed_write_result_survives_a_vm_stop_after_tool_commit() { + let fixture = Fixture::new("p1-committed-write"); + let executor = Arc::new( + McpToolExecutor::new( + McpToolExecutorConfig::new(&fixture.root).with_epoch_check_interval_for_test(1), + ) + .expect("executor"), + ); + let gate = Arc::new(SeamGate::default()); + executor.set_commit_observer_for_test({ + let gate = Arc::clone(&gate); + Arc::new(move |_token| gate.block()) + }); + let worker = { + let executor = Arc::clone(&executor); + std::thread::spawn(move || { + executor.execute_tool( + Some("p1-committed-write"), + "write_file", + &json!({"path": "committed.txt", "content": "durable\n"}), + ) + }) + }; + + // The guest reached `tool_commit`; the durable payload already exists, but + // the VM has not returned yet. + gate.wait_started(); + assert!( + executor.cancel_call("p1-committed-write"), + "the active call must accept cancellation" + ); + gate.release(); + + let result = worker.join().expect("worker thread").expect("receipt"); + assert!( + result.ok, + "a committed write must return its committed payload, not a synthetic cancellation: {result:?}" + ); + let committed = executor + .committed_receipt_for_test("p1-committed-write") + .expect("durable committed payload"); + assert_eq!( + serde_json::to_value(&result).expect("serialize returned result"), + serde_json::to_value(&committed).expect("serialize committed receipt"), + "the returned result must equal the durable committed receipt" + ); + assert_eq!( + fs::read_to_string(fixture.root.join("committed.txt")).expect("committed file"), + "durable\n" + ); + assert_eq!(executor.open_token_count(), 0); + assert_eq!(executor.committed_token_count(), 1); + executor.shutdown(); +} + +#[test] +fn published_write_receipt_survives_a_vm_stop_before_tool_commit() { + let fixture = Fixture::new("p1-published-write"); + let executor = Arc::new( + McpToolExecutor::new( + McpToolExecutorConfig::new(&fixture.root).with_epoch_check_interval_for_test(1), + ) + .expect("executor"), + ); + let gate = Arc::new(SeamGate::default()); + executor.filesystem_for_test().inject_before_publish({ + let gate = Arc::clone(&gate); + Arc::new(move || gate.block()) + }); + let worker = { + let executor = Arc::clone(&executor); + std::thread::spawn(move || { + executor.execute_tool( + Some("p1-published-write"), + "write_file", + &json!({"path": "published.txt", "content": "published\n"}), + ) + }) + }; + + gate.wait_started(); + assert!(executor.cancel_call("p1-published-write")); + gate.release(); + + let result = worker.join().expect("worker thread").expect("receipt"); + assert!( + result.ok, + "a rename that happened must not be reported as a cancellation: {result:?}" + ); + assert_eq!(result.data["publication"], json!("published")); + assert!( + result.data["hash"] + .as_str() + .is_some_and(|hash| !hash.is_empty()), + "the published write receipt must keep the effect identity: {result:?}" + ); + let committed = executor + .committed_receipt_for_test("p1-published-write") + .expect("durable published receipt"); + assert_eq!( + serde_json::to_value(&result).expect("serialize returned result"), + serde_json::to_value(&committed).expect("serialize committed receipt"), + "the returned result must equal the settled published receipt" + ); + assert_eq!( + fs::read_to_string(fixture.root.join("published.txt")).expect("published file"), + "published\n" + ); + assert_eq!(executor.open_token_count(), 0); + assert_eq!(executor.interrupted_token_count(), 0); + assert_eq!(executor.committed_token_count(), 1); + executor.shutdown(); +} + +#[test] +fn prepared_receipt_bytes_are_bound_to_their_one_read_version() { + let fixture = Fixture::new("r10-receipt-binding"); + let owner = CapabilityOwner::new("sol-lifecycle", "session", "receipt-binding").expect("owner"); + let durable = Arc::new(RecordingDurable::default()); + let lifecycle = CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry") + .workspace(&fixture.root) + .limits(LifecycleLimits { + max_tool_calls: 8, + max_output_bytes: 8192, + max_summary_bytes: 256, + }) + .deadline_ms(SystemClock.now_ms().saturating_add(60_000)) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(durable.clone() as Arc) + .approval( + Arc::new(AllowAllApproval) as Arc + ) + .cancellation(Arc::new(NeverCancelled) as Arc) + .build() + .expect("lifecycle"); + let token = prepare_token( + &lifecycle, + &owner, + "r10-receipt-binding", + CapabilityRisk::Write, + ); + lifecycle + .enter_publication(&token) + .expect("first publication") + .published_effect( + rustscript_agent::capabilities::NativeEffectRecord::artifact_store( + rustscript_agent::capabilities::NativeArtifactIdentity { + id: "first-artifact".to_string(), + len: 4, + hash: "hash".to_string(), + }, + ), + ); + // The executor's one read captures both the authoritative bytes and the + // ledger version that produced them. + let receipt = lifecycle + .derive_call_receipt("r10-receipt-binding") + .expect("derive receipt") + .expect("published receipt"); + assert!(receipt.result().ok); + assert_eq!( + receipt.result().artifacts, + vec!["first-artifact".to_string()] + ); + // A later effect extends the ledger after that read. + lifecycle + .enter_publication(&token) + .expect("later publication") + .published_effect( + rustscript_agent::capabilities::NativeEffectRecord::artifact_store( + rustscript_agent::capabilities::NativeArtifactIdentity { + id: "late-artifact".to_string(), + len: 4, + hash: "hash".to_string(), + }, + ), + ); + let settlement = lifecycle + .settle_call_with_call_receipt("r10-receipt-binding", &receipt) + .expect("settlement"); + assert_eq!( + settlement.committed, 0, + "bytes derived from an older ledger version must not commit: {settlement:?}" + ); + assert!( + settlement.retained >= 1, + "the stale receipt must stay open for a retry: {settlement:?}" + ); + assert_eq!(lifecycle.open_token_count(), 1); + assert!( + durable.result("r10-receipt-binding").is_none(), + "no durable receipt may be written from stale bytes" + ); + // Re-deriving now binds the full ledger, including the later artifact, to + // a fresh version; that exact pair commits once. + let fresh = lifecycle + .derive_call_receipt("r10-receipt-binding") + .expect("derive fresh receipt") + .expect("published receipt"); + assert!( + fresh + .result() + .artifacts + .iter() + .any(|id| id == "late-artifact"), + "the fresh receipt must describe the whole ledger: {fresh:?}" + ); + let retried = lifecycle + .settle_call_with_call_receipt("r10-receipt-binding", &fresh) + .expect("retry settlement"); + assert_eq!(retried.committed, 1); + assert_eq!(lifecycle.open_token_count(), 0); + let committed = durable + .result("r10-receipt-binding") + .expect("durable committed payload"); + assert_eq!( + committed, + fresh.encoded().clone(), + "the committed payload must be the exact bytes the fresh version describes" + ); +} + +/// Holds the admitted prepare inside approval until the test has observed +/// that the duplicate prepare of the same call id was refused before the +/// approval gate. The call-id reservation now makes that refusal happen +/// before the gate is reached, so exactly one arrival is expected. +struct TwoPrepareGate { + arrived: (Mutex, Condvar), + released: (Mutex, Condvar), +} + +impl TwoPrepareGate { + fn new() -> Arc { + Arc::new(Self { + arrived: (Mutex::new(0), Condvar::new()), + released: (Mutex::new(false), Condvar::new()), + }) + } + + fn wait_one_arrived(&self) { + let mut arrived = self + .arrived + .0 + .lock() + .unwrap_or_else(|error| error.into_inner()); + let deadline = Instant::now() + Duration::from_secs(10); + while *arrived < 1 { + let remaining = deadline.saturating_duration_since(Instant::now()); + assert!( + !remaining.is_zero(), + "the admitted prepare must reach approval" + ); + let (guard, _) = self + .arrived + .1 + .wait_timeout(arrived, remaining) + .unwrap_or_else(|error| error.into_inner()); + arrived = guard; + } + } + + fn arrived_count(&self) -> usize { + *self + .arrived + .0 + .lock() + .unwrap_or_else(|error| error.into_inner()) + } + + fn release(&self) { + *self + .released + .0 + .lock() + .unwrap_or_else(|error| error.into_inner()) = true; + self.released.1.notify_all(); + } +} + +impl rustscript_agent::capabilities::ApprovalGate for TwoPrepareGate { + fn authorize(&self, metadata: &PrepareMetadata) -> Result { + { + let mut arrived = self + .arrived + .0 + .lock() + .unwrap_or_else(|error| error.into_inner()); + *arrived += 1; + self.arrived.1.notify_all(); + } + let mut released = self + .released + .0 + .lock() + .unwrap_or_else(|error| error.into_inner()); + while !*released { + released = self + .released + .1 + .wait(released) + .unwrap_or_else(|error| error.into_inner()); + } + Ok(metadata.risk_class) + } +} + +#[test] +fn concurrent_prepares_of_one_call_id_admit_exactly_one_token() { + let fixture = Fixture::new("r12-prepare-race"); + let owner = CapabilityOwner::new("sol-lifecycle", "session", "prepare-race").expect("owner"); + let durable = Arc::new(RecordingDurable::default()); + let gate = TwoPrepareGate::new(); + let lifecycle = CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry") + .workspace(&fixture.root) + .limits(LifecycleLimits { + max_tool_calls: 8, + max_output_bytes: 8192, + max_summary_bytes: 256, + }) + .deadline_ms(SystemClock.now_ms().saturating_add(60_000)) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(durable.clone() as Arc) + .approval(gate.clone() as Arc) + .cancellation(Arc::new(NeverCancelled) as Arc) + .published_token_policy( + rustscript_agent::capabilities::PublishedTokenPolicy::RetainForSettlement, + ) + .build() + .expect("lifecycle"); + let prepares: Vec<_> = (0..2) + .map(|_| { + let lifecycle = lifecycle.clone(); + let owner = owner.clone(); + std::thread::spawn(move || { + lifecycle.prepare( + &owner, + PrepareMetadata { + run_id: owner.run().to_string(), + call_id: "r12-prepare-race".to_string(), + tool_name: "fixture_tool".to_string(), + argument_digest: "digest".to_string(), + registry_identity: "registry".to_string(), + risk_class: CapabilityRisk::Read, + summary: "fixture".to_string(), + }, + ) + }) + }) + .collect(); + gate.wait_one_arrived(); + // The duplicate prepare is refused by the call-id reservation before it + // can reach approval or write a second durable start. + assert_eq!( + gate.arrived_count(), + 1, + "a duplicate prepare of the same call id must be refused before approval" + ); + gate.release(); + let mut token = None; + let mut refused = 0usize; + for prepare in prepares { + match prepare.join().expect("prepare thread") { + Ok(PrepareOutcome::Execute { + execution_token, .. + }) => { + assert!(token.is_none(), "the race must admit exactly one token"); + token = Some(execution_token); + } + Err(LifecycleError::UnresolvedCall) => refused += 1, + other => panic!("expected one admission and one refusal, got {other:?}"), + } + } + assert_eq!(refused, 1, "the later prepare must be refused"); + assert_eq!( + lifecycle.open_token_count(), + 1, + "the refused prepare must never publish a second token" + ); + assert_eq!( + durable.start_count(), + 1, + "each call id must produce exactly one durable start" + ); + // The one admitted token settles the whole call with one receipt. + let token = token.expect("one admitted token"); + lifecycle + .enter_publication(&token) + .expect("publication") + .published_effect( + rustscript_agent::capabilities::NativeEffectRecord::artifact_store( + rustscript_agent::capabilities::NativeArtifactIdentity { + id: "r12-artifact".to_string(), + len: 3, + hash: "hash".to_string(), + }, + ), + ); + let settlement = lifecycle + .settle_call_terminal( + "r12-prepare-race", + rustscript_agent::capabilities::CallTerminalRequest::Derived, + ) + .expect("terminal settlement"); + assert_eq!( + settlement.decision, + rustscript_agent::capabilities::CallTerminalDecision::Committed + ); + assert_eq!(settlement.committed, 1); + assert_eq!(durable.commit_count(), 1); + assert_eq!(lifecycle.open_token_count(), 0); +} + +#[test] +fn synthetic_terminal_never_replaces_a_publication_that_landed_first() { + let fixture = Fixture::new("r12-synthetic-published"); + let owner = CapabilityOwner::new("sol-lifecycle", "session", "synthetic").expect("owner"); + let durable = Arc::new(RecordingDurable::default()); + let lifecycle = CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry") + .workspace(&fixture.root) + .limits(LifecycleLimits { + max_tool_calls: 8, + max_output_bytes: 8192, + max_summary_bytes: 256, + }) + .deadline_ms(SystemClock.now_ms().saturating_add(60_000)) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(durable.clone() as Arc) + .approval( + Arc::new(AllowAllApproval) as Arc + ) + .cancellation(Arc::new(NeverCancelled) as Arc) + .published_token_policy( + rustscript_agent::capabilities::PublishedTokenPolicy::RetainForSettlement, + ) + .build() + .expect("lifecycle"); + let token = prepare_token( + &lifecycle, + &owner, + "r12-synthetic-published", + CapabilityRisk::Write, + ); + let published = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let gate = Arc::new(SeamGate::default()); + lifecycle.inject_settle_snapshot_observer_for_test({ + let lifecycle = lifecycle.clone(); + let published = Arc::clone(&published); + let gate = Arc::clone(&gate); + Arc::new(move || { + if published.swap(true, Ordering::SeqCst) { + return; + } + // The publication lands before the single terminal decision reads + // the live call. Legacy two-read settlement bound the synthetic + // bytes to this new version and committed them over the effect. + lifecycle + .enter_publication(&token) + .expect("publication crossing the terminal window") + .published_effect( + rustscript_agent::capabilities::NativeEffectRecord::artifact_store( + rustscript_agent::capabilities::NativeArtifactIdentity { + id: "r12-real-effect".to_string(), + len: 4, + hash: "hash".to_string(), + }, + ), + ); + assert!(lifecycle.request_call_cancellation("r12-synthetic-published")); + gate.release(); + }) + }); + let synthetic = json!(ToolResult::failure("cancelled", "tool call was cancelled")); + let settlement = lifecycle + .settle_call_terminal( + "r12-synthetic-published", + rustscript_agent::capabilities::CallTerminalRequest::Synthetic(&synthetic), + ) + .expect("terminal settlement"); + assert_eq!( + settlement.decision, + rustscript_agent::capabilities::CallTerminalDecision::Committed, + "the published effect must decide the call: {settlement:?}" + ); + assert_eq!(settlement.committed, 1); + let committed = durable + .result("r12-synthetic-published") + .expect("durable receipt"); + let typed: ToolResult = serde_json::from_value(committed).expect("typed receipt"); + assert!(typed.ok, "the real effect must win: {typed:?}"); + assert_eq!( + typed.artifacts, + vec!["r12-real-effect".to_string()], + "the committed receipt must describe the published artifact" + ); + assert_ne!( + typed.error.as_ref().map(|error| error.code.as_str()), + Some("cancelled") + ); +} + +#[test] +fn synthetic_receipt_is_bound_to_the_empty_ledger_it_was_derived_from() { + let fixture = Fixture::new("r11-synthetic-binding"); + let owner = CapabilityOwner::new("sol-lifecycle", "session", "synthetic").expect("owner"); + let durable = Arc::new(RecordingDurable::default()); + let lifecycle = CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry") + .workspace(&fixture.root) + .limits(LifecycleLimits { + max_tool_calls: 8, + max_output_bytes: 8192, + max_summary_bytes: 256, + }) + .deadline_ms(SystemClock.now_ms().saturating_add(60_000)) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(durable.clone() as Arc) + .approval( + Arc::new(AllowAllApproval) as Arc + ) + .cancellation(Arc::new(NeverCancelled) as Arc) + .published_token_policy( + rustscript_agent::capabilities::PublishedTokenPolicy::RetainForSettlement, + ) + .build() + .expect("lifecycle"); + let token = prepare_token( + &lifecycle, + &owner, + "r11-synthetic-binding", + CapabilityRisk::Write, + ); + // Nothing has published yet: this is the empty read the executor turns + // into a synthetic cancellation receipt. + assert!( + lifecycle + .derive_call_receipt("r11-synthetic-binding") + .expect("derive") + .is_none() + ); + let synthetic = lifecycle.bind_synthetic_result( + "r11-synthetic-binding", + ToolResult::failure("cancelled", "tool call was cancelled"), + ); + // A publication finishes after that empty read. + lifecycle + .enter_publication(&token) + .expect("publication") + .published_effect( + rustscript_agent::capabilities::NativeEffectRecord::artifact_store( + rustscript_agent::capabilities::NativeArtifactIdentity { + id: "r11-synthetic-artifact".to_string(), + len: 3, + hash: "hash".to_string(), + }, + ), + ); + let settlement = lifecycle + .settle_call_with_call_receipt("r11-synthetic-binding", &synthetic) + .expect("settlement"); + assert_eq!( + settlement.committed, 0, + "synthetic bytes must not settle a publication that finished after the empty read: {settlement:?}" + ); + assert!(settlement.retained >= 1); + assert_eq!( + durable.commit_count(), + 0, + "no synthetic result may be written over a real published effect" + ); + assert_eq!(lifecycle.open_token_count(), 1); + // The owner re-derives the canonical receipt from the advanced ledger and + // commits it once. + let fresh = lifecycle + .derive_call_receipt("r11-synthetic-binding") + .expect("derive fresh receipt") + .expect("published receipt"); + let retried = lifecycle + .settle_call_with_call_receipt("r11-synthetic-binding", &fresh) + .expect("retry settlement"); + assert_eq!(retried.committed, 1); + assert_eq!(lifecycle.open_token_count(), 0); + assert_eq!(durable.commit_count(), 1); +} + +#[test] +fn executor_artifact_store_cannot_mask_a_timed_out_process_terminal() { + let fixture = Fixture::new("p1-timeout-mask"); + let executor = Arc::new( + McpToolExecutor::new( + McpToolExecutorConfig::new(&fixture.root) + .with_max_output_bytes(512) + .with_epoch_check_interval_for_test(1), + ) + .expect("executor"), + ); + let gate = Arc::new(SeamGate::default()); + executor.artifacts_for_test().inject_before_publish({ + let gate = Arc::clone(&gate); + Arc::new(move || gate.block()) + }); + let worker = { + let executor = Arc::clone(&executor); + std::thread::spawn(move || { + executor.execute_tool( + Some("p1-timeout-mask"), + "terminal", + &json!({ + "argv": ["/bin/sh", "-c", "i=0; while [ $i -lt 1200 ]; do printf z; i=$((i+1)); done; exec sleep 30"], + "timeout_ms": 50 + }), + ) + }) + }; + // The host process deadline already fired and the terminal record is a + // typed failure; the subsequent overflow artifact store is where an + // artifact-only OK fragment used to become the first receipt. + gate.wait_started(); + assert!(executor.cancel_call("p1-timeout-mask")); + gate.release(); + + let result = worker.join().expect("worker").expect("receipt"); + assert!( + !result.ok, + "the timed-out terminal must not be masked by the artifact store: {result:?}" + ); + assert_eq!( + result.error.as_ref().map(|error| error.code.as_str()), + Some("deadline_elapsed"), + "the typed host deadline code must stay authoritative: {result:?}" + ); + assert_eq!( + result.artifacts.len(), + 1, + "the artifact stored after the failed terminal must still be reported: {result:?}" + ); + assert_eq!( + result.data["effect"], + json!("process_spawn"), + "the authoritative record must stay the failed process terminal: {result:?}" + ); + assert!( + result.data["process_state"].is_string(), + "the failed terminal must carry its observed process state: {result:?}" + ); + assert_eq!( + executor.committed_token_count(), + 1, + "exactly one canonical receipt must be committed" + ); + executor.shutdown(); +} + +#[test] +fn published_artifact_receipt_survives_a_vm_stop_before_tool_commit() { + let fixture = Fixture::new("p1-published-artifact"); + let executor = Arc::new( + McpToolExecutor::new( + McpToolExecutorConfig::new(&fixture.root) + .with_max_output_bytes(512) + .with_epoch_check_interval_for_test(1), + ) + .expect("executor"), + ); + let gate = Arc::new(SeamGate::default()); + executor.artifacts_for_test().inject_before_publish({ + let gate = Arc::clone(&gate); + Arc::new(move || gate.block()) + }); + let guest_commits = Arc::new(AtomicU64::new(0)); + executor.set_commit_observer_for_test({ + let guest_commits = Arc::clone(&guest_commits); + Arc::new(move |_call_id| { + guest_commits.fetch_add(1, Ordering::SeqCst); + }) + }); + let stdout = "z".repeat(1024); + let worker = { + let executor = Arc::clone(&executor); + std::thread::spawn(move || { + executor.execute_tool( + Some("p1-published-artifact"), + "terminal", + &json!({"argv": ["/usr/bin/printf", "%s", stdout]}), + ) + }) + }; + + gate.wait_started(); + assert!(executor.cancel_call("p1-published-artifact")); + // The request alone does not stop the guest: a separate watcher thread + // advances the VM epoch on its own schedule. Release the synchronous host + // call only after that jump is acknowledged, so the next epoch check is + // guaranteed to abort the guest before `tool_commit`. + wait_until("the epoch watcher acknowledges the cancellation", || { + executor.call_epoch_advanced_for_test("p1-published-artifact") == Some(true) + }); + gate.release(); + + let result = worker.join().expect("worker thread").expect("receipt"); + // Cancellation was armed while the artifact insertion was still blocked + // inside its fence. With the VM epoch interval at one, the next VM + // instruction after that host call observes the cancellation, so the guest + // cannot reach `tool_commit`. The primary ledger record is therefore the + // foreground spawn with its observed exit 0, and the artifact only appends + // its exact UUID. + assert_eq!( + guest_commits.load(Ordering::SeqCst), + 0, + "the pre-commit stop must be deterministic: {result:?}" + ); + assert!( + result.ok, + "the exited foreground spawn keeps its success record: {result:?}" + ); + assert_eq!( + result.data["effect"], + json!("process_spawn"), + "the authoritative record must be the observed foreground spawn: {result:?}" + ); + assert_eq!( + result.data["process_state"], + json!("exited"), + "the spawn record must carry its observed terminal state: {result:?}" + ); + assert_eq!( + result.data["exit_code"], + json!(0), + "the spawn must report the observed exit 0: {result:?}" + ); + assert!( + result.data["pid"].as_u64().is_some_and(|pid| pid > 0), + "the primary spawn record must keep its real pid: {result:?}" + ); + assert_eq!( + result.artifacts.len(), + 1, + "exactly the appended artifact identity must survive: {result:?}" + ); + assert_eq!(result.artifacts[0].len(), 36); + let stored = executor.artifacts_for_test().stored_ids(); + assert_eq!( + stored, + vec![result.artifacts[0].clone()], + "the receipt must carry the exact inserted artifact UUID: {result:?}" + ); + let committed = executor + .durable_committed_receipt_for_test("p1-published-artifact") + .expect("the guard must durably commit the snapshot"); + assert_eq!( + serde_json::to_value(&result).expect("serialize returned result"), + serde_json::to_value(&committed).expect("serialize committed receipt"), + "the returned result must equal the durably committed snapshot" + ); + assert_eq!(executor.open_token_count(), 0); + assert_eq!(executor.interrupted_token_count(), 0); + assert_eq!(executor.committed_token_count(), 1); + executor.shutdown(); +} + +#[test] +fn minimum_cap_compaction_keeps_the_canonical_error_and_terminal_facts() { + let artifact = "01234567-89ab-cdef-0123-456789abcdef"; + let terminal = json!({"status": "signaled", "process_state": "signaled", "signal": 9}); + let mut data = terminal.clone(); + // The extra data can fit only by shortening the canonical error code. + data["diagnostics"] = json!("x".repeat(315)); + let mut result = ToolResult::failure_with( + "deadline_elapsed", + "\0".repeat(96), + "large output", + data, + false, + ); + result.artifacts = vec![artifact.to_owned()]; + let compact = result.compact_to_bytes(512); + let encoded = serde_json::to_vec(&compact).expect("encode compact receipt"); + assert!(encoded.len() <= 512); + let replayed: ToolResult = serde_json::from_slice(&encoded).expect("decode compact receipt"); + assert_eq!( + replayed.error.as_ref().expect("failure").code, + "deadline_elapsed" + ); + assert_eq!(replayed.data, terminal); + assert_eq!(replayed.artifacts, [artifact]); + assert!(!replayed.ok && replayed.truncated); + assert_eq!( + serde_json::to_vec(&replayed).expect("encode replay"), + encoded + ); +} + +#[test] +fn minimal_receipt_worst_case_bound_includes_json_escaping() { + // Exact worst-case shape emitted by both RSS `minimal_canonical_receipt` + // implementations: status + both i32 terminal values, a 48-JSON-byte code + // (eight control characters escape to six bytes each), a 96-JSON-byte + // message, and one canonical 36-byte artifact id. + let receipt = json!({ + "ok": false, + "content": "", + "data": { + "status": "signaled", + "exit_code": -2147483648, + "signal": -2147483648 + }, + "error": { + "code": "\0".repeat(8), + "message": "\0".repeat(16) + }, + "truncated": true, + "artifacts": ["01234567-89ab-cdef-0123-456789abcdef"] + }); + let encoded = serde_json::to_vec(&receipt).expect("serialize worst-case receipt"); + assert_eq!( + encoded.len(), + 346, + "the real escaped worst-case bound must be measured exactly" + ); + let typed: ToolResult = + serde_json::from_value(receipt.clone()).expect("decode at the typed boundary"); + assert_eq!( + typed.encoded_len(), + 346, + "the typed serializer must reproduce the exact escaped worst-case bound" + ); + assert!( + typed.encoded_len() <= rustscript_agent::mcp::executor::MIN_EFFECT_TOOL_OUTPUT_BYTES, + "the worst-case receipt must fit the 512-byte effect floor" + ); +} + +#[test] +fn cancellation_during_file_staging_never_reaches_the_rename_boundary() { + let fixture = Fixture::new("p2-file-staging"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle_with_call_cancel(&fixture.root, Arc::clone(&cancel)); + let filesystem = FilesystemCapability::new( + lifecycle.clone(), + owner.clone(), + FilesystemLimits::default(), + ) + .expect("filesystem"); + let token = prepare_token(&lifecycle, &owner, "p2-file-staging", CapabilityRisk::Write); + let gate = Arc::new(SeamGate::default()); + filesystem.inject_during_staging({ + let gate = Arc::clone(&gate); + Arc::new(move || gate.block()) + }); + + let publisher = { + let filesystem = filesystem.clone(); + let token = token.clone(); + std::thread::spawn(move || filesystem.write_atomic(&token, "staged.txt", "*", b"durable\n")) + }; + gate.wait_started(); + // The effect is still staging: the temporary exists, the destination does + // not. Cancellation must win and refuse the rename. + assert!(!cancel.load(Ordering::SeqCst), "fixture sanity"); + assert!( + lifecycle.request_call_cancellation("p2-file-staging"), + "the open token must accept the cancellation request" + ); + gate.release(); + + let error = publisher + .join() + .expect("publisher thread") + .expect_err("a cancelled staging write must not publish"); + assert_eq!( + error.code(), + "cancelled", + "cancellation before the rename must refuse the effect: {error:?}" + ); + assert!( + !fixture.root.join("staged.txt").exists(), + "a cancelled staging write must leave no published destination" + ); + let leftovers: Vec = fs::read_dir(&fixture.root) + .expect("read workspace") + .filter_map(|entry| entry.ok()) + .map(|entry| entry.file_name().to_string_lossy().into_owned()) + .collect(); + assert!( + leftovers + .iter() + .all(|name| !name.starts_with(".rustscript-tmp")), + "the refused staging temporary must be removed: {leftovers:?}" + ); + let commit = lifecycle + .commit(&owner, &token, success_receipt()) + .expect_err("an unpublished refusal must not commit"); + assert_eq!(commit.code(), "cancelled"); + let settlement = lifecycle + .settle_call_with_receipt("p2-file-staging", Some(&success_receipt())) + .expect("settle"); + assert_eq!( + settlement.interrupted, 1, + "a call cancelled before publication must be interrupted, not committed" + ); + assert_eq!(settlement.committed, 0); +} + +#[test] +fn post_spawn_setup_failure_keeps_the_native_effect_published() { + let fixture = Fixture::new("p2-post-spawn"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle_with_call_cancel(&fixture.root, Arc::clone(&cancel)); + let processes = rustscript_agent::capabilities::ProcessCapability::new_with_table_limits( + lifecycle.clone(), + owner.clone(), + rustscript_agent::capabilities::ProcessLimits::default(), + rustscript_agent::capabilities::ProcessTableLimits::new(2, 2, Duration::from_millis(500)) + .expect("table limits"), + ) + .expect("processes"); + let token = prepare_token(&lifecycle, &owner, "p2-post-spawn", CapabilityRisk::Execute); + let argv = vec![ + "/bin/sh".to_string(), + "-c".to_string(), + "printf spawned".to_string(), + ]; + // The child really spawned, so its ownership must stay visible until a + // bounded reap is proven. Withholding the proof models a stalled reap. + processes.withhold_cleanup_proof_for_test(); + let error = processes + .spawn_with_post_spawn_failure_for_test( + &token, + &argv, + "", + &[], + rustscript_agent::capabilities::ProcessLimits { + timeout_ms: 5_000, + close_after_initial: true, + ..rustscript_agent::capabilities::ProcessLimits::default() + }, + ) + .expect_err("the injected post-spawn setup failure must be reported"); + assert_ne!(error.code(), "process_limit", "error={error:?}"); + assert_eq!( + processes.table_len(), + 1, + "a post-spawn setup failure must retain the unproven child record" + ); + let cutoff = Instant::now() + Duration::from_millis(150); + let proof = processes.shutdown_all_within(cutoff); + assert!( + matches!(proof, ProcessCleanupProof::TimedOut { retained } if retained >= 1), + "shutdown must not report Clean over an unproven setup failure: {proof:?}" + ); + + // The OS spawn did execute, so cancellation can no longer turn the call + // into an unpublished refusal: the authoritative settlement commits the + // canonical failure receipt exactly once. + assert!(lifecycle.request_call_cancellation("p2-post-spawn")); + let receipt = json!({ + "ok": false, + "content": "", + "data": {}, + "error": {"code": "spawn_failed", "message": "process spawn failed"}, + "truncated": false, + "artifacts": [] + }); + let settlement = lifecycle + .settle_call_with_receipt("p2-post-spawn", Some(&receipt)) + .expect("settle"); + assert_eq!( + settlement.interrupted, 0, + "a spawn that reached the OS boundary must never be interrupted as unpublished" + ); + assert_eq!( + settlement.committed, 1, + "the published spawn must keep exactly one canonical receipt" + ); + assert_eq!(lifecycle.open_token_count(), 0); + + // Once the real cleanup proof is available, the retained record is reaped + // and only then released. + processes.allow_cleanup_proof_for_test(); + let cutoff = Instant::now() + Duration::from_secs(2); + let proof = processes.shutdown_all_within(cutoff); + assert!( + proof.is_clean(), + "the retained spawn-abort record must be reaped under a proven cleanup: {proof:?}" + ); + assert_eq!(processes.table_len(), 0); +} + +#[test] +fn stderr_drainer_setup_failure_retains_the_child_and_started_drainer() { + let fixture = Fixture::new("p3-stderr-drainer"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle_with_call_cancel(&fixture.root, Arc::clone(&cancel)); + let processes = rustscript_agent::capabilities::ProcessCapability::new_with_table_limits( + lifecycle.clone(), + owner.clone(), + rustscript_agent::capabilities::ProcessLimits::default(), + rustscript_agent::capabilities::ProcessTableLimits::new(1, 1, Duration::from_millis(500)) + .expect("table limits"), + ) + .expect("processes"); + let token = prepare_token( + &lifecycle, + &owner, + "p3-stderr-drainer", + CapabilityRisk::Execute, + ); + processes.withhold_cleanup_proof_for_test(); + let error = processes + .spawn_with_stderr_drainer_failure_for_test( + &token, + &["/bin/sleep".to_string(), "30".to_string()], + "", + &[], + rustscript_agent::capabilities::ProcessLimits { + timeout_ms: 5_000, + close_after_initial: false, + ..rustscript_agent::capabilities::ProcessLimits::default() + }, + ) + .expect_err("the injected stderr-drainer failure must be reported"); + assert_eq!( + processes.table_len(), + 1, + "the spawned child and its started drainer must stay owned: {error:?}" + ); + let cutoff = Instant::now() + Duration::from_millis(150); + let proof = processes.shutdown_all_within(cutoff); + assert!( + matches!(proof, ProcessCleanupProof::TimedOut { retained } if retained >= 1), + "an unproven drainer setup failure must not be reported Clean: {proof:?}" + ); + processes.allow_cleanup_proof_for_test(); + let proof = processes.shutdown_all_within(Instant::now() + Duration::from_secs(2)); + assert!( + proof.is_clean(), + "the retained child and started drainer must be reaped and joined: {proof:?}" + ); + assert_eq!(processes.table_len(), 0); +} + +#[test] +fn process_fence_is_entered_only_at_the_os_spawn_boundary() { + let fixture = Fixture::new("p2-spawn-fence"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle_with_call_cancel(&fixture.root, Arc::clone(&cancel)); + let processes = Arc::new( + rustscript_agent::capabilities::ProcessCapability::new_with_table_limits( + lifecycle.clone(), + owner.clone(), + rustscript_agent::capabilities::ProcessLimits::default(), + rustscript_agent::capabilities::ProcessTableLimits::new( + 1, + 1, + Duration::from_millis(500), + ) + .expect("table limits"), + ) + .expect("processes"), + ); + let gate = Arc::new(SeamGate::default()); + processes.set_before_publication_hook({ + let gate = Arc::clone(&gate); + Arc::new(move || gate.block()) + }); + let token = prepare_token( + &lifecycle, + &owner, + "p2-spawn-fence", + CapabilityRisk::Execute, + ); + let spawner = { + let processes = Arc::clone(&processes); + let token = token.clone(); + std::thread::spawn(move || { + processes.spawn( + &token, + &["/bin/true".to_string()], + "", + &[], + rustscript_agent::capabilities::ProcessLimits::default(), + ) + }) + }; + gate.wait_started(); + assert_eq!( + processes.table_len(), + 0, + "no ownership record may exist before the OS spawn syscall" + ); + // The fence has not been consumed yet: the request validation and cwd + // setup completed, but the permit is entered only after this hook. + assert!(lifecycle.request_call_cancellation("p2-spawn-fence")); + let receipt = json!({ + "ok": false, + "content": "", + "data": {}, + "error": {"code": "cancelled", "message": "process was cancelled"}, + "truncated": false, + "artifacts": [] + }); + let settlement = lifecycle + .settle_call_with_receipt("p2-spawn-fence", Some(&receipt)) + .expect("settle"); + assert_eq!( + settlement.interrupted, 1, + "a fence that was never entered must be interrupted, not retained" + ); + assert_eq!(settlement.retained, 0); + gate.release(); + let error = spawner + .join() + .expect("spawner thread") + .expect_err("the refused publication must prevent the spawn"); + assert!( + error.code() == "cancelled" || error.code() == "interrupted", + "the refusal must be typed: {error:?}" + ); + assert_eq!(processes.table_len(), 0); + assert!( + !fixture.root.join("spawned.txt").exists(), + "a refused spawn must not execute the program" + ); +} + +#[test] +fn successful_spawn_publishes_only_after_the_syscall() { + let fixture = Fixture::new("p2-spawn-success"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle_with_call_cancel(&fixture.root, Arc::clone(&cancel)); + let processes = Arc::new( + rustscript_agent::capabilities::ProcessCapability::new_with_table_limits( + lifecycle.clone(), + owner.clone(), + rustscript_agent::capabilities::ProcessLimits::default(), + rustscript_agent::capabilities::ProcessTableLimits::new( + 1, + 1, + Duration::from_millis(500), + ) + .expect("table limits"), + ) + .expect("processes"), + ); + let token = prepare_token( + &lifecycle, + &owner, + "p2-spawn-success", + CapabilityRisk::Execute, + ); + let _spawned = processes + .spawn( + &token, + &["/bin/sleep".to_string(), "30".to_string()], + "", + &[], + rustscript_agent::capabilities::ProcessLimits { + timeout_ms: 5_000, + close_after_initial: false, + ..rustscript_agent::capabilities::ProcessLimits::default() + }, + ) + .expect("spawn"); + assert_eq!(processes.table_len(), 1); + assert!( + lifecycle + .call_native_outcome("p2-spawn-success") + .is_some_and(|outcome| outcome.record.process.is_some_and(|process| { + process.pid == _spawned.pid + && process.state == rustscript_agent::capabilities::NativeProcessState::Running + })), + "an OS spawn must carry its complete pid/running record" + ); + let settlement = lifecycle + .settle_call_with_receipt( + "p2-spawn-success", + Some(&json!({ + "ok": false, + "content": "", + "data": {}, + "error": {"code": "cancelled", "message": "process was cancelled"}, + "truncated": false, + "artifacts": [] + })), + ) + .expect("settle"); + assert_eq!(settlement.interrupted, 0); + assert_eq!(settlement.committed, 1); + processes.shutdown_all(); +} + +#[test] +fn pidfd_failure_on_original_and_retry_still_proves_the_retained_child() { + let fixture = Fixture::new("p3-pidfd"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle_with_call_cancel(&fixture.root, Arc::clone(&cancel)); + let processes = Arc::new( + ProcessCapability::new_with_table_limits( + lifecycle.clone(), + owner.clone(), + ProcessLimits::default(), + ProcessTableLimits::new(1, 1, Duration::from_millis(300)).expect("table limits"), + ) + .expect("processes"), + ); + let token = prepare_token(&lifecycle, &owner, "p3-pidfd", CapabilityRisk::Execute); + // The original spawn acquisition and the retained handle's lazy retry both + // fail. The owned Child's bounded wait status must still prove a real + // terminal outcome. + processes.fail_pidfd_opens_for_test(2); + processes.withhold_cleanup_proof_for_test(); + let error = processes + .spawn( + &token, + &["/bin/sleep".to_string(), "30".to_string()], + "", + &[], + ProcessLimits { + timeout_ms: 5_000, + close_after_initial: false, + ..ProcessLimits::default() + }, + ) + .expect_err("a failed pidfd acquisition must retain the child and surface"); + assert_eq!(error.code(), "process_failed", "{error:?}"); + assert_eq!( + processes.table_len(), + 1, + "the retained child must stay owned until a real proof exists" + ); + let pid = processes.live_pids()[0]; + assert!( + pid_alive(pid), + "the retained child is still a real OS process" + ); + + processes.allow_cleanup_proof_for_test(); + assert_eq!( + processes.shutdown_all_within(Instant::now() + Duration::from_secs(2)), + ProcessCleanupProof::Clean, + "the wait-status fallback must produce a truthful bounded proof" + ); + assert_eq!(processes.table_len(), 0); + assert!( + !pid_alive(pid), + "the retained child must be killed and reaped" + ); +} + +fn pid_alive(pid: u32) -> bool { + std::path::Path::new(&format!("/proc/{pid}")).exists() +} + +#[test] +fn shutdown_never_observes_an_empty_table_during_spawn_conversion() { + let fixture = Fixture::new("p3-convert"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle_with_call_cancel(&fixture.root, Arc::clone(&cancel)); + let processes = Arc::new( + rustscript_agent::capabilities::ProcessCapability::new_with_table_limits( + lifecycle.clone(), + owner.clone(), + rustscript_agent::capabilities::ProcessLimits::default(), + rustscript_agent::capabilities::ProcessTableLimits::new( + 1, + 1, + Duration::from_millis(200), + ) + .expect("table limits"), + ) + .expect("processes"), + ); + let spawn_gate = Arc::new(SeamGate::default()); + processes.set_after_os_spawn_hook({ + let gate = Arc::clone(&spawn_gate); + Arc::new(move || gate.block()) + }); + let conversion_gate = Arc::new(SeamGate::default()); + processes.set_after_closing_conversion_hook({ + let gate = Arc::clone(&conversion_gate); + Arc::new(move || gate.block()) + }); + let token = prepare_token(&lifecycle, &owner, "p3-convert", CapabilityRisk::Execute); + let spawner = { + let processes = Arc::clone(&processes); + let token = token.clone(); + std::thread::spawn(move || { + processes.spawn( + &token, + &["/bin/sleep".to_string(), "30".to_string()], + "", + &[], + rustscript_agent::capabilities::ProcessLimits { + timeout_ms: 10_000, + close_after_initial: false, + ..rustscript_agent::capabilities::ProcessLimits::default() + }, + ) + }) + }; + spawn_gate.wait_started(); + + // Shutdown starts while the spawn is between its reservation and its + // record. Its own proof is deterministically withheld, so it can only + // report Clean if ownership vanished; it must never observe 0/0/0 while + // the converted child is still owned. + processes.withhold_cleanup_proof_for_test(); + let shutdown = { + let processes = Arc::clone(&processes); + std::thread::spawn(move || { + processes.shutdown_all_within(Instant::now() + Duration::from_millis(400)) + }) + }; + std::thread::sleep(Duration::from_millis(100)); + spawn_gate.release(); + conversion_gate.wait_started(); + assert_eq!( + processes.table_len(), + 1, + "the converted child must be visible while its cleanup is unproven" + ); + let proof = shutdown.join().expect("shutdown thread"); + assert!( + !proof.is_clean(), + "shutdown must not report Clean while a converted child is still owned: {proof:?}" + ); + assert!( + proof.retained() >= 1, + "the timed-out proof must retain ownership: {proof:?}" + ); + conversion_gate.release(); + let error = spawner + .join() + .expect("spawn thread") + .expect_err("a spawn racing shutdown must be refused"); + assert_eq!(error.code(), "capability_unavailable"); + assert_eq!( + processes.table_len(), + 1, + "the retained record must survive the refused spawn until its proof" + ); + processes.allow_cleanup_proof_for_test(); + assert_eq!( + processes.shutdown_all_within(Instant::now() + Duration::from_secs(2)), + rustscript_agent::capabilities::ProcessCleanupProof::Clean, + "a later cleanup must still prove the retained record" + ); +} + +#[test] +fn terminal_foreground_retirement_keeps_ownership_until_the_bounded_proof() { + let fixture = Fixture::new("p3-retire"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle_with_call_cancel(&fixture.root, Arc::clone(&cancel)); + let processes = rustscript_agent::capabilities::ProcessCapability::new_with_table_limits( + lifecycle.clone(), + owner.clone(), + rustscript_agent::capabilities::ProcessLimits::default(), + rustscript_agent::capabilities::ProcessTableLimits::new(1, 1, Duration::from_millis(200)) + .expect("table limits"), + ) + .expect("processes"); + let token = prepare_token(&lifecycle, &owner, "p3-retire", CapabilityRisk::Execute); + let spawned = processes + .spawn( + &token, + &[ + "/bin/sh".to_string(), + "-c".to_string(), + "printf done".to_string(), + ], + "", + &[], + rustscript_agent::capabilities::ProcessLimits { + timeout_ms: 5_000, + close_after_initial: true, + ..rustscript_agent::capabilities::ProcessLimits::default() + }, + ) + .expect("foreground spawn"); + processes.withhold_cleanup_proof_for_test(); + let deadline = Instant::now() + Duration::from_secs(10); + loop { + let snapshot = processes + .poll(&token, &spawned.handle, 0, 4096) + .expect("poll foreground child"); + if !snapshot.running { + break; + } + assert!(Instant::now() < deadline, "child never reached terminal"); + std::thread::sleep(Duration::from_millis(5)); + } + assert_eq!( + processes.table_len(), + 1, + "retirement without a completed drain/stdin proof must keep the record owned" + ); + let proof = processes.shutdown_all_within(Instant::now() + Duration::from_millis(150)); + assert!( + !proof.is_clean(), + "an unproven retirement must not let shutdown report Clean: {proof:?}" + ); + assert!(proof.retained() >= 1); + processes.allow_cleanup_proof_for_test(); + assert_eq!( + processes.shutdown_all_within(Instant::now() + Duration::from_secs(2)), + rustscript_agent::capabilities::ProcessCleanupProof::Clean + ); + assert_eq!(processes.table_len(), 0); +} + +#[test] +fn executor_shutdown_exposes_and_retries_its_typed_cleanup_outcome() { + let fixture = Fixture::new("p4-outcome"); + let executor = McpToolExecutor::new( + McpToolExecutorConfig::new(&fixture.root) + .with_process_cleanup_timeout(Duration::from_millis(150)), + ) + .expect("executor"); + let background = executor + .execute_tool( + Some("p4-background"), + "terminal", + &json!({"argv": ["/bin/sleep", "30"], "background": true}), + ) + .expect("background dispatch"); + assert!(background.ok, "background receipt: {background:?}"); + assert_eq!(executor.process_table_len(), 1); + + executor.withhold_process_cleanup_proof_for_test(); + let started = Instant::now(); + let first = executor.shutdown(); + let elapsed = started.elapsed(); + assert!( + !first.is_clean(), + "a withheld proof must be a typed non-clean outcome: {first:?}" + ); + assert!( + elapsed < Duration::from_secs(2), + "the teardown must stay inside its configured cleanup budget: {elapsed:?}" + ); + assert_eq!( + executor.cleanup_outcome(), + Some(first), + "the exact typed outcome must be observable after shutdown" + ); + assert_eq!( + executor.process_table_len(), + 1, + "an unproven teardown must retain ownership" + ); + + executor.allow_process_cleanup_proof_for_test(); + let second = executor.shutdown(); + assert_eq!( + second, + ProcessCleanupProof::Clean, + "a later shutdown must retry the retained record" + ); + assert_eq!(executor.process_table_len(), 0); + assert_eq!(executor.cleanup_outcome(), Some(ProcessCleanupProof::Clean)); +} + +#[test] +fn executor_teardown_lock_wait_is_inside_the_absolute_budget() { + let fixture = Fixture::new("p4-lock"); + let executor = Arc::new( + McpToolExecutor::new( + McpToolExecutorConfig::new(&fixture.root) + .with_process_cleanup_timeout(Duration::from_millis(150)), + ) + .expect("executor"), + ); + let background = executor + .execute_tool( + Some("p4-lock-background"), + "terminal", + &json!({"argv": ["/bin/sleep", "30"], "background": true}), + ) + .expect("background dispatch"); + assert!(background.ok, "background receipt: {background:?}"); + + // Hold the real teardown mutex and measure a concurrent shutdown: the lock + // wait is part of the same absolute budget, not extra time on top of it. + let guard = executor.hold_teardown_for_test(); + let worker = { + let executor = Arc::clone(&executor); + std::thread::spawn(move || { + let started = Instant::now(); + let proof = executor.shutdown(); + (started.elapsed(), proof) + }) + }; + std::thread::sleep(Duration::from_millis(400)); + drop(guard); + let (elapsed, proof) = worker.join().expect("shutdown thread"); + assert!( + elapsed < Duration::from_millis(300), + "the teardown lock wait escaped the cleanup budget: {elapsed:?}" + ); + assert!( + !proof.is_clean(), + "a shutdown that could not acquire the teardown lock must stay typed: {proof:?}" + ); + executor.allow_process_cleanup_proof_for_test(); + let _ = executor.shutdown(); +} + +#[test] +fn shutdown_installs_one_cutoff_and_the_foreground_writer_joins_against_it() { + let fixture = Fixture::new("p4-foreground-stdin-cutoff"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle_with_call_cancel(&fixture.root, Arc::clone(&cancel)); + let processes = Arc::new( + ProcessCapability::new_with_table_limits( + lifecycle.clone(), + owner.clone(), + ProcessLimits { + stdin_limit: 1024 * 1024, + ..ProcessLimits::default() + }, + ProcessTableLimits::new(1, 1, Duration::from_millis(600)).expect("table limits"), + ) + .expect("processes"), + ); + let token = prepare_token( + &lifecycle, + &owner, + "p4-foreground-stdin", + CapabilityRisk::Execute, + ); + let spawned = processes + .spawn( + &token, + &[ + "/bin/sh".to_string(), + "-c".to_string(), + "sleep 30".to_string(), + ], + "", + &[], + ProcessLimits { + timeout_ms: 10_000, + stdin_limit: 1024 * 1024, + close_after_initial: false, + ..ProcessLimits::default() + }, + ) + .expect("background spawn"); + let writer = { + let processes = Arc::clone(&processes); + let token = token.clone(); + let handle = spawned.handle.clone(); + std::thread::spawn(move || { + processes.write_stdin(&token, &handle, &vec![b's'; 512 * 1024], Some(30_000)) + }) + }; + wait_until( + "the foreground stdin worker stalls on the child pipe", + || processes.active_stdin_workers() >= 1, + ); + + // The supported 600 ms grace is above every former local 200 ms floor. + let cutoff = Instant::now() + Duration::from_millis(600); + processes.begin_shutdown_for_test(cutoff); + assert_eq!( + processes.cleanup_cutoff_for_test(), + Some(cutoff), + "the first declared grace must be the one stored cutoff" + ); + cancel.store(true, Ordering::SeqCst); + let started = Instant::now(); + let result = writer.join().expect("foreground writer thread"); + let elapsed = started.elapsed(); + assert_eq!( + result + .expect_err("cancellation must interrupt the writer") + .code(), + "cancelled" + ); + assert!( + elapsed < Duration::from_millis(400), + "the foreground writer did not join inside the single stored cutoff: {elapsed:?}" + ); + assert_eq!( + processes.active_stdin_workers(), + 0, + "the foreground writer must really be joined, not merely abandoned" + ); + let observed = processes + .stdin_close_cutoff_for_test(&spawned.handle) + .expect("the foreground writer must record the cutoff it closed against"); + assert_eq!( + observed, cutoff, + "the foreground writer must close against the stored cutoff, never a 200 ms floor" + ); + + processes.cancel_all(); + let _ = processes.shutdown_all(); +} + +#[test] +fn shutdown_installs_one_cutoff_before_the_teardown_lock_and_the_stdin_writer_observes_it() { + let fixture = Fixture::new("p4-stdin-cutoff"); + let executor = Arc::new( + McpToolExecutor::new( + McpToolExecutorConfig::new(&fixture.root) + .with_max_output_bytes(512) + .with_process_cleanup_timeout(Duration::from_millis(600)), + ) + .expect("executor"), + ); + let background = executor + .execute_tool( + Some("p4-stdin-background"), + "terminal", + &json!({ + "argv": ["/bin/sh", "-c", "sleep 30"], + "background": true, + "stdin": "s".repeat(512 * 1024) + }), + ) + .expect("background dispatch"); + assert!(background.ok, "background receipt: {background:?}"); + let stdin_handle = background.data["process_id"] + .as_str() + .expect("background process handle") + .to_string(); + wait_until("a real stdin writer is stalled on the child pipe", || { + executor.pending_initial_stdin_writers_for_test() >= 1 + }); + + let guard = executor.hold_teardown_for_test(); + let shutdown = { + let executor = Arc::clone(&executor); + std::thread::spawn(move || { + let started = Instant::now(); + let proof = executor.shutdown(); + (started.elapsed(), proof) + }) + }; + wait_until("the absolute teardown cutoff is fixed", || { + executor.executor_cleanup_cutoff_for_test().is_some() + }); + let core_cutoff = executor + .executor_cleanup_cutoff_for_test() + .expect("core cutoff"); + assert_eq!( + executor.process_cleanup_cutoff_for_test(), + Some(core_cutoff), + "the process table and every retained participant must receive the cutoff before the teardown lock" + ); + drop(guard); + let (elapsed, _proof) = shutdown.join().expect("shutdown thread"); + assert!( + elapsed < Duration::from_millis(900), + "the stalled stdin writer escaped the absolute shutdown budget: {elapsed:?}" + ); + let worker_cutoff = executor + .stdin_worker_cutoff_for_test(&stdin_handle) + .expect("the interrupted stdin worker must record its close cutoff"); + assert_eq!( + worker_cutoff, core_cutoff, + "the interrupted stdin worker must close against the stored absolute cutoff" + ); + + let started = Instant::now(); + drop(executor); + assert!( + started.elapsed() < Duration::from_millis(500), + "the destructor restarted an ordinary grace instead of reusing the installed cutoff" + ); +} + +#[test] +fn spawn_converted_during_closing_uses_the_absolute_shutdown_cutoff() { + let fixture = Fixture::new("p4-convert-cutoff"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle_with_call_cancel(&fixture.root, Arc::clone(&cancel)); + let processes = Arc::new( + ProcessCapability::new_with_table_limits( + lifecycle.clone(), + owner.clone(), + ProcessLimits::default(), + ProcessTableLimits::new(1, 1, Duration::from_millis(600)).expect("table limits"), + ) + .expect("processes"), + ); + processes.stall_tree_cleanup_for_test(); + let spawn_gate = Arc::new(SeamGate::default()); + processes.set_after_os_spawn_hook({ + let gate = Arc::clone(&spawn_gate); + Arc::new(move || gate.block()) + }); + let conversion_gate = Arc::new(SeamGate::default()); + processes.set_after_closing_conversion_hook({ + let gate = Arc::clone(&conversion_gate); + Arc::new(move || gate.block()) + }); + let token = prepare_token( + &lifecycle, + &owner, + "p4-convert-cutoff", + CapabilityRisk::Execute, + ); + let spawner = { + let processes = Arc::clone(&processes); + let token = token.clone(); + std::thread::spawn(move || { + processes.spawn( + &token, + &["/bin/sleep".to_string(), "30".to_string()], + "", + &[], + ProcessLimits { + timeout_ms: 10_000, + close_after_initial: false, + ..ProcessLimits::default() + }, + ) + }) + }; + spawn_gate.wait_started(); + let shutdown = { + let processes = Arc::clone(&processes); + std::thread::spawn(move || { + processes.shutdown_all_within(Instant::now() + Duration::from_millis(150)) + }) + }; + std::thread::sleep(Duration::from_millis(100)); + spawn_gate.release(); + conversion_gate.wait_started(); + let released_at = Instant::now(); + conversion_gate.release(); + let spawner = spawner.join().expect("spawn thread"); + let conversion_elapsed = released_at.elapsed(); + assert!( + conversion_elapsed < Duration::from_millis(350), + "the child converted during closing started a fresh table grace instead of the absolute cutoff: {conversion_elapsed:?}" + ); + assert_eq!( + spawner + .expect_err("closing must refuse the converted spawn") + .code(), + "capability_unavailable" + ); + let _ = shutdown.join().expect("shutdown thread"); +} + +#[test] +fn round5_shutdown_reuses_the_stored_cutoff_for_the_interrupted_stdin_worker() { + let fixture = Fixture::new("r5-stdin-cutoff"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle_with_call_cancel(&fixture.root, Arc::clone(&cancel)); + let processes = Arc::new( + ProcessCapability::new_with_table_limits( + lifecycle.clone(), + owner.clone(), + ProcessLimits { + stdin_limit: 1024 * 1024, + ..ProcessLimits::default() + }, + ProcessTableLimits::new(1, 1, Duration::from_millis(600)).expect("table limits"), + ) + .expect("processes"), + ); + let token = prepare_token( + &lifecycle, + &owner, + "r5-stdin-cutoff", + CapabilityRisk::Execute, + ); + let spawned = processes + .spawn_with( + &token, + &[ + "/bin/sh".to_string(), + "-c".to_string(), + "sleep 30".to_string(), + ], + "", + &[], + ProcessLimits { + timeout_ms: 10_000, + stdin_limit: 1024 * 1024, + close_after_initial: false, + ..ProcessLimits::default() + }, + Some(&vec![b's'; 512 * 1024]), + ) + .expect("background spawn"); + wait_until("the stdin writer stalls on the child pipe", || { + processes.pending_initial_stdin_writers_for_test() >= 1 + }); + + // Keep the record retained after the first bounded pass so the retry can + // prove it reused the stored cutoff rather than the later argument. + processes.withhold_cleanup_proof_for_test(); + let stored = Instant::now() + Duration::from_millis(600); + let shutdown = { + let processes = Arc::clone(&processes); + std::thread::spawn(move || processes.shutdown_all_within(stored)) + }; + // Read the observation while the handle is still retained, before the + // teardown can retire it. + wait_until( + "the first teardown observes the stdin worker cutoff", + || { + processes + .stdin_close_cutoff_for_test(&spawned.handle) + .is_some() + }, + ); + let first_observation = processes + .stdin_close_cutoff_for_test(&spawned.handle) + .expect("the first teardown must observe the stdin worker cutoff"); + assert_eq!( + first_observation, stored, + "the first teardown must hand its absolute cutoff to the stdin worker" + ); + let _ = shutdown.join().expect("shutdown thread"); + assert_eq!( + processes.table_len(), + 1, + "a withheld proof must retain the record for the retry" + ); + + // A later teardown argument must not replace the already stored cutoff. + let later = stored + Duration::from_millis(800); + let _ = processes.shutdown_all_within(later); + let interrupted = processes + .stdin_close_cutoff_for_test(&spawned.handle) + .expect("the interrupted stdin worker cutoff"); + assert_eq!( + interrupted, stored, + "the later teardown must reuse the stored absolute cutoff, not its argument" + ); + processes.allow_cleanup_proof_for_test(); + let _ = processes.shutdown_all_within(later); +} + +#[test] +fn executor_drop_reuses_the_first_absolute_cutoff() { + let fixture = Fixture::new("p4-drop-cutoff"); + let executor = McpToolExecutor::new( + McpToolExecutorConfig::new(&fixture.root) + .with_process_cleanup_timeout(Duration::from_millis(150)), + ) + .expect("executor"); + let background = executor + .execute_tool( + Some("p4-drop-background"), + "terminal", + &json!({"argv": ["/bin/sleep", "30"], "background": true}), + ) + .expect("background dispatch"); + assert!(background.ok, "background receipt: {background:?}"); + executor.withhold_process_cleanup_proof_for_test(); + let first = executor.shutdown(); + assert!(!first.is_clean(), "withheld proof: {first:?}"); + let started = Instant::now(); + drop(executor); + let elapsed = started.elapsed(); + assert!( + elapsed < Duration::from_millis(120), + "the destructor started a fresh cleanup budget instead of reusing the absolute cutoff: {elapsed:?}" + ); +} + +#[test] +fn bounded_destructor_never_restarts_the_stored_cleanup_budget() { + let fixture = Fixture::new("p4-destructor"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle_with_call_cancel(&fixture.root, Arc::clone(&cancel)); + let processes = rustscript_agent::capabilities::ProcessCapability::new_with_table_limits( + lifecycle.clone(), + owner.clone(), + rustscript_agent::capabilities::ProcessLimits::default(), + rustscript_agent::capabilities::ProcessTableLimits::new(1, 1, Duration::from_millis(200)) + .expect("table limits"), + ) + .expect("processes"); + processes.stall_tree_cleanup_for_test(); + let token = prepare_token(&lifecycle, &owner, "p4-destructor", CapabilityRisk::Execute); + let spawned = processes + .spawn( + &token, + &["/bin/sleep".to_string(), "30".to_string()], + "", + &[], + rustscript_agent::capabilities::ProcessLimits { + timeout_ms: 5_000, + close_after_initial: false, + ..rustscript_agent::capabilities::ProcessLimits::default() + }, + ) + .expect("spawn"); + let cutoff = Instant::now() + Duration::from_millis(150); + let started = Instant::now(); + let proof = processes.shutdown_all_within(cutoff); + let elapsed = started.elapsed(); + assert!( + matches!(proof, ProcessCleanupProof::TimedOut { retained } if retained >= 1), + "the withheld tree proof must be a retained timeout: {proof:?}" + ); + assert!( + elapsed >= Duration::from_millis(140) && elapsed < Duration::from_secs(1), + "the teardown must stop at its cutoff: {elapsed:?}" + ); + + let started = Instant::now(); + // The uncommitted call's token owns a process reaper, so the retained + // handle is released when the lifecycle itself drops. Both drops still + // belong to the same absolute cutoff. + drop(processes); + drop(lifecycle); + drop(owner); + let drop_elapsed = started.elapsed(); + assert!( + drop_elapsed < Duration::from_millis(500), + "the destructor restarted a fresh cleanup budget: {drop_elapsed:?}" + ); + // The destructor keeps an unproven tree under its exit-sweep record and + // hands it to the bounded reclaimer. Reclamation is asynchronous, so the + // final disappearance is asserted within a bounded grace rather than at + // the drop instant. + let gone_deadline = Instant::now() + Duration::from_secs(5); + while std::path::Path::new(&format!("/proc/{}", spawned.pid)).exists() { + assert!( + Instant::now() < gone_deadline, + "the killed child must be reclaimed by the destructor path: pid={}", + spawned.pid + ); + std::thread::sleep(Duration::from_millis(20)); + } +} + +#[test] +fn bounded_shutdown_does_not_block_on_an_in_progress_ordinary_drain_join() { + let fixture = Fixture::new("p4-join"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle_with_call_cancel(&fixture.root, Arc::clone(&cancel)); + let processes = Arc::new( + rustscript_agent::capabilities::ProcessCapability::new_with_table_limits( + lifecycle.clone(), + owner.clone(), + rustscript_agent::capabilities::ProcessLimits::default(), + rustscript_agent::capabilities::ProcessTableLimits::new( + 1, + 1, + Duration::from_millis(200), + ) + .expect("table limits"), + ) + .expect("processes"), + ); + let gate = Arc::new(SeamGate::default()); + processes.set_drain_join_observer_for_test({ + let gate = Arc::clone(&gate); + Arc::new(move || gate.block()) + }); + let token = prepare_token(&lifecycle, &owner, "p4-join", CapabilityRisk::Execute); + let spawned = processes + .spawn( + &token, + &["/bin/sleep".to_string(), "30".to_string()], + "", + &[], + rustscript_agent::capabilities::ProcessLimits { + timeout_ms: 5_000, + close_after_initial: false, + ..rustscript_agent::capabilities::ProcessLimits::default() + }, + ) + .expect("spawn"); + let killer = { + let processes = Arc::clone(&processes); + let token = token.clone(); + let handle = spawned.handle.clone(); + std::thread::spawn(move || { + let _ = processes.kill(&token, &handle); + }) + }; + gate.wait_started(); + + let started = Instant::now(); + let proof = processes.shutdown_all_within(Instant::now() + Duration::from_millis(150)); + let elapsed = started.elapsed(); + assert!( + !proof.is_clean(), + "a bounded teardown cannot inherit another owner's pending join: {proof:?}" + ); + assert!( + elapsed < Duration::from_millis(700), + "the bounded teardown waited for the ordinary join: {elapsed:?}" + ); + + gate.release(); + killer.join().expect("killer thread"); + let retry = processes.shutdown_all_within(Instant::now() + Duration::from_secs(2)); + assert_eq!( + retry, + ProcessCleanupProof::Clean, + "the completed ordinary join must support a later clean proof" + ); +} + +#[test] +fn minimum_cap_foreground_deadline_keeps_the_error_and_artifact_identity() { + let fixture = Fixture::new("p5-cap"); + let executor = + McpToolExecutor::new(McpToolExecutorConfig::new(&fixture.root).with_max_output_bytes(512)) + .expect("minimum safe cap constructs"); + let stdout = "x".repeat(256); + let script = format!("printf '{stdout}'; exec sleep 30"); + let result = executor + .execute_tool( + Some("p5-deadline"), + "terminal", + &json!({"argv": ["/bin/sh", "-c", script], "timeout_ms": 250}), + ) + .expect("terminal dispatch"); + assert!( + !result.ok, + "the foreground timeout must stay a typed failure: {result:?}" + ); + let code = result + .error + .as_ref() + .map(|error| error.code.as_str()) + .unwrap_or(""); + assert_eq!( + code, "deadline_elapsed", + "the canonical deadline semantics must survive the minimum cap: {result:?}" + ); + assert_eq!( + result.artifacts.len(), + 1, + "the canonical artifact reference must survive: {result:?}" + ); + assert_eq!( + result.artifacts[0].len(), + 36, + "the artifact identity must stay canonical: {result:?}" + ); + assert!( + result.truncated, + "the bounded receipt must remain marked truncated: {result:?}" + ); + let encoded = serde_json::to_vec(&result).expect("serialize canonical receipt"); + assert!( + encoded.len() <= 512, + "the canonical receipt must fit the configured minimum ({} bytes): {result:?}", + encoded.len() + ); + assert_eq!( + executor.committed_token_count(), + 1, + "the bounded deadline receipt must commit exactly once" + ); + let outcome = executor.shutdown(); + assert!( + outcome.is_clean() || matches!(outcome, ProcessCleanupProof::TimedOut { retained: 1 }), + "the adapter cleanup must stay typed: {outcome:?}" + ); +} + +#[test] +fn round5_per_call_deadline_commits_the_exact_returned_snapshot() { + let fixture = Fixture::new("r5-snapshot"); + let executor = Arc::new( + McpToolExecutor::new( + McpToolExecutorConfig::new(&fixture.root) + .with_max_output_bytes(512) + .with_call_timeout(Duration::from_secs(2)) + .with_epoch_check_interval_for_test(1), + ) + .expect("executor"), + ); + // Hold the worker after the OS spawn record has crossed the publication + // fence. The per-call VM deadline elapses while it is held, so the VM stops + // after the effect published but before the guest can commit. + let gate = Arc::new(SeamGate::default()); + executor.processes_for_test().set_after_os_spawn_hook({ + let gate = Arc::clone(&gate); + Arc::new(move || gate.block()) + }); + let worker = { + let executor = Arc::clone(&executor); + std::thread::spawn(move || { + executor.execute_tool( + Some("r5-snapshot"), + "terminal", + &json!({"argv": ["/bin/sh", "-c", "sleep 5"]}), + ) + }) + }; + gate.wait_started(); + std::thread::sleep(Duration::from_millis(2300)); + gate.release(); + + let result = worker.join().expect("worker").expect("receipt"); + assert_eq!( + result.error.as_ref().map(|error| error.code.as_str()), + Some("deadline_elapsed"), + "the per-call deadline must remain the returned outcome: {result:?}" + ); + assert_eq!( + result.data["effect"], + json!("process_spawn"), + "the returned result must be the typed ledger snapshot: {result:?}" + ); + assert!( + result.data["process_state"].is_string(), + "the returned snapshot must carry the observed process state: {result:?}" + ); + let committed = executor + .durable_committed_receipt_for_test("r5-snapshot") + .expect("the guard must commit the caller's snapshot"); + assert_eq!( + serde_json::to_value(&result).expect("serialize returned result"), + serde_json::to_value(&committed).expect("serialize committed snapshot"), + "settlement must commit the exact snapshot the executor returned" + ); + assert_eq!( + committed.error.as_ref().map(|error| error.code.as_str()), + Some("deadline_elapsed"), + "the durable snapshot must not be recomputed to a success: {committed:?}" + ); + assert_eq!(executor.open_token_count(), 0); + assert_eq!(executor.committed_token_count(), 1); + executor.shutdown(); +} + +#[test] +fn round5_published_token_checks_admission_at_the_effect_boundary() { + let fixture = Fixture::new("r5-boundary"); + let cancel = Arc::new(AtomicBool::new(false)); + let owner = CapabilityOwner::new("sol-lifecycle", "session", "run").expect("owner"); + let lifecycle = CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry") + .workspace(&fixture.root) + .limits(LifecycleLimits { + max_tool_calls: 32, + max_output_bytes: 8192, + max_summary_bytes: 256, + }) + .deadline_ms(SystemClock.now_ms().saturating_add(60_000)) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(Arc::new(NoopDurable) as Arc) + .approval( + Arc::new(AllowAllApproval) as Arc + ) + .cancellation(Arc::new(FlagCancelled(Arc::clone(&cancel))) as Arc) + .call_cancellation(Arc::new(ManualCall(Arc::new(AtomicBool::new(false)))) + as Arc) + .build() + .expect("lifecycle"); + let filesystem = FilesystemCapability::new( + lifecycle.clone(), + owner.clone(), + FilesystemLimits::default(), + ) + .expect("filesystem"); + let token = prepare_token(&lifecycle, &owner, "r5-boundary", CapabilityRisk::Write); + + // The first effect publishes its own fence. A later effect must still pass + // the admission checks at its own effect boundary, even though the token + // has already published once. + filesystem + .write_atomic(&token, "r5-first.txt", "*", b"first\n") + .expect("first published write"); + let gate = Arc::new(SeamGate::default()); + filesystem.inject_during_staging({ + let gate = Arc::clone(&gate); + Arc::new(move || gate.block()) + }); + let second = { + let filesystem = filesystem.clone(); + let token = token.clone(); + std::thread::spawn(move || { + filesystem.write_atomic(&token, "r5-second.txt", "*", b"second\n") + }) + }; + gate.wait_started(); + cancel.store(true, Ordering::SeqCst); + gate.release(); + + let error = second + .join() + .expect("second worker") + .expect_err("a later effect must observe the run cancellation at its boundary"); + assert_eq!( + error.code(), + "cancelled", + "the effect boundary must refuse the later write: {error:?}" + ); + assert!( + !fixture.root.join("r5-second.txt").exists(), + "a refused later effect must not replace the destination" + ); +} + +#[test] +fn settlement_commit_refuses_a_receipt_superseded_by_a_later_publisher() { + let fixture = Fixture::new("r8-settle-race"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle_with_call_cancel(&fixture.root, cancel); + let artifacts = + ArtifactCapability::new(lifecycle.clone(), owner.clone(), ArtifactLimits::default()) + .expect("artifacts"); + let token = prepare_token(&lifecycle, &owner, "r8-settle-race", CapabilityRisk::Write); + lifecycle + .enter_publication(&token) + .expect("first publication") + .published_effect( + rustscript_agent::capabilities::NativeEffectRecord::artifact_store( + rustscript_agent::capabilities::NativeArtifactIdentity { + id: "first-artifact".to_string(), + len: 4, + hash: "hash".to_string(), + }, + ), + ); + // The caller captured this receipt and its ledger versions before the + // later publisher was admitted; the decision must refuse it as stale. + let prepared = lifecycle.bind_caller_receipt( + "r8-settle-race", + serde_json::from_value(typed_success_receipt()).expect("typed receipt"), + ); + let gate = Arc::new(SeamGate::default()); + lifecycle.inject_settle_snapshot_observer_for_test({ + let gate = Arc::clone(&gate); + Arc::new(move || gate.block()) + }); + let (tx, rx) = std::sync::mpsc::channel(); + let settler = { + let lifecycle = lifecycle.clone(); + let prepared = prepared.clone(); + std::thread::spawn(move || { + let _ = tx.send(lifecycle.settle_call_with_call_receipt("r8-settle-race", &prepared)); + }) + }; + gate.wait_started(); + // The settlement already took its snapshot and released the fence. A + // later effect of the same call is admitted and records itself before the + // snapshot receipt reaches the final commit. + artifacts + .put_result(&token, b"late-artifact", &json!({})) + .expect("later publisher must be admitted after the snapshot"); + gate.release(); + let settlement = rx + .recv_timeout(Duration::from_secs(5)) + .expect("settlement must finish bounded") + .expect("settlement"); + assert_eq!( + settlement.committed, 0, + "a receipt predating a later effect must not commit: {settlement:?}" + ); + assert!( + settlement.retained >= 1, + "the superseded token must stay open for a retry: {settlement:?}" + ); + assert_eq!(lifecycle.committed_token_count(), 0); + assert_eq!(lifecycle.open_token_count(), 1); + settler.join().expect("settler"); + + // Once the later effect is part of the ledger, the owner's retry settles + // the call exactly once. + let retried = lifecycle + .settle_call_with_receipt("r8-settle-race", Some(&success_receipt())) + .expect("retry settlement"); + assert_eq!(retried.committed, 1); + assert_eq!(lifecycle.open_token_count(), 0); +} + +#[test] +fn settlement_receipt_is_bound_to_the_ledger_version_it_sampled() { + let fixture = Fixture::new("r8-settle-version"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle_with_call_cancel(&fixture.root, cancel); + let token = prepare_token( + &lifecycle, + &owner, + "r8-settle-version", + CapabilityRisk::Write, + ); + lifecycle + .enter_publication(&token) + .expect("first publication") + .published_effect( + rustscript_agent::capabilities::NativeEffectRecord::artifact_store( + rustscript_agent::capabilities::NativeArtifactIdentity { + id: "version-artifact".to_string(), + len: 4, + hash: "hash".to_string(), + }, + ), + ); + let prepared = lifecycle.bind_caller_receipt( + "r8-settle-version", + serde_json::from_value(typed_success_receipt()).expect("typed receipt"), + ); + let gate = Arc::new(SeamGate::default()); + lifecycle.inject_settle_snapshot_observer_for_test({ + let gate = Arc::clone(&gate); + Arc::new(move || gate.block()) + }); + let (tx, rx) = std::sync::mpsc::channel(); + let settler = { + let lifecycle = lifecycle.clone(); + let prepared = prepared.clone(); + std::thread::spawn(move || { + let _ = + tx.send(lifecycle.settle_call_with_call_receipt("r8-settle-version", &prepared)); + }) + }; + gate.wait_started(); + // A later publisher is admitted and retires without recording an effect. + // The pending count is back to zero and the effect list is unchanged, so + // only the ledger version proves the receipt's snapshot is stale. + let later = lifecycle + .enter_publication(&token) + .expect("later admission after the snapshot"); + drop(later); + gate.release(); + let settlement = rx + .recv_timeout(Duration::from_secs(5)) + .expect("settlement must finish bounded") + .expect("settlement"); + assert_eq!( + settlement.committed, 0, + "a receipt from an older ledger version must not commit: {settlement:?}" + ); + assert!( + settlement.retained >= 1, + "the stale token must stay open for a retry: {settlement:?}" + ); + assert_eq!(lifecycle.open_token_count(), 1); + settler.join().expect("settler"); + + let retried = lifecycle + .settle_call_with_receipt("r8-settle-version", Some(&success_receipt())) + .expect("retry settlement"); + assert_eq!(retried.committed, 1); + assert_eq!(lifecycle.open_token_count(), 0); +} + +#[test] +fn settlement_closure_is_atomic_with_admission() { + let fixture = Fixture::new("r8-settle-atomic"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle_with_call_cancel(&fixture.root, cancel); + let token = prepare_token( + &lifecycle, + &owner, + "r8-settle-atomic", + CapabilityRisk::Write, + ); + lifecycle + .enter_publication(&token) + .expect("first publication") + .published_effect( + rustscript_agent::capabilities::NativeEffectRecord::artifact_store( + rustscript_agent::capabilities::NativeArtifactIdentity { + id: "atomic-artifact".to_string(), + len: 4, + hash: "hash".to_string(), + }, + ), + ); + // A later publisher copies the fence, passes its first admission check and + // parks before re-locking the fence. + let admission_gate = Arc::new(SeamGate::default()); + lifecycle.inject_admission_recheck_observer_for_test({ + let gate = Arc::clone(&admission_gate); + Arc::new(move || gate.block()) + }); + let (tx_admission, rx_admission) = std::sync::mpsc::channel(); + let admission = { + let lifecycle = lifecycle.clone(); + let token = token.clone(); + std::thread::spawn(move || { + let _ = tx_admission.send(lifecycle.enter_publication(&token)); + }) + }; + admission_gate.wait_started(); + // The settlement validates its snapshot and parks while holding the fence. + let commit_gate = Arc::new(SeamGate::default()); + lifecycle.inject_settle_commit_observer_for_test({ + let gate = Arc::clone(&commit_gate); + Arc::new(move || gate.block()) + }); + let (tx_settlement, rx_settlement) = std::sync::mpsc::channel(); + let settler = { + let lifecycle = lifecycle.clone(); + std::thread::spawn(move || { + let _ = tx_settlement.send( + lifecycle.settle_call_with_receipt("r8-settle-atomic", Some(&success_receipt())), + ); + }) + }; + commit_gate.wait_started(); + admission_gate.release(); + // Give the copied-fence publisher time to reach the fence the settlement + // still holds. + std::thread::sleep(Duration::from_millis(50)); + commit_gate.release(); + let settlement = rx_settlement + .recv_timeout(Duration::from_secs(5)) + .expect("settlement must finish bounded") + .expect("settlement"); + let admission_result = rx_admission + .recv_timeout(Duration::from_secs(5)) + .expect("admission must finish bounded"); + assert!( + matches!(admission_result, Err(LifecycleError::Interrupted)), + "admission must be refused by the closed fence, not race the receipt commit" + ); + assert_eq!( + settlement.committed, 1, + "the settled receipt must commit exactly once: {settlement:?}" + ); + assert_eq!(lifecycle.open_token_count(), 0); + admission.join().expect("admission"); + settler.join().expect("settler"); +} + +#[test] +fn unpublished_settlement_never_lets_a_publisher_lose_its_token() { + let fixture = Fixture::new("r10-unpublished-gap"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle_with_call_cancel(&fixture.root, cancel); + let token = prepare_token( + &lifecycle, + &owner, + "r10-unpublished-gap", + CapabilityRisk::Write, + ); + // A publisher copies the fence and parks before locking it. + let copy_gate = Arc::new(SeamGate::default()); + lifecycle.inject_publisher_copy_observer_for_test({ + let gate = Arc::clone(©_gate); + Arc::new(move || gate.block()) + }); + // Settlement parks at its unpublished decision. The fix keeps the fence + // held here, so the publisher cannot enter while the token closes. + let settle_gate = Arc::new(SeamGate::default()); + lifecycle.inject_settle_unpublished_observer_for_test({ + let gate = Arc::clone(&settle_gate); + Arc::new(move || gate.block()) + }); + let (tx_admission, rx_admission) = std::sync::mpsc::channel(); + let publisher = { + let lifecycle = lifecycle.clone(); + let token = token.clone(); + std::thread::spawn(move || { + let _ = tx_admission.send(lifecycle.enter_publication(&token)); + }) + }; + copy_gate.wait_started(); + let (tx_settlement, rx_settlement) = std::sync::mpsc::channel(); + let settler = { + let lifecycle = lifecycle.clone(); + std::thread::spawn(move || { + let _ = + tx_settlement.send(lifecycle.settle_call_with_receipt("r10-unpublished-gap", None)); + }) + }; + settle_gate.wait_started(); + copy_gate.release(); + // Give the publisher the chance to take the fence the settlement is + // holding. With the fence held continuously it blocks here. + std::thread::sleep(Duration::from_millis(50)); + settle_gate.release(); + let settlement = rx_settlement + .recv_timeout(Duration::from_secs(5)) + .expect("settlement must finish bounded") + .expect("settlement"); + let admission_result = rx_admission + .recv_timeout(Duration::from_secs(5)) + .expect("admission must finish bounded"); + match admission_result { + Ok(permit) => { + drop(permit); + assert_eq!( + settlement.interrupted, 0, + "a publisher that entered the fence must keep its token, not lose it to interruption: {settlement:?}" + ); + } + Err(LifecycleError::Interrupted) => { + assert_eq!( + settlement.interrupted, 1, + "the settlement owns the unpublished decision: {settlement:?}" + ); + assert_eq!(lifecycle.open_token_count(), 0); + } + Err(other) => panic!("unexpected admission error: {other:?}"), + } + publisher.join().expect("publisher"); + settler.join().expect("settler"); +} + +#[test] +fn admission_rechecks_generation_after_a_cleared_recovery_claim() { + let fixture = Fixture::new("r8-admission-recheck"); + let owner = CapabilityOwner::new("sol-lifecycle", "session", "admission").expect("owner"); + let cancel = Arc::new(AtomicBool::new(false)); + let lifecycle = CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry") + .workspace(&fixture.root) + .limits(LifecycleLimits { + max_tool_calls: 8, + max_output_bytes: 8192, + max_summary_bytes: 256, + }) + .deadline_ms(SystemClock.now_ms().saturating_add(60_000)) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(Arc::new(NoopDurable) as Arc) + .approval( + Arc::new(AllowAllApproval) as Arc + ) + .cancellation(Arc::new(NeverCancelled) as Arc) + .call_cancellation(Arc::new(ManualCall(cancel)) as Arc) + .build() + .expect("lifecycle"); + let token = prepare_token(&lifecycle, &owner, "r8-admission", CapabilityRisk::Write); + lifecycle + .enter_publication(&token) + .expect("first publication") + .published_effect( + rustscript_agent::capabilities::NativeEffectRecord::artifact_store( + rustscript_agent::capabilities::NativeArtifactIdentity { + id: "admission-artifact".to_string(), + len: 4, + hash: "hash".to_string(), + }, + ), + ); + let gate = Arc::new(SeamGate::default()); + lifecycle.inject_admission_recheck_observer_for_test({ + let gate = Arc::clone(&gate); + Arc::new(move || gate.block()) + }); + // Recovery is parked after it cleared its per-call claim but before it + // advanced the generation: exactly the window the generation-only + // revalidation could not cover. + let recovery_gate = Arc::new(SeamGate::default()); + lifecycle.inject_recovery_pre_generation_observer_for_test({ + let gate = Arc::clone(&recovery_gate); + Arc::new(move || gate.block()) + }); + let (tx, rx) = std::sync::mpsc::channel(); + let admission = { + let lifecycle = lifecycle.clone(); + let token = token.clone(); + std::thread::spawn(move || { + let _ = tx.send(lifecycle.enter_publication(&token)); + }) + }; + gate.wait_started(); + let recovered = { + let lifecycle = lifecycle.clone(); + std::thread::spawn(move || lifecycle.recover_open_tokens()) + }; + recovery_gate.wait_started(); + // The recovery claim was released by its guard at the end of the call + // iteration; the token is already interrupted and the generation has not + // moved yet. + assert_eq!(lifecycle.interrupted_token_count(), 1); + gate.release(); + let result = rx + .recv_timeout(Duration::from_secs(5)) + .expect("admission must finish bounded"); + assert!( + matches!(result, Err(LifecycleError::Interrupted)), + "a cleared claim on a settled fence must not resume admission before the generation bump" + ); + recovery_gate.release(); + let recovered = recovered.join().expect("recovery"); + assert_eq!( + recovered.expect("recovery"), + vec!["r8-admission".to_string()] + ); + admission.join().expect("admission"); + assert_eq!(lifecycle.interrupted_token_count(), 1); +} + +#[test] +fn round5_abort_does_not_interrupt_or_retract_a_published_artifact() { + let fixture = Fixture::new("r5-abort-published"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle_with_call_cancel_and_policy( + &fixture.root, + Arc::clone(&cancel), + rustscript_agent::capabilities::PublishedTokenPolicy::RetainForSettlement, + ); + let artifacts = + ArtifactCapability::new(lifecycle.clone(), owner.clone(), ArtifactLimits::default()) + .expect("artifacts"); + let token = prepare_token( + &lifecycle, + &owner, + "r5-abort-published", + CapabilityRisk::Read, + ); + let published = artifacts + .put_result(&token, b"published payload\n", &json!({})) + .expect("publish artifact"); + + // The shared guest lease is the abort path. A token that already crossed + // the publication fence must keep its effect and its right to settle. + drop(lifecycle.lease(&token).expect("abort lease")); + assert_eq!( + lifecycle.interrupted_token_count(), + 0, + "an abort must not interrupt a published token" + ); + assert_eq!( + lifecycle.open_token_count(), + 1, + "the published token must stay open for settlement" + ); + assert!( + artifacts.stored(&published.id).is_some(), + "the already inserted artifact must not be retracted by abort" + ); + assert_eq!(artifacts.stored_len(), 1); + let settlement = lifecycle + .settle_call_with_receipt("r5-abort-published", Some(&success_receipt())) + .expect("settle published token"); + assert_eq!(settlement.committed, 1); + assert_eq!(lifecycle.open_token_count(), 0); +} + +struct FlakyInterruptDurable { + calls: Mutex>, + fail_next: AtomicBool, +} + +impl FlakyInterruptDurable { + fn failing_once() -> Self { + Self { + calls: Mutex::new(Vec::new()), + fail_next: AtomicBool::new(true), + } + } + + fn calls(&self) -> Vec { + self.calls + .lock() + .unwrap_or_else(|error| error.into_inner()) + .clone() + } +} + +impl DurableToolLifecycle for FlakyInterruptDurable { + fn assert_active_run(&self, _run_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } + + fn prepare_parent( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result<(), LifecycleError> { + Ok(()) + } + + fn replay_result( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result, LifecycleError> { + Ok(None) + } + + fn commit_started(&self, _record: &DurableStarted) -> Result<(), LifecycleError> { + Ok(()) + } + + fn commit_result(&self, _call_id: &str, result: &Value) -> Result { + Ok(result.clone()) + } + + fn interrupt(&self, call_id: &str) -> Result<(), LifecycleError> { + self.calls + .lock() + .unwrap_or_else(|error| error.into_inner()) + .push(call_id.to_string()); + if self.fail_next.swap(false, Ordering::SeqCst) { + Err(LifecycleError::ResultCommitFailed( + "interrupt storage failed".to_string(), + )) + } else { + Ok(()) + } + } +} + +#[test] +fn round5_recovery_retries_after_a_partial_interrupt_failure() { + let fixture = Fixture::new("r5-recovery-retry"); + let owner = CapabilityOwner::new("sol-lifecycle", "session", "run").expect("owner"); + let durable = Arc::new(FlakyInterruptDurable::failing_once()); + let lifecycle = CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry") + .workspace(&fixture.root) + .limits(LifecycleLimits { + max_tool_calls: 8, + max_output_bytes: 8192, + max_summary_bytes: 256, + }) + .deadline_ms(SystemClock.now_ms().saturating_add(60_000)) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(Arc::clone(&durable) as Arc) + .approval( + Arc::new(AllowAllApproval) as Arc + ) + .cancellation(Arc::new(NeverCancelled) as Arc) + // Retry-after-interrupt-failure is the MCP retention contract. The + // managed/default policy transitions before durable I/O and does not + // retry, exactly as the base `e9da5dc` did. + .published_token_policy( + rustscript_agent::capabilities::PublishedTokenPolicy::RetainForSettlement, + ) + .build() + .expect("lifecycle"); + let _token = prepare_token( + &lifecycle, + &owner, + "r5-recovery-retry", + CapabilityRisk::Read, + ); + let first = lifecycle + .recover_open_tokens() + .expect_err("the durable interrupt must fail once"); + assert!(matches!(first, LifecycleError::ResultCommitFailed(_))); + assert_eq!( + lifecycle.open_token_count(), + 1, + "a failed durable interrupt must leave the token open and retryable" + ); + assert_eq!(lifecycle.interrupted_token_count(), 0); + assert_eq!(durable.calls(), vec!["r5-recovery-retry".to_string()]); + + let recovered = lifecycle + .recover_open_tokens() + .expect("the retry must succeed"); + assert_eq!(recovered, vec!["r5-recovery-retry".to_string()]); + assert_eq!(lifecycle.open_token_count(), 0); + assert_eq!(lifecycle.interrupted_token_count(), 1); + assert_eq!(durable.calls().len(), 2); +} + +#[test] +fn default_managed_recovery_transitions_before_durable_interrupt_io() { + let fixture = Fixture::new("r10-managed-order"); + let owner = CapabilityOwner::new("sol-lifecycle", "session", "managed-order").expect("owner"); + let durable = Arc::new(FlakyInterruptDurable::failing_once()); + let lifecycle = CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry") + .workspace(&fixture.root) + .limits(LifecycleLimits { + max_tool_calls: 8, + max_output_bytes: 8192, + max_summary_bytes: 256, + }) + .deadline_ms(SystemClock.now_ms().saturating_add(60_000)) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(Arc::clone(&durable) as Arc) + .approval( + Arc::new(AllowAllApproval) as Arc + ) + .cancellation(Arc::new(NeverCancelled) as Arc) + .build() + .expect("lifecycle"); + let _token = prepare_token( + &lifecycle, + &owner, + "r10-managed-order", + CapabilityRisk::Read, + ); + let error = lifecycle + .recover_open_tokens() + .expect_err("the durable interrupt must fail once"); + assert!(matches!(error, LifecycleError::ResultCommitFailed(_))); + assert_eq!( + lifecycle.open_token_count(), + 0, + "managed/base recovery transitions the token before the durable write" + ); + assert_eq!(lifecycle.interrupted_token_count(), 1); + assert_eq!(durable.calls(), vec!["r10-managed-order".to_string()]); + let retried = lifecycle + .recover_open_tokens() + .expect("no token remains to retry"); + assert!( + retried.is_empty(), + "base recovery must not retry {retried:?}" + ); + assert_eq!( + durable.calls().len(), + 1, + "a failed managed interrupt must not be retried by a later close" + ); +} + +#[test] +fn published_token_retention_is_enabled_only_by_the_mcp_executor() { + let fixture = Fixture::new("r6-retention-mode"); + let executor = + McpToolExecutor::new(McpToolExecutorConfig::new(&fixture.root)).expect("executor"); + assert!( + executor.retains_published_tokens_for_test(), + "the standalone MCP executor must retain published tokens" + ); + let cancel = Arc::new(AtomicBool::new(false)); + let (managed, _) = lifecycle_with_call_cancel(&fixture.root, cancel); + assert!( + !managed.retains_published_tokens(), + "the managed/agent-run lifecycle must keep base abort semantics" + ); + executor.shutdown(); +} + +#[test] +fn pending_commit_write_reports_retained_to_a_concurrent_settler() { + let fixture = Fixture::new("r13-pending-commit"); + let durable = Arc::new(StallingDurable::new()); + let (lifecycle, owner) = lifecycle_with_durable( + &fixture.root, + Arc::clone(&durable) as Arc, + rustscript_agent::capabilities::PublishedTokenPolicy::RetainForSettlement, + ); + let call_id = "r13-pending-commit"; + let token = prepare_token(&lifecycle, &owner, call_id, CapabilityRisk::Write); + lifecycle + .enter_publication(&token) + .expect("publication") + .published_effect(NativeEffectRecord::artifact_store(NativeArtifactIdentity { + id: "r13-commit-effect".to_string(), + len: 4, + hash: "hash".to_string(), + })); + let gate = Arc::new(SeamGate::default()); + durable.stall_commit(Arc::clone(&gate)); + let settler = { + let lifecycle = lifecycle.clone(); + std::thread::spawn(move || { + lifecycle.settle_call_terminal(call_id, CallTerminalRequest::Derived) + }) + }; + gate.wait_started(); + // The durable write is entered and not yet acknowledged. Publishers are + // fenced, and a second settler must see retained ownership. + let blocked = match lifecycle.enter_publication(&token) { + Ok(_) => panic!("publishers must be fenced while the terminal write is pending"), + Err(error) => error, + }; + assert!( + matches!(blocked, LifecycleError::Interrupted), + "{blocked:?}" + ); + let concurrent = lifecycle + .settle_call_terminal(call_id, CallTerminalRequest::Derived) + .expect("concurrent settlement"); + assert_eq!( + concurrent.decision, + CallTerminalDecision::Retained, + "a pending durable write is not terminal: {concurrent:?}" + ); + assert_eq!( + concurrent.retained, 1, + "the pending token must still count as retained ownership: {concurrent:?}" + ); + assert!( + concurrent.result.is_some(), + "a retained decision must carry the pending receipt disposition: {concurrent:?}" + ); + assert_eq!(durable.commit_count(), 1); + gate.release(); + let first = settler.join().expect("settler").expect("first settlement"); + assert_eq!(first.decision, CallTerminalDecision::Committed); + assert_eq!(first.committed, 1); + assert_eq!(durable.commit_count(), 1); + assert_eq!(lifecycle.open_token_count(), 0); + assert_eq!(lifecycle.committed_token_count(), 1); + let after = lifecycle + .settle_call_terminal(call_id, CallTerminalRequest::Derived) + .expect("post-acknowledgement settlement"); + assert_eq!(after.decision, CallTerminalDecision::NoOp); + assert_eq!(after.retained, 0); +} + +#[test] +fn pending_interrupt_write_reports_retained_to_a_concurrent_settler() { + let fixture = Fixture::new("r13-pending-interrupt"); + let durable = Arc::new(StallingDurable::new()); + let (lifecycle, owner) = lifecycle_with_durable( + &fixture.root, + Arc::clone(&durable) as Arc, + rustscript_agent::capabilities::PublishedTokenPolicy::RetainForSettlement, + ); + let call_id = "r13-pending-interrupt"; + let token = prepare_token(&lifecycle, &owner, call_id, CapabilityRisk::Read); + let gate = Arc::new(SeamGate::default()); + durable.stall_interrupt(Arc::clone(&gate)); + let settler = { + let lifecycle = lifecycle.clone(); + std::thread::spawn(move || { + lifecycle.settle_call_terminal(call_id, CallTerminalRequest::Derived) + }) + }; + gate.wait_started(); + let blocked = match lifecycle.enter_publication(&token) { + Ok(_) => panic!("publishers must be fenced while the terminal write is pending"), + Err(error) => error, + }; + assert!( + matches!(blocked, LifecycleError::Interrupted), + "{blocked:?}" + ); + let concurrent = lifecycle + .settle_call_terminal(call_id, CallTerminalRequest::Derived) + .expect("concurrent settlement"); + assert_eq!( + concurrent.decision, + CallTerminalDecision::Retained, + "a pending durable interrupt is not terminal: {concurrent:?}" + ); + assert_eq!(concurrent.retained, 1); + assert_eq!(durable.interrupt_count(), 1); + gate.release(); + let first = settler.join().expect("settler").expect("first settlement"); + assert_eq!(first.decision, CallTerminalDecision::Interrupted); + assert_eq!(first.interrupted, 1); + assert_eq!(durable.interrupt_count(), 1); + assert_eq!(lifecycle.open_token_count(), 0); + assert_eq!(lifecycle.interrupted_token_count(), 1); + assert_eq!(durable.commit_count(), 0); + let after = lifecycle + .settle_call_terminal(call_id, CallTerminalRequest::Derived) + .expect("post-acknowledgement settlement"); + assert_eq!(after.decision, CallTerminalDecision::NoOp); + assert_eq!(after.retained, 0); +} + +#[test] +fn retained_synthetic_disposition_is_bound_inside_the_decision() { + let fixture = Fixture::new("r13-binding-window"); + let durable = Arc::new(RecordingDurable::default()); + let (lifecycle, owner) = lifecycle_with_durable( + &fixture.root, + Arc::clone(&durable) as Arc, + rustscript_agent::capabilities::PublishedTokenPolicy::RetainForSettlement, + ); + let call_id = "r13-binding-window"; + let token = prepare_token(&lifecycle, &owner, call_id, CapabilityRisk::Write); + // A publisher has entered the fence but has not recorded its effect yet. + let publisher = lifecycle + .enter_publication(&token) + .expect("publisher permit"); + let synthetic = json!(ToolResult::failure( + "internal_error", + "tool call ended without a canonical result" + )); + let retained = lifecycle + .settle_call_terminal(call_id, CallTerminalRequest::Synthetic(&synthetic)) + .expect("retained settlement"); + assert_eq!(retained.decision, CallTerminalDecision::Retained); + assert_eq!(retained.retained, 1); + let disposition = retained.result.expect( + "the retained decision must bind its synthetic disposition inside the decision critical section", + ); + // The publication lands after the decision, in the former external binding + // window. The bound disposition must no longer describe the ledger. + publisher.published_effect(NativeEffectRecord::artifact_store(NativeArtifactIdentity { + id: "r13-late-effect".to_string(), + len: 4, + hash: "hash".to_string(), + })); + let stale = lifecycle + .settle_call_with_call_receipt(call_id, &disposition) + .expect("stale retry"); + assert_eq!( + stale.retained, 1, + "synthetic bytes must not settle a later publication: {stale:?}" + ); + assert_eq!(stale.committed, 0); + assert_eq!(durable.commit_count(), 0); + let fresh = lifecycle + .settle_call_terminal(call_id, CallTerminalRequest::Derived) + .expect("fresh settlement"); + assert_eq!(fresh.decision, CallTerminalDecision::Committed); + let committed = durable.result(call_id).expect("durable receipt"); + let typed: ToolResult = serde_json::from_value(committed).expect("typed receipt"); + assert!(typed.ok); + assert_eq!(typed.artifacts, vec!["r13-late-effect".to_string()]); + assert_ne!( + typed.error.as_ref().map(|error| error.code.as_str()), + Some("internal_error"), + "a late publication must never be frozen with the fallback bytes" + ); +} + +#[test] +fn retention_guest_commit_retains_while_a_later_publisher_holds_a_permit() { + let fixture = Fixture::new("r13-guest-later"); + let durable = Arc::new(RecordingDurable::default()); + let (lifecycle, owner) = lifecycle_with_durable( + &fixture.root, + Arc::clone(&durable) as Arc, + rustscript_agent::capabilities::PublishedTokenPolicy::RetainForSettlement, + ); + let call_id = "r13-guest-later"; + let token = prepare_token(&lifecycle, &owner, call_id, CapabilityRisk::Write); + lifecycle + .enter_publication(&token) + .expect("first publication") + .published_effect(NativeEffectRecord::artifact_store(NativeArtifactIdentity { + id: "r13-guest-effect".to_string(), + len: 4, + hash: "hash".to_string(), + })); + let later = lifecycle + .enter_publication(&token) + .expect("later publisher permit"); + let error = lifecycle + .commit(&owner, &token, success_receipt()) + .expect_err("a held publisher permit must block the guest commit"); + assert_eq!(error.code(), "commit_retained", "{error:?}"); + assert_eq!( + durable.commit_count(), + 0, + "the guest commit must not freeze a receipt while a publisher is in flight" + ); + assert_eq!(lifecycle.open_token_count(), 1); + drop(later); + let settlement = lifecycle + .settle_call_terminal(call_id, CallTerminalRequest::Derived) + .expect("owner settlement"); + assert_eq!(settlement.decision, CallTerminalDecision::Committed); + assert_eq!(settlement.committed, 1); + assert_eq!(durable.commit_count(), 1); + let committed = durable.result(call_id).expect("durable receipt"); + let typed: ToolResult = serde_json::from_value(committed).expect("typed receipt"); + assert!(typed.ok); + assert_eq!(typed.artifacts, vec!["r13-guest-effect".to_string()]); +} + +#[test] +fn retention_guest_commit_retains_while_the_first_publisher_is_in_flight() { + let fixture = Fixture::new("r13-guest-first"); + let durable = Arc::new(RecordingDurable::default()); + let (lifecycle, owner) = lifecycle_with_durable( + &fixture.root, + Arc::clone(&durable) as Arc, + rustscript_agent::capabilities::PublishedTokenPolicy::RetainForSettlement, + ); + let artifacts = + ArtifactCapability::new(lifecycle.clone(), owner.clone(), ArtifactLimits::default()) + .expect("artifacts"); + let call_id = "r13-guest-first"; + let token = prepare_token(&lifecycle, &owner, call_id, CapabilityRisk::Read); + let gate = Arc::new(SeamGate::default()); + artifacts.inject_before_publish({ + let gate = Arc::clone(&gate); + Arc::new(move || gate.block()) + }); + let worker = { + let artifacts = artifacts.clone(); + let token = token.clone(); + std::thread::spawn(move || artifacts.put_result(&token, b"published payload\n", &json!({}))) + }; + gate.wait_started(); + let error = lifecycle + .commit(&owner, &token, success_receipt()) + .expect_err("an in-flight first publisher must block the guest commit"); + assert_eq!(error.code(), "commit_retained", "{error:?}"); + assert_eq!(durable.commit_count(), 0); + gate.release(); + let published = worker.join().expect("worker").expect("published artifact"); + let settlement = lifecycle + .settle_call_terminal(call_id, CallTerminalRequest::Derived) + .expect("owner settlement"); + assert_eq!(settlement.decision, CallTerminalDecision::Committed); + assert_eq!(durable.commit_count(), 1); + let committed = durable.result(call_id).expect("durable receipt"); + let typed: ToolResult = serde_json::from_value(committed).expect("typed receipt"); + assert!(typed.ok); + assert_eq!(typed.artifacts, vec![published.id]); +} + +#[test] +fn raw_settlement_receipt_is_persisted_as_a_round_trippable_typed_result() { + let fixture = Fixture::new("r13-raw-receipt"); + let durable = Arc::new(RecordingDurable::default()); + let (lifecycle, owner) = lifecycle_with_durable( + &fixture.root, + Arc::clone(&durable) as Arc, + rustscript_agent::capabilities::PublishedTokenPolicy::RetainForSettlement, + ); + let call_id = "r13-raw-receipt"; + let token = prepare_token(&lifecycle, &owner, call_id, CapabilityRisk::Write); + lifecycle + .enter_publication(&token) + .expect("publication") + .published_effect(NativeEffectRecord::artifact_store(NativeArtifactIdentity { + id: "r13-raw-effect".to_string(), + len: 4, + hash: "hash".to_string(), + })); + // This is canonical enough for `validate_canonical_result` but not a + // complete typed `ToolResult`. The raw path used to persist it verbatim + // while returning a typed internal_error. + let raw = json!({"ok": true, "content": "accepted"}); + let settlement = lifecycle + .settle_call_with_receipt(call_id, Some(&raw)) + .expect("raw settlement"); + assert_eq!(settlement.committed, 1); + let committed = durable.result(call_id).expect("durable payload"); + let typed: ToolResult = serde_json::from_value(committed.clone()) + .expect("the persisted payload must round-trip through a strict typed replay"); + assert!(typed.ok, "{typed:?}"); + assert_eq!(typed.content, "accepted"); + let receipt = settlement.result.expect("settlement receipt"); + assert_eq!( + receipt.encoded(), + &committed, + "the returned bytes and the persisted bytes must be identical" + ); +} + +#[test] +fn recovery_cannot_settle_a_call_while_a_later_artifact_insertion_is_in_flight() { + let fixture = Fixture::new("r7-pending-publisher"); + let owner = CapabilityOwner::new("sol-lifecycle", "session", "pending").expect("owner"); + let durable = Arc::new(RecordingDurable::default()); + let lifecycle = CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry") + .workspace(&fixture.root) + .limits(LifecycleLimits { + max_tool_calls: 8, + max_output_bytes: 8192, + max_summary_bytes: 256, + }) + .deadline_ms(SystemClock.now_ms().saturating_add(60_000)) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(durable.clone() as Arc) + .approval( + Arc::new(AllowAllApproval) as Arc + ) + .cancellation(Arc::new(NeverCancelled) as Arc) + .published_token_policy( + rustscript_agent::capabilities::PublishedTokenPolicy::RetainForSettlement, + ) + .build() + .expect("lifecycle"); + let processes = Arc::new( + ProcessCapability::new_with_table_limits( + lifecycle.clone(), + owner.clone(), + ProcessLimits::default(), + ProcessTableLimits::new(1, 1, Duration::from_millis(300)).expect("table limits"), + ) + .expect("processes"), + ); + let artifacts = + ArtifactCapability::new(lifecycle.clone(), owner.clone(), ArtifactLimits::default()) + .expect("artifacts"); + let token = prepare_token(&lifecycle, &owner, "pending-call", CapabilityRisk::Execute); + processes + .spawn( + &token, + &[ + "/bin/sh".to_string(), + "-c".to_string(), + "exit 0".to_string(), + ], + "", + &[], + ProcessLimits { + timeout_ms: 5_000, + close_after_initial: true, + ..ProcessLimits::default() + }, + ) + .expect("spawned process record"); + + // The process record is already published; the artifact insertion is a + // later effect of the same call and is held inside its publication fence. + let gate = Arc::new(SeamGate::default()); + artifacts.inject_before_publish({ + let gate = Arc::clone(&gate); + Arc::new(move || gate.block()) + }); + let worker = { + let artifacts = artifacts.clone(); + let token = token.clone(); + std::thread::spawn(move || artifacts.put_result(&token, b"late artifact\n", &json!({}))) + }; + gate.wait_started(); + + let recovered = lifecycle + .recover_open_tokens() + .expect("recovery must leave an in-flight publisher alone"); + assert!( + recovered.is_empty(), + "recovery must not settle a stale ledger: {recovered:?}" + ); + assert_eq!( + lifecycle.pending_recovery_calls(), + vec!["pending-call".to_string()], + "the in-flight call must be reported as pending for the owner to retry" + ); + assert_eq!( + lifecycle.open_token_count(), + 1, + "the call must stay open while its insertion is in flight" + ); + assert!( + durable.result("pending-call").is_none(), + "recovery must not write a receipt that omits the in-flight artifact" + ); + + gate.release(); + let stored = worker + .join() + .expect("artifact worker") + .expect("artifact insertion must complete"); + + let recovered = lifecycle + .recover_open_tokens() + .expect("recovery must settle the retired publisher"); + assert_eq!(recovered, vec!["pending-call".to_string()]); + assert_eq!(lifecycle.open_token_count(), 0); + let committed = durable + .result("pending-call") + .expect("the settled receipt must include the inserted artifact"); + assert!( + committed["artifacts"] + .as_array() + .is_some_and(|artifacts| artifacts.iter().any(|id| id == &json!(stored.id))), + "the receipt must carry the artifact inserted after the process record: {committed}" + ); +} + +/// Durable whose `commit_started` can park one call id, so a second call can +/// prove its own token operations do not wait behind that persistence. +#[derive(Default)] +struct PreparingDurable { + starts: AtomicUsize, + stalled_call: Mutex>, + start_gate: Mutex>>, +} + +impl PreparingDurable { + fn stall_start(&self, call_id: &str, gate: Arc) { + *self + .stalled_call + .lock() + .unwrap_or_else(|error| error.into_inner()) = Some(call_id.to_string()); + *self + .start_gate + .lock() + .unwrap_or_else(|error| error.into_inner()) = Some(gate); + } + + fn start_count(&self) -> usize { + self.starts.load(Ordering::SeqCst) + } +} + +impl DurableToolLifecycle for PreparingDurable { + fn assert_active_run(&self, _run_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } + + fn prepare_parent( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result<(), LifecycleError> { + Ok(()) + } + + fn replay_result( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result, LifecycleError> { + Ok(None) + } + + fn commit_started(&self, record: &DurableStarted) -> Result<(), LifecycleError> { + self.starts.fetch_add(1, Ordering::SeqCst); + let stalled = self + .stalled_call + .lock() + .unwrap_or_else(|error| error.into_inner()) + .clone(); + if stalled.as_deref() == Some(record.call_id.as_str()) { + let gate = self + .start_gate + .lock() + .unwrap_or_else(|error| error.into_inner()) + .clone(); + if let Some(gate) = gate { + gate.block(); + } + } + Ok(()) + } + + fn commit_result(&self, _call_id: &str, result: &Value) -> Result { + Ok(result.clone()) + } + + fn interrupt(&self, _call_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } +} + +#[test] +fn undecided_pending_interrupt_never_creates_an_authoritative_fallback() { + let fixture = Fixture::new("r14-pending-authority"); + let durable = Arc::new(StallingDurable::new()); + let (lifecycle, owner) = lifecycle_with_durable( + &fixture.root, + Arc::clone(&durable) as Arc, + rustscript_agent::capabilities::PublishedTokenPolicy::RetainForSettlement, + ); + let call_id = "r14-pending-authority"; + let token = prepare_token(&lifecycle, &owner, call_id, CapabilityRisk::Write); + // A derived interrupt is in flight. It publishes nothing, so the pending + // decision stored no retry receipt. + let gate = Arc::new(SeamGate::default()); + durable.stall_interrupt(Arc::clone(&gate)); + durable.fail_interrupt_after_gate(); + let settler = { + let lifecycle = lifecycle.clone(); + std::thread::spawn(move || { + lifecycle.settle_call_terminal(call_id, CallTerminalRequest::Derived) + }) + }; + gate.wait_started(); + + let fallback = json!(ToolResult::failure( + "internal_error", + "tool call ended without a canonical result" + )); + let concurrent = lifecycle + .settle_call_terminal(call_id, CallTerminalRequest::Synthetic(&fallback)) + .expect("concurrent settlement"); + assert_eq!( + concurrent.decision, + CallTerminalDecision::Retained, + "a pending interrupt is retained ownership, not a decision: {concurrent:?}" + ); + assert_eq!(concurrent.retained, 1); + let disposition = concurrent.result.clone(); + + // The pending interrupt fails and the fence reopens. + gate.release(); + let interrupted = settler + .join() + .expect("settler") + .expect_err("the injected interrupt failure must surface"); + assert!(matches!(interrupted, LifecycleError::ResultCommitFailed(_))); + assert_eq!(lifecycle.open_token_count(), 1); + + // A publisher lands in the reopened window, after the concurrent settler + // observed the pending write. + lifecycle + .enter_publication(&token) + .expect("publication after the failed interrupt") + .published_effect(NativeEffectRecord::artifact_store(NativeArtifactIdentity { + id: "r14-authority-effect".to_string(), + len: 4, + hash: "hash".to_string(), + })); + + // Whatever the retained decision handed out must not be able to settle the + // later publication. + if let Some(disposition) = disposition { + let retried = lifecycle + .settle_call_with_call_receipt(call_id, &disposition) + .expect("retry with the retained disposition"); + assert_eq!( + retried.committed, 0, + "an undecided disposition must never commit over a later publication: {retried:?}" + ); + } + + let settlement = lifecycle + .settle_call_terminal(call_id, CallTerminalRequest::Derived) + .expect("derived settlement"); + assert_eq!(settlement.decision, CallTerminalDecision::Committed); + let committed = durable.result(call_id).expect("durable receipt"); + let typed: ToolResult = serde_json::from_value(committed).expect("typed receipt"); + assert!( + typed.ok, + "the native effect, not the synthetic fallback, must be the receipt: {typed:?}" + ); + assert_eq!(typed.artifacts, vec!["r14-authority-effect".to_string()]); +} + +/// Publisher that holds one dispatched call's permit across the guest +/// `tool_commit` and records a native effect in the decision window. +/// +/// The first seam proves the host refuses the guest commit while a publisher +/// holds the permit. The second seam finishes the publication after the +/// refusal is decided but before the executor's own settlement, so the +/// executor observes a completed ledger rather than a pending write. +struct DispatchPublisher { + permit_gate: Arc, + published_gate: Arc, + handle: Arc>>>, +} + +impl DispatchPublisher { + fn install(lifecycle: &Arc, effect_id: &'static str) -> Self { + Self::install_with(lifecycle, effect_id, true) + } + + /// Variant that keeps the publisher inside its permit until [`Self::finish`], + /// so the executor's own settlement observes a genuinely in-flight start. + fn install_in_flight(lifecycle: &Arc, effect_id: &'static str) -> Self { + Self::install_with(lifecycle, effect_id, false) + } + + fn install_with( + lifecycle: &Arc, + effect_id: &'static str, + release_at_decision: bool, + ) -> Self { + let permit_gate = Arc::new(SeamGate::default()); + let published_gate = Arc::new(SeamGate::default()); + let handle = Arc::new(Mutex::new(None::>)); + lifecycle.inject_commit_attempt_observer_for_test({ + let lifecycle = Arc::clone(lifecycle); + let permit_gate = Arc::clone(&permit_gate); + let published_gate = Arc::clone(&published_gate); + let handle = Arc::clone(&handle); + Arc::new(move |token: &str| { + let token = token.to_string(); + let worker = { + let lifecycle = Arc::clone(&lifecycle); + let permit_gate = Arc::clone(&permit_gate); + let published_gate = Arc::clone(&published_gate); + std::thread::spawn(move || { + let permit = lifecycle + .enter_publication(&token) + .expect("publisher permit"); + // Held while the guest commit is decided. + permit_gate.block(); + permit.published_effect(NativeEffectRecord::artifact_store( + NativeArtifactIdentity { + id: effect_id.to_string(), + len: 4, + hash: "hash".to_string(), + }, + )); + published_gate.block(); + }) + }; + *handle.lock().unwrap_or_else(|error| error.into_inner()) = Some(worker); + permit_gate.wait_started(); + }) + }); + if release_at_decision { + lifecycle.inject_commit_decision_observer_for_test({ + let permit_gate = Arc::clone(&permit_gate); + let published_gate = Arc::clone(&published_gate); + Arc::new(move |_token: &str| { + permit_gate.release(); + published_gate.wait_started(); + }) + }); + } + Self { + permit_gate, + published_gate, + handle, + } + } + + fn finish(&self) { + self.permit_gate.release(); + self.published_gate.release(); + self.handle + .lock() + .unwrap_or_else(|error| error.into_inner()) + .take() + .expect("publisher") + .join() + .expect("publisher"); + } +} + +fn dispatch_terminal(executor: &McpToolExecutor, call_id: &str) -> ToolResult { + executor + .execute_tool( + Some(call_id), + "terminal", + &json!({"argv": ["/bin/sh", "-c", "printf ready"], "timeout_ms": 1000}), + ) + .expect("terminal dispatch") +} + +#[test] +fn terminal_dispatch_refusal_is_settled_by_the_native_receipt_once() { + let fixture = Fixture::new("r14-rss-refusal"); + let executor = + McpToolExecutor::new(McpToolExecutorConfig::new(&fixture.root)).expect("executor"); + let lifecycle = Arc::clone(executor.lifecycle_for_test()); + let call_id = "r14-rss-refusal"; + let publisher = DispatchPublisher::install(&lifecycle, "r14-native-effect"); + + let result = dispatch_terminal(&executor, call_id); + assert!( + result.ok, + "the native receipt, never the refused commit envelope, is the call result: {result:?}" + ); + assert_eq!( + result.artifacts, + vec!["r14-native-effect".to_string()], + "the committed receipt must be the live ledger derivation" + ); + assert_eq!( + executor.durable_commit_count_for_test(), + 1, + "the call must write exactly one durable receipt" + ); + let committed = executor + .durable_committed_receipt_for_test(call_id) + .expect("native receipt"); + assert!(committed.ok, "{committed:?}"); + assert_eq!(committed.artifacts, vec!["r14-native-effect".to_string()]); + assert_ne!( + committed.error.as_ref().map(|error| error.code.as_str()), + Some("interrupted"), + "the refused commit bytes must never become the durable receipt" + ); + assert_eq!(executor.committed_token_count(), 1); + + publisher.finish(); + + // A later teardown must not write a second receipt for the same call. + let _ = executor.shutdown(); + assert_eq!(executor.durable_commit_count_for_test(), 1); + assert_eq!(executor.open_token_count(), 0); +} + +#[test] +fn settlement_failure_retries_the_native_receipt_not_dispatch_bytes() { + let fixture = Fixture::new("r14-settlement-retry"); + let executor = + McpToolExecutor::new(McpToolExecutorConfig::new(&fixture.root)).expect("executor"); + let lifecycle = Arc::clone(executor.lifecycle_for_test()); + let call_id = "r14-settlement-retry"; + let publisher = DispatchPublisher::install(&lifecycle, "r14-retry-effect"); + // The guest commit is refused before any durable write, so this injected + // failure lands on the executor's own settlement. + executor.fail_next_durable_commit_for_test(); + + let error = executor + .execute_tool( + Some(call_id), + "terminal", + &json!({"argv": ["/bin/sh", "-c", "printf ready"], "timeout_ms": 1000}), + ) + .expect_err("a deferred guest commit must not become the caller's terminal result"); + assert_eq!( + error.code(), + "retained", + "the caller observes the retained disposition, not the refusal bytes: {error:?}" + ); + + publisher.finish(); + + // The guard's retry owns the reopened token and must derive the native + // receipt instead of rebinding the dispatch bytes through a second read. + executor.settle_retained_for_test(); + let committed = executor + .durable_committed_receipt_for_test(call_id) + .expect("the retry must commit the native receipt"); + assert!( + committed.ok, + "dispatch bytes must not overwrite the published effect: {committed:?}" + ); + assert_eq!(committed.artifacts, vec!["r14-retry-effect".to_string()]); + assert_ne!( + committed.error.as_ref().map(|error| error.code.as_str()), + Some("commit_retained"), + "the host refusal must never become the durable receipt" + ); + assert_eq!(executor.durable_commit_count_for_test(), 1); + let _ = executor.shutdown(); + assert_eq!(executor.durable_commit_count_for_test(), 1); +} + +#[test] +fn terminal_dispatch_refusal_reports_retained_until_the_publisher_finishes() { + let fixture = Fixture::new("r15-rss-retained"); + let executor = + McpToolExecutor::new(McpToolExecutorConfig::new(&fixture.root)).expect("executor"); + let lifecycle = Arc::clone(executor.lifecycle_for_test()); + let call_id = "r15-rss-retained"; + let publisher = DispatchPublisher::install_in_flight(&lifecycle, "r15-retained-effect"); + + let error = executor + .execute_tool( + Some(call_id), + "terminal", + &json!({"argv": ["/bin/sh", "-c", "printf ready"], "timeout_ms": 1000}), + ) + .expect_err("a refused guest commit is never the caller's terminal result"); + assert_eq!( + error.code(), + "retained", + "the caller sees the retained disposition while the publisher holds its permit: {error:?}" + ); + assert_eq!( + executor.open_token_count(), + 1, + "the call must stay retained until its publisher settles" + ); + assert_eq!( + executor.durable_commit_count_for_test(), + 0, + "no receipt may be written before the publisher finishes" + ); + + publisher.finish(); + + // Once the publisher finishes, the retained disposition settles the native + // ledger receipt for the call. + executor.settle_retained_for_test(); + let committed = executor + .durable_committed_receipt_for_test(call_id) + .expect("the settled native receipt"); + assert!(committed.ok, "{committed:?}"); + assert_eq!(committed.artifacts, vec!["r15-retained-effect".to_string()]); + assert_eq!(executor.durable_commit_count_for_test(), 1); + let _ = executor.shutdown(); + assert_eq!(executor.durable_commit_count_for_test(), 1); +} + +#[test] +fn prepare_persistence_does_not_block_another_calls_token_operation() { + let fixture = Fixture::new("r14-prepare-split"); + let durable = Arc::new(PreparingDurable::default()); + let (lifecycle, owner) = lifecycle_with_durable( + &fixture.root, + Arc::clone(&durable) as Arc, + rustscript_agent::capabilities::PublishedTokenPolicy::RetainForSettlement, + ); + let gate = Arc::new(SeamGate::default()); + durable.stall_start("call-a", Arc::clone(&gate)); + let first = { + let lifecycle = lifecycle.clone(); + let owner = owner.clone(); + std::thread::spawn(move || { + prepare_token(&lifecycle, &owner, "call-a", CapabilityRisk::Read) + }) + }; + gate.wait_started(); + + // A different call's prepare must complete while call-a's durable start is + // still in flight. + let completed = Arc::new(AtomicBool::new(false)); + let probe = { + let lifecycle = lifecycle.clone(); + let owner = owner.clone(); + let completed = Arc::clone(&completed); + std::thread::spawn(move || { + let token = prepare_token(&lifecycle, &owner, "call-b", CapabilityRisk::Read); + completed.store(true, Ordering::SeqCst); + token + }) + }; + let deadline = Instant::now() + Duration::from_secs(5); + while !completed.load(Ordering::SeqCst) { + assert!( + Instant::now() < deadline, + "a second call's prepare must not wait behind another call's durable start" + ); + std::thread::sleep(Duration::from_millis(5)); + } + + gate.release(); + let token_a = first.join().expect("first prepare"); + let token_b = probe.join().expect("probe prepare"); + assert_ne!(token_a, token_b); + assert_eq!(lifecycle.open_token_count(), 2); + assert_eq!( + durable.start_count(), + 2, + "each admitted call persists exactly one durable start" + ); +} + +#[test] +fn settlement_observes_an_in_flight_start_as_retained() { + let fixture = Fixture::new("r15-start-settle"); + let durable = Arc::new(PreparingDurable::default()); + let (lifecycle, owner) = lifecycle_with_durable( + &fixture.root, + Arc::clone(&durable) as Arc, + rustscript_agent::capabilities::PublishedTokenPolicy::RetainForSettlement, + ); + let call_id = "r15-start-settle"; + let gate = Arc::new(SeamGate::default()); + durable.stall_start(call_id, Arc::clone(&gate)); + let preparer = { + let lifecycle = lifecycle.clone(); + let owner = owner.clone(); + std::thread::spawn(move || prepare_token(&lifecycle, &owner, call_id, CapabilityRisk::Read)) + }; + gate.wait_started(); + + // The token does not exist yet, but the call is already owned by the + // durable start. Settlement must report that retained ownership instead of + // NoOp and must not hand out a receipt the start never bound. + let settlement = lifecycle + .settle_call_terminal(call_id, CallTerminalRequest::Derived) + .expect("settlement while the durable start is in flight"); + assert_eq!( + settlement.decision, + CallTerminalDecision::Retained, + "an in-flight start is retained ownership: {settlement:?}" + ); + assert_eq!(settlement.retained, 1); + assert!(settlement.result.is_none()); + assert_eq!( + lifecycle.open_token_count(), + 1, + "the start reservation counts as open ownership" + ); + + gate.release(); + let token = preparer.join().expect("prepare thread"); + assert!(!token.is_empty()); + + let settled = lifecycle + .settle_call_terminal(call_id, CallTerminalRequest::Derived) + .expect("settlement after the start acknowledged"); + assert_eq!(settled.decision, CallTerminalDecision::Interrupted); + assert_eq!(lifecycle.open_token_count(), 0); +} + +#[test] +fn recovery_reports_an_in_flight_start_as_pending() { + let fixture = Fixture::new("r15-start-recovery"); + let durable = Arc::new(PreparingDurable::default()); + let (lifecycle, owner) = lifecycle_with_durable( + &fixture.root, + Arc::clone(&durable) as Arc, + rustscript_agent::capabilities::PublishedTokenPolicy::RetainForSettlement, + ); + let call_id = "r15-start-recovery"; + let gate = Arc::new(SeamGate::default()); + durable.stall_start(call_id, Arc::clone(&gate)); + let preparer = { + let lifecycle = lifecycle.clone(); + let owner = owner.clone(); + std::thread::spawn(move || prepare_token(&lifecycle, &owner, call_id, CapabilityRisk::Read)) + }; + gate.wait_started(); + + let recovered = lifecycle + .recover_open_tokens() + .expect("recovery must not fail while a start is in flight"); + assert!( + recovered.is_empty(), + "no token exists to settle yet: {recovered:?}" + ); + assert_eq!( + lifecycle.pending_recovery_calls(), + vec![call_id.to_string()], + "recovery must report the in-flight start as pending work" + ); + + gate.release(); + let token = preparer.join().expect("prepare thread"); + assert!(!token.is_empty()); + assert_eq!( + lifecycle.open_token_count(), + 1, + "the acknowledged start must remain visible for the next recovery" + ); + + let recovered = lifecycle + .recover_open_tokens() + .expect("the retried recovery settles the acknowledged token"); + assert_eq!(recovered, vec![call_id.to_string()]); + assert!(lifecycle.pending_recovery_calls().is_empty()); + assert_eq!(lifecycle.open_token_count(), 0); +} + +#[test] +fn malformed_raw_receipt_is_rejected_before_optional_defaults_are_filled() { + let fixture = Fixture::new("r14-malformed-raw"); + let durable = Arc::new(RecordingDurable::default()); + let (lifecycle, owner) = lifecycle_with_durable( + &fixture.root, + Arc::clone(&durable) as Arc, + rustscript_agent::capabilities::PublishedTokenPolicy::RetainForSettlement, + ); + let call_id = "r14-malformed-raw"; + let token = prepare_token(&lifecycle, &owner, call_id, CapabilityRisk::Write); + lifecycle + .enter_publication(&token) + .expect("publication") + .published_effect(NativeEffectRecord::artifact_store(NativeArtifactIdentity { + id: "r14-malformed-effect".to_string(), + len: 4, + hash: "hash".to_string(), + })); + + // A success without string `content` would normalize to an empty-content + // success and then validate. It must be refused before normalization. + let malformed = json!({"ok": true}); + let error = lifecycle + .settle_call_with_receipt(call_id, Some(&malformed)) + .expect_err("a success without string content is not a canonical receipt"); + assert!( + matches!(error, LifecycleError::InvalidMetadata(_)), + "the rejection must be a typed metadata error: {error:?}" + ); + assert_eq!(durable.commit_count(), 0); + assert!(durable.result(call_id).is_none()); + assert_eq!( + lifecycle.open_token_count(), + 1, + "a rejected receipt must leave the call open for a valid retry" + ); + + // A success payload carrying a typed error is contradictory: the raw + // validator must reject it instead of normalizing the error away and + // committing a success. + let contradictory = json!({ + "ok": true, + "content": "accepted", + "error": {"code": "injected_failure", "message": "must not ride a success"} + }); + let error = lifecycle + .settle_call_with_receipt(call_id, Some(&contradictory)) + .expect_err("a success carrying an error is not a canonical receipt"); + assert!( + matches!(error, LifecycleError::InvalidMetadata(_)), + "the contradiction must be a typed metadata error: {error:?}" + ); + assert_eq!(durable.commit_count(), 0); + assert!(durable.result(call_id).is_none()); + assert_eq!( + lifecycle.open_token_count(), + 1, + "a rejected receipt must leave the call open for a valid retry" + ); + + // The minimal valid canonical payload still settles and round-trips. + let minimal = json!({"ok": true, "content": "accepted"}); + let settlement = lifecycle + .settle_call_with_receipt(call_id, Some(&minimal)) + .expect("minimal valid receipt"); + assert_eq!(settlement.committed, 1); + let committed = durable.result(call_id).expect("durable payload"); + let typed: ToolResult = + serde_json::from_value(committed).expect("strict typed replay of the persisted payload"); + assert!(typed.ok); + assert_eq!(typed.content, "accepted"); +} diff --git a/tests/mcp_sol_publication_settlement_tests.rs b/tests/mcp_sol_publication_settlement_tests.rs new file mode 100644 index 00000000..706f2e7c --- /dev/null +++ b/tests/mcp_sol_publication_settlement_tests.rs @@ -0,0 +1,655 @@ +//! Second Sol re-review regressions for MCP Tasks 3-4. +//! +//! These tests exercise the real capability and executor seams with the APIs +//! that already existed at 36ae6da: a late call cancellation after an +//! irreversible publication must still settle the canonical receipt, process +//! capacity failures are typed, foreground records retire, idle lifetime +//! expiry cleans owned children, and profile-aware output minima admit valid +//! read-only configurations. + +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +use rustscript_agent::capabilities::{ + AllowAllApproval, ArtifactCapability, ArtifactLimits, CallCancellationSource, + CallCancellationState, CancellationFlag, CapabilityLifecycle, CapabilityOwner, CapabilityRisk, + DurableStarted, DurableToolLifecycle, FilesystemCapability, FilesystemLimits, LifecycleClock, + LifecycleError, LifecycleLimits, NeverCancelled, ProcessCapability, ProcessLimits, + ProcessTableLimits, SystemClock, TokenIssuer, UuidIssuer, +}; +use rustscript_agent::mcp::ToolProfile; +use rustscript_agent::mcp::executor::{McpToolExecutor, McpToolExecutorConfig}; +use serde_json::{Value, json}; + +static NEXT_FIXTURE: AtomicU64 = AtomicU64::new(0); + +struct Fixture { + parent: PathBuf, + root: PathBuf, +} + +impl Fixture { + fn new(label: &str) -> Self { + let sequence = NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed); + let parent = std::env::temp_dir().join(format!( + "mcp-sol-settle-{label}-{}-{sequence}", + std::process::id() + )); + let root = parent.join("workspace"); + fs::create_dir_all(&root).expect("create fixture workspace"); + Self { parent, root } + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.parent); + } +} + +struct ManualCall(Arc); + +impl CallCancellationSource for ManualCall { + fn call_state(&self, _call_id: &str) -> CallCancellationState { + if self.0.load(Ordering::SeqCst) { + CallCancellationState::Cancelled + } else { + CallCancellationState::Active + } + } +} + +#[derive(Default)] +struct NoopDurable; + +impl DurableToolLifecycle for NoopDurable { + fn assert_active_run(&self, _run_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } + + fn prepare_parent( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result<(), LifecycleError> { + Ok(()) + } + + fn replay_result( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result, LifecycleError> { + Ok(None) + } + + fn commit_started(&self, _record: &DurableStarted) -> Result<(), LifecycleError> { + Ok(()) + } + + fn commit_result(&self, _call_id: &str, result: &Value) -> Result { + Ok(result.clone()) + } + + fn interrupt(&self, _call_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } +} + +fn lifecycle_with_call_cancel( + root: &Path, + cancel: Arc, +) -> (CapabilityLifecycle, CapabilityOwner) { + let owner = CapabilityOwner::new("sol-final", "session", "run").expect("owner"); + let lifecycle = CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry") + .workspace(root) + .limits(LifecycleLimits { + max_tool_calls: 32, + max_output_bytes: 8192, + max_summary_bytes: 256, + }) + .deadline_ms(SystemClock.now_ms().saturating_add(60_000)) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(Arc::new(NoopDurable) as Arc) + .approval( + Arc::new(AllowAllApproval) as Arc + ) + .cancellation(Arc::new(NeverCancelled) as Arc) + .call_cancellation(Arc::new(ManualCall(cancel)) as Arc) + .build() + .expect("lifecycle"); + (lifecycle, owner) +} + +fn prepare_token( + lifecycle: &CapabilityLifecycle, + owner: &CapabilityOwner, + call_id: &str, + risk: CapabilityRisk, +) -> String { + match lifecycle + .prepare( + owner, + rustscript_agent::capabilities::PrepareMetadata { + run_id: owner.run().to_string(), + call_id: call_id.to_string(), + tool_name: "fixture_tool".to_string(), + argument_digest: "digest".to_string(), + registry_identity: "registry".to_string(), + risk_class: risk, + summary: "fixture".to_string(), + }, + ) + .expect("prepare") + { + rustscript_agent::capabilities::PrepareOutcome::Execute { + execution_token, .. + } => execution_token, + other => panic!("expected execute, got {other:?}"), + } +} + +fn success_receipt() -> Value { + json!({"ok": true, "content": "receipt", "data": {}}) +} + +fn error_code(error: &rustscript_agent::capabilities::CapabilityError) -> &str { + error.code() +} + +#[test] +fn cancellation_before_file_publication_never_writes() { + let fixture = Fixture::new("file-pre-cancel"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle_with_call_cancel(&fixture.root, Arc::clone(&cancel)); + let filesystem = FilesystemCapability::new( + lifecycle.clone(), + owner.clone(), + FilesystemLimits::default(), + ) + .expect("filesystem"); + let token = prepare_token(&lifecycle, &owner, "pre-file", CapabilityRisk::Write); + cancel.store(true, Ordering::SeqCst); + let error = filesystem + .write_atomic(&token, "never.txt", "*", b"no\n") + .expect_err("cancellation before the fence must refuse the rename"); + assert_eq!(error_code(&error), "cancelled"); + assert!(!fixture.root.join("never.txt").exists()); +} + +#[test] +fn cancellation_before_artifact_insertion_never_stores() { + let fixture = Fixture::new("artifact-pre-cancel"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle_with_call_cancel(&fixture.root, Arc::clone(&cancel)); + let artifacts = + ArtifactCapability::new(lifecycle.clone(), owner.clone(), ArtifactLimits::default()) + .expect("artifacts"); + let token = prepare_token(&lifecycle, &owner, "pre-artifact", CapabilityRisk::Read); + cancel.store(true, Ordering::SeqCst); + let error = artifacts + .put_result(&token, b"payload", &json!({})) + .expect_err("cancellation before the fence must refuse the insertion"); + assert_eq!(error_code(&error), "cancelled"); + assert_eq!(artifacts.stored_len(), 0); +} + +#[test] +fn late_call_cancellation_after_file_rename_still_settles_the_receipt() { + let fixture = Fixture::new("file-late-cancel"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle_with_call_cancel(&fixture.root, Arc::clone(&cancel)); + let filesystem = FilesystemCapability::new( + lifecycle.clone(), + owner.clone(), + FilesystemLimits::default(), + ) + .expect("filesystem"); + let token = prepare_token(&lifecycle, &owner, "late-file", CapabilityRisk::Write); + filesystem.inject_after_publish({ + let cancel = Arc::clone(&cancel); + Arc::new(move |_path, _bytes| { + cancel.store(true, Ordering::SeqCst); + false + }) + }); + + let written = filesystem + .write_atomic(&token, "late.txt", "*", b"committed\n") + .expect("the rename is the irreversible publication point"); + assert!(written.hash.len() > 8); + assert_eq!( + fs::read_to_string(fixture.root.join("late.txt")).expect("published file"), + "committed\n" + ); + + // The publication already won. A later effect in the same call must still + // be refused, but that refusal cannot undo the published receipt. + let second = filesystem + .write_atomic(&token, "second.txt", "*", b"no\n") + .expect_err("post-publication operations must stay cancelled"); + assert_eq!(error_code(&second), "cancelled"); + assert!(!fixture.root.join("second.txt").exists()); + + lifecycle + .commit(&owner, &token, success_receipt()) + .expect("a published effect must settle its canonical receipt exactly once"); + assert!(!lifecycle_has_open_tokens(&lifecycle)); +} + +fn lifecycle_has_open_tokens(lifecycle: &CapabilityLifecycle) -> bool { + lifecycle.open_token_count() != 0 +} + +#[test] +fn late_call_cancellation_after_artifact_insertion_still_settles_the_receipt() { + let fixture = Fixture::new("artifact-late-cancel"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle_with_call_cancel(&fixture.root, Arc::clone(&cancel)); + let artifacts = + ArtifactCapability::new(lifecycle.clone(), owner.clone(), ArtifactLimits::default()) + .expect("artifacts"); + let token = prepare_token(&lifecycle, &owner, "late-artifact", CapabilityRisk::Read); + + let stored = artifacts + .put_result(&token, b"payload", &json!({})) + .expect("artifact insertion publishes the result blob"); + assert_eq!(stored.len, 7); + cancel.store(true, Ordering::SeqCst); + + let second = artifacts + .put(&token, b"more", &json!({})) + .expect_err("post-publication artifact operations must stay cancelled"); + assert_eq!(error_code(&second), "cancelled"); + + lifecycle + .commit(&owner, &token, success_receipt()) + .expect("an inserted artifact must retain its receipt after a later cancellation"); + assert_eq!(artifacts.stored_len(), 1); + assert!(artifacts.stored(&stored.id).is_some()); +} + +#[test] +fn late_call_cancellation_after_process_spawn_still_settles_the_receipt() { + let fixture = Fixture::new("process-late-cancel"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle_with_call_cancel(&fixture.root, Arc::clone(&cancel)); + let processes = ProcessCapability::new_with_table_limits( + lifecycle.clone(), + owner.clone(), + ProcessLimits::default(), + ProcessTableLimits::new(4, 4, Duration::from_millis(500)).expect("table limits"), + ) + .expect("processes"); + let token = prepare_token(&lifecycle, &owner, "late-spawn", CapabilityRisk::Execute); + processes.set_after_os_spawn_hook({ + let cancel = Arc::clone(&cancel); + Arc::new(move || cancel.store(true, Ordering::SeqCst)) + }); + + let spawned = processes + .spawn( + &token, + &[ + "/bin/sh".to_string(), + "-c".to_string(), + "exec sleep 30".to_string(), + ], + "", + &[], + ProcessLimits { + timeout_ms: 10_000, + close_after_initial: false, + ..ProcessLimits::default() + }, + ) + .expect("the OS spawn is the irreversible publication point"); + assert!( + Path::new(&format!("/proc/{}", spawned.pid)).exists(), + "published child must remain owned" + ); + + let later = processes + .spawn( + &token, + &["/bin/true".to_string()], + "", + &[], + ProcessLimits::default(), + ) + .expect_err("post-publication process operations must stay cancelled"); + assert_eq!(error_code(&later), "cancelled"); + + lifecycle + .commit(&owner, &token, success_receipt()) + .expect("a spawned child must retain its receipt after a later cancellation"); + let _ = processes.shutdown_all_within(Instant::now() + Duration::from_secs(2)); +} + +#[test] +fn cancellation_before_os_spawn_never_executes_the_program() { + let fixture = Fixture::new("process-pre-cancel"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle_with_call_cancel(&fixture.root, Arc::clone(&cancel)); + let processes = ProcessCapability::new_with_table_limits( + lifecycle.clone(), + owner.clone(), + ProcessLimits::default(), + ProcessTableLimits::new(4, 4, Duration::from_millis(500)).expect("table limits"), + ) + .expect("processes"); + let token = prepare_token(&lifecycle, &owner, "pre-spawn", CapabilityRisk::Execute); + processes.set_before_os_spawn_hook({ + let cancel = Arc::clone(&cancel); + Arc::new(move || cancel.store(true, Ordering::SeqCst)) + }); + + let error = processes + .spawn( + &token, + &[ + "/bin/sh".to_string(), + "-c".to_string(), + "printf executed > spawn-marker.txt".to_string(), + ], + "", + &[], + ProcessLimits::default(), + ) + .expect_err("cancellation winning before publication must refuse the effect"); + assert_eq!(error_code(&error), "cancelled"); + assert!( + !fixture.root.join("spawn-marker.txt").exists(), + "no child may execute after cancellation won the publication fence" + ); + assert_eq!(processes.table_len(), 0); +} + +#[test] +fn repeated_foreground_commands_retire_records_and_recover_capacity() { + let fixture = Fixture::new("foreground-retire"); + let executor = McpToolExecutor::new( + McpToolExecutorConfig::new(&fixture.root) + .with_max_processes(1) + .with_max_processes_per_owner(1), + ) + .expect("construct executor"); + for index in 0..4 { + let result = executor + .execute_tool( + Some(&format!("foreground-{index}")), + "terminal", + &json!({"argv": ["/bin/echo", "hello"]}), + ) + .expect("terminal dispatch"); + assert!( + result.ok, + "foreground command {index} must fit the one-record table: {result:?}" + ); + assert_eq!( + executor.process_table_len(), + 0, + "a completed foreground command must retire its record" + ); + } +} + +#[test] +fn process_capacity_exhaustion_is_a_typed_process_limit_error() { + let fixture = Fixture::new("process-limit-code"); + let executor = McpToolExecutor::new( + McpToolExecutorConfig::new(&fixture.root) + .with_max_processes(1) + .with_max_processes_per_owner(1), + ) + .expect("construct executor"); + let first = executor + .execute_tool( + Some("limit-first"), + "terminal", + &json!({"argv": ["/bin/sleep", "30"], "background": true}), + ) + .expect("terminal dispatch"); + assert!(first.ok, "first child result={first:?}"); + let over = executor + .execute_tool( + Some("limit-second"), + "terminal", + &json!({"argv": ["/bin/sleep", "30"], "background": true}), + ) + .expect("terminal dispatch"); + assert!(!over.ok, "capacity exhaustion must fail: {over:?}"); + assert_eq!( + over.error.as_ref().map(|error| error.code.as_str()), + Some("process_limit"), + "capacity exhaustion must not be reported as invalid stdin: {over:?}" + ); + executor.shutdown(); +} + +#[test] +fn idle_lifetime_expiry_cancels_and_cleans_owned_children_without_a_later_call() { + let fixture = Fixture::new("idle-expiry"); + let executor = McpToolExecutor::new( + McpToolExecutorConfig::new(&fixture.root) + .with_server_lifetime(Duration::from_secs(3)) + .with_process_cleanup_timeout(Duration::from_millis(500)), + ) + .expect("construct executor"); + let spawn = executor + .execute_tool( + Some("idle-child"), + "terminal", + &json!({ + "argv": ["/bin/sh", "-c", "echo $$ > idle.pid; exec sleep 30"], + "background": true, + }), + ) + .expect("terminal dispatch"); + assert!(spawn.ok, "spawn result={spawn:?}"); + let pid = wait_for_pid(&fixture.root.join("idle.pid")); + + // No later tool call: the configured lifetime itself must initiate the + // cancellation and bounded cleanup. + let deadline = Instant::now() + Duration::from_secs(6); + while Instant::now() < deadline && !executor.is_closed() { + std::thread::sleep(Duration::from_millis(10)); + } + assert!( + executor.is_closed(), + "an idle executor must initiate shutdown at its configured lifetime" + ); + while Instant::now() < deadline && executor.process_table_len() != 0 { + std::thread::sleep(Duration::from_millis(10)); + } + assert_eq!( + executor.process_table_len(), + 0, + "idle expiry must clean the owned child table" + ); + assert!( + !Path::new(&format!("/proc/{pid}")).exists(), + "idle expiry must reap the live child" + ); +} + +#[test] +fn read_only_profile_admits_a_512_byte_cap_for_short_results() { + let fixture = Fixture::new("readonly-cap"); + fs::write(fixture.root.join("hello.txt"), "hello\n").expect("write hello"); + let executor = McpToolExecutor::new( + McpToolExecutorConfig::new(&fixture.root) + .with_profile(ToolProfile::ReadOnly) + .with_max_output_bytes(512), + ) + .expect("a read-only 512-byte cap can carry every admitted read receipt"); + let result = executor + .execute_tool( + Some("readonly-short"), + "read_file", + &json!({"path": "hello.txt"}), + ) + .expect("read dispatch"); + assert!(result.ok, "short read result={result:?}"); + assert_eq!(result.content, "hello\n"); + assert!(!result.truncated); + assert!(result.artifacts.is_empty()); +} + +#[test] +fn read_only_profile_admits_its_256_byte_proven_minimum() { + let fixture = Fixture::new("readonly-min"); + fs::write(fixture.root.join("hello.txt"), "hello\n").expect("write hello"); + let executor = McpToolExecutor::new( + McpToolExecutorConfig::new(&fixture.root) + .with_profile(ToolProfile::ReadOnly) + .with_max_output_bytes(256), + ) + .expect("the proven read-only minimum must construct"); + let result = executor + .execute_tool( + Some("readonly-min-read"), + "read_file", + &json!({"path": "hello.txt"}), + ) + .expect("read dispatch"); + assert!(result.ok, "short read result={result:?}"); + assert_eq!(result.content, "hello\n"); + assert!(!result.truncated); +} + +#[test] +fn coding_profile_rejects_a_cap_below_the_effect_receipt_minimum() { + let fixture = Fixture::new("coding-cap"); + let error = match McpToolExecutor::new( + McpToolExecutorConfig::new(&fixture.root) + .with_profile(ToolProfile::Coding) + .with_max_output_bytes(384), + ) { + Ok(_) => panic!("coding mode must reject a cap that cannot hold a committed receipt"), + Err(error) => error, + }; + assert_eq!(error.code(), "invalid_config", "error={error:?}"); + assert!(!fixture.root.join("never-created.txt").exists()); +} + +#[test] +fn minimum_effect_cap_supports_patch_receipts() { + let fixture = Fixture::new("min-patch-output"); + fs::write(fixture.root.join("patch.txt"), "before\n").expect("write patch fixture"); + let executor = + McpToolExecutor::new(McpToolExecutorConfig::new(&fixture.root).with_max_output_bytes(512)) + .expect("minimum effect cap constructs"); + let patched = executor + .execute_tool( + Some("min-cap-patch"), + "patch", + &json!({"path": "patch.txt", "old_string": "before", "new_string": "after"}), + ) + .expect("patch dispatch"); + assert!( + patched.ok, + "patch receipt must fit the minimum effect cap: {patched:?}" + ); + assert_eq!( + fs::read_to_string(fixture.root.join("patch.txt")).expect("read patched file"), + "after\n" + ); +} + +#[test] +fn read_only_512_cap_uses_the_artifact_receipt_path_exactly() { + let fixture = Fixture::new("readonly-large"); + let payload = "abcdefghijklmnopqrstuvwxyz".repeat(64); + fs::write(fixture.root.join("large.txt"), &payload).expect("write large fixture"); + let executor = McpToolExecutor::new( + McpToolExecutorConfig::new(&fixture.root) + .with_profile(ToolProfile::ReadOnly) + .with_max_output_bytes(512), + ) + .expect("read-only minimum cap constructs"); + let result = executor + .execute_tool( + Some("readonly-large-read"), + "read_file", + &json!({"path": "large.txt"}), + ) + .expect("large read dispatch"); + assert!(result.ok, "large read result={result:?}"); + assert!(result.truncated, "artifact receipt must mark truncation"); + assert_eq!( + result.artifacts.len(), + 1, + "read-only large output must publish exactly one artifact: {result:?}" + ); + assert!( + result.content.starts_with("artifact "), + "read-only artifact receipt must be canonical: {result:?}" + ); + assert!( + result + .content + .ends_with(&format!("({} bytes)", payload.len())), + "artifact receipt must report the exact payload size: {result:?}" + ); +} + +#[test] +fn large_read_uses_the_artifact_receipt_path_exactly() { + let fixture = Fixture::new("large-artifact"); + let payload = "abcdefghijklmnopqrstuvwxyz".repeat(128); + fs::write(fixture.root.join("large.txt"), &payload).expect("write large fixture"); + let executor = + McpToolExecutor::new(McpToolExecutorConfig::new(&fixture.root).with_max_output_bytes(512)) + .expect("minimum effect cap constructs"); + let result = executor + .execute_tool( + Some("large-read"), + "read_file", + &json!({"path": "large.txt"}), + ) + .expect("large read dispatch"); + assert!( + result.ok, + "truncation is a successful bounded result: {result:?}" + ); + assert!(result.truncated, "artifact receipt must mark truncation"); + assert_eq!( + result.artifacts.len(), + 1, + "large output must publish exactly one artifact: {result:?}" + ); + assert!( + result.content.starts_with("artifact "), + "artifact receipt content must be canonical: {result:?}" + ); + assert!( + result + .content + .ends_with(&format!("({} bytes)", payload.len())), + "artifact receipt must report the exact payload size: {result:?}" + ); + assert_eq!(result.data["offset"], json!(1)); + assert_eq!(result.data["line_count"], json!(1)); +} + +fn wait_for_pid(path: &Path) -> i32 { + let deadline = Instant::now() + Duration::from_secs(5); + while Instant::now() < deadline { + if let Ok(text) = fs::read_to_string(path) + && let Ok(pid) = text.trim().parse::() + { + return pid; + } + std::thread::sleep(Duration::from_millis(20)); + } + panic!("child did not publish its pid at {}", path.display()); +} diff --git a/tests/mcp_sol_synchronized_tests.rs b/tests/mcp_sol_synchronized_tests.rs new file mode 100644 index 00000000..33f94ba5 --- /dev/null +++ b/tests/mcp_sol_synchronized_tests.rs @@ -0,0 +1,650 @@ +//! Synchronized, real-seam proofs for the second Sol re-review blockers. +//! +//! These tests need the test-only publication barriers, reservation observer, +//! cleanup-proof withholding and constructor adoption hook added by the fix: +//! they drive the actual fence linearization point instead of inspecting +//! source text. + +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Condvar, Mutex}; +use std::time::{Duration, Instant}; + +use rustscript_agent::capabilities::{ + AllowAllApproval, ArtifactCapability, ArtifactLimits, CallCancellationSource, + CallCancellationState, CancellationFlag, CapabilityLifecycle, CapabilityOwner, CapabilityRisk, + DurableStarted, DurableToolLifecycle, FilesystemCapability, FilesystemLimits, LifecycleClock, + LifecycleError, LifecycleLimits, NeverCancelled, ProcessCapability, ProcessCleanupProof, + ProcessLimits, ProcessTableLimits, SystemClock, TokenIssuer, UuidIssuer, +}; +use rustscript_agent::mcp::ToolProfile; +use rustscript_agent::mcp::executor::{McpToolExecutor, McpToolExecutorConfig}; +use serde_json::{Value, json}; + +static NEXT_FIXTURE: AtomicU64 = AtomicU64::new(0); + +struct Fixture { + parent: PathBuf, + root: PathBuf, +} + +impl Fixture { + fn new(label: &str) -> Self { + let sequence = NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed); + let parent = std::env::temp_dir().join(format!( + "mcp-sol-sync-{label}-{}-{sequence}", + std::process::id() + )); + let root = parent.join("workspace"); + fs::create_dir_all(&root).expect("create fixture workspace"); + Self { parent, root } + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.parent); + } +} + +struct ManualCall(Arc); + +impl CallCancellationSource for ManualCall { + fn call_state(&self, _call_id: &str) -> CallCancellationState { + if self.0.load(Ordering::SeqCst) { + CallCancellationState::Cancelled + } else { + CallCancellationState::Active + } + } +} + +#[derive(Default)] +struct NoopDurable; + +impl DurableToolLifecycle for NoopDurable { + fn assert_active_run(&self, _run_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } + + fn prepare_parent( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result<(), LifecycleError> { + Ok(()) + } + + fn replay_result( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result, LifecycleError> { + Ok(None) + } + + fn commit_started(&self, _record: &DurableStarted) -> Result<(), LifecycleError> { + Ok(()) + } + + fn commit_result(&self, _call_id: &str, result: &Value) -> Result { + Ok(result.clone()) + } + + fn interrupt(&self, _call_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } +} + +fn lifecycle_with_call_cancel( + root: &Path, + cancel: Arc, +) -> (CapabilityLifecycle, CapabilityOwner) { + let owner = CapabilityOwner::new("sol-sync", "session", "run").expect("owner"); + let lifecycle = CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry") + .workspace(root) + .limits(LifecycleLimits { + max_tool_calls: 32, + max_output_bytes: 8192, + max_summary_bytes: 256, + }) + .deadline_ms(SystemClock.now_ms().saturating_add(60_000)) + .clock(Arc::new(SystemClock) as Arc) + .tokens(Arc::new(UuidIssuer) as Arc) + .durable(Arc::new(NoopDurable) as Arc) + .approval( + Arc::new(AllowAllApproval) as Arc + ) + .cancellation(Arc::new(NeverCancelled) as Arc) + .call_cancellation(Arc::new(ManualCall(cancel)) as Arc) + .build() + .expect("lifecycle"); + (lifecycle, owner) +} + +fn prepare_token( + lifecycle: &CapabilityLifecycle, + owner: &CapabilityOwner, + call_id: &str, + risk: CapabilityRisk, +) -> String { + match lifecycle + .prepare( + owner, + rustscript_agent::capabilities::PrepareMetadata { + run_id: owner.run().to_string(), + call_id: call_id.to_string(), + tool_name: "fixture_tool".to_string(), + argument_digest: "digest".to_string(), + registry_identity: "registry".to_string(), + risk_class: risk, + summary: "fixture".to_string(), + }, + ) + .expect("prepare") + { + rustscript_agent::capabilities::PrepareOutcome::Execute { + execution_token, .. + } => execution_token, + other => panic!("expected execute, got {other:?}"), + } +} + +fn success_receipt() -> Value { + json!({"ok": true, "content": "receipt", "data": {}}) +} + +/// A blocking test gate whose "started" signal fires inside the publication +/// fence, immediately before the irreversible native operation. +#[derive(Default)] +struct PublicationGate { + started: (Mutex, Condvar), + release: (Mutex, Condvar), +} + +impl PublicationGate { + fn block(&self) { + *self + .started + .0 + .lock() + .unwrap_or_else(|error| error.into_inner()) = true; + self.started.1.notify_all(); + let mut released = self + .release + .0 + .lock() + .unwrap_or_else(|error| error.into_inner()); + while !*released { + released = self + .release + .1 + .wait(released) + .unwrap_or_else(|error| error.into_inner()); + } + } + + fn wait_started(&self) { + let mut started = self + .started + .0 + .lock() + .unwrap_or_else(|error| error.into_inner()); + let deadline = Instant::now() + Duration::from_secs(5); + while !*started { + let remaining = deadline.saturating_duration_since(Instant::now()); + assert!(!remaining.is_zero(), "publication gate was never entered"); + let (guard, _) = self + .started + .1 + .wait_timeout(started, remaining) + .unwrap_or_else(|error| error.into_inner()); + started = guard; + } + } + + fn release(&self) { + *self + .release + .0 + .lock() + .unwrap_or_else(|error| error.into_inner()) = true; + self.release.1.notify_all(); + } +} + +#[test] +fn in_flight_cancellation_during_file_rename_still_settles_the_receipt() { + let fixture = Fixture::new("file-fence"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle_with_call_cancel(&fixture.root, Arc::clone(&cancel)); + let filesystem = FilesystemCapability::new( + lifecycle.clone(), + owner.clone(), + FilesystemLimits::default(), + ) + .expect("filesystem"); + let token = prepare_token(&lifecycle, &owner, "file-fence", CapabilityRisk::Write); + let gate = Arc::new(PublicationGate::default()); + filesystem.inject_before_publish({ + let gate = Arc::clone(&gate); + Arc::new(move || gate.block()) + }); + + let publisher = { + let filesystem = filesystem.clone(); + let token = token.clone(); + std::thread::spawn(move || filesystem.write_atomic(&token, "fenced.txt", "*", b"durable\n")) + }; + gate.wait_started(); + + // Cancellation is requested after the publication linearization point and + // before the rename executes. The fence must classify publication as the + // winner, so the write and its receipt survive. + assert!( + lifecycle.request_call_cancellation("file-fence"), + "the open token must accept the cancellation request" + ); + gate.release(); + publisher + .join() + .expect("publisher thread") + .expect("publication that crossed the fence must complete"); + assert_eq!( + fs::read_to_string(fixture.root.join("fenced.txt")).expect("published file"), + "durable\n" + ); + let second = filesystem + .write_atomic(&token, "after.txt", "*", b"no\n") + .expect_err("a later effect in the same call must be cancelled"); + assert_eq!(second.code(), "cancelled"); + assert!(!fixture.root.join("after.txt").exists()); + lifecycle + .commit(&owner, &token, success_receipt()) + .expect("a publication that crossed the fence must settle exactly once"); +} + +#[test] +fn in_flight_cancellation_during_artifact_insertion_still_settles_the_receipt() { + let fixture = Fixture::new("artifact-fence"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle_with_call_cancel(&fixture.root, Arc::clone(&cancel)); + let artifacts = + ArtifactCapability::new(lifecycle.clone(), owner.clone(), ArtifactLimits::default()) + .expect("artifacts"); + let token = prepare_token(&lifecycle, &owner, "artifact-fence", CapabilityRisk::Read); + let gate = Arc::new(PublicationGate::default()); + artifacts.inject_before_publish({ + let gate = Arc::clone(&gate); + Arc::new(move || gate.block()) + }); + + let publisher = { + let artifacts = artifacts.clone(); + let token = token.clone(); + std::thread::spawn(move || artifacts.put_result(&token, b"payload", &json!({}))) + }; + gate.wait_started(); + assert!(lifecycle.request_call_cancellation("artifact-fence")); + gate.release(); + let stored = publisher + .join() + .expect("publisher thread") + .expect("artifact that crossed the fence must be inserted"); + let second = match lifecycle.enter_publication(&token) { + Ok(_) => panic!("a later artifact publication must be cancelled"), + Err(error) => error, + }; + assert_eq!(second.code(), "cancelled"); + lifecycle + .commit(&owner, &token, success_receipt()) + .expect("an inserted artifact must settle exactly once"); + assert!(artifacts.stored(&stored.id).is_some()); +} + +#[test] +fn in_flight_cancellation_before_the_os_spawn_boundary_refuses_the_child() { + let fixture = Fixture::new("process-fence"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle_with_call_cancel(&fixture.root, Arc::clone(&cancel)); + let processes = ProcessCapability::new_with_table_limits( + lifecycle.clone(), + owner.clone(), + ProcessLimits::default(), + ProcessTableLimits::new(4, 4, Duration::from_millis(500)).expect("table limits"), + ) + .expect("processes"); + let token = prepare_token(&lifecycle, &owner, "process-fence", CapabilityRisk::Execute); + let gate = Arc::new(PublicationGate::default()); + processes.set_before_publication_hook({ + let gate = Arc::clone(&gate); + Arc::new(move || gate.block()) + }); + + let publisher = { + let processes = processes.clone(); + let token = token.clone(); + std::thread::spawn(move || { + processes.spawn( + &token, + &[ + "/bin/sh".to_string(), + "-c".to_string(), + "printf spawned > fence-marker.txt; exec sleep 30".to_string(), + ], + "", + &[], + ProcessLimits { + timeout_ms: 10_000, + close_after_initial: false, + ..ProcessLimits::default() + }, + ) + }) + }; + gate.wait_started(); + assert!(lifecycle.request_call_cancellation("process-fence")); + gate.release(); + // The fence is entered only after this validation/cwd hook, so the + // cancellation wins and no OS child is created. + let error = publisher + .join() + .expect("publisher thread") + .expect_err("a spawn refused before the fence must not execute"); + assert_eq!(error.code(), "cancelled", "{error:?}"); + assert!( + !fixture.root.join("fence-marker.txt").exists(), + "a refused pre-fence spawn must not run the program" + ); + assert_eq!(processes.table_len(), 0); + let settlement = lifecycle + .settle_call_with_receipt("process-fence", Some(&success_receipt())) + .expect("settle"); + assert_eq!(settlement.interrupted, 1); + assert_eq!(settlement.committed, 0); + let _ = processes.shutdown_all_within(Instant::now() + Duration::from_secs(2)); +} + +#[test] +fn concurrent_spawns_reserve_capacity_before_the_os_spawn_hook() { + let fixture = Fixture::new("spawn-reserve"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle_with_call_cancel(&fixture.root, Arc::clone(&cancel)); + let lifecycle = Arc::new(lifecycle); + let processes = ProcessCapability::new_with_table_limits( + lifecycle.as_ref().clone(), + owner.clone(), + ProcessLimits::default(), + ProcessTableLimits::new(2, 2, Duration::from_millis(500)).expect("table limits"), + ) + .expect("processes"); + let crossings = Arc::new(AtomicUsize::new(0)); + processes.set_os_spawn_observer({ + let crossings = Arc::clone(&crossings); + Arc::new(move || { + crossings.fetch_add(1, Ordering::SeqCst); + }) + }); + let tokens: Vec = (0..8) + .map(|index| { + prepare_token( + lifecycle.as_ref(), + &owner, + &format!("reserve-{index}"), + CapabilityRisk::Execute, + ) + }) + .collect(); + let barrier = Arc::new(std::sync::Barrier::new(tokens.len())); + let mut threads = Vec::new(); + for token in tokens { + let processes = processes.clone(); + let barrier = Arc::clone(&barrier); + threads.push(std::thread::spawn(move || { + barrier.wait(); + processes.spawn( + &token, + &["/bin/sleep".to_string(), "30".to_string()], + "", + &[], + ProcessLimits { + timeout_ms: 10_000, + close_after_initial: false, + ..ProcessLimits::default() + }, + ) + })); + } + let successes = threads + .into_iter() + .map(|thread| thread.join().expect("spawn thread")) + .filter(Result::is_ok) + .count(); + assert_eq!(successes, 2, "only the configured slots may spawn"); + assert_eq!( + crossings.load(Ordering::SeqCst), + 2, + "no child beyond the reserved capacity may cross the OS-spawn hook" + ); + assert_eq!(processes.table_len(), 2); + assert_eq!( + processes.shutdown_all(), + ProcessCleanupProof::Clean, + "the two admitted children must be proved reaped" + ); + assert_eq!(processes.table_len(), 0); +} + +#[test] +fn failed_or_cancelled_spawns_release_their_reserved_capacity() { + let fixture = Fixture::new("spawn-release"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle_with_call_cancel(&fixture.root, Arc::clone(&cancel)); + let processes = ProcessCapability::new_with_table_limits( + lifecycle.clone(), + owner.clone(), + ProcessLimits::default(), + ProcessTableLimits::new(1, 1, Duration::from_millis(500)).expect("table limits"), + ) + .expect("processes"); + + let cancelled = prepare_token( + &lifecycle, + &owner, + "release-cancel", + CapabilityRisk::Execute, + ); + let hook_cancel = Arc::clone(&cancel); + processes.set_before_os_spawn_hook(Arc::new(move || { + hook_cancel.store(true, Ordering::SeqCst); + })); + let error = processes + .spawn( + &cancelled, + &["/bin/true".to_string()], + "", + &[], + ProcessLimits::default(), + ) + .expect_err("cancellation must release the reservation"); + assert_eq!(error.code(), "cancelled"); + assert_eq!(processes.table_len(), 0); + cancel.store(false, Ordering::SeqCst); + + // A real spawn failure must also release the slot. + let failing = prepare_token(&lifecycle, &owner, "release-fail", CapabilityRisk::Execute); + let error = processes + .spawn( + &failing, + &["/definitely/not/a/binary".to_string()], + "", + &[], + ProcessLimits::default(), + ) + .expect_err("a failed OS spawn must release the reservation"); + assert_ne!(error.code(), "process_limit"); + assert_eq!(processes.table_len(), 0); + + // The one real slot is still available. + let live = prepare_token(&lifecycle, &owner, "release-live", CapabilityRisk::Execute); + let spawned = processes + .spawn( + &live, + &["/bin/sleep".to_string(), "30".to_string()], + "", + &[], + ProcessLimits { + timeout_ms: 10_000, + close_after_initial: false, + ..ProcessLimits::default() + }, + ) + .expect("the released slot must be reusable"); + assert!(Path::new(&format!("/proc/{}", spawned.pid)).exists()); + let _ = processes.shutdown_all_within(Instant::now() + Duration::from_secs(2)); +} + +#[test] +fn cleanup_proof_withheld_past_a_short_cutoff_reports_typed_timeout_and_retains_ownership() { + let fixture = Fixture::new("cleanup-withhold"); + let cancel = Arc::new(AtomicBool::new(false)); + let (lifecycle, owner) = lifecycle_with_call_cancel(&fixture.root, Arc::clone(&cancel)); + let processes = ProcessCapability::new_with_table_limits( + lifecycle.clone(), + owner.clone(), + ProcessLimits::default(), + ProcessTableLimits::new(2, 2, Duration::from_millis(150)).expect("table limits"), + ) + .expect("processes"); + let token = prepare_token(&lifecycle, &owner, "cleanup-live", CapabilityRisk::Execute); + processes + .spawn( + &token, + &["/bin/sleep".to_string(), "30".to_string()], + "", + &[], + ProcessLimits { + timeout_ms: 10_000, + close_after_initial: false, + ..ProcessLimits::default() + }, + ) + .expect("spawn live child"); + processes.withhold_cleanup_proof_for_test(); + + let cutoff = Instant::now() + Duration::from_millis(150); + let started = Instant::now(); + let proof = processes.shutdown_all_within(cutoff); + let elapsed = started.elapsed(); + assert!( + matches!(proof, ProcessCleanupProof::TimedOut { retained: 1 }), + "withheld proof must be a typed timeout, got {proof:?}" + ); + assert!( + elapsed >= Duration::from_millis(140), + "cleanup must actually wait for the configured cutoff: {elapsed:?}" + ); + assert!( + elapsed < Duration::from_millis(1_000), + "cleanup must be tied to the short cutoff, not a permissive window: {elapsed:?}" + ); + assert_eq!( + processes.table_len(), + 1, + "ownership must be retained until the reap is proven" + ); + + processes.allow_cleanup_proof_for_test(); + assert_eq!( + processes.shutdown_all_within(Instant::now() + Duration::from_secs(2)), + ProcessCleanupProof::Clean + ); + assert_eq!(processes.table_len(), 0); +} + +#[test] +fn workspace_identity_is_adopted_once_across_filesystem_and_process_setup() { + let fixture = Fixture::new("workspace-identity"); + fs::write(fixture.root.join("marker.txt"), "original\n").expect("write original marker"); + let moved = fixture.parent.join("workspace-original"); + let replacement = fixture.parent.join("workspace-replacement"); + fs::create_dir_all(&replacement).expect("create replacement"); + fs::write(replacement.join("marker.txt"), "replacement\n").expect("write replacement marker"); + let root = fixture.root.clone(); + let replacement_for_hook = replacement.clone(); + let moved_for_hook = moved.clone(); + + let executor = McpToolExecutor::new_with_workspace_hook( + McpToolExecutorConfig::new(&root), + Arc::new(move || { + fs::rename(&root, &moved_for_hook).expect("move original workspace"); + std::os::unix::fs::symlink(&replacement_for_hook, &root) + .expect("replace workspace pathname"); + }), + ) + .expect("construction must either bind the original identity or fail closed"); + + let read = executor + .execute_tool( + Some("identity-read"), + "read_file", + &json!({"path": "marker.txt"}), + ) + .expect("read dispatch"); + if read.ok { + assert_eq!( + read.content, "original\n", + "filesystem must keep the original retained identity" + ); + } else { + assert_ne!( + read.content, "replacement\n", + "a replaced pathname must never redirect the retained root" + ); + } + let terminal = executor + .execute_tool( + Some("identity-terminal"), + "terminal", + &json!({"argv": ["/bin/cat", "marker.txt"]}), + ) + .expect("terminal dispatch"); + if terminal.ok { + assert!( + terminal.content.contains("original"), + "process capability must bind the same retained workspace: {terminal:?}" + ); + assert!( + !terminal.content.contains("replacement"), + "process capability must never observe the replacement tree: {terminal:?}" + ); + } else { + assert!( + !terminal.content.contains("replacement"), + "a fail-closed process must not leak replacement content: {terminal:?}" + ); + } + let written = executor + .execute_tool( + Some("identity-write"), + "write_file", + &json!({"path": "identity.txt", "content": "written\n"}), + ) + .expect("write dispatch"); + if written.ok { + assert!( + moved.join("identity.txt").exists(), + "writes must land in the original retained directory" + ); + } + assert!( + !replacement.join("identity.txt").exists(), + "the replacement pathname must never receive an effect" + ); + assert_eq!(executor.profile(), ToolProfile::Coding, "fixture sanity"); +} diff --git a/tests/mcp_tool_cli_tests.rs b/tests/mcp_tool_cli_tests.rs new file mode 100644 index 00000000..c839413b --- /dev/null +++ b/tests/mcp_tool_cli_tests.rs @@ -0,0 +1,357 @@ +//! Exact `tools serve --stdio` CLI parser contract. +//! +//! The parser is the only place where a tool-server invocation is admitted: +//! every rejected shape must fail before the executor or transport exists. + +use std::ffi::OsString; +use std::path::PathBuf; +use std::time::Duration; + +use rustscript_agent::cli::{ + CliError, CliInvocation, ToolsServeOptions, cli_usage, parse_cli_args, +}; +use rustscript_agent::mcp::ToolProfile; + +fn parse(values: &[&str]) -> Result { + parse_cli_args(values.iter().map(OsString::from)) +} + +fn options(values: &[&str]) -> ToolsServeOptions { + match parse(values) { + Ok(CliInvocation::ToolsServe(options)) => options, + other => panic!("expected a tools serve invocation, got {other:?}"), + } +} + +#[test] +fn tools_serve_stdio_parses_with_executor_defaults() { + let parsed = options(&["tools", "serve", "--stdio", "--workspace", "/tmp/workspace"]); + + assert_eq!(parsed.workspace, PathBuf::from("/tmp/workspace")); + assert_eq!(parsed.profile, ToolProfile::Coding); + assert_eq!(parsed.max_tool_calls, None); + assert_eq!(parsed.max_output_bytes, None); + assert_eq!(parsed.call_timeout, None); + assert_eq!(parsed.server_lifetime, None); + assert_eq!(parsed.max_processes, None); + assert_eq!(parsed.max_processes_per_owner, None); + assert_eq!(parsed.process_cleanup_timeout, None); + + let config = parsed.executor_config(); + assert_eq!(config.workspace_root, PathBuf::from("/tmp/workspace")); + assert_eq!(config.profile, ToolProfile::Coding); + assert_eq!( + config.max_tool_calls, + rustscript_agent::mcp::executor::DEFAULT_MAX_TOOL_CALLS + ); + assert_eq!( + config.call_timeout, + rustscript_agent::mcp::executor::DEFAULT_CALL_TIMEOUT + ); + assert_eq!( + config.server_lifetime, + rustscript_agent::mcp::executor::DEFAULT_SERVER_LIFETIME + ); +} + +#[test] +fn tools_serve_accepts_both_profile_spellings() { + let read_only_flag = options(&[ + "tools", + "serve", + "--stdio", + "--workspace", + "/tmp/workspace", + "--read-only", + ]); + assert_eq!(read_only_flag.profile, ToolProfile::ReadOnly); + + let read_only_profile = options(&[ + "tools", + "serve", + "--stdio", + "--workspace", + "/tmp/workspace", + "--profile", + "read-only", + ]); + assert_eq!(read_only_profile.profile, ToolProfile::ReadOnly); + + let coding = options(&[ + "tools", + "serve", + "--stdio", + "--workspace", + "/tmp/workspace", + "--profile", + "coding", + ]); + assert_eq!(coding.profile, ToolProfile::Coding); +} + +#[test] +fn tools_serve_bounds_map_to_the_executor_configuration() { + let parsed = options(&[ + "tools", + "serve", + "--stdio", + "--workspace", + "/tmp/workspace", + "--max-tool-calls", + "17", + "--max-output-bytes", + "8192", + "--call-timeout-ms", + "1500", + "--server-lifetime-ms", + "2000", + "--max-processes", + "4", + "--max-processes-per-owner", + "2", + "--process-cleanup-timeout-ms", + "2500", + ]); + + let config = parsed.executor_config(); + assert_eq!(config.max_tool_calls, 17); + assert_eq!(config.max_output_bytes, 8192); + assert_eq!(config.call_timeout, Duration::from_millis(1500)); + assert_eq!(config.server_lifetime, Duration::from_millis(2000)); + assert_eq!(config.max_processes, 4); + assert_eq!(config.max_processes_per_owner, 2); + assert_eq!(config.process_cleanup_timeout, Duration::from_millis(2500)); +} + +#[test] +fn tools_serve_rejects_unknown_flags_and_transports() { + for argv in [ + vec![ + "tools", + "serve", + "--stdio", + "--workspace", + "/tmp/workspace", + "--socket", + ], + vec!["tools", "serve", "--http", "--workspace", "/tmp/workspace"], + vec!["tools", "serve", "--workspace", "/tmp/workspace"], + vec![ + "tools", + "serve", + "--stdio", + "--workspace", + "/tmp/workspace", + "trailing", + ], + ] { + assert_eq!( + parse(&argv), + Err(CliError::InvalidArguments), + "argv={argv:?}" + ); + } +} + +#[test] +fn tools_serve_rejects_duplicate_mode_flags() { + for argv in [ + vec![ + "tools", + "serve", + "--stdio", + "--stdio", + "--workspace", + "/tmp/workspace", + ], + vec![ + "tools", + "serve", + "--stdio", + "--workspace", + "/tmp/workspace", + "--read-only", + "--profile", + "read-only", + ], + vec![ + "tools", + "serve", + "--stdio", + "--workspace", + "/tmp/workspace", + "--profile", + "coding", + "--profile", + "coding", + ], + vec![ + "tools", + "serve", + "--stdio", + "--workspace", + "/tmp/workspace", + "--max-tool-calls", + "5", + "--max-tool-calls", + "6", + ], + vec![ + "tools", + "serve", + "--stdio", + "--workspace", + "/tmp/workspace", + "--call-timeout-ms", + "100", + "--call-timeout-ms", + "200", + ], + vec![ + "tools", + "serve", + "--stdio", + "--workspace", + "/tmp/workspace", + "--process-cleanup-timeout-ms", + "100", + "--process-cleanup-timeout-ms", + "200", + ], + ] { + assert_eq!( + parse(&argv), + Err(CliError::InvalidArguments), + "argv={argv:?}" + ); + } +} + +#[test] +fn tools_serve_rejects_a_relative_or_empty_workspace_before_serving() { + let relative = parse(&[ + "tools", + "serve", + "--stdio", + "--workspace", + "relative/workspace", + ]) + .expect_err("relative workspace must be rejected"); + assert_eq!(relative, CliError::InvalidWorkspace); + assert_eq!(relative.code(), "cli_workspace_invalid"); + + let empty = parse(&["tools", "serve", "--stdio", "--workspace", ""]) + .expect_err("empty workspace must be rejected"); + assert_eq!(empty, CliError::InvalidWorkspace); + + let missing = parse(&["tools", "serve", "--stdio", "--workspace"]) + .expect_err("missing workspace value must be rejected"); + assert_eq!(missing, CliError::InvalidArguments); +} + +#[test] +fn tools_serve_rejects_zero_and_non_numeric_bounds() { + for argv in [ + vec![ + "tools", + "serve", + "--stdio", + "--workspace", + "/tmp/workspace", + "--max-tool-calls", + "0", + ], + vec![ + "tools", + "serve", + "--stdio", + "--workspace", + "/tmp/workspace", + "--max-output-bytes", + "0", + ], + vec![ + "tools", + "serve", + "--stdio", + "--workspace", + "/tmp/workspace", + "--call-timeout-ms", + "soon", + ], + vec![ + "tools", + "serve", + "--stdio", + "--workspace", + "/tmp/workspace", + "--server-lifetime-ms", + "-1", + ], + vec![ + "tools", + "serve", + "--stdio", + "--workspace", + "/tmp/workspace", + "--max-processes", + "0", + ], + vec![ + "tools", + "serve", + "--stdio", + "--workspace", + "/tmp/workspace", + "--max-processes-per-owner", + "1.5", + ], + vec![ + "tools", + "serve", + "--stdio", + "--workspace", + "/tmp/workspace", + "--process-cleanup-timeout-ms", + "0", + ], + ] { + assert_eq!( + parse(&argv), + Err(CliError::InvalidArguments), + "argv={argv:?}" + ); + } +} + +#[test] +fn tools_serve_help_is_available_at_both_levels() { + assert_eq!(parse(&["tools", "--help"]), Ok(CliInvocation::Help)); + assert_eq!( + parse(&["tools", "serve", "--help"]), + Ok(CliInvocation::Help) + ); + assert!(cli_usage().contains("tools serve --stdio --workspace")); +} + +#[test] +fn legacy_run_auth_and_config_shapes_are_unchanged() { + assert_eq!( + parse(&["auth", "status"]), + Ok(CliInvocation::Auth( + rustscript_agent::runtime::AuthCommandInput { + operation: "auth.status".to_owned(), + provider: None, + credential_id: None, + } + )) + ); + assert!(matches!( + parse(&["--script", "main.rss", "--allow-host", "fixture.invalid"]), + Ok(CliInvocation::Run { .. }) + )); + assert!(matches!( + parse(&["config", "path"]), + Ok(CliInvocation::ConfigPath(_)) + )); +} diff --git a/tests/mcp_tool_retained_tests.rs b/tests/mcp_tool_retained_tests.rs new file mode 100644 index 00000000..ca6f13af --- /dev/null +++ b/tests/mcp_tool_retained_tests.rs @@ -0,0 +1,288 @@ +//! Wire-level proof that a retained executor disposition is nonterminal. +//! +//! This target requires the `workspace-io-fault` test seam because a retained +//! decision can only be produced while a real publisher still holds its +//! permit. The seam installs that publisher; the MCP service, executor, +//! dispatch, and effect still run for real. + +use std::fs; +use std::path::PathBuf; +use std::sync::{Arc, Condvar, Mutex}; +use std::time::Duration; + +use rustscript_agent::mcp::executor::{McpToolExecutor, McpToolExecutorConfig}; +use rustscript_agent::mcp::server::{ + ERROR_CODE_DATA_KEY, REPLAY_DATA_KEY, RETAINED_ERROR_CODE, RustScriptToolServer, + TERMINAL_DATA_KEY, +}; +use serde_json::{Value, json}; +use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, DuplexStream}; + +struct Fixture { + parent: PathBuf, + root: PathBuf, +} + +impl Fixture { + fn new(label: &str) -> Self { + let base = std::env::var_os("RUSTSCRIPT_AGENT_TEST_TMP") + .map(PathBuf::from) + .unwrap_or_else(std::env::temp_dir); + let parent = base.join(format!("mcp-retained-{label}-{}", std::process::id())); + let root = parent.join("workspace"); + fs::create_dir_all(&root).expect("create retained fixture"); + Self { parent, root } + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.parent); + } +} + +#[derive(Default)] +struct GateState { + started: bool, + released: bool, +} + +#[derive(Default)] +struct Gate { + state: Mutex, + changed: Condvar, +} + +impl Gate { + fn mark_started(&self) { + let mut state = self + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + state.started = true; + self.changed.notify_all(); + } + + fn wait_started(&self) { + let mut state = self + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + while !state.started { + state = self + .changed + .wait(state) + .unwrap_or_else(|poisoned| poisoned.into_inner()); + } + } + + fn release(&self) { + let mut state = self + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + state.released = true; + self.changed.notify_all(); + } + + fn wait_released(&self) { + let mut state = self + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + while !state.released { + state = self + .changed + .wait(state) + .unwrap_or_else(|poisoned| poisoned.into_inner()); + } + } +} + +/// Publisher that keeps its permit across the guest `tool_commit` decision. +struct Publisher { + gate: Arc, + handle: Arc>>>, +} + +impl Publisher { + fn install(executor: &Arc) -> Self { + let lifecycle = Arc::clone(executor.lifecycle_for_test()); + let gate = Arc::new(Gate::default()); + let handle = Arc::new(Mutex::new(None::>)); + let observed = Arc::clone(&gate); + let publisher_handle = Arc::clone(&handle); + let publisher_lifecycle = Arc::clone(&lifecycle); + lifecycle.inject_commit_attempt_observer_for_test(Arc::new(move |token: &str| { + let token = token.to_string(); + let gate = Arc::clone(&observed); + let thread_gate = Arc::clone(&gate); + let lifecycle = Arc::clone(&publisher_lifecycle); + let worker = std::thread::spawn(move || { + let _permit = lifecycle + .enter_publication(&token) + .expect("publisher permit"); + thread_gate.mark_started(); + thread_gate.wait_released(); + }); + *publisher_handle + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(worker); + gate.wait_started(); + })); + Self { gate, handle } + } + + fn release(self) { + self.gate.release(); + self.handle + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .take() + .expect("publisher thread") + .join() + .expect("publisher thread"); + } +} + +struct Client { + reader: BufReader>, + writer: tokio::io::WriteHalf, + next_id: i64, + buffered: Vec, +} + +impl Client { + fn new(stream: DuplexStream) -> Self { + let (reader, writer) = tokio::io::split(stream); + Self { + reader: BufReader::new(reader), + writer, + next_id: 1, + buffered: Vec::new(), + } + } + + async fn send(&mut self, message: Value) { + let mut line = serde_json::to_vec(&message).expect("serialize"); + line.push(b'\n'); + self.writer.write_all(&line).await.expect("write"); + self.writer.flush().await.expect("flush"); + } + + async fn read(&mut self) -> Value { + let mut line = String::new(); + let read = tokio::time::timeout(Duration::from_secs(30), self.reader.read_line(&mut line)) + .await + .expect("timed out") + .expect("read"); + assert!(read > 0, "server closed before responding"); + serde_json::from_str(line.trim_end()).expect("JSON protocol line") + } + + async fn request(&mut self, method: &str, params: Option) -> Value { + let id = self.next_id; + self.next_id += 1; + let mut message = json!({"jsonrpc": "2.0", "id": id, "method": method}); + if let Some(params) = params { + message["params"] = params; + } + self.send(message).await; + loop { + let response = self.read().await; + if response.get("id") == Some(&json!(id)) { + return response; + } + self.buffered.push(response); + } + } +} + +async fn serve(executor: Arc) -> (Client, tokio::task::JoinHandle<()>) { + let (server_io, client_io) = tokio::io::duplex(64 * 1024); + let (server_reader, server_writer) = tokio::io::split(server_io); + let server = RustScriptToolServer::from_executor(executor).expect("server"); + let task = tokio::spawn(async move { + let _ = server + .serve_with_shutdown(server_reader, server_writer, None) + .await; + }); + (Client::new(client_io), task) +} + +#[tokio::test] +async fn retained_call_returns_a_nonterminal_protocol_error_without_replaying_the_effect() { + let fixture = Fixture::new("wire"); + let executor = Arc::new( + McpToolExecutor::new(McpToolExecutorConfig::new(&fixture.root)).expect("executor"), + ); + let publisher = Publisher::install(&executor); + let (mut client, server_task) = serve(Arc::clone(&executor)).await; + + let init = client + .request( + "initialize", + Some(json!({ + "protocolVersion": "2025-06-18", + "capabilities": {}, + "clientInfo": {"name": "retained-wire-test", "version": "1"} + })), + ) + .await; + assert!(init.get("result").is_some(), "init={init}"); + client + .send(json!({"jsonrpc": "2.0", "method": "notifications/initialized"})) + .await; + + let response = client + .request( + "tools/call", + Some(json!({ + "name": "terminal", + "arguments": { + "argv": ["/bin/sh", "-c", "printf x >> runs.txt"], + "timeout_ms": 5000 + } + })), + ) + .await; + + let error = response + .get("error") + .unwrap_or_else(|| panic!("retention must not be a tool result: {response}")); + assert!( + response.get("result").is_none(), + "retention must not produce a CallToolResult: {response}" + ); + assert_eq!(error["code"], json!(RETAINED_ERROR_CODE)); + assert_eq!(error["data"][ERROR_CODE_DATA_KEY], json!("retained")); + assert_eq!( + error["data"][TERMINAL_DATA_KEY], + json!(false), + "retention is a nonterminal disposition" + ); + assert_eq!(error["data"][REPLAY_DATA_KEY], json!(false)); + assert_eq!(error["data"]["call_id"], json!("mcp-call-0")); + + // The effect ran exactly once and stays owned by the pending publisher; + // the server neither re-executed the call nor reported a tool failure. + assert_eq!( + fs::read_to_string(fixture.root.join("runs.txt")).expect("effect output"), + "x" + ); + assert_eq!(executor.open_token_count(), 1); + assert_eq!(executor.committed_token_count(), 0); + + publisher.release(); + executor.settle_retained_for_test(); + assert_eq!(executor.open_token_count(), 0); + assert_eq!(executor.committed_token_count(), 1); + assert_eq!( + fs::read_to_string(fixture.root.join("runs.txt")).expect("effect output"), + "x", + "settling a retained call must not execute it again" + ); + + drop(client); + let _ = tokio::time::timeout(Duration::from_secs(10), server_task).await; +} diff --git a/tests/mcp_tool_server_tests.rs b/tests/mcp_tool_server_tests.rs new file mode 100644 index 00000000..1c9302f4 --- /dev/null +++ b/tests/mcp_tool_server_tests.rs @@ -0,0 +1,3605 @@ +//! Provider-free MCP tool-provider behavior. +//! +//! These tests exercise the standalone RSS executor rooted at a canonical +//! workspace. They never construct an `AgentService`, load provider +//! configuration, or run the bundled agent loop. + +use std::fs; +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Condvar, Mutex}; +use std::time::{Duration, Instant}; + +use rustscript_agent::ToolResult; +#[cfg(all(unix, feature = "workspace-io-fault"))] +use rustscript_agent::capabilities::hold_reap_serial_for_test; +#[cfg(all(unix, feature = "workspace-io-fault"))] +use rustscript_agent::capabilities::pause_retained_reaper_for_test; +use rustscript_agent::capabilities::{ + AllowAllApproval, CapabilityLifecycle, CapabilityOwner, CapabilityRisk, DurableStarted, + DurableToolLifecycle, LifecycleError, LifecycleLimits, PrepareMetadata, PrepareOutcome, + ProcessCleanupProof, SystemClock, UuidIssuer, sweep_spawned_children, +}; +#[cfg(feature = "workspace-io-fault")] +use rustscript_agent::capabilities::{ + clear_sweep_group_observer_for_test, registered_child_for_test, + set_sweep_group_observer_for_test, sweep_registered_child_for_test, +}; +use rustscript_agent::mcp::ToolProfile; +use rustscript_agent::mcp::catalog; +use rustscript_agent::mcp::executor::{ + AdmissionCancellation, McpToolExecutor, McpToolExecutorConfig, McpToolExecutorError, +}; +use rustscript_agent::mcp::result; +use rustscript_agent::mcp::server::RustScriptToolServer; +use serde_json::json; + +static NEXT_FIXTURE: AtomicU64 = AtomicU64::new(0); + +struct Fixture { + parent: PathBuf, + root: PathBuf, +} + +impl Fixture { + fn new(label: &str) -> Self { + let sequence = NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed); + let parent = std::env::temp_dir().join(format!( + "mcp-executor-{label}-{}-{sequence}", + std::process::id() + )); + let root = parent.join("workspace"); + fs::create_dir_all(&root).expect("create executor fixture"); + Self { parent, root } + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.parent); + } +} + +fn executor(root: &PathBuf) -> McpToolExecutor { + McpToolExecutor::new(McpToolExecutorConfig::new(root)) + .unwrap_or_else(|error| panic!("construct standalone executor: {error}")) +} + +fn read_only_executor(root: &PathBuf) -> McpToolExecutor { + McpToolExecutor::new(McpToolExecutorConfig::new(root).with_profile(ToolProfile::ReadOnly)) + .unwrap_or_else(|error| panic!("construct read-only executor: {error}")) +} + +#[test] +fn standalone_executor_returns_canonical_read_file_result() { + let fixture = Fixture::new("read-file"); + fs::write(fixture.root.join("hello.txt"), "hello\n").expect("write fixture file"); + let executor = executor(&fixture.root); + + let result = executor + .execute_tool( + Some("call-read-1"), + "read_file", + &json!({"path": "hello.txt"}), + ) + .unwrap_or_else(|error| panic!("read_file through executor: {error}")); + + assert_eq!( + result, + ToolResult::success("hello\n", json!({"offset": 1, "line_count": 1})) + ); +} + +#[test] +fn standalone_executor_rejects_unknown_tool_before_dispatch() { + let fixture = Fixture::new("unknown-tool"); + let executor = executor(&fixture.root); + + let error = executor + .execute_tool(Some("call-unknown-1"), "not_a_real_tool", &json!({})) + .expect_err("unknown tool must be rejected"); + assert!( + matches!( + error, + McpToolExecutorError::UnknownTool { ref name } if name == "not_a_real_tool" + ), + "error={error:?}" + ); + assert_eq!(error.code(), "unknown_tool"); +} + +#[test] +fn standalone_executor_rejects_arguments_that_do_not_match_the_descriptor() { + let fixture = Fixture::new("invalid-args"); + let executor = executor(&fixture.root); + + let missing_path = executor + .execute_tool(Some("call-invalid-1"), "read_file", &json!({})) + .expect_err("missing required path must be rejected"); + assert!( + matches!(missing_path, McpToolExecutorError::InvalidArguments { .. }), + "error={missing_path:?}" + ); + assert_eq!(missing_path.code(), "invalid_arguments"); + + let extra_property = executor + .execute_tool( + Some("call-invalid-2"), + "read_file", + &json!({"path": "hello.txt", "unexpected": true}), + ) + .expect_err("additional properties must be rejected"); + assert!( + matches!( + extra_property, + McpToolExecutorError::InvalidArguments { .. } + ), + "error={extra_property:?}" + ); + + let non_object = executor + .execute_tool(Some("call-invalid-3"), "read_file", &json!("hello.txt")) + .expect_err("non-object arguments must be rejected"); + assert!( + matches!(non_object, McpToolExecutorError::InvalidArguments { .. }), + "error={non_object:?}" + ); +} + +#[test] +fn read_only_executor_disables_write_and_execute_before_any_effect() { + let fixture = Fixture::new("read-only"); + let executor = read_only_executor(&fixture.root); + + let write_error = executor + .execute_tool( + Some("call-write-1"), + "write_file", + &json!({"path": "blocked.txt", "content": "must not exist\n"}), + ) + .expect_err("read-only write_file must be disabled"); + assert!( + matches!( + write_error, + McpToolExecutorError::DisabledTool { + ref name, + ref risk_class + } if name == "write_file" && risk_class == "write" + ), + "error={write_error:?}" + ); + assert_eq!(write_error.code(), "disabled_tool"); + + let terminal_error = executor + .execute_tool( + Some("call-terminal-1"), + "terminal", + &json!({"argv": ["/bin/true"]}), + ) + .expect_err("read-only terminal must be disabled"); + assert!( + matches!( + terminal_error, + McpToolExecutorError::DisabledTool { + ref name, + ref risk_class + } if name == "terminal" && risk_class == "execute" + ), + "error={terminal_error:?}" + ); + + assert!( + !fixture.root.join("blocked.txt").exists(), + "disabled write_file must not create a file" + ); +} + +#[test] +fn standalone_executor_confines_paths_to_the_canonical_workspace() { + let fixture = Fixture::new("escape"); + fs::write( + fixture.parent.join("outside-secret.txt"), + "outside-secret\n", + ) + .expect("write outside fixture"); + let executor = executor(&fixture.root); + + let result = executor + .execute_tool( + Some("call-escape-1"), + "read_file", + &json!({"path": "../outside-secret.txt"}), + ) + .expect("confinement failure is a canonical tool result"); + + assert!(!result.ok, "result={result:?}"); + assert_eq!( + result.error.as_ref().map(|error| error.code.as_str()), + Some("path_denied") + ); + assert_eq!(result.content, ""); + assert_eq!(result.data, json!({})); + assert!(!result.truncated); + assert!(result.artifacts.is_empty()); +} + +#[test] +fn standalone_executor_rejects_a_duplicate_call_id_within_one_lifetime() { + let fixture = Fixture::new("duplicate-call"); + fs::write(fixture.root.join("hello.txt"), "hello\n").expect("write fixture file"); + let executor = executor(&fixture.root); + + let first = executor + .execute_tool( + Some("call-duplicate"), + "read_file", + &json!({"path": "hello.txt"}), + ) + .expect("first call succeeds"); + assert_eq!( + first, + ToolResult::success("hello\n", json!({"offset": 1, "line_count": 1})) + ); + + let duplicate = executor + .execute_tool( + Some("call-duplicate"), + "read_file", + &json!({"path": "hello.txt"}), + ) + .expect_err("duplicate call id must be rejected"); + assert!( + matches!( + duplicate, + McpToolExecutorError::DuplicateCallId { ref call_id } if call_id == "call-duplicate" + ), + "error={duplicate:?}" + ); + assert_eq!(duplicate.code(), "duplicate_call_id"); + + let generated = executor + .execute_tool(None, "read_file", &json!({"path": "hello.txt"})) + .expect("generated call id succeeds"); + assert_eq!(generated.content, "hello\n"); +} + +#[test] +fn standalone_executor_keeps_process_ownership_across_calls_and_cleans_up() { + let fixture = Fixture::new("process-lifecycle"); + let executor = executor(&fixture.root); + + let spawn = executor + .execute_tool( + Some("call-process-spawn"), + "terminal", + &json!({ + "argv": ["/bin/sh", "-c", "printf process-ready"], + "background": true, + }), + ) + .expect("background terminal dispatch"); + assert!(spawn.ok, "spawn result={spawn:?}"); + assert_eq!(spawn.data["background"], json!(true)); + let process_id = spawn.data["process_id"] + .as_str() + .expect("background terminal returns a process id") + .to_string(); + + let poll = executor + .execute_tool( + Some("call-process-poll"), + "process", + &json!({"action": "poll", "process_id": process_id}), + ) + .expect("process poll dispatch"); + assert!(poll.ok, "poll result={poll:?}"); + assert!( + poll.content.contains("process-ready"), + "poll content={:?}", + poll.content + ); + + let kill = executor + .execute_tool( + Some("call-process-kill"), + "process", + &json!({"action": "kill", "process_id": process_id}), + ) + .expect("process kill dispatch"); + assert!(kill.ok, "kill result={kill:?}"); + + executor.shutdown(); + assert!(executor.is_closed()); + let closed = executor + .execute_tool( + Some("call-after-close"), + "read_file", + &json!({"path": "hello.txt"}), + ) + .expect_err("closed executor must reject calls"); + assert!( + matches!(closed, McpToolExecutorError::Closed), + "error={closed:?}" + ); +} + +#[test] +fn standalone_executor_catalog_and_result_mapping_share_one_registry_contract() { + let fixture = Fixture::new("catalog-integration"); + fs::write(fixture.root.join("hello.txt"), "hello\n").expect("write fixture file"); + let executor = executor(&fixture.root); + + let tools = catalog::catalog_from_registry(executor.registry(), executor.profile()) + .expect("catalog from executor registry"); + let catalog_names: Vec<&str> = tools.iter().map(|tool| tool.name.as_ref()).collect(); + let registry_names: Vec<&str> = executor + .registry() + .names() + .iter() + .map(String::as_str) + .collect(); + assert_eq!(catalog_names, registry_names); + + let read_file = tools + .iter() + .find(|tool| tool.name.as_ref() == "read_file") + .expect("read_file tool"); + assert_eq!( + read_file.schema_as_json_value(), + executor + .registry() + .descriptor("read_file") + .expect("read_file descriptor") + .schema + ); + + let result = executor + .execute_tool( + Some("call-integration"), + "read_file", + &json!({"path": "hello.txt"}), + ) + .expect("read_file through executor"); + let converted = result::to_call_tool_result(&result); + assert_eq!(converted.is_error, Some(false)); + assert_eq!( + converted.structured_content, + Some(json!({"offset": 1, "line_count": 1})) + ); + assert_eq!( + converted.content[0].as_text().expect("text block").text, + "hello\n" + ); + let meta = converted.meta.as_ref().expect("result metadata"); + assert_eq!(meta.0[result::TRUNCATED_META_KEY], json!(false)); + assert_eq!(meta.0[result::ARTIFACTS_META_KEY], json!([])); +} + +#[test] +fn read_only_executor_catalog_contains_only_its_admitted_tools() { + let fixture = Fixture::new("read-only-catalog"); + let executor = read_only_executor(&fixture.root); + + let tools = catalog::catalog_from_registry(executor.registry(), executor.profile()) + .expect("read-only catalog"); + let names: Vec<&str> = tools.iter().map(|tool| tool.name.as_ref()).collect(); + assert_eq!(names, ["read_file", "search_files"]); +} + +#[test] +fn standalone_executor_is_send_and_sync_for_the_mcp_service() { + fn assert_send_sync() {} + assert_send_sync::(); + assert_send_sync::(); +} + +#[test] +fn standalone_executor_rejects_an_invalid_workspace_before_construction() { + let relative = McpToolExecutor::new(McpToolExecutorConfig::new("relative/workspace")) + .map(|_| ()) + .expect_err("relative workspace must be rejected"); + assert!( + matches!(relative, McpToolExecutorError::InvalidConfig { .. }), + "error={relative:?}" + ); + assert_eq!(relative.code(), "invalid_config"); + + let file = Fixture::new("workspace-file"); + let file_path = file.parent.join("workspace-file.txt"); + fs::write(&file_path, "not a directory").expect("write workspace file"); + let not_directory = McpToolExecutor::new(McpToolExecutorConfig::new(&file_path)) + .map(|_| ()) + .expect_err("file workspace must be rejected"); + assert!( + matches!(not_directory, McpToolExecutorError::InvalidConfig { .. }), + "error={not_directory:?}" + ); +} + +/// Blocking seam used to hold a worker at an exact executor observation point. +#[derive(Default)] +struct SeamGate { + state: Mutex<(bool, bool)>, + changed: Condvar, +} + +impl SeamGate { + fn mark_started(&self) { + let mut state = self + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + state.0 = true; + self.changed.notify_all(); + } + + fn wait_started(&self) { + let mut state = self + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + while !state.0 { + state = self + .changed + .wait(state) + .unwrap_or_else(|poisoned| poisoned.into_inner()); + } + } + + fn wait_released(&self) { + let mut state = self + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + while !state.1 { + state = self + .changed + .wait(state) + .unwrap_or_else(|poisoned| poisoned.into_inner()); + } + } + + fn release(&self) { + let mut state = self + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + state.1 = true; + self.changed.notify_all(); + } +} + +/// Cancellation is linearized at the admission lock: the request source is +/// re-checked while the lock is held, before the identity is burned and before +/// any prepare. A cancellation recorded after the lock was taken but before +/// that check must still refuse the call. +#[cfg(feature = "workspace-io-fault")] +#[test] +fn cancellation_at_the_admission_lock_boundary_never_admits_or_effects() { + let fixture = Fixture::new("admission-boundary"); + let executor = Arc::new( + McpToolExecutor::new(McpToolExecutorConfig::new(&fixture.root)).expect("executor"), + ); + let gate = Arc::new(SeamGate::default()); + let observer_gate = Arc::clone(&gate); + executor.set_admission_observer_for_test(Arc::new(move |call_id: &str| { + if call_id == "boundary-call" { + observer_gate.mark_started(); + observer_gate.wait_released(); + } + })); + let probe = Arc::new(AtomicBool::new(false)); + + let worker = { + let executor = Arc::clone(&executor); + let probe = Arc::clone(&probe); + std::thread::spawn(move || { + executor.execute_tool_with_cancellation( + Some("boundary-call"), + "write_file", + &json!({"path": "boundary.txt", "content": "leaked\n"}), + Some(AdmissionCancellation::new(move || { + probe.load(Ordering::SeqCst) + })), + ) + }) + }; + gate.wait_started(); + // The worker holds the admission lock here. Cancel the request source, and + // start `cancel_call` so it is waiting on that same lock. Admission must + // observe the request source when it resumes; the pre-admission intent is + // not recorded until `cancel_call` acquires the lock. + probe.store(true, Ordering::SeqCst); + let canceller = { + let executor = Arc::clone(&executor); + std::thread::spawn(move || executor.cancel_call("boundary-call")) + }; + std::thread::sleep(Duration::from_millis(50)); + gate.release(); + + let error = worker + .join() + .expect("worker") + .expect_err("a cancelled admission must be refused"); + assert!( + matches!(error, McpToolExecutorError::Cancelled { ref call_id } if call_id == "boundary-call"), + "error={error:?}" + ); + let _ = canceller.join(); + assert_eq!( + executor.admitted_call_count(), + 0, + "no call may be admitted after the request token was cancelled" + ); + assert_eq!( + executor.retained_identity_count_for_test(), + 1, + "the refused identity must be burned and charged exactly once" + ); + assert_eq!(executor.retained_call_id_count(), 1); + assert_eq!( + executor.pending_pre_admission_cancellations_for_test(), + 0, + "an intent recorded after admission must not linger" + ); + assert!( + !fixture.root.join("boundary.txt").exists(), + "a refused admission must prepare no effect" + ); +} + +/// Sequential cancel-then-call cycles must charge burned identities to the +/// same quota as admitted calls. Otherwise `ids` would grow without bound +/// while the pending-intent set stayed under its own cap. +#[cfg(feature = "workspace-io-fault")] +#[test] +fn cancellation_identities_are_charged_to_the_lifetime_quota() { + let fixture = Fixture::new("cancel-quota"); + fs::write(fixture.root.join("hello.txt"), "hello\n").expect("hello"); + let executor = + McpToolExecutor::new(McpToolExecutorConfig::new(&fixture.root).with_max_tool_calls(2)) + .expect("executor"); + + for index in 0..2 { + let call_id = format!("burned-{index}"); + assert!(executor.cancel_call(&call_id), "cancel must be recorded"); + let error = executor + .execute_tool(Some(&call_id), "read_file", &json!({"path": "hello.txt"})) + .expect_err("a cancelled identity must be refused"); + assert!( + matches!(error, McpToolExecutorError::Cancelled { .. }), + "error={error:?}" + ); + } + assert_eq!(executor.retained_identity_count_for_test(), 2); + assert_eq!(executor.retained_call_id_count(), 2); + + for index in 2..8 { + let call_id = format!("burned-{index}"); + assert!(executor.cancel_call(&call_id)); + let error = executor + .execute_tool(Some(&call_id), "read_file", &json!({"path": "hello.txt"})) + .expect_err("the identity quota must bound burned cancellations"); + assert!( + matches!(error, McpToolExecutorError::CallQuotaExhausted { limit: 2 }), + "error={error:?}" + ); + } + assert_eq!( + executor.retained_call_id_count(), + 2, + "burned identities must never exceed the advertised quota" + ); + assert_eq!(executor.admitted_call_count(), 0); +} + +/// A request cancelled before any worker exists still burns its identity and +/// is charged to the quota. +#[cfg(feature = "workspace-io-fault")] +#[test] +fn pre_spawn_cancellation_burns_the_identity_without_a_worker() { + let fixture = Fixture::new("pre-spawn-cancel"); + let executor = + McpToolExecutor::new(McpToolExecutorConfig::new(&fixture.root).with_max_tool_calls(1)) + .expect("executor"); + + let error = executor.refuse_cancelled_call("never-spawned"); + assert!( + matches!(error, McpToolExecutorError::Cancelled { .. }), + "error={error:?}" + ); + assert_eq!(executor.admitted_call_count(), 0); + assert_eq!(executor.retained_identity_count_for_test(), 1); + assert_eq!(executor.retained_call_id_count(), 1); + // The same identity cannot be admitted later. + let duplicate = executor + .execute_tool( + Some("never-spawned"), + "read_file", + &json!({"path": "anything.txt"}), + ) + .expect_err("a burned identity must stay refused"); + assert!( + matches!(duplicate, McpToolExecutorError::DuplicateCallId { .. }), + "error={duplicate:?}" + ); +} + +/// A child can exist while its worker owns only a spawn reservation. The +/// process table proves a timeout there, and the exit sweep must still be able +/// to signal and reap the real OS child directly. +#[cfg(all(unix, feature = "workspace-io-fault"))] +#[test] +fn exit_sweep_reaps_a_child_held_between_spawn_and_record() { + let fixture = Fixture::new("exit-window"); + let executor = Arc::new( + McpToolExecutor::new( + McpToolExecutorConfig::new(&fixture.root) + .with_process_cleanup_timeout(Duration::from_millis(300)), + ) + .expect("executor"), + ); + let gate = Arc::new(SeamGate::default()); + executor + .processes_for_test() + .set_after_os_spawn_hook(Arc::new({ + let gate = Arc::clone(&gate); + move || { + gate.mark_started(); + gate.wait_released(); + } + })); + let worker = { + let executor = Arc::clone(&executor); + std::thread::spawn(move || { + executor.execute_tool( + Some("exit-window"), + "terminal", + &json!({ + "argv": [ + "/bin/sh", + "-c", + "printf '%s' $$ > exit-window.pid; exec sleep 30" + ] + }), + ) + }) + }; + gate.wait_started(); + + let pid_file = fixture.root.join("exit-window.pid"); + let pid_deadline = Instant::now() + Duration::from_secs(5); + let pid = loop { + if let Ok(text) = fs::read_to_string(&pid_file) + && let Ok(pid) = text.trim().parse::() + { + break pid; + } + assert!( + Instant::now() < pid_deadline, + "child pid file never appeared" + ); + std::thread::sleep(Duration::from_millis(10)); + }; + assert!(registered_child_for_test(pid)); + assert_eq!( + unsafe { libc::kill(pid as libc::pid_t, 0) }, + 0, + "the reservation-owned child must be alive before the sweep" + ); + + let proof = executor.shutdown(); + assert!( + matches!(proof, ProcessCleanupProof::TimedOut { .. }), + "a reservation-only table must prove a timeout: {proof:?}" + ); + assert_eq!( + unsafe { libc::kill(pid as libc::pid_t, 0) }, + 0, + "the child must still be alive while only its reservation exists" + ); + + assert!( + sweep_registered_child_for_test(pid, Instant::now() + Duration::from_secs(2)), + "the exit sweep must prove the reservation-owned child gone" + ); + let gone_deadline = Instant::now() + Duration::from_secs(2); + loop { + let rc = unsafe { libc::kill(pid as libc::pid_t, 0) }; + if rc != 0 { + break; + } + assert!( + Instant::now() < gone_deadline, + "the swept child must be signalled and reaped" + ); + std::thread::sleep(Duration::from_millis(10)); + } + + gate.release(); + let _ = worker.join(); +} + +/// A request cancelled immediately after admission's first token check must +/// still never prepare or publish. The cancellation source is consumed again +/// under the admission lock after the call is registered; this source reports +/// "not cancelled" on the first observation and "cancelled" on the second, +/// exactly modelling a cancellation that lands in that boundary. +#[cfg(feature = "workspace-io-fault")] +#[test] +fn cancellation_immediately_after_the_admission_token_check_never_prepares() { + use std::sync::atomic::AtomicUsize; + + let fixture = Fixture::new("post-token-cancel"); + let executor = Arc::new( + McpToolExecutor::new(McpToolExecutorConfig::new(&fixture.root)).expect("executor"), + ); + let observations = Arc::new(AtomicUsize::new(0)); + let source = { + let observations = Arc::clone(&observations); + AdmissionCancellation::new(move || observations.fetch_add(1, Ordering::SeqCst) >= 1) + }; + + let error = executor + .execute_tool_with_cancellation( + Some("post-token-call"), + "write_file", + &json!({"path": "post-token.txt", "content": "leaked\n"}), + Some(source), + ) + .expect_err("a cancellation after the token check must refuse the call"); + assert!( + matches!(error, McpToolExecutorError::Cancelled { ref call_id } if call_id == "post-token-call"), + "error={error:?}" + ); + assert!( + observations.load(Ordering::SeqCst) >= 2, + "admission must consume the request cancellation again after registration" + ); + assert_eq!( + executor.admitted_call_count(), + 0, + "the boundary-cancelled call must not remain admitted" + ); + assert_eq!( + executor.retained_identity_count_for_test(), + 1, + "the refused identity must be burned and charged exactly once" + ); + assert_eq!(executor.retained_call_id_count(), 1); + assert_eq!( + executor.durable_commit_count_for_test(), + 0, + "prepare must never have started: no durable start/commit was written" + ); + assert!( + !fixture.root.join("post-token.txt").exists(), + "no effect may be published after a boundary cancellation" + ); +} + +/// A group leader can exit before the exit sweep runs. Its unreaped zombie +/// must not hide live descendants: the sweep signals the process group before +/// it reaps the leader, so the descendant cannot outlive the leader. +#[cfg(all(unix, feature = "workspace-io-fault"))] +#[test] +fn exit_sweep_signals_the_group_after_its_leader_exited() { + fn process_alive(pid: u32) -> bool { + unsafe { libc::kill(pid as libc::pid_t, 0) == 0 } + } + + let fixture = Fixture::new("exit-group"); + let executor = Arc::new( + McpToolExecutor::new( + McpToolExecutorConfig::new(&fixture.root) + .with_process_cleanup_timeout(Duration::from_millis(300)), + ) + .expect("executor"), + ); + let gate = Arc::new(SeamGate::default()); + executor + .processes_for_test() + .set_after_os_spawn_hook(Arc::new({ + let gate = Arc::clone(&gate); + move || { + gate.mark_started(); + gate.wait_released(); + } + })); + let worker = { + let executor = Arc::clone(&executor); + std::thread::spawn(move || { + executor.execute_tool( + Some("exit-group"), + "terminal", + &json!({ + "argv": [ + "/bin/sh", + "-c", + "sleep 30 & printf '%s' $! > desc.pid; printf '%s' $$ > root.pid; exit 0" + ] + }), + ) + }) + }; + gate.wait_started(); + + let read_pid = |name: &str| -> u32 { + let deadline = Instant::now() + Duration::from_secs(5); + loop { + if let Ok(text) = fs::read_to_string(fixture.root.join(name)) + && let Ok(pid) = text.trim().parse::() + { + return pid; + } + assert!( + Instant::now() < deadline, + "the child pid file {name} never appeared" + ); + std::thread::sleep(Duration::from_millis(10)); + } + }; + let descendant = read_pid("desc.pid"); + let root = read_pid("root.pid"); + assert!( + registered_child_for_test(root), + "the spawned group leader must be registered" + ); + + assert!( + sweep_registered_child_for_test(root, Instant::now() + Duration::from_secs(2)), + "the exit sweep must prove the group leader gone" + ); + let gone_deadline = Instant::now() + Duration::from_secs(3); + while process_alive(descendant) { + assert!( + Instant::now() < gone_deadline, + "a descendant of an already-exited leader must be killed with its group" + ); + std::thread::sleep(Duration::from_millis(10)); + } + + gate.release(); + let _ = worker.join(); +} + +/// An accepted cancellation intent is never erased by a failed attempt. A +/// later attempt with the same explicit client id is still refused before +/// prepare, even when the earlier attempt failed tool validation. +#[cfg(feature = "workspace-io-fault")] +#[test] +fn a_rejected_attempt_keeps_its_intent_until_a_valid_attempt_is_refused() { + let fixture = Fixture::new("intent-retained"); + fs::write(fixture.root.join("hello.txt"), "hello\n").expect("hello file"); + let executor = executor(&fixture.root); + + assert!( + executor.cancel_call("retained-intent"), + "the intent is recorded before the call fails validation" + ); + let rejected = executor + .execute_tool(Some("retained-intent"), "not_a_tool", &json!({})) + .expect_err("unknown tool"); + assert!(matches!(rejected, McpToolExecutorError::UnknownTool { .. })); + assert_eq!( + executor.pending_pre_admission_cancellations_for_test(), + 1, + "a failed attempt must not erase an accepted cancellation intent" + ); + + let valid = executor + .execute_tool( + Some("retained-intent"), + "read_file", + &json!({"path": "hello.txt"}), + ) + .expect_err("the later valid attempt with the cancelled id must be refused"); + assert!( + matches!(valid, McpToolExecutorError::Cancelled { ref call_id } if call_id == "retained-intent"), + "error={valid:?}" + ); + assert_eq!( + executor.pending_pre_admission_cancellations_for_test(), + 0, + "admission consumes the intent when it refuses the call" + ); + assert_eq!(executor.admitted_call_count(), 0); + assert_eq!( + executor.retained_identity_count_for_test(), + 1, + "the refused identity is burned exactly once" + ); +} + +/// A cancellation that lands after admission's registered token check, but +/// before the handler observes its cancellation branch, must still be visible +/// to the publication fence. The request source is retained in the call state +/// and consulted by the fence, so no prepare and no effect may happen. +/// +/// The source reports "not cancelled" for admission's two checks and +/// "cancelled" for every later observation, exactly modelling that boundary. +#[cfg(feature = "workspace-io-fault")] +#[test] +fn cancellation_after_the_registered_token_check_never_prepares() { + use std::sync::atomic::AtomicUsize; + + let fixture = Fixture::new("post-registration-cancel"); + let executor = Arc::new( + McpToolExecutor::new(McpToolExecutorConfig::new(&fixture.root)).expect("executor"), + ); + let observations = Arc::new(AtomicUsize::new(0)); + let source = { + let observations = Arc::clone(&observations); + AdmissionCancellation::new(move || observations.fetch_add(1, Ordering::SeqCst) >= 2) + }; + + let result = executor + .execute_tool_with_cancellation( + Some("post-registration-call"), + "write_file", + &json!({"path": "post-registration.txt", "content": "leaked\n"}), + Some(source), + ) + .expect("a fence-level cancellation returns a failed tool result, not an executor error"); + assert!( + !result.ok, + "the cancelled call must fail at or before prepare: {result:?}" + ); + assert!( + observations.load(Ordering::SeqCst) >= 3, + "the publication fence must consult the retained request source" + ); + assert_eq!( + executor.durable_prepare_count_for_test(), + 0, + "prepare must never run for a call cancelled before its first effect" + ); + assert_eq!(executor.durable_commit_count_for_test(), 0); + assert!( + !fixture.root.join("post-registration.txt").exists(), + "no effect may be published after a fence-visible cancellation" + ); +} + +/// A request held before admission must be refused when the transport's +/// terminal overflow latch closes, even though no teardown has run yet and the +/// executor is not `closed`. The worker is released after the latch, so on the +/// old behavior it would admit and publish the write. +#[cfg(feature = "workspace-io-fault")] +#[test] +fn the_terminal_overflow_latch_refuses_a_worker_held_before_admission() { + let fixture = Fixture::new("gate-pre-admission"); + let executor = Arc::new( + McpToolExecutor::new(McpToolExecutorConfig::new(&fixture.root)).expect("executor"), + ); + let gate = Arc::new(AtomicBool::new(false)); + executor.set_admission_gate(Arc::clone(&gate)); + let seam = Arc::new(SeamGate::default()); + executor.set_pre_admission_observer_for_test(Arc::new({ + let seam = Arc::clone(&seam); + move |_| { + seam.mark_started(); + seam.wait_released(); + } + })); + + let worker = { + let executor = Arc::clone(&executor); + std::thread::spawn(move || { + executor.execute_tool( + Some("gate-held-call"), + "write_file", + &json!({"path": "gate-held.txt", "content": "leaked\n"}), + ) + }) + }; + seam.wait_started(); + // Close the transport latch exactly as a reader-queue overflow does. The + // executor is not closed and no watchdog teardown has run. + gate.store(true, Ordering::SeqCst); + seam.release(); + + let result = worker.join().expect("held worker"); + assert!( + matches!(result, Err(McpToolExecutorError::Closed)), + "a latched terminal input must refuse the queued call: {result:?}" + ); + assert_eq!(executor.admitted_call_count(), 0); + assert_eq!(executor.retained_identity_count_for_test(), 0); + assert!( + !fixture.root.join("gate-held.txt").exists(), + "a refused queued call must not publish an effect" + ); +} + +/// The overflow hook cancels an already-active call as soon as the terminal +/// latch closes, and every later call is refused at admission. +/// +/// The call is held inside the atomic write's staging step, after admission and +/// prepare: the publication fence must refuse it when the latch cancels the +/// call's own token, so the staged bytes are never published. +#[cfg(feature = "workspace-io-fault")] +#[test] +fn terminal_input_cancels_an_active_call_and_refuses_a_later_one() { + let fixture = Fixture::new("overflow-active"); + let executor = Arc::new( + McpToolExecutor::new(McpToolExecutorConfig::new(&fixture.root)).expect("executor"), + ); + let server = RustScriptToolServer::from_executor(Arc::clone(&executor)).expect("server"); + let staging = Arc::new(SeamGate::default()); + executor + .filesystem_for_test() + .inject_during_staging(Arc::new({ + let staging = Arc::clone(&staging); + move || { + staging.mark_started(); + staging.wait_released(); + } + })); + let worker = { + let executor = Arc::clone(&executor); + std::thread::spawn(move || { + executor.execute_tool( + Some("active-overflow"), + "write_file", + &json!({"path": "overflow-active.txt", "content": "leaked\n"}), + ) + }) + }; + staging.wait_started(); + + // Close the terminal input latch exactly as a reader-queue overflow does. + server.terminate_input_for_test(); + staging.release(); + + let result = worker.join().expect("active worker"); + match result { + Ok(result) => { + assert!( + !result.ok, + "the cancelled active call must not report success: {result:?}" + ); + assert_eq!( + result.error.as_ref().map(|error| error.code.as_str()), + Some("cancelled"), + "the cancelled active call must report the typed cancellation: {result:?}" + ); + } + Err(error) => assert!( + matches!(error, McpToolExecutorError::Cancelled { .. }), + "the cancelled active call must report cancellation, not {error:?}" + ), + } + assert!( + !fixture.root.join("overflow-active.txt").exists(), + "a call cancelled while staging must not publish its effect" + ); + + let late = executor.execute_tool( + Some("late-after-overflow"), + "read_file", + &json!({"path": "hello.txt"}), + ); + assert!( + matches!(late, Err(McpToolExecutorError::Closed)), + "a call after the terminal latch must be refused: {late:?}" + ); +} + +/// A worker parked between the admission gate check and the registration of +/// its call must not escape a terminal input overflow: the overflow latch is +/// taken under the admission lock, registration re-reads it, and the +/// publication fence reads it too, so the write can never be published. +#[cfg(feature = "workspace-io-fault")] +#[test] +fn overflow_between_the_gate_check_and_registration_writes_nothing() { + let fixture = Fixture::new("gate-at-registration"); + let executor = Arc::new( + McpToolExecutor::new(McpToolExecutorConfig::new(&fixture.root)).expect("executor"), + ); + let server = RustScriptToolServer::from_executor(Arc::clone(&executor)).expect("server"); + let seam = Arc::new(SeamGate::default()); + executor.set_admission_observer_for_test(Arc::new({ + let seam = Arc::clone(&seam); + move |call_id: &str| { + if call_id == "gate-registration-call" { + seam.mark_started(); + seam.wait_released(); + } + } + })); + + let worker = { + let executor = Arc::clone(&executor); + std::thread::spawn(move || { + executor.execute_tool( + Some("gate-registration-call"), + "write_file", + &json!({"path": "gate-registration.txt", "content": "leaked\n"}), + ) + }) + }; + seam.wait_started(); + + // Close the terminal latch exactly as a reader-queue overflow does, from + // another thread: the latch and the cancellation snapshot both need the + // admission lock the parked worker currently holds. + let overflow = { + let server = server.clone(); + std::thread::spawn(move || server.terminate_input_for_test()) + }; + std::thread::sleep(Duration::from_millis(100)); + seam.release(); + + let result = worker.join().expect("parked worker"); + overflow.join().expect("overflow thread"); + assert!( + !result.as_ref().is_ok_and(|result| result.ok), + "a call whose registration raced the overflow must not succeed: {result:?}" + ); + assert_eq!( + executor.durable_prepare_count_for_test(), + 0, + "no durable prepare may run for a call cancelled at registration" + ); + assert_eq!(executor.durable_commit_count_for_test(), 0); + assert!( + !fixture.root.join("gate-registration.txt").exists(), + "a call cancelled at registration must not publish an artifact" + ); +} + +/// A cancellation that lands after a call's durable run check has passed, but +/// before its durable parent record is written, must refuse the prepare. The +/// durable implementation cancels from inside `assert_active_run`, which is +/// exactly the interval the lifecycle previously left open. +#[cfg(feature = "workspace-io-fault")] +#[test] +fn cancellation_between_assert_active_run_and_prepare_never_prepares() { + use std::sync::OnceLock; + + struct CancelInAssertActiveRun { + lifecycle: OnceLock, + prepares: std::sync::atomic::AtomicUsize, + call_id: String, + } + + impl DurableToolLifecycle for CancelInAssertActiveRun { + fn assert_active_run(&self, _run_id: &str) -> Result<(), LifecycleError> { + let lifecycle = self.lifecycle.get().expect("lifecycle installed"); + lifecycle.request_call_cancellation(&self.call_id); + Ok(()) + } + + fn prepare_parent( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result<(), LifecycleError> { + self.prepares.fetch_add(1, Ordering::SeqCst); + Ok(()) + } + + fn replay_result( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result, LifecycleError> { + Ok(None) + } + + fn commit_started(&self, _record: &DurableStarted) -> Result<(), LifecycleError> { + Ok(()) + } + + fn commit_result( + &self, + _call_id: &str, + result: &serde_json::Value, + ) -> Result { + Ok(result.clone()) + } + + fn interrupt(&self, _call_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } + } + + let fixture = Fixture::new("prepare-fence"); + let owner = CapabilityOwner::new("mcp", "prepare-fence", "run").expect("owner"); + let durable = Arc::new(CancelInAssertActiveRun { + lifecycle: OnceLock::new(), + prepares: std::sync::atomic::AtomicUsize::new(0), + call_id: "prepare-fence-call".to_string(), + }); + let lifecycle = CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry-prepare-fence") + .workspace(fixture.root.clone()) + .limits(LifecycleLimits { + max_tool_calls: 8, + max_output_bytes: 4096, + max_summary_bytes: 4096, + }) + .deadline_ms(u64::MAX) + .clock(Arc::new(SystemClock)) + .tokens(Arc::new(UuidIssuer)) + .durable(Arc::clone(&durable) as Arc) + .approval(Arc::new(AllowAllApproval)) + .build() + .expect("lifecycle"); + let _ = durable.lifecycle.set(lifecycle.clone()); + + let metadata = PrepareMetadata { + run_id: owner.run().to_string(), + call_id: "prepare-fence-call".to_string(), + tool_name: "write_file".to_string(), + argument_digest: "digest".to_string(), + registry_identity: "registry-prepare-fence".to_string(), + risk_class: CapabilityRisk::Write, + summary: "fenced prepare".to_string(), + }; + let outcome = lifecycle.prepare(&owner, metadata); + assert!( + matches!(outcome, Err(LifecycleError::Cancelled)), + "a cancellation between the run check and the prepare boundary must refuse: {outcome:?}" + ); + assert_eq!( + durable.prepares.load(Ordering::SeqCst), + 0, + "the durable prepare must never run for a cancelled call" + ); +} + +/// A reservation that publishes while the sweep is waiting on another root +/// must be signalled by the same loop. +/// +/// The old sweep sampled quiescence before the wait and, at its cap, counted +/// the entries that appeared during the wait without signalling them, so the +/// late child survived. The test runs in its own process because the +/// production sweep is process-global. +#[cfg(all(unix, feature = "workspace-io-fault"))] +const SWEEP_LATE_PUBLISH_CHILD: &str = "RUSTSCRIPT_AGENT_SWEEP_LATE_PUBLISH_CHILD"; + +#[cfg(all(unix, feature = "workspace-io-fault"))] +#[test] +fn sweep_signals_a_child_published_while_another_root_is_reaped() { + if std::env::var_os(SWEEP_LATE_PUBLISH_CHILD).is_none() { + let base = std::env::temp_dir().join(format!( + "mcp-sweep-late-{}-{}", + std::process::id(), + NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&base).expect("late-publish base"); + let output = + std::process::Command::new(std::env::current_exe().expect("test executable path")) + .args([ + "--exact", + "sweep_signals_a_child_published_while_another_root_is_reaped", + "--nocapture", + "--test-threads=1", + ]) + .env(SWEEP_LATE_PUBLISH_CHILD, "1") + .env( + "RUSTSCRIPT_AGENT_TEST_SPAWN_BEFORE_RECORD_PARK_FILE", + base.join("spawn.park"), + ) + .env( + "RUSTSCRIPT_AGENT_TEST_SPAWN_BEFORE_RECORD_RELEASE_FILE", + base.join("spawn.release"), + ) + .env( + "RUSTSCRIPT_AGENT_TEST_SWEEP_REAP_PARK_FILE", + base.join("reap.park"), + ) + .env( + "RUSTSCRIPT_AGENT_TEST_SWEEP_REAP_RELEASE_FILE", + base.join("reap.release"), + ) + .output() + .expect("run isolated late-publish sweep"); + let _ = fs::remove_dir_all(&base); + assert!( + output.status.success(), + "isolated late-publish sweep failed\nstdout={}\nstderr={}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + return; + } + + let spawn_park = std::env::var_os("RUSTSCRIPT_AGENT_TEST_SPAWN_BEFORE_RECORD_PARK_FILE") + .map(PathBuf::from) + .expect("spawn park path"); + let spawn_release = std::env::var_os("RUSTSCRIPT_AGENT_TEST_SPAWN_BEFORE_RECORD_RELEASE_FILE") + .map(PathBuf::from) + .expect("spawn release path"); + let reap_park = std::env::var_os("RUSTSCRIPT_AGENT_TEST_SWEEP_REAP_PARK_FILE") + .map(PathBuf::from) + .expect("reap park path"); + let reap_release = std::env::var_os("RUSTSCRIPT_AGENT_TEST_SWEEP_REAP_RELEASE_FILE") + .map(PathBuf::from) + .expect("reap release path"); + + let fixture = Fixture::new("sweep-late"); + let executor = Arc::new( + McpToolExecutor::new(McpToolExecutorConfig::new(&fixture.root)).expect("executor"), + ); + + // 1. The first spawn parks between its OS spawn and the recording of its + // pid: a child the first drain cannot name yet. + let late = { + let executor = Arc::clone(&executor); + std::thread::spawn(move || { + executor.execute_tool( + Some("sweep-late-reservation"), + "terminal", + &json!({"argv": ["/bin/sh", "-c", "exec sleep 300"]}), + ) + }) + }; + let park_deadline = Instant::now() + Duration::from_secs(20); + while !spawn_park.exists() { + assert!( + Instant::now() < park_deadline, + "the worker never reached the create-before-record window" + ); + std::thread::sleep(Duration::from_millis(5)); + } + let late_pid: u32 = fs::read_to_string(&spawn_park) + .expect("parked pid file") + .trim() + .parse() + .expect("parked pid"); + assert!( + !registered_child_for_test(late_pid), + "the late child must be invisible to the first drain" + ); + + // 2. A registered, visible root whose reap consumes the sweep's budget. + let background = executor + .execute_tool( + Some("sweep-visible-root"), + "terminal", + &json!({ + "argv": ["/bin/sh", "-c", "printf '%s' $$ > root.pid; exec sleep 300"], + "background": true + }), + ) + .expect("background spawn"); + let _process_id = background.data["process_id"] + .as_str() + .expect("background process id") + .to_string(); + let root: u32 = { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + if let Ok(text) = fs::read_to_string(fixture.root.join("root.pid")) + && let Ok(pid) = text.trim().parse::() + { + break pid; + } + assert!( + Instant::now() < deadline, + "the root pid file never appeared" + ); + std::thread::sleep(Duration::from_millis(10)); + } + }; + + let sweep = + std::thread::spawn(|| sweep_spawned_children(Instant::now() + Duration::from_millis(100))); + let park_deadline = Instant::now() + Duration::from_secs(20); + while !reap_park.exists() { + assert!( + Instant::now() < park_deadline, + "the sweep never reached the visible root's reap wait" + ); + std::thread::sleep(Duration::from_millis(5)); + } + let parked_root: u32 = fs::read_to_string(&reap_park) + .expect("reap park file") + .trim() + .parse() + .expect("parked reap pid"); + assert_eq!( + parked_root, root, + "only the visible root may be in the first drain: parked={parked_root} root={root} late={late_pid}" + ); + + // 3. The parked reservation records its pid and publishes while the sweep + // is still inside the root's reap. It was not part of the first drain, + // so only a re-drain can catch it. + fs::write(&spawn_release, b"release").expect("release late spawn"); + let recorded_deadline = Instant::now() + Duration::from_secs(10); + while !registered_child_for_test(late_pid) { + assert!( + Instant::now() < recorded_deadline, + "the released reservation must record its pid" + ); + std::thread::sleep(Duration::from_millis(10)); + } + // Let the sweep reach its hard cap with the newly visible root still + // undrained. + std::thread::sleep(Duration::from_millis(1500)); + fs::write(&reap_release, b"release").expect("release the reap wait"); + let retained = sweep.join().expect("sweep thread"); + + let gone_deadline = Instant::now() + Duration::from_secs(5); + loop { + let alive = unsafe { libc::kill(late_pid as libc::pid_t, 0) == 0 }; + if !alive { + break; + } + assert!( + Instant::now() < gone_deadline, + "a child that became visible after the first drain must be caught by the final drain (retained={retained})" + ); + std::thread::sleep(Duration::from_millis(10)); + } + assert_eq!(retained, 0, "the sweep must prove every batch gone"); + let late_result = late.join().expect("late worker"); + let _ = late_result; +} + +/// The production exit sweep and an ordinary cleanup must never signal a +/// process group whose ownership was not proven at signal time. +/// +/// The sweep reaps the root first; the ordinary cleanup then runs against the +/// same handle. Its old group number is no longer ours, so it must not be +/// signalled. The test runs in its own process because the production sweep is +/// process-global and would otherwise signal children of concurrently running +/// tests. +#[cfg(all(unix, feature = "workspace-io-fault"))] +const SWEEP_GROUP_RACE_CHILD: &str = "RUSTSCRIPT_AGENT_SWEEP_GROUP_RACE_CHILD"; + +#[cfg(all(unix, feature = "workspace-io-fault"))] +#[test] +fn sweep_and_ordinary_cleanup_never_signal_an_unowned_group() { + if std::env::var_os(SWEEP_GROUP_RACE_CHILD).is_none() { + let base = std::env::temp_dir().join(format!( + "mcp-sweep-race-{}-{}", + std::process::id(), + NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&base).expect("race base"); + let output = + std::process::Command::new(std::env::current_exe().expect("test executable path")) + .args([ + "--exact", + "sweep_and_ordinary_cleanup_never_signal_an_unowned_group", + "--nocapture", + "--test-threads=1", + ]) + .env(SWEEP_GROUP_RACE_CHILD, "1") + .output() + .expect("run isolated sweep race"); + let _ = fs::remove_dir_all(&base); + assert!( + output.status.success(), + "isolated sweep race failed\nstdout={}\nstderr={}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + return; + } + + let fixture = Fixture::new("sweep-race"); + let executor = Arc::new( + McpToolExecutor::new( + McpToolExecutorConfig::new(&fixture.root) + .with_process_cleanup_timeout(Duration::from_millis(300)), + ) + .expect("executor"), + ); + let background = executor + .execute_tool( + Some("sweep-race-root"), + "terminal", + &json!({ + "argv": ["/bin/sh", "-c", "printf '%s' $$ > root.pid; exec sleep 300"], + "background": true + }), + ) + .expect("background spawn"); + assert!( + background.data["process_id"].as_str().is_some(), + "the background spawn must be recorded in the process table" + ); + let root: u32 = { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + if let Ok(text) = fs::read_to_string(fixture.root.join("root.pid")) + && let Ok(pid) = text.trim().parse::() + { + break pid; + } + assert!( + Instant::now() < deadline, + "the root pid file never appeared" + ); + std::thread::sleep(Duration::from_millis(10)); + } + }; + let mut sentinel = std::process::Command::new("/bin/sleep") + .arg("300") + .spawn() + .expect("sentinel process"); + + // Every numeric group signal fired by the production helper is recorded + // with its instant, for either path. + let signals: Arc>> = Arc::new(Mutex::new(Vec::new())); + set_sweep_group_observer_for_test(Arc::new({ + let signals = Arc::clone(&signals); + move |pid| { + signals + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .push((pid, Instant::now())); + } + })); + + // The ordinary cleanup is ready and racing, but its group signal can only + // run after the sweep has reaped the root: that is the ordering the old + // unconditional `kill(-pid)` got wrong. + let (release_ordinary, wait_release) = std::sync::mpsc::channel::<()>(); + let ordinary = { + let executor = Arc::clone(&executor); + std::thread::spawn(move || { + let _ = wait_release.recv(); + // The ordinary teardown of the recorded handle: it runs the same + // tree cleanup (and group signal) a normal shutdown uses. + let _ = executor + .processes_for_test() + .shutdown_all_within(Instant::now() + Duration::from_millis(300)); + }) + }; + let sweep = + std::thread::spawn(|| sweep_spawned_children(Instant::now() + Duration::from_secs(5))); + let swept = sweep.join().expect("sweep thread"); + let swept_at = Instant::now(); + release_ordinary.send(()).expect("release ordinary cleanup"); + ordinary.join().expect("ordinary cleanup thread"); + clear_sweep_group_observer_for_test(); + + let observed = signals + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .clone(); + assert_eq!(swept, 0, "the sweep must prove the root gone"); + assert!( + observed.iter().any(|(pid, _)| *pid == root), + "the sweep must have signalled the root's group: {observed:?}" + ); + let after_reap = observed + .iter() + .filter(|(pid, at)| *pid == root && *at > swept_at) + .count(); + assert_eq!( + after_reap, 0, + "the ordinary reaper must not signal a group whose root the sweep already reaped: {observed:?}" + ); + assert!( + unsafe { libc::kill(sentinel.id() as libc::pid_t, 0) == 0 }, + "an unrelated process must never be signalled" + ); + let _ = sentinel.kill(); + let _ = sentinel.wait(); +} + +/// The exit sweep's group observation and numeric group signal are +/// serialized against an ordinary reap of the same root. +/// +/// The sweep is parked after `waitid(WNOWAIT)` and before `kill(-pid)` while +/// holding the reap lock. A concurrent ordinary `try_wait` must not reap the +/// root or kill its group in that window, because a recycled pid could then +/// name an unrelated group. The sentinel proves no unrelated process was +/// signalled. +#[cfg(all(target_os = "linux", feature = "workspace-io-fault"))] +#[test] +fn exit_sweep_group_signal_is_serialized_with_the_ordinary_reaper() { + let fixture = Fixture::new("reap-serialized"); + let executor = Arc::new( + McpToolExecutor::new( + McpToolExecutorConfig::new(&fixture.root) + .with_process_cleanup_timeout(Duration::from_millis(300)), + ) + .expect("executor"), + ); + + let sentinel = std::process::Command::new("/bin/sleep") + .arg("300") + .spawn() + .expect("sentinel process"); + let sentinel_pid = sentinel.id(); + let sentinel = Arc::new(Mutex::new(Some(sentinel))); + + let background = executor + .execute_tool( + Some("reap-serialized-background"), + "terminal", + &json!({ + "argv": [ + "/bin/sh", + "-c", + "sleep 300 & printf '%s' $! > desc.pid; printf '%s' $$ > root.pid; exit 0" + ], + "background": true + }), + ) + .expect("background spawn"); + let process_id = background.data["process_id"] + .as_str() + .expect("background process id") + .to_string(); + + let read_pid = |name: &str| -> u32 { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + if let Ok(text) = fs::read_to_string(fixture.root.join(name)) + && let Ok(pid) = text.trim().parse() + { + return pid; + } + assert!( + Instant::now() < deadline, + "the {name} pid file never appeared" + ); + std::thread::sleep(Duration::from_millis(10)); + } + }; + let root = read_pid("root.pid"); + let descendant = read_pid("desc.pid"); + // Wait for the leader to become an unreaped zombie: the sweep then + // observes it with WNOWAIT instead of finding a live child. + let zombie_deadline = Instant::now() + Duration::from_secs(10); + loop { + let stat = fs::read_to_string(format!("/proc/{root}/stat")).unwrap_or_default(); + if stat + .rfind(')') + .and_then(|close| stat[close + 1..].split_whitespace().next()) + == Some("Z") + { + break; + } + assert!( + Instant::now() < zombie_deadline, + "the background group leader never exited" + ); + std::thread::sleep(Duration::from_millis(10)); + } + + let sweep_entered = Arc::new(SeamGate::default()); + set_sweep_group_observer_for_test(Arc::new({ + let sweep_entered = Arc::clone(&sweep_entered); + move |pid| { + if pid == root { + sweep_entered.mark_started(); + sweep_entered.wait_released(); + } + } + })); + + let sweep = { + let sweep_entered = Arc::clone(&sweep_entered); + std::thread::spawn(move || { + let swept = + sweep_registered_child_for_test(root, Instant::now() + Duration::from_secs(5)); + sweep_entered.release(); + swept + }) + }; + sweep_entered.wait_started(); + + let reap_done = Arc::new(AtomicBool::new(false)); + let reaper = { + let executor = Arc::clone(&executor); + let reap_done = Arc::clone(&reap_done); + let process_id = process_id.clone(); + std::thread::spawn(move || { + let reaped = executor + .processes_for_test() + .reap_handle_for_test(&process_id); + reap_done.store(true, Ordering::SeqCst); + reaped + }) + }; + + // The ordinary reap must be blocked inside the sweep's observation + // window: the leader stays an unreaped zombie and the reaper's own group + // kill has not run, so the descendant is still alive. + std::thread::sleep(Duration::from_millis(300)); + assert!( + !reap_done.load(Ordering::SeqCst), + "an ordinary reap must not interleave between WNOWAIT and the group signal" + ); + assert!( + unsafe { libc::kill(root as libc::pid_t, 0) == 0 }, + "the sweep's WNOWAIT window must keep the root unreaped" + ); + assert!( + unsafe { libc::kill(descendant as libc::pid_t, 0) == 0 }, + "no reaper may signal the group while the sweep owns the observation" + ); + + sweep_entered.release(); + let swept = sweep.join().expect("sweep thread"); + assert!(swept, "the sweep must prove the group leader gone"); + let _ = reaper.join().expect("reaper thread"); + + clear_sweep_group_observer_for_test(); + let gone_deadline = Instant::now() + Duration::from_secs(5); + for pid in [root, descendant] { + loop { + let alive = unsafe { libc::kill(pid as libc::pid_t, 0) == 0 }; + if !alive { + break; + } + assert!( + Instant::now() < gone_deadline, + "pid {pid} survived the serialized sweep and reap" + ); + std::thread::sleep(Duration::from_millis(10)); + } + } + assert!( + unsafe { libc::kill(sentinel_pid as libc::pid_t, 0) == 0 }, + "an unrelated process must never be signalled" + ); + if let Some(mut sentinel) = sentinel + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .take() + { + let _ = sentinel.kill(); + let _ = sentinel.wait(); + } +} + +/// Re-runs one test in a fresh process when `marker` is absent. +/// +/// The exit sweep, the pidfd-failure counter and the process-wide reap lock +/// are all process globals; an isolated child keeps each scenario exact. +#[cfg(all(unix, feature = "workspace-io-fault"))] +fn run_isolated(test: &str, marker: &str, extra_env: &[(&str, PathBuf)]) -> bool { + if std::env::var_os(marker).is_some() { + return false; + } + let mut command = + std::process::Command::new(std::env::current_exe().expect("test executable path")); + command + .args(["--exact", test, "--nocapture", "--test-threads=1"]) + .env(marker, "1"); + for (name, path) in extra_env { + command.env(name, path); + } + let output = command.output().expect("run isolated test"); + assert!( + output.status.success(), + "isolated {test} failed\nstdout={}\nstderr={}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + true +} + +#[cfg(all(unix, feature = "workspace-io-fault"))] +fn wait_for_file(path: &std::path::Path, deadline: Instant, what: &str) { + while !path.exists() { + assert!(Instant::now() < deadline, "{what} never appeared"); + std::thread::sleep(Duration::from_millis(10)); + } +} + +/// The durable prepare boundary is call-scoped. +/// +/// Call A is parked inside its own `prepare_parent`. Call B must still prepare, +/// conclude its approval facts and be cancelled, and a third call that has not +/// prepared must be cancellable too - all before A is released. A cancellation +/// recorded while A is inside the durable write must still refuse A at its +/// boundary exit, and must keep refusing later prepares of A. +#[cfg(all(unix, feature = "workspace-io-fault"))] +#[test] +fn prepare_gate_is_call_scoped_and_still_refuses_a_cancelled_boundary() { + struct RecordingDurable { + prepares: Mutex>, + park: Arc, + } + + impl DurableToolLifecycle for RecordingDurable { + fn assert_active_run(&self, _run_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } + + fn prepare_parent( + &self, + _run_id: &str, + call_id: &str, + _tool_name: &str, + ) -> Result<(), LifecycleError> { + self.prepares + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .push(call_id.to_string()); + // Park inside the durable write itself, after the gate's final + // cancellation read: this is the window the boundary must cover. + if call_id == "gate-call-a" { + self.park.mark_started(); + self.park.wait_released(); + } + Ok(()) + } + + fn replay_result( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result, LifecycleError> { + Ok(None) + } + + fn commit_started(&self, _record: &DurableStarted) -> Result<(), LifecycleError> { + Ok(()) + } + + fn commit_result( + &self, + _call_id: &str, + result: &serde_json::Value, + ) -> Result { + Ok(result.clone()) + } + + fn interrupt(&self, _call_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } + } + + let fixture = Fixture::new("prepare-gate-scope"); + let owner = CapabilityOwner::new("mcp", "prepare-gate", "run").expect("owner"); + let park = Arc::new(SeamGate::default()); + let durable = Arc::new(RecordingDurable { + prepares: Mutex::new(Vec::new()), + park: Arc::clone(&park), + }); + let lifecycle = CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry-prepare-gate") + .workspace(fixture.root.clone()) + .limits(LifecycleLimits { + max_tool_calls: 8, + max_output_bytes: 4096, + max_summary_bytes: 4096, + }) + .deadline_ms(u64::MAX) + .clock(Arc::new(SystemClock)) + .tokens(Arc::new(UuidIssuer)) + .durable(Arc::clone(&durable) as Arc) + .approval(Arc::new(AllowAllApproval)) + .build() + .expect("lifecycle"); + + let metadata = |call_id: &str| PrepareMetadata { + run_id: owner.run().to_string(), + call_id: call_id.to_string(), + tool_name: "read_file".to_string(), + argument_digest: "digest".to_string(), + registry_identity: "registry-prepare-gate".to_string(), + risk_class: CapabilityRisk::Read, + summary: "call-scoped prepare".to_string(), + }; + + let parked = { + let lifecycle = lifecycle.clone(); + let owner = owner.clone(); + let metadata = metadata("gate-call-a"); + std::thread::spawn(move || lifecycle.prepare(&owner, metadata)) + }; + park.wait_started(); + + // 1. A different call prepares while call A is parked inside its durable + // prepare. + let (probe_tx, probe_rx) = std::sync::mpsc::channel(); + let probe = { + let lifecycle = lifecycle.clone(); + let owner = owner.clone(); + let metadata = metadata("gate-call-b"); + std::thread::spawn(move || { + let _ = probe_tx.send(lifecycle.prepare(&owner, metadata)); + }) + }; + let outcome_b = probe_rx + .recv_timeout(Duration::from_secs(5)) + .expect("another call's prepare must not wait behind a parked prepare"); + let token_b = match outcome_b { + Ok(PrepareOutcome::Execute { + execution_token, .. + }) => execution_token, + other => panic!("call B must execute, got {other:?}"), + }; + + // 2. Cancelling B (which has a token) and C (which has none) must both be + // recorded before A is released. C's cancellation is the one that used + // to wait on A's durable write. + let (cancel_tx, cancel_rx) = std::sync::mpsc::channel(); + let canceller = { + let lifecycle = lifecycle.clone(); + std::thread::spawn(move || { + let b = lifecycle.request_call_cancellation("gate-call-b"); + let c = lifecycle.request_call_cancellation("gate-call-c"); + let a = lifecycle.request_call_cancellation("gate-call-a"); + let _ = cancel_tx.send((b, c, a)); + }) + }; + let (cancelled_b, cancelled_c, cancelled_a) = cancel_rx + .recv_timeout(Duration::from_secs(2)) + .expect("a cancellation must be recorded without waiting on a durable write"); + assert!(cancelled_b, "B already has an open token to fence"); + assert!(!cancelled_c, "C has not prepared, so no token exists yet"); + assert!(!cancelled_a, "A has no token while it is parked"); + assert!( + matches!( + lifecycle.enter_publication(&token_b), + Err(LifecycleError::Cancelled) + ), + "a cancelled call must not publish" + ); + + // 3. Releasing A must refuse the call: the cancellation was recorded while + // A was inside its durable write, so no token may be handed out. + park.release(); + let outcome_a = parked.join().expect("parked prepare"); + assert!( + matches!(outcome_a, Err(LifecycleError::Cancelled)), + "a cancellation recorded inside the durable prepare must refuse it: {outcome_a:?}" + ); + probe.join().expect("probe prepare"); + canceller.join().expect("cancellation thread"); + + let refused_c = lifecycle.prepare(&owner, metadata("gate-call-c")); + assert!( + matches!(refused_c, Err(LifecycleError::Cancelled)), + "a durable prepare after the call's own cancellation must be refused: {refused_c:?}" + ); + assert_eq!( + *durable + .prepares + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()), + vec!["gate-call-a".to_string(), "gate-call-b".to_string()], + "A crossed its durable boundary before the cancellation; C and the A retry never did" + ); + assert_eq!(lifecycle.open_token_count(), 1); +} + +/// A cancellation recorded while the durable `prepare_parent` is running must +/// still refuse the call. +/// +/// The call's one gate stays in its map entry from the boundary through the +/// token handoff, and the cancellation is recorded in the shared prepare +/// ledger, so a prepare that already entered the durable write still observes +/// the intent before it can hand out a token. +#[cfg(all(unix, feature = "workspace-io-fault"))] +#[test] +fn cancellation_inside_prepare_parent_refuses_the_call() { + struct ParkedDurable { + park: Arc, + prepares: Mutex>, + } + + impl DurableToolLifecycle for ParkedDurable { + fn assert_active_run(&self, _run_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } + + fn prepare_parent( + &self, + _run_id: &str, + call_id: &str, + _tool_name: &str, + ) -> Result<(), LifecycleError> { + self.prepares + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .push(call_id.to_string()); + if call_id == "inside-prepare-call" { + self.park.mark_started(); + self.park.wait_released(); + } + Ok(()) + } + + fn replay_result( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result, LifecycleError> { + Ok(None) + } + + fn commit_started(&self, _record: &DurableStarted) -> Result<(), LifecycleError> { + Ok(()) + } + + fn commit_result( + &self, + _call_id: &str, + result: &serde_json::Value, + ) -> Result { + Ok(result.clone()) + } + + fn interrupt(&self, _call_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } + } + + let fixture = Fixture::new("prepare-parent-cancel"); + let owner = CapabilityOwner::new("mcp", "prepare-parent", "run").expect("owner"); + let park = Arc::new(SeamGate::default()); + let durable = Arc::new(ParkedDurable { + park: Arc::clone(&park), + prepares: Mutex::new(Vec::new()), + }); + let metadata = |call_id: &str| PrepareMetadata { + run_id: owner.run().to_string(), + call_id: call_id.to_string(), + tool_name: "read_file".to_string(), + argument_digest: "digest".to_string(), + registry_identity: "registry-prepare-parent".to_string(), + risk_class: CapabilityRisk::Read, + summary: "cancelled inside prepare_parent".to_string(), + }; + let lifecycle = CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry-prepare-parent") + .workspace(fixture.root.clone()) + .limits(LifecycleLimits { + max_tool_calls: 8, + max_output_bytes: 4096, + max_summary_bytes: 4096, + }) + .deadline_ms(u64::MAX) + .clock(Arc::new(SystemClock)) + .tokens(Arc::new(UuidIssuer)) + .durable(Arc::clone(&durable) as Arc) + .approval(Arc::new(AllowAllApproval)) + .build() + .expect("lifecycle"); + + let parked = { + let lifecycle = lifecycle.clone(); + let owner = owner.clone(); + let metadata = metadata("inside-prepare-call"); + std::thread::spawn(move || lifecycle.prepare(&owner, metadata)) + }; + park.wait_started(); + assert_eq!( + lifecycle.open_token_state_count_for_test(), + 0, + "the durable boundary must run before any token exists" + ); + assert!( + !lifecycle.request_call_cancellation("inside-prepare-call"), + "a call inside its durable prepare has no token to fence yet" + ); + park.release(); + + let outcome = parked.join().expect("parked prepare"); + assert!( + matches!(outcome, Err(LifecycleError::Cancelled)), + "a cancellation recorded inside prepare_parent must refuse the call: {outcome:?}" + ); + assert_eq!( + lifecycle.open_token_count(), + 0, + "a refused prepare must not hand out a token" + ); + + // The refusal is durable: a retry never reaches the durable write again. + let crossed = durable + .prepares + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .len(); + let retry = lifecycle.prepare(&owner, metadata("inside-prepare-call")); + assert!( + matches!(retry, Err(LifecycleError::Cancelled)), + "the recorded cancellation must refuse every later prepare: {retry:?}" + ); + assert_eq!( + durable + .prepares + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .len(), + crossed, + "a refused prepare must not cross the durable boundary again" + ); +} + +/// A cancellation recorded while `commit_started` runs must reach the token's +/// publication fence. +/// +/// No token exists during that durable write, so the intent is recorded in the +/// shared prepare ledger. The token created right afterwards must inherit it as +/// its own publication cancellation instead of admitting a write. +#[cfg(all(unix, feature = "workspace-io-fault"))] +#[test] +fn cancellation_inside_commit_started_fences_the_publication() { + struct ParkedStart { + park: Arc, + } + + impl DurableToolLifecycle for ParkedStart { + fn assert_active_run(&self, _run_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } + + fn prepare_parent( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result<(), LifecycleError> { + Ok(()) + } + + fn replay_result( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result, LifecycleError> { + Ok(None) + } + + fn commit_started(&self, record: &DurableStarted) -> Result<(), LifecycleError> { + if record.call_id == "inside-commit-call" { + self.park.mark_started(); + self.park.wait_released(); + } + Ok(()) + } + + fn commit_result( + &self, + _call_id: &str, + result: &serde_json::Value, + ) -> Result { + Ok(result.clone()) + } + + fn interrupt(&self, _call_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } + } + + let fixture = Fixture::new("commit-started-cancel"); + let owner = CapabilityOwner::new("mcp", "commit-started", "run").expect("owner"); + let park = Arc::new(SeamGate::default()); + let durable = Arc::new(ParkedStart { + park: Arc::clone(&park), + }); + let lifecycle = CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry-commit-started") + .workspace(fixture.root.clone()) + .limits(LifecycleLimits { + max_tool_calls: 8, + max_output_bytes: 4096, + max_summary_bytes: 4096, + }) + .deadline_ms(u64::MAX) + .clock(Arc::new(SystemClock)) + .tokens(Arc::new(UuidIssuer)) + .durable(Arc::clone(&durable) as Arc) + .approval(Arc::new(AllowAllApproval)) + .build() + .expect("lifecycle"); + + let parked = { + let lifecycle = lifecycle.clone(); + let owner = owner.clone(); + let metadata = PrepareMetadata { + run_id: owner.run().to_string(), + call_id: "inside-commit-call".to_string(), + tool_name: "read_file".to_string(), + argument_digest: "digest".to_string(), + registry_identity: "registry-commit-started".to_string(), + risk_class: CapabilityRisk::Read, + summary: "cancelled inside commit_started".to_string(), + }; + std::thread::spawn(move || lifecycle.prepare(&owner, metadata)) + }; + park.wait_started(); + assert!( + !lifecycle.request_call_cancellation("inside-commit-call"), + "the call has no token while its durable start is being written" + ); + park.release(); + + let token = match parked.join().expect("parked prepare") { + Ok(PrepareOutcome::Execute { + execution_token, .. + }) => execution_token, + other => panic!("the durable start already acknowledged, got {other:?}"), + }; + assert!( + matches!( + lifecycle.enter_publication(&token), + Err(LifecycleError::Cancelled) + ), + "the prepare cancellation must be inherited by the publication fence" + ); +} + +/// A child recorded at the OS spawn is sweepable before its worker publishes. +/// +/// The worker parks between the spawn and its publication, so the only thing +/// that can stop the child at the exit cap is the registry entry written at +/// the spawn. The spawn effect must also be recorded before that worker can be +/// abandoned. +#[cfg(all(unix, feature = "workspace-io-fault"))] +const SWEEP_UNPUBLISHED_CHILD: &str = "RUSTSCRIPT_AGENT_SWEEP_UNPUBLISHED_CHILD"; + +#[cfg(all(unix, feature = "workspace-io-fault"))] +#[test] +fn sweep_reaps_a_child_recorded_before_its_publication() { + let base = std::env::temp_dir().join(format!( + "mcp-sweep-unpublished-{}-{}", + std::process::id(), + NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&base).expect("unpublished-sweep base"); + if run_isolated( + "sweep_reaps_a_child_recorded_before_its_publication", + SWEEP_UNPUBLISHED_CHILD, + &[ + ( + "RUSTSCRIPT_AGENT_TEST_SPAWN_PARK_FILE", + base.join("spawn.park"), + ), + ( + "RUSTSCRIPT_AGENT_TEST_SPAWN_RELEASE_FILE", + base.join("spawn.release"), + ), + ], + ) { + let _ = fs::remove_dir_all(&base); + return; + } + + let spawn_park = std::env::var_os("RUSTSCRIPT_AGENT_TEST_SPAWN_PARK_FILE") + .map(PathBuf::from) + .expect("spawn park path"); + let spawn_release = std::env::var_os("RUSTSCRIPT_AGENT_TEST_SPAWN_RELEASE_FILE") + .map(PathBuf::from) + .expect("spawn release path"); + let fixture = Fixture::new("sweep-unpublished"); + let executor = Arc::new( + McpToolExecutor::new(McpToolExecutorConfig::new(&fixture.root)).expect("executor"), + ); + let lifecycle = Arc::clone(executor.lifecycle_for_test()); + let call_id = "sweep-unpublished-call"; + + let worker = { + let executor = Arc::clone(&executor); + std::thread::spawn(move || { + executor.execute_tool( + Some(call_id), + "terminal", + &json!({"argv": ["/bin/sh", "-c", "exec sleep 300"], "background": true}), + ) + }) + }; + wait_for_file( + &spawn_park, + Instant::now() + Duration::from_secs(20), + "spawn park", + ); + let parked_pid: u32 = fs::read_to_string(&spawn_park) + .expect("parked pid file") + .trim() + .parse() + .expect("parked pid"); + assert!( + registered_child_for_test(parked_pid), + "the pid must be sweep-visible at the OS spawn, before publication" + ); + + let sweep = + std::thread::spawn(|| sweep_spawned_children(Instant::now() + Duration::from_millis(100))); + let gone_deadline = Instant::now() + Duration::from_secs(5); + loop { + if unsafe { libc::kill(parked_pid as libc::pid_t, 0) != 0 } { + break; + } + assert!( + Instant::now() < gone_deadline, + "the sweep must signal and reap a child recorded before its publication" + ); + std::thread::sleep(Duration::from_millis(10)); + } + + // The real effect is recorded before the worker's publication decision, so + // the native ledger already owns the spawn the sweep terminated. + let outcome = lifecycle + .call_native_outcome(call_id) + .expect("the spawn effect must be recorded before publication"); + assert!( + outcome + .record + .process + .is_some_and(|process| process.pid == parked_pid), + "the native ledger must carry the recorded spawn: {outcome:?}" + ); + + // Let the sweep reach its hard cap and abandon the still-parked + // reservation before the worker publishes. The child it already killed is + // not counted as unproven because its record was visible to that drain. + let retained = sweep.join().expect("sweep thread"); + assert_eq!( + retained, 0, + "a child recorded before publication is signalled and proven by the final drain" + ); + + fs::write(&spawn_release, b"release").expect("release the parked spawn"); + let result = worker + .join() + .expect("parked worker") + .expect("terminal tool result"); + assert!( + !result.ok, + "the abandoned spawn must not succeed: {result:?}" + ); + assert!( + result + .error + .as_ref() + .is_some_and(|error| error.code == "closing"), + "the publisher must observe the abandoned reservation, not a usable handle: {result:?}" + ); +} + +/// A child that exists before its pid is recorded is accounted for and +/// terminated. +/// +/// The worker parks in the narrowest ownership window: the OS child exists but +/// the registry cannot name it. The final drain cannot signal that child, so it +/// must give the reservation exactly one disposition and leave the child to its +/// publisher, which terminates it as soon as it can name it - not only when a +/// later publication happens to run. +#[cfg(all(unix, feature = "workspace-io-fault"))] +const SPAWN_GAP_CHILD: &str = "RUSTSCRIPT_AGENT_SPAWN_GAP_CHILD"; + +#[cfg(all(unix, feature = "workspace-io-fault"))] +#[test] +fn sweep_accounts_for_a_child_spawned_before_its_pid_is_recorded() { + let base = std::env::temp_dir().join(format!( + "mcp-spawn-gap-{}-{}", + std::process::id(), + NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&base).expect("spawn-gap base"); + if run_isolated( + "sweep_accounts_for_a_child_spawned_before_its_pid_is_recorded", + SPAWN_GAP_CHILD, + &[ + ( + "RUSTSCRIPT_AGENT_TEST_SPAWN_BEFORE_RECORD_PARK_FILE", + base.join("gap.park"), + ), + ( + "RUSTSCRIPT_AGENT_TEST_SPAWN_BEFORE_RECORD_RELEASE_FILE", + base.join("gap.release"), + ), + ( + "RUSTSCRIPT_AGENT_TEST_SPAWN_PARK_FILE", + base.join("publish.park"), + ), + ( + "RUSTSCRIPT_AGENT_TEST_SPAWN_RELEASE_FILE", + base.join("publish.release"), + ), + ], + ) { + let _ = fs::remove_dir_all(&base); + return; + } + + let gap_park = std::env::var_os("RUSTSCRIPT_AGENT_TEST_SPAWN_BEFORE_RECORD_PARK_FILE") + .map(PathBuf::from) + .expect("gap park path"); + let gap_release = std::env::var_os("RUSTSCRIPT_AGENT_TEST_SPAWN_BEFORE_RECORD_RELEASE_FILE") + .map(PathBuf::from) + .expect("gap release path"); + let publish_park = std::env::var_os("RUSTSCRIPT_AGENT_TEST_SPAWN_PARK_FILE") + .map(PathBuf::from) + .expect("publish park path"); + let publish_release = std::env::var_os("RUSTSCRIPT_AGENT_TEST_SPAWN_RELEASE_FILE") + .map(PathBuf::from) + .expect("publish release path"); + + let fixture = Fixture::new("spawn-gap"); + let executor = Arc::new( + McpToolExecutor::new(McpToolExecutorConfig::new(&fixture.root)).expect("executor"), + ); + let worker = { + let executor = Arc::clone(&executor); + std::thread::spawn(move || { + executor.execute_tool( + Some("spawn-gap-call"), + "terminal", + &json!({"argv": ["/bin/sh", "-c", "exec sleep 300"]}), + ) + }) + }; + wait_for_file( + &gap_park, + Instant::now() + Duration::from_secs(20), + "create-before-record park", + ); + let pid: u32 = fs::read_to_string(&gap_park) + .expect("gap pid file") + .trim() + .parse() + .expect("gap pid"); + assert!( + !registered_child_for_test(pid), + "the child must not be sweep-visible before its pid is recorded" + ); + + // The final drain cannot name this child: it must account for the + // reservation exactly once instead of dropping it. + let retained = sweep_spawned_children(Instant::now() + Duration::from_millis(50)); + assert_eq!( + retained, 1, + "one abandoned reservation is exactly one unproven disposition" + ); + + fs::write(&gap_release, b"release").expect("release the create-before-record park"); + wait_for_file( + &publish_park, + Instant::now() + Duration::from_secs(20), + "post-record park", + ); + // The worker is parked before its publication. The child it can now name + // must already be terminated by the record itself, because the sweep that + // could have owned it has already run. + let gone_deadline = Instant::now() + Duration::from_secs(5); + loop { + if unsafe { libc::kill(pid as libc::pid_t, 0) != 0 } { + break; + } + assert!( + Instant::now() < gone_deadline, + "a child recorded after the final drain must be terminated by its publisher" + ); + std::thread::sleep(Duration::from_millis(10)); + } + + fs::write(&publish_release, b"release").expect("release the parked publish"); + let result = worker + .join() + .expect("parked worker") + .expect("terminal tool result"); + assert!( + !result.ok, + "the abandoned spawn must not succeed: {result:?}" + ); + assert!( + result + .error + .as_ref() + .is_some_and(|error| error.code == "closing"), + "the publisher must refuse a child it no longer owns: {result:?}" + ); + assert!( + !registered_child_for_test(pid), + "the drained record must not be resurrected" + ); +} + +/// A drained record is a tombstone: a late publish must not recreate it. +/// +/// The sweep drains and reaps the recorded child without abandoning the +/// registry. The publisher that arrives afterwards must observe the drain +/// rather than recreate an entry (and reopen a pidfd) for a pid that may +/// already be recycled. +#[cfg(all(unix, feature = "workspace-io-fault"))] +const DRAINED_BEFORE_ABANDON_CHILD: &str = "RUSTSCRIPT_AGENT_DRAINED_BEFORE_ABANDON_CHILD"; + +#[cfg(all(unix, feature = "workspace-io-fault"))] +#[test] +fn a_drained_record_is_never_recreated_by_a_late_publish() { + let base = std::env::temp_dir().join(format!( + "mcp-drained-before-abandon-{}-{}", + std::process::id(), + NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&base).expect("drained base"); + if run_isolated( + "a_drained_record_is_never_recreated_by_a_late_publish", + DRAINED_BEFORE_ABANDON_CHILD, + &[ + ( + "RUSTSCRIPT_AGENT_TEST_SPAWN_PARK_FILE", + base.join("publish.park"), + ), + ( + "RUSTSCRIPT_AGENT_TEST_SPAWN_RELEASE_FILE", + base.join("publish.release"), + ), + ], + ) { + let _ = fs::remove_dir_all(&base); + return; + } + + let publish_park = std::env::var_os("RUSTSCRIPT_AGENT_TEST_SPAWN_PARK_FILE") + .map(PathBuf::from) + .expect("publish park path"); + let publish_release = std::env::var_os("RUSTSCRIPT_AGENT_TEST_SPAWN_RELEASE_FILE") + .map(PathBuf::from) + .expect("publish release path"); + + let fixture = Fixture::new("drained-before-abandon"); + let executor = Arc::new( + McpToolExecutor::new(McpToolExecutorConfig::new(&fixture.root)).expect("executor"), + ); + let worker = { + let executor = Arc::clone(&executor); + std::thread::spawn(move || { + executor.execute_tool( + Some("drained-before-abandon-call"), + "terminal", + &json!({"argv": ["/bin/sh", "-c", "exec sleep 300"]}), + ) + }) + }; + wait_for_file( + &publish_park, + Instant::now() + Duration::from_secs(20), + "post-record park", + ); + let pid: u32 = fs::read_to_string(&publish_park) + .expect("parked pid file") + .trim() + .parse() + .expect("parked pid"); + assert!( + registered_child_for_test(pid), + "a recorded child must be sweep-visible before publication" + ); + + // Drain and reap the recorded child without abandoning the registry. + assert!( + sweep_registered_child_for_test(pid, Instant::now() + Duration::from_secs(5)), + "the drain must signal and reap the recorded child" + ); + assert!( + !registered_child_for_test(pid), + "a drained record stops naming a live child" + ); + + fs::write(&publish_release, b"release").expect("release the parked publish"); + let result = worker + .join() + .expect("parked worker") + .expect("terminal tool result"); + assert!( + !result.ok, + "a publisher that lost its child to the drain must refuse: {result:?}" + ); + assert!( + result + .error + .as_ref() + .is_some_and(|error| error.code == "closing"), + "the spawn must report the drain, not a usable handle: {result:?}" + ); + assert!( + !registered_child_for_test(pid), + "publish must never recreate a drained record" + ); + assert!( + unsafe { libc::kill(pid as libc::pid_t, 0) != 0 }, + "the drained child must stay reaped" + ); +} + +/// The destructor obeys the group decision, exactly like every other reaper. +/// +/// Another reaper owns the group decision for the whole teardown, so no attempt +/// can decide it. The destructor must then leave the leader unreaped (its pid +/// still reserves the group id) and keep the exit-sweep record that still owns +/// the tree instead of dropping the last ownership it has. +#[cfg(all(unix, feature = "workspace-io-fault"))] +const DESTRUCTOR_PENDING_CHILD: &str = "RUSTSCRIPT_AGENT_DESTRUCTOR_PENDING_CHILD"; + +#[cfg(all(target_os = "linux", feature = "workspace-io-fault"))] +#[test] +fn destructor_with_a_pending_group_decision_keeps_the_leader_and_the_record() { + if run_isolated( + "destructor_with_a_pending_group_decision_keeps_the_leader_and_the_record", + DESTRUCTOR_PENDING_CHILD, + &[], + ) { + return; + } + + let fixture = Fixture::new("destructor-pending"); + let executor = Arc::new( + McpToolExecutor::new( + McpToolExecutorConfig::new(&fixture.root) + .with_process_cleanup_timeout(Duration::from_millis(300)), + ) + .expect("executor"), + ); + let background = executor + .execute_tool( + Some("destructor-pending-root"), + "terminal", + &json!({ + "argv": [ + "/bin/sh", + "-c", + "printf '%s' $$ > root.pid; exec sleep 300" + ], + "background": true + }), + ) + .expect("background spawn"); + assert!( + background.data["process_id"].as_str().is_some(), + "the background spawn must be recorded in the process table" + ); + let pid: u32 = { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + if let Ok(text) = fs::read_to_string(fixture.root.join("root.pid")) + && let Ok(pid) = text.trim().parse() + { + break pid; + } + assert!( + Instant::now() < deadline, + "the root pid file never appeared" + ); + std::thread::sleep(Duration::from_millis(10)); + } + }; + + // Another reaper owns the group decision for the whole teardown. + let reap_lock = hold_reap_serial_for_test(); + let proof = executor.shutdown(); + assert!( + !proof.is_clean(), + "a decision that timed out must never report a cleaned tree: {proof:?}" + ); + // The destructor runs while the decision is still Pending. It must not + // reap the leader and must keep the sweep's ownership of the tree. + drop(executor); + + let state = proc_state(pid); + assert!( + state.as_deref().is_some_and(|state| state != "Z"), + "the destructor must not kill or reap a leader whose group decision timed out: {state:?}" + ); + assert!( + registered_child_for_test(pid), + "an unproven tree must stay owned by the exit sweep, not lose its record" + ); + + // Releasing the decision lock hands the retained tree to the bounded + // reclaimer. It must decide, kill and reap without waiting for process + // exit, and the record must disappear only after that proof. + drop(reap_lock); + let reclaim_deadline = Instant::now() + Duration::from_secs(10); + while registered_child_for_test(pid) || proc_state(pid).is_some() { + assert!( + Instant::now() < reclaim_deadline, + "the retained tree must be reclaimed in a long-lived process: record={} state={:?}", + registered_child_for_test(pid), + proc_state(pid) + ); + std::thread::sleep(Duration::from_millis(20)); + } +} + +/// An ordinary cleanup must never reap the group leader before the group +/// decision, even when no pidfd is usable. +/// +/// The leader exits and leaves a live descendant in its process group. The +/// reaping observation used to free the leader first, after which the group +/// signal saw `ECHILD` and skipped the kill. +#[cfg(all(unix, feature = "workspace-io-fault"))] +const NO_PIDFD_DESCENDANT_CHILD: &str = "RUSTSCRIPT_AGENT_NO_PIDFD_DESCENDANT_CHILD"; + +#[cfg(all(target_os = "linux", feature = "workspace-io-fault"))] +#[test] +fn ordinary_cleanup_without_a_pidfd_keeps_the_leader_for_the_group_signal() { + if run_isolated( + "ordinary_cleanup_without_a_pidfd_keeps_the_leader_for_the_group_signal", + NO_PIDFD_DESCENDANT_CHILD, + &[], + ) { + return; + } + + let fixture = Fixture::new("no-pidfd-descendant"); + let executor = Arc::new( + McpToolExecutor::new( + McpToolExecutorConfig::new(&fixture.root) + .with_process_cleanup_timeout(Duration::from_millis(500)), + ) + .expect("executor"), + ); + // The spawn-time acquisition, the registry's acquisition and the retained + // handle's lazy retry all fail: this handle has no usable pidfd. + executor.processes_for_test().fail_pidfd_opens_for_test(8); + // Keep the retained handle reachable instead of letting the spawn-failure + // path kill and forget it. + executor + .processes_for_test() + .withhold_cleanup_proof_for_test(); + + let spawn = executor + .execute_tool( + Some("no-pidfd-descendant"), + "terminal", + &json!({ + "argv": [ + "/bin/sh", + "-c", + "sleep 300 & printf '%s' $! > desc.pid; printf '%s' $$ > root.pid; exit 0" + ], + "background": true + }), + ) + .expect("terminal tool result"); + assert!( + !spawn.ok, + "a failed pidfd acquisition must surface and retain the real child: {spawn:?}" + ); + let read_pid = |name: &str| -> u32 { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + if let Ok(text) = fs::read_to_string(fixture.root.join(name)) + && let Ok(pid) = text.trim().parse() + { + return pid; + } + assert!( + Instant::now() < deadline, + "the {name} pid file never appeared" + ); + std::thread::sleep(Duration::from_millis(10)); + } + }; + let root = read_pid("root.pid"); + let descendant = read_pid("desc.pid"); + let ids = executor.processes_for_test().handle_ids_for_test(); + assert_eq!(ids.len(), 1, "the retained child must stay owned: {ids:?}"); + + // Wait for the leader to become an unreaped zombie, then run the ordinary + // observation + cleanup path. + let zombie_deadline = Instant::now() + Duration::from_secs(10); + loop { + let stat = fs::read_to_string(format!("/proc/{root}/stat")).unwrap_or_default(); + if stat + .rfind(')') + .and_then(|close| stat[close + 1..].split_whitespace().next()) + == Some("Z") + { + break; + } + assert!( + Instant::now() < zombie_deadline, + "the group leader never exited" + ); + std::thread::sleep(Duration::from_millis(10)); + } + let reaped = executor.processes_for_test().reap_handle_for_test(&ids[0]); + assert!(reaped, "the ordinary reap must observe and reap the leader"); + + let gone_deadline = Instant::now() + Duration::from_secs(5); + loop { + if unsafe { libc::kill(descendant as libc::pid_t, 0) != 0 } { + break; + } + assert!( + Instant::now() < gone_deadline, + "the group signal must kill a descendant of a leader without a pidfd" + ); + std::thread::sleep(Duration::from_millis(10)); + } + + executor.processes_for_test().allow_cleanup_proof_for_test(); + let _proof = executor + .processes_for_test() + .shutdown_all_within(Instant::now() + Duration::from_secs(5)); + let _ = executor.shutdown(); +} + +/// A reap-lock timeout must leave the tree pending, never report it clean, and +/// never take the cleanup action the missing decision was supposed to guard. +#[cfg(all(unix, feature = "workspace-io-fault"))] +const REAP_LOCK_TIMEOUT_CHILD: &str = "RUSTSCRIPT_AGENT_REAP_LOCK_TIMEOUT_CHILD"; + +#[cfg(all(target_os = "linux", feature = "workspace-io-fault"))] +#[test] +fn cleanup_lock_timeout_never_reports_a_cleaned_tree() { + if run_isolated( + "cleanup_lock_timeout_never_reports_a_cleaned_tree", + REAP_LOCK_TIMEOUT_CHILD, + &[], + ) { + return; + } + + let fixture = Fixture::new("reap-lock-timeout"); + let executor = Arc::new( + McpToolExecutor::new( + McpToolExecutorConfig::new(&fixture.root) + .with_process_cleanup_timeout(Duration::from_millis(600)), + ) + .expect("executor"), + ); + let background = executor + .execute_tool( + Some("reap-lock-timeout-root"), + "terminal", + &json!({"argv": ["/bin/sh", "-c", "exec sleep 300"], "background": true}), + ) + .expect("background spawn"); + assert!( + background.data["process_id"].as_str().is_some(), + "the background spawn must be recorded in the process table" + ); + let pid = executor.processes_for_test().live_pids()[0]; + + // Another reaper owns the group decision for this whole teardown. + let reap_lock = hold_reap_serial_for_test(); + let processes = Arc::clone(executor.processes_for_test()); + let proof = std::thread::spawn(move || { + processes.shutdown_all_within(Instant::now() + Duration::from_millis(600)) + }) + .join() + .expect("teardown thread"); + assert!( + !proof.is_clean(), + "a reap-lock timeout must stay pending, not Cleaned: {proof:?}" + ); + assert!( + proof.retained() >= 1, + "the unproven tree must stay retained: {proof:?}" + ); + // The root must still be a running process: no kill or reap may run while + // the group decision is held by another reaper. A reaped or killed root + // shows up as a zombie here, and that is exactly what the old cleanup did. + // A SIGKILL is delivered asynchronously, so give the kernel a moment to + // settle before reading the state. An untouched root keeps sleeping. + std::thread::sleep(Duration::from_millis(300)); + let state = proc_state(pid); + assert!( + state.as_deref().is_some_and(|state| state != "Z"), + "the cleanup must not kill or reap a root whose group decision timed out: {state:?}" + ); + + // With the lock free, a later attempt takes the decision and kills it. + drop(reap_lock); + let _retry = executor + .processes_for_test() + .shutdown_all_within(Instant::now() + Duration::from_secs(2)); + let gone_deadline = Instant::now() + Duration::from_secs(5); + loop { + let state = proc_state(pid); + if state.is_none() || state.as_deref() == Some("Z") { + break; + } + assert!( + Instant::now() < gone_deadline, + "a later attempt with the lock free must still decide the tree: {state:?}" + ); + std::thread::sleep(Duration::from_millis(10)); + } + let _ = executor.shutdown(); +} + +/// Kernel state letter of one process, or `None` when it is gone. +#[cfg(all(target_os = "linux", feature = "workspace-io-fault"))] +fn proc_state(pid: u32) -> Option { + let stat = fs::read_to_string(format!("/proc/{pid}/stat")).ok()?; + stat.rfind(')') + .and_then(|close| stat[close + 1..].split_whitespace().next()) + .map(str::to_string) +} + +/// A sealed cancelled-before-prepare ledger must fail closed across +/// `commit_started`. +/// +/// The ledger seals when it is at capacity. A cancellation that arrives while +/// the call is already inside `commit_started` can no longer be stored by id, +/// so the only safe disposition is refusal: the handed-out token must not +/// publish, and the lifecycle must not rely on an owner-installed cancellation +/// source to notice it. The default source reports `Active` in this test. +#[cfg(all(unix, feature = "workspace-io-fault"))] +#[test] +fn sealed_prepare_ledger_fails_closed_across_commit_started() { + struct ParkedStart { + park: Arc, + } + + impl DurableToolLifecycle for ParkedStart { + fn assert_active_run(&self, _run_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } + + fn prepare_parent( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result<(), LifecycleError> { + Ok(()) + } + + fn replay_result( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result, LifecycleError> { + Ok(None) + } + + fn commit_started(&self, record: &DurableStarted) -> Result<(), LifecycleError> { + if record.call_id == "sealed-commit-call" { + self.park.mark_started(); + self.park.wait_released(); + } + Ok(()) + } + + fn commit_result( + &self, + _call_id: &str, + result: &serde_json::Value, + ) -> Result { + Ok(result.clone()) + } + + fn interrupt(&self, _call_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } + } + + let fixture = Fixture::new("sealed-prepare-ledger"); + let owner = CapabilityOwner::new("mcp", "sealed-ledger", "run").expect("owner"); + let park = Arc::new(SeamGate::default()); + let durable = Arc::new(ParkedStart { + park: Arc::clone(&park), + }); + let lifecycle = CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry-sealed-ledger") + .workspace(fixture.root.clone()) + .limits(LifecycleLimits { + max_tool_calls: 2, + max_output_bytes: 4096, + max_summary_bytes: 4096, + }) + .deadline_ms(u64::MAX) + .clock(Arc::new(SystemClock)) + .tokens(Arc::new(UuidIssuer)) + .durable(Arc::clone(&durable) as Arc) + .approval(Arc::new(AllowAllApproval)) + .build() + .expect("lifecycle"); + + let parked = { + let lifecycle = lifecycle.clone(); + let owner = owner.clone(); + let metadata = PrepareMetadata { + run_id: owner.run().to_string(), + call_id: "sealed-commit-call".to_string(), + tool_name: "read_file".to_string(), + argument_digest: "digest".to_string(), + registry_identity: "registry-sealed-ledger".to_string(), + risk_class: CapabilityRisk::Read, + summary: "sealed ledger commit started".to_string(), + }; + std::thread::spawn(move || lifecycle.prepare(&owner, metadata)) + }; + park.wait_started(); + + // Fill the lifetime-bounded cancelled ledger to capacity with calls that + // never prepared. The third distinct intent cannot be stored: the ledger + // must seal instead of forgetting it. + assert!(!lifecycle.request_call_cancellation("ledger-filler-a")); + assert!(!lifecycle.request_call_cancellation("ledger-filler-b")); + let (_, _, cancelled, sealed) = lifecycle.prepare_gate_state_for_test(); + assert_eq!(cancelled, 2); + assert!(!sealed); + assert!( + !lifecycle.request_call_cancellation("sealed-commit-call"), + "the parked call has no token while its durable start is being written" + ); + let (_, _, cancelled, sealed) = lifecycle.prepare_gate_state_for_test(); + assert_eq!( + cancelled, 2, + "a sealed ledger must not claim the overflowing intent was recorded" + ); + assert!( + sealed, + "the third distinct pre-prepare cancellation must seal the ledger" + ); + + park.release(); + let token = match parked.join().expect("parked prepare") { + Ok(PrepareOutcome::Execute { + execution_token, .. + }) => execution_token, + other => panic!("the durable start already acknowledged, got {other:?}"), + }; + assert!( + matches!( + lifecycle.enter_publication(&token), + Err(LifecycleError::Cancelled) + ), + "a sealed ledger must fence the publication even though the default cancellation source reports Active" + ); +} + +/// One call id owns exactly one prepare gate and one durable start. +/// +/// A second prepare while the first is inside its durable boundary must be +/// refused before it can create another gate or cross the boundary again, and +/// a late prepare after the token handoff must not resurrect a gate either. +/// Every prepare of the call shares the same admission gate, and the map is +/// empty again once the call has handed off. +#[cfg(all(unix, feature = "workspace-io-fault"))] +#[test] +fn same_call_prepares_share_one_gate_and_no_late_gate_is_created() { + struct ParkedSameCall { + park: Arc, + crossings: Mutex>, + parked: AtomicBool, + } + + impl DurableToolLifecycle for ParkedSameCall { + fn assert_active_run(&self, _run_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } + + fn prepare_parent( + &self, + _run_id: &str, + call_id: &str, + _tool_name: &str, + ) -> Result<(), LifecycleError> { + self.crossings + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .push(call_id.to_string()); + if call_id == "same-id-call" && !self.parked.swap(true, Ordering::SeqCst) { + self.park.mark_started(); + self.park.wait_released(); + } + Ok(()) + } + + fn replay_result( + &self, + _run_id: &str, + _call_id: &str, + _tool_name: &str, + ) -> Result, LifecycleError> { + Ok(None) + } + + fn commit_started(&self, _record: &DurableStarted) -> Result<(), LifecycleError> { + Ok(()) + } + + fn commit_result( + &self, + _call_id: &str, + result: &serde_json::Value, + ) -> Result { + Ok(result.clone()) + } + + fn interrupt(&self, _call_id: &str) -> Result<(), LifecycleError> { + Ok(()) + } + } + + let fixture = Fixture::new("same-call-gate"); + let owner = CapabilityOwner::new("mcp", "same-call", "run").expect("owner"); + let park = Arc::new(SeamGate::default()); + let durable = Arc::new(ParkedSameCall { + park: Arc::clone(&park), + crossings: Mutex::new(Vec::new()), + parked: AtomicBool::new(false), + }); + let lifecycle = CapabilityLifecycle::builder() + .owner(owner.clone()) + .registry_identity("registry-same-call") + .workspace(fixture.root.clone()) + .limits(LifecycleLimits { + max_tool_calls: 4, + max_output_bytes: 4096, + max_summary_bytes: 4096, + }) + .deadline_ms(u64::MAX) + .clock(Arc::new(SystemClock)) + .tokens(Arc::new(UuidIssuer)) + .durable(Arc::clone(&durable) as Arc) + .approval(Arc::new(AllowAllApproval)) + .build() + .expect("lifecycle"); + + let metadata = |call_id: &str| PrepareMetadata { + run_id: owner.run().to_string(), + call_id: call_id.to_string(), + tool_name: "read_file".to_string(), + argument_digest: "digest".to_string(), + registry_identity: "registry-same-call".to_string(), + risk_class: CapabilityRisk::Read, + summary: "same-id prepare".to_string(), + }; + + let first = { + let lifecycle = lifecycle.clone(); + let owner = owner.clone(); + let metadata = metadata("same-id-call"); + std::thread::spawn(move || lifecycle.prepare(&owner, metadata)) + }; + park.wait_started(); + let second = { + let lifecycle = lifecycle.clone(); + let owner = owner.clone(); + let metadata = metadata("same-id-call"); + std::thread::spawn(move || lifecycle.prepare(&owner, metadata)) + }; + // Let the second prepare reach the point where the old implementation + // would have waited for the shared gate and then crossed the boundary + // again. + std::thread::sleep(Duration::from_millis(50)); + park.release(); + + let outcome_first = first.join().expect("first prepare"); + let outcome_second = second.join().expect("second prepare"); + assert!( + matches!(outcome_first, Ok(PrepareOutcome::Execute { .. })), + "the admitted prepare must hand out a token: {outcome_first:?}" + ); + assert!( + matches!(outcome_second, Err(LifecycleError::UnresolvedCall)), + "a concurrent prepare of the same call must be refused: {outcome_second:?}" + ); + + // A late prepare after the handoff must observe the open token before it + // can create another gate or cross the durable boundary. + let late = lifecycle.prepare(&owner, metadata("same-id-call")); + assert!( + matches!(late, Err(LifecycleError::UnresolvedCall)), + "a late prepare of a handed-off call must be refused: {late:?}" + ); + + assert_eq!( + *durable + .crossings + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()), + vec!["same-id-call".to_string()], + "one call id must have exactly one durable prepare boundary crossing" + ); + let (created, live, _, _) = lifecycle.prepare_gate_state_for_test(); + assert_eq!( + created, 1, + "exactly one admission gate may ever be created for one call id" + ); + assert_eq!(live, 0, "no idle admission gate may remain in the map"); + assert_eq!(lifecycle.open_token_count(), 1); +} + +/// An unproven reap after a successful group decision must still keep the +/// exit-sweep record, and the bounded reclaimer must eventually drop it. +/// +/// The destructor may not report a tree clean when its own final reap +/// observation does not prove the leader gone. The registration is the only +/// remaining owner at that point, so it moves into the retained-child list +/// instead of being forgotten. A long-lived caller must then reclaim it +/// without waiting for process exit. +#[cfg(all(target_os = "linux", feature = "workspace-io-fault"))] +const DESTRUCTOR_UNPROVEN_CHILD: &str = "RUSTSCRIPT_AGENT_DESTRUCTOR_UNPROVEN_CHILD"; + +#[cfg(all(target_os = "linux", feature = "workspace-io-fault"))] +#[test] +fn destructor_with_an_unproven_reap_keeps_the_record_until_reclaimed() { + if run_isolated( + "destructor_with_an_unproven_reap_keeps_the_record_until_reclaimed", + DESTRUCTOR_UNPROVEN_CHILD, + &[], + ) { + return; + } + + let fixture = Fixture::new("destructor-unproven"); + let executor = Arc::new( + McpToolExecutor::new( + McpToolExecutorConfig::new(&fixture.root) + .with_process_cleanup_timeout(Duration::from_millis(300)), + ) + .expect("executor"), + ); + let background = executor + .execute_tool( + Some("destructor-unproven-root"), + "terminal", + &json!({ + "argv": [ + "/bin/sh", + "-c", + "printf '%s' $$ > root.pid; exec sleep 300" + ], + "background": true + }), + ) + .expect("background spawn"); + assert!( + background.data["process_id"].as_str().is_some(), + "the background spawn must be recorded in the process table" + ); + let pid: u32 = { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + if let Ok(text) = fs::read_to_string(fixture.root.join("root.pid")) + && let Ok(pid) = text.trim().parse() + { + break pid; + } + assert!( + Instant::now() < deadline, + "the root pid file never appeared" + ); + std::thread::sleep(Duration::from_millis(10)); + } + }; + + // The group decision during teardown succeeds, but the destructor's own + // final reap observation is forced to look unproven. Keep the reclaimer + // paused so the retained record is observable before it reclaims it. The + // record is taken out of the table so only the handle destructor under + // test can decide its fate. + pause_retained_reaper_for_test(true); + let handle = executor + .processes_for_test() + .take_handle_for_test(pid) + .expect("the background process record must own the handle"); + handle.force_destructor_reap_unproven_for_test(); + drop(handle); + drop(executor); + assert!( + registered_child_for_test(pid), + "an unproven reap after a successful group decision must keep the exit-sweep record" + ); + + // Resume the reclaimer: it must reap the signalled child and drop the + // record without the process having to exit. + pause_retained_reaper_for_test(false); + let reclaim_deadline = Instant::now() + Duration::from_secs(10); + while registered_child_for_test(pid) || proc_state(pid).is_some() { + assert!( + Instant::now() < reclaim_deadline, + "the retained unproven record must be reclaimed after a proven disappearance: \ + record={} state={:?}", + registered_child_for_test(pid), + proc_state(pid) + ); + std::thread::sleep(Duration::from_millis(20)); + } +} + +/// Reads a pid from a park file once it appears. +/// +/// Used only with the Linux fixture tests below; keep its cfg aligned with +/// their `/proc`-based proof. +#[cfg(all(target_os = "linux", feature = "workspace-io-fault"))] +fn wait_for_parked_pid(path: &std::path::Path, deadline: Instant, what: &str) -> u32 { + wait_for_file(path, deadline, what); + fs::read_to_string(path) + .unwrap_or_else(|error| panic!("read {what}: {error}")) + .trim() + .parse() + .unwrap_or_else(|error| panic!("parse {what} pid: {error}")) +} + +/// Waits for a failed-release decision line for `pid` while requiring that +/// the sweep-owned child still exists. +/// +/// The sweep is parked before its own reap, so a worker that signals or reaps +/// the transferred child removes the process before the decision marker can +/// be observed. No PID reuse is required for this distinction. +/// +/// Linux-gated with `proc_state`: this is a Linux `/proc` proof, not a +/// portable Unix one. +#[cfg(all(target_os = "linux", feature = "workspace-io-fault"))] +fn wait_for_swept_failure_marker( + marker: &std::path::Path, + pid: u32, + deadline: Instant, + context: &str, +) -> String { + let prefix = format!("{pid} "); + while Instant::now() < deadline { + if let Ok(text) = fs::read_to_string(marker) + && let Some(line) = text.lines().find(|line| line.starts_with(&prefix)) + { + return line.to_string(); + } + assert!( + proc_state(pid).is_some(), + "the worker reaped a child that the exit sweep already owned: \ + pid={pid} context={context}" + ); + std::thread::sleep(Duration::from_millis(10)); + } + panic!( + "the worker never recorded its failed-release decision: marker={marker:?} \ + marker_text={:?} state={:?} context={context}", + fs::read_to_string(marker).ok(), + proc_state(pid) + ); +} + +/// Waits for one retained attempt line for `pid` while requiring that the +/// sweep-owned child still exists. +#[cfg(all(target_os = "linux", feature = "workspace-io-fault"))] +fn wait_for_retained_attempt( + marker: &std::path::Path, + pid: u32, + deadline: Instant, + context: &str, +) -> String { + wait_for_swept_failure_marker(marker, pid, deadline, context) +} + +/// Owns one fixture child for failure-safe cleanup. +/// +/// The guard only signals a pid that `waitpid(WNOHANG)` still reports as our +/// unreaped child, so an already-reaped (or recycled) number is never +/// signalled. Normal passing paths disarm it after the sweep proved +/// disappearance. +#[cfg(all(target_os = "linux", feature = "workspace-io-fault"))] +struct OwnedFixtureChild { + pid: Option, +} + +#[cfg(all(target_os = "linux", feature = "workspace-io-fault"))] +impl OwnedFixtureChild { + fn new(pid: u32) -> Self { + Self { pid: Some(pid) } + } + + fn disarm(&mut self) { + self.pid = None; + } +} + +#[cfg(all(target_os = "linux", feature = "workspace-io-fault"))] +impl Drop for OwnedFixtureChild { + fn drop(&mut self) { + let Some(pid) = self.pid else { + return; + }; + let raw = pid as libc::pid_t; + let mut status: libc::c_int = 0; + // 0 means the exact recorded child is still unreaped, so its pid and + // process-group id cannot have been reused. + let observed = unsafe { libc::waitpid(raw, &mut status, libc::WNOHANG) }; + if observed != 0 { + return; + } + unsafe { + let _ = libc::kill(-raw, libc::SIGKILL); + let _ = libc::kill(raw, libc::SIGKILL); + } + let deadline = Instant::now() + Duration::from_secs(1); + loop { + let mut status: libc::c_int = 0; + let reaped = unsafe { libc::waitpid(raw, &mut status, libc::WNOHANG) }; + if reaped != 0 || Instant::now() >= deadline { + return; + } + std::thread::sleep(Duration::from_millis(5)); + } + } +} + +/// The retained reclaimer must revalidate its exact reservation. +/// +/// The destructor's unproven branch retains a Published record and child. The +/// reclaimer selects that entry and parks before its atomic attempt; the exit +/// sweep then claims the record and parks before its own reap. The reclaimer +/// must observe the tombstone, perform no numeric signal or reap, and leave +/// the still-unreaped child entirely to the sweep. +#[cfg(all(target_os = "linux", feature = "workspace-io-fault"))] +const RETAINED_INVERSE_RACE_CHILD: &str = "RUSTSCRIPT_AGENT_RETAINED_INVERSE_RACE_CHILD"; + +#[cfg(all(target_os = "linux", feature = "workspace-io-fault"))] +#[test] +fn retained_reaper_that_observed_eligibility_never_touches_a_swept_child() { + let base = std::env::temp_dir().join(format!( + "mcp-retained-inverse-{}-{}", + std::process::id(), + NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&base).expect("retained inverse base"); + if run_isolated( + "retained_reaper_that_observed_eligibility_never_touches_a_swept_child", + RETAINED_INVERSE_RACE_CHILD, + &[ + ( + "RUSTSCRIPT_AGENT_TEST_RETAINED_DECISION_PARK_FILE", + base.join("decision.park"), + ), + ( + "RUSTSCRIPT_AGENT_TEST_RETAINED_DECISION_RELEASE_FILE", + base.join("decision.release"), + ), + ( + "RUSTSCRIPT_AGENT_TEST_RETAINED_ATTEMPT_MARKER", + base.join("attempt.marker"), + ), + ( + "RUSTSCRIPT_AGENT_TEST_SWEEP_REAP_PARK_FILE", + base.join("sweep.park"), + ), + ( + "RUSTSCRIPT_AGENT_TEST_SWEEP_REAP_RELEASE_FILE", + base.join("sweep.release"), + ), + ], + ) { + let _ = fs::remove_dir_all(&base); + return; + } + + let decision_park = std::env::var_os("RUSTSCRIPT_AGENT_TEST_RETAINED_DECISION_PARK_FILE") + .map(PathBuf::from) + .expect("decision park path"); + let decision_release = std::env::var_os("RUSTSCRIPT_AGENT_TEST_RETAINED_DECISION_RELEASE_FILE") + .map(PathBuf::from) + .expect("decision release path"); + let attempt_marker = std::env::var_os("RUSTSCRIPT_AGENT_TEST_RETAINED_ATTEMPT_MARKER") + .map(PathBuf::from) + .expect("attempt marker path"); + let sweep_park = std::env::var_os("RUSTSCRIPT_AGENT_TEST_SWEEP_REAP_PARK_FILE") + .map(PathBuf::from) + .expect("sweep park path"); + let sweep_release = std::env::var_os("RUSTSCRIPT_AGENT_TEST_SWEEP_REAP_RELEASE_FILE") + .map(PathBuf::from) + .expect("sweep release path"); + + let fixture = Fixture::new("retained-inverse"); + let executor = Arc::new( + McpToolExecutor::new( + McpToolExecutorConfig::new(&fixture.root) + .with_process_cleanup_timeout(Duration::from_millis(300)), + ) + .expect("executor"), + ); + let background = executor + .execute_tool( + Some("retained-inverse-root"), + "terminal", + &json!({ + "argv": [ + "/bin/sh", + "-c", + "printf '%s' $$ > root.pid; exec sleep 300" + ], + "background": true + }), + ) + .expect("background spawn"); + assert!( + background.data["process_id"].as_str().is_some(), + "the background spawn must be recorded in the process table" + ); + let pid = wait_for_parked_pid( + &fixture.root.join("root.pid"), + Instant::now() + Duration::from_secs(10), + "root pid", + ); + let mut guard = OwnedFixtureChild::new(pid); + + // Keep the reclaimer off the entry while the destructor's unproven branch + // turns it into the only remaining owner of a Published record. + pause_retained_reaper_for_test(true); + let handle = executor + .processes_for_test() + .take_handle_for_test(pid) + .expect("the background process record must own the handle"); + handle.force_destructor_reap_unproven_for_test(); + drop(handle); + assert!( + registered_child_for_test(pid), + "an unproven reap must keep the exit-sweep record: pid={pid}" + ); + assert_eq!( + proc_state(pid).as_deref(), + Some("Z"), + "the destructor's group decision must leave the retained leader unreaped: pid={pid}" + ); + + // Let the reclaimer select the entry and park before its atomic attempt. + pause_retained_reaper_for_test(false); + wait_for_file( + &decision_park, + Instant::now() + Duration::from_secs(10), + "retained decision park", + ); + + // The sweep claims the same record and parks before its own reap. + let sweep = + std::thread::spawn(|| sweep_spawned_children(Instant::now() + Duration::from_secs(5))); + wait_for_file( + &sweep_park, + Instant::now() + Duration::from_secs(10), + "sweep reap park", + ); + assert!( + !registered_child_for_test(pid), + "the sweep must have claimed the retained record: pid={pid}" + ); + assert_eq!( + proc_state(pid).as_deref(), + Some("Z"), + "the sweep must own an unreaped child before the retained reclaimer resumes: pid={pid}" + ); + + fs::write(&decision_release, b"release").expect("release the parked retained reclaimer"); + let line = wait_for_retained_attempt( + &attempt_marker, + pid, + Instant::now() + Duration::from_secs(10), + "retained eligibility-before-claim", + ); + assert_eq!( + line, + format!("{pid} swept"), + "a retained reclaimer that lost the record must observe the tombstone, not reap" + ); + assert_eq!( + proc_state(pid).as_deref(), + Some("Z"), + "the retained reclaimer must not signal or reap a child the sweep owns: pid={pid}" + ); + + fs::write(&sweep_release, b"release").expect("release the parked sweep"); + let unproven = sweep.join().expect("sweep thread"); + assert_eq!( + unproven, 0, + "the sweep alone must prove the still-owned retained child gone" + ); + let gone_deadline = Instant::now() + Duration::from_secs(5); + while proc_state(pid).is_some() { + assert!( + Instant::now() < gone_deadline, + "the sweep must reap the exact retained child it owned: pid={pid}" + ); + std::thread::sleep(Duration::from_millis(20)); + } + guard.disarm(); + let _ = executor.shutdown(); +} diff --git a/tests/mcp_tool_stdio_tests.rs b/tests/mcp_tool_stdio_tests.rs new file mode 100644 index 00000000..19510965 --- /dev/null +++ b/tests/mcp_tool_stdio_tests.rs @@ -0,0 +1,2563 @@ +//! Packaged `tools serve --stdio` process contract. +//! +//! These tests drive the real binary over its real standard streams: stdout +//! must carry protocol bytes only, diagnostics must stay on stderr, and an +//! orderly stdin close must terminate owned children within a bounded grace. + +use std::fs; +use std::path::PathBuf; +use std::process::{ExitStatus, Stdio}; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::Duration; + +#[cfg(unix)] +use std::os::fd::OwnedFd; +#[cfg(unix)] +use std::os::unix::net::UnixStream; + +use serde_json::{Value, json}; +use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; +use tokio::process::{Child, ChildStdin, ChildStdout, Command}; +use tokio::sync::Mutex; +use tokio::task::JoinHandle; + +static NEXT_FIXTURE: AtomicU64 = AtomicU64::new(0); + +struct Fixture { + parent: PathBuf, + root: PathBuf, +} + +impl Fixture { + fn new(label: &str) -> Self { + let sequence = NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed); + let base = std::env::var_os("RUSTSCRIPT_AGENT_TEST_TMP") + .map(PathBuf::from) + .unwrap_or_else(std::env::temp_dir); + let parent = base.join(format!( + "mcp-stdio-{label}-{}-{sequence}", + std::process::id() + )); + let root = parent.join("workspace"); + fs::create_dir_all(&root).expect("create stdio fixture"); + Self { parent, root } + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.parent); + } +} + +fn binary() -> &'static str { + env!("CARGO_BIN_EXE_rustscript-agent") +} + +struct ChildServer { + child: Child, + stdin: Option, + stdout: BufReader, + stderr: Arc>>, + stderr_task: Option>, + next_id: i64, +} + +impl ChildServer { + async fn spawn(args: &[&str]) -> Self { + Self::spawn_with_env(args, &[]).await + } + + async fn spawn_with_env(args: &[&str], envs: &[(&str, &str)]) -> Self { + let mut command = Command::new(binary()); + command.args(args); + for (key, value) in envs { + command.env(key, value); + } + let mut child = command + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .kill_on_drop(true) + .spawn() + .unwrap_or_else(|error| panic!("spawn {}: {error}", binary())); + let stdin = child.stdin.take().expect("child stdin"); + let stdout = BufReader::new(child.stdout.take().expect("child stdout")); + let mut stderr_pipe = child.stderr.take().expect("child stderr"); + let stderr = Arc::new(Mutex::new(Vec::new())); + let sink = Arc::clone(&stderr); + let stderr_task = tokio::spawn(async move { + let mut buffer = Vec::new(); + let _ = stderr_pipe.read_to_end(&mut buffer).await; + *sink.lock().await = buffer; + }); + Self { + child, + stdin: Some(stdin), + stdout, + stderr, + stderr_task: Some(stderr_task), + next_id: 1, + } + } + + async fn send(&mut self, message: Value) { + let mut line = serde_json::to_vec(&message).expect("serialize"); + line.push(b'\n'); + let stdin = self.stdin.as_mut().expect("stdin still open"); + stdin.write_all(&line).await.expect("write child stdin"); + stdin.flush().await.expect("flush child stdin"); + } + + async fn read(&mut self) -> Option { + let mut line = String::new(); + // The debug-build executor compiles the bundled RSS dispatch program + // during construction, so the first protocol response can take tens of + // seconds on a loaded host. The bound is generous but finite. + let read = tokio::time::timeout(Duration::from_secs(90), self.stdout.read_line(&mut line)) + .await + .expect("timed out waiting for the tool server") + .expect("read child stdout"); + if read == 0 { + return None; + } + let message: Value = + serde_json::from_str(line.trim_end()).expect("stdout line was not JSON"); + assert_eq!( + message["jsonrpc"], + json!("2.0"), + "stdout carried a non-protocol line: {line:?}" + ); + Some(message) + } + + async fn request(&mut self, method: &str, params: Option) -> Value { + let id = self.next_id; + self.next_id += 1; + let mut message = json!({"jsonrpc": "2.0", "id": id, "method": method}); + if let Some(params) = params { + message["params"] = params; + } + self.send(message).await; + loop { + let response = self.read().await.expect("server responded"); + if response.get("id") == Some(&json!(id)) { + return response; + } + } + } + + async fn initialize(&mut self) -> Value { + let response = self + .request( + "initialize", + Some(json!({ + "protocolVersion": "2025-06-18", + "capabilities": {}, + "clientInfo": {"name": "mcp-stdio-tests", "version": "1"}, + })), + ) + .await; + self.send(json!({"jsonrpc": "2.0", "method": "notifications/initialized"})) + .await; + response + } + + fn close_stdin(&mut self) { + self.stdin.take(); + } + + async fn finish(mut self, timeout: Duration) -> Finished { + let status: ExitStatus = tokio::time::timeout(timeout, self.child.wait()) + .await + .expect("tool server exited within the bounded grace") + .expect("wait for tool server"); + let mut remainder = String::new(); + self.stdout + .read_to_string(&mut remainder) + .await + .expect("drain child stdout"); + for line in remainder.lines() { + let value: Value = serde_json::from_str(line) + .unwrap_or_else(|_| panic!("stdout carried a non-protocol line: {line:?}")); + assert_eq!(value["jsonrpc"], json!("2.0"), "line={line:?}"); + } + let stderr_task = self.stderr_task.take().expect("stderr task"); + let _ = tokio::time::timeout(Duration::from_secs(5), stderr_task).await; + let stderr = String::from_utf8_lossy(&self.stderr.lock().await).into_owned(); + Finished { + status, + stderr, + stdout_remainder: remainder, + } + } +} + +impl Drop for ChildServer { + fn drop(&mut self) { + let _ = self.child.start_kill(); + } +} + +struct Finished { + status: ExitStatus, + stderr: String, + stdout_remainder: String, +} + +#[tokio::test] +async fn packaged_stdio_server_serves_the_catalog_and_exits_cleanly_on_eof() { + let fixture = Fixture::new("serve"); + fs::write(fixture.root.join("hello.txt"), "hello\n").expect("hello file"); + let workspace = fixture.root.to_string_lossy().into_owned(); + let mut child = + ChildServer::spawn(&["tools", "serve", "--stdio", "--workspace", &workspace]).await; + + let init = child.initialize().await; + assert_eq!( + init["result"]["capabilities"], + json!({"tools": {}}), + "initialize={init}" + ); + + let list = child.request("tools/list", Some(json!({}))).await; + let names: Vec<&str> = list["result"]["tools"] + .as_array() + .expect("tools") + .iter() + .map(|tool| tool["name"].as_str().expect("name")) + .collect(); + assert_eq!( + names, + vec![ + "read_file", + "search_files", + "write_file", + "patch", + "terminal", + "process" + ] + ); + + let call = child + .request( + "tools/call", + Some(json!({"name": "read_file", "arguments": {"path": "hello.txt"}})), + ) + .await; + assert_eq!(call["result"]["isError"], json!(false)); + assert_eq!(call["result"]["content"][0]["text"], json!("hello\n")); + + child.close_stdin(); + let finished = child.finish(Duration::from_secs(30)).await; + assert!( + finished.status.success(), + "status={:?} stderr={}", + finished.status, + finished.stderr + ); + assert!( + finished.stdout_remainder.is_empty(), + "EOF must not add stdout bytes: {:?}", + finished.stdout_remainder + ); + assert!( + finished.stderr.contains("cleanup=clean"), + "stderr={}", + finished.stderr + ); + assert!( + finished.stderr.contains("quit=closed"), + "stderr={}", + finished.stderr + ); + assert!( + finished.stderr.lines().all(|line| line.len() <= 512), + "diagnostics are bounded: {}", + finished.stderr + ); +} + +#[tokio::test] +async fn packaged_stdio_server_rejects_invalid_startup_without_writing_stdout() { + let fixture = Fixture::new("invalid-startup"); + let relative = "relative/workspace"; + let relative = ChildServer::spawn(&["tools", "serve", "--stdio", "--workspace", relative]) + .await + .finish(Duration::from_secs(10)) + .await; + assert!(!relative.status.success()); + assert_eq!(relative.status.code(), Some(2)); + assert!(relative.stdout_remainder.is_empty()); + assert!( + relative.stderr.contains("cli_workspace_invalid"), + "stderr={}", + relative.stderr + ); + + let missing = fixture.parent.join("not-there"); + let missing = missing.to_string_lossy().into_owned(); + let missing = ChildServer::spawn(&["tools", "serve", "--stdio", "--workspace", &missing]) + .await + .finish(Duration::from_secs(10)) + .await; + assert_eq!(missing.status.code(), Some(1)); + assert!(missing.stdout_remainder.is_empty()); + assert!( + missing.stderr.contains("tools_workspace_unresolvable"), + "stderr={}", + missing.stderr + ); + + let unknown = ChildServer::spawn(&[ + "tools", + "serve", + "--stdio", + "--workspace", + "/tmp", + "--socket", + ]) + .await + .finish(Duration::from_secs(10)) + .await; + assert_eq!(unknown.status.code(), Some(2)); + assert!(unknown.stdout_remainder.is_empty()); + assert!( + unknown.stderr.contains("cli_arguments_invalid"), + "stderr={}", + unknown.stderr + ); +} + +#[tokio::test] +async fn packaged_stdio_server_cancels_a_running_call_and_cleans_up() { + let fixture = Fixture::new("cancel"); + let workspace = fixture.root.to_string_lossy().into_owned(); + let mut child = + ChildServer::spawn(&["tools", "serve", "--stdio", "--workspace", &workspace]).await; + child.initialize().await; + + let id = child.next_id; + child.next_id += 1; + child + .send(json!({ + "jsonrpc": "2.0", + "id": id, + "method": "tools/call", + "params": { + "name": "terminal", + "arguments": { + "argv": [ + "/bin/sh", + "-c", + "printf started > started.txt; sleep 30; printf done > done.txt" + ] + } + } + })) + .await; + + let started = fixture.root.join("started.txt"); + tokio::time::timeout(Duration::from_secs(10), async { + while !started.exists() { + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await + .expect("the tool call reached its child process"); + + child + .send(json!({ + "jsonrpc": "2.0", + "method": "notifications/cancelled", + "params": {"requestId": id, "reason": "stdio test cancellation"} + })) + .await; + tokio::time::sleep(Duration::from_millis(500)).await; + + let ping = child.request("ping", None).await; + assert_eq!(ping["result"], json!({})); + assert!( + !fixture.root.join("done.txt").exists(), + "cancellation must stop the running child before it completes" + ); + + child.close_stdin(); + let finished = child.finish(Duration::from_secs(15)).await; + assert!( + finished.status.success(), + "status={:?} stderr={}", + finished.status, + finished.stderr + ); + assert!( + finished.stderr.contains("cleanup=clean"), + "stderr={}", + finished.stderr + ); + assert!(!fixture.root.join("done.txt").exists()); +} + +/// Half-close stdin while stdout is never drained: pending response writes +/// hold rmcp's writer lock, so shutdown must abandon the transport and exit +/// within the cleanup deadline instead of waiting for that lock forever. +#[tokio::test] +async fn stdin_eof_with_a_stalled_stdout_reader_exits_within_the_cleanup_deadline() { + let fixture = Fixture::new("stalled-stdout"); + let workspace = fixture.root.to_string_lossy().into_owned(); + let mut child = Command::new(binary()) + .args([ + "tools", + "serve", + "--stdio", + "--workspace", + &workspace, + "--process-cleanup-timeout-ms", + "500", + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .kill_on_drop(true) + .spawn() + .unwrap_or_else(|error| panic!("spawn {}: {error}", binary())); + let mut stdin = child.stdin.take().expect("child stdin"); + let mut stdout = BufReader::new(child.stdout.take().expect("child stdout")); + let mut stderr_pipe = child.stderr.take().expect("child stderr"); + let stderr_task = tokio::spawn(async move { + let mut bytes = Vec::new(); + let _ = stderr_pipe.read_to_end(&mut bytes).await; + bytes + }); + + let mut initialize = serde_json::to_vec(&json!({ + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2025-06-18", + "capabilities": {}, + "clientInfo": {"name": "stalled-stdout-test", "version": "1"} + } + })) + .expect("serialize initialize"); + initialize.push(b'\n'); + stdin + .write_all(&initialize) + .await + .expect("write initialize"); + stdin.flush().await.expect("flush initialize"); + let mut response = String::new(); + tokio::time::timeout(Duration::from_secs(90), stdout.read_line(&mut response)) + .await + .expect("tool server initialized") + .expect("read initialize response"); + assert!(response.contains("\"result\""), "initialize={response}"); + + // Queue enough catalog responses to fill the stdout pipe, then stop + // reading. The peer deliberately never drains them. + for id in 2..134 { + let mut request = serde_json::to_vec(&json!({ + "jsonrpc": "2.0", + "id": id, + "method": "tools/list", + "params": {} + })) + .expect("serialize tools/list"); + request.push(b'\n'); + stdin.write_all(&request).await.expect("write tools/list"); + } + stdin.flush().await.expect("flush tools/list"); + drop(stdin); + + let status = tokio::time::timeout(Duration::from_secs(20), child.wait()) + .await + .expect("stalled stdout peer must not hold the server past its cleanup deadline") + .expect("wait for tool server"); + assert!(status.success(), "status={status:?}"); + let stderr = String::from_utf8_lossy(&stderr_task.await.expect("stderr task")).into_owned(); + // The peer queues more requests than the bounded reader can hold, so the + // input side terminates either by the observed EOF or by the terminal + // overflow latch. Both are the non-lifetime exit path under test. + assert!( + stderr.contains("quit=closed") || stderr.contains("quit=input_terminated"), + "stderr={stderr}" + ); + assert!( + !stderr.contains("quit=lifetime_elapsed"), + "the stalled writer path must not wait for the server lifetime: {stderr}" + ); + // Keep the unread stdout end alive until the wait above completed. + drop(stdout); +} + +/// A non-FIFO stdin forces rmcp's blocking stdio fallback, whose pending read +/// cannot be cancelled. Lifetime expiry must still exit the process within a +/// bound instead of leaving the CLI runtime waiting on that read. +#[cfg(unix)] +#[tokio::test] +async fn blocking_stdio_fallback_exits_after_lifetime_expiry() { + let fixture = Fixture::new("blocking-stdin"); + let workspace = fixture.root.to_string_lossy().into_owned(); + let (parent, child_stdin) = UnixStream::pair().expect("unix socketpair"); + let mut child = Command::new(binary()) + .args([ + "tools", + "serve", + "--stdio", + "--workspace", + &workspace, + "--server-lifetime-ms", + "500", + "--process-cleanup-timeout-ms", + "500", + ]) + .stdin(Stdio::from(OwnedFd::from(child_stdin))) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .env("RUSTSCRIPT_AGENT_TEST_READY_MARKER", "1") + .kill_on_drop(true) + .spawn() + .unwrap_or_else(|error| panic!("spawn {}: {error}", binary())); + // Readiness is measured before the tight teardown deadline: construction + // compiles the bundled dispatch program and is not part of the lifetime + // bound under test. + let mut stderr_reader = BufReader::new(child.stderr.take().expect("child stderr")); + let mut stderr = String::new(); + tokio::time::timeout(Duration::from_secs(90), async { + loop { + let mut line = String::new(); + let read = stderr_reader + .read_line(&mut line) + .await + .expect("read child stderr"); + if read == 0 { + panic!("stderr closed before the readiness marker: {stderr}"); + } + stderr.push_str(&line); + if line.contains("tools serve ready") { + return; + } + } + }) + .await + .expect("the tool server became ready"); + // Keep the peer end open with no data so the blocking read stays pending. + let _parent = parent; + + let status = tokio::time::timeout(Duration::from_secs(15), child.wait()) + .await + .expect("the blocking-stdin fallback must not outlive the lifetime bound") + .expect("wait for tool server"); + assert!(status.success(), "status={status:?}"); + let mut remainder = Vec::new(); + stderr_reader + .read_to_end(&mut remainder) + .await + .expect("drain child stderr"); + stderr.push_str(&String::from_utf8_lossy(&remainder)); + assert!(stderr.contains("quit=lifetime_elapsed"), "stderr={stderr}"); +} + +/// A rejected initialization message can carry free-form peer text. Neither +/// the server nor the CLI may echo it to stderr; only the stable code is +/// emitted. +#[tokio::test] +async fn rejected_initialization_does_not_echo_peer_data() { + let fixture = Fixture::new("init-redaction"); + let workspace = fixture.root.to_string_lossy().into_owned(); + let mut child = + ChildServer::spawn(&["tools", "serve", "--stdio", "--workspace", &workspace]).await; + let marker = "peer-marker-f3c1a7d9e4b2"; + child + .send(json!({ + "jsonrpc": "2.0", + "method": "notifications/cancelled", + "params": { + "requestId": 1, + "reason": marker, + "metadata": {"detail": marker} + } + })) + .await; + child.close_stdin(); + + // Executor construction compiles the bundled dispatch program before the + // server reads stdin (~14 s in a debug build alone, longer under the full + // target's parallel load), so the exit bound must cover construction plus + // the rejected handshake teardown. + let finished = child.finish(Duration::from_secs(90)).await; + assert_eq!( + finished.status.code(), + Some(1), + "status={:?}", + finished.status + ); + assert!( + !finished.stderr.contains(marker), + "peer-derived initialization detail leaked to stderr: {}", + finished.stderr + ); + assert!( + finished.stderr.contains("tools_initialize_failed"), + "stderr={}", + finished.stderr + ); + assert_eq!( + finished.stderr.matches("tools_initialize_failed").count(), + 1, + "the binary must not print the fixed code a second time: {}", + finished.stderr + ); + assert!( + finished.stdout_remainder.is_empty(), + "stdout={:?}", + finished.stdout_remainder + ); +} + +/// EOF must be observed even when rmcp never polls the reader again. This +/// peer closes stdin while the initialize response is stalled behind a full +/// stdout pipe; only the independent reader pump can see the close. +#[cfg(unix)] +#[tokio::test] +async fn initialization_write_stall_still_observes_eof_and_exits() { + use std::io::Write as _; + + let fixture = Fixture::new("init-stalled-writer"); + let workspace = fixture.root.to_string_lossy().into_owned(); + let (parent_end, mut child_end) = UnixStream::pair().expect("socketpair"); + // Fill the direction the child writes (child end -> parent end) in + // non-blocking mode, then hand the fd back blocking. + child_end + .set_nonblocking(true) + .expect("nonblocking child end"); + let filler = vec![b'x'; 8192]; + loop { + match child_end.write(&filler) { + Ok(0) => break, + Ok(_) => {} + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => break, + Err(error) => panic!("fill stdout socket: {error}"), + } + } + // Give the fd back to the child in blocking mode: the filled buffer is + // what must stall its writes, not O_NONBLOCK. + child_end + .set_nonblocking(false) + .expect("blocking child end"); + let mut child = Command::new(binary()) + .args([ + "tools", + "serve", + "--stdio", + "--workspace", + &workspace, + "--process-cleanup-timeout-ms", + "300", + ]) + .env("RUSTSCRIPT_AGENT_TEST_READY_MARKER", "1") + .stdin(Stdio::piped()) + .stdout(Stdio::from(OwnedFd::from(child_end))) + .stderr(Stdio::piped()) + .kill_on_drop(true) + .spawn() + .unwrap_or_else(|error| panic!("spawn {}: {error}", binary())); + let mut stdin = child.stdin.take().expect("child stdin"); + let mut initialize = serde_json::to_vec(&json!({ + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2025-06-18", + "capabilities": {}, + "clientInfo": {"name": "init-stall-test", "version": "1"} + } + })) + .expect("serialize initialize"); + initialize.push(b'\n'); + stdin + .write_all(&initialize) + .await + .expect("write initialize"); + stdin.flush().await.expect("flush initialize"); + + // Readiness is measured separately from the teardown deadline: executor + // construction compiles the bundled dispatch program and can take tens of + // seconds. Only after the server announces it is serving do we close + // stdin and apply the tight stall bound. + let mut stderr_reader = BufReader::new(child.stderr.take().expect("child stderr")); + let mut stderr = String::new(); + tokio::time::timeout(Duration::from_secs(90), async { + loop { + let mut line = String::new(); + let read = stderr_reader + .read_line(&mut line) + .await + .expect("read child stderr"); + if read == 0 { + panic!("stderr closed before the readiness marker: {stderr}"); + } + stderr.push_str(&line); + if line.contains("tools serve ready") { + return; + } + } + }) + .await + .expect("the tool server became ready"); + + // Close stdin while the handshake response write is stalled. + drop(stdin); + let status = tokio::time::timeout(Duration::from_secs(15), child.wait()) + .await + .expect("an initialization write stall must not wait for the server lifetime") + .expect("wait for tool server"); + assert!(status.success(), "status={status:?}"); + let mut remainder = Vec::new(); + stderr_reader + .read_to_end(&mut remainder) + .await + .expect("drain child stderr"); + stderr.push_str(&String::from_utf8_lossy(&remainder)); + assert!(stderr.contains("quit=closed"), "stderr={stderr}"); + assert!(stderr.contains("cleanup=clean"), "stderr={stderr}"); + // Keep the unread end open until the wait above completed. + drop(parent_end); +} + +/// A peer that floods invalid requests and then stops reading stdout makes +/// rmcp flush an invalid-request response inside `receive`. EOF arrives while +/// that receive is blocked; the independent pump must still end the server +/// within the cleanup budget instead of the server lifetime. +#[tokio::test] +async fn invalid_request_flush_with_a_stalled_reader_still_exits_on_eof() { + let fixture = Fixture::new("invalid-flush-stall"); + let workspace = fixture.root.to_string_lossy().into_owned(); + let mut child = ChildServer::spawn(&[ + "tools", + "serve", + "--stdio", + "--workspace", + &workspace, + "--process-cleanup-timeout-ms", + "300", + ]) + .await; + child.initialize().await; + + let mut stdin = child.stdin.take().expect("child stdin"); + let writer = tokio::spawn(async move { + for id in 1_000..6_000u64 { + let mut line = serde_json::to_vec(&json!({ + "jsonrpc": "2.0", + "id": id, + "method": 3 + })) + .expect("serialize invalid request"); + line.push(b'\n'); + if stdin.write_all(&line).await.is_err() { + break; + } + } + let _ = stdin.flush().await; + // Dropping closes stdin: the pump observes EOF even though rmcp is + // blocked on the stalled stdout writer. + }); + + // Never read stdout: the response pipe fills and the invalid-request + // flush (or the writer lock) blocks inside receive. + let status = tokio::time::timeout(Duration::from_secs(20), child.child.wait()) + .await + .expect("an invalid-request flush stall must not wait for the server lifetime") + .expect("wait for tool server"); + assert!(status.success(), "status={status:?}"); + writer.abort(); + let stderr_task = child.stderr_task.take().expect("stderr task"); + let _ = tokio::time::timeout(Duration::from_secs(5), stderr_task).await; + let stderr = String::from_utf8_lossy(&child.stderr.lock().await).into_owned(); + assert!( + stderr.contains("quit=closed") || stderr.contains("quit=input_terminated"), + "stderr={stderr}" + ); +} + +/// A stalled stderr sink must not hold the process past its cleanup bound. +/// The diagnostic queue is drained by its own thread; a blocked write can only +/// fill that bounded queue. +#[cfg(unix)] +#[tokio::test] +async fn stalled_stderr_sink_does_not_extend_the_exit_bound() { + use std::io::Write as _; + + let fixture = Fixture::new("stalled-stderr"); + let workspace = fixture.root.to_string_lossy().into_owned(); + let (read_end, mut write_end) = UnixStream::pair().expect("socketpair"); + // Pre-fill the direction the child writes before it starts, in + // non-blocking mode; O_NONBLOCK is shared by the duplicated child fd, so + // it must be cleared again before the spawn. + write_end + .set_nonblocking(true) + .expect("nonblocking stderr end"); + let filler = vec![b'x'; 8192]; + loop { + match write_end.write(&filler) { + Ok(0) => break, + Ok(_) => {} + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => break, + Err(error) => panic!("fill stderr socket: {error}"), + } + } + write_end + .set_nonblocking(false) + .expect("blocking stderr end"); + let mut child = Command::new(binary()) + .args([ + "tools", + "serve", + "--stdio", + "--workspace", + &workspace, + "--process-cleanup-timeout-ms", + "300", + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::from(OwnedFd::from(write_end))) + .kill_on_drop(true) + .spawn() + .unwrap_or_else(|error| panic!("spawn {}: {error}", binary())); + + // The bound covers executor construction plus the stalled teardown; the + // differential is that a synchronous stderr write never finishes at all. + drop(child.stdin.take()); + let status = tokio::time::timeout(Duration::from_secs(60), child.wait()) + .await + .expect("a stalled stderr sink must not defeat the cleanup bound") + .expect("wait for tool server"); + assert!(status.success(), "status={status:?}"); + // Keep the unread stderr end open until the wait above completed. + drop(read_end); +} + +/// Enabling the tracing event path must never copy peer payloads into stderr +/// or an embedding subscriber's log. rmcp logs full requests and notifications +/// at debug/info, so its target is filtered before any subscriber sees it. +#[tokio::test] +async fn peer_payloads_never_reach_enabled_logs() { + let fixture = Fixture::new("log-redaction"); + let workspace = fixture.root.to_string_lossy().into_owned(); + let marker = "log-marker-b7e41c2d9a"; + let mut child = ChildServer::spawn_with_env( + &["tools", "serve", "--stdio", "--workspace", &workspace], + &[("RUSTSCRIPT_AGENT_TOOLS_TRACE", "1")], + ) + .await; + child.initialize().await; + // A valid notification: rmcp logs the whole notification at info. + child + .send(json!({ + "jsonrpc": "2.0", + "method": "notifications/roots/list_changed", + "params": {"marker": marker, "detail": marker} + })) + .await; + // Well-formed JSON that is not a valid request: rmcp logs the raw line at + // debug and answers with Invalid Request. + child + .send(json!({ + "jsonrpc": "2.0", + "id": 77, + "method": 3, + "marker": marker + })) + .await; + let invalid = child.read().await.expect("invalid request response"); + assert_eq!(invalid["error"]["code"], json!(-32600)); + child.close_stdin(); + let finished = child.finish(Duration::from_secs(30)).await; + assert!(finished.status.success(), "status={:?}", finished.status); + assert!( + !finished.stderr.contains(marker), + "peer payload leaked into enabled logs: {}", + finished.stderr + ); + assert!( + finished + .stderr + .contains("rustscript-agent tool server starting"), + "the trace event path must have been enabled: {}", + finished.stderr + ); +} + +/// With TRACE enabled and stderr completely full, startup must still reach +/// the watchdog and the reader pump, and an EOF must stop the server within +/// the bounded teardown window. A synchronous log write would block the only +/// serving thread before the watchdog exists. +#[cfg(unix)] +#[tokio::test] +async fn trace_startup_with_a_full_stderr_sink_still_reaches_bounded_cleanup() { + use std::io::Write as _; + + let fixture = Fixture::new("trace-stalled-stderr"); + let workspace = fixture.root.to_string_lossy().into_owned(); + let (read_end, mut write_end) = UnixStream::pair().expect("socketpair"); + write_end + .set_nonblocking(true) + .expect("nonblocking stderr end"); + let filler = vec![b'x'; 8192]; + loop { + match write_end.write(&filler) { + Ok(0) => break, + Ok(_) => {} + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => break, + Err(error) => panic!("fill stderr socket: {error}"), + } + } + write_end + .set_nonblocking(false) + .expect("blocking stderr end"); + let ready = fixture.parent.join("ready"); + let mut child = Command::new(binary()) + .args([ + "tools", + "serve", + "--stdio", + "--workspace", + &workspace, + "--server-lifetime-ms", + "60000", + "--process-cleanup-timeout-ms", + "300", + ]) + .env("RUSTSCRIPT_AGENT_TOOLS_TRACE", "1") + .env("RUSTSCRIPT_AGENT_TEST_READY_FILE", &ready) + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .stderr(Stdio::from(OwnedFd::from(write_end))) + .kill_on_drop(true) + .spawn() + .unwrap_or_else(|error| panic!("spawn {}: {error}", binary())); + let stdin = child.stdin.take().expect("child stdin"); + + // Readiness is separate from teardown: construction compiles the bundled + // dispatch program, which is not part of the bound under test. + let ready_deadline = tokio::time::Instant::now() + Duration::from_secs(90); + while !ready.exists() { + assert!( + tokio::time::Instant::now() < ready_deadline, + "the server never reached serving with TRACE logging enabled" + ); + tokio::time::sleep(Duration::from_millis(20)).await; + } + + // From readiness the bound is tight. Every log record is blocked behind + // the full stderr sink; only the bounded diagnostic queue may absorb it. + let triggered = std::time::Instant::now(); + drop(stdin); + let status = tokio::time::timeout(Duration::from_secs(10), child.wait()) + .await + .expect("TRACE logging must not extend the bounded teardown") + .expect("wait for tool server"); + assert!( + triggered.elapsed() <= Duration::from_secs(10), + "teardown took {:?}", + triggered.elapsed() + ); + assert!(status.success(), "status={status:?}"); + // Keep the unread stderr end open until the wait above completed. + drop(read_end); +} + +/// A worker parked after the OS spawn but before its pid is registered must +/// still be covered by the production exit sweep. The sweep latches the spawn +/// fence, waits for the in-flight reservation to publish, and then signals the +/// child it can now see; no process survives the exit. +#[cfg(all(unix, feature = "workspace-io-fault"))] +#[tokio::test] +async fn exit_sweep_covers_a_spawn_parked_before_registration() { + let fixture = Fixture::new("exit-parked-spawn"); + let workspace = fixture.root.to_string_lossy().into_owned(); + let park = fixture.parent.join("parked.pid"); + let release = fixture.parent.join("release.park"); + let sweep = fixture.parent.join("sweep.started"); + let park_env = park.to_string_lossy().into_owned(); + let release_env = release.to_string_lossy().into_owned(); + let sweep_env = sweep.to_string_lossy().into_owned(); + let mut child = ChildServer::spawn_with_env( + &[ + "tools", + "serve", + "--stdio", + "--workspace", + &workspace, + "--server-lifetime-ms", + "60000", + "--process-cleanup-timeout-ms", + "300", + ], + &[ + ("RUSTSCRIPT_AGENT_TEST_SPAWN_PARK_FILE", &park_env), + ("RUSTSCRIPT_AGENT_TEST_SPAWN_RELEASE_FILE", &release_env), + ("RUSTSCRIPT_AGENT_TEST_SWEEP_MARKER", &sweep_env), + ], + ) + .await; + child.initialize().await; + + let id = child.next_id; + child + .send(json!({ + "jsonrpc": "2.0", + "id": id, + "method": "tools/call", + "params": { + "name": "terminal", + "arguments": {"argv": ["/bin/sh", "-c", "exec sleep 300"]} + } + })) + .await; + + let park_deadline = std::time::Instant::now() + Duration::from_secs(20); + while !park.exists() { + assert!( + std::time::Instant::now() < park_deadline, + "the worker never reached the post-spawn reservation window" + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } + let pid: u32 = fs::read_to_string(&park) + .expect("parked pid file") + .trim() + .parse() + .expect("parked pid"); + + // Close stdin, then wait until the production exit path has entered the + // sweep. The worker is intentionally still parked: the sweep must wait for + // the in-flight spawn rather than drain an empty snapshot. + child.close_stdin(); + let sweep_deadline = std::time::Instant::now() + Duration::from_secs(30); + while !sweep.exists() { + assert!( + std::time::Instant::now() < sweep_deadline, + "the production exit sweep never started" + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } + // Give a fence-less sweep time to return and the process time to exit. + tokio::time::sleep(Duration::from_millis(200)).await; + fs::write(&release, b"release").expect("release parked spawn"); + let finished = child.finish(Duration::from_secs(15)).await; + + let gone_deadline = std::time::Instant::now() + Duration::from_secs(5); + loop { + let alive = unsafe { libc::kill(pid as libc::pid_t, 0) == 0 }; + if !alive { + break; + } + assert!( + std::time::Instant::now() < gone_deadline, + "a child parked before registration must not survive the exit sweep; status={:?} stderr={}", + finished.status, + finished.stderr + ); + tokio::time::sleep(Duration::from_millis(20)).await; + } +} + +/// The production exit path stops a live foreground child and every +/// descendant that shares its process group. +#[cfg(unix)] +#[tokio::test] +async fn exit_stops_a_live_child_and_its_descendant() { + let fixture = Fixture::new("exit-live-tree"); + let workspace = fixture.root.to_string_lossy().into_owned(); + let mut child = ChildServer::spawn(&[ + "tools", + "serve", + "--stdio", + "--workspace", + &workspace, + "--process-cleanup-timeout-ms", + "300", + ]) + .await; + child.initialize().await; + + let id = child.next_id; + child + .send(json!({ + "jsonrpc": "2.0", + "id": id, + "method": "tools/call", + "params": { + "name": "terminal", + "arguments": { + "argv": [ + "/bin/sh", + "-c", + "sleep 300 & printf '%s' $! > descendant.pid; printf '%s' $$ > child.pid; exec sleep 300" + ] + } + } + })) + .await; + + let read_pid = |name: &str| -> u32 { + let deadline = std::time::Instant::now() + Duration::from_secs(20); + loop { + if let Ok(text) = fs::read_to_string(fixture.root.join(name)) + && let Ok(pid) = text.trim().parse::() + { + return pid; + } + assert!( + std::time::Instant::now() < deadline, + "the {name} pid file never appeared" + ); + std::thread::sleep(Duration::from_millis(10)); + } + }; + let root = read_pid("child.pid"); + let descendant = read_pid("descendant.pid"); + + child.close_stdin(); + let _finished = child.finish(Duration::from_secs(20)).await; + + let gone_deadline = std::time::Instant::now() + Duration::from_secs(5); + for pid in [root, descendant] { + loop { + let alive = unsafe { libc::kill(pid as libc::pid_t, 0) == 0 }; + if !alive { + break; + } + assert!( + std::time::Instant::now() < gone_deadline, + "pid {pid} survived the production exit path" + ); + tokio::time::sleep(Duration::from_millis(20)).await; + } + } +} + +/// A reservation that publishes after the sweep's two-second deadline must +/// still be signalled and reaped before the process exits. The old sweep +/// drained its snapshot and returned at the deadline, so this child survived. +/// A sentinel proves no unrelated process is signalled. +#[cfg(all(unix, feature = "workspace-io-fault"))] +#[tokio::test] +async fn exit_sweep_signals_a_reservation_that_publishes_after_the_deadline() { + let fixture = Fixture::new("exit-late-publish"); + let workspace = fixture.root.to_string_lossy().into_owned(); + let park = fixture.parent.join("late.pid"); + let release = fixture.parent.join("release.late"); + let sweep = fixture.parent.join("late.sweep"); + let park_env = park.to_string_lossy().into_owned(); + let release_env = release.to_string_lossy().into_owned(); + let sweep_env = sweep.to_string_lossy().into_owned(); + let mut child = ChildServer::spawn_with_env( + &[ + "tools", + "serve", + "--stdio", + "--workspace", + &workspace, + "--server-lifetime-ms", + "60000", + "--process-cleanup-timeout-ms", + "300", + ], + &[ + ("RUSTSCRIPT_AGENT_TEST_SPAWN_PARK_FILE", &park_env), + ("RUSTSCRIPT_AGENT_TEST_SPAWN_RELEASE_FILE", &release_env), + ("RUSTSCRIPT_AGENT_TEST_SWEEP_MARKER", &sweep_env), + ], + ) + .await; + child.initialize().await; + + let id = child.next_id; + child + .send(json!({ + "jsonrpc": "2.0", + "id": id, + "method": "tools/call", + "params": { + "name": "terminal", + "arguments": {"argv": ["/bin/sh", "-c", "exec sleep 300"]} + } + })) + .await; + + let park_deadline = std::time::Instant::now() + Duration::from_secs(20); + while !park.exists() { + assert!( + std::time::Instant::now() < park_deadline, + "the worker never reached the post-spawn reservation window" + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } + let pid: u32 = fs::read_to_string(&park) + .expect("parked pid file") + .trim() + .parse() + .expect("parked pid"); + + let mut sentinel = std::process::Command::new("/bin/sleep") + .arg("300") + .spawn() + .expect("sentinel process"); + + child.close_stdin(); + let sweep_deadline = std::time::Instant::now() + Duration::from_secs(30); + while !sweep.exists() { + assert!( + std::time::Instant::now() < sweep_deadline, + "the production exit sweep never started" + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } + // Release the reservation only after the sweep's soft deadline (2 s), and + // inside its hard cap. + tokio::time::sleep(Duration::from_millis(2200)).await; + fs::write(&release, b"release").expect("release late spawn"); + let finished = child.finish(Duration::from_secs(20)).await; + + let gone_deadline = std::time::Instant::now() + Duration::from_secs(5); + loop { + let alive = unsafe { libc::kill(pid as libc::pid_t, 0) == 0 }; + if !alive { + break; + } + assert!( + std::time::Instant::now() < gone_deadline, + "a reservation published after the deadline must still be signalled; status={:?} stderr={}", + finished.status, + finished.stderr + ); + tokio::time::sleep(Duration::from_millis(20)).await; + } + assert!( + unsafe { libc::kill(sentinel.id() as libc::pid_t, 0) == 0 }, + "an unrelated process must never be signalled" + ); + let _ = sentinel.kill(); + let _ = sentinel.wait(); + assert!( + finished.stderr.contains("exit sweep: retained="), + "the sweep result must be a diagnostic, not only an exit status: {}", + finished.stderr + ); +} + +/// A constructor failure must use the bounded writer that is started before +/// construction: a full, unread stderr pipe must not block the process. +#[cfg(unix)] +#[tokio::test] +async fn constructor_failure_is_bounded_when_stderr_is_stalled() { + use std::io::Write as _; + + let fixture = Fixture::new("constructor-stalled"); + let missing = fixture.parent.join("missing-workspace"); + let missing = missing.to_string_lossy().into_owned(); + let (read_end, mut write_end) = UnixStream::pair().expect("socketpair"); + write_end + .set_nonblocking(true) + .expect("nonblocking stderr end"); + let filler = vec![b'x'; 8192]; + loop { + match write_end.write(&filler) { + Ok(0) => break, + Ok(_) => {} + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => break, + Err(error) => panic!("fill stderr socket: {error}"), + } + } + write_end + .set_nonblocking(false) + .expect("blocking stderr end"); + let child = Command::new(binary()) + .args(["tools", "serve", "--stdio", "--workspace", &missing]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::from(OwnedFd::from(write_end))) + .kill_on_drop(true) + .spawn() + .unwrap_or_else(|error| panic!("spawn {}: {error}", binary())); + let status = tokio::time::timeout(Duration::from_secs(10), child.wait_with_output()) + .await + .expect("a constructor refusal must not block on a stalled stderr") + .expect("wait for tool server"); + assert!(!status.status.success()); + drop(read_end); + + // With a drained stderr, the same failure still carries the stable code. + let output = Command::new(binary()) + .args(["tools", "serve", "--stdio", "--workspace", &missing]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .output() + .await + .expect("run tool server constructor failure"); + assert!(!output.status.success()); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("tools_workspace_unresolvable"), + "the constructor failure must reach stderr: {stderr}" + ); +} + +/// The teardown proof must survive diagnostic-queue pressure at the exact +/// moment it is emitted. The pipe is full and unread, and the test floods the +/// queue with TRACE-like lines; the proof's reserved slot is the only reason +/// it still reaches stderr. +#[cfg(all(unix, feature = "workspace-io-fault"))] +#[tokio::test] +async fn the_cleanup_proof_survives_diagnostic_pressure() { + use std::io::{Read as _, Write as _}; + + let fixture = Fixture::new("proof-pressure"); + let workspace = fixture.root.to_string_lossy().into_owned(); + let (read_end, mut write_end) = UnixStream::pair().expect("socketpair"); + write_end + .set_nonblocking(true) + .expect("nonblocking stderr end"); + let filler = vec![b'x'; 8192]; + loop { + match write_end.write(&filler) { + Ok(0) => break, + Ok(_) => {} + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => break, + Err(error) => panic!("fill stderr socket: {error}"), + } + } + write_end + .set_nonblocking(false) + .expect("blocking stderr end"); + let mut child = Command::new(binary()) + .args([ + "tools", + "serve", + "--stdio", + "--workspace", + &workspace, + "--server-lifetime-ms", + "60000", + "--process-cleanup-timeout-ms", + "300", + ]) + .env("RUSTSCRIPT_AGENT_TOOLS_TRACE", "1") + .env("RUSTSCRIPT_AGENT_TEST_DIAGNOSTIC_FLOOD", "1") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::from(OwnedFd::from(write_end))) + .kill_on_drop(true) + .spawn() + .unwrap_or_else(|error| panic!("spawn {}: {error}", binary())); + let mut stdin = child.stdin.take().expect("child stdin"); + let mut stdout = BufReader::new(child.stdout.take().expect("child stdout")); + let mut initialize = serde_json::to_vec(&json!({ + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2025-06-18", + "capabilities": {}, + "clientInfo": {"name": "proof-pressure", "version": "1"} + } + })) + .expect("serialize initialize"); + initialize.push(b'\n'); + stdin + .write_all(&initialize) + .await + .expect("write initialize"); + stdin.flush().await.expect("flush initialize"); + let mut response = String::new(); + tokio::time::timeout(Duration::from_secs(90), stdout.read_line(&mut response)) + .await + .expect("tool server initialized") + .expect("read initialize response"); + assert!(response.contains("\"result\""), "initialize={response}"); + + // The stderr pipe is already full, so the writer thread is blocked and + // the queue stays at capacity until the reader below starts. + drop(stdin); + let reader = tokio::task::spawn_blocking(move || { + std::thread::sleep(Duration::from_millis(350)); + let mut bytes = Vec::new(); + let _ = (&read_end).read_to_end(&mut bytes); + bytes + }); + let status = tokio::time::timeout(Duration::from_secs(20), child.wait()) + .await + .expect("diagnostic pressure must not extend the teardown bound") + .expect("wait for tool server"); + assert!(status.success(), "status={status:?}"); + let bytes = reader.await.expect("stderr reader"); + let stderr = String::from_utf8_lossy(&bytes); + assert!( + stderr.contains("rustscript-agent tools serve stopped:"), + "the cleanup proof must use its reserved slot: {stderr}" + ); + assert!( + stderr.contains("cleanup="), + "the cleanup proof must carry the typed cleanup result: {stderr}" + ); +} +/// A bounded abort of a stalled initialize write (here: the server lifetime) +/// is a normal stop, not an initialization failure. The peer never sent a +/// malformed message; the server itself abandoned the blocked writer. +#[cfg(unix)] +#[tokio::test] +async fn lifetime_expiry_during_a_stalled_initialize_write_is_a_normal_stop() { + use std::io::Write as _; + + let fixture = Fixture::new("init-stall-lifetime"); + let workspace = fixture.root.to_string_lossy().into_owned(); + let (parent_end, mut child_end) = UnixStream::pair().expect("socketpair"); + child_end + .set_nonblocking(true) + .expect("nonblocking stdout end"); + let filler = vec![b'x'; 8192]; + loop { + match child_end.write(&filler) { + Ok(0) => break, + Ok(_) => {} + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => break, + Err(error) => panic!("fill stdout socket: {error}"), + } + } + child_end + .set_nonblocking(false) + .expect("blocking stdout end"); + let mut child = Command::new(binary()) + .args([ + "tools", + "serve", + "--stdio", + "--workspace", + &workspace, + "--server-lifetime-ms", + "800", + "--process-cleanup-timeout-ms", + "300", + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::from(OwnedFd::from(child_end))) + .stderr(Stdio::piped()) + .kill_on_drop(true) + .spawn() + .unwrap_or_else(|error| panic!("spawn {}: {error}", binary())); + let mut stdin = child.stdin.take().expect("child stdin"); + let mut initialize = serde_json::to_vec(&json!({ + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2025-06-18", + "capabilities": {}, + "clientInfo": {"name": "init-lifetime-test", "version": "1"} + } + })) + .expect("serialize initialize"); + initialize.push(b'\n'); + stdin + .write_all(&initialize) + .await + .expect("write initialize"); + stdin.flush().await.expect("flush initialize"); + // Keep stdin and the unread stdout end open: only the lifetime bound may + // end this handshake. + let _stdin = stdin; + let _parent = parent_end; + + let status = tokio::time::timeout(Duration::from_secs(90), child.wait()) + .await + .expect("the lifetime bound must end the stalled handshake") + .expect("wait for tool server"); + assert!(status.success(), "status={status:?}"); + let mut stderr = Vec::new(); + child + .stderr + .take() + .expect("child stderr") + .read_to_end(&mut stderr) + .await + .expect("drain child stderr"); + let stderr = String::from_utf8_lossy(&stderr); + assert!( + stderr.contains("quit=lifetime_elapsed"), + "the abort must map to the recorded lifetime stop: {stderr}" + ); + assert!( + !stderr.contains("tools_initialize_failed"), + "our own bounded abort must not be reported as a protocol rejection: {stderr}" + ); +} + +/// The environment-selected readiness marker can be a FIFO with no reader. +/// Writing it must never block the serving path: the reader pump still starts, +/// an EOF still stops the server, and the process reaches its bounded exit. +#[cfg(unix)] +#[tokio::test] +async fn a_reader_less_readiness_fifo_does_not_block_the_bounded_exit() { + use std::ffi::CString; + use std::os::unix::ffi::OsStrExt as _; + + let fixture = Fixture::new("ready-fifo"); + let workspace = fixture.root.to_string_lossy().into_owned(); + let ready = fixture.parent.join("ready.fifo"); + let ready_c = CString::new(ready.as_os_str().as_bytes()).expect("fifo path"); + // SAFETY: a NUL-terminated path and a literal mode; no memory is shared. + let created = unsafe { libc::mkfifo(ready_c.as_ptr(), 0o600) }; + assert_eq!( + created, + 0, + "mkfifo {}: {}", + ready.display(), + std::io::Error::last_os_error() + ); + + let mut child = Command::new(binary()) + .args([ + "tools", + "serve", + "--stdio", + "--workspace", + &workspace, + "--server-lifetime-ms", + "60000", + "--process-cleanup-timeout-ms", + "300", + ]) + .env("RUSTSCRIPT_AGENT_TEST_READY_MARKER", "1") + .env("RUSTSCRIPT_AGENT_TEST_READY_FILE", &ready) + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .kill_on_drop(true) + .spawn() + .unwrap_or_else(|error| panic!("spawn {}: {error}", binary())); + let stdin = child.stdin.take().expect("child stdin"); + let stderr = child.stderr.take().expect("child stderr"); + let mut lines = BufReader::new(stderr).lines(); + + // Readiness is announced on stderr immediately before the FIFO write, so + // seeing it proves the serving future reached the hook without entering + // the protocol. + let ready_seen = tokio::time::timeout(Duration::from_secs(90), async { + while let Ok(Some(line)) = lines.next_line().await { + if line.contains("serve ready") { + return true; + } + } + false + }) + .await + .expect("readiness diagnostic must arrive"); + assert!(ready_seen, "the server never announced readiness"); + + let triggered = std::time::Instant::now(); + drop(stdin); + let status = tokio::time::timeout(Duration::from_secs(10), child.wait()) + .await + .expect("a reader-less readiness FIFO must not extend the bounded exit") + .expect("wait for tool server"); + assert!( + triggered.elapsed() <= Duration::from_secs(10), + "bounded exit took {:?}", + triggered.elapsed() + ); + assert!(status.success(), "status={status:?}"); +} + +/// Kills a fixture process (and its process group) if a test fails before it +/// has proven the process gone. +#[cfg(all(target_os = "linux", feature = "workspace-io-fault"))] +struct ParkedChildGuard { + pid: Option, +} + +#[cfg(all(target_os = "linux", feature = "workspace-io-fault"))] +impl ParkedChildGuard { + fn new(pid: u32) -> Self { + Self { pid: Some(pid) } + } + + fn disarm(&mut self) { + self.pid = None; + } +} + +#[cfg(all(target_os = "linux", feature = "workspace-io-fault"))] +impl Drop for ParkedChildGuard { + fn drop(&mut self) { + if let Some(pid) = self.pid { + let pid = pid as libc::pid_t; + unsafe { + let _ = libc::kill(-pid, libc::SIGKILL); + let _ = libc::kill(pid, libc::SIGKILL); + } + } + } +} + +#[cfg(all(target_os = "linux", feature = "workspace-io-fault"))] +fn linux_process_state(pid: u32) -> Option { + let stat = fs::read_to_string(format!("/proc/{pid}/stat")).ok()?; + // The state is the first field after the parenthesized command name. + let close = stat.rfind(')')?; + stat[close + 1..] + .split_whitespace() + .next() + .map(str::to_string) +} + +#[cfg(all(target_os = "linux", feature = "workspace-io-fault"))] +fn linux_cmdline(pid: u32) -> String { + let raw = fs::read(format!("/proc/{pid}/cmdline")).unwrap_or_default(); + raw.split(|byte| *byte == 0) + .filter(|part| !part.is_empty()) + .map(|part| String::from_utf8_lossy(part).into_owned()) + .collect::>() + .join(" ") +} + +/// Waits for a file written by a spawn hook and returns the pid it names. +#[cfg(all(target_os = "linux", feature = "workspace-io-fault"))] +async fn wait_for_pid_file( + path: &std::path::Path, + deadline: std::time::Instant, + what: &str, +) -> u32 { + while !path.exists() { + assert!( + std::time::Instant::now() < deadline, + "{what} never appeared" + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } + fs::read_to_string(path) + .unwrap_or_else(|error| panic!("read {what}: {error}")) + .trim() + .parse() + .unwrap_or_else(|error| panic!("parse {what} pid: {error}")) +} + +/// Waits for a file while allowing a running worker to make progress. +#[cfg(all(target_os = "linux", feature = "workspace-io-fault"))] +async fn await_file(path: &std::path::Path, deadline: std::time::Instant, what: &str) { + while !path.exists() { + assert!( + std::time::Instant::now() < deadline, + "{what} never appeared" + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } +} + +/// Waits, bounded, for a sweep-owned fixture to become an unreaped zombie. +/// +/// SIGKILL delivery is asynchronous: the park file proves the sweep reached +/// its reap attempt, not that the kernel already applied the signal. The +/// ownership requirement is unchanged - the child must still exist and be +/// unreaped when the worker resumes. +#[cfg(all(target_os = "linux", feature = "workspace-io-fault"))] +async fn await_unreaped_zombie(pid: u32, deadline: std::time::Instant, what: &str) { + while linux_process_state(pid).as_deref() != Some("Z") { + assert!( + std::time::Instant::now() < deadline, + "{what}: pid={pid} state={:?}", + linux_process_state(pid) + ); + tokio::time::sleep(Duration::from_millis(5)).await; + } +} + +/// Waits for the worker's failed-release decision marker for `pid` while +/// requiring that the sweep-owned process still exists. +/// +/// The sweep is parked before its reap, so a worker that signals or reaps the +/// transferred child removes the process before the marker can appear. That is +/// the observable ownership difference; no PID reuse is required. +#[cfg(all(target_os = "linux", feature = "workspace-io-fault"))] +async fn await_swept_failure_marker( + marker: &std::path::Path, + pid: u32, + deadline: std::time::Instant, + context: &str, +) -> String { + let prefix = format!("{pid} "); + while std::time::Instant::now() < deadline { + if let Ok(text) = fs::read_to_string(marker) + && let Some(line) = text.lines().find(|line| line.starts_with(&prefix)) + { + return line.to_string(); + } + let state = linux_process_state(pid); + assert!( + state.is_some(), + "the worker reaped a child that the exit sweep already owned: \ + pid={pid} context={context}" + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } + panic!( + "the worker never recorded its failed-release decision: marker={marker:?} \ + marker_text={:?} state={:?} context={context}", + fs::read_to_string(marker).ok(), + linux_process_state(pid) + ); +} + +/// The production hard-exit path must never leave a child that the exit sweep +/// cannot name. +/// +/// The worker is parked between the successful OS spawn and the recording of +/// its pid: the sweep cannot name this child, and the CLI then exits. The +/// direct child must be a gate that has executed no tool code and that exits +/// when its parent-bound control channel reaches EOF. The command's marker +/// file must therefore never appear, and the recorded pid must disappear +/// without the test releasing the parked worker. +#[cfg(all(target_os = "linux", feature = "workspace-io-fault"))] +#[tokio::test] +async fn exit_with_an_unrecorded_spawn_runs_no_tool_code_and_leaves_no_child() { + let fixture = Fixture::new("exit-unrecorded-spawn"); + let workspace = fixture.root.to_string_lossy().into_owned(); + let park = fixture.parent.join("before-record.pid"); + let release = fixture.parent.join("never-release.park"); + let marker = fixture.parent.join("tool-ran.marker"); + let sweep = fixture.parent.join("sweep.started"); + let park_env = park.to_string_lossy().into_owned(); + let release_env = release.to_string_lossy().into_owned(); + let marker_env = marker.to_string_lossy().into_owned(); + let sweep_env = sweep.to_string_lossy().into_owned(); + let command = format!("printf ran > '{marker_env}'; exec sleep 300"); + + let mut child = ChildServer::spawn_with_env( + &[ + "tools", + "serve", + "--stdio", + "--workspace", + &workspace, + "--server-lifetime-ms", + "60000", + "--process-cleanup-timeout-ms", + "300", + ], + &[ + ( + "RUSTSCRIPT_AGENT_TEST_SPAWN_BEFORE_RECORD_PARK_FILE", + &park_env, + ), + ( + "RUSTSCRIPT_AGENT_TEST_SPAWN_BEFORE_RECORD_RELEASE_FILE", + &release_env, + ), + ("RUSTSCRIPT_AGENT_TEST_SWEEP_MARKER", &sweep_env), + ], + ) + .await; + + // Startup readiness has its own budget: construction compiles the bundled + // dispatch program in a debug build. + let ready = tokio::time::timeout(Duration::from_secs(90), child.initialize()).await; + assert!(ready.is_ok(), "the tool server never became ready"); + + let id = child.next_id; + child + .send(json!({ + "jsonrpc": "2.0", + "id": id, + "method": "tools/call", + "params": { + "name": "terminal", + "arguments": {"argv": ["/bin/sh", "-c", command]} + } + })) + .await; + + let park_deadline = std::time::Instant::now() + Duration::from_secs(30); + while !park.exists() { + assert!( + std::time::Instant::now() < park_deadline, + "the worker never reached the spawn-before-record window" + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } + let pid: u32 = fs::read_to_string(&park) + .expect("parked pid file") + .trim() + .parse() + .expect("parked pid"); + let mut guard = ParkedChildGuard::new(pid); + // Exact child identity and liveness: the parked pid must be a live process + // whose command line is readable before EOF. The production invariant + // needs the direct child to be the pre-exec gate here, not the tool and + // not a process that is already racing to exit. + let identity_deadline = std::time::Instant::now() + Duration::from_secs(10); + let mut parked_cmdline = String::new(); + let mut parked_state = None; + while std::time::Instant::now() < identity_deadline { + parked_cmdline = linux_cmdline(pid); + parked_state = linux_process_state(pid); + if !parked_cmdline.is_empty() && parked_state.as_deref() != Some("Z") { + break; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + assert!( + !parked_cmdline.is_empty() && parked_state.as_deref() != Some("Z"), + "the parked pid {pid} must name a live direct child: state={parked_state:?} \ + cmdline={parked_cmdline:?}" + ); + assert!( + parked_cmdline.contains("--rustscript-agent-exec-gate-v1"), + "the direct child at the pre-record boundary must be the pre-exec gate, \ + not the tool: pid={pid} cmdline={parked_cmdline:?}" + ); + // A gate that exits immediately would also make the later disappearance + // assertions pass, so prove it is parked rather than racing out. + tokio::time::sleep(Duration::from_millis(200)).await; + let still_parked = linux_process_state(pid); + assert!( + still_parked.as_deref() != Some("Z") && still_parked.is_some(), + "the pre-exec gate must stay parked until the worker records its pid: \ + pid={pid} state={still_parked:?}" + ); + + // Post-EOF teardown has its own budget, separate from startup. + let eof = std::time::Instant::now(); + child.close_stdin(); + let finished = child.finish(Duration::from_secs(30)).await; + let after_eof = eof.elapsed(); + assert!( + after_eof <= Duration::from_secs(20), + "the CLI exit must stay inside the bounded teardown: {after_eof:?}" + ); + + // The tool must not have executed before the gate was released, and no + // owned process may survive the CLI exit. + let gone_deadline = std::time::Instant::now() + Duration::from_secs(5); + let mut last_state = linux_process_state(pid); + while last_state.is_some() { + assert!( + std::time::Instant::now() < gone_deadline, + "an unregistered direct child must not survive the CLI exit: \ + pid={pid} state={last_state:?} cmdline={parked_cmdline:?} \ + marker={} sweep={} status={:?} stderr={}", + marker.exists(), + sweep.exists(), + finished.status, + finished.stderr + ); + tokio::time::sleep(Duration::from_millis(20)).await; + last_state = linux_process_state(pid); + } + guard.disarm(); + assert!( + !marker.exists(), + "the tool must not run before its pid ownership is enrolled: pid={pid} \ + cmdline={parked_cmdline:?}" + ); + // The production sweep is still part of this run's proof. + assert!( + sweep.exists() || finished.stderr.contains("cleanup="), + "the packaged exit path must still produce its teardown proof: \ + status={:?} stderr={}", + finished.status, + finished.stderr + ); +} + +/// A confirmed exec errno stays a typed spawn failure with no tool effect even +/// after the exit sweep owns the exact reservation. +/// +/// The worker is parked after the release byte was written, so the sweep can +/// drain and signal the gate before the worker reads the errno. The sweep is +/// parked before its own reap: the worker must not reap the transferred child. +#[cfg(all(target_os = "linux", feature = "workspace-io-fault"))] +#[tokio::test] +async fn confirmed_exec_failure_stays_typed_when_the_sweep_owns_the_reservation() { + let fixture = Fixture::new("swept-exec-error"); + let workspace = fixture.root.to_string_lossy().into_owned(); + let after_release = fixture.parent.join("after-release.pid"); + let worker_release = fixture.parent.join("after-release.release"); + let sweep_park = fixture.parent.join("sweep-reap.park"); + let sweep_release = fixture.parent.join("sweep-reap.release"); + let sweep_marker = fixture.parent.join("sweep.started"); + let failure_marker = fixture.parent.join("failure.marker"); + let missing = fixture.parent.join("missing-tool"); + let missing = missing.to_string_lossy().into_owned(); + + let mut child = ChildServer::spawn_with_env( + &[ + "tools", + "serve", + "--stdio", + "--workspace", + &workspace, + "--server-lifetime-ms", + "60000", + "--process-cleanup-timeout-ms", + "300", + ], + &[ + ( + "RUSTSCRIPT_AGENT_TEST_GATE_AFTER_RELEASE_PARK_FILE", + after_release.to_str().expect("utf-8 path"), + ), + ( + "RUSTSCRIPT_AGENT_TEST_GATE_AFTER_RELEASE_RELEASE_FILE", + worker_release.to_str().expect("utf-8 path"), + ), + ( + "RUSTSCRIPT_AGENT_TEST_SWEEP_REAP_PARK_FILE", + sweep_park.to_str().expect("utf-8 path"), + ), + ( + "RUSTSCRIPT_AGENT_TEST_SWEEP_REAP_RELEASE_FILE", + sweep_release.to_str().expect("utf-8 path"), + ), + ( + "RUSTSCRIPT_AGENT_TEST_GATE_RELEASE_FAILURE_MARKER", + failure_marker.to_str().expect("utf-8 path"), + ), + ( + "RUSTSCRIPT_AGENT_TEST_SWEEP_MARKER", + sweep_marker.to_str().expect("utf-8 path"), + ), + ], + ) + .await; + + let ready = tokio::time::timeout(Duration::from_secs(90), child.initialize()).await; + assert!(ready.is_ok(), "the tool server never became ready"); + + let id = child.next_id; + child + .send(json!({ + "jsonrpc": "2.0", + "id": id, + "method": "tools/call", + "params": { + "name": "terminal", + "arguments": {"argv": [missing]} + } + })) + .await; + + let pid = wait_for_pid_file( + &after_release, + std::time::Instant::now() + Duration::from_secs(30), + "post-release park", + ) + .await; + + // Post-EOF teardown has its own budget, separate from startup. + let eof = std::time::Instant::now(); + child.close_stdin(); + await_file( + &sweep_park, + std::time::Instant::now() + Duration::from_secs(10), + "sweep reap park", + ) + .await; + assert_eq!( + linux_process_state(pid).as_deref(), + Some("Z"), + "the sweep must own an unreaped gate before the worker resumes: pid={pid}" + ); + + fs::write(&worker_release, b"release").expect("release the parked gate worker"); + let line = await_swept_failure_marker( + &failure_marker, + pid, + std::time::Instant::now() + Duration::from_secs(10), + "confirmed exec errno", + ) + .await; + assert_eq!( + line, + format!("{pid} exec_failed swept effect=0"), + "a confirmed exec errno must keep the typed spawn failure and no tool effect" + ); + assert_eq!( + linux_process_state(pid).as_deref(), + Some("Z"), + "the worker must not reap a child the sweep already owns: pid={pid}" + ); + + fs::write(&sweep_release, b"release").expect("release the parked sweep"); + let finished = child.finish(Duration::from_secs(30)).await; + assert!( + eof.elapsed() <= Duration::from_secs(25), + "the CLI exit must stay inside the bounded teardown: {:?}", + eof.elapsed() + ); + assert!( + sweep_marker.exists() || finished.stderr.contains("cleanup="), + "the packaged exit path must still produce its teardown proof: \ + status={:?} stderr={}", + finished.status, + finished.stderr + ); +} + +/// An ambiguous post-release confirmation keeps the tool effect after the exit +/// sweep owns the exact reservation, and the worker must not reap the swept +/// child. +#[cfg(all(target_os = "linux", feature = "workspace-io-fault"))] +#[tokio::test] +async fn ambiguous_release_keeps_the_effect_when_the_sweep_owns_the_reservation() { + let fixture = Fixture::new("swept-ambiguous"); + let workspace = fixture.root.to_string_lossy().into_owned(); + let after_release = fixture.parent.join("after-release.pid"); + let worker_release = fixture.parent.join("after-release.release"); + let sweep_park = fixture.parent.join("sweep-reap.park"); + let sweep_release = fixture.parent.join("sweep-reap.release"); + let sweep_marker = fixture.parent.join("sweep.started"); + let failure_marker = fixture.parent.join("failure.marker"); + let tool_marker = fixture.parent.join("tool-ran.marker"); + let command = format!( + "printf ran > '{}'; exec sleep 300", + tool_marker.to_string_lossy() + ); + + let mut child = ChildServer::spawn_with_env( + &[ + "tools", + "serve", + "--stdio", + "--workspace", + &workspace, + "--server-lifetime-ms", + "60000", + "--process-cleanup-timeout-ms", + "300", + ], + &[ + ( + "RUSTSCRIPT_AGENT_TEST_GATE_AFTER_RELEASE_PARK_FILE", + after_release.to_str().expect("utf-8 path"), + ), + ( + "RUSTSCRIPT_AGENT_TEST_GATE_AFTER_RELEASE_RELEASE_FILE", + worker_release.to_str().expect("utf-8 path"), + ), + ("RUSTSCRIPT_AGENT_TEST_GATE_FORCE_AMBIGUOUS", "1"), + ( + "RUSTSCRIPT_AGENT_TEST_SWEEP_REAP_PARK_FILE", + sweep_park.to_str().expect("utf-8 path"), + ), + ( + "RUSTSCRIPT_AGENT_TEST_SWEEP_REAP_RELEASE_FILE", + sweep_release.to_str().expect("utf-8 path"), + ), + ( + "RUSTSCRIPT_AGENT_TEST_GATE_RELEASE_FAILURE_MARKER", + failure_marker.to_str().expect("utf-8 path"), + ), + ( + "RUSTSCRIPT_AGENT_TEST_SWEEP_MARKER", + sweep_marker.to_str().expect("utf-8 path"), + ), + ], + ) + .await; + + let ready = tokio::time::timeout(Duration::from_secs(90), child.initialize()).await; + assert!(ready.is_ok(), "the tool server never became ready"); + + let id = child.next_id; + child + .send(json!({ + "jsonrpc": "2.0", + "id": id, + "method": "tools/call", + "params": { + "name": "terminal", + "arguments": {"argv": ["/bin/sh", "-c", command]} + } + })) + .await; + + let pid = wait_for_pid_file( + &after_release, + std::time::Instant::now() + Duration::from_secs(30), + "post-release park", + ) + .await; + await_file( + &tool_marker, + std::time::Instant::now() + Duration::from_secs(10), + "released tool marker", + ) + .await; + + child.close_stdin(); + await_file( + &sweep_park, + std::time::Instant::now() + Duration::from_secs(10), + "sweep reap park", + ) + .await; + await_unreaped_zombie( + pid, + std::time::Instant::now() + Duration::from_secs(5), + "the sweep must own an unreaped tool process before the worker resumes", + ) + .await; + + fs::write(&worker_release, b"release").expect("release the parked gate worker"); + let line = await_swept_failure_marker( + &failure_marker, + pid, + std::time::Instant::now() + Duration::from_secs(10), + "ambiguous release", + ) + .await; + assert_eq!( + line, + format!("{pid} ambiguous swept effect=1"), + "a release that may have reached the tool must keep its ledger effect" + ); + assert!( + tool_marker.exists(), + "the released tool must have executed before the sweep killed it" + ); + + fs::write(&sweep_release, b"release").expect("release the parked sweep"); + let finished = child.finish(Duration::from_secs(30)).await; + assert!( + sweep_marker.exists() || finished.stderr.contains("cleanup="), + "the packaged exit path must still produce its teardown proof: \ + status={:?} stderr={}", + finished.status, + finished.stderr + ); +} + +/// A release that is known never to have been delivered records no tool effect +/// even after the sweep owns the exact reservation. +/// +/// The gate is still parked before release when EOF lands, so the sweep kills +/// it. The worker's later write fails; the sweep is parked before its reap, so +/// a worker that reaps the transferred child removes the process observably. +#[cfg(all(target_os = "linux", feature = "workspace-io-fault"))] +#[tokio::test] +async fn undelivered_release_records_no_effect_and_does_not_reap_the_swept_child() { + let fixture = Fixture::new("swept-undelivered"); + let workspace = fixture.root.to_string_lossy().into_owned(); + let before_release = fixture.parent.join("before-release.pid"); + let worker_release = fixture.parent.join("before-release.release"); + let sweep_park = fixture.parent.join("sweep-reap.park"); + let sweep_release = fixture.parent.join("sweep-reap.release"); + let sweep_marker = fixture.parent.join("sweep.started"); + let failure_marker = fixture.parent.join("failure.marker"); + let tool_marker = fixture.parent.join("tool-ran.marker"); + let command = format!( + "printf ran > '{}'; exec sleep 300", + tool_marker.to_string_lossy() + ); + + let mut child = ChildServer::spawn_with_env( + &[ + "tools", + "serve", + "--stdio", + "--workspace", + &workspace, + "--server-lifetime-ms", + "60000", + "--process-cleanup-timeout-ms", + "300", + ], + &[ + ( + "RUSTSCRIPT_AGENT_TEST_SPAWN_BEFORE_RELEASE_PARK_FILE", + before_release.to_str().expect("utf-8 path"), + ), + ( + "RUSTSCRIPT_AGENT_TEST_SPAWN_BEFORE_RELEASE_RELEASE_FILE", + worker_release.to_str().expect("utf-8 path"), + ), + ( + "RUSTSCRIPT_AGENT_TEST_SWEEP_REAP_PARK_FILE", + sweep_park.to_str().expect("utf-8 path"), + ), + ( + "RUSTSCRIPT_AGENT_TEST_SWEEP_REAP_RELEASE_FILE", + sweep_release.to_str().expect("utf-8 path"), + ), + ( + "RUSTSCRIPT_AGENT_TEST_GATE_RELEASE_FAILURE_MARKER", + failure_marker.to_str().expect("utf-8 path"), + ), + ( + "RUSTSCRIPT_AGENT_TEST_SWEEP_MARKER", + sweep_marker.to_str().expect("utf-8 path"), + ), + ], + ) + .await; + + let ready = tokio::time::timeout(Duration::from_secs(90), child.initialize()).await; + assert!(ready.is_ok(), "the tool server never became ready"); + + let id = child.next_id; + child + .send(json!({ + "jsonrpc": "2.0", + "id": id, + "method": "tools/call", + "params": { + "name": "terminal", + "arguments": {"argv": ["/bin/sh", "-c", command]} + } + })) + .await; + + let pid = wait_for_pid_file( + &before_release, + std::time::Instant::now() + Duration::from_secs(30), + "pre-release park", + ) + .await; + let cmdline = linux_cmdline(pid); + assert!( + cmdline.contains("--rustscript-agent-exec-gate-v1"), + "the parked direct child must still be the pre-exec gate: pid={pid} cmdline={cmdline:?}" + ); + + child.close_stdin(); + await_file( + &sweep_park, + std::time::Instant::now() + Duration::from_secs(10), + "sweep reap park", + ) + .await; + await_unreaped_zombie( + pid, + std::time::Instant::now() + Duration::from_secs(5), + "the sweep must own an unreaped gate before the worker resumes", + ) + .await; + assert!( + !tool_marker.exists(), + "the undelivered release must never run tool code" + ); + + fs::write(&worker_release, b"release").expect("release the parked gate worker"); + let line = await_swept_failure_marker( + &failure_marker, + pid, + std::time::Instant::now() + Duration::from_secs(10), + "undelivered release", + ) + .await; + assert_eq!( + line, + format!("{pid} not_released swept effect=0"), + "a release that was never delivered must record no tool effect" + ); + assert!( + !tool_marker.exists(), + "the undelivered release must still never run tool code" + ); + assert_eq!( + linux_process_state(pid).as_deref(), + Some("Z"), + "the worker must not reap a child the sweep already owns: pid={pid}" + ); + + fs::write(&sweep_release, b"release").expect("release the parked sweep"); + let finished = child.finish(Duration::from_secs(30)).await; + assert!( + sweep_marker.exists() || finished.stderr.contains("cleanup="), + "the packaged exit path must still produce its teardown proof: \ + status={:?} stderr={}", + finished.status, + finished.stderr + ); +} + +/// The inverse ownership ordering for the gate-failure worker. +/// +/// The worker first observes that it still owns the recorded reservation, then +/// parks before the atomic decision. The packaged EOF sweep claims the exact +/// record and parks before its own reap, so the child is an unreaped zombie +/// owned by the sweep. When the worker resumes it must revalidate the +/// tombstone and perform no numeric group signal and no reap; the sweep alone +/// owns the still-unreaped child and its disappearance. +#[cfg(all(target_os = "linux", feature = "workspace-io-fault"))] +#[tokio::test] +async fn worker_that_observed_eligibility_does_not_touch_a_swept_child() { + let fixture = Fixture::new("worker-inverse"); + let workspace = fixture.root.to_string_lossy().into_owned(); + let eligibility_park = fixture.parent.join("eligibility.pid"); + let eligibility_release = fixture.parent.join("eligibility.release"); + let sweep_park = fixture.parent.join("sweep-reap.park"); + let sweep_release = fixture.parent.join("sweep-reap.release"); + let sweep_marker = fixture.parent.join("sweep.started"); + let failure_marker = fixture.parent.join("failure.marker"); + let missing = fixture.parent.join("missing-tool"); + let missing = missing.to_string_lossy().into_owned(); + + let mut child = ChildServer::spawn_with_env( + &[ + "tools", + "serve", + "--stdio", + "--workspace", + &workspace, + "--server-lifetime-ms", + "60000", + "--process-cleanup-timeout-ms", + "300", + ], + &[ + ( + "RUSTSCRIPT_AGENT_TEST_OWNED_CLEANUP_PARK_FILE", + eligibility_park.to_str().expect("utf-8 path"), + ), + ( + "RUSTSCRIPT_AGENT_TEST_OWNED_CLEANUP_RELEASE_FILE", + eligibility_release.to_str().expect("utf-8 path"), + ), + ( + "RUSTSCRIPT_AGENT_TEST_SWEEP_REAP_PARK_FILE", + sweep_park.to_str().expect("utf-8 path"), + ), + ( + "RUSTSCRIPT_AGENT_TEST_SWEEP_REAP_RELEASE_FILE", + sweep_release.to_str().expect("utf-8 path"), + ), + ( + "RUSTSCRIPT_AGENT_TEST_GATE_RELEASE_FAILURE_MARKER", + failure_marker.to_str().expect("utf-8 path"), + ), + ( + "RUSTSCRIPT_AGENT_TEST_SWEEP_MARKER", + sweep_marker.to_str().expect("utf-8 path"), + ), + ], + ) + .await; + + let ready = tokio::time::timeout(Duration::from_secs(90), child.initialize()).await; + assert!(ready.is_ok(), "the tool server never became ready"); + + let id = child.next_id; + child + .send(json!({ + "jsonrpc": "2.0", + "id": id, + "method": "tools/call", + "params": { + "name": "terminal", + "arguments": {"argv": [missing]} + } + })) + .await; + + let pid = wait_for_pid_file( + &eligibility_park, + std::time::Instant::now() + Duration::from_secs(30), + "worker eligibility park", + ) + .await; + let mut guard = ParkedChildGuard::new(pid); + // The confirmed exec errno already exited the gate; the worker is parked + // after eligibility, so the child is an unreaped zombie. + let zombie_deadline = std::time::Instant::now() + Duration::from_secs(10); + while linux_process_state(pid).as_deref() != Some("Z") { + assert!( + std::time::Instant::now() < zombie_deadline, + "the failed exec gate must exit while the worker is parked: \ + pid={pid} state={:?}", + linux_process_state(pid) + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } + + // Post-EOF teardown has its own budget, separate from startup. + let eof = std::time::Instant::now(); + child.close_stdin(); + await_file( + &sweep_park, + std::time::Instant::now() + Duration::from_secs(10), + "sweep reap park", + ) + .await; + assert_eq!( + linux_process_state(pid).as_deref(), + Some("Z"), + "the sweep must own an unreaped child before the worker resumes: pid={pid}" + ); + + fs::write(&eligibility_release, b"release").expect("release the parked worker"); + let line = await_swept_failure_marker( + &failure_marker, + pid, + std::time::Instant::now() + Duration::from_secs(10), + "worker eligibility-before-claim", + ) + .await; + assert_eq!( + line, + format!("{pid} exec_failed swept effect=0"), + "a worker that lost the record before its atomic attempt must transfer it, not reap it" + ); + assert_eq!( + linux_process_state(pid).as_deref(), + Some("Z"), + "the worker must not signal or reap a child the sweep already owns: pid={pid}" + ); + + fs::write(&sweep_release, b"release").expect("release the parked sweep"); + let finished = child.finish(Duration::from_secs(30)).await; + assert!( + eof.elapsed() <= Duration::from_secs(25), + "the CLI exit must stay inside the bounded teardown: {:?}", + eof.elapsed() + ); + let gone_deadline = std::time::Instant::now() + Duration::from_secs(5); + while linux_process_state(pid).is_some() { + assert!( + std::time::Instant::now() < gone_deadline, + "the sweep alone must reap the exact child it owned: pid={pid}" + ); + tokio::time::sleep(Duration::from_millis(20)).await; + } + guard.disarm(); + assert!( + sweep_marker.exists() || finished.stderr.contains("cleanup="), + "the packaged exit path must still produce its teardown proof: \ + status={:?} stderr={}", + finished.status, + finished.stderr + ); +} + +/// A live gate failure is reaped by its own worker before the answer. +/// +/// The worker reaches eligibility and wins the atomic attempt while the record +/// is still `Recorded`. It must signal and reap the exact gate, retire the +/// record in the same critical section, and return the typed spawn failure +/// without any exit sweep. The workspace is still serving (stdin is open), so +/// the child cannot disappear through the packaged teardown path. +#[cfg(all(target_os = "linux", feature = "workspace-io-fault"))] +#[tokio::test] +async fn confirmed_exec_failure_reaps_its_own_gate_without_a_sweep() { + let fixture = Fixture::new("own-gate"); + let workspace = fixture.root.to_string_lossy().into_owned(); + let eligibility_park = fixture.parent.join("eligibility.pid"); + let eligibility_release = fixture.parent.join("eligibility.release"); + let failure_marker = fixture.parent.join("failure.marker"); + let missing = fixture.parent.join("missing-tool"); + let missing = missing.to_string_lossy().into_owned(); + + let mut child = ChildServer::spawn_with_env( + &[ + "tools", + "serve", + "--stdio", + "--workspace", + &workspace, + "--server-lifetime-ms", + "60000", + "--process-cleanup-timeout-ms", + "300", + ], + &[ + ( + "RUSTSCRIPT_AGENT_TEST_OWNED_CLEANUP_PARK_FILE", + eligibility_park.to_str().expect("utf-8 path"), + ), + ( + "RUSTSCRIPT_AGENT_TEST_OWNED_CLEANUP_RELEASE_FILE", + eligibility_release.to_str().expect("utf-8 path"), + ), + ( + "RUSTSCRIPT_AGENT_TEST_GATE_RELEASE_FAILURE_MARKER", + failure_marker.to_str().expect("utf-8 path"), + ), + ], + ) + .await; + + let ready = tokio::time::timeout(Duration::from_secs(90), child.initialize()).await; + assert!(ready.is_ok(), "the tool server never became ready"); + + let id = child.next_id; + child + .send(json!({ + "jsonrpc": "2.0", + "id": id, + "method": "tools/call", + "params": { + "name": "terminal", + "arguments": {"argv": [missing]} + } + })) + .await; + + let pid = wait_for_pid_file( + &eligibility_park, + std::time::Instant::now() + Duration::from_secs(30), + "worker eligibility park", + ) + .await; + let mut guard = ParkedChildGuard::new(pid); + let zombie_deadline = std::time::Instant::now() + Duration::from_secs(10); + while linux_process_state(pid).as_deref() != Some("Z") { + assert!( + std::time::Instant::now() < zombie_deadline, + "the failed exec gate must exit while the worker is parked: \ + pid={pid} state={:?}", + linux_process_state(pid) + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } + + fs::write(&eligibility_release, b"release").expect("release the parked worker"); + let prefix = format!("{pid} "); + let marker_deadline = std::time::Instant::now() + Duration::from_secs(10); + let line = loop { + if let Ok(text) = fs::read_to_string(&failure_marker) + && let Some(line) = text.lines().find(|line| line.starts_with(&prefix)) + { + break line.to_string(); + } + assert!( + std::time::Instant::now() < marker_deadline, + "the worker never recorded its own cleanup decision: marker={:?}", + fs::read_to_string(&failure_marker).ok() + ); + tokio::time::sleep(Duration::from_millis(10)).await; + }; + assert_eq!( + line, + format!("{pid} exec_failed reaped effect=0"), + "the owning worker must reap its own gate and keep the typed failure" + ); + let gone_deadline = std::time::Instant::now() + Duration::from_secs(5); + while linux_process_state(pid).is_some() { + assert!( + std::time::Instant::now() < gone_deadline, + "the owning worker must reap the exact gate it proved gone: pid={pid}" + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } + guard.disarm(); + + // The server is still serving; stdin was never closed for this call. + child.close_stdin(); + let _finished = child.finish(Duration::from_secs(30)).await; +} diff --git a/tests/mcp_tool_transport_tests.rs b/tests/mcp_tool_transport_tests.rs new file mode 100644 index 00000000..2931a521 --- /dev/null +++ b/tests/mcp_tool_transport_tests.rs @@ -0,0 +1,1360 @@ +//! Real MCP transport behavior over in-memory duplex streams. +//! +//! Every test drives the official `rmcp` server lifecycle through +//! `RustScriptToolServer::serve_with_shutdown`, so initialization, framing, +//! `tools/list`, `tools/call`, notifications, and EOF are exercised on the +//! same code path as the packaged stdio binary. + +use std::fs; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::Duration; + +use rustscript_agent::mcp::ToolProfile; +use rustscript_agent::mcp::catalog; +use rustscript_agent::mcp::executor::{ + McpToolExecutor, McpToolExecutorConfig, McpToolExecutorError, +}; +use rustscript_agent::mcp::result; +use rustscript_agent::mcp::server::{ + ERROR_CODE_DATA_KEY, REPLAY_DATA_KEY, RETAINED_ERROR_CODE, RustScriptToolServer, SERVER_NAME, + TERMINAL_DATA_KEY, ToolServerOutcome, ToolServerQuit, executor_error_to_mcp_error, +}; +use serde_json::{Value, json}; +use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, DuplexStream, ReadHalf, WriteHalf}; +use tokio::task::JoinHandle; + +static NEXT_FIXTURE: AtomicU64 = AtomicU64::new(0); + +struct Fixture { + parent: PathBuf, + root: PathBuf, +} + +impl Fixture { + fn new(label: &str) -> Self { + let sequence = NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed); + let base = std::env::var_os("RUSTSCRIPT_AGENT_TEST_TMP") + .map(PathBuf::from) + .unwrap_or_else(std::env::temp_dir); + let parent = base.join(format!( + "mcp-server-{label}-{}-{sequence}", + std::process::id() + )); + let root = parent.join("workspace"); + fs::create_dir_all(&root).expect("create mcp server fixture"); + Self { parent, root } + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.parent); + } +} + +fn executor(root: &PathBuf) -> Arc { + Arc::new( + McpToolExecutor::new(McpToolExecutorConfig::new(root)) + .unwrap_or_else(|error| panic!("construct standalone executor: {error}")), + ) +} + +fn read_only_executor(root: &PathBuf) -> Arc { + Arc::new( + McpToolExecutor::new(McpToolExecutorConfig::new(root).with_profile(ToolProfile::ReadOnly)) + .unwrap_or_else(|error| panic!("construct read-only executor: {error}")), + ) +} + +struct Client { + reader: BufReader>, + writer: WriteHalf, + next_id: i64, + buffered: Vec, +} + +impl Client { + fn new(stream: DuplexStream) -> Self { + let (reader, writer) = tokio::io::split(stream); + Self { + reader: BufReader::new(reader), + writer, + next_id: 1, + buffered: Vec::new(), + } + } + + async fn send(&mut self, message: Value) { + let mut line = serde_json::to_vec(&message).expect("serialize client message"); + line.push(b'\n'); + self.writer + .write_all(&line) + .await + .expect("write client message"); + self.writer.flush().await.expect("flush client message"); + } + + async fn send_raw(&mut self, line: &str) { + self.writer + .write_all(line.as_bytes()) + .await + .expect("write raw client bytes"); + self.writer.flush().await.expect("flush raw client bytes"); + } + + async fn next_message(&mut self) -> Option { + let mut line = String::new(); + let read = tokio::time::timeout(Duration::from_secs(10), self.reader.read_line(&mut line)) + .await + .ok()? + .ok()?; + if read == 0 { + return None; + } + Some(serde_json::from_str(line.trim_end()).expect("server emitted non-JSON stdout")) + } + + async fn next_message_within(&mut self, timeout: Duration) -> Option { + let mut line = String::new(); + let read = tokio::time::timeout(timeout, self.reader.read_line(&mut line)) + .await + .ok()? + .ok()?; + if read == 0 { + return None; + } + Some(serde_json::from_str(line.trim_end()).expect("server emitted non-JSON stdout")) + } + + fn allocate_id(&mut self) -> i64 { + let id = self.next_id; + self.next_id += 1; + id + } + + async fn request(&mut self, method: &str, params: Value) -> Value { + let id = self.allocate_id(); + self.send(json!({ + "jsonrpc": "2.0", + "id": id, + "method": method, + "params": params, + })) + .await; + self.response_for(id).await + } + + async fn request_without_params(&mut self, method: &str) -> Value { + let id = self.allocate_id(); + self.send(json!({"jsonrpc": "2.0", "id": id, "method": method})) + .await; + self.response_for(id).await + } + + async fn notify(&mut self, method: &str, params: Value) { + self.send(json!({"jsonrpc": "2.0", "method": method, "params": params})) + .await; + } + + async fn response_for(&mut self, id: i64) -> Value { + if let Some(position) = self + .buffered + .iter() + .position(|message| message.get("id") == Some(&json!(id))) + { + return self.buffered.remove(position); + } + loop { + let message = self + .next_message() + .await + .unwrap_or_else(|| panic!("server closed before responding to id {id}")); + if message.get("id") == Some(&json!(id)) { + return message; + } + self.buffered.push(message); + } + } + + async fn initialize(&mut self) -> Value { + let response = self + .request( + "initialize", + json!({ + "protocolVersion": "2025-06-18", + "capabilities": {}, + "clientInfo": {"name": "mcp-tool-transport-tests", "version": "1"}, + }), + ) + .await; + self.notify("notifications/initialized", json!({})).await; + response + } +} + +struct RunningServer { + client: Client, + task: JoinHandle>, +} + +fn success_message(message: &Value) -> &Value { + message + .get("result") + .unwrap_or_else(|| panic!("expected a result, got {message}")) +} + +fn error_message(message: &Value) -> &Value { + message + .get("error") + .unwrap_or_else(|| panic!("expected an error, got {message}")) +} + +fn tool_result(message: &Value) -> &Value { + let result = success_message(message); + assert!( + result.get("isError").is_some(), + "tools/call must return a CallToolResult: {message}" + ); + result +} + +fn tool_text(result: &Value) -> String { + result["content"] + .as_array() + .expect("content blocks") + .iter() + .filter_map(|block| block.get("text").and_then(Value::as_str)) + .collect::>() + .join("\n") +} + +fn error_code_of(result: &Value) -> Option<&str> { + result["_meta"][result::ERROR_CODE_META_KEY].as_str() +} + +// The helper above is intentionally explicit: the server side of a duplex +// pair is split into independent read and write halves, and the client keeps +// the other half of the same pair. +async fn serve_pair(server: RustScriptToolServer) -> RunningServer { + let (server_io, client_io) = tokio::io::duplex(64 * 1024); + let (server_reader, server_writer) = tokio::io::split(server_io); + let client = Client::new(client_io); + let task = tokio::spawn(server.serve_with_shutdown(server_reader, server_writer, None)); + RunningServer { client, task } +} + +/// Test-only hold at the executor's pre-admission observation point. +#[cfg(feature = "workspace-io-fault")] +#[derive(Default)] +struct PreAdmissionGate { + state: std::sync::Mutex<(bool, bool)>, + changed: std::sync::Condvar, +} + +#[cfg(feature = "workspace-io-fault")] +impl PreAdmissionGate { + fn mark_started(&self) { + let mut state = self + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + state.0 = true; + self.changed.notify_all(); + } + + fn started(&self) -> bool { + self.state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .0 + } + + fn wait_released(&self) { + let mut state = self + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + while !state.1 { + state = self + .changed + .wait(state) + .unwrap_or_else(|poisoned| poisoned.into_inner()); + } + } + + fn release(&self) { + let mut state = self + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + state.1 = true; + self.changed.notify_all(); + } +} + +#[tokio::test] +async fn initialize_negotiates_the_protocol_and_advertises_only_tools() { + let fixture = Fixture::new("initialize"); + let server = RustScriptToolServer::from_executor(executor(&fixture.root)).expect("server"); + let mut running = serve_pair(server).await; + + let response = running.client.initialize().await; + let result = success_message(&response); + + assert_eq!(result["protocolVersion"], json!("2025-06-18")); + assert_eq!(result["capabilities"], json!({"tools": {}})); + assert_eq!(result["serverInfo"]["name"], json!(SERVER_NAME)); + assert_eq!( + result["serverInfo"]["version"], + json!(env!("CARGO_PKG_VERSION")) + ); + assert!( + result["capabilities"].get("resources").is_none(), + "the tool server must not advertise resources: {result}" + ); + assert!( + result["capabilities"].get("prompts").is_none(), + "the tool server must not advertise prompts: {result}" + ); + + drop(running.client); + let outcome = tokio::time::timeout(Duration::from_secs(10), running.task) + .await + .expect("server exited on EOF") + .expect("server task"); + let outcome = outcome.expect("clean serve"); + assert_eq!(outcome.quit, ToolServerQuit::Closed); + assert!(outcome.cleanup.is_clean(), "outcome={outcome:?}"); +} + +#[tokio::test] +async fn tools_list_matches_the_admitted_registry_catalog_exactly() { + let fixture = Fixture::new("list"); + let executor = executor(&fixture.root); + let expected = catalog::catalog_from_registry(executor.registry(), executor.profile()) + .expect("catalog from executor"); + let server = RustScriptToolServer::from_executor(Arc::clone(&executor)).expect("server"); + let mut running = serve_pair(server).await; + running.client.initialize().await; + + let response = running.client.request("tools/list", json!({})).await; + let tools = success_message(&response)["tools"] + .as_array() + .expect("tools array") + .clone(); + assert_eq!(tools.len(), expected.len()); + for (wire, expected) in tools.iter().zip(expected.iter()) { + assert_eq!( + wire, + &serde_json::to_value(expected).expect("serialize expected tool"), + "tools/list must copy the descriptor exactly" + ); + } + + let names: Vec<&str> = tools + .iter() + .map(|tool| tool["name"].as_str().expect("tool name")) + .collect(); + assert_eq!( + names, + vec![ + "read_file", + "search_files", + "write_file", + "patch", + "terminal", + "process" + ] + ); + + let read_file = &tools[0]; + assert_eq!(read_file["annotations"]["readOnlyHint"], json!(true)); + assert_eq!(read_file["annotations"]["openWorldHint"], json!(false)); + assert_eq!(read_file["_meta"][catalog::RISK_META_KEY], json!("read")); + assert_eq!( + read_file["_meta"][catalog::TOOLSET_META_KEY], + json!("coding") + ); + assert_eq!( + read_file["inputSchema"], + executor + .registry() + .descriptor("read_file") + .expect("read_file descriptor") + .schema + ); + + let terminal = tools + .iter() + .find(|tool| tool["name"] == json!("terminal")) + .expect("terminal tool"); + assert_eq!(terminal["annotations"]["openWorldHint"], json!(true)); + assert_eq!(terminal["annotations"]["readOnlyHint"], json!(false)); + + drop(running.client); + let _ = tokio::time::timeout(Duration::from_secs(10), running.task).await; +} + +#[tokio::test] +async fn read_only_profile_lists_only_its_read_risk_tools() { + let fixture = Fixture::new("read-only-list"); + let server = + RustScriptToolServer::from_executor(read_only_executor(&fixture.root)).expect("server"); + let mut running = serve_pair(server).await; + running.client.initialize().await; + + let response = running.client.request("tools/list", json!({})).await; + let names: Vec = success_message(&response)["tools"] + .as_array() + .expect("tools array") + .iter() + .map(|tool| tool["name"].as_str().expect("tool name").to_string()) + .collect(); + assert_eq!( + names, + vec!["read_file".to_string(), "search_files".to_string()] + ); + + drop(running.client); + let _ = tokio::time::timeout(Duration::from_secs(10), running.task).await; +} + +#[tokio::test] +async fn tools_call_read_file_round_trips_the_canonical_result() { + let fixture = Fixture::new("read-call"); + fs::write(fixture.root.join("hello.txt"), "hello\n").expect("write fixture file"); + let server = RustScriptToolServer::from_executor(executor(&fixture.root)).expect("server"); + let mut running = serve_pair(server).await; + running.client.initialize().await; + + let response = running + .client + .request( + "tools/call", + json!({"name": "read_file", "arguments": {"path": "hello.txt"}}), + ) + .await; + let result = tool_result(&response); + + assert_eq!(result["isError"], json!(false)); + assert_eq!(tool_text(result), "hello\n"); + assert_eq!( + result["structuredContent"], + json!({"offset": 1, "line_count": 1}) + ); + assert_eq!(result["_meta"][result::TRUNCATED_META_KEY], json!(false)); + assert_eq!(result["_meta"][result::ARTIFACTS_META_KEY], json!([])); + + drop(running.client); + let _ = tokio::time::timeout(Duration::from_secs(10), running.task).await; +} + +#[tokio::test] +async fn coding_profile_writes_and_patches_workspace_files() { + let fixture = Fixture::new("write-patch"); + let server = RustScriptToolServer::from_executor(executor(&fixture.root)).expect("server"); + let mut running = serve_pair(server).await; + running.client.initialize().await; + + let write = running + .client + .request( + "tools/call", + json!({"name": "write_file", "arguments": {"path": "notes.txt", "content": "one\n"}}), + ) + .await; + assert_eq!(tool_result(&write)["isError"], json!(false)); + assert_eq!( + fs::read_to_string(fixture.root.join("notes.txt")).expect("written file"), + "one\n" + ); + + let patch = running + .client + .request( + "tools/call", + json!({ + "name": "patch", + "arguments": {"path": "notes.txt", "old_string": "one\n", "new_string": "two\n"} + }), + ) + .await; + assert_eq!(tool_result(&patch)["isError"], json!(false)); + assert_eq!( + fs::read_to_string(fixture.root.join("notes.txt")).expect("patched file"), + "two\n" + ); + + drop(running.client); + let outcome = tokio::time::timeout(Duration::from_secs(10), running.task) + .await + .expect("server exited on EOF") + .expect("server task") + .expect("clean serve"); + assert!(outcome.cleanup.is_clean(), "outcome={outcome:?}"); +} + +#[tokio::test] +async fn terminal_and_process_preserve_the_owned_handle_lifecycle() { + let fixture = Fixture::new("process-lifecycle"); + let executor = executor(&fixture.root); + let server = RustScriptToolServer::from_executor(Arc::clone(&executor)).expect("server"); + let mut running = serve_pair(server).await; + running.client.initialize().await; + + let spawn = running + .client + .request( + "tools/call", + json!({ + "name": "terminal", + "arguments": { + "argv": ["/bin/sh", "-c", "printf process-ready"], + "background": true + } + }), + ) + .await; + let spawn = tool_result(&spawn); + assert_eq!(spawn["isError"], json!(false)); + assert_eq!(spawn["structuredContent"]["background"], json!(true)); + let process_id = spawn["structuredContent"]["process_id"] + .as_str() + .expect("background terminal returns a process id") + .to_string(); + assert_eq!(executor.process_table_len(), 1); + + let wait = running + .client + .request( + "tools/call", + json!({ + "name": "process", + "arguments": {"action": "wait", "process_id": process_id, "timeout_ms": 3000} + }), + ) + .await; + let wait = tool_result(&wait); + assert_eq!(wait["isError"], json!(false)); + assert!( + tool_text(wait).contains("process-ready"), + "wait content={:?}", + tool_text(wait) + ); + + let kill = running + .client + .request( + "tools/call", + json!({ + "name": "process", + "arguments": {"action": "kill", "process_id": process_id} + }), + ) + .await; + assert_eq!(tool_result(&kill)["isError"], json!(false)); + + drop(running.client); + let outcome = tokio::time::timeout(Duration::from_secs(10), running.task) + .await + .expect("server exited on EOF") + .expect("server task") + .expect("clean serve"); + assert!(outcome.cleanup.is_clean(), "outcome={outcome:?}"); + assert!(executor.is_closed()); +} + +#[tokio::test] +async fn read_only_profile_rejects_write_and_execute_before_any_effect() { + let fixture = Fixture::new("read-only-refusal"); + let executor = read_only_executor(&fixture.root); + let server = RustScriptToolServer::from_executor(Arc::clone(&executor)).expect("server"); + let mut running = serve_pair(server).await; + running.client.initialize().await; + + let write = running + .client + .request( + "tools/call", + json!({"name": "write_file", "arguments": {"path": "blocked.txt", "content": "nope\n"}}), + ) + .await; + let write = error_message(&write); + assert_eq!(write["code"], json!(-32602)); + assert_eq!(write["data"][ERROR_CODE_DATA_KEY], json!("disabled_tool")); + assert_eq!(write["data"][TERMINAL_DATA_KEY], json!(true)); + assert!(!fixture.root.join("blocked.txt").exists()); + + let terminal = running + .client + .request( + "tools/call", + json!({"name": "terminal", "arguments": {"argv": ["/bin/true"]}}), + ) + .await; + let terminal = error_message(&terminal); + assert_eq!( + terminal["data"][ERROR_CODE_DATA_KEY], + json!("disabled_tool") + ); + + assert_eq!(executor.admitted_call_count(), 0); + assert_eq!(executor.process_table_len(), 0); + + drop(running.client); + let _ = tokio::time::timeout(Duration::from_secs(10), running.task).await; +} + +#[tokio::test] +async fn path_escape_and_disallowed_process_cwd_fail_with_typed_tool_errors() { + let fixture = Fixture::new("path-escape"); + fs::write( + fixture.parent.join("outside-secret.txt"), + "outside-secret\n", + ) + .expect("write outside fixture"); + let server = RustScriptToolServer::from_executor(executor(&fixture.root)).expect("server"); + let mut running = serve_pair(server).await; + running.client.initialize().await; + + let read = running + .client + .request( + "tools/call", + json!({"name": "read_file", "arguments": {"path": "../outside-secret.txt"}}), + ) + .await; + let read = tool_result(&read); + assert_eq!(read["isError"], json!(true)); + assert_eq!(error_code_of(read), Some("path_denied")); + assert!(!tool_text(read).contains("outside-secret")); + + let terminal = running + .client + .request( + "tools/call", + json!({"name": "terminal", "arguments": {"argv": ["/bin/true"], "cwd": "../"}}), + ) + .await; + let terminal = tool_result(&terminal); + assert_eq!(terminal["isError"], json!(true)); + assert_eq!(error_code_of(terminal), Some("invalid_cwd")); + + drop(running.client); + let _ = tokio::time::timeout(Duration::from_secs(10), running.task).await; +} + +#[tokio::test] +async fn malformed_messages_are_bounded_and_do_not_kill_the_session() { + let fixture = Fixture::new("malformed"); + let server = RustScriptToolServer::from_executor(executor(&fixture.root)).expect("server"); + let mut running = serve_pair(server).await; + running.client.initialize().await; + + // Invalid JSON syntax is ignored by the official transport. + running.client.send_raw("this is not json\n").await; + let ping = running.client.request_without_params("ping").await; + assert_eq!(success_message(&ping), &json!({})); + + // Well-formed JSON that is not a valid JSON-RPC request receives the + // protocol Invalid Request error with a null id and the session survives. + running + .client + .send(json!({"jsonrpc": "2.0", "id": 90, "method": 3})) + .await; + let invalid = running + .client + .next_message() + .await + .expect("invalid request response"); + assert_eq!(error_message(&invalid)["code"], json!(-32600)); + assert_eq!(invalid["id"], Value::Null); + + let ping = running.client.request_without_params("ping").await; + assert_eq!(success_message(&ping), &json!({})); + + drop(running.client); + let _ = tokio::time::timeout(Duration::from_secs(10), running.task).await; +} + +#[tokio::test] +async fn cancelled_notification_stops_the_running_call_and_keeps_the_session_alive() { + let fixture = Fixture::new("cancel"); + let executor = executor(&fixture.root); + let server = RustScriptToolServer::from_executor(Arc::clone(&executor)).expect("server"); + let mut running = serve_pair(server).await; + running.client.initialize().await; + + let id = running.client.allocate_id(); + running + .client + .send(json!({ + "jsonrpc": "2.0", + "id": id, + "method": "tools/call", + "params": { + "name": "terminal", + "arguments": { + "argv": ["/bin/sh", "-c", "sleep 30; printf done > cancelled-marker.txt"] + } + } + })) + .await; + + let admitted = tokio::time::timeout(Duration::from_secs(5), async { + loop { + if executor.admitted_call_count() == 1 { + return; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await; + assert!(admitted.is_ok(), "the call was never admitted"); + + running + .client + .notify( + "notifications/cancelled", + json!({"requestId": id, "reason": "test cancellation"}), + ) + .await; + + let stopped = tokio::time::timeout(Duration::from_secs(8), async { + loop { + if executor.process_table_len() == 0 && executor.open_token_count() == 0 { + return; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await; + assert!(stopped.is_ok(), "cancellation did not stop the owned child"); + + // The SDK drops the response for a cancelled request; nothing else is sent. + assert!( + running + .client + .next_message_within(Duration::from_millis(500)) + .await + .is_none(), + "a cancelled call must not emit a late response" + ); + assert!(!fixture.root.join("cancelled-marker.txt").exists()); + + let ping = running.client.request_without_params("ping").await; + assert_eq!(success_message(&ping), &json!({})); + + drop(running.client); + let outcome = tokio::time::timeout(Duration::from_secs(10), running.task) + .await + .expect("server exited on EOF") + .expect("server task") + .expect("clean serve"); + assert!(outcome.cleanup.is_clean(), "outcome={outcome:?}"); +} + +/// A cancellation that arrives while the worker is still queued must be +/// recorded at the executor before admission, so releasing the worker cannot +/// execute the effect and then have the SDK silently suppress the reply. +#[cfg(feature = "workspace-io-fault")] +#[tokio::test] +async fn cancellation_before_admission_is_durable_and_prevents_the_effect() { + let fixture = Fixture::new("cancel-before-admission"); + let executor = executor(&fixture.root); + let gate = Arc::new(PreAdmissionGate::default()); + let observed = Arc::clone(&gate); + executor.set_pre_admission_observer_for_test(Arc::new(move |call_id: &str| { + if call_id.starts_with("mcp-call-") { + observed.mark_started(); + observed.wait_released(); + } + })); + let server = RustScriptToolServer::from_executor(Arc::clone(&executor)) + .expect("server") + .with_cancel_grace_for_test(Duration::from_millis(100)); + let server_handle = server.clone(); + let mut running = serve_pair(server).await; + running.client.initialize().await; + + let id = running.client.allocate_id(); + running + .client + .send(json!({ + "jsonrpc": "2.0", + "id": id, + "method": "tools/call", + "params": { + "name": "write_file", + "arguments": { + "path": "cancelled-before-admission.txt", + "content": "leaked\n" + } + } + })) + .await; + tokio::time::timeout(Duration::from_secs(10), async { + while !gate.started() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("the worker reached the pre-admission hold"); + + running + .client + .notify( + "notifications/cancelled", + json!({"requestId": id, "reason": "pre-admission cancellation"}), + ) + .await; + // The handler must record the cancellation while the worker is held. + tokio::time::timeout(Duration::from_secs(5), async { + while executor.pending_pre_admission_cancellations_for_test() == 0 { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("the cancellation must be recorded before the worker is released"); + // The worker is still held. The handler must exhaust its (test-shortened) + // grace and answer with the synthetic cancellation without releasing it. + tokio::time::timeout(Duration::from_secs(5), async { + while server_handle.cancelled_after_grace_for_test() == 0 { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("the handler's grace must expire while the worker is still held"); + assert_eq!( + server_handle.cancelled_after_grace_for_test(), + 1, + "exactly one handler must take the grace-timeout path" + ); + assert!( + running + .client + .next_message_within(Duration::from_millis(200)) + .await + .is_none(), + "the expired handler must not emit a late response" + ); + gate.release(); + + assert!( + running + .client + .next_message_within(Duration::from_millis(1000)) + .await + .is_none(), + "a cancelled call must not emit a late response" + ); + // Give a silently admitted worker time to publish its effect, so the + // no-effect assertion below is meaningful rather than a timing artifact. + tokio::time::sleep(Duration::from_secs(2)).await; + assert!( + !fixture.root.join("cancelled-before-admission.txt").exists(), + "a call cancelled before admission must not create a file" + ); + assert_eq!( + executor.admitted_call_count(), + 0, + "the cancelled call must be refused at admission, not silently executed" + ); + assert_eq!( + executor.pending_pre_admission_cancellations_for_test(), + 0, + "admission consumes the recorded cancellation" + ); + + // The admitted refusal is typed as cancelled, not a dropped success. + assert!(executor.cancel_call("pre-admission-direct")); + let direct = executor + .execute_tool( + Some("pre-admission-direct"), + "write_file", + &json!({"path": "direct-cancelled.txt", "content": "leaked\n"}), + ) + .expect_err("a recorded pre-admission cancellation must refuse the call"); + assert!( + matches!( + direct, + McpToolExecutorError::Cancelled { ref call_id } if call_id == "pre-admission-direct" + ), + "error={direct:?}" + ); + assert!(!fixture.root.join("direct-cancelled.txt").exists()); + + drop(running.client); + let outcome = tokio::time::timeout(Duration::from_secs(10), running.task) + .await + .expect("server exited on EOF") + .expect("server task") + .expect("clean serve"); + assert!(outcome.cleanup.is_clean(), "outcome={outcome:?}"); +} + +#[tokio::test] +async fn concurrent_calls_keep_independent_state_and_respect_the_call_quota() { + let fixture = Fixture::new("concurrent"); + let executor = executor(&fixture.root); + let server = RustScriptToolServer::from_executor(Arc::clone(&executor)).expect("server"); + let mut running = serve_pair(server).await; + running.client.initialize().await; + + let first_id = running.client.allocate_id(); + let second_id = running.client.allocate_id(); + for (id, path, content) in [ + (first_id, "first.txt", "first\n"), + (second_id, "second.txt", "second\n"), + ] { + running + .client + .send(json!({ + "jsonrpc": "2.0", + "id": id, + "method": "tools/call", + "params": {"name": "write_file", "arguments": {"path": path, "content": content}} + })) + .await; + } + for id in [first_id, second_id] { + let response = running.client.response_for(id).await; + assert_eq!(tool_result(&response)["isError"], json!(false)); + } + assert_eq!( + fs::read_to_string(fixture.root.join("first.txt")).expect("first file"), + "first\n" + ); + assert_eq!( + fs::read_to_string(fixture.root.join("second.txt")).expect("second file"), + "second\n" + ); + + drop(running.client); + let _ = tokio::time::timeout(Duration::from_secs(10), running.task).await; + + // A separate server with a two-call lifetime quota admits exactly two of + // three concurrent calls; the refusal is a typed protocol error. + let fixture = Fixture::new("quota"); + fs::write(fixture.root.join("hello.txt"), "hello\n").expect("hello"); + let quota = Arc::new( + McpToolExecutor::new(McpToolExecutorConfig::new(&fixture.root).with_max_tool_calls(2)) + .expect("quota executor"), + ); + let server = RustScriptToolServer::from_executor(Arc::clone("a)).expect("server"); + let mut running = serve_pair(server).await; + running.client.initialize().await; + + let ids: Vec = (0..3).map(|_| running.client.allocate_id()).collect(); + for id in &ids { + running + .client + .send(json!({ + "jsonrpc": "2.0", + "id": id, + "method": "tools/call", + "params": {"name": "read_file", "arguments": {"path": "hello.txt"}} + })) + .await; + } + let mut succeeded = 0; + let mut refused = 0; + for id in ids { + let response = running.client.response_for(id).await; + if let Some(error) = response.get("error") { + assert_eq!( + error["data"][ERROR_CODE_DATA_KEY], + json!("call_quota_exhausted") + ); + refused += 1; + } else { + assert_eq!(tool_result(&response)["isError"], json!(false)); + succeeded += 1; + } + } + assert_eq!((succeeded, refused), (2, 1)); + + drop(running.client); + let _ = tokio::time::timeout(Duration::from_secs(10), running.task).await; +} + +#[tokio::test] +async fn closing_the_transport_cancels_running_calls_and_reports_clean_cleanup() { + let fixture = Fixture::new("eof-cleanup"); + let executor = executor(&fixture.root); + let server = RustScriptToolServer::from_executor(Arc::clone(&executor)).expect("server"); + let mut running = serve_pair(server).await; + running.client.initialize().await; + + let id = running.client.allocate_id(); + running + .client + .send(json!({ + "jsonrpc": "2.0", + "id": id, + "method": "tools/call", + "params": { + "name": "terminal", + "arguments": { + "argv": ["/bin/sh", "-c", "sleep 30; printf done > eof-marker.txt"] + } + } + })) + .await; + tokio::time::timeout(Duration::from_secs(5), async { + loop { + if executor.admitted_call_count() == 1 { + return; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("call admitted"); + + drop(running.client); + let outcome = tokio::time::timeout(Duration::from_secs(12), running.task) + .await + .expect("EOF shutdown is bounded") + .expect("server task") + .expect("clean serve"); + + assert_eq!(outcome.quit, ToolServerQuit::Closed); + assert!(outcome.cleanup.is_clean(), "outcome={outcome:?}"); + assert!(executor.is_closed()); + assert_eq!(executor.process_table_len(), 0); + assert!(!fixture.root.join("eof-marker.txt").exists()); +} + +#[tokio::test] +async fn executor_lifetime_bounds_the_server_without_peer_eof() { + let fixture = Fixture::new("lifetime"); + let server = RustScriptToolServer::new( + McpToolExecutorConfig::new(&fixture.root).with_server_lifetime(Duration::from_millis(400)), + ) + .expect("server"); + let mut running = serve_pair(server).await; + running.client.initialize().await; + + let outcome = tokio::time::timeout(Duration::from_secs(10), running.task) + .await + .expect("lifetime shutdown is bounded") + .expect("server task") + .expect("clean serve"); + assert_eq!(outcome.quit, ToolServerQuit::LifetimeElapsed); + assert!(outcome.cleanup.is_clean(), "outcome={outcome:?}"); +} + +#[test] +fn retained_executor_error_is_nonterminal_and_forbids_replay() { + let error = McpToolExecutorError::Retained { + call_id: "call-retained".to_string(), + }; + let wire = executor_error_to_mcp_error(&error); + + assert_eq!(wire.code.0, RETAINED_ERROR_CODE); + assert_eq!( + wire.data.as_ref().expect("typed data")[ERROR_CODE_DATA_KEY], + json!("retained") + ); + assert_eq!( + wire.data.as_ref().expect("typed data")[TERMINAL_DATA_KEY], + json!(false), + "retention must not be presented as a terminal tool failure" + ); + assert_eq!( + wire.data.as_ref().expect("typed data")[REPLAY_DATA_KEY], + json!(false), + "retention must never be replayed" + ); + assert_eq!( + wire.data.as_ref().expect("typed data")["call_id"], + json!("call-retained") + ); + assert!(wire.message.contains("retained")); +} + +#[tokio::test] +async fn reused_request_ids_do_not_collide_in_the_executor_ledger() { + let fixture = Fixture::new("reused-id"); + fs::write(fixture.root.join("hello.txt"), "hello\n").expect("hello"); + let server = RustScriptToolServer::from_executor(executor(&fixture.root)).expect("server"); + let mut running = serve_pair(server).await; + running.client.initialize().await; + + // JSON-RPC ids are unique only among in-flight requests. The server must + // accept the same id again after the first response. + for _ in 0..2 { + running + .client + .send(json!({ + "jsonrpc": "2.0", + "id": 7, + "method": "tools/call", + "params": {"name": "read_file", "arguments": {"path": "hello.txt"}} + })) + .await; + let response = running.client.response_for(7).await; + assert_eq!(tool_text(tool_result(&response)), "hello\n"); + } + + drop(running.client); + let _ = tokio::time::timeout(Duration::from_secs(10), running.task).await; +} + +#[test] +fn tool_server_errors_are_typed_and_bounded() { + let error = RustScriptToolServer::new(McpToolExecutorConfig::new("relative/workspace")) + .err() + .expect("relative workspace rejected"); + assert_eq!(error.code(), "tools_workspace_not_absolute"); + + let missing = Fixture::new("missing-workspace").parent.join("not-there"); + let error = RustScriptToolServer::new(McpToolExecutorConfig::new(&missing)) + .err() + .expect("missing workspace rejected"); + assert_eq!(error.code(), "tools_workspace_unresolvable"); + + let file = Fixture::new("file-workspace"); + let path = file.parent.join("workspace-file.txt"); + fs::write(&path, "not a directory").expect("workspace file"); + let error = RustScriptToolServer::new(McpToolExecutorConfig::new(&path)) + .err() + .expect("file workspace rejected"); + assert_eq!(error.code(), "tools_workspace_not_directory"); + + let fixture = Fixture::new("bad-config"); + let error = + RustScriptToolServer::new(McpToolExecutorConfig::new(&fixture.root).with_max_tool_calls(0)) + .err() + .expect("invalid bounds rejected"); + assert_eq!(error.code(), "tools_config_invalid"); + assert!( + error.message().expect("config message").len() <= 512, + "diagnostics are bounded: {error:?}" + ); +} + +/// A tools/call that was already dispatched into the blocking pool, but is +/// still held before admission, must be refused when the terminal overflow +/// latch closes. The worker is released only after the latch, while the async +/// runtime is deliberately blocked so the watchdog's teardown cannot close +/// admission first: the refusal can only come from admission's own gate check. +#[cfg(feature = "workspace-io-fault")] +#[tokio::test] +async fn terminal_overflow_refuses_a_worker_held_before_admission() { + let fixture = Fixture::new("overflow-held-admission"); + let executor = executor(&fixture.root); + let gate = Arc::new(PreAdmissionGate::default()); + executor.set_pre_admission_observer_for_test(Arc::new({ + let gate = Arc::clone(&gate); + move |_| { + gate.mark_started(); + gate.wait_released(); + } + })); + let server = RustScriptToolServer::from_executor(Arc::clone(&executor)).expect("server"); + let observer = server.clone(); + let mut running = serve_pair(server).await; + running.client.initialize().await; + + let id = running.client.next_id; + running.client.next_id += 1; + running + .client + .send(json!({ + "jsonrpc": "2.0", + "id": id, + "method": "tools/call", + "params": { + "name": "write_file", + "arguments": {"path": "overflow-held.txt", "content": "leaked\n"} + } + })) + .await; + + let started_deadline = tokio::time::Instant::now() + Duration::from_secs(20); + while !gate.started() { + assert!( + tokio::time::Instant::now() < started_deadline, + "the call never reached the pre-admission hold" + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } + + // Close the terminal input latch exactly as a reader-queue overflow does. + observer.terminate_input_for_test(); + gate.release(); + // Block the only async worker so the watchdog cannot run: on the old + // behavior the released worker would admit and publish the write. + std::thread::sleep(Duration::from_millis(1500)); + + assert_eq!( + executor.admitted_call_count(), + 0, + "a queued call must be refused by admission's terminal gate" + ); + assert!( + !fixture.root.join("overflow-held.txt").exists(), + "a refused queued call must not publish an effect" + ); + + drop(running.client); + let outcome = tokio::time::timeout(Duration::from_secs(15), running.task) + .await + .expect("terminal input must start bounded cleanup") + .expect("serve task") + .expect("clean serve"); + assert_eq!( + outcome.quit, + ToolServerQuit::InputTerminated, + "outcome={outcome:?}" + ); +} + +/// A full reader queue is terminal for protocol input. +/// +/// The pump must not discard the overflow chunk and then resume forwarding: +/// a parser that lost an arbitrary chunk can drop a cancellation or accept a +/// spliced request. Once the queue overflows, no later byte may reach the +/// parser, new calls must be refused, and bounded cleanup must start. +#[cfg(feature = "workspace-io-fault")] +#[tokio::test] +async fn reader_queue_overflow_is_terminal_and_refuses_later_input() { + use std::pin::Pin; + use std::task::{Context as TaskContext, Poll}; + + use tokio::io::AsyncWrite; + + /// Accepts a few bytes of the initialize response, then stalls forever. + /// rmcp blocks in `send`, so it never drains the reader pump. + struct StalledWriter { + written: usize, + } + + impl AsyncWrite for StalledWriter { + fn poll_write( + mut self: Pin<&mut Self>, + _context: &mut TaskContext<'_>, + buffer: &[u8], + ) -> Poll> { + if self.written >= 8 { + return Poll::Pending; + } + let take = buffer.len().min(8 - self.written); + self.written += take; + Poll::Ready(Ok(take)) + } + + fn poll_flush( + self: Pin<&mut Self>, + _context: &mut TaskContext<'_>, + ) -> Poll> { + Poll::Ready(Ok(())) + } + + fn poll_shutdown( + self: Pin<&mut Self>, + _context: &mut TaskContext<'_>, + ) -> Poll> { + Poll::Ready(Ok(())) + } + } + + let fixture = Fixture::new("input-overflow"); + let executor = executor(&fixture.root); + let server = RustScriptToolServer::from_executor(Arc::clone(&executor)).expect("server"); + let observer = server.clone(); + let (server_io, mut client_io) = tokio::io::duplex(64 * 1024); + let task = + tokio::spawn(server.serve_with_shutdown(server_io, StalledWriter { written: 0 }, None)); + + let mut initialize = serde_json::to_vec(&json!({ + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2025-06-18", + "capabilities": {}, + "clientInfo": {"name": "overflow-test", "version": "1"} + } + })) + .expect("serialize initialize"); + initialize.push(b'\n'); + client_io + .write_all(&initialize) + .await + .expect("write initialize"); + + // Fill the pump's bounded pre-read queue while rmcp is blocked writing + // the initialize response into the stalled writer. Cleanup may start as + // soon as the latch is set; a closed peer then proves no later byte can + // reach the parser either. + let flood = vec![b'x'; 8 * 1024]; + for _ in 0..160 { + if observer.input_terminated_for_test() { + break; + } + match client_io.write_all(&flood).await { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::BrokenPipe => break, + Err(error) => panic!("write flood: {error:?}"), + } + } + tokio::time::timeout(Duration::from_secs(10), async { + while !observer.input_terminated_for_test() { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .expect("the reader queue overflow must latch the terminal input state"); + + // These bytes arrive after the overflow. A transport that resumed + // forwarding could act on the cancellation or the synthesized request. + let mut tail = serde_json::to_vec(&json!({ + "jsonrpc": "2.0", + "method": "notifications/cancelled", + "params": {"requestId": 2, "reason": "overflow"} + })) + .expect("serialize cancellation"); + tail.push(b'\n'); + tail.extend_from_slice( + &serde_json::to_vec(&json!({ + "jsonrpc": "2.0", + "id": 3, + "method": "tools/call", + "params": { + "name": "write_file", + "arguments": {"path": "overflow-request.txt", "content": "leaked\n"} + } + })) + .expect("serialize synthesized request"), + ); + tail.push(b'\n'); + // A broken pipe means cleanup already closed the peer, which is an even + // stronger proof that these bytes cannot be parsed. + let _ = client_io.write_all(&tail).await; + drop(client_io); + + let outcome = tokio::time::timeout(Duration::from_secs(15), task) + .await + .expect("terminal input must start bounded cleanup") + .expect("serve task") + .expect("clean serve"); + assert_eq!( + outcome.quit, + ToolServerQuit::InputTerminated, + "outcome={outcome:?}" + ); + assert_eq!( + executor.admitted_call_count(), + 0, + "a terminal transport must refuse new calls" + ); + assert!( + !fixture.root.join("overflow-request.txt").exists(), + "bytes after the overflow must never be forwarded to the parser" + ); +} diff --git a/tests/rss_process_tool_tests.rs b/tests/rss_process_tool_tests.rs index 536d21bf..1c0dc04d 100644 --- a/tests/rss_process_tool_tests.rs +++ b/tests/rss_process_tool_tests.rs @@ -1738,6 +1738,35 @@ fn overflow_tiny_threshold_matches_native() { assert_canonical_envelope(&rss.result); } +#[test] +fn overlapping_output_cap_keeps_the_full_receipt_bound_at_512_bytes() { + let fixture = Fixture::new("cap-512"); + let mut config = fixture.config(); + config.max_stream_bytes = 256; + config.max_output_bytes = 512; + let run = rss_terminal( + &fixture, + &config, + json!({"argv": ["/usr/bin/printf", "%s", "x".repeat(4000)]}), + ); + assert_canonical_envelope(&run.result); + let encoded = serde_json::to_vec(&run.result).expect("serialize 512-byte receipt"); + assert!( + encoded.len() <= 512, + "the canonical receipt must fit the configured cap ({} bytes): {}", + encoded.len(), + run.result + ); + assert_eq!(run.result["data"]["status"], json!("exited")); + assert_eq!(run.result["data"]["exit_code"], json!(0)); + assert_eq!( + run.result["artifacts"].as_array().map(Vec::len), + Some(1), + "the overflow artifact identity must survive at 512 bytes: {}", + run.result + ); +} + #[test] fn bounded_process_consumers_preserve_payload_canonical_result_and_quota_fallback() { for background in [false, true] { @@ -2101,7 +2130,7 @@ fn repeated_close_kill_forged_stale_and_signal_exits_match_native() { } #[test] -fn commit_failure_after_background_spawn_leaves_no_process_residue() { +fn commit_failure_after_background_spawn_retains_owned_child_for_cleanup() { let fixture = Fixture::new("commit-residue"); let config = fixture.config(); let clock = Arc::new(SystemClock); @@ -2160,9 +2189,14 @@ fn commit_failure_after_background_spawn_leaves_no_process_residue() { "commit must observe a live child from the process table" ); for pid in &pids { - wait_until_dead(*pid); + assert!( + pid_alive(*pid), + "a published spawn must not be rolled back by a commit-storage failure" + ); } - assert_eq!(processes.table_len(), 0); + // The published child stays owned by the run table and is reaped by the + // ordinary bounded cleanup rather than a retraction of the effect. + assert_eq!(processes.table_len(), 1); let replay = run_rss_exec( &fixture, &config, @@ -2183,9 +2217,21 @@ fn commit_failure_after_background_spawn_leaves_no_process_residue() { }, ); assert_eq!(error_code(&replay.result), "unresolved_call"); + spawn_pids_cleanup(&processes, &pids); assert_eq!(processes.table_len(), 0); } +fn spawn_pids_cleanup(processes: &ProcessCapability, pids: &[u32]) { + let proof = processes.shutdown_all_within(Instant::now() + Duration::from_secs(2)); + assert!( + proof.is_clean(), + "bounded cleanup must prove the retained child reaped: {proof:?}" + ); + for pid in pids { + wait_until_dead(*pid); + } +} + #[test] fn durable_replay_does_not_repeat_spawn_write_or_kill() { let fixture = Fixture::new("replay-matrix"); @@ -2200,7 +2246,7 @@ fn durable_replay_does_not_repeat_spawn_write_or_kill() { ..default_exec( "terminal.rss", "terminal", - json!({"argv": ["/bin/sleep", "8"], "background": true, "timeout_ms": 5000}), + json!({"argv": ["/bin/sleep", "8"], "background": true, "timeout_ms": 30000}), ) }, ); @@ -2220,7 +2266,7 @@ fn durable_replay_does_not_repeat_spawn_write_or_kill() { ..default_exec( "terminal.rss", "terminal", - json!({"argv": ["/bin/sleep", "8"], "background": true, "timeout_ms": 5000}), + json!({"argv": ["/bin/sleep", "8"], "background": true, "timeout_ms": 30000}), ) }, ); @@ -2309,13 +2355,11 @@ fn initial_stdin_epipe_from_fast_child_does_not_fail_terminal_spawn() { ); assert_ne!(error_code(&rss.result), "process_failed"); assert_ne!(error_code(&rss.result), "spawn_failed"); - let pid = rss - .processes - .live_pids() - .first() - .copied() - .expect("table pid"); - wait_until_dead(pid); + assert_eq!( + rss.processes.table_len(), + 0, + "iteration {i}: a completed foreground record must retire after its final snapshot" + ); } } @@ -2859,3 +2903,63 @@ fn terminal_enospc_is_a_failed_canonical_result_without_retry() { ); } } + +/// The managed/agent path must keep the historical `e9da5dc` overflow +/// envelope byte-for-byte. The expected string was produced by the same +/// dispatch shape against `e9da5dc:rss/tools/terminal.rss` and must not drift +/// with MCP receipt compaction. +#[test] +fn managed_overflow_envelope_is_byte_identical_to_base() { + let fixture = Fixture::new("managed-overflow-parity"); + let mut config = fixture.config(); + config.max_stream_bytes = 64; + config.max_output_bytes = 128; + let run = rss_terminal( + &fixture, + &config, + json!({"argv": ["/usr/bin/printf", "%s", "o".repeat(400)]}), + ); + let encoded = String::from_utf8(serde_json::to_vec(&run.result).expect("serialize result")) + .expect("JSON is UTF-8"); + assert_eq!( + encoded, + "{\"ok\":false,\"error\":{\"code\":\"output_truncated\",\"message\":\"bounded\"},\"truncated\":true,\"content\":\"\",\"artifacts\":[],\"data\":{}}", + "the managed overflow envelope must match the base bytes" + ); +} + +/// The process tool's own overflow helper must keep the same historical +/// `e9da5dc` bytes as the terminal helper on the managed path. +#[test] +fn managed_process_overflow_envelope_is_byte_identical_to_base() { + let fixture = Fixture::new("managed-process-overflow-parity"); + let mut spawn_config = fixture.config(); + spawn_config.max_stream_bytes = 64; + let spawn = rss_terminal( + &fixture, + &spawn_config, + json!({ + "argv": ["/usr/bin/printf", "%s", "o".repeat(400)], + "background": true + }), + ); + let process_id = spawn.result["data"]["process_id"] + .as_str() + .expect("background process id") + .to_string(); + let mut config = spawn_config; + config.max_output_bytes = 128; + let waited = rss_process( + &fixture, + &config, + &spawn, + json!({"action": "wait", "process_id": process_id, "timeout_ms": 2000}), + ); + let encoded = String::from_utf8(serde_json::to_vec(&waited.result).expect("serialize result")) + .expect("JSON is UTF-8"); + assert_eq!( + encoded, + "{\"ok\":false,\"error\":{\"code\":\"output_truncated\",\"message\":\"tool result exceeds the configured bound\"},\"truncated\":true,\"content\":\"\",\"artifacts\":[],\"data\":{}}", + "the managed process overflow envelope must match the base bytes" + ); +} diff --git a/tests/service_tests.rs b/tests/service_tests.rs index 9ad4f394..7e017067 100644 --- a/tests/service_tests.rs +++ b/tests/service_tests.rs @@ -3760,6 +3760,99 @@ async fn production_stop_recovers_open_capability_tokens() { let _ = std::fs::remove_dir_all(&workspace); } +#[tokio::test] +async fn production_stop_interrupts_a_published_capability_token_like_base() { + let path = temporary_db_path(); + let workspace = path.with_file_name(format!("ws-cap-published-{}", Uuid::new_v4())); + std::fs::create_dir_all(&workspace).expect("workspace"); + let state = AgentGatewayState::with_agent_source_and_sqlite( + AgentGatewayConfig::default(), + test_source(), + &path, + ) + .expect("SQLite gateway should open"); + let service = state.service(); + service + .set_run_limits(RunLimits::new(8, 8, 65_536, &workspace).expect("limits")) + .expect("set limits"); + let admitted = service + .admit(admit_request(None)) + .await + .expect("admit should succeed"); + let call = ToolCall { + id: "call-cap-published".to_string(), + name: "read_file".to_string(), + arguments: json!({"path": "unread.txt"}), + }; + commit_tool_parent(&service, &admitted.run_id, &call); + let (lifecycle, owner) = service + .capability_lifecycle(&admitted.run_id) + .expect("production lifecycle"); + let registry_identity = service.tool_registry_snapshot().identity().to_string(); + let token = match lifecycle + .prepare( + &owner, + PrepareMetadata { + run_id: admitted.run_id.clone(), + call_id: call.id.clone(), + tool_name: call.name.clone(), + argument_digest: "digest-cap-published".to_string(), + registry_identity, + risk_class: CapabilityRisk::Read, + summary: "published effect".to_string(), + }, + ) + .expect("prepare should issue a token") + { + PrepareOutcome::Execute { + execution_token, .. + } => execution_token, + other => panic!("expected execute, got {other:?}"), + }; + let artifacts = rustscript_agent::capabilities::ArtifactCapability::new( + lifecycle.as_ref().clone(), + owner.clone(), + rustscript_agent::capabilities::ArtifactLimits::default(), + ) + .expect("artifacts"); + let stored = artifacts + .put_result(&token, b"published artifact\n", &json!({})) + .expect("real published artifact"); + assert_eq!(stored.len, "published artifact\n".len()); + + assert_eq!(service.stop(&admitted.run_id).as_deref(), Some("stopping")); + let replayed = common::dispatch_rss(&service, &admitted.run_id, std::slice::from_ref(&call)) + .expect("stop recovery must dispatch"); + assert!( + !replayed[0].ok, + "the managed lifecycle must keep base abort semantics: {:?}", + replayed[0] + ); + assert_eq!( + replayed[0].error.as_ref().map(|error| error.code.as_str()), + Some("interrupted_effect"), + "base recovery interrupts even a token whose artifact crossed the fence: {:?}", + replayed[0] + ); + assert!( + replayed[0].artifacts.is_empty(), + "an interrupted receipt must not claim a settled artifact: {:?}", + replayed[0] + ); + assert!( + artifacts.stored(&stored.id).is_none(), + "the managed interrupt must retract the inserted artifact like base" + ); + assert_eq!( + artifacts.stored_len(), + 0, + "the interrupted result artifact must not stay visible" + ); + drop(state); + std::fs::remove_file(path).expect("temporary SQLite state should be removed"); + let _ = std::fs::remove_dir_all(&workspace); +} + fn cache_script(tag: &str) -> String { format!("pub fn run(context: map) -> map {{ {{status: \"completed\", output: \"{tag}\"}}; }}") } diff --git a/tests/tools_pin_invoke_tracer.rs b/tests/tools_pin_invoke_tracer.rs index 22640225..0be6f727 100644 --- a/tests/tools_pin_invoke_tracer.rs +++ b/tests/tools_pin_invoke_tracer.rs @@ -426,6 +426,7 @@ fn pinned_read_file_bytes_stay_on_program_a_after_activation_of_b() { processes: None, artifacts: None, control_hook: None, + commit_observer: None, pinned_tool: Some(pinned.program_handle()), allow_stateless_pin: false, }; @@ -636,6 +637,7 @@ fn pinned_handle_rejects_other_owner_without_started_effect() { processes: None, artifacts: None, control_hook: None, + commit_observer: None, pinned_tool: Some(pinned.program_handle()), allow_stateless_pin: false, }; @@ -692,6 +694,7 @@ fn pinned_handle_rejects_other_owner_without_started_effect() { processes: None, artifacts: None, control_hook: None, + commit_observer: None, pinned_tool: Some(pinned.program_handle()), allow_stateless_pin: false, }; @@ -1235,6 +1238,7 @@ fn invoke_pinned_text( processes: None, artifacts: None, control_hook: None, + commit_observer: None, pinned_tool: Some(pinned.program_handle()), allow_stateless_pin: false, }; @@ -1904,6 +1908,7 @@ impl NativeCase { processes: None, artifacts: None, control_hook: None, + commit_observer: None, pinned_tool: Some(self.pinned.program_handle()), allow_stateless_pin: false, }; @@ -1987,6 +1992,7 @@ impl NativeCase { processes: None, artifacts: None, control_hook: None, + commit_observer: None, pinned_tool: Some(self.pinned.program_handle()), allow_stateless_pin: false, }; @@ -2475,6 +2481,7 @@ fn phase_a_native_guard_honors_elapsed_original_deadline() { processes: None, artifacts: None, control_hook: None, + commit_observer: None, pinned_tool: Some(pinned.program_handle()), allow_stateless_pin: false, }; From 3e48b268329f1fbbd4ac0f60f91b0cae2dee243b Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 29 Nov 2026 01:27:19 +0800 Subject: [PATCH 03/14] feat(acp): proxy harness sessions and inject workspace MCP tools Forward ACP v1 over stdio and inject the workspace tool server without taking ownership of harness inference. Include SDK contract, lifecycle, and end-to-end coverage for the proxy and injection boundary. --- Cargo.lock | 1 + Cargo.toml | 1 + src/acp/config.rs | 110 + src/acp/mod.rs | 13 + src/acp/proxy.rs | 4115 ++++++++++++++++++++++++++++++ src/acp/wire.rs | 779 ++++++ src/bin/rustscript-agent.rs | 22 + src/cli.rs | 53 +- src/lib.rs | 1 + tests/acp_mcp_e2e_tests.rs | 450 ++++ tests/acp_proxy_bridge/mod.rs | 17 + tests/acp_proxy_tests.rs | 2509 ++++++++++++++++++ tests/acp_sdk_contract_tests.rs | 457 ++++ tests/fixtures/acp/build.rs | 35 + tests/fixtures/acp/fake_agent.rs | 653 +++++ tests/fixtures/acp/owning_mcp.rs | 247 ++ 16 files changed, 9462 insertions(+), 1 deletion(-) create mode 100644 src/acp/config.rs create mode 100644 src/acp/mod.rs create mode 100644 src/acp/proxy.rs create mode 100644 src/acp/wire.rs create mode 100644 tests/acp_mcp_e2e_tests.rs create mode 100644 tests/acp_proxy_bridge/mod.rs create mode 100644 tests/acp_proxy_tests.rs create mode 100644 tests/acp_sdk_contract_tests.rs create mode 100644 tests/fixtures/acp/build.rs create mode 100644 tests/fixtures/acp/fake_agent.rs create mode 100644 tests/fixtures/acp/owning_mcp.rs diff --git a/Cargo.lock b/Cargo.lock index 36c21829..255caa59 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2298,6 +2298,7 @@ version = "0.1.0" dependencies = [ "agent-client-protocol", "axum", + "blocking", "bytes", "futures-util", "http-body-util", diff --git a/Cargo.toml b/Cargo.toml index 57441cbf..0ce7ee33 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,6 +24,7 @@ path = "src/bin/rustscript-agent-gateway.rs" # proxy surface; no v5 feature selection can disable that internal prerequisite. agent-client-protocol = { version = "5.6.1", default-features = false, features = ["process", "stdio"] } axum = "0.8" +blocking = "1" bytes = "1" futures-util = "0.3" http-body-util = "0.1" diff --git a/src/acp/config.rs b/src/acp/config.rs new file mode 100644 index 00000000..e8de3d78 --- /dev/null +++ b/src/acp/config.rs @@ -0,0 +1,110 @@ +//! Bounded configuration for `rustscript-agent acp proxy`. +//! +//! The harness command is launched as an exact argument vector. There is no +//! shell, no command string parsing, and no environment mutation: the harness +//! keeps the environment it was started with by the user. + +use std::path::{Path, PathBuf}; + +/// Maximum number of harness arguments after the executable. +pub const MAX_HARNESS_ARGUMENTS: usize = 128; +/// Maximum bytes in one harness argument. +pub const MAX_HARNESS_ARGUMENT_BYTES: usize = 8 * 1024; +/// Maximum aggregate bytes across the executable and all arguments. +pub const MAX_HARNESS_ARGV_BYTES: usize = 64 * 1024; + +/// A validated downstream harness invocation. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AcpProxyConfig { + command: PathBuf, + arguments: Vec, + read_only: bool, +} + +/// Why a harness invocation was refused before any process was launched. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AcpConfigError { + /// The executable name or an argument was empty or contained a NUL. + InvalidHarnessCommand, + /// More than [`MAX_HARNESS_ARGUMENTS`] arguments were supplied. + TooManyHarnessArguments, + /// One argument exceeded [`MAX_HARNESS_ARGUMENT_BYTES`]. + HarnessArgumentTooLarge, + /// The executable plus arguments exceeded [`MAX_HARNESS_ARGV_BYTES`]. + HarnessArgumentVectorTooLarge, +} + +impl AcpConfigError { + /// Stable diagnostic code; never contains peer-provided text. + pub const fn code(self) -> &'static str { + match self { + Self::InvalidHarnessCommand => "acp_harness_command_invalid", + Self::TooManyHarnessArguments => "acp_harness_arguments_too_many", + Self::HarnessArgumentTooLarge => "acp_harness_argument_too_large", + Self::HarnessArgumentVectorTooLarge => "acp_harness_argv_too_large", + } + } +} + +impl std::fmt::Display for AcpConfigError { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(self.code()) + } +} + +impl std::error::Error for AcpConfigError {} + +impl AcpProxyConfig { + /// Validate one exact harness argument vector. + /// + /// `read_only` selects the profile of the injected RustScript MCP server + /// without changing the harness invocation. + pub fn new( + command: PathBuf, + arguments: Vec, + read_only: bool, + ) -> Result { + let command_text = command + .to_str() + .ok_or(AcpConfigError::InvalidHarnessCommand)?; + if command_text.is_empty() || command_text.contains('\0') { + return Err(AcpConfigError::InvalidHarnessCommand); + } + if arguments.len() > MAX_HARNESS_ARGUMENTS { + return Err(AcpConfigError::TooManyHarnessArguments); + } + let mut total = command_text.len(); + for argument in &arguments { + if argument.contains('\0') { + return Err(AcpConfigError::InvalidHarnessCommand); + } + if argument.len() > MAX_HARNESS_ARGUMENT_BYTES { + return Err(AcpConfigError::HarnessArgumentTooLarge); + } + total = total.saturating_add(argument.len()); + } + if total > MAX_HARNESS_ARGV_BYTES { + return Err(AcpConfigError::HarnessArgumentVectorTooLarge); + } + Ok(Self { + command, + arguments, + read_only, + }) + } + + /// The exact executable to launch. + pub fn command(&self) -> &Path { + &self.command + } + + /// The exact argument vector after the executable. + pub fn arguments(&self) -> &[String] { + &self.arguments + } + + /// Whether injected RustScript tools use the read-only profile. + pub fn read_only(&self) -> bool { + self.read_only + } +} diff --git a/src/acp/mod.rs b/src/acp/mod.rs new file mode 100644 index 00000000..0fffe94c --- /dev/null +++ b/src/acp/mod.rs @@ -0,0 +1,13 @@ +//! Public ACP v1 transport entry point. +//! +//! `rustscript-agent acp proxy -- ...` is a transparent client-facing +//! ACP v1 agent backed by an external ACP harness. The public surface accepts +//! ordinary ACP `initialize`; the SDK's internal `proxy/initialize` role is not +//! exposed to clients. All framing, request IDs, response routing, and +//! cancellation use the official `agent-client-protocol` v1 connections. + +pub mod config; +pub mod proxy; + +pub use config::{AcpConfigError, AcpProxyConfig}; +pub use proxy::{AcpProxyError, ProxyDisposition, run_proxy}; diff --git a/src/acp/proxy.rs b/src/acp/proxy.rs new file mode 100644 index 00000000..8bafb42b --- /dev/null +++ b/src/acp/proxy.rs @@ -0,0 +1,4115 @@ +//! Stable ACP v1 proxy transport. +//! +//! The public `rustscript-agent acp proxy` process serves ordinary ACP v1 to a +//! client and drives one downstream ACP harness process. It is a two-role +//! facade: an `Agent` connection toward the client and a `Client` connection +//! toward the harness, joined by SDK dispatch/response routing. The local +//! transport adapter bounds byte and request admission; the SDK owns JSON-RPC. +//! +//! # Ordering +//! +//! Every forwarded request selects the SDK's ordered response callback before +//! it is published. The callback only records the typed result and enqueues a +//! constant-sized ticket; the single bridge task answers the pending +//! responder. A peer response therefore always reaches the destination before +//! a later inbound notification that the peer wrote after it, in both +//! directions. The callback never waits for network I/O or later messages. +//! +//! # Shutdown +//! +//! One absolute deadline starts at the first shutdown cause (client EOF, a +//! termination signal, an observed driver failure, or a readiness failure) and +//! is published to the supervising task immediately, independently of the +//! later request to close the downstream stdin. Shutdown is explicit: +//! +//! 1. admission closes (handlers and bridge refuse new forwarded work); +//! 2. the traffic accepted before the cause is fenced and forwarded in wire +//! order, so queued permission answers and notifications are not overtaken +//! by synthetic cancellations or settlement fallbacks; +//! 3. every live session is cancelled once. A `session/new`, `session/load` +//! or `session/resume` whose successful completion is processed during +//! shutdown is registered and cancelled, then refused with the fixed +//! correlated `proxy_shutting_down` error: the SDK notification route only +//! admits a cancellation to its queue and cannot prove the harness +//! application received it; +//! 4. in-flight requests settle at their own queued `Settle` events until the +//! registry is empty or the shared settle deadline expires. One finite +//! producer-side cutoff then freezes both queues: remaining entries receive +//! one fixed typed error in acceptance order, and a callback that loses the +//! cutoff race cannot install a result outside its event; +//! 5. the downstream close request lets the SDK close the harness stdin, and +//! the upstream foreground returns success so the SDK's physical finish +//! contract drains and flushes the client-facing sink. +//! +//! The proxy owns both bridge queue receivers for the whole supervisor run; +//! the client-facing foreground and the bridge only borrow them. The +//! supervisor owns the two connection drivers. Both drivers are released +//! downstream-first, so the owned harness group is escalated before either +//! backlog can be disposed, even when a foreground returned early from its own +//! deadline check. A clean semantic cause is reported as a clean disposition +//! only when the client-facing driver returned success, was not forced down by +//! the hard deadline, and left no accepted prefix queued or pending; a +//! returned transport error, an abandoned prefix, or a forced drop is the fixed +//! transport failure. Accepted work and fallbacks run in small batches that +//! yield, so a continuously ready queue cannot starve either the supervisor or +//! the deadline check. A startup that never reaches the bridge seals both +//! producer directions before it settles and samples the residual queues; +//! there is no bridge consumer that could drain an event dispatched after that +//! snapshot. + +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; +use std::future::Future; +use std::path::{Path, PathBuf}; +use std::pin::Pin; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use agent_client_protocol::v1::{ConnectionTo, Responder}; +use agent_client_protocol::{ + Agent, CONNECTION_TERMINATED_REASON, Client, ConnectionTermination, Error, UntypedMessage, + is_incoming_transport_closed, +}; +use serde_json::Value; +use tokio::sync::{mpsc, oneshot, watch}; +use tokio::task::yield_now; +use tokio::time::{Instant, sleep_until, timeout}; + +use super::config::AcpProxyConfig; +#[path = "wire.rs"] +mod wire; +use wire::{ChildIo, HarnessChild, Peer, WirePolicy, bounded_transport}; + +/// Bound on waiting for the downstream connection to become usable. This is a +/// startup bound, not a shutdown grace period. +const HARNESS_READY_TIMEOUT: Duration = Duration::from_secs(15); +/// Absolute budget from the first shutdown cause until the proxy must be +/// gone. Every phase shares this deadline. +const SHUTDOWN_BUDGET: Duration = Duration::from_secs(5); +/// Part of [`SHUTDOWN_BUDGET`] the bridge may spend waiting for settlements +/// from the harness before it falls back to fixed errors. +const SHUTDOWN_SETTLE_BUDGET: Duration = Duration::from_secs(3); +/// Number of queued events one pump pass forwards before yielding to the +/// supervisor and re-checking the absolute deadline. +const QUEUE_BATCH: usize = 32; +/// Reason used when the proxy stops admitting work before it reaches the peer. +const PROXY_SHUTTING_DOWN_REASON: &str = "proxy_shutting_down"; +const RUSTSCRIPT_MCP_NAME: &str = "rustscript-tools"; +// ACP v1 has no session-close operation; keep live IDs until proxy shutdown. +const MAX_LIVE_SESSIONS: usize = 32; + +/// Clean ways the proxy itself stops. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ProxyDisposition { + /// The client closed its input; the owned harness was terminated. + ClientEof, + /// A termination signal arrived; the owned harness was terminated. + Signal, +} + +/// Fixed proxy failures. No variant carries peer-provided text, so the CLI can +/// print the code without ever surfacing a harness stderr tail or argv. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AcpProxyError { + /// The downstream harness stopped while the proxy was serving. + HarnessExited, + /// The downstream connection could not be established or readied. + HarnessUnavailable, + /// A protocol/transport failure while the client side was still active. + Transport, +} + +impl AcpProxyError { + /// Stable diagnostic code suitable for stderr. + pub const fn code(self) -> &'static str { + match self { + Self::HarnessExited => "acp_harness_exited", + Self::HarnessUnavailable => "acp_harness_unavailable", + Self::Transport => "acp_proxy_failed", + } + } +} + +impl std::fmt::Display for AcpProxyError { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(self.code()) + } +} + +impl std::error::Error for AcpProxyError {} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum TerminationCause { + ClientEof, + Signal, + HarnessExited, + HarnessUnavailable, + Transport, +} + +/// Why the bridge itself stopped. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum BridgeFailure { + HarnessClosed, + Transport, +} + +impl BridgeFailure { + fn cause(self) -> TerminationCause { + match self { + Self::HarnessClosed => TerminationCause::HarnessExited, + Self::Transport => TerminationCause::Transport, + } + } +} + +#[derive(Clone, Copy)] +struct ShutdownState { + cause: TerminationCause, + started: Instant, +} + +/// The first shutdown cause plus the one absolute deadline every phase shares. +/// +/// The deadline and the downstream-close request travel on separate watches: +/// the supervisor must observe the deadline the instant the cause is claimed, +/// while the harness must stay writable until accepted traffic and +/// cancellations have been forwarded. Claiming therefore records the deadline +/// immediately, and only [`Self::publish_close`] asks the drivers to wind down. +#[derive(Clone)] +struct Shutdown { + state: Arc>>, + deadline: watch::Sender>, + close: watch::Sender, + /// Set when shutdown stopped before the frozen prefix was fully delivered. + /// A residual is never reported as a clean disposition. + residual: Arc, +} + +impl Shutdown { + fn new() -> Self { + let (deadline, _receiver) = watch::channel(None); + let (close, _receiver) = watch::channel(false); + Self { + state: Arc::new(Mutex::new(None)), + deadline, + close, + residual: Arc::new(AtomicBool::new(false)), + } + } + + /// Claim the first cause and publish its absolute deadline to the + /// supervisor immediately. The downstream close request is deliberately + /// not part of this step. + fn claim(&self, cause: TerminationCause) -> bool { + let started = { + let mut slot = self + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if slot.is_some() { + return false; + } + let started = Instant::now(); + *slot = Some(ShutdownState { cause, started }); + started + }; + self.deadline.send_replace(Some(started + SHUTDOWN_BUDGET)); + true + } + + /// Ask both drivers to stop accepting traffic and drain. This is the only + /// signal that lets the downstream foreground close the harness stdin. + fn publish_close(&self) { + self.close.send_replace(true); + } + + /// Record the first cause and request the downstream close. Used when a + /// whole driver has already finished, so no settlement can be forwarded. + fn request(&self, cause: TerminationCause) -> bool { + let claimed = self.claim(cause); + self.publish_close(); + claimed + } + + fn state(&self) -> Option { + *self + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + } + + fn cause(&self) -> Option { + self.state().map(|state| state.cause) + } + + fn is_closing(&self) -> bool { + self.state().is_some() + } + + /// The instant after which the bridge must stop waiting for settlements. + fn drain_deadline(&self) -> Instant { + let started = self + .state() + .map(|state| state.started) + .unwrap_or_else(Instant::now); + started + SHUTDOWN_SETTLE_BUDGET + } + + /// The absolute instant at which every driver is dropped. + fn hard_deadline(&self) -> Instant { + let started = self + .state() + .map(|state| state.started) + .unwrap_or_else(Instant::now); + started + SHUTDOWN_BUDGET + } + + fn subscribe_deadline(&self) -> watch::Receiver> { + self.deadline.subscribe() + } + + fn subscribe_close(&self) -> watch::Receiver { + self.close.subscribe() + } + + /// Record that shutdown stopped with accepted work still queued or pending. + fn record_residual(&self, residual: bool) { + if residual { + self.residual.store(true, Ordering::Release); + } + } + + /// Whether any accepted prefix was abandoned instead of settled. + fn residual(&self) -> bool { + self.residual.load(Ordering::Acquire) + } +} + +/// One predicate over an absolute shutdown deadline. +/// +/// Production compares only the monotonic clock. Unit tests can force this +/// predicate after an upstream poll has already started, so a deadline +/// crossing is exercised deterministically without sleeping on wall time. +fn deadline_reached(stop: Instant) -> bool { + #[cfg(test)] + if test_deadline::passed() { + return true; + } + Instant::now() >= stop +} + +#[cfg(test)] +mod test_deadline { + use std::cell::Cell; + + thread_local! { + static PASSED: Cell = const { Cell::new(false) }; + } + + pub(super) fn passed() -> bool { + PASSED.with(Cell::get) + } + + pub(super) fn set(passed: bool) { + PASSED.with(|flag| flag.set(passed)); + } + + /// Resets the thread-local crossing when the owning test unwinds. + pub(super) struct ResetOnDrop; + + impl Drop for ResetOnDrop { + fn drop(&mut self) { + set(false); + } + } + + pub(super) fn reset_on_drop() -> ResetOnDrop { + set(false); + ResetOnDrop + } +} + +/// One accepted request whose responder is owned by the bridge until exactly +/// one terminal outcome is delivered. +struct PendingEntry { + method: String, + /// `session/load` and `session/resume` name the session in the request; + /// their v1 responses carry no session id. + requested_session: Option, + direction: Direction, + setup_slot: Option, + /// Test-only count of selection visits. Production builds do not carry + /// it; the traversal tests use it to prove a sweep never probes an entry + /// of the opposite direction or re-visits one it already selected. + #[cfg(test)] + visits: AtomicU64, + state: Mutex, +} + +struct PendingState { + outcome: Option>, + responder: Option>, + finalized: bool, +} + +impl PendingEntry { + fn new( + method: String, + requested_session: Option, + direction: Direction, + responder: Responder, + ) -> Self { + Self { + method, + requested_session, + direction, + setup_slot: None, + #[cfg(test)] + visits: AtomicU64::new(0), + state: Mutex::new(PendingState { + outcome: None, + responder: Some(responder), + finalized: false, + }), + } + } + + /// Test-only observation hook for ordered-map selection. Called once per + /// entry the sweep actually visits, so a test can distinguish a bounded + /// front-of-map walk from a full-map filter. + #[cfg(test)] + fn record_visit(&self) { + self.visits.fetch_add(1, Ordering::Relaxed); + } + + #[cfg(not(test))] + fn record_visit(&self) {} + + #[cfg(test)] + fn visit_count(&self) -> u64 { + self.visits.load(Ordering::Relaxed) + } + + /// Record the typed peer result. Returns `false` when a shutdown sweep + /// already finalized the entry, so a late response cannot duplicate it. + fn complete(&self, result: Result) -> bool { + let mut state = self + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if state.finalized || state.outcome.is_some() { + return false; + } + state.outcome = Some(result); + true + } + + /// True when the recorded outcome is the SDK's own clean-EOF failure for a + /// request the client can no longer answer. That failure must not be + /// forwarded before shutdown's synthetic cancellations. + fn is_clean_eof_failure(&self) -> bool { + let state = self + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + matches!(&state.outcome, Some(Err(error)) if is_incoming_transport_closed(error)) + } + + /// Remove the one outcome and responder, substituting `fallback` only when + /// no peer result was recorded. The entry can be finalized once. + fn finalize(&self, fallback: Error) -> Option<(Result, Responder)> { + let mut state = self + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if state.finalized { + return None; + } + state.finalized = true; + if state.outcome.is_none() { + state.outcome = Some(Err(fallback)); + } + let outcome = state.outcome.take()?; + let responder = state.responder.take()?; + Some((outcome, responder)) + } + + /// Take the responder and install the fixed fallback unconditionally. + /// + /// Used by the post-cutoff sweep: a recorded outcome whose `Settle` event + /// was not part of the frozen prefix must not be delivered as if it had + /// been, so the sweep never consults `outcome`. + fn finalize_fallback( + &self, + fallback: Error, + ) -> Option<(Result, Responder)> { + let mut state = self + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if state.finalized { + return None; + } + state.finalized = true; + let responder = state.responder.take()?; + Some((Err(fallback), responder)) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Direction { + /// The request travels harness -> client; its responder writes to the + /// harness. + ToClient, + /// The request travels client -> harness; its responder writes to the + /// client. + ToHarness, +} + +/// Every accepted forwarded request, keyed by ticket inside one ordered map +/// per direction. Only the bridge removes entries, so the final enqueue cannot +/// be missed by a racing counter. Tickets are globally monotonic, so iterating +/// one direction's map is acceptance order for that direction. +#[derive(Default)] +struct PendingRegistry { + next_id: AtomicU64, + entries: Mutex, +} + +#[derive(Default)] +struct PendingEntries { + to_client: BTreeMap>, + to_harness: BTreeMap>, +} + +impl PendingEntries { + fn by_direction_mut(&mut self, direction: Direction) -> &mut BTreeMap> { + match direction { + Direction::ToClient => &mut self.to_client, + Direction::ToHarness => &mut self.to_harness, + } + } +} + +/// One finalized request on its way back to the peer that asked. +type PendingDelivery = (Arc, Result, Responder); + +impl PendingRegistry { + fn insert(&self, entry: PendingEntry) -> u64 { + let id = self.next_id.fetch_add(1, Ordering::Relaxed) + 1; + let direction = entry.direction; + self.entries + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .by_direction_mut(direction) + .insert(id, Arc::new(entry)); + id + } + + fn get(&self, id: u64) -> Option> { + let entries = self + .entries + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + entries + .to_client + .get(&id) + .or_else(|| entries.to_harness.get(&id)) + .cloned() + } + + /// Take the entry and its single outcome. `fallback` runs only when no + /// peer result was recorded before the cutoff. + fn deliver(&self, id: u64, fallback: impl FnOnce(&str) -> Error) -> Option { + let mut entries = self + .entries + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let entry = match entries.to_client.remove(&id) { + Some(entry) => entry, + None => entries.to_harness.remove(&id)?, + }; + let (outcome, responder) = entry.finalize(fallback(&entry.method))?; + Some((entry, outcome, responder)) + } + + /// Remove at most `limit` entries travelling in `direction`, in acceptance + /// order, and give each one the fixed fallback. + /// + /// This is the unordered sweep used only after the producer-side cutoff: + /// it deliberately does not read a recorded peer outcome, because a result + /// may only be delivered at its own queued `Settle` event. The sweep walks + /// only `direction`'s ordered map, so a batch visits at most `limit` + /// eligible entries regardless of how large the opposite backlog is, and + /// removal is logarithmic per selected ticket. + fn take_direction_batch( + &self, + direction: Direction, + limit: usize, + fallback: impl Fn(&str) -> Error, + ) -> Vec { + let mut entries = self + .entries + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let map = entries.by_direction_mut(direction); + let ids: Vec = map + .iter() + .take(limit) + .map(|(id, entry)| { + entry.record_visit(); + *id + }) + .collect(); + ids.into_iter() + .filter_map(|id| { + let entry = map.remove(&id)?; + let (outcome, responder) = entry.finalize_fallback(fallback(&entry.method))?; + Some((entry, outcome, responder)) + }) + .collect() + } + + fn is_empty(&self) -> bool { + let entries = self + .entries + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + entries.to_client.is_empty() && entries.to_harness.is_empty() + } +} + +/// The single linearization point shared by every queue producer and the +/// shutdown cutoff. +/// +/// Peer dispatch handlers and ordered response callbacks append while holding +/// this lock, and [`Self::freeze`] appends the two `Fence` markers while +/// holding it. The markers therefore split each queue exactly into the prefix +/// accepted before the cutoff and everything published after it. A callback +/// that loses the race does not record its result at all, so the fixed sweep +/// is the only possible answer for that ticket. +#[derive(Clone)] +struct Publication { + state: Arc>, + pending: Arc, + wire: WirePolicy, + to_downstream: mpsc::UnboundedSender, + to_upstream: mpsc::UnboundedSender, +} + +#[derive(Default)] +struct PublicationState { + frozen: bool, + fence: u64, +} + +impl Publication { + fn new( + pending: Arc, + to_downstream: mpsc::UnboundedSender, + to_upstream: mpsc::UnboundedSender, + ) -> Self { + Self { + state: Arc::new(Mutex::new(PublicationState::default())), + pending, + wire: WirePolicy::default(), + to_downstream, + to_upstream, + } + } + + /// Append one admitted event unless the cutoff already froze the prefix. + /// On refusal the event is handed back so a request can still be answered + /// with a fixed typed error. + fn admit_to_downstream(&self, event: ToDownstream) -> Result<(), ToDownstream> { + let state = self + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if state.frozen { + return Err(event); + } + self.to_downstream.send(event).map_err(|error| error.0) + } + + fn admit_to_upstream(&self, event: ToUpstream) -> Result<(), ToUpstream> { + let state = self + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if state.frozen { + return Err(event); + } + self.to_upstream.send(event).map_err(|error| error.0) + } + + /// Record a peer result and publish its ordered `Settle` ticket as one + /// step. A callback that arrives after the cutoff is ignored: its ticket + /// cannot be part of the frozen prefix, so the fixed fallback owns it. + /// The frozen check and the ticket append happen under the same lock as + /// [`Self::freeze`], so a losing callback can neither install a result nor + /// append an event behind the marker. + fn complete_upstream(&self, id: u64, result: Result) { + let state = self + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if state.frozen { + return; + } + if let Some(entry) = self.pending.get(id) + && entry.complete(result) + { + let _ = self.to_upstream.send(ToUpstream::Settle { id }); + } + } + + fn complete_downstream(&self, id: u64, result: Result) { + let state = self + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if state.frozen { + return; + } + if let Some(entry) = self.pending.get(id) + && entry.complete(result) + { + let _ = self.to_downstream.send(ToDownstream::Settle { id }); + } + } + + /// Close both producer directions without appending wire-order markers. + /// + /// Readiness exits never establish a bridge consumer, so no drain can + /// consume a `Fence` event. Sealing still uses the same linearization lock + /// as every admission and completion callback: an event that loses the + /// race is handed back to its producer, and the following residual + /// snapshot is final. + fn seal(&self) -> bool { + let mut state = self + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + Self::seal_locked(&mut state) + } + + /// The one cutoff primitive shared by the readiness seal and the ordered + /// bridge freeze. Returns `false` when a cutoff already happened. + fn seal_locked(state: &mut PublicationState) -> bool { + if state.frozen { + return false; + } + state.frozen = true; + true + } + + /// Close the accepted prefixes and return the marker id, or `None` when a + /// cutoff already happened. + fn freeze(&self) -> Option { + let mut state = self + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if !Self::seal_locked(&mut state) { + return None; + } + state.fence += 1; + let fence = state.fence; + // Both markers are appended under the same lock, so a producer cannot + // slip an event into either queue between the two freezes. + let _ = self.to_downstream.send(ToDownstream::Fence { id: fence }); + let _ = self.to_upstream.send(ToUpstream::Fence { id: fence }); + Some(fence) + } +} + +/// Session IDs observed in successful `session/new`, `session/load`, and +/// `session/resume` responses. Shutdown uses them to cancel active downstream +/// sessions before closing the downstream stdin, and a session is cancelled at +/// most once even when its setup succeeds during shutdown. +#[derive(Clone, Default)] +struct SessionRegistry { + buckets: Arc>, +} + +#[derive(Default)] +struct SessionBuckets { + live: HashSet, + reserved_new: usize, + reserved_named: HashMap, + cancelled: HashSet, + /// Sessions observed live and not yet marked for cancellation, in stable + /// id order. A cancellation consumes from this set instead of rescanning + /// `live`, so already-cancelled sessions are never replayed. + outstanding: BTreeSet, + /// Test-only count of sessions examined by `begin_cancellations`. A + /// bounded consume visits exactly the ids it returns. + #[cfg(test)] + scanned: u64, +} + +/// Held by an in-flight setup until its terminal answer. Failure to publish, +/// peer error, and shutdown fallback all release via the same ownership path. +struct SessionSlot { + registry: SessionRegistry, + name: Option, +} + +impl Drop for SessionSlot { + fn drop(&mut self) { + let mut buckets = self + .registry + .buckets + .lock() + .unwrap_or_else(|e| e.into_inner()); + if let Some(name) = &self.name { + // A successful setup already made this name live and released + // the shared reservation for all setups using that name. + if let Some(count) = buckets.reserved_named.get_mut(name) { + *count -= 1; + if *count == 0 { + buckets.reserved_named.remove(name); + } + } + } else { + buckets.reserved_new -= 1; + } + } +} + +impl SessionRegistry { + fn reserve(&self, name: Option<&str>) -> Result, ()> { + let mut buckets = self.buckets.lock().unwrap_or_else(|e| e.into_inner()); + let slot = || SessionSlot { + registry: self.clone(), + name: name.map(str::to_owned), + }; + if let Some(name) = name { + if buckets.live.contains(name) { + return Ok(None); + } + if let Some(count) = buckets.reserved_named.get_mut(name) { + *count += 1; + return Ok(Some(slot())); + } + } + if buckets.live.len() + buckets.reserved_new + buckets.reserved_named.len() + >= MAX_LIVE_SESSIONS + { + return Err(()); + } + if let Some(name) = name { + buckets.reserved_named.insert(name.to_owned(), 1); + } else { + buckets.reserved_new += 1; + } + Ok(Some(slot())) + } + + /// Record a successfully answered session setup request. + /// + /// `session/new` carries the assigned id in the response. The v1 + /// `session/load` and `session/resume` responses carry no id, so the + /// request's own `sessionId` names the live session. Returns the observed + /// id for a setup method so the caller can cancel it before reporting the + /// success during shutdown; non-setup responses return `None`. + fn observe( + &self, + method: &str, + requested_session: Option<&str>, + result: &Value, + ) -> Option { + let session_id = match method { + "session/new" => result + .get("sessionId") + .and_then(Value::as_str) + .map(str::to_owned), + "session/load" | "session/resume" => requested_session.map(str::to_owned), + _ => None, + }?; + let mut buckets = self + .buckets + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + buckets.reserved_named.remove(&session_id); + if buckets.live.insert(session_id.clone()) && !buckets.cancelled.contains(&session_id) { + buckets.outstanding.insert(session_id.clone()); + } + Some(session_id) + } + + /// Mark `session_id` as cancelled. Returns `false` when it already was, so + /// a synthetic cancellation is sent exactly once. + fn begin_cancel(&self, session_id: &str) -> bool { + let mut buckets = self + .buckets + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if buckets.cancelled.insert(session_id.to_owned()) { + buckets.outstanding.remove(session_id); + true + } else { + false + } + } + + /// Consume up to `limit` outstanding sessions and return them. + /// + /// The outstanding set is drained, not filtered: a batch examines only the + /// ids it removes, so already-cancelled sessions are never rescanned and a + /// poll costs at most [`QUEUE_BATCH`] logarithmic removals. An id observed + /// again after its cancellation is not re-inserted, so a repeated + /// successful setup cannot re-arm a second synthetic cancellation. + fn begin_cancellations(&self, limit: usize) -> Vec { + let mut buckets = self + .buckets + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let mut ids = Vec::with_capacity(limit.min(buckets.outstanding.len())); + for _ in 0..limit { + let Some(session_id) = buckets.outstanding.pop_first() else { + break; + }; + #[cfg(test)] + { + buckets.scanned += 1; + } + if buckets.cancelled.insert(session_id.clone()) { + ids.push(session_id); + } + } + ids + } + + #[cfg(test)] + fn scanned(&self) -> u64 { + self.buckets + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .scanned + } +} + +/// One inbound request or notification queued for forwarding. +enum Inbound { + Request(UntypedMessage, Box>), + Notification(UntypedMessage), +} + +/// Ordered client-to-harness traffic: messages as received, plus the ticket of +/// a request the harness sent upstream whose response is now known, plus the +/// one producer-side marker that freezes the accepted prefix during shutdown. +enum ToDownstream { + Message(Inbound), + Settle { + id: u64, + }, + /// Inserted while holding the [`Publication`] lock, so every event an + /// admitted producer appended before the cutoff is in front of it and no + /// event published after the cutoff can be. + Fence { + id: u64, + }, + /// Test-only undispatched event. Its drop counts as backlog disposal, so a + /// regression can observe queue lifetime without owning the receiver. + #[cfg(test)] + #[allow(dead_code)] + Sentinel(test_queue::Sentinel), +} + +#[cfg(test)] +mod test_queue { + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + + /// Test-only undispatched event. A counting sentinel records disposal of + /// the tail backlog; an arming sentinel also marks the injected hard + /// deadline as reached, from inside the driver's own poll. + pub(super) struct Sentinel { + drops: Arc, + arm_deadline: bool, + } + + impl Sentinel { + pub(super) fn counting(drops: Arc) -> Self { + Self { + drops, + arm_deadline: false, + } + } + + pub(super) fn arming(drops: Arc) -> Self { + Self { + drops, + arm_deadline: true, + } + } + } + + impl Drop for Sentinel { + fn drop(&mut self) { + self.drops.fetch_add(1, Ordering::Release); + if self.arm_deadline { + super::test_deadline::set(true); + } + } + } +} + +/// Ordered harness-to-client traffic: messages as received, plus the ticket of +/// a request the client sent downstream whose response is now known, plus the +/// same cutoff marker. +enum ToUpstream { + Message(Inbound), + Settle { id: u64 }, + Fence { id: u64 }, +} + +/// What handling one queued event did. +enum Handled { + Continue, + /// The queue reached the producer-side cutoff marker for this direction. + Fence(u64), +} + +/// Run the public ACP proxy over this process's stdin/stdout. +pub async fn run_proxy(config: AcpProxyConfig) -> Result { + let (to_downstream_tx, mut to_downstream_rx) = mpsc::unbounded_channel(); + let (to_upstream_tx, mut to_upstream_rx) = mpsc::unbounded_channel(); + let (downstream_ready_tx, downstream_ready_rx) = oneshot::channel(); + let shutdown = Shutdown::new(); + let pending = Arc::new(PendingRegistry::default()); + let sessions = SessionRegistry::default(); + let upstream_watch: Arc>>> = Arc::new(Mutex::new(None)); + let downstream_ready_seen = Arc::new(AtomicBool::new(false)); + + let publication = Publication::new( + Arc::clone(&pending), + to_downstream_tx.clone(), + to_upstream_tx.clone(), + ); + let upstream_request_admission = shutdown.clone(); + let upstream_requests = publication.clone(); + let upstream_notification_admission = shutdown.clone(); + let upstream_notifications = publication.clone(); + // SDK Lines retains the cooperative finish contract. Unblock avoids + // waiting for a synchronous host stdin read at proxy exit. + let upstream_transport = bounded_transport( + blocking::Unblock::new(std::io::stdout()), + blocking::Unblock::new(std::io::stdin()), + shutdown.clone(), + TerminationCause::Transport, + publication.wire.clone(), + Peer::Client, + ); + let read_only = config.read_only(); + let upstream = Agent + .v1() + .on_close({ + let wire = publication.wire.clone(); + let shutdown = shutdown.clone(); + async move |_| { + wire.close_cause(Peer::Client, &shutdown, TerminationCause::Transport); + Ok(()) + } + }) + .on_receive_request( + async move |request: UntypedMessage, responder: Responder, _cx| { + if upstream_request_admission.is_closing() { + // Stop new admission: no work may start after shutdown. + let _ = + responder.respond_with_result(Err(shutting_down_error(request.method()))); + return Ok(()); + } + if let Err(event) = upstream_requests.admit_to_downstream(ToDownstream::Message( + Inbound::Request(request, Box::new(responder)), + )) && let ToDownstream::Message(Inbound::Request(request, responder)) = event + { + // Only a cutoff can refuse admission; answer instead of + // dropping the responder. + let _ = + responder.respond_with_result(Err(shutting_down_error(request.method()))); + } + Ok(()) + }, + agent_client_protocol::on_receive_request!(), + ) + .on_receive_notification( + async move |notification: UntypedMessage, _cx| { + if upstream_notification_admission.is_closing() { + return Ok(()); + } + let notification = upstream_notifications + .wire + .track_notice(Peer::Client, notification); + let _ = upstream_notifications.admit_to_downstream(ToDownstream::Message( + Inbound::Notification(notification), + )); + Ok(()) + }, + agent_client_protocol::on_receive_notification!(), + ) + .connect_with(upstream_transport, { + let shutdown = shutdown.clone(); + let pending = Arc::clone(&pending); + let sessions = sessions.clone(); + let upstream_watch = Arc::clone(&upstream_watch); + let publication = publication.clone(); + // Borrow the queues instead of moving them in: the supervisor + // keeps ownership so a foreground that returns inside its own poll + // cannot dispose accepted work before the harness is escalated. + let to_downstream = &mut to_downstream_rx; + let to_upstream = &mut to_upstream_rx; + async move |upstream: ConnectionTo| { + *upstream_watch + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(upstream.clone()); + // The foreground always returns success: every semantic + // failure is already recorded in `shutdown`, and the SDK must + // be allowed to drain the fixed typed outcomes it just + // accepted before the driver terminates. The fixed diagnostic + // is selected outside the SDK, from the recorded cause. + let _ = drive_upstream( + upstream, + downstream_ready_rx, + to_downstream, + to_upstream, + shutdown.clone(), + pending, + sessions, + publication, + read_only, + ) + .await; + Ok(()) + } + }); + + let downstream_request_admission = shutdown.clone(); + let downstream_requests = publication.clone(); + let downstream_notifications = publication.clone(); + let downstream_builder = Client + .v1() + .on_close({ + let wire = publication.wire.clone(); + let shutdown = shutdown.clone(); + async move |_| { + wire.close_cause(Peer::Harness, &shutdown, TerminationCause::HarnessExited); + Ok(()) + } + }) + .on_receive_request( + async move |request: UntypedMessage, responder: Responder, _cx| { + if downstream_request_admission.is_closing() { + let _ = + responder.respond_with_result(Err(shutting_down_error(request.method()))); + return Ok(()); + } + if let Err(event) = downstream_requests.admit_to_upstream(ToUpstream::Message( + Inbound::Request(request, Box::new(responder)), + )) && let ToUpstream::Message(Inbound::Request(request, responder)) = event + { + let _ = + responder.respond_with_result(Err(shutting_down_error(request.method()))); + } + Ok(()) + }, + agent_client_protocol::on_receive_request!(), + ) + .on_receive_notification( + async move |notification: UntypedMessage, _cx| { + // Harness-to-client updates describe work the client already + // started. They are part of the accepted prefix and stay in + // wire order with the responses that follow them, so shutdown + // must not drop one merely because the cause was claimed. + let notification = downstream_notifications + .wire + .track_notice(Peer::Harness, notification); + let _ = downstream_notifications + .admit_to_upstream(ToUpstream::Message(Inbound::Notification(notification))); + Ok(()) + }, + agent_client_protocol::on_receive_notification!(), + ); + let downstream = { + let shutdown = shutdown.clone(); + let downstream_ready_seen = Arc::clone(&downstream_ready_seen); + async move { + let (child, stdin, stdout) = + HarnessChild::spawn(&config).map_err(|_| Error::internal_error())?; + let harness = bounded_transport( + ChildIo(stdin), + ChildIo(stdout), + shutdown.clone(), + TerminationCause::HarnessExited, + publication.wire.clone(), + Peer::Harness, + ); + let driver = downstream_builder.connect_with(harness, async move |downstream| { + downstream_ready_seen.store(true, Ordering::Release); + let _ = downstream_ready_tx.send(downstream.clone()); + downstream_until_terminated(downstream, shutdown).await + }); + child.supervise(driver).await + } + }; + + // The two bridge queues stay in this scope, outside both drivers. A + // driver's foreground may return early when the hard deadline fires inside + // one of its own polls; keeping the receivers here means neither backlog + // can be disposed before the supervisor escalates the harness. + let mut deadline = shutdown.subscribe_deadline(); + supervise_connections( + upstream, + downstream, + shutdown, + &upstream_watch, + &downstream_ready_seen, + wait_for_hard_deadline(&mut deadline), + ) + .await +} + +/// Drive both connection drivers and both shutdown signals to completion. +/// +/// The caller owns the two bridge queue receivers for the whole call; the +/// client-facing foreground only borrows them. The drivers are boxed and +/// observed as whole futures, so a connection that finishes before its +/// foreground published still releases the other side. The hard deadline is +/// an explicit future so tests can cross it deterministically while an +/// upstream poll is already in flight. +async fn supervise_connections( + upstream: U, + downstream: D, + shutdown: Shutdown, + upstream_watch: &Mutex>>, + downstream_ready_seen: &AtomicBool, + deadline: F, +) -> Result +where + U: std::future::Future>, + D: std::future::Future>, + F: std::future::Future, +{ + let mut upstream = Box::pin(upstream); + let mut downstream = Box::pin(downstream); + let mut deadline = Box::pin(deadline); + let mut upstream_done = false; + let mut downstream_done = false; + let mut upstream_forced_drop = false; + // `None` until the client-facing driver finishes; `Some(true)` only when + // that driver reported success after draining, flushing, and closing the + // physical writer. An error or a forced drop must never be reported as a + // clean exit. + let mut upstream_drained: Option = None; + + loop { + if upstream_done && downstream_done { + break; + } + tokio::select! { + biased; + result = &mut upstream, if !upstream_done => { + upstream_done = true; + upstream_drained = Some(result.is_ok()); + let cause = match upstream_watch + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .as_ref() + { + Some(connection) + if connection.is_incoming_closed() + || matches!( + connection.termination(), + Some(ConnectionTermination::IncomingClosed) + ) => + { + TerminationCause::ClientEof + } + _ => TerminationCause::Transport, + }; + shutdown.request(cause); + } + result = &mut downstream, if !downstream_done => { + downstream_done = true; + let _ = result; + // A connection that never reached its foreground never served + // the harness; report the readiness failure, not a peer exit. + let cause = if downstream_ready_seen.load(Ordering::Acquire) { + TerminationCause::HarnessExited + } else { + TerminationCause::HarnessUnavailable + }; + shutdown.request(cause); + } + _ = &mut deadline => { + // The physical flush did not complete in the shared budget. + // Remember that even though the semantic cause may be clean, + // the proxy cannot claim that its accepted output drained. + upstream_forced_drop = !upstream_done; + // Falls through to `release_drivers`, which escalates the + // owned harness group before either bridge backlog is dropped. + break; + } + } + } + + // Explicitly release whichever driver is still running before returning: + // the downstream release is the owned-harness escalation path and happens + // first, while the caller still owns the bridge queues. A foreground that + // already returned cannot dispose them, because it only borrowed them. + release_drivers(upstream, downstream); + + let cause = shutdown.cause().unwrap_or(TerminationCause::Transport); + match cause { + TerminationCause::HarnessExited => Err(AcpProxyError::HarnessExited), + TerminationCause::HarnessUnavailable => Err(AcpProxyError::HarnessUnavailable), + TerminationCause::Transport => Err(AcpProxyError::Transport), + // A clean semantic cause is only a clean exit when the client-facing + // driver returned success: that is the SDK's physical drain/flush/close + // contract, the shutdown left no accepted prefix behind, and no driver + // was forced down by the hard deadline. Anything else is a fixed + // transport failure, even for a clean cause. + TerminationCause::ClientEof + if upstream_drained == Some(true) && !upstream_forced_drop && !shutdown.residual() => + { + Ok(ProxyDisposition::ClientEof) + } + TerminationCause::Signal + if upstream_drained == Some(true) && !upstream_forced_drop && !shutdown.residual() => + { + Ok(ProxyDisposition::Signal) + } + TerminationCause::ClientEof | TerminationCause::Signal => Err(AcpProxyError::Transport), + } +} + +/// Release both connection drivers on supervisor exit. +/// +/// The downstream future owns the child guard for the spawned harness; +/// its `Drop` synchronously kills the owned process group. The downstream +/// future is therefore released before the client-facing driver, so the +/// harness group is escalated while the client-facing future (and the bridge +/// queues it owns) still exist. This is the only driver destruction path; no +/// cleanup task or deferred guard owns the child handle. +fn release_drivers(upstream: U, downstream: D) { + drop(downstream); + drop(upstream); +} + +/// Bridge plus both connection handles, the ordered output queues, and their +/// one publication/cutoff gate. +struct Bridge<'a> { + upstream: &'a ConnectionTo, + downstream: &'a ConnectionTo, + pending: Arc, + publication: Publication, + sessions: SessionRegistry, + shutdown: Shutdown, + mcp: Mutex, +} + +struct PendingSessionMcp { + request: UntypedMessage, + responder: Box>, + declaration: Pin> + Send>>, +} + +#[allow(clippy::too_many_arguments)] +async fn drive_upstream( + upstream: ConnectionTo, + downstream_ready: oneshot::Receiver>, + to_downstream: &mut mpsc::UnboundedReceiver, + to_upstream: &mut mpsc::UnboundedReceiver, + shutdown: Shutdown, + pending: Arc, + sessions: SessionRegistry, + publication: Publication, + read_only: bool, +) -> Result<(), BridgeFailure> { + let mut close_rx = shutdown.subscribe_close(); + let signal = wait_for_shutdown_signal(); + tokio::pin!(signal); + + // The readiness budget is fixed at startup and independent of the first + // shutdown claim. A client EOF or termination signal observed while the + // harness is still starting must win immediately, and every request the + // client already queued gets its fixed typed failure instead of being + // dropped with its responder. + let readiness = timeout(HARNESS_READY_TIMEOUT, downstream_ready); + tokio::pin!(readiness); + let downstream = tokio::select! { + biased; + _ = wait_for_close(&mut close_rx) => { + // A supervisor-observed driver failure already recorded the + // cause; admission is closed, so only queued work remains. + seal_and_settle_unready(&publication, &shutdown, to_downstream, to_upstream).await; + return Ok(()); + } + _ = upstream.incoming_closed() => { + shutdown.claim(TerminationCause::ClientEof); + seal_and_settle_unready(&publication, &shutdown, to_downstream, to_upstream).await; + return Ok(()); + } + _ = &mut signal => { + shutdown.claim(TerminationCause::Signal); + seal_and_settle_unready(&publication, &shutdown, to_downstream, to_upstream).await; + return Ok(()); + } + ready = &mut readiness => { + match ready { + Ok(Ok(downstream)) => downstream, + // The transport either failed before its foreground or + // exceeded the bounded startup wait. + Ok(Err(_)) | Err(_) => { + shutdown.claim(TerminationCause::HarnessUnavailable); + seal_and_settle_unready(&publication, &shutdown, to_downstream, to_upstream) + .await; + return Ok(()); + } + } + } + }; + + let bridge = Bridge { + upstream: &upstream, + downstream: &downstream, + pending, + publication, + sessions, + shutdown: shutdown.clone(), + mcp: Mutex::default(), + }; + let mut downstream_terminated = Box::pin(downstream.terminated()); + let mut failure = None; + // Hold just the head setup request during filesystem validation. Keep + // handling harness traffic and shutdown without reordering the downstream FIFO. + let mut validating: Option = None; + + loop { + tokio::select! { + biased; + _ = wait_for_close(&mut close_rx) => { + // The supervisor observed a whole-driver failure, or the + // harness closed in its own foreground. + break; + } + _ = &mut downstream_terminated => { + shutdown.claim(TerminationCause::HarnessExited); + break; + } + _ = upstream.incoming_closed() => { + // Clean client EOF means every accepted frame has already been + // dispatched into the queues; the fence runs in `finish`. + shutdown.claim(TerminationCause::ClientEof); + break; + } + _ = &mut signal => { + shutdown.claim(TerminationCause::Signal); + break; + } + declaration = async { validating.as_mut().unwrap().declaration.as_mut().await }, if validating.is_some() => { + let PendingSessionMcp { mut request, responder, .. } = validating.take().unwrap(); + let method = request.method().to_owned(); + match declaration { + Ok(declaration) => { + // List shape and name were checked before starting I/O. + match request.params.get_mut("mcpServers") { + Some(Value::Array(servers)) => servers.push(declaration), + _ => request.params["mcpServers"] = Value::Array(vec![declaration]), + } + bridge.forward_request_downstream(request, *responder, method); + } + Err(error) => { + let _ = responder.respond_with_result(Err(error)); + } + } + } + event = to_downstream.recv(), if validating.is_none() => { + match event { + Some(ToDownstream::Message(Inbound::Request(request, responder))) + if !shutdown.is_closing() && bridge.injects_mcp(request.method()) => + { + match session_mcp_workspace(&request) { + Ok(cwd) => { + let declaration = Box::pin(session_mcp_declaration( + cwd, read_only, request.method().to_owned(), + )); + validating = Some(PendingSessionMcp { request, responder, declaration }); + } + Err(error) => { + let _ = responder.respond_with_result(Err(error)); + } + } + } + Some(event) => { + if bridge.handle_to_downstream(event).is_err() { + failure = Some(BridgeFailure::HarnessClosed); + break; + } + } + None => { + shutdown.claim(TerminationCause::Transport); + break; + } + } + } + event = to_upstream.recv() => { + match event { + Some(event) => { + if bridge.handle_to_upstream(event).is_err() { + failure = Some(BridgeFailure::Transport); + break; + } + } + None => { + shutdown.claim(TerminationCause::Transport); + break; + } + } + } + } + } + + if let Some(failure) = failure { + // Record the semantic cause before the phases consult the deadline, + // but keep the foreground successful so the SDK can still drain the + // typed outcomes accepted above. + shutdown.claim(failure.cause()); + } + if let Some(PendingSessionMcp { + request, responder, .. + }) = validating.take() + { + let _ = responder.respond_with_result(Err(shutting_down_error(request.method()))); + } + let residual = bridge.finish(to_downstream, to_upstream).await; + shutdown.record_residual(residual); + Ok(()) +} + +/// Seal both producer directions and settle the accepted client-to-harness +/// prefix when the harness never became usable. +/// +/// This is the only readiness-exit path, shared by client EOF, a termination +/// signal, a supervisor-observed driver close, and failed or timed-out +/// readiness. Sealing happens before the drain and the residual snapshot, so +/// the snapshot is final: a downstream notification or completion callback +/// that is dispatched afterwards loses admission under the same lock instead +/// of appending an event no bridge consumer will ever drain. A request already +/// queued below the seal still receives exactly one fixed typed refusal; work +/// the drain cannot finish before the deadline stays queued and is recorded as +/// residual. +async fn seal_and_settle_unready( + publication: &Publication, + shutdown: &Shutdown, + to_downstream: &mut mpsc::UnboundedReceiver, + to_upstream: &mut mpsc::UnboundedReceiver, +) { + publication.seal(); + settle_unready(to_downstream, shutdown.hard_deadline()).await; + shutdown.record_residual(!to_downstream.is_empty() || !to_upstream.is_empty()); + shutdown.publish_close(); +} + +/// Answer every request the client already queued while the harness was never +/// usable. Notifications are dropped; each responder gets one fixed, typed +/// failure rather than being released by a drop guard. +/// +/// The drain runs in bounded batches that yield, because a client may have +/// queued an arbitrarily large accepted prefix before the harness failed to +/// start, and the first absolute deadline must stay observable. +async fn settle_unready(to_downstream: &mut mpsc::UnboundedReceiver, stop: Instant) { + loop { + let mut progressed = false; + for _ in 0..QUEUE_BATCH { + if deadline_reached(stop) { + return; + } + match to_downstream.try_recv() { + Ok(ToDownstream::Message(Inbound::Request(request, responder))) => { + let _ = + responder.respond_with_result(Err(shutting_down_error(request.method()))); + progressed = true; + } + Ok(_) => progressed = true, + Err(_) => break, + } + } + if !progressed { + return; + } + yield_now().await; + } +} + +impl Bridge<'_> { + fn injects_mcp(&self, method: &str) -> bool { + match method { + "session/new" => true, + "session/load" | "session/resume" => { + let caps = self.mcp.lock().unwrap_or_else(|error| error.into_inner()); + if method == "session/load" { + caps.load + } else { + caps.resume + } + } + _ => false, + } + } + + fn handle_to_downstream(&self, event: ToDownstream) -> Result { + match event { + ToDownstream::Message(Inbound::Request(request, responder)) => { + let responder = *responder; + let method = request.method().to_owned(); + self.forward_request_downstream(request, responder, method); + Ok(Handled::Continue) + } + ToDownstream::Message(Inbound::Notification(notification)) => self + .downstream + .send_notification_to(Agent, notification) + .map(|()| Handled::Continue), + ToDownstream::Settle { id } => { + self.deliver_to_downstream(id); + Ok(Handled::Continue) + } + ToDownstream::Fence { id } => Ok(Handled::Fence(id)), + #[cfg(test)] + ToDownstream::Sentinel(_) => Ok(Handled::Continue), + } + } + + fn handle_to_upstream(&self, event: ToUpstream) -> Result { + match event { + ToUpstream::Message(Inbound::Request(request, responder)) => { + let responder = *responder; + let method = request.method().to_owned(); + if self.shutdown.is_closing() { + let _ = responder.respond_with_result(Err(shutting_down_error(&method))); + return Ok(Handled::Continue); + } + self.forward_request_upstream(request, responder, method); + Ok(Handled::Continue) + } + ToUpstream::Message(Inbound::Notification(notification)) => self + .upstream + .send_notification_to(Client, notification) + .map(|()| Handled::Continue), + ToUpstream::Settle { id } => { + self.deliver_to_upstream(id); + Ok(Handled::Continue) + } + ToUpstream::Fence { id } => Ok(Handled::Fence(id)), + } + } + + /// Publish a client request downstream with ordered response selection. + fn forward_request_downstream( + &self, + request: UntypedMessage, + responder: Responder, + method: String, + ) { + // Re-check admission after asynchronous validation. During shutdown + // the queue drain also refuses requests that were never forwarded. + if self.shutdown.is_closing() { + let _ = responder.respond_with_result(Err(shutting_down_error(&method))); + return; + } + let requested_session = requested_session_for(&method, &request); + let setup_slot = if is_session_setup(&method) { + match self.sessions.reserve(requested_session.as_deref()) { + Ok(slot) => slot, + Err(()) => { + let _ = responder + .respond_with_result(Err(typed_error(&method, "proxy_session_limit"))); + return; + } + } + } else { + None + }; + let prepared = self + .downstream + .prepare_request_to(Agent, request) + .forwarded_from(&responder); + self.publication + .wire + .expect_reply(Peer::Harness, prepared.raw_id(), responder.raw_id()); + let mut entry = + PendingEntry::new(method, requested_session, Direction::ToHarness, responder); + entry.setup_slot = setup_slot; + let id = self.pending.insert(entry); + let settlement = UpstreamSettlement { + id, + publication: self.publication.clone(), + }; + if prepared + .on_receiving_result(move |result| { + settlement.complete(result); + std::future::ready(Ok(())) + }) + .is_err() + && let Some((_, outcome, responder)) = + self.pending.deliver(id, connection_terminated_error) + { + // Registration failed, so the request was never published and no + // callback will run. Answer here, still inside bridge order. + let _ = responder.respond_with_result(outcome); + } + } + + /// Publish a harness request upstream with ordered response selection. + fn forward_request_upstream( + &self, + request: UntypedMessage, + responder: Responder, + method: String, + ) { + let prepared = self + .upstream + .prepare_request_to(Client, request) + .forwarded_from(&responder); + self.publication + .wire + .expect_reply(Peer::Client, prepared.raw_id(), responder.raw_id()); + let id = self.pending.insert(PendingEntry::new( + method, + None, + Direction::ToClient, + responder, + )); + let settlement = DownstreamSettlement { + id, + publication: self.publication.clone(), + }; + if prepared + .on_receiving_result(move |result| { + settlement.complete(result); + std::future::ready(Ok(())) + }) + .is_err() + && let Some((_, outcome, responder)) = + self.pending.deliver(id, connection_terminated_error) + { + let _ = responder.respond_with_result(outcome); + } + } + + fn deliver_to_downstream(&self, id: u64) { + // When the client-facing input has closed, the SDK fails every request + // the harness sent to it with a clean-EOF error. That automatic + // failure is not a client decision, and forwarding it before the + // synthetic session cancellation would let the harness treat a + // permission request as denied and finish the prompt. Leave the entry + // pending; the shutdown sweep answers it after the cancellations. A + // genuine answer the client already gave is still delivered in order. + if self.upstream.is_incoming_closed() + && self.shutdown.is_closing() + && self + .pending + .get(id) + .is_some_and(|entry| entry.is_clean_eof_failure()) + { + return; + } + if let Some((_, outcome, responder)) = self.pending.deliver(id, shutting_down_error) { + let _ = responder.respond_with_result(outcome); + } + } + + fn deliver_to_upstream(&self, id: u64) { + if let Some(delivery) = self.pending.deliver(id, connection_terminated_error) { + self.answer_client_request(delivery); + } + } + + /// Answer a request that travelled harness -> client. + /// + /// A successful session setup observed here is registered before any + /// answer. If its completion is processed after the first shutdown cause, + /// the client receives the fixed `proxy_shutting_down` refusal instead of + /// a success it could no longer account for: the SDK's notification route + /// only proves queue admission, not that the harness application received + /// the cancellation. The observed session id is still tracked, and the + /// cancellation is attempted exactly once, ordered after the accepted + /// client-to-harness prefix. + fn answer_client_request(&self, delivery: PendingDelivery) { + let (entry, outcome, responder) = delivery; + let mut outcome = outcome; + if let Ok(result) = &outcome { + if entry.method == "initialize" { + let mut caps = self.mcp.lock().unwrap_or_else(|error| error.into_inner()); + *caps = SessionMcpCapabilities::from_initialize(result); + } + let observed = + self.sessions + .observe(&entry.method, entry.requested_session.as_deref(), result); + if self.shutdown.is_closing() && is_session_setup(&entry.method) { + if let Some(session_id) = observed + && self.sessions.begin_cancel(&session_id) + { + let _ = self.send_session_cancel(&session_id); + } + outcome = Err(shutting_down_error(&entry.method)); + } + } + let _ = responder.respond_with_result(outcome); + } + + /// Cancel every session observed so far, at most once per session. + /// + /// Called only after the accepted client-to-harness prefix has been + /// forwarded, never from the cause handler, so a synthetic cancellation + /// cannot overtake a queued permission answer or a client notification. + /// The sweep copies at most [`QUEUE_BATCH`] ids per poll and yields, so a + /// very large session set cannot delay the absolute deadline. + async fn cancel_registered_sessions(&self, stop: Instant) { + loop { + let ids = self.sessions.begin_cancellations(QUEUE_BATCH); + if ids.is_empty() { + return; + } + for session_id in &ids { + let _ = self.send_session_cancel(session_id); + } + if deadline_reached(stop) { + return; + } + yield_now().await; + } + } + + fn send_session_cancel(&self, session_id: &str) -> bool { + let Ok(notification) = UntypedMessage::new( + "session/cancel", + serde_json::json!({ "sessionId": session_id }), + ) else { + return false; + }; + self.downstream + .send_notification_to(Agent, notification) + .is_ok() + } + + /// Run the explicit shutdown phases. The physical flush is not a phase + /// here: it is the SDK's finish contract for the client-facing connection, + /// which runs after this foreground returns success. + /// + /// Returns `true` when the frozen prefix was not fully delivered, either + /// because the hard deadline stopped a phase or because a request is still + /// pending. The supervisor must not report that as a clean exit. + async fn finish( + &self, + to_downstream: &mut mpsc::UnboundedReceiver, + to_upstream: &mut mpsc::UnboundedReceiver, + ) -> bool { + let hard_deadline = self.shutdown.hard_deadline(); + // Phase 1: fence the client-to-harness traffic accepted before the + // cause, in wire order. A queued permission answer therefore reaches + // the harness before the synthetic cancellation below. + self.pump_downstream(to_downstream, hard_deadline).await; + // Phase 2: cancellation follows that accepted prefix, once per live + // session. + self.cancel_registered_sessions(hard_deadline).await; + // Phase 3: settle accepted in-flight requests at their own queued + // events until the settle budget expires, then freeze one finite + // producer-side cutoff and answer whatever remains with fixed errors. + self.settle_pending(to_downstream, to_upstream).await; + // Phase 4: let the downstream foreground close the harness stdin. The + // SDK drains the downstream sink before that driver returns. + self.shutdown.publish_close(); + // The queues were frozen in phase 3, so they cannot grow here. Any + // entry still present, or any ticket still unanswered, is an accepted + // prefix the deadline abandoned. + !to_downstream.is_empty() || !to_upstream.is_empty() || !self.pending.is_empty() + } + + async fn settle_pending( + &self, + to_downstream: &mut mpsc::UnboundedReceiver, + to_upstream: &mut mpsc::UnboundedReceiver, + ) { + let settle_deadline = self + .shutdown + .drain_deadline() + .min(self.shutdown.hard_deadline()); + let mut terminated = Box::pin(self.downstream.terminated()); + + loop { + self.pump_both(to_downstream, to_upstream, settle_deadline) + .await; + self.cancel_registered_sessions(settle_deadline).await; + if self.pending.is_empty() || deadline_reached(settle_deadline) { + break; + } + tokio::select! { + biased; + _ = &mut terminated => break, + _ = sleep_until(settle_deadline) => break, + event = to_downstream.recv() => { + if let Some(event) = event { + let _ = self.handle_to_downstream(event); + } + } + event = to_upstream.recv() => { + if let Some(event) = event { + let _ = self.handle_to_upstream(event); + } + } + } + } + + self.final_cutoff(to_downstream, to_upstream).await; + } + + /// Freeze both ordered queues at one producer-side marker and process the + /// resulting prefix to its end. + /// + /// Every producer that can append an event holds the same publication + /// lock, and this method appends both `Fence` markers under it. The + /// prefix is therefore finite and exactly the traffic accepted before the + /// cutoff; a response callback that loses the race is not recorded at all + /// and is owned by the fixed fallback sweep. Events are still processed in + /// FIFO order, so a real peer result is only delivered at its own queued + /// `Settle` event. + async fn final_cutoff( + &self, + to_downstream: &mut mpsc::UnboundedReceiver, + to_upstream: &mut mpsc::UnboundedReceiver, + ) { + let hard_deadline = self.shutdown.hard_deadline(); + let Some(fence) = self.publication.freeze() else { + return; + }; + // The client-to-harness direction first: cancellations and refusal + // answers generated while processing the other prefix must not + // overtake an accepted permission answer or client notification. + let _downstream_complete = self + .drain_downstream_to_fence(to_downstream, fence, hard_deadline) + .await; + if deadline_reached(hard_deadline) { + return; + } + self.cancel_registered_sessions(hard_deadline).await; + if deadline_reached(hard_deadline) { + return; + } + // Even when the harness sink is already unwritable, the client-facing + // direction must still be drained in order: its older updates are not + // made obsolete by a failed downstream write. + let _ = self + .drain_upstream_to_fence(to_upstream, fence, hard_deadline) + .await; + self.cancel_registered_sessions(hard_deadline).await; + if deadline_reached(hard_deadline) { + return; + } + // Only tickets whose `Settle` event was not part of the frozen prefix + // remain. They receive one fixed, correlated failure in acceptance + // order; the sweep never consults a recorded outcome, so it can neither + // overtake an older notification nor deliver the same request twice. + self.settle_remaining(Direction::ToClient, shutting_down_error, hard_deadline) + .await; + self.settle_remaining( + Direction::ToHarness, + connection_terminated_error, + hard_deadline, + ) + .await; + self.cancel_registered_sessions(hard_deadline).await; + } + + async fn settle_remaining( + &self, + direction: Direction, + fallback: fn(&str) -> Error, + stop: Instant, + ) { + loop { + if deadline_reached(stop) { + return; + } + let deliveries = self + .pending + .take_direction_batch(direction, QUEUE_BATCH, fallback); + if deliveries.is_empty() { + return; + } + for delivery in deliveries { + match direction { + Direction::ToClient => self.answer_client_request(delivery), + Direction::ToHarness => { + let (_, outcome, responder) = delivery; + let _ = responder.respond_with_result(outcome); + } + } + } + yield_now().await; + } + } + + async fn pump_both( + &self, + to_downstream: &mut mpsc::UnboundedReceiver, + to_upstream: &mut mpsc::UnboundedReceiver, + stop: Instant, + ) { + loop { + if deadline_reached(stop) { + return; + } + // Alternate one bounded batch per direction instead of draining + // one queue to a sampled-empty state before looking at the other. + let downstream = self.batch_downstream(to_downstream, stop); + let upstream = self.batch_upstream(to_upstream, stop); + if matches!(downstream, Batch::Idle) && matches!(upstream, Batch::Idle) { + return; + } + yield_now().await; + } + } + + /// Forward every already-queued client-to-harness event in bounded + /// batches, preserving wire order. + async fn pump_downstream( + &self, + to_downstream: &mut mpsc::UnboundedReceiver, + stop: Instant, + ) { + loop { + if matches!(self.batch_downstream(to_downstream, stop), Batch::Idle) { + return; + } + yield_now().await; + } + } + + /// Process one bounded batch of client-to-harness events. + fn batch_downstream( + &self, + to_downstream: &mut mpsc::UnboundedReceiver, + stop: Instant, + ) -> Batch { + for _ in 0..QUEUE_BATCH { + if deadline_reached(stop) { + return Batch::Idle; + } + match to_downstream.try_recv() { + Ok(event) => { + if let Ok(Handled::Fence(_)) = self.handle_to_downstream(event) { + return Batch::Idle; + } + } + Err(_) => return Batch::Idle, + } + } + Batch::Progressed + } + + /// Process one bounded batch of harness-to-client events. + fn batch_upstream( + &self, + to_upstream: &mut mpsc::UnboundedReceiver, + stop: Instant, + ) -> Batch { + for _ in 0..QUEUE_BATCH { + if deadline_reached(stop) { + return Batch::Idle; + } + match to_upstream.try_recv() { + Ok(event) => { + if let Ok(Handled::Fence(_)) = self.handle_to_upstream(event) { + return Batch::Idle; + } + } + Err(_) => return Batch::Idle, + } + } + Batch::Progressed + } + + /// Process the frozen client-to-harness prefix through its marker. + async fn drain_downstream_to_fence( + &self, + to_downstream: &mut mpsc::UnboundedReceiver, + fence: u64, + stop: Instant, + ) -> bool { + loop { + for _ in 0..QUEUE_BATCH { + if deadline_reached(stop) { + return false; + } + match to_downstream.try_recv() { + Ok(event) => { + let Ok(handled) = self.handle_to_downstream(event) else { + return false; + }; + if let Handled::Fence(id) = handled { + return id == fence; + } + } + Err(_) => return false, + } + } + yield_now().await; + } + } + + /// Process the frozen harness-to-client prefix through its marker. + async fn drain_upstream_to_fence( + &self, + to_upstream: &mut mpsc::UnboundedReceiver, + fence: u64, + stop: Instant, + ) -> bool { + loop { + for _ in 0..QUEUE_BATCH { + if deadline_reached(stop) { + return false; + } + match to_upstream.try_recv() { + Ok(event) => { + let Ok(handled) = self.handle_to_upstream(event) else { + return false; + }; + if let Handled::Fence(id) = handled { + return id == fence; + } + } + Err(_) => return false, + } + } + yield_now().await; + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Batch { + Idle, + Progressed, +} + +/// The ordered response callback's only work: record the typed result and +/// enqueue a constant-sized ticket. It never waits for the bridge. +struct UpstreamSettlement { + id: u64, + publication: Publication, +} + +impl UpstreamSettlement { + fn complete(self, result: Result) { + self.publication.complete_upstream(self.id, result); + } +} + +/// The same ordered contract for a request the harness sent to the client. +struct DownstreamSettlement { + id: u64, + publication: Publication, +} + +impl DownstreamSettlement { + fn complete(self, result: Result) { + self.publication.complete_downstream(self.id, result); + } +} + +async fn downstream_until_terminated( + downstream: ConnectionTo, + shutdown: Shutdown, +) -> Result<(), Error> { + let mut close_rx = shutdown.subscribe_close(); + tokio::select! { + biased; + _ = wait_for_close(&mut close_rx) => Ok(()), + _ = downstream.incoming_closed() => { + // Publishing lets the bridge drain traffic already queued before + // the harness closed, including typed failures for requests still + // pending downstream. + shutdown.request(TerminationCause::HarnessExited); + Ok(()) + } + } +} + +/// Wait until the downstream close has been requested. +/// +/// Checking the stored value first makes a close published before this +/// receiver subscribed observable instead of waiting for a later change. +async fn wait_for_close(close: &mut watch::Receiver) { + loop { + if *close.borrow_and_update() { + return; + } + if close.changed().await.is_err() { + std::future::pending::<()>().await; + } + } +} + +/// Wait until the first shutdown cause publishes the absolute hard deadline. +async fn wait_for_hard_deadline(deadline: &mut watch::Receiver>) { + loop { + // Copy the instant out before awaiting: a `watch::Ref` held across an + // await would keep the watch value's read lock and block the claim. + let at = *deadline.borrow_and_update(); + if let Some(at) = at { + sleep_until(at).await; + return; + } + if deadline.changed().await.is_err() { + std::future::pending::<()>().await; + return; + } + } +} + +fn requested_session_for(method: &str, request: &UntypedMessage) -> Option { + if !matches!(method, "session/load" | "session/resume") { + return None; + } + request + .params() + .get("sessionId") + .and_then(Value::as_str) + .map(str::to_owned) +} + +/// Methods whose success creates or addresses a live downstream session. A +/// completion of one of these processed after shutdown is refused, because the +/// proxy cannot prove the harness application saw the cancellation. +fn is_session_setup(method: &str) -> bool { + matches!(method, "session/new" | "session/load" | "session/resume") +} + +#[derive(Default)] +struct SessionMcpCapabilities { + load: bool, + resume: bool, +} + +impl SessionMcpCapabilities { + fn from_initialize(result: &Value) -> Self { + let caps = &result["agentCapabilities"]; + Self { + load: caps["loadSession"].as_bool() == Some(true), + // A v1 resume capability is an optional object, not a boolean. + resume: caps["sessionCapabilities"]["resume"].is_object(), + } + } +} + +fn session_mcp_workspace(request: &UntypedMessage) -> Result { + let method = request.method(); + // Match the locked v1 types: null is empty for every setup, but only + // resume allows omission. Never parse/re-encode a caller declaration. + match request.params.get("mcpServers") { + Some(Value::Array(servers)) => { + if servers.iter().any(|server| { + server.get("name").and_then(Value::as_str) == Some(RUSTSCRIPT_MCP_NAME) + }) { + return Err(session_mcp_error(method, "mcp_server_name_conflict")); + } + } + Some(Value::Null) => {} + None if method == "session/resume" => {} + _ => return Err(session_mcp_error(method, "invalid_mcp_servers")), + } + request.params["cwd"] + .as_str() + .map(Path::new) + .filter(|cwd| cwd.is_absolute()) + .map(Path::to_path_buf) + .ok_or_else(|| session_mcp_error(method, "invalid_workspace")) +} + +async fn session_mcp_declaration( + cwd: PathBuf, + read_only: bool, + method: String, +) -> Result { + // Use the same independent blocking executor as the stdio endpoints. + // Tokio runtime shutdown must not wait for path I/O to return. + blocking::unblock(move || { + let workspace = cwd.canonicalize().ok().filter(|path| path.is_dir()); + let workspace = workspace + .as_deref() + .and_then(Path::to_str) + .ok_or_else(|| session_mcp_error(&method, "invalid_workspace"))?; + let exe = std::env::current_exe() + .ok() + .filter(|path| path.is_absolute()); + let exe = exe.as_deref().and_then(Path::to_str).ok_or_else(|| { + Error::internal_error().data(serde_json::json!({ + "method": method, "reason": "mcp_executable_unavailable", + })) + })?; + let mut args = vec!["tools", "serve", "--stdio", "--workspace", workspace]; + if read_only { + args.push("--read-only"); + } + Ok(serde_json::json!({ + "name": RUSTSCRIPT_MCP_NAME, "command": exe, "args": args, "env": [], + })) + }) + .await +} + +fn session_mcp_error(method: &str, reason: &'static str) -> Error { + Error::invalid_params().data(serde_json::json!({ "method": method, "reason": reason })) +} + +/// Fixed, sanitized JSON-RPC error for a request the peer never answered. +fn connection_terminated_error(method: &str) -> Error { + typed_error(method, CONNECTION_TERMINATED_REASON) +} + +/// Fixed, sanitized JSON-RPC error for work the proxy refused to admit. +fn shutting_down_error(method: &str) -> Error { + typed_error(method, PROXY_SHUTTING_DOWN_REASON) +} + +fn typed_error(method: &str, reason: &'static str) -> Error { + // Both values stay inside this process; the CLI maps the cause to a fixed + // code and never prints the peer's text. + Error::internal_error().data(serde_json::json!({ + "method": method, + "reason": reason, + })) +} + +async fn wait_for_shutdown_signal() { + #[cfg(unix)] + { + let Ok(mut terminate) = + tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) + else { + let _ = tokio::signal::ctrl_c().await; + return; + }; + tokio::select! { + _ = tokio::signal::ctrl_c() => {} + _ = terminate.recv() => {} + } + } + #[cfg(not(unix))] + { + let _ = tokio::signal::ctrl_c().await; + } +} + +#[cfg(test)] +mod tests { + use super::*; + use agent_client_protocol::{ + Channel, RawJsonRpcId, RawJsonRpcMessage, RawJsonRpcResponse, TransportFrame, + }; + use futures_util::StreamExt as _; + use std::time::Duration; + + /// One owned proxy-side agent connection plus its raw peer endpoint. + struct OwnedUpstream { + connection: ConnectionTo, + peer: Channel, + queued: mpsc::UnboundedReceiver, + task: tokio::task::JoinHandle>, + } + + /// A proxy-side `Agent` connection over a raw [`Channel`]. The peer keeps + /// the raw endpoint so the test can write requests and read the exact + /// outgoing frame order, without a second protocol implementation. + async fn owned_upstream() -> OwnedUpstream { + let (proxy_channel, peer) = Channel::duplex(); + let (connection_tx, connection_rx) = oneshot::channel(); + let (queued_tx, queued) = mpsc::unbounded_channel(); + let task = tokio::spawn( + Agent + .v1() + .on_receive_request( + async move |request: UntypedMessage, responder: Responder, _cx| { + let _ = queued_tx.send(ToDownstream::Message(Inbound::Request( + request, + Box::new(responder), + ))); + Ok(()) + }, + agent_client_protocol::on_receive_request!(), + ) + .on_receive_notification( + async move |_notification: UntypedMessage, _cx| Ok(()), + agent_client_protocol::on_receive_notification!(), + ) + .connect_with(proxy_channel, async move |connection| { + let _ = connection_tx.send(connection); + std::future::pending::>().await + }), + ); + let connection = connection_rx.await.expect("upstream foreground ran"); + OwnedUpstream { + connection, + peer, + queued, + task, + } + } + + /// The downstream half a [`Bridge`] requires. + struct OwnedDownstream { + connection: ConnectionTo, + peer: Channel, + queued: mpsc::UnboundedReceiver, + task: tokio::task::JoinHandle>, + } + + async fn owned_downstream() -> OwnedDownstream { + let (proxy_channel, peer) = Channel::duplex(); + let (connection_tx, connection_rx) = oneshot::channel(); + let (queued_tx, queued) = mpsc::unbounded_channel(); + let task = tokio::spawn( + Client + .v1() + .on_receive_request( + async move |request: UntypedMessage, responder: Responder, _cx| { + let _ = queued_tx.send(ToDownstream::Message(Inbound::Request( + request, + Box::new(responder), + ))); + Ok(()) + }, + agent_client_protocol::on_receive_request!(), + ) + .on_receive_notification( + async move |_notification: UntypedMessage, _cx| Ok(()), + agent_client_protocol::on_receive_notification!(), + ) + .connect_with( + proxy_channel, + async move |connection: ConnectionTo| { + let _ = connection_tx.send(connection); + std::future::pending::>().await + }, + ), + ); + let connection = connection_rx.await.expect("downstream foreground ran"); + OwnedDownstream { + connection, + peer, + queued, + task, + } + } + + /// Send one raw request to the proxy-side agent connection and take the + /// responder the real dispatch handler queued. + async fn send_raw_request( + upstream: &mut OwnedUpstream, + id: i64, + method: &str, + ) -> Responder { + upstream + .peer + .tx + .unbounded_send(TransportFrame::Single( + RawJsonRpcMessage::request(method.to_owned(), serde_json::json!({}), id) + .expect("raw request"), + )) + .expect("peer open"); + let ToDownstream::Message(Inbound::Request(_, responder)) = upstream + .queued + .recv() + .await + .expect("dispatch queued the request") + else { + panic!("expected a dispatched request"); + }; + *responder + } + + fn update_message(text: &str) -> UntypedMessage { + UntypedMessage::new( + "session/update", + serde_json::json!({ + "sessionId": "fixture", + "update": { + "sessionUpdate": "agent_message_chunk", + "content": { "type": "text", "text": text } + } + }), + ) + .expect("session/update notification") + } + + fn response_result(frame: &TransportFrame) -> Option<(&RawJsonRpcId, &Value)> { + match frame { + TransportFrame::Single(RawJsonRpcMessage::Response(RawJsonRpcResponse::Result { + id, + result, + })) => Some((id, result)), + _ => None, + } + } + + fn response_error( + frame: &TransportFrame, + ) -> Option<(&RawJsonRpcId, &agent_client_protocol::RawJsonRpcError)> { + match frame { + TransportFrame::Single(RawJsonRpcMessage::Response(RawJsonRpcResponse::Error { + id, + error, + })) => Some((id, error)), + _ => None, + } + } + + async fn next_frame(peer: &mut Channel) -> TransportFrame { + tokio::time::timeout(Duration::from_secs(2), peer.rx.next()) + .await + .expect("proxy emitted the expected frame") + .expect("peer still open") + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn cutoff_keeps_reverse_acceptance_results_at_their_fifo_events() { + let mut upstream = owned_upstream().await; + let downstream = owned_downstream().await; + let (to_downstream_tx, mut to_downstream_rx) = mpsc::unbounded_channel(); + let (to_upstream_tx, mut to_upstream_rx) = mpsc::unbounded_channel(); + let pending = Arc::new(PendingRegistry::default()); + let publication = Publication::new( + Arc::clone(&pending), + to_downstream_tx.clone(), + to_upstream_tx.clone(), + ); + let shutdown = Shutdown::new(); + shutdown.claim(TerminationCause::ClientEof); + let upstream_connection = upstream.connection.clone(); + let downstream_connection = downstream.connection.clone(); + let bridge = Bridge { + upstream: &upstream_connection, + downstream: &downstream_connection, + pending: Arc::clone(&pending), + publication: publication.clone(), + sessions: SessionRegistry::default(), + shutdown: shutdown.clone(), + mcp: Mutex::default(), + }; + + // Acceptance order is A then B; the peer answers B then A. + let responder_a = send_raw_request(&mut upstream, 1, "fixture/a").await; + let responder_b = send_raw_request(&mut upstream, 2, "fixture/b").await; + let a = pending.insert(PendingEntry::new( + "fixture/a".to_owned(), + None, + Direction::ToHarness, + responder_a, + )); + let b = pending.insert(PendingEntry::new( + "fixture/b".to_owned(), + None, + Direction::ToHarness, + responder_b, + )); + assert!(a < b, "tickets must follow acceptance order"); + + // An older ordinary update, then the two results in reverse order. + assert!( + publication + .admit_to_upstream(ToUpstream::Message(Inbound::Notification(update_message( + "older-update" + )))) + .is_ok(), + "update admitted before the cutoff" + ); + publication.complete_upstream(b, Ok(serde_json::json!({ "which": "b" }))); + publication.complete_upstream(a, Ok(serde_json::json!({ "which": "a" }))); + + bridge + .final_cutoff(&mut to_downstream_rx, &mut to_upstream_rx) + .await; + + let first = next_frame(&mut upstream.peer).await; + match &first { + TransportFrame::Single(RawJsonRpcMessage::Notification(notification)) => { + assert_eq!(&*notification.method, "session/update"); + } + other => panic!("expected the older update first, got {other:?}"), + } + let second = next_frame(&mut upstream.peer).await; + let (id_b, result_b) = + response_result(&second).expect("second frame answers B in its own event"); + assert_eq!(id_b, &RawJsonRpcId::Number(2)); + assert_eq!(result_b, &serde_json::json!({ "which": "b" })); + let third = next_frame(&mut upstream.peer).await; + let (id_a, result_a) = + response_result(&third).expect("third frame answers A in its own event"); + assert_eq!(id_a, &RawJsonRpcId::Number(1)); + assert_eq!(result_a, &serde_json::json!({ "which": "a" })); + + upstream.task.abort(); + downstream.task.abort(); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn cutoff_late_publication_loses_to_one_ordered_fixed_fallback() { + let mut upstream = owned_upstream().await; + let downstream = owned_downstream().await; + let (to_downstream_tx, mut to_downstream_rx) = mpsc::unbounded_channel(); + let (to_upstream_tx, mut to_upstream_rx) = mpsc::unbounded_channel(); + let pending = Arc::new(PendingRegistry::default()); + let publication = Publication::new( + Arc::clone(&pending), + to_downstream_tx.clone(), + to_upstream_tx.clone(), + ); + let shutdown = Shutdown::new(); + shutdown.claim(TerminationCause::ClientEof); + let upstream_connection = upstream.connection.clone(); + let downstream_connection = downstream.connection.clone(); + let bridge = Bridge { + upstream: &upstream_connection, + downstream: &downstream_connection, + pending: Arc::clone(&pending), + publication: publication.clone(), + sessions: SessionRegistry::default(), + shutdown: shutdown.clone(), + mcp: Mutex::default(), + }; + + let responder_a = send_raw_request(&mut upstream, 1, "fixture/a").await; + let responder_b = send_raw_request(&mut upstream, 2, "fixture/b").await; + let a = pending.insert(PendingEntry::new( + "fixture/a".to_owned(), + None, + Direction::ToHarness, + responder_a, + )); + let b = pending.insert(PendingEntry::new( + "fixture/b".to_owned(), + None, + Direction::ToHarness, + responder_b, + )); + + assert!( + publication + .admit_to_upstream(ToUpstream::Message(Inbound::Notification(update_message( + "older-update" + )))) + .is_ok(), + "update admitted before the cutoff" + ); + publication.complete_upstream(b, Ok(serde_json::json!({ "which": "b" }))); + // More than one batch of accepted downstream traffic keeps the cutoff + // suspended between batches while A's result is published into the + // opposite queue. The fence was already appended, so that publication + // cannot join the prefix. + for _ in 0..(QUEUE_BATCH * 2) { + assert!( + to_downstream_tx + .send(ToDownstream::Settle { id: u64::MAX }) + .is_ok(), + "downstream queue open" + ); + } + let late = async { + publication.complete_upstream(a, Ok(serde_json::json!({ "which": "a" }))); + }; + tokio::join!( + bridge.final_cutoff(&mut to_downstream_rx, &mut to_upstream_rx), + late + ); + + let first = next_frame(&mut upstream.peer).await; + match &first { + TransportFrame::Single(RawJsonRpcMessage::Notification(notification)) => { + assert_eq!(&*notification.method, "session/update"); + } + other => panic!("expected the older update first, got {other:?}"), + } + let second = next_frame(&mut upstream.peer).await; + let (id_b, result_b) = + response_result(&second).expect("the prefix result answers B at its event"); + assert_eq!(id_b, &RawJsonRpcId::Number(2)); + assert_eq!(result_b, &serde_json::json!({ "which": "b" })); + let third = next_frame(&mut upstream.peer).await; + let (id_a, error_a) = + response_error(&third).expect("the late publication gets the fixed fallback"); + assert_eq!(id_a, &RawJsonRpcId::Number(1)); + let data_a = error_a.data.value().expect("fallback error carries data"); + assert_eq!(data_a["method"], serde_json::json!("fixture/a")); + assert_eq!( + data_a["reason"], + serde_json::json!(CONNECTION_TERMINATED_REASON) + ); + // No fourth frame: exactly one terminal outcome, and no result extracted + // ahead of the older notification or a later settlement. + let extra = tokio::time::timeout(Duration::from_millis(100), upstream.peer.rx.next()).await; + assert!( + extra.is_err() || extra.expect("poll").is_none(), + "a late publication must not produce a second outcome" + ); + + upstream.task.abort(); + downstream.task.abort(); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn cutoff_does_not_extract_a_recorded_result_outside_its_event() { + let mut upstream = owned_upstream().await; + let downstream = owned_downstream().await; + let (to_downstream_tx, mut to_downstream_rx) = mpsc::unbounded_channel(); + let (to_upstream_tx, mut to_upstream_rx) = mpsc::unbounded_channel(); + let pending = Arc::new(PendingRegistry::default()); + let publication = Publication::new( + Arc::clone(&pending), + to_downstream_tx.clone(), + to_upstream_tx.clone(), + ); + let shutdown = Shutdown::new(); + shutdown.claim(TerminationCause::ClientEof); + let upstream_connection = upstream.connection.clone(); + let downstream_connection = downstream.connection.clone(); + let bridge = Bridge { + upstream: &upstream_connection, + downstream: &downstream_connection, + pending: Arc::clone(&pending), + publication: publication.clone(), + sessions: SessionRegistry::default(), + shutdown: shutdown.clone(), + mcp: Mutex::default(), + }; + + let responder_a = send_raw_request(&mut upstream, 1, "fixture/a").await; + let responder_b = send_raw_request(&mut upstream, 2, "fixture/b").await; + let a = pending.insert(PendingEntry::new( + "fixture/a".to_owned(), + None, + Direction::ToHarness, + responder_a, + )); + let b = pending.insert(PendingEntry::new( + "fixture/b".to_owned(), + None, + Direction::ToHarness, + responder_b, + )); + + // A's result is recorded, but its ordered ticket never reaches the + // queue before the cutoff (the callback was preempted between the two + // steps the SDK route performs). B's ticket is queued, and an older + // update precedes both. + assert!( + to_upstream_tx + .send(ToUpstream::Message(Inbound::Notification(update_message( + "older-update" + )))) + .is_ok() + ); + let entry_b = pending.get(b).expect("ticket b"); + assert!(entry_b.complete(Ok(serde_json::json!({ "which": "b" })))); + assert!(to_upstream_tx.send(ToUpstream::Settle { id: b }).is_ok()); + let entry_a = pending.get(a).expect("ticket a"); + assert!(entry_a.complete(Ok(serde_json::json!({ "which": "a" })))); + + // The settle window is already over, so `finish` goes straight to the + // cutoff, but the absolute deadline still has room. + { + let mut state = shutdown + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + *state = Some(ShutdownState { + cause: TerminationCause::ClientEof, + started: Instant::now() - SHUTDOWN_SETTLE_BUDGET + Duration::from_millis(150), + }); + } + + bridge + .finish(&mut to_downstream_rx, &mut to_upstream_rx) + .await; + + let first = next_frame(&mut upstream.peer).await; + match &first { + TransportFrame::Single(RawJsonRpcMessage::Notification(notification)) => { + assert_eq!(&*notification.method, "session/update"); + } + other => panic!("expected the older update first, got {other:?}"), + } + let second = next_frame(&mut upstream.peer).await; + let (id_b, result_b) = + response_result(&second).expect("B's real result belongs to its own event"); + assert_eq!(id_b, &RawJsonRpcId::Number(2)); + assert_eq!(result_b, &serde_json::json!({ "which": "b" })); + let third = next_frame(&mut upstream.peer).await; + let (id_a, error_a) = response_error(&third) + .expect("a recorded result outside the prefix must become the fixed fallback"); + assert_eq!(id_a, &RawJsonRpcId::Number(1)); + let data_a = error_a.data.value().expect("fallback error carries data"); + assert_eq!(data_a["method"], serde_json::json!("fixture/a")); + assert_eq!( + data_a["reason"], + serde_json::json!(CONNECTION_TERMINATED_REASON) + ); + let extra = tokio::time::timeout(Duration::from_millis(100), upstream.peer.rx.next()).await; + assert!( + extra.is_err() || extra.expect("poll").is_none(), + "the recorded result must not be delivered twice" + ); + + upstream.task.abort(); + downstream.task.abort(); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn cutoff_sweeps_the_harness_direction_with_its_own_fixed_error() { + let upstream = owned_upstream().await; + let mut downstream = owned_downstream().await; + let (to_downstream_tx, mut to_downstream_rx) = mpsc::unbounded_channel(); + let (to_upstream_tx, mut to_upstream_rx) = mpsc::unbounded_channel(); + let pending = Arc::new(PendingRegistry::default()); + let publication = Publication::new( + Arc::clone(&pending), + to_downstream_tx.clone(), + to_upstream_tx.clone(), + ); + let shutdown = Shutdown::new(); + shutdown.claim(TerminationCause::ClientEof); + let upstream_connection = upstream.connection.clone(); + let downstream_connection = downstream.connection.clone(); + let bridge = Bridge { + upstream: &upstream_connection, + downstream: &downstream_connection, + pending: Arc::clone(&pending), + publication: publication.clone(), + sessions: SessionRegistry::default(), + shutdown: shutdown.clone(), + mcp: Mutex::default(), + }; + + // The harness asks the client for permission; the request is accepted + // but its response ticket never joins the frozen prefix. + downstream + .peer + .tx + .unbounded_send(TransportFrame::Single( + RawJsonRpcMessage::request( + "session/request_permission".to_owned(), + serde_json::json!({ "sessionId": "fixture" }), + 7, + ) + .expect("raw request"), + )) + .expect("peer open"); + let ToDownstream::Message(Inbound::Request(_, responder)) = downstream + .queued + .recv() + .await + .expect("dispatch queued the request") + else { + panic!("expected a dispatched request"); + }; + let id = pending.insert(PendingEntry::new( + "session/request_permission".to_owned(), + None, + Direction::ToClient, + *responder, + )); + assert!(pending.get(id).expect("ticket").complete(Ok( + serde_json::json!({ "outcome": { "outcome": "selected" } }) + ))); + + bridge + .final_cutoff(&mut to_downstream_rx, &mut to_upstream_rx) + .await; + + let frame = next_frame(&mut downstream.peer).await; + let (id_reply, error) = + response_error(&frame).expect("the harness direction gets its fixed fallback"); + assert_eq!(id_reply, &RawJsonRpcId::Number(7)); + let data = error.data.value().expect("fallback error carries data"); + assert_eq!( + data["method"], + serde_json::json!("session/request_permission") + ); + assert_eq!( + data["reason"], + serde_json::json!(PROXY_SHUTTING_DOWN_REASON) + ); + let extra = + tokio::time::timeout(Duration::from_millis(100), downstream.peer.rx.next()).await; + assert!( + extra.is_err() || extra.expect("poll").is_none(), + "the harness request must receive exactly one outcome" + ); + + upstream.task.abort(); + downstream.task.abort(); + } + + /// Production-shaped client-facing driver whose bridge queues stay + /// borrowed, so a test can poll the supervisor and inspect them between + /// polls. Admission and the upstream watch match `build_proxy`. + #[allow(clippy::too_many_arguments)] + async fn proxy_side_driver( + channel: Channel, + readiness: oneshot::Receiver>, + shutdown: Shutdown, + publication: Publication, + pending: Arc, + upstream_watch: Arc>>>, + to_downstream: &mut mpsc::UnboundedReceiver, + to_upstream: &mut mpsc::UnboundedReceiver, + ) -> Result<(), Error> { + let request_admission = shutdown.clone(); + let requests = publication.clone(); + let notification_admission = shutdown.clone(); + let notifications = publication.clone(); + let bridge_shutdown = shutdown.clone(); + Agent + .v1() + .on_receive_request( + async move |request: UntypedMessage, responder: Responder, _cx| { + if request_admission.is_closing() { + let _ = responder + .respond_with_result(Err(shutting_down_error(request.method()))); + return Ok(()); + } + let _ = requests.admit_to_downstream(ToDownstream::Message(Inbound::Request( + request, + Box::new(responder), + ))); + Ok(()) + }, + agent_client_protocol::on_receive_request!(), + ) + .on_receive_notification( + async move |notification: UntypedMessage, _cx| { + if notification_admission.is_closing() { + return Ok(()); + } + let _ = notifications.admit_to_downstream(ToDownstream::Message( + Inbound::Notification(notification), + )); + Ok(()) + }, + agent_client_protocol::on_receive_notification!(), + ) + .connect_with(channel, { + let to_downstream = &mut *to_downstream; + let to_upstream = &mut *to_upstream; + async move |upstream: ConnectionTo| { + *upstream_watch + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(upstream.clone()); + let _ = drive_upstream( + upstream, + readiness, + to_downstream, + to_upstream, + bridge_shutdown, + pending, + SessionRegistry::default(), + publication, + false, + ) + .await; + Ok(()) + } + }) + .await + } + + /// Build the proxy-side agent connection around [`drive_upstream`] with a + /// controllable readiness counterpart. This tests the real bridge under a + /// driver this test owns, without a packaged process boundary. + async fn proxy_side( + channel: Channel, + readiness: oneshot::Receiver>, + shutdown: Shutdown, + accepted: mpsc::UnboundedSender<()>, + ) -> Result<(), Error> { + let (to_downstream_tx, mut to_downstream_rx) = mpsc::unbounded_channel(); + let (to_upstream_tx, mut to_upstream_rx) = mpsc::unbounded_channel(); + let pending = Arc::new(PendingRegistry::default()); + let publication = Publication::new( + Arc::clone(&pending), + to_downstream_tx.clone(), + to_upstream_tx.clone(), + ); + let request_admission = shutdown.clone(); + let requests = publication.clone(); + let notification_admission = shutdown.clone(); + let notifications = publication.clone(); + Agent + .v1() + .on_receive_request( + async move |request: UntypedMessage, responder: Responder, _cx| { + if request_admission.is_closing() { + let _ = responder + .respond_with_result(Err(shutting_down_error(request.method()))); + return Ok(()); + } + let _ = requests.admit_to_downstream(ToDownstream::Message(Inbound::Request( + request, + Box::new(responder), + ))); + let _ = accepted.send(()); + Ok(()) + }, + agent_client_protocol::on_receive_request!(), + ) + .on_receive_notification( + async move |notification: UntypedMessage, _cx| { + if notification_admission.is_closing() { + return Ok(()); + } + let _ = notifications.admit_to_downstream(ToDownstream::Message( + Inbound::Notification(notification), + )); + Ok(()) + }, + agent_client_protocol::on_receive_notification!(), + ) + .connect_with(channel, { + let shutdown_for_bridge = shutdown.clone(); + let to_downstream = &mut to_downstream_rx; + let to_upstream = &mut to_upstream_rx; + async move |upstream: ConnectionTo| { + let _ = drive_upstream( + upstream, + readiness, + to_downstream, + to_upstream, + shutdown_for_bridge, + pending, + SessionRegistry::default(), + publication, + false, + ) + .await; + Ok(()) + } + }) + .await + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn readiness_failure_answers_an_already_accepted_initialize_once() { + let (client_channel, proxy_channel) = Channel::duplex(); + let (readiness_tx, readiness_rx) = oneshot::channel(); + let (accepted_tx, mut accepted_rx) = mpsc::unbounded_channel(); + let shutdown = Shutdown::new(); + let proxy_shutdown = shutdown.clone(); + let proxy = tokio::spawn(proxy_side( + proxy_channel, + readiness_rx, + proxy_shutdown, + accepted_tx, + )); + + let (response_tx, response_rx) = oneshot::channel(); + let client = tokio::spawn(Client.v1().connect_with( + client_channel, + async move |connection: ConnectionTo| { + let request = + UntypedMessage::new("initialize", serde_json::json!({ "protocolVersion": 1 }))?; + let result = connection + .prepare_request_to(Agent, request) + .block_task() + .await; + let _ = response_tx.send(result); + Ok(()) + }, + )); + + // Wait until the request is inside the bridge queue, then fail + // readiness. The failure is therefore guaranteed to find accepted work. + accepted_rx.recv().await.expect("initialize was accepted"); + drop(readiness_tx); + + let error = response_rx + .await + .expect("client received a terminal outcome") + .expect_err("readiness failure must answer with a fixed error"); + assert_eq!(error.code.value(), -32603); + assert_eq!( + error.data.as_ref().and_then(|data| data.get("method")), + Some(&serde_json::json!("initialize")), + "the typed failure must be correlated with the request id/method: {error:?}" + ); + assert_eq!( + error.data.as_ref().and_then(|data| data.get("reason")), + Some(&serde_json::json!("proxy_shutting_down")) + ); + assert_eq!(shutdown.cause(), Some(TerminationCause::HarnessUnavailable)); + + tokio::time::timeout(Duration::from_secs(5), proxy) + .await + .expect("the bridge must finish after the readiness failure") + .expect("proxy task") + .expect("proxy connection"); + tokio::time::timeout(Duration::from_secs(5), client) + .await + .expect("the client must finish") + .expect("client task") + .expect("client connection"); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn client_eof_during_readiness_is_observed_without_waiting_for_the_harness() { + let (client_channel, proxy_channel) = Channel::duplex(); + let (readiness_tx, readiness_rx) = oneshot::channel(); + let (accepted_tx, _accepted_rx) = mpsc::unbounded_channel(); + let shutdown = Shutdown::new(); + let proxy_shutdown = shutdown.clone(); + let proxy = tokio::spawn(proxy_side( + proxy_channel, + readiness_rx, + proxy_shutdown, + accepted_tx, + )); + + // Keep the readiness sender alive: the harness is still starting. The + // client sends one request and closes its side immediately. + let _readiness_tx = readiness_tx; + let client = tokio::spawn(Client.v1().connect_with( + client_channel, + async move |connection: ConnectionTo| { + let request = + UntypedMessage::new("initialize", serde_json::json!({ "protocolVersion": 1 }))?; + connection.prepare_request_to(Agent, request).detach()?; + Ok(()) + }, + )); + + let proxy_result = tokio::time::timeout(Duration::from_secs(3), proxy) + .await + .expect("client EOF must be observed while readiness is still pending") + .expect("proxy task"); + // The typed failure may not be writable to a peer that closed both + // directions; the observed cause is what this case asserts. + let _ = proxy_result; + assert_eq!(shutdown.cause(), Some(TerminationCause::ClientEof)); + tokio::time::timeout(Duration::from_secs(5), client) + .await + .expect("the client must finish") + .expect("client task") + .expect("client connection"); + } + + /// Poll one driver future once without waiting for any wall clock, + /// returning its output when it finishes in this poll. `yield_now` stays + /// pending on its first poll, so the driver branch is always polled in the + /// same select. + async fn poll_once(driver: &mut std::pin::Pin>) -> Option + where + F: std::future::Future, + { + tokio::select! { + output = driver => Some(output), + _ = tokio::task::yield_now() => None, + } + } + + /// A real downstream connection is already sitting in the readiness slot + /// when the upstream driver is first polled, and a client EOF is already + /// pending on the same poll. The biased readiness select must take EOF and + /// seal publication. The notification buffered in the harness transport is + /// dispatched only when the downstream driver is polled again, after the + /// readiness branch answered the accepted request and sampled the residual + /// queues. Producing an event there would be silently dropped on the clean + /// exit the proxy just reported, so the seal must refuse it. + #[tokio::test(flavor = "current_thread")] + async fn interrupted_readiness_seals_late_downstream_dispatch() { + let (client_channel, client_peer) = Channel::duplex(); + let (mut client_rx, client_tx) = client_peer.into_parts(); + let (harness_channel, mut harness_peer) = Channel::duplex(); + let (downstream_ready_tx, mut downstream_ready_rx) = oneshot::channel(); + let (to_downstream_tx, mut to_downstream_rx) = mpsc::unbounded_channel(); + let (to_upstream_tx, mut to_upstream_rx) = mpsc::unbounded_channel(); + let pending = Arc::new(PendingRegistry::default()); + let publication = Publication::new( + Arc::clone(&pending), + to_downstream_tx.clone(), + to_upstream_tx.clone(), + ); + let shutdown = Shutdown::new(); + let upstream_watch: Arc>>> = Arc::new(Mutex::new(None)); + let downstream_ready_seen = Arc::new(AtomicBool::new(false)); + let dispatches = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let close_at_dispatch = Arc::new(AtomicBool::new(false)); + + // Prime the downstream driver first: its foreground publishes a real + // `ConnectionTo` and then parks on the close watch. The + // supervisor cannot poll it again until the readiness exit publishes + // close, after the residual snapshot. + let downstream_requests = publication.clone(); + let downstream_request_admission = shutdown.clone(); + let downstream_notifications = publication.clone(); + let downstream_dispatch_count = Arc::clone(&dispatches); + let downstream_close_at_dispatch = Arc::clone(&close_at_dispatch); + let downstream_dispatch_close = shutdown.subscribe_close(); + let downstream_shutdown = shutdown.clone(); + let mut downstream = Box::pin( + Client + .v1() + .on_receive_request( + async move |request: UntypedMessage, responder: Responder, _cx| { + if downstream_request_admission.is_closing() { + let _ = responder + .respond_with_result(Err(shutting_down_error(request.method()))); + return Ok(()); + } + if let Err(event) = downstream_requests.admit_to_upstream( + ToUpstream::Message(Inbound::Request(request, Box::new(responder))), + ) && let ToUpstream::Message(Inbound::Request(request, responder)) = + event + { + let _ = responder + .respond_with_result(Err(shutting_down_error(request.method()))); + } + Ok(()) + }, + agent_client_protocol::on_receive_request!(), + ) + .on_receive_notification( + async move |notification: UntypedMessage, _cx| { + // Production admission: the queue receiver belongs to + // the supervisor here, so only the publication seal can + // refuse this event once the readiness cutoff is + // claimed. + downstream_close_at_dispatch + .store(*downstream_dispatch_close.borrow(), Ordering::Release); + downstream_dispatch_count.fetch_add(1, Ordering::AcqRel); + let _ = downstream_notifications.admit_to_upstream(ToUpstream::Message( + Inbound::Notification(notification), + )); + Ok(()) + }, + agent_client_protocol::on_receive_notification!(), + ) + .connect_with( + harness_channel, + async move |downstream: ConnectionTo| { + let _ = downstream_ready_tx.send(downstream.clone()); + downstream_until_terminated(downstream, downstream_shutdown).await + }, + ), + ); + assert!( + poll_once(&mut downstream).await.is_none(), + "the downstream driver must park after publishing readiness" + ); + let downstream_connection = downstream_ready_rx + .try_recv() + .expect("the downstream foreground published its ready connection"); + + // Readiness is therefore available before the upstream driver exists; + // the queued client request is accepted during the same first poll that + // observes EOF, and the biased select must prefer EOF over readiness. + let (ready_tx, ready_rx) = oneshot::channel(); + ready_tx + .send(downstream_connection) + .expect("the readiness receiver is still open"); + client_tx + .unbounded_send(TransportFrame::Single( + RawJsonRpcMessage::request( + "initialize".to_owned(), + serde_json::json!({ "protocolVersion": 1 }), + 1, + ) + .expect("raw request"), + )) + .expect("client open"); + let upstream = proxy_side_driver( + client_channel, + ready_rx, + shutdown.clone(), + publication.clone(), + Arc::clone(&pending), + Arc::clone(&upstream_watch), + &mut to_downstream_rx, + &mut to_upstream_rx, + ); + drop(client_tx); + harness_peer + .tx + .unbounded_send(TransportFrame::Single( + RawJsonRpcMessage::notification( + "session/update".to_owned(), + serde_json::json!({ + "sessionId": "fixture", + "update": { + "sessionUpdate": "agent_message_chunk", + "content": { "type": "text", "text": "late-after-readiness" } + } + }), + ) + .expect("raw notification"), + )) + .expect("harness peer open"); + + let mut downstream_poll_close = shutdown.subscribe_close(); + let downstream_after_snapshot = async move { + wait_for_close(&mut downstream_poll_close).await; + downstream.await + }; + let mut supervisor = Box::pin(supervise_connections( + upstream, + downstream_after_snapshot, + shutdown.clone(), + upstream_watch.as_ref(), + downstream_ready_seen.as_ref(), + std::future::pending::<()>(), + )); + let outcome = tokio::time::timeout(Duration::from_secs(2), async { + loop { + if let Some(outcome) = poll_once(&mut supervisor).await { + break outcome; + } + } + }) + .await + .expect("the interrupted readiness path must finish"); + + assert_eq!(shutdown.cause(), Some(TerminationCause::ClientEof)); + assert_eq!( + dispatches.load(Ordering::Acquire), + 1, + "the buffered notification must reach the real downstream admission handler" + ); + assert!( + close_at_dispatch.load(Ordering::Acquire), + "the real SDK notification handler must run after the readiness residual snapshot" + ); + drop(supervisor); + let late = to_upstream_rx.try_recv(); + assert!( + !shutdown.residual(), + "the accepted request was answered, so no residual may be recorded" + ); + assert_eq!(outcome, Ok(ProxyDisposition::ClientEof)); + + let frame = tokio::time::timeout(Duration::from_secs(2), client_rx.next()) + .await + .expect("the accepted initialize receives exactly one outcome") + .expect("the client receive side stays open"); + let (id, error) = response_error(&frame).expect("initialize gets the fixed typed refusal"); + assert_eq!(id, &RawJsonRpcId::Number(1)); + assert_eq!(error.code, -32603); + let data = error.data.value().expect("refusal data"); + assert_eq!(data["method"], serde_json::json!("initialize")); + assert_eq!( + data["reason"], + serde_json::json!(PROXY_SHUTTING_DOWN_REASON) + ); + + let extra = tokio::time::timeout(Duration::from_secs(2), client_rx.next()) + .await + .expect("the client receive side must close cleanly"); + assert!( + extra.is_none(), + "the accepted request must receive exactly one outcome" + ); + let forwarded = + tokio::time::timeout(Duration::from_millis(100), harness_peer.rx.next()).await; + assert!( + forwarded.is_err() || forwarded.expect("poll").is_none(), + "the already-available readiness must not forward the queued initialize" + ); + + match late { + Err(_) => {} + Ok(ToUpstream::Message(Inbound::Notification(notification))) => panic!( + "late notification appended after the empty readiness residual snapshot: {}", + notification.method() + ), + Ok(_) => panic!("an unexpected event entered the supervisor-owned queue"), + } + + // Keep both queue senders alive through the observations above. + drop((to_downstream_tx, to_upstream_tx)); + } + + /// The same seal leaves an accepted prefix that the drain could not finish + /// queued, so the supervisor must see a residual and refuse a clean exit. + #[tokio::test(flavor = "current_thread")] + async fn interrupted_readiness_seal_keeps_undrained_accepted_prefix_residual() { + let _deadline_guard = test_deadline::reset_on_drop(); + let (to_downstream_tx, mut to_downstream_rx) = mpsc::unbounded_channel(); + let (to_upstream_tx, mut to_upstream_rx) = mpsc::unbounded_channel(); + let pending = Arc::new(PendingRegistry::default()); + let publication = Publication::new( + Arc::clone(&pending), + to_downstream_tx.clone(), + to_upstream_tx.clone(), + ); + let shutdown = Shutdown::new(); + shutdown.claim(TerminationCause::ClientEof); + + assert!( + publication + .admit_to_downstream(ToDownstream::Message(Inbound::Notification( + update_message("accepted-before-seal") + ))) + .is_ok(), + "the prefix must be accepted before the readiness cutoff" + ); + // The shared budget is exhausted before the drain can settle the + // accepted prefix; only the residual snapshot may classify that. + test_deadline::set(true); + seal_and_settle_unready( + &publication, + &shutdown, + &mut to_downstream_rx, + &mut to_upstream_rx, + ) + .await; + + assert!( + shutdown.residual(), + "an undrained accepted prefix must be reported as residual" + ); + assert!( + to_downstream_rx.try_recv().is_ok(), + "the undrained accepted event must stay queued for the supervisor" + ); + assert!( + publication + .admit_to_upstream(ToUpstream::Message(Inbound::Notification(update_message( + "above-seal" + )))) + .is_err(), + "the seal must still refuse an event dispatched after the snapshot" + ); + + drop((to_downstream_tx, to_upstream_tx)); + } + + /// What the client-to-harness queue looked like when the harness-side + /// driver was dropped. This guard stands in for the SDK's owned child + /// guard: the supervisor must escalate the harness before the accepted + /// prefix is disposed. + struct HarnessGuardProbe { + downstream: mpsc::UnboundedSender, + seen_closed: Arc>>, + } + + impl Drop for HarnessGuardProbe { + fn drop(&mut self) { + *self + .seen_closed + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = + Some(self.downstream.is_closed()); + } + } + + /// The deadline becomes ready while the real upstream driver is midway + /// through a bounded shutdown pass. The accepted prefix must still be in + /// the supervisor-owned queues when the harness guard is dropped, and the + /// abandoned prefix must not be reported as a clean exit. + #[tokio::test(flavor = "current_thread")] + async fn hard_deadline_keeps_the_accepted_prefix_until_the_harness_is_escalated() { + let _deadline_guard = test_deadline::reset_on_drop(); + let (client_channel, _client_peer) = Channel::duplex(); + let (harness_channel, _harness_peer) = Channel::duplex(); + let (downstream_ready_tx, downstream_ready_rx) = oneshot::channel(); + let (deadline_tx, deadline_rx) = oneshot::channel(); + let (to_downstream_tx, mut to_downstream_rx) = mpsc::unbounded_channel(); + let (to_upstream_tx, mut to_upstream_rx) = mpsc::unbounded_channel(); + let arm_drops = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let tail_drops = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let guard_closed = Arc::new(Mutex::new(None)); + let probe = HarnessGuardProbe { + downstream: to_downstream_tx.clone(), + seen_closed: Arc::clone(&guard_closed), + }; + let shutdown = Shutdown::new(); + let pending = Arc::new(PendingRegistry::default()); + let publication = Publication::new( + Arc::clone(&pending), + to_downstream_tx.clone(), + to_upstream_tx.clone(), + ); + let upstream_watch: Arc>>> = Arc::new(Mutex::new(None)); + let downstream_ready_seen = Arc::new(AtomicBool::new(false)); + + // The harness driver stands in for the SDK child-guard owner. It + // publishes its connection, then stays pending until the supervisor + // drops it. + let downstream = Client.v1().connect_with(harness_channel, { + async move |downstream: ConnectionTo| { + let _probe = probe; + let _ = downstream_ready_tx.send(downstream); + std::future::pending::>().await + } + }); + + let upstream = Agent + .v1() + .on_receive_request( + async move |_request: UntypedMessage, _responder: Responder, _cx| Ok(()), + agent_client_protocol::on_receive_request!(), + ) + .on_receive_notification( + async move |_notification: UntypedMessage, _cx| Ok(()), + agent_client_protocol::on_receive_notification!(), + ) + .connect_with(client_channel, { + let shutdown = shutdown.clone(); + // These are borrows: `run_proxy` (here, the test body) keeps + // ownership of both queues for the whole supervisor run. + let to_downstream = &mut to_downstream_rx; + let to_upstream = &mut to_upstream_rx; + async move |upstream: ConnectionTo| { + let _ = drive_upstream( + upstream, + downstream_ready_rx, + to_downstream, + to_upstream, + shutdown, + pending, + SessionRegistry::default(), + publication, + false, + ) + .await; + Ok(()) + } + }); + + let mut supervisor = Box::pin(supervise_connections( + upstream, + downstream, + shutdown.clone(), + upstream_watch.as_ref(), + downstream_ready_seen.as_ref(), + async move { + let _ = deadline_rx.await; + }, + )); + + // Poll once so the harness publishes its connection while the + // client-facing driver is still waiting for readiness. The queues are + // empty here, so nothing can be consumed in this poll. + poll_supervisor_once(&mut supervisor).await; + // Poll again with the close still unpublished: readiness resolves and + // the driver settles into its bridge loop. With empty queues that loop + // parks without dispatching anything. + poll_supervisor_once(&mut supervisor).await; + + // Now fill the queues and let the next poll break out of the bridge + // loop into `finish`. The first pump batch drains the notifications and + // reaches the arming sentinel, which marks the deadline as reached from + // inside that same upstream poll. The counting tail is the accepted + // remainder that must survive until the harness is escalated. + for index in 0..(QUEUE_BATCH - 1) { + to_downstream_tx + .send(ToDownstream::Message(Inbound::Notification( + update_message(&format!("queued-{index}")), + ))) + .expect("queue open"); + } + to_downstream_tx + .send(ToDownstream::Sentinel(test_queue::Sentinel::arming( + Arc::clone(&arm_drops), + ))) + .expect("queue open"); + for _ in 0..QUEUE_BATCH { + to_downstream_tx + .send(ToDownstream::Sentinel(test_queue::Sentinel::counting( + Arc::clone(&tail_drops), + ))) + .expect("queue open"); + } + + shutdown.claim(TerminationCause::ClientEof); + shutdown.publish_close(); + + // This poll observes the close first, enters `finish`, drains exactly + // one pump batch, and stops because the arming sentinel crossed the + // deadline inside the poll. + poll_supervisor_once(&mut supervisor).await; + assert_eq!( + arm_drops.load(std::sync::atomic::Ordering::Acquire), + 1, + "the poll must reach the arming sentinel inside the accepted prefix" + ); + + let _ = deadline_tx.send(()); + let result = tokio::time::timeout(Duration::from_secs(2), supervisor) + .await + .expect("the injected deadline must finish the supervisor"); + + let closed = guard_closed + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .take() + .expect("the harness driver was dropped"); + let disposed = tail_drops.load(std::sync::atomic::Ordering::Acquire); + assert!( + !closed, + "the harness guard must be escalated while the accepted prefix is still queued \ + (disposed tail sentinels: {disposed})" + ); + assert_eq!( + disposed, 0, + "the driver foreground must not dispose the supervisor-owned backlog" + ); + assert_eq!( + result, + Err(AcpProxyError::Transport), + "an accepted prefix abandoned by the deadline must not report a clean exit" + ); + assert_eq!(shutdown.cause(), Some(TerminationCause::ClientEof)); + } + + /// Poll the supervised drivers once without waiting for any wall clock. + /// `yield_now` stays pending on its first poll, so the supervisor branch is + /// always polled in the same select. + async fn poll_supervisor_once(supervisor: &mut std::pin::Pin>) + where + F: std::future::Future, + { + tokio::select! { + _ = supervisor => panic!("supervisor finished during setup"), + _ = tokio::task::yield_now() => {} + } + } + + /// Send `count` raw requests to `peer` and collect the responders the real + /// dispatch handler queued. The registry tests only need real responders; + /// the traffic is never forwarded in those cases. + async fn collect_responders( + peer: &mut Channel, + queued: &mut mpsc::UnboundedReceiver, + method_prefix: &str, + count: usize, + first_id: i64, + ) -> Vec> { + for offset in 0..count { + let id = first_id + offset as i64; + peer.tx + .unbounded_send(TransportFrame::Single( + RawJsonRpcMessage::request( + format!("{method_prefix}/{id}"), + serde_json::json!({}), + id, + ) + .expect("raw request"), + )) + .expect("peer open"); + } + let mut responders = Vec::with_capacity(count); + for _ in 0..count { + let ToDownstream::Message(Inbound::Request(_, responder)) = + queued.recv().await.expect("dispatch queued the request") + else { + panic!("expected a dispatched request"); + }; + responders.push(*responder); + } + responders + } + + fn outcome_is_recorded(entry: &PendingEntry) -> bool { + let state = entry.state.lock().expect("pending state"); + state.outcome.is_some() + } + + fn has_event_after_the_fence(receiver: &mut mpsc::UnboundedReceiver) -> bool { + receiver.try_recv().is_ok() + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn late_upstream_completion_after_freeze_does_not_touch_the_outcome_or_queue() { + let mut upstream = owned_upstream().await; + let downstream = owned_downstream().await; + let (to_downstream_tx, mut to_downstream_rx) = mpsc::unbounded_channel(); + let (to_upstream_tx, mut to_upstream_rx) = mpsc::unbounded_channel(); + let pending = Arc::new(PendingRegistry::default()); + let publication = Publication::new( + Arc::clone(&pending), + to_downstream_tx.clone(), + to_upstream_tx.clone(), + ); + let shutdown = Shutdown::new(); + shutdown.claim(TerminationCause::ClientEof); + let upstream_connection = upstream.connection.clone(); + let downstream_connection = downstream.connection.clone(); + let bridge = Bridge { + upstream: &upstream_connection, + downstream: &downstream_connection, + pending: Arc::clone(&pending), + publication: publication.clone(), + sessions: SessionRegistry::default(), + shutdown: shutdown.clone(), + mcp: Mutex::default(), + }; + + // Both requests are accepted before the cutoff. The early result is + // published before the freeze; the late result callback loses the + // race while the cutoff is suspended in the opposite queue. + let responder_early = send_raw_request(&mut upstream, 1, "fixture/early").await; + let responder_late = send_raw_request(&mut upstream, 2, "fixture/late").await; + let early = pending.insert(PendingEntry::new( + "fixture/early".to_owned(), + None, + Direction::ToHarness, + responder_early, + )); + let late = pending.insert(PendingEntry::new( + "fixture/late".to_owned(), + None, + Direction::ToHarness, + responder_late, + )); + let early_entry = pending.get(early).expect("early ticket"); + let late_entry = pending.get(late).expect("late ticket"); + + publication.complete_upstream(early, Ok(serde_json::json!({ "which": "early" }))); + assert!( + outcome_is_recorded(&early_entry), + "a completion before the freeze must be recorded" + ); + + for _ in 0..(QUEUE_BATCH * 2) { + assert!( + to_downstream_tx + .send(ToDownstream::Settle { id: u64::MAX }) + .is_ok(), + "downstream queue open" + ); + } + let late_completion = async { + publication.complete_upstream(late, Ok(serde_json::json!({ "which": "late" }))); + }; + tokio::join!( + bridge.final_cutoff(&mut to_downstream_rx, &mut to_upstream_rx), + late_completion + ); + + let outcome_recorded = outcome_is_recorded(&late_entry); + let settle_behind = has_event_after_the_fence(&mut to_upstream_rx); + assert!( + !outcome_recorded && !settle_behind, + "a completion that loses the freeze race must leave the outcome slot untouched \ + and append nothing behind the marker \ + (outcome_recorded={outcome_recorded}, settle_behind={settle_behind})" + ); + + let first = next_frame(&mut upstream.peer).await; + let (early_id, early_result) = + response_result(&first).expect("the early result belongs to its own event"); + assert_eq!(early_id, &RawJsonRpcId::Number(1)); + assert_eq!(early_result, &serde_json::json!({ "which": "early" })); + + let second = next_frame(&mut upstream.peer).await; + let (late_id, late_error) = + response_error(&second).expect("the late request gets one fixed fallback"); + assert_eq!(late_id, &RawJsonRpcId::Number(2)); + let data = late_error.data.value().expect("fallback data"); + assert_eq!(data["method"], serde_json::json!("fixture/late")); + assert_eq!( + data["reason"], + serde_json::json!(CONNECTION_TERMINATED_REASON) + ); + let extra = tokio::time::timeout(Duration::from_millis(100), upstream.peer.rx.next()).await; + assert!( + extra.is_err() || extra.expect("poll").is_none(), + "the late request must receive exactly one outcome" + ); + + upstream.task.abort(); + downstream.task.abort(); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn late_downstream_completion_after_freeze_does_not_touch_the_outcome_or_queue() { + let upstream = owned_upstream().await; + let mut downstream = owned_downstream().await; + let (to_downstream_tx, mut to_downstream_rx) = mpsc::unbounded_channel(); + let (to_upstream_tx, mut to_upstream_rx) = mpsc::unbounded_channel(); + let pending = Arc::new(PendingRegistry::default()); + let publication = Publication::new( + Arc::clone(&pending), + to_downstream_tx.clone(), + to_upstream_tx.clone(), + ); + let shutdown = Shutdown::new(); + shutdown.claim(TerminationCause::ClientEof); + let upstream_connection = upstream.connection.clone(); + let downstream_connection = downstream.connection.clone(); + let bridge = Bridge { + upstream: &upstream_connection, + downstream: &downstream_connection, + pending: Arc::clone(&pending), + publication: publication.clone(), + sessions: SessionRegistry::default(), + shutdown: shutdown.clone(), + mcp: Mutex::default(), + }; + + let responders = collect_responders( + &mut downstream.peer, + &mut downstream.queued, + "fixture", + 2, + 7, + ) + .await; + let mut responders = responders.into_iter(); + let early = pending.insert(PendingEntry::new( + "fixture/early".to_owned(), + None, + Direction::ToClient, + responders.next().expect("early responder"), + )); + let late = pending.insert(PendingEntry::new( + "fixture/late".to_owned(), + None, + Direction::ToClient, + responders.next().expect("late responder"), + )); + let early_entry = pending.get(early).expect("early ticket"); + let late_entry = pending.get(late).expect("late ticket"); + + publication.complete_downstream(early, Ok(serde_json::json!({ "which": "early" }))); + assert!( + outcome_is_recorded(&early_entry), + "a completion before the freeze must be recorded" + ); + + // The accepted upstream prefix suspends the cutoff after `freeze`, so + // the losing callback runs before the fixed sweep. + for _ in 0..(QUEUE_BATCH * 2) { + assert!( + to_upstream_tx + .send(ToUpstream::Settle { id: u64::MAX }) + .is_ok(), + "upstream queue open" + ); + } + let late_completion = async { + publication.complete_downstream(late, Ok(serde_json::json!({ "which": "late" }))); + }; + tokio::join!( + bridge.final_cutoff(&mut to_downstream_rx, &mut to_upstream_rx), + late_completion + ); + + let outcome_recorded = outcome_is_recorded(&late_entry); + let settle_behind = has_event_after_the_fence(&mut to_downstream_rx); + assert!( + !outcome_recorded && !settle_behind, + "a completion that loses the freeze race must leave the outcome slot untouched \ + and append nothing behind the marker \ + (outcome_recorded={outcome_recorded}, settle_behind={settle_behind})" + ); + + let first = next_frame(&mut downstream.peer).await; + let (early_id, early_result) = + response_result(&first).expect("the early result belongs to its own event"); + assert_eq!(early_id, &RawJsonRpcId::Number(7)); + assert_eq!(early_result, &serde_json::json!({ "which": "early" })); + + let second = next_frame(&mut downstream.peer).await; + let (late_id, late_error) = + response_error(&second).expect("the late harness request gets one fixed fallback"); + assert_eq!(late_id, &RawJsonRpcId::Number(8)); + let data = late_error.data.value().expect("fallback data"); + assert_eq!(data["method"], serde_json::json!("fixture/late")); + assert_eq!( + data["reason"], + serde_json::json!(PROXY_SHUTTING_DOWN_REASON) + ); + let extra = + tokio::time::timeout(Duration::from_millis(100), downstream.peer.rx.next()).await; + assert!( + extra.is_err() || extra.expect("poll").is_none(), + "the late harness request must receive exactly one outcome" + ); + + upstream.task.abort(); + downstream.task.abort(); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn direction_sweep_traverses_only_the_front_of_the_target_queue() { + let mut upstream = owned_upstream().await; + let pending = Arc::new(PendingRegistry::default()); + + // A large opposite-direction backlog: the sweep must never probe it. + let opposite_responders = collect_responders( + &mut upstream.peer, + &mut upstream.queued, + "fixture/opposite", + 64, + 1, + ) + .await; + let opposite: Vec<_> = opposite_responders + .into_iter() + .map(|responder| { + let id = pending.insert(PendingEntry::new( + "fixture/opposite".to_owned(), + None, + Direction::ToClient, + responder, + )); + pending.get(id).expect("opposite ticket") + }) + .collect(); + + // Empty target direction: no entry may be visited anywhere else. + assert!( + pending + .take_direction_batch(Direction::ToHarness, 4, shutting_down_error) + .is_empty(), + "an empty direction has nothing to sweep" + ); + assert!(opposite.iter().all(|entry| entry.visit_count() == 0)); + + // Mixed target: five eligible entries behind the opposite backlog. + let target_responders = collect_responders( + &mut upstream.peer, + &mut upstream.queued, + "fixture/target", + 5, + 1000, + ) + .await; + let target: Vec<_> = target_responders + .into_iter() + .map(|responder| { + let id = pending.insert(PendingEntry::new( + "fixture/target".to_owned(), + None, + Direction::ToHarness, + responder, + )); + pending.get(id).expect("target ticket") + }) + .collect(); + + let first = pending.take_direction_batch(Direction::ToHarness, 3, shutting_down_error); + assert_eq!(first.len(), 3); + assert!( + first + .iter() + .all(|(entry, _, _)| entry.direction == Direction::ToHarness), + "a sweep must not deliver an opposite-direction entry" + ); + assert_eq!(target[0].visit_count(), 1); + assert_eq!(target[1].visit_count(), 1); + assert_eq!(target[2].visit_count(), 1); + assert_eq!(target[3].visit_count(), 0); + assert_eq!(target[4].visit_count(), 0); + assert!(opposite.iter().all(|entry| entry.visit_count() == 0)); + + let second = pending.take_direction_batch(Direction::ToHarness, 3, shutting_down_error); + assert_eq!(second.len(), 2); + assert_eq!(target[3].visit_count(), 1); + assert_eq!(target[4].visit_count(), 1); + assert!( + target.iter().all(|entry| entry.visit_count() == 1), + "no already-selected target entry may be visited again" + ); + assert!(opposite.iter().all(|entry| entry.visit_count() == 0)); + + assert!( + pending + .take_direction_batch(Direction::ToHarness, 3, shutting_down_error) + .is_empty(), + "the exhausted target direction stays cheap" + ); + assert!(target.iter().all(|entry| entry.visit_count() == 1)); + assert!(opposite.iter().all(|entry| entry.visit_count() == 0)); + + upstream.task.abort(); + } + + #[test] + fn session_cancellations_consume_each_id_once_and_do_not_rescan() { + let sessions = SessionRegistry::default(); + assert!(sessions.begin_cancellations(QUEUE_BATCH).is_empty()); + assert_eq!(sessions.scanned(), 0); + + const TOTAL: usize = QUEUE_BATCH + 9; + let mut observed = Vec::new(); + for index in 0..TOTAL { + let id = format!("fixture-session-{index:03}"); + assert_eq!( + sessions + .observe("session/new", None, &serde_json::json!({ "sessionId": id })) + .as_deref(), + Some(id.as_str()) + ); + observed.push(id); + } + // Re-observing a live but not-yet-cancelled id must not duplicate it + // in the outstanding set. + assert!( + sessions + .observe( + "session/new", + None, + &serde_json::json!({ "sessionId": observed[0] }) + ) + .is_some() + ); + + let first = sessions.begin_cancellations(QUEUE_BATCH); + assert_eq!(first.len(), QUEUE_BATCH); + let second = sessions.begin_cancellations(QUEUE_BATCH); + assert_eq!(second.len(), TOTAL - QUEUE_BATCH); + assert_eq!( + sessions.scanned(), + TOTAL as u64, + "cancellation batches must examine only the ids they consume" + ); + let mut seen = HashSet::new(); + for id in first.into_iter().chain(second) { + assert!(seen.insert(id), "a synthetic cancellation repeated an id"); + } + assert_eq!(seen.len(), TOTAL); + + // A repeated successful setup of an already-cancelled id must not + // re-arm the synthetic cancellation or enqueue more traversal. + assert!( + sessions + .observe( + "session/new", + None, + &serde_json::json!({ "sessionId": observed[0] }) + ) + .is_some() + ); + assert!(sessions.begin_cancellations(QUEUE_BATCH).is_empty()); + assert_eq!(sessions.scanned(), TOTAL as u64); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn repeated_setup_of_the_same_session_during_shutdown_cancels_once() { + let upstream = owned_upstream().await; + let mut downstream = owned_downstream().await; + let (to_downstream_tx, _to_downstream_rx) = mpsc::unbounded_channel(); + let (to_upstream_tx, _to_upstream_rx) = mpsc::unbounded_channel(); + let pending = Arc::new(PendingRegistry::default()); + let publication = Publication::new(Arc::clone(&pending), to_downstream_tx, to_upstream_tx); + let shutdown = Shutdown::new(); + shutdown.claim(TerminationCause::ClientEof); + let sessions = SessionRegistry::default(); + let upstream_connection = upstream.connection.clone(); + let downstream_connection = downstream.connection.clone(); + let bridge = Bridge { + upstream: &upstream_connection, + downstream: &downstream_connection, + pending: Arc::clone(&pending), + publication, + sessions: sessions.clone(), + shutdown, + mcp: Mutex::default(), + }; + + let responders = collect_responders( + &mut downstream.peer, + &mut downstream.queued, + "fixture/setup", + 2, + 1, + ) + .await; + for responder in responders { + let id = pending.insert(PendingEntry::new( + "session/new".to_owned(), + None, + Direction::ToClient, + responder, + )); + let entry = pending.get(id).expect("setup ticket"); + assert!(entry.complete(Ok( + serde_json::json!({ "sessionId": "fixture-same-session" }) + ))); + let delivery = pending + .deliver(id, shutting_down_error) + .expect("recorded setup is deliverable"); + bridge.answer_client_request(delivery); + } + + let mut cancellations = 0; + let mut refusals = 0; + for _ in 0..3 { + let frame = next_frame(&mut downstream.peer).await; + match &frame { + TransportFrame::Single(RawJsonRpcMessage::Notification(notification)) => { + assert_eq!(&*notification.method, "session/cancel"); + cancellations += 1; + } + TransportFrame::Single(RawJsonRpcMessage::Response( + RawJsonRpcResponse::Error { error, .. }, + )) => { + assert_eq!(error.code, -32603); + let data = error.data.value().expect("refusal data"); + assert_eq!( + data["reason"], + serde_json::json!(PROXY_SHUTTING_DOWN_REASON) + ); + refusals += 1; + } + other => panic!("unexpected setup-shutdown frame: {other:?}"), + } + } + assert_eq!( + cancellations, 1, + "a repeated successful setup of the same session must not re-arm a cancel" + ); + assert_eq!(refusals, 2); + assert!(sessions.begin_cancellations(QUEUE_BATCH).is_empty()); + + upstream.task.abort(); + downstream.task.abort(); + } + + struct DropSpy { + name: &'static str, + order: Arc>>, + } + + impl Drop for DropSpy { + fn drop(&mut self) { + self.order + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .push(self.name); + } + } + + #[test] + fn supervisor_releases_the_harness_driver_before_the_client_driver() { + let order = Arc::new(Mutex::new(Vec::new())); + release_drivers( + DropSpy { + name: "upstream", + order: Arc::clone(&order), + }, + DropSpy { + name: "downstream", + order: Arc::clone(&order), + }, + ); + assert_eq!( + *order.lock().expect("drop order"), + vec!["downstream", "upstream"], + "the owned harness group must be escalated before the upstream queues are destroyed" + ); + } +} diff --git a/src/acp/wire.rs b/src/acp/wire.rs new file mode 100644 index 00000000..7ede7664 --- /dev/null +++ b/src/acp/wire.rs @@ -0,0 +1,779 @@ +//! Resource policy around the SDK's `Lines` transport. The SDK still parses, +//! dispatches, assigns forwarded IDs and correlates replies. + +use std::collections::{BTreeMap, HashMap, VecDeque}; +use std::future::Future; +use std::io; +use std::pin::Pin; +use std::process::{ExitStatus, Stdio}; +use std::sync::{Arc, Mutex}; +use std::task::{Context, Poll}; +use std::time::Duration; + +use agent_client_protocol::{ + Error, Lines, RawJsonRpcId, RawJsonRpcMessage, RawJsonRpcNotification, RawJsonRpcParams, + TransportFrame, UntypedMessage, +}; +use futures_util::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader}; +use futures_util::{Sink, Stream, sink, stream}; +use serde_json::Value; +use tokio::io::ReadBuf; +use tokio::process::{Child, ChildStdin, ChildStdout, Command}; +use tokio::time::{sleep, timeout}; + +use super::{AcpProxyConfig, Shutdown, TerminationCause}; + +// Counts bytes before LF (including any CR), before the SDK can accumulate a +// line. SDK-assigned IDs and injected declarations may add bytes on output. +const MAX_LINE_BYTES: usize = 1024 * 1024; +const MAX_PENDING_REQUESTS: usize = 1024; +const MAX_PENDING_REQUEST_BYTES: usize = 16 * MAX_LINE_BYTES; +const NON_REQUEST_LIMIT: Limits = Limits { + count: 1024, + bytes: 16 * MAX_LINE_BYTES, +}; +const NOTICE_RECEIPT: &str = "rustscript-acp-write-receipt"; +// These are subordinate to the proxy's existing absolute shutdown deadline. +const HARNESS_EXIT_GRACE: Duration = Duration::from_secs(1); +const HARNESS_TERM_GRACE: Duration = Duration::from_secs(2); + +#[derive(Default)] +struct RequestWindow { + ids: HashMap, + bytes: usize, +} + +struct RequestCharge { + bytes: usize, + forwarded: Option, + reply_bytes: Option, +} + +impl RequestWindow { + fn admit(&mut self, id: RawJsonRpcId, bytes: usize) -> bool { + if self.ids.len() >= MAX_PENDING_REQUESTS + || self.bytes + bytes > MAX_PENDING_REQUEST_BYTES + || self.ids.contains_key(&id) + { + return false; + } + self.ids.insert( + id, + RequestCharge { + bytes, + forwarded: None, + reply_bytes: None, + }, + ); + self.bytes += bytes; + true + } + + fn retire(&mut self, id: &RawJsonRpcId) -> Option { + let charge = self.ids.remove(id)?; + self.bytes -= charge.bytes; + Some(charge) + } +} + +#[derive(Clone, Copy)] +struct Limits { + count: usize, + bytes: usize, +} + +#[derive(Default)] +struct Budget { + count: usize, + bytes: usize, +} + +impl Budget { + fn admit(&mut self, len: usize, limit: Limits) -> bool { + if self.count >= limit.count || len > limit.bytes - self.bytes { + return false; + } + self.count += 1; + self.bytes += len; + true + } + + fn retire(&mut self, len: usize) { + self.count -= 1; + self.bytes -= len; + } +} + +#[derive(Clone, Copy)] +pub(super) enum Peer { + Client, + Harness, +} + +impl Peer { + fn opposite(self) -> Self { + match self { + Self::Client => Self::Harness, + Self::Harness => Self::Client, + } + } +} + +#[derive(Default)] +struct PeerWindow { + requests: RequestWindow, + // SDK-assigned ID -> original ID. Only the first response can spend a + // credit. No values for unsolicited or duplicate replies enter the SDK. + expected: HashMap, + replies: Budget, + notices: Budget, + undispatched: VecDeque, + dispatched: BTreeMap)>, + next_notice: u64, + saturated: bool, +} + +/// Per-source, per-class count and byte limits for every unbounded queue in +/// the SDK and bridge. The SDK still owns routing and dispatch. This side +/// ledger owns only credits, and returns them on physical write + flush. +#[derive(Clone)] +pub(super) struct WirePolicy { + windows: Arc>, + limit: Limits, +} + +impl Default for WirePolicy { + fn default() -> Self { + Self { + windows: Arc::default(), + limit: NON_REQUEST_LIMIT, + } + } +} + +#[derive(Debug, Eq, PartialEq)] +enum Admission { + Forward, + Ignore, + Cutoff, +} + +impl WirePolicy { + pub(super) fn close_cause(&self, peer: Peer, shutdown: &Shutdown, failure: TerminationCause) { + if self.windows.lock().unwrap()[peer as usize].saturated { + // The SDK invokes on_close after dispatching its accepted input + // prefix. Claiming earlier drops already-admitted client notices. + shutdown.claim(failure); + } + } + + /// Bind a reply credit to the request's existing wire lifetime. The SDK + /// still chooses the forwarded ID and correlates the actual reply. + pub(super) fn expect_reply( + &self, + target: Peer, + sdk_id: &RawJsonRpcId, + original: &RawJsonRpcId, + ) { + let mut windows = self.windows.lock().unwrap(); + let Some(request) = windows[target.opposite() as usize] + .requests + .ids + .get_mut(original) + else { + return; + }; + request.forwarded = Some(sdk_id.clone()); + windows[target as usize] + .expected + .insert(sdk_id.clone(), (original.clone(), false)); + } + + fn begin_request_write(&self, target: Peer, id: &RawJsonRpcId) { + if let Some((_, writing)) = self.windows.lock().unwrap()[target as usize] + .expected + .get_mut(id) + { + *writing = true; + } + } + + fn admit(&self, source: Peer, frame: RawJsonRpcMessage, len: usize) -> Admission { + let mut windows = self.windows.lock().unwrap(); + let source_index = source as usize; + match frame { + RawJsonRpcMessage::Request(request) => { + if windows[source_index].requests.admit(request.id, len) { + Admission::Forward + } else { + Admission::Cutoff + } + } + RawJsonRpcMessage::Notification(notice) => { + let value = notice + .params + .map_or(Value::Null, RawJsonRpcParams::into_value); + let len = notice_size(¬ice.method, &value); + let window = &mut windows[source_index]; + if !window.notices.admit(len, self.limit) { + window.saturated = true; + return Admission::Cutoff; + } + window.undispatched.push_back(len); + Admission::Forward + } + response @ RawJsonRpcMessage::Response(_) => { + let window = &mut windows[source_index]; + let id = response.response_id().unwrap(); + if !window.expected.get(id).is_some_and(|(_, writing)| *writing) { + return Admission::Ignore; + } + let (original, _) = window.expected.remove(id).unwrap(); + if !window.replies.admit(len, self.limit) { + window.saturated = true; + return Admission::Cutoff; + } + let request = windows[source.opposite() as usize] + .requests + .ids + .get_mut(&original) + .expect("expected reply belongs to an active request"); + request.reply_bytes = Some(len); + Admission::Forward + } + } + } + + /// Before publication, move the ingress charge to a local write receipt. + /// The locked v1 SDK dispatches at most one unchanged notification per + /// frame, in order. A skipped prefix (e.g. pre-initialize) can be retired; + /// an equal-sized skipped item is indistinguishable but transfers exactly + /// the same credit, retaining the other item until a later dispatch. + pub(super) fn track_notice(&self, source: Peer, mut notice: UntypedMessage) -> UntypedMessage { + let len = notice_size(¬ice.method, ¬ice.params); + let mut windows = self.windows.lock().unwrap(); + let window = &mut windows[source as usize]; + let index = window + .undispatched + .iter() + .position(|&size| size == len) + .expect("v1 dispatch must match a wire notification charge"); + for skipped in window.undispatched.drain(..index) { + window.notices.retire(skipped); + } + window.undispatched.pop_front(); + window.next_notice += 1; + let ticket = window.next_notice; + let params = RawJsonRpcParams::from_value(notice.params).expect("validated v1 params"); + window.dispatched.insert(ticket, (len, params)); + // The SDK checks the original method. Its output queues hold a local + // receipt; the bounded ledger owns the original params. SDK-generated + // cancellations carry no receipt. Receipt-shaped peer data stays behind + // its own receipt and is restored only once, at the physical sink. + notice.params = serde_json::json!([NOTICE_RECEIPT, ticket]); + notice + } + + fn restore_notice( + &self, + source: Peer, + mut notice: RawJsonRpcNotification, + ticket: u64, + ) -> io::Result { + notice.params = self.windows.lock().unwrap()[source as usize] + .dispatched + .get_mut(&ticket) + .ok_or_else(|| io::Error::other("invalid ACP write receipt"))? + .1 + .take(); + Ok(serde_json::to_string(&RawJsonRpcMessage::Notification( + notice, + ))?) + } + + fn begin_reply_write(&self, target: Peer, id: &RawJsonRpcId) -> Option { + let mut windows = self.windows.lock().unwrap(); + let request = windows[target as usize].requests.retire(id)?; + if let Some(sdk_id) = request.forwarded { + windows[target.opposite() as usize].expected.remove(&sdk_id); + } + request.reply_bytes + } + + fn finish_write(&self, source: Peer, reply: Option, notice: Option) { + let mut windows = self.windows.lock().unwrap(); + let window = &mut windows[source as usize]; + if let Some(len) = reply { + window.replies.retire(len); + } + if let Some(ticket) = notice { + // Output from the SDK is FIFO. An earlier receipt still present + // here was suppressed during publication or by the SDK. + while window + .dispatched + .first_key_value() + .is_some_and(|(&n, _)| n <= ticket) + { + let (_, (len, _)) = window.dispatched.pop_first().unwrap(); + window.notices.retire(len); + } + } + } +} + +fn notice_size(method: &str, params: &Value) -> usize { + serde_json::to_vec(&(method, params)) + .expect("JSON value serializes") + .len() +} + +fn notice_receipt(notice: &RawJsonRpcNotification) -> Option { + if let Some(RawJsonRpcParams::Array(args)) = ¬ice.params + && let [marker, ticket] = args.as_slice() + && marker.as_str() == Some(NOTICE_RECEIPT) + { + return ticket.as_u64(); + } + None +} + +/// Track inbound requests from before SDK dispatch (including readiness) to +/// their terminal SDK output. Each peer has an independent ID namespace. A +/// same-peer collision has no unambiguous second response, and exhausting the +/// window is a terminal admission cutoff. Neither frame enters the SDK; the +/// synthetic EOF lets it drain and settle the already accepted prefix. +pub(super) fn bounded_transport( + writer: impl AsyncWrite + Send + Unpin + 'static, + reader: impl AsyncRead + Send + Unpin + 'static, + shutdown: Shutdown, + failure: TerminationCause, + policy: WirePolicy, + peer: Peer, +) -> Lines< + impl Sink + Send + 'static, + impl Stream> + Send + 'static, +> { + let incoming = stream::try_unfold(BufReader::new(reader), { + let policy = policy.clone(); + move |mut reader| { + let policy = policy.clone(); + let shutdown = shutdown.clone(); + async move { + 'next: loop { + // SDK channels use nonblocking sends. Charge the Tokio + // budget for each frame without stalling a short coalesced + // prefix on individual scheduler turns. + tokio::task::consume_budget().await; + let mut bytes = Vec::new(); + loop { + let chunk = reader.fill_buf().await?; + if chunk.is_empty() { + if bytes.is_empty() { + return Ok(None); + } + break; + } + let lf = chunk.iter().position(|byte| *byte == b'\n'); + let take = lf.unwrap_or(chunk.len()); + if bytes.len() + take > MAX_LINE_BYTES { + shutdown.claim(failure); + return Ok(None); + } + bytes.extend_from_slice(&chunk[..take]); + reader.consume_unpin(take + usize::from(lf.is_some())); + if lf.is_some() { + if bytes.last() == Some(&b'\r') { + bytes.pop(); + } + break; + } + } + let len = bytes.len(); + let line = String::from_utf8(bytes).unwrap_or_else(|error| { + String::from_utf8_lossy(error.as_bytes()).into_owned() + }); + match TransportFrame::parse_json(&line) { + TransportFrame::Single(frame) => { + let request = matches!(frame, RawJsonRpcMessage::Request(_)); + match policy.admit(peer, frame, len) { + Admission::Forward => return Ok(Some((line, reader))), + Admission::Ignore => continue 'next, + Admission::Cutoff => { + if request { + shutdown.claim(failure); + } + return Ok(None); + } + } + } + _ => { + // SDK parse errors can contain the original line. Do + // not dispatch malformed input into that error path. + shutdown.claim(failure); + return Ok(None); + } + } + } + } + } + }); + let outgoing = sink::unfold(writer, move |mut writer, mut line: String| { + let policy = policy.clone(); + async move { + let mut reply = None; + let mut receipt = None; + match serde_json::from_str::(&line) { + Ok(RawJsonRpcMessage::Request(request)) => { + policy.begin_request_write(peer, &request.id) + } + Ok(response @ RawJsonRpcMessage::Response(_)) => { + // Free the ID before writing so reuse cannot race the + // final flush. Keep the reply payload itself charged. + reply = policy.begin_reply_write(peer, response.response_id().unwrap()); + } + Ok(RawJsonRpcMessage::Notification(notice)) => { + if let Some(ticket) = notice_receipt(¬ice) { + line = policy.restore_notice(peer.opposite(), notice, ticket)?; + receipt = Some(ticket); + } + } + _ => {} + } + line.push('\n'); + writer.write_all(line.as_bytes()).await?; + writer.flush().await?; + if reply.is_some() || receipt.is_some() { + policy.finish_write(peer.opposite(), reply, receipt); + } + Ok(writer) + } + }); + Lines::new(outgoing, incoming) +} + +/// `Lines` uses futures I/O, whereas the locally owned child uses Tokio I/O. +pub(super) struct ChildIo(pub T); + +impl AsyncRead for ChildIo { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + bytes: &mut [u8], + ) -> Poll> { + let mut buf = ReadBuf::new(bytes); + std::task::ready!(Pin::new(&mut self.0).poll_read(cx, &mut buf))?; + Poll::Ready(Ok(buf.filled().len())) + } +} + +impl AsyncWrite for ChildIo { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + bytes: &[u8], + ) -> Poll> { + Pin::new(&mut self.0).poll_write(cx, bytes) + } + + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.0).poll_flush(cx) + } + + fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.0).poll_shutdown(cx) + } +} + +/// The locked SDK does not expose the child pipes or a pre-buffer size limit. +/// Own only the process and its byte streams here; the SDK owns the protocol. +pub(super) struct HarnessChild(Child); + +impl HarnessChild { + pub(super) fn spawn(config: &AcpProxyConfig) -> io::Result<(Self, ChildStdin, ChildStdout)> { + let mut command = Command::new(config.command()); + command + .args(config.arguments()) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + // A null sink cannot backpressure the child or retain secrets. + .stderr(Stdio::null()) + .kill_on_drop(true); + #[cfg(unix)] + command.process_group(0); + let mut child = Self(command.spawn()?); + let stdin = child.0.stdin.take().ok_or_else(pipe_unavailable)?; + let stdout = child.0.stdout.take().ok_or_else(pipe_unavailable)?; + Ok((child, stdin, stdout)) + } + + pub(super) async fn supervise( + mut self, + driver: impl Future>, + ) -> Result<(), Error> { + let mut driver = Box::pin(driver); + tokio::select! { + biased; + result = &mut driver => result?, + status = self.wait() => { + check_exit(status)?; + // A descendant may have kept pipes open. The group is + // already terminated; give the SDK time to drain the exit. + return timeout(HARNESS_EXIT_GRACE, driver).await.unwrap_or(Ok(())); + } + } + // Drop the SDK transport (in particular, child stdin) before waiting + // for the child's reaction to the ACP stdio shutdown signal. + drop(driver); + if let Ok(status) = timeout(HARNESS_EXIT_GRACE, self.wait()).await { + return check_exit(status); + } + #[cfg(unix)] + { + signal_owned_group(&self.0, libc::SIGTERM); + if timeout(HARNESS_TERM_GRACE, self.wait()).await.is_ok() { + return Ok(()); + } + } + self.kill(); + // The outer absolute budget still applies to reaping a killed child. + self.0.wait().await.map_err(|_| Error::internal_error())?; + Ok(()) + } + + async fn wait(&mut self) -> io::Result { + #[cfg(unix)] + { + // Keep the unreaped leader as the group identity anchor. A + // normal Child::wait would release it before group cleanup. + loop { + let pid = self.0.id().ok_or_else(pipe_unavailable)? as libc::pid_t; + if child_exited(pid)? { + signal_owned_group(&self.0, libc::SIGKILL); + break; + } + sleep(Duration::from_millis(20)).await; + } + } + self.0.wait().await + } + + fn kill(&mut self) { + #[cfg(unix)] + signal_owned_group(&self.0, libc::SIGKILL); + let _ = self.0.start_kill(); + } +} + +impl Drop for HarnessChild { + fn drop(&mut self) { + // Cancellation cannot await. Tokio owns the direct-child reap; signal + // the group while the unreaped direct child's identity still exists. + self.kill(); + } +} + +fn check_exit(status: io::Result) -> Result<(), Error> { + if status.is_ok_and(|status| status.success()) { + Ok(()) + } else { + Err(Error::internal_error()) + } +} + +fn pipe_unavailable() -> io::Error { + io::Error::other("ACP harness pipe unavailable") +} + +#[cfg(unix)] +fn child_exited(pid: libc::pid_t) -> io::Result { + loop { + // SAFETY: waitid initializes the output; a zero si_pid means no exit. + let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() }; + let result = unsafe { + libc::waitid( + libc::P_PID, + pid as libc::id_t, + &mut info, + libc::WEXITED | libc::WNOHANG | libc::WNOWAIT, + ) + }; + if result == 0 { + // SAFETY: waitid returned a child status or a zeroed structure. + return Ok(unsafe { info.si_pid() } == pid); + } + let error = io::Error::last_os_error(); + if error.kind() != io::ErrorKind::Interrupted { + return Err(error); + } + } +} + +#[cfg(unix)] +fn signal_owned_group(child: &Child, signal: libc::c_int) { + if let Some(pid) = child.id() + && child_exited(pid as libc::pid_t).is_ok() + { + // SAFETY: group was created at spawn, and the ownership check did + // not reap its leader. No other code holds this child's wait handle. + unsafe { libc::kill(-(pid as libc::pid_t), signal) }; + } +} + +#[cfg(test)] +mod tests { + use agent_client_protocol::{Agent, ConnectTo}; + use futures_util::{StreamExt, io}; + use serde_json::json; + use tokio::sync::{Notify, oneshot}; + + use super::*; + + #[tokio::test] + async fn backpressure_unsolicited_reply_stays_out_of_sdk() { + let input = concat!( + "{\"jsonrpc\":\"2.0\",\"id\":7,\"result\":{\"label\":\"fixture\"}}\n", + "{\"jsonrpc\":\"2.0\",\"method\":\"fixture/notice\",\"params\":{}}\n", + ); + let lines = bounded_transport( + io::sink(), + io::Cursor::new(input.as_bytes()), + Shutdown::new(), + TerminationCause::Transport, + WirePolicy::default(), + Peer::Client, + ); + let (mut channel, driver) = ConnectTo::::into_channel_and_future(lines); + let driver = tokio::spawn(driver.unwrap()); + let frame = channel.rx.next().await.unwrap(); + assert!( + matches!(frame, TransportFrame::Single(RawJsonRpcMessage::Notification(n)) + if &*n.method == "fixture/notice"), + "only the ordinary notification should enter the SDK" + ); + assert!(channel.rx.next().await.is_none()); + driver.abort(); + } + + fn policy(count: usize, bytes: usize) -> WirePolicy { + WirePolicy { + limit: Limits { count, bytes }, + ..WirePolicy::default() + } + } + + fn request(policy: &WirePolicy, source: Peer, original: i64, forwarded: i64) { + let original = RawJsonRpcId::Number(original); + let forwarded = RawJsonRpcId::Number(forwarded); + let message = + RawJsonRpcMessage::request("fixture/get".into(), Value::Null, original.clone()) + .unwrap(); + assert_eq!(policy.admit(source, message, 75), Admission::Forward); + policy.expect_reply(source.opposite(), &forwarded, &original); + policy.begin_request_write(source.opposite(), &forwarded); + } + + #[test] + fn backpressure_reply_budget_is_per_source_and_independent_of_notices() { + // Each reply below costs 60 bytes. The second distinct reply crosses + // the byte limit without crossing the count limit. + let policy = policy(3, 100); + let reply = + |id| RawJsonRpcMessage::response(RawJsonRpcId::Number(id), Ok(json!({"ok": true}))); + request(&policy, Peer::Client, 1, 1); + request(&policy, Peer::Client, 2, 2); + request(&policy, Peer::Harness, 1, 1); + assert_eq!( + policy.admit(Peer::Harness, reply(1), 60), + Admission::Forward + ); + assert_eq!(policy.admit(Peer::Harness, reply(1), 60), Admission::Ignore); + assert_eq!(policy.admit(Peer::Client, reply(1), 60), Admission::Forward); + let notice = RawJsonRpcMessage::notification("fixture/notice".into(), json!({})).unwrap(); + assert_eq!(policy.admit(Peer::Harness, notice, 60), Admission::Forward); + assert_eq!(policy.admit(Peer::Harness, reply(2), 60), Admission::Cutoff); + } + + struct FlushGate { + bytes: Arc>>, + waiting: Arc, + flushed: Arc, + release: oneshot::Receiver<()>, + } + + impl AsyncWrite for FlushGate { + fn poll_write( + self: Pin<&mut Self>, + _: &mut Context<'_>, + bytes: &[u8], + ) -> Poll> { + self.bytes.lock().unwrap().extend_from_slice(bytes); + Poll::Ready(Ok(bytes.len())) + } + + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.waiting.notify_one(); + std::task::ready!(Pin::new(&mut self.release).poll(cx)).unwrap(); + self.flushed.notify_one(); + Poll::Ready(Ok(())) + } + + fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.poll_flush(cx) + } + } + + #[tokio::test] + async fn backpressure_notification_credit_survives_sdk_enqueue_and_pending_flush() { + let policy = policy(1, 256); + let peer = Peer::Client; + let params = json!(["rustscript-acp-write-receipt", 77]); + let input = + || RawJsonRpcMessage::notification("fixture/notice".into(), params.clone()).unwrap(); + assert_eq!(policy.admit(peer, input(), 85), Admission::Forward); + let notice = policy.track_notice( + peer, + UntypedMessage::new("fixture/notice", ¶ms).unwrap(), + ); + let bytes = Arc::new(Mutex::new(Vec::new())); + let waiting = Arc::new(Notify::new()); + let flushed = Arc::new(Notify::new()); + let (release_tx, release) = oneshot::channel(); + let lines = bounded_transport( + FlushGate { + bytes: bytes.clone(), + waiting: waiting.clone(), + flushed: flushed.clone(), + release, + }, + io::Cursor::new(b""), + Shutdown::new(), + TerminationCause::HarnessExited, + policy.clone(), + Peer::Harness, + ); + let (channel, driver) = ConnectTo::::into_channel_and_future(lines); + let driver = tokio::spawn(driver.unwrap()); + channel + .tx + .unbounded_send(TransportFrame::Single( + RawJsonRpcMessage::notification(notice.method, notice.params).unwrap(), + )) + .unwrap(); + timeout(Duration::from_secs(1), waiting.notified()) + .await + .unwrap(); + let emitted: Value = serde_json::from_slice(&bytes.lock().unwrap()).unwrap(); + assert_eq!(emitted["params"], params); + assert_eq!(policy.admit(peer, input(), 85), Admission::Cutoff); + release_tx.send(()).unwrap(); + timeout(Duration::from_secs(1), flushed.notified()) + .await + .unwrap(); + assert_eq!( + policy.admit(peer, input(), 85), + Admission::Forward, + "credit replenishes after flush" + ); + driver.abort(); + } +} diff --git a/src/bin/rustscript-agent.rs b/src/bin/rustscript-agent.rs index 64fe831d..a5b77894 100644 --- a/src/bin/rustscript-agent.rs +++ b/src/bin/rustscript-agent.rs @@ -9,6 +9,7 @@ use std::process::ExitCode; use std::sync::{Arc, Mutex}; use std::time::Duration; +use rustscript_agent::acp::{AcpProxyConfig, ProxyDisposition, run_proxy}; use rustscript_agent::auth::authorization_output::{ NativeAuthorizationInstructionOutput, NativeAuthorizationInstructionWorker, }; @@ -105,6 +106,8 @@ async fn main() -> ExitCode { // MCP mode owns stdout exclusively: it must never pass through the // human-oriented `CliOutput` renderer or the legacy signal driver. CliInvocation::ToolsServe(options) => run_tool_server(options).await, + // ACP proxy mode likewise owns stdout as a protocol wire. + CliInvocation::AcpProxy(config) => run_acp_proxy(config).await, invocation => run_with_owned_signal(invocation).await, } } @@ -155,6 +158,23 @@ async fn run_tool_server(options: ToolsServeOptions) -> ExitCode { std::process::exit(exit_code); } +async fn run_acp_proxy(config: AcpProxyConfig) -> ExitCode { + match run_proxy(config).await { + Ok(ProxyDisposition::ClientEof) => ExitCode::SUCCESS, + // A signal is an intentional cancellation of the proxied session. + Ok(ProxyDisposition::Signal) => ExitCode::from(130), + Err(error) => { + // `AcpProxyError` exposes only a fixed code. The SDK can retain a + // raw stderr tail for a failed harness; it is never printed here. + let mut stderr = io::stderr().lock(); + let _ = stderr + .write_all(format!("{}\n", error.code()).as_bytes()) + .and_then(|()| stderr.flush()); + ExitCode::from(1) + } + } +} + async fn run_with_owned_signal(invocation: CliInvocation) -> ExitCode { let output = run_with_owned_signal_driver(invocation, install_sigint_watcher).await; emit_output(output) @@ -235,6 +255,8 @@ fn execute_invocation(invocation: CliInvocation, cancellation: RunCancellation) // `tools serve` runs on the async tool-server path in `main`; reaching // this synchronous legacy driver means the mode was misrouted. CliInvocation::ToolsServe(_) => code_output("tools_serve_unavailable", 1), + // `acp proxy` runs on the async protocol path in `main`. + CliInvocation::AcpProxy(_) => code_output("acp_proxy_unavailable", 1), } } diff --git a/src/cli.rs b/src/cli.rs index 6d7ab631..9f8fba2a 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -7,6 +7,7 @@ use std::time::Duration; use rustscript_vm::Value; use crate::AgentPaths; +use crate::acp::AcpProxyConfig; use crate::auth::host::{AuthHost, ConfigPathHost}; use crate::mcp::ToolProfile; use crate::mcp::executor::McpToolExecutorConfig; @@ -25,6 +26,7 @@ pub enum CliInvocation { Auth(AuthCommandInput), ConfigPath(AuthCommandInput), ToolsServe(ToolsServeOptions), + AcpProxy(AcpProxyConfig), } /// Parsed `tools serve --stdio` invocation. @@ -237,7 +239,7 @@ fn unsafe_report_control(value: &str) -> bool { } pub fn cli_usage() -> &'static str { - "Usage:\n rustscript-agent --script PATH --allow-host HOST [--allow-host HOST ...]\n rustscript-agent run --script PATH --allow-host HOST [--allow-host HOST ...]\n rustscript-agent auth login PROVIDER\n rustscript-agent auth status [PROVIDER]\n rustscript-agent auth logout ID\n rustscript-agent config path\n rustscript-agent config check\n rustscript-agent tools serve --stdio --workspace PATH [--profile coding|read-only] [--read-only] [--max-tool-calls N] [--max-output-bytes N] [--call-timeout-ms N] [--server-lifetime-ms N] [--max-processes N] [--max-processes-per-owner N] [--process-cleanup-timeout-ms N]" + "Usage:\n rustscript-agent --script PATH --allow-host HOST [--allow-host HOST ...]\n rustscript-agent run --script PATH --allow-host HOST [--allow-host HOST ...]\n rustscript-agent auth login PROVIDER\n rustscript-agent auth status [PROVIDER]\n rustscript-agent auth logout ID\n rustscript-agent config path\n rustscript-agent config check\n rustscript-agent tools serve --stdio --workspace PATH [--profile coding|read-only] [--read-only] [--max-tool-calls N] [--max-output-bytes N] [--call-timeout-ms N] [--server-lifetime-ms N] [--max-processes N] [--max-processes-per-owner N] [--process-cleanup-timeout-ms N]\n rustscript-agent acp proxy [--read-only] -- HARNESS [ARG ...]\n --read-only selects the read-only profile for injected RustScript tools." } pub fn parse_cli_args(args: impl IntoIterator) -> Result { @@ -251,6 +253,7 @@ pub fn parse_cli_args(args: impl IntoIterator) -> Result parse_auth(&args[1..]), Some("config") => parse_config(&args[1..]), Some("tools") => parse_tools(&args[1..]), + Some("acp") => parse_acp(&args[1..]), _ => parse_run(&args), } } @@ -415,6 +418,54 @@ fn parse_tools_serve(args: &[OsString]) -> Result { })) } +fn parse_acp(args: &[OsString]) -> Result { + match args.first().and_then(|value| value.to_str()) { + Some("--help" | "-h") if args.len() == 1 => Ok(CliInvocation::Help), + Some("proxy") => parse_acp_proxy(&args[1..]), + _ => Err(CliError::InvalidArguments), + } +} + +fn parse_acp_proxy(args: &[OsString]) -> Result { + let mut read_only = false; + let mut index = 0; + loop { + let argument = args.get(index).ok_or(CliError::InvalidArguments)?; + match argument.to_str() { + Some("--") => { + index += 1; + break; + } + Some("--help" | "-h") => return Ok(CliInvocation::Help), + Some("--read-only") => { + if read_only { + return Err(CliError::InvalidArguments); + } + read_only = true; + index += 1; + } + _ => return Err(CliError::InvalidArguments), + } + } + + let mut harness = args[index..].iter(); + let command = harness.next().ok_or(CliError::InvalidArguments)?; + if command.is_empty() { + return Err(CliError::InvalidArguments); + } + let mut arguments = Vec::new(); + for argument in harness { + let text = argument.to_str().ok_or(CliError::InvalidArguments)?; + arguments.push(text.to_owned()); + } + + // The shape is validated by the ACP configuration boundary so the public + // parser and any future internal caller share the same bounds. + let config = AcpProxyConfig::new(PathBuf::from(command), arguments, read_only) + .map_err(|_| CliError::InvalidArguments)?; + Ok(CliInvocation::AcpProxy(config)) +} + fn validated_workspace(value: &OsString) -> Result { if value.is_empty() { return Err(CliError::InvalidWorkspace); diff --git a/src/lib.rs b/src/lib.rs index 41098064..0fbef5e9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,6 +6,7 @@ //! of stream. The structured run context is the sole callable argument; the //! script-visible event builtin is `stream::emit(value)`. +pub mod acp; pub mod auth; pub mod capabilities; pub mod cli; diff --git a/tests/acp_mcp_e2e_tests.rs b/tests/acp_mcp_e2e_tests.rs new file mode 100644 index 00000000..846173fb --- /dev/null +++ b/tests/acp_mcp_e2e_tests.rs @@ -0,0 +1,450 @@ +//! Exercise the packaged proxy and the MCP server the harness starts from ACP. +//! Linux procfs verifies exact parentage and reaping, including the live tool. +#![cfg(target_os = "linux")] + +#[path = "fixtures/acp/build.rs"] +mod fixture_build; + +use std::fs::{self, File}; +use std::io; +use std::path::{Path, PathBuf}; +use std::process::Stdio; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use serde_json::{Value, json}; +use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, Lines}; +use tokio::process::{ChildStdin, ChildStdout, Command}; +use tokio::time::timeout; + +const BINARY: &str = env!("CARGO_BIN_EXE_rustscript-agent"); +// Debug startup compiles bundled RSS, as in the packaged MCP stdio tests. +const SETUP: Duration = Duration::from_secs(90); +const TURN: Duration = Duration::from_secs(90); +// Match the transport tests: the proxy's five seconds plus scheduling allowance. +const SHUTDOWN: Duration = Duration::from_millis(5500); + +struct Root(PathBuf); + +impl Root { + fn new() -> Self { + let root = std::env::var_os("RUSTSCRIPT_AGENT_TEST_TMP") + .map(PathBuf::from) + .unwrap_or_else(std::env::temp_dir); + let nonce = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos(); + let path = root.join(format!("acp-mcp-e2e-{}-{nonce}", std::process::id())); + fs::create_dir(&path).expect("create isolated test root"); + Self(path.canonicalize().unwrap()) + } +} + +impl Drop for Root { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +async fn send(input: &mut ChildStdin, id: u32, method: &str, params: Value) -> io::Result<()> { + let message = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}); + input.write_all(format!("{message}\n").as_bytes()).await +} + +async fn receive(output: &mut Lines>) -> io::Result { + let line = output + .next_line() + .await? + .ok_or_else(|| io::Error::other("unexpected ACP EOF"))?; + let message: Value = serde_json::from_str(&line)?; + if message["jsonrpc"] != "2.0" { + return Err(io::Error::other(format!("not ACP JSON-RPC: {message}"))); + } + Ok(message) +} + +async fn setup( + input: &mut ChildStdin, + output: &mut Lines>, + workspace: &Path, +) -> io::Result { + send(input, 11, "initialize", json!({"protocolVersion": 1})).await?; + let init = receive(output).await?; + if init["id"] != 11 + || init["result"]["protocolVersion"] != 1 + || init["result"]["agentInfo"]["name"] != "fake-acp-harness" + { + return Err(io::Error::other(format!( + "unexpected ACP initialize: {init}" + ))); + } + send( + input, + 12, + "session/new", + json!({"cwd": workspace, "mcpServers": []}), + ) + .await?; + let session = receive(output).await?; + if session["id"] != 12 { + return Err(io::Error::other(format!( + "uncorrelated session response: {session}" + ))); + } + session["result"]["sessionId"] + .as_str() + .map(str::to_owned) + .ok_or_else(|| { + io::Error::other(format!( + "session/new did not open the injected MCP server: {session}" + )) + }) +} + +async fn prompt( + input: &mut ChildStdin, + output: &mut Lines>, + session: &str, +) -> io::Result> { + send( + input, + 13, + "session/prompt", + json!({ + "sessionId": session, + "prompt": [{"type": "text", "text": "Run the fixture tool turn."}] + }), + ) + .await?; + let mut messages = Vec::new(); + // Bound unexpected traffic as well as total time. The scripted turn emits + // seven notifications and one result; allow room to report duplicates. + for _ in 0..16 { + let message = receive(output).await?; + let response = message.get("id").is_some(); + messages.push(message); + if response { + return Ok(messages); + } + } + Err(io::Error::other(format!( + "no prompt result after {messages:?}" + ))) +} + +fn events(path: &Path) -> Vec { + fs::read_to_string(path) + .unwrap_or_default() + .lines() + .map(|line| serde_json::from_str(line).expect("parse harness event log")) + .collect() +} + +fn event<'a>(events: &'a [Value], name: &str) -> &'a Value { + let matches: Vec<_> = events + .iter() + .filter(|entry| entry["event"] == name) + .collect(); + assert_eq!( + matches.len(), + 1, + "expected one {name} event, got {events:?}" + ); + &matches[0]["data"] +} + +#[derive(Debug)] +struct Process { + pid: u64, + parent: u64, + start: u64, + state: String, +} + +impl Process { + fn read(pid: u64) -> Option { + let stat = fs::read_to_string(format!("/proc/{pid}/stat")).ok()?; + // After (comm), the state starts at field 3; PPID is field 4 and + // starttime is field 22. Include starttime to distinguish PID reuse. + let fields: Vec<_> = stat.rsplit_once(") ")?.1.split_whitespace().collect(); + Some(Self { + pid, + parent: fields.get(1)?.parse().ok()?, + start: fields.get(19)?.parse().ok()?, + state: fields.first()?.to_string(), + }) + } + + fn gone(&self) -> bool { + Self::read(self.pid).is_none_or(|process| process.start != self.start) + } +} + +fn has_fixture_environment(pid: u64, home: &Path) -> io::Result { + let environment = fs::read(format!("/proc/{pid}/environ"))?; + let mut saw_home = false; + for entry in environment + .split(|&byte| byte == 0) + .filter(|entry| !entry.is_empty()) + { + if let Some(value) = entry.strip_prefix(b"HOME=") { + saw_home = value == home.as_os_str().as_encoded_bytes(); + } else if ![ + b"TMPDIR=".as_slice(), + b"TMP=", + b"TEMP=", + b"FAKE_ACP_MODE=", + b"FAKE_ACP_RECORD=", + ] + .iter() + .any(|prefix| entry.starts_with(prefix)) + { + return Ok(false); + } + } + Ok(saw_home) +} + +#[tokio::test] +async fn packaged_proxy_relays_harness_owned_mcp_tool_turn() { + let root = Root::new(); + let workspace = root.0.join("session workspace"); + let home = root.0.join("empty-home"); + let scratch = root.0.join("runtime"); + let launch_cwd = root.0.join("launch cwd"); + for directory in [&workspace, &home, &scratch, &launch_cwd] { + fs::create_dir(directory).unwrap(); + } + let seed = format!( + "seed from {}\n", + root.0.file_name().unwrap().to_string_lossy() + ); + fs::write(workspace.join("seed.txt"), &seed).unwrap(); + let canary = root.0.join("outside.txt"); + fs::write(&canary, "outside canary\n").unwrap(); + let harness = root.0.join("fake_agent"); + fixture_build::compile_fake_agent(&harness); + let record = root.0.join("events.jsonl"); + let stderr = root.0.join("proxy.stderr"); + let binary = Path::new(BINARY) + .canonicalize() + .expect("canonical packaged executable"); + let mut proxy = Command::new(&binary) + .args(["acp", "proxy", "--"]) + .arg(&harness) + .current_dir(&launch_cwd) + // Neither RustScript nor the harness inherits provider credentials or + // configuration. The provider-disabled runner itself is exercised by + // the separate mcp_provider_isolation_tests target. + .env_clear() + .env("HOME", &home) + .envs(["TMPDIR", "TMP", "TEMP"].map(|key| { + ( + key, + std::env::var_os(key).unwrap_or_else(|| scratch.as_os_str().to_owned()), + ) + })) + .env("FAKE_ACP_MODE", "own_mcp") + .env("FAKE_ACP_RECORD", &record) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(File::create(&stderr).unwrap()) + .kill_on_drop(true) + .spawn() + .expect("launch packaged ACP proxy"); + let proxy_pid = u64::from(proxy.id().unwrap()); + let mut input = proxy.stdin.take().unwrap(); + let mut output = BufReader::new(proxy.stdout.take().unwrap()).lines(); + + // Close the real ACP input and wait even if a protocol phase fails. + let turn = async { + let session = timeout(SETUP, setup(&mut input, &mut output, &workspace)).await??; + let messages = timeout(TURN, prompt(&mut input, &mut output, &session)).await??; + Ok::<_, Box>((session, messages)) + } + .await; + let live = events(&record); + let snapshot = |name, key: &str| { + live.iter() + .find(|entry| entry["event"] == name) + .and_then(|entry| entry["data"][key].as_u64()) + .and_then(Process::read) + }; + let harness_process = snapshot("start", "pid"); + let mcp_process = snapshot("mcp_started", "pid"); + let tool_process = snapshot("terminal_ready", "pid"); + let mcp_exe = mcp_process + .as_ref() + .map(|process| fs::read_link(format!("/proc/{}/exe", process.pid))); + let mcp_argv = mcp_process + .as_ref() + .map(|process| fs::read(format!("/proc/{}/cmdline", process.pid))); + let environments = [ + Some(proxy_pid), + harness_process.as_ref().map(|p| p.pid), + mcp_process.as_ref().map(|p| p.pid), + ] + .map(|pid| pid.map(|pid| has_fixture_environment(pid, &home))); + drop(input); + let shutdown = timeout(SHUTDOWN, async { + tokio::try_join!(proxy.wait(), async { + let mut lines = Vec::new(); + while let Some(line) = output.next_line().await? { + lines.push(line); + } + Ok(lines) + }) + }) + .await; + let diagnostic = fs::read_to_string(stderr).unwrap_or_default(); + let mcp_diagnostic = + fs::read_to_string(record.with_extension("mcp.stderr")).unwrap_or_default(); + let recorded = events(&record); + let (session, messages) = turn.unwrap_or_else(|error| { + panic!("ACP flow: {error}\nevents={recorded:?}\nproxy stderr={diagnostic}\nMCP stderr={mcp_diagnostic}") + }); + let (status, trailing) = shutdown + .expect("ACP shutdown exceeded its deadline") + .expect("wait for ACP EOF and exit"); + assert!( + status.success(), + "proxy status={status}; stderr={diagnostic}" + ); + assert!( + trailing.is_empty(), + "duplicate or unexpected ACP output before EOF: {trailing:?}" + ); + assert!( + !recorded.iter().any(|entry| entry["event"] == "mcp_error"), + "MCP errors: {recorded:?}" + ); + + let declaration = json!({ + "name": "rustscript-tools", "command": binary, + "args": ["tools", "serve", "--stdio", "--workspace", workspace], "env": [] + }); + assert_eq!( + event(&recorded, "session/new")["params"]["mcpServers"], + json!([declaration]) + ); + assert_eq!(event(&recorded, "mcp_started")["declaration"], declaration); + let init = event(&recorded, "mcp_initialize"); + assert_eq!(init["serverInfo"]["name"], "rustscript-agent-tools"); + assert_eq!(init["protocolVersion"], "2025-06-18"); + assert_eq!(init["capabilities"], json!({"tools": {}})); + assert_eq!( + event(&recorded, "mcp_catalog"), + &json!([ + "read_file", + "search_files", + "write_file", + "patch", + "terminal", + "process" + ]) + ); + assert_eq!(event(&recorded, "outside_write")["isError"], true); + assert_eq!( + event(&recorded, "outside_write")["_meta"]["org.rustscript/error_code"], + "path_denied" + ); + assert_eq!(fs::read_to_string(&canary).unwrap(), "outside canary\n"); + assert!(fs::read_dir(&launch_cwd).unwrap().next().is_none()); + assert!(fs::read_dir(&home).unwrap().next().is_none()); + assert_eq!( + fs::read_to_string(workspace.join("acp-note.txt")).unwrap(), + "written by the owning harness\n" + ); + assert_eq!( + fs::read_to_string(workspace.join("seed.txt")).unwrap(), + seed + ); + let terminal = event(&recorded, "terminal_ready"); + assert_eq!(terminal["text"], "written by the owning harness\n"); + + let mut expected = Vec::new(); + let update = |update: Value| { + json!({"jsonrpc": "2.0", "method": "session/update", "params": { + "sessionId": session, "update": update + }}) + }; + for (tool, kind, text) in [ + ("write_file", "edit", None), + ("read_file", "read", Some(seed.as_str())), + ( + "terminal", + "execute", + Some("written by the owning harness\n"), + ), + ] { + expected.push(update( + json!({"sessionUpdate": "tool_call", "toolCallId": tool, + "title": tool, "kind": kind, "status": "in_progress"}), + )); + let mut done = + json!({"sessionUpdate": "tool_call_update", "toolCallId": tool, "status": "completed"}); + if let Some(text) = text { + done["content"] = + json!([{"type": "content", "content": {"type": "text", "text": text}}]); + } + expected.push(update(done)); + } + expected.push(update( + json!({"sessionUpdate": "agent_message_chunk", "content": { + "type": "text", "text": "Fake harness completed its tool turn." + }}), + )); + expected.push(json!({"jsonrpc": "2.0", "id": 13, "result": {"stopReason": "end_turn"}})); + assert_eq!( + messages, expected, + "ACP update order, content, and correlation" + ); + + let harness_process = harness_process.expect("live harness before ACP EOF"); + let mcp_process = mcp_process.expect("live MCP server before ACP EOF"); + let tool_process = tool_process.expect("live tool before ACP EOF"); + assert_eq!(harness_process.parent, proxy_pid); + assert_eq!(mcp_process.parent, harness_process.pid); + assert_eq!(tool_process.parent, mcp_process.pid); + for (name, isolated) in ["proxy", "harness", "MCP server"] + .into_iter() + .zip(environments) + { + assert!( + isolated + .expect("live process") + .expect("read child environment"), + "{name} must use only the fixture environment and its empty home" + ); + } + assert_eq!(mcp_exe.unwrap().unwrap(), binary); + let argv = mcp_argv.unwrap().unwrap(); + assert_eq!( + argv.split(|&byte| byte == 0).collect::>(), + [ + binary.as_os_str().as_encoded_bytes(), + b"tools", + b"serve", + b"--stdio", + b"--workspace", + workspace.as_os_str().as_encoded_bytes(), + b"", + ] + ); + event(&recorded, "stdin_eof"); + assert_eq!( + event(&recorded, "mcp_exit"), + &json!({"pid": mcp_process.pid, "code": 0}) + ); + assert!( + mcp_diagnostic.contains("quit=closed cleanup=clean retained=0"), + "MCP stderr={mcp_diagnostic}" + ); + for process in [&harness_process, &mcp_process, &tool_process] { + assert!( + !matches!(process.state.as_str(), "Z" | "X"), + "not live before ACP EOF: {process:?}" + ); + assert!(process.gone(), "owned process was not reaped: {process:?}"); + } +} diff --git a/tests/acp_proxy_bridge/mod.rs b/tests/acp_proxy_bridge/mod.rs new file mode 100644 index 00000000..87391a34 --- /dev/null +++ b/tests/acp_proxy_bridge/mod.rs @@ -0,0 +1,17 @@ +//! Test-only inclusion of the real ACP proxy bridge source. +//! +//! The readiness and first-claim decisions live inside `run_proxy`'s foreground +//! and cannot be produced deterministically through a packaged process: a +//! missing harness fails during spawn, before a client request is guaranteed to +//! be queued. This module compiles the actual `src/acp/proxy.rs` into the +//! integration test binary so `drive_upstream` can be driven with a readiness +//! channel the test owns. Nothing here is reimplemented; the packaged cases in +//! `tests/acp_proxy_tests.rs` still cover the observable ordering and +//! lifecycle of the shipped binary. + +pub mod config { + pub use rustscript_agent::acp::config::*; +} + +#[path = "../../src/acp/proxy.rs"] +pub mod proxy; diff --git a/tests/acp_proxy_tests.rs b/tests/acp_proxy_tests.rs new file mode 100644 index 00000000..74fd0472 --- /dev/null +++ b/tests/acp_proxy_tests.rs @@ -0,0 +1,2509 @@ +//! Packaged `rustscript-agent acp proxy` transport contract. +//! +//! Every test drives the real binary over its real standard streams against a +//! deterministic local fake ACP v1 harness. No model, provider, credential, or +//! network path is exercised: the fake harness answers with fixed replies. +//! +//! The fixture source lives in `tests/fixtures/acp/fake_agent.rs` and is +//! compiled once by this test binary with `rustc`, using the `serde_json` +//! rlib cargo already built for this test profile. That keeps the test at the +//! packaged process boundary without adding a second shipped binary target. + +use std::ffi::OsString; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{ExitStatus, Stdio}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; +use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; +use tokio::process::{Child, ChildStdin, ChildStdout, Command}; +use tokio::task::JoinHandle; + +#[path = "fixtures/acp/build.rs"] +mod fixture_build; + +const READY_BOUND: Duration = Duration::from_secs(30); +/// Independent outer watchdog for every test that waits for the proxy process. +/// This is not the proxy's shutdown budget: assertions below use the shorter, +/// explicit shutdown bound instead. +const EXIT_WATCHDOG: Duration = Duration::from_secs(20); +/// The proxy's absolute shutdown budget (`SHUTDOWN_BUDGET` in the proxy). +const SHUTDOWN_HARD_BOUND: Duration = Duration::from_secs(5); +/// Measured allowance for process exit and scheduler wakeup after the proxy +/// drops its drivers at the hard bound. It is not a second grace window. +const SHUTDOWN_SCHEDULING_ALLOWANCE: Duration = Duration::from_millis(500); +const CLEANUP_BOUND: Duration = Duration::from_secs(5); +static NEXT_TEST: AtomicU64 = AtomicU64::new(0); + +fn binary() -> &'static str { + env!("CARGO_BIN_EXE_rustscript-agent") +} + +fn assigned_tmp_root() -> PathBuf { + std::env::var_os("RUSTSCRIPT_AGENT_TEST_TMP") + .or_else(|| std::env::var_os("RUSTSCRIPT_AGENT_TEST_TMPDIR")) + .or_else(|| std::env::var_os("TMPDIR")) + .map(PathBuf::from) + .unwrap_or_else(std::env::temp_dir) +} + +struct TestRoot { + path: PathBuf, +} + +impl TestRoot { + fn new(label: &str) -> Self { + let sequence = NEXT_TEST.fetch_add(1, Ordering::Relaxed); + let path = assigned_tmp_root().join(format!( + "acp-proxy-{label}-{}-{sequence}", + std::process::id() + )); + fs::create_dir_all(&path).expect("create isolated ACP proxy test root"); + Self { path } + } + + fn record_path(&self) -> PathBuf { + self.path.join("events.jsonl") + } +} + +impl Drop for TestRoot { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +/// Compile the fake ACP harness once for this test binary. +fn fixture_binary() -> &'static Path { + static FIXTURE: OnceLock = OnceLock::new(); + FIXTURE + .get_or_init(|| { + let output_root = assigned_tmp_root().join(format!( + "acp-fake-harness-{}-{}", + std::process::id(), + NEXT_TEST.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&output_root).expect("create fixture build directory"); + let binary = output_root.join("fake_agent"); + + fixture_build::compile_fake_agent(&binary); + binary + }) + .as_path() +} + +fn initialize_params() -> Value { + json!({ + "protocolVersion": 1, + "clientInfo": { + "name": "fixture-client", + "title": "Fixture Client", + "version": "9.9.9" + }, + "clientCapabilities": { + "fs": { "readTextFile": true, "writeTextFile": false }, + "terminal": true + }, + "_meta": { "fixture": "client-meta", "hop": 7 } + }) +} + +fn user_mcp_servers() -> Value { + json!([ + { + "name": "user-fixture-server", + "command": "/bin/true", + "args": ["--fixture-flag", "hello world"], + "env": [{ "name": "FIXTURE_ENV", "value": "fixture-value" }] + } + ]) +} + +struct Proxy { + child: Child, + stdin: Option, + stdout: Option>, + stderr: Arc>>, + stderr_task: Option>, + next_id: i64, +} + +impl Proxy { + fn spawn(root: &TestRoot, mode: &str, extra_env: &[(&str, &str)]) -> Self { + Self::spawn_with_profile(root, mode, extra_env, false) + } + + fn spawn_with_profile( + root: &TestRoot, + mode: &str, + extra_env: &[(&str, &str)], + read_only: bool, + ) -> Self { + let mut command = Command::new(binary()); + command.args(["acp", "proxy"]); + if read_only { + command.arg("--read-only"); + } + command + .arg("--") + .arg(fixture_binary()) + .args(["--fixture-label", "hello world", "--acp"]) + .env("FAKE_ACP_MODE", mode) + .env("FAKE_ACP_RECORD", root.record_path()) + .env( + "FAKE_ACP_STDERR_MARKER", + format!("fixture-benign-marker-{}", std::process::id()), + ); + for (key, value) in extra_env { + command.env(key, value); + } + let mut child = command + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .kill_on_drop(true) + .spawn() + .unwrap_or_else(|error| panic!("spawn {} acp proxy: {error}", binary())); + let stdin = child.stdin.take().expect("proxy stdin"); + let stdout = Some(BufReader::new(child.stdout.take().expect("proxy stdout"))); + let mut stderr_pipe = child.stderr.take().expect("proxy stderr"); + let stderr = Arc::new(Mutex::new(Vec::new())); + let sink = Arc::clone(&stderr); + let stderr_task = tokio::spawn(async move { + let mut buffer = Vec::new(); + let _ = stderr_pipe.read_to_end(&mut buffer).await; + *sink.lock().expect("stderr sink") = buffer; + }); + Self { + child, + stdin: Some(stdin), + stdout, + stderr, + stderr_task: Some(stderr_task), + next_id: 1, + } + } + + fn pid(&self) -> u32 { + self.child.id().expect("proxy still running") + } + + async fn send(&mut self, message: Value) { + let mut line = serde_json::to_vec(&message).expect("serialize client message"); + line.push(b'\n'); + let stdin = self.stdin.as_mut().expect("proxy stdin still open"); + stdin.write_all(&line).await.expect("write proxy stdin"); + stdin.flush().await.expect("flush proxy stdin"); + } + + /// Write several protocol messages in one system write. + async fn send_batch(&mut self, messages: &[Value]) { + let mut batch = Vec::new(); + for message in messages { + let line = serde_json::to_vec(message).expect("serialize client message"); + batch.extend_from_slice(&line); + batch.push(b'\n'); + } + let stdin = self.stdin.as_mut().expect("proxy stdin still open"); + stdin.write_all(&batch).await.expect("write proxy stdin"); + stdin.flush().await.expect("flush proxy stdin"); + } + + async fn send_request(&mut self, method: &str, params: Value) -> i64 { + let id = self.next_id; + self.next_id += 1; + self.send(json!({ + "jsonrpc": "2.0", + "id": id, + "method": method, + "params": params + })) + .await; + id + } + + async fn send_notification(&mut self, method: &str, params: Value) { + self.send(json!({ + "jsonrpc": "2.0", + "method": method, + "params": params + })) + .await; + } + + async fn respond(&mut self, id: &Value, result: Value) { + self.send(json!({ "jsonrpc": "2.0", "id": id, "result": result })) + .await; + } + + /// Read one protocol line, rejecting any non-ACP bytes on stdout. + async fn read(&mut self) -> Value { + let mut line = String::new(); + let stdout = self.stdout.as_mut().expect("proxy stdout is still open"); + let read = tokio::time::timeout(READY_BOUND, stdout.read_line(&mut line)) + .await + .expect("timed out waiting for ACP proxy output") + .expect("read proxy stdout"); + assert!(read != 0, "ACP proxy stdout closed unexpectedly"); + let trimmed = line.trim_end(); + let message: Value = serde_json::from_str(trimmed) + .unwrap_or_else(|error| panic!("non-ACP bytes on proxy stdout ({error}): {line:?}")); + assert_eq!( + message["jsonrpc"], + json!("2.0"), + "stdout line was not JSON-RPC: {line:?}" + ); + message + } + + async fn read_response(&mut self, id: i64) -> (Value, Vec) { + let mut seen = Vec::new(); + loop { + let message = self.read().await; + if message.get("id") == Some(&json!(id)) + && (message.get("result").is_some() || message.get("error").is_some()) + { + return (message, seen); + } + assert!( + message.get("id").is_none() || message.get("method").is_some(), + "unexpected response while waiting for id {id}: {message}" + ); + seen.push(message); + } + } + + async fn initialize(&mut self) -> (Value, Vec) { + let id = self.send_request("initialize", initialize_params()).await; + let (response, seen) = self.read_response(id).await; + self.send_notification("notifications/initialized", json!({})) + .await; + (response, seen) + } + + async fn new_session(&mut self, cwd: &Path) -> (String, Vec) { + let id = self + .send_request( + "session/new", + json!({ "cwd": cwd, "mcpServers": user_mcp_servers() }), + ) + .await; + let (response, seen) = self.read_response(id).await; + let session_id = response["result"]["sessionId"] + .as_str() + .unwrap_or_else(|| panic!("session/new response without sessionId: {response}")) + .to_owned(); + (session_id, seen) + } + + fn close_stdin(&mut self) { + self.stdin.take(); + } + + /// Close this test's read end of the proxy stdout pipe, so the next proxy + /// write fails with EPIPE. The proxy must then fail bounded instead of + /// leaving its harness connection parked. + fn close_stdout_reader(&mut self) { + self.stdout.take(); + } + + async fn wait_exit(&mut self, bound: Duration) -> ExitStatus { + tokio::time::timeout(bound, self.child.wait()) + .await + .expect("ACP proxy did not exit within its bound") + .expect("wait for ACP proxy") + } + + async fn finish(mut self, bound: Duration) -> (ExitStatus, Vec, Vec) { + let status = self.wait_exit(bound).await; + let mut trailing = Vec::new(); + if let Some(stdout) = self.stdout.as_mut() { + let mut line = String::new(); + loop { + line.clear(); + let read = + tokio::time::timeout(Duration::from_secs(5), stdout.read_line(&mut line)) + .await + .expect("timed out draining proxy stdout") + .expect("drain proxy stdout"); + if read == 0 { + break; + } + let trimmed = line.trim_end(); + if trimmed.is_empty() { + continue; + } + let message: Value = serde_json::from_str(trimmed).unwrap_or_else(|error| { + panic!("non-ACP bytes after proxy exit ({error}): {line:?}") + }); + assert_eq!(message["jsonrpc"], json!("2.0"), "{message}"); + trailing.push(message); + } + } + if let Some(task) = self.stderr_task.take() { + let _ = tokio::time::timeout(Duration::from_secs(5), task).await; + } + let stderr = self.stderr.lock().expect("stderr sink").clone(); + (status, trailing, stderr) + } + + /// Finish when the stdout read end was already closed by the test. + async fn finish_without_stdout(mut self, bound: Duration) -> (ExitStatus, Vec) { + let status = self.wait_exit(bound).await; + if let Some(task) = self.stderr_task.take() { + let _ = tokio::time::timeout(Duration::from_secs(5), task).await; + } + let stderr = self.stderr.lock().expect("stderr sink").clone(); + (status, stderr) + } +} + +/// Require exactly one terminal response for `id` among `messages`, and no +/// second response carrying the same id. +fn single_response(messages: &[Value], id: i64) -> &Value { + let matching: Vec<&Value> = messages + .iter() + .filter(|message| { + message.get("id") == Some(&json!(id)) + && (message.get("result").is_some() || message.get("error").is_some()) + }) + .collect(); + assert_eq!( + matching.len(), + 1, + "expected exactly one terminal response for id {id}, got {matching:?} in {messages:?}" + ); + matching[0] +} + +fn read_events(path: &Path) -> Vec { + let text = fs::read_to_string(path) + .unwrap_or_else(|error| panic!("read fixture event log {}: {error}", path.display())); + text.lines() + .filter(|line| !line.trim().is_empty()) + .map(|line| serde_json::from_str(line).expect("fixture event line is JSON")) + .collect() +} + +fn events_named<'a>(events: &'a [Value], name: &str) -> Vec<&'a Value> { + events + .iter() + .filter(|event| event.get("event").and_then(Value::as_str) == Some(name)) + .collect() +} + +fn assert_stderr_is_fixed_codes(stderr: &[u8], marker: &str) { + let text = String::from_utf8_lossy(stderr); + assert!( + !text.contains(marker), + "proxy surfaced the peer stderr marker: {text:?}" + ); + for line in text.lines() { + assert!(!line.is_empty()); + assert!( + line.chars().all(|character| character.is_ascii_lowercase() + || character.is_ascii_digit() + || character == '_'), + "proxy stderr was not a fixed code: {line:?}" + ); + } +} + +fn process_is_live(pid: u32) -> bool { + let Ok(stat) = fs::read_to_string(format!("/proc/{pid}/stat")) else { + return false; + }; + let Some(close) = stat.rfind(')') else { + return false; + }; + let state = stat[close + 1..].split_whitespace().next(); + !matches!(state, Some("Z") | Some("X") | None) +} + +fn wait_process_gone(pid: u32) { + let deadline = Instant::now() + CLEANUP_BOUND; + while Instant::now() < deadline { + if !process_is_live(pid) { + return; + } + std::thread::sleep(Duration::from_millis(10)); + } + panic!("owned process {pid} was still live after the proxy exited"); +} + +struct PidGuard(Vec); + +impl Drop for PidGuard { + fn drop(&mut self) { + for pid in &self.0 { + if process_is_live(*pid) { + // SAFETY: best-effort cleanup of a test fixture process group + // member; the pid came from the fixture's own event log. + unsafe { + libc::kill(*pid as i32, libc::SIGKILL); + } + } + } + } +} + +fn recorded_pids(events: &[Value]) -> PidGuard { + let mut pids = Vec::new(); + for event in events { + match event.get("event").and_then(Value::as_str) { + Some("start") => { + if let Some(pid) = event["data"]["pid"].as_u64() { + pids.push(pid as u32); + } + } + Some("descendant") => { + if let Some(pid) = event["data"]["pid"].as_u64() { + pids.push(pid as u32); + } + } + _ => {} + } + } + assert!(!pids.is_empty(), "fixture did not record its process ids"); + PidGuard(pids) +} + +async fn exchange(proxy: &mut Proxy, id: Value, method: &str, params: &Value) -> Value { + proxy + .send(json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params })) + .await; + let reply = proxy.read().await; + assert_eq!(reply["id"], id, "correlation for {method}: {reply}"); + assert!(reply.get("method").is_none(), "unexpected replay: {reply}"); + reply +} + +async fn finish_session_mcp(mut proxy: Proxy, root: &TestRoot) -> Vec { + proxy.close_stdin(); + let (status, trailing, stderr) = proxy.finish(EXIT_WATCHDOG).await; + assert!(status.success(), "{status:?}, stderr={stderr:?}"); + assert!(trailing.is_empty(), "unexpected messages: {trailing:?}"); + read_events(&root.record_path()) +} + +fn expected_mcp(canonical: &Path, read_only: bool) -> Value { + let mut args = vec![ + "tools", + "serve", + "--stdio", + "--workspace", + canonical.to_str().unwrap(), + ]; + if read_only { + args.push("--read-only"); + } + json!({ + "name": "rustscript-tools", + "command": fs::canonicalize(binary()).unwrap(), + "args": args, + "env": [] + }) +} + +fn assert_setup_wire(frame: &Value, method: &str, params: &Value) { + assert!( + frame["id"].is_number() || frame["id"].is_string(), + "{frame}" + ); + assert_eq!( + frame, + &json!({ "jsonrpc": "2.0", "method": method, "id": frame["id"], "params": params }), + "downstream wire for {method}" + ); +} + +#[cfg(unix)] +#[tokio::test] +async fn session_mcp_new_appends_only_the_declaration_for_each_profile() { + let root = TestRoot::new("session-mcp-profiles"); + let workspace = root.path.join("real workspace"); + fs::create_dir(&workspace).unwrap(); + let alias = root.path.join("workspace alias"); + std::os::unix::fs::symlink(&workspace, &alias).unwrap(); + let canonical = workspace.canonicalize().unwrap(); + let callers = json!([ + { "name": "first", "command": "/bin/true", "args": ["hello world"], + "env": [{ "name": "FIXTURE", "value": "sample" }], "x-declaration": [1, 2] }, + { "type": "http", "name": "second", "url": "https://example.invalid/mcp", + "headers": [], "x-declaration": { "order": 2 } } + ]); + for read_only in [false, true] { + let peer = TestRoot::new(if read_only { "readonly" } else { "coding" }); + let mut proxy = Proxy::spawn_with_profile(&peer, "normal", &[], read_only); + let _ = proxy.initialize().await; + let params = json!({ "cwd": alias, "mcpServers": callers, "_meta": { "tag": 7 }, + "x-caller": { "arbitrary": [null, false] } }); + let reply = exchange(&mut proxy, json!("new/string-id"), "session/new", ¶ms).await; + assert_eq!(reply["result"]["sessionId"], json!("fixture-session-1")); + let unrelated = json!({ "cwd": "relative", "mcpServers": "untouched", "x-caller": [4] }); + let reply = exchange(&mut proxy, json!(94), "session/newer", &unrelated).await; + assert_eq!(reply["error"]["code"], json!(-32601)); + let events = finish_session_mcp(proxy, &peer).await; + let wire = events_named(&events, "setup_wire"); + assert_eq!(wire.len(), 1); + + let mut expected = params; + expected["mcpServers"] + .as_array_mut() + .unwrap() + .push(expected_mcp(&canonical, read_only)); + assert_setup_wire(&wire[0]["data"], "session/new", &expected); + assert_eq!( + events_named(&events, "start")[0]["data"]["args"], + json!(["--fixture-label", "hello world", "--acp"]) + ); + let other = events_named(&events, "unsupported_request"); + assert_eq!(other.len(), 1); + assert_eq!(other[0]["data"]["method"], json!("session/newer")); + assert_eq!(other[0]["data"]["params"], unrelated); + } +} + +#[tokio::test] +async fn session_mcp_load_and_resume_follow_independent_capabilities() { + for (mode, supported, unsupported, capabilities) in [ + ( + "load_only", + "session/load", + "session/resume", + json!({ "loadSession": true, + "sessionCapabilities": { "_meta": { "fixture": "no-resume" } } }), + ), + ( + "resume_only", + "session/resume", + "session/load", + json!({ "loadSession": false, + "sessionCapabilities": { "resume": {}, "_meta": { "fixture": "resume" } } }), + ), + ] { + let root = TestRoot::new(mode); + let mut proxy = Proxy::spawn(&root, mode, &[]); + let (reply, seen) = proxy.initialize().await; + assert!(seen.is_empty()); + let mut expected_caps = capabilities; + expected_caps["promptCapabilities"] = + json!({ "image": false, "audio": false, "embeddedContext": false }); + assert_eq!(reply["result"]["agentCapabilities"], expected_caps); + let params = json!({ "cwd": root.path, "sessionId": "existing", "mcpServers": user_mcp_servers(), + "_meta": { "fixture": true }, "x-caller": "retain" }); + let reply = exchange(&mut proxy, json!("setup/supported"), supported, ¶ms).await; + assert_eq!(reply["result"], json!({})); + let bypass = json!({ "cwd": "relative", "sessionId": "other", "mcpServers": "as sent" }); + let reply = exchange(&mut proxy, json!("setup/unsupported"), unsupported, &bypass).await; + assert_eq!(reply["error"]["code"], json!(-32601)); + let events = finish_session_mcp(proxy, &root).await; + let wire = events_named(&events, "setup_wire"); + assert_eq!(wire.len(), 2); + + assert_setup_wire(&wire[1]["data"], unsupported, &bypass); + let mut expected = params; + expected["mcpServers"] + .as_array_mut() + .unwrap() + .push(expected_mcp(&root.path.canonicalize().unwrap(), false)); + assert_setup_wire(&wire[0]["data"], supported, &expected); + } +} + +#[tokio::test] +async fn session_mcp_empty_array_null_and_omitted_resume() { + let root = TestRoot::new("session-mcp-empty"); + let mut proxy = Proxy::spawn(&root, "normal", &[]); + let _ = proxy.initialize().await; + let mut cases = Vec::new(); + for method in ["session/new", "session/load", "session/resume"] { + for list in [Some(json!([])), Some(Value::Null), None] { + if list.is_none() && method != "session/resume" { + continue; + } + let mut params = json!({ "cwd": root.path }); + if method != "session/new" { + params["sessionId"] = json!("known-session"); + } + if let Some(list) = list { + params["mcpServers"] = list; + } + let reply = exchange(&mut proxy, json!(cases.len()), method, ¶ms).await; + assert!(reply.get("result").is_some(), "{reply}"); + cases.push((method, params)); + } + } + let events = finish_session_mcp(proxy, &root).await; + let wire = events_named(&events, "setup_wire"); + assert_eq!(wire.len(), cases.len()); + let injected = expected_mcp(&root.path.canonicalize().unwrap(), false); + for (event, (method, mut params)) in wire.into_iter().zip(cases) { + params["mcpServers"] = json!([injected]); + assert_setup_wire(&event["data"], method, ¶ms); + } +} + +#[tokio::test] +async fn session_mcp_invalid_list_conflict_and_workspace_are_refused_locally() { + let root = TestRoot::new("session-mcp-refusals"); + let file = root.path.join("regular file"); + fs::write(&file, "fixture").unwrap(); + let missing = root.path.join("no such path"); + let mut proxy = Proxy::spawn(&root, "normal", &[]); + let _ = proxy.initialize().await; + let mut checks = Vec::new(); + for method in ["session/new", "session/load", "session/resume"] { + let mut base = json!({ "cwd": root.path }); + if method != "session/new" { + base["sessionId"] = json!("existing"); + } + if method != "session/resume" { + checks.push((method, base.clone(), "invalid_mcp_servers")); + } + for invalid in [json!({}), json!("invalid"), json!(42), json!(false)] { + let mut params = base.clone(); + params["mcpServers"] = invalid; + checks.push((method, params, "invalid_mcp_servers")); + } + let mut params = base; + params["mcpServers"] = json!([{ "name": "rustscript-tools", "command": "/bin/true", + "args": [], "env": [] }]); + checks.push((method, params, "mcp_server_name_conflict")); + } + for cwd in [json!("relative"), json!(missing), json!(file), json!(null)] { + checks.push(( + "session/new", + json!({ "cwd": cwd, "mcpServers": [] }), + "invalid_workspace", + )); + } + checks.push(( + "session/new", + json!({ "mcpServers": [] }), + "invalid_workspace", + )); + #[cfg(unix)] + { + let loop_link = root.path.join("loop"); + std::os::unix::fs::symlink("loop", &loop_link).unwrap(); + checks.push(( + "session/new", + json!({ "cwd": loop_link, "mcpServers": [] }), + "invalid_workspace", + )); + } + + let mut replies = Vec::new(); + for (index, (method, params, _)) in checks.iter().enumerate() { + let reply = exchange( + &mut proxy, + json!(format!("refusal/{index}")), + method, + params, + ) + .await; + + replies.push(reply); + } + let events = finish_session_mcp(proxy, &root).await; + assert_eq!( + events_named(&events, "setup_wire"), + Vec::<&Value>::new(), + "validation must refuse before forwarding" + ); + for (reply, (method, _, reason)) in replies.iter().zip(checks) { + assert!(reply.get("result").is_none(), "{reply}"); + assert_eq!(reply["error"]["code"], json!(-32602), "{reply}"); + assert_eq!( + reply["error"]["data"], + json!({ "method": method, "reason": reason }) + ); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn initialize_preserves_v1_client_metadata_and_returns_agent_metadata() { + let root = TestRoot::new("initialize"); + let marker = format!("fixture-benign-marker-{}", std::process::id()); + let mut proxy = Proxy::spawn(&root, "normal", &[]); + + let (response, seen) = proxy.initialize().await; + assert!( + seen.is_empty(), + "initialize produced extra messages: {seen:?}" + ); + assert_eq!(response["result"]["protocolVersion"], json!(1)); + assert_eq!( + response["result"]["agentInfo"], + json!({ + "name": "fake-acp-harness", + "title": "Fake ACP Harness", + "version": "0.1.0" + }) + ); + assert_eq!( + response["result"]["_meta"], + json!({ "fixture": "agent-meta" }) + ); + assert_eq!( + response["result"]["agentCapabilities"]["loadSession"], + json!(true) + ); + + proxy.close_stdin(); + let (status, trailing, stderr) = proxy.finish(EXIT_WATCHDOG).await; + assert!( + status.success(), + "clean client EOF should exit successfully: {status:?}, stderr={stderr:?}" + ); + assert!( + trailing.is_empty(), + "unexpected output after EOF: {trailing:?}" + ); + assert_stderr_is_fixed_codes(&stderr, &marker); + + let events = read_events(&root.record_path()); + let initialize = events_named(&events, "initialize"); + assert_eq!( + initialize.len(), + 1, + "initialize must reach the harness once" + ); + assert_eq!(initialize[0]["data"], initialize_params()); + assert_eq!(events_named(&events, "notifications/initialized").len(), 1); + assert!( + events_named(&events, "unsupported_request").is_empty(), + "the public proxy must never require the private proxy/initialize method" + ); + let start = events_named(&events, "start"); + assert_eq!( + start[0]["data"]["args"], + json!(["--fixture-label", "hello world", "--acp"]), + "the harness must receive the exact argv without shell splitting" + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn prompt_updates_and_permission_pass_through_in_order() { + let root = TestRoot::new("prompt"); + let marker = format!("fixture-benign-marker-{}", std::process::id()); + let mut proxy = Proxy::spawn(&root, "normal", &[]); + let _ = proxy.initialize().await; + let (session_id, seen) = proxy.new_session(&root.path).await; + assert!(seen.is_empty(), "{seen:?}"); + + let prompt_id = proxy + .send_request( + "session/prompt", + json!({ + "sessionId": session_id, + "prompt": [{ "type": "text", "text": "run the fixture" }] + }), + ) + .await; + + let mut labels = Vec::new(); + let mut texts = Vec::new(); + let mut permission_id = None; + let mut permission_params = None; + let mut prompt_response = None; + while prompt_response.is_none() { + let message = proxy.read().await; + if message.get("id") == Some(&json!(prompt_id)) { + prompt_response = Some(message); + break; + } + if message.get("method") == Some(&json!("session/request_permission")) { + assert_eq!(message["params"]["sessionId"], json!(session_id)); + permission_id = message["id"].clone().into(); + permission_params = Some(message["params"].clone()); + labels.push("permission".to_owned()); + let id = message["id"].clone(); + proxy + .respond( + &id, + json!({ "outcome": { "outcome": "selected", "optionId": "allow" } }), + ) + .await; + continue; + } + if message.get("method") == Some(&json!("session/update")) { + assert_eq!(message["params"]["sessionId"], json!(session_id)); + let update = &message["params"]["update"]; + let kind = update["sessionUpdate"] + .as_str() + .unwrap_or_default() + .to_owned(); + if let Some(text) = update["content"]["text"].as_str() { + texts.push(text.to_owned()); + } + labels.push(kind); + continue; + } + panic!("unexpected message while prompting: {message}"); + } + + let response = prompt_response.expect("prompt response"); + assert_eq!(response["result"]["stopReason"], json!("end_turn")); + assert_eq!( + labels, + vec![ + "agent_message_chunk", + "tool_call", + "tool_call_update", + "permission", + "tool_call_update", + "agent_message_chunk", + ], + "streamed updates and the permission request must keep their order" + ); + assert_eq!(texts, vec!["working", "done"]); + let permission_params = permission_params.expect("permission request observed"); + assert_eq!( + permission_params["toolCall"]["toolCallId"], + json!("fixture-call-1") + ); + assert_eq!(permission_params["options"][0]["optionId"], json!("allow")); + assert!(permission_id.is_some()); + + proxy.close_stdin(); + let (status, trailing, stderr) = proxy.finish(EXIT_WATCHDOG).await; + assert!(status.success(), "{status:?}"); + assert!(trailing.is_empty(), "{trailing:?}"); + assert_stderr_is_fixed_codes(&stderr, &marker); + + let events = read_events(&root.record_path()); + let new_sessions = events_named(&events, "session/new"); + assert_eq!(new_sessions.len(), 1); + assert_eq!( + new_sessions[0]["data"]["params"]["mcpServers"][0], + user_mcp_servers()[0], + "the caller declaration must remain first and intact" + ); + assert_eq!(new_sessions[0]["data"]["params"]["cwd"], json!(root.path)); + let responses = events_named(&events, "permission_response"); + assert_eq!(responses.len(), 1); + assert_eq!( + responses[0]["data"]["result"], + json!({ "outcome": { "outcome": "selected", "optionId": "allow" } }) + ); + assert!(responses[0]["data"]["error"].is_null()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn session_cancel_reaches_only_the_named_downstream_session() { + let root = TestRoot::new("cancel"); + let marker = format!("fixture-benign-marker-{}", std::process::id()); + let mut proxy = Proxy::spawn(&root, "cancel", &[]); + let _ = proxy.initialize().await; + let (session_a, _) = proxy.new_session(&root.path).await; + let (session_b, _) = proxy.new_session(&root.path).await; + + let prompt_a = proxy + .send_request( + "session/prompt", + json!({ + "sessionId": session_a, + "prompt": [{ "type": "text", "text": "session a" }] + }), + ) + .await; + let first_update = proxy.read().await; + assert_eq!(first_update["method"], json!("session/update")); + assert_eq!(first_update["params"]["sessionId"], json!(session_a)); + + let prompt_b = proxy + .send_request( + "session/prompt", + json!({ + "sessionId": session_b, + "prompt": [{ "type": "text", "text": "session b" }] + }), + ) + .await; + let second_update = proxy.read().await; + assert_eq!(second_update["method"], json!("session/update")); + assert_eq!(second_update["params"]["sessionId"], json!(session_b)); + + proxy + .send_notification("session/cancel", json!({ "sessionId": session_a })) + .await; + + let (cancelled_a, seen) = proxy.read_response(prompt_a).await; + assert_eq!(cancelled_a["result"]["stopReason"], json!("cancelled")); + for message in &seen { + assert_ne!( + message.get("id"), + Some(&json!(prompt_b)), + "session B prompt must not terminate when session A is cancelled" + ); + } + + proxy + .send_notification("session/cancel", json!({ "sessionId": session_b })) + .await; + let (cancelled_b, _) = proxy.read_response(prompt_b).await; + assert_eq!(cancelled_b["result"]["stopReason"], json!("cancelled")); + + proxy.close_stdin(); + let (status, _trailing, stderr) = proxy.finish(EXIT_WATCHDOG).await; + assert!(status.success(), "{status:?}"); + assert_stderr_is_fixed_codes(&stderr, &marker); + + let events = read_events(&root.record_path()); + let cancels = events_named(&events, "session/cancel"); + assert!( + cancels.len() >= 2, + "expected the two explicit session cancellations: {cancels:?}" + ); + assert_eq!(cancels[0]["data"]["sessionId"], json!(session_a)); + assert_eq!(cancels[1]["data"]["sessionId"], json!(session_b)); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn downstream_exit_fails_the_pending_prompt_before_the_proxy_exits() { + let root = TestRoot::new("downstream-exit"); + let marker = format!("fixture-benign-marker-{}", std::process::id()); + let mut proxy = Proxy::spawn(&root, "exit_on_prompt", &[]); + let _ = proxy.initialize().await; + let (session_id, _) = proxy.new_session(&root.path).await; + + let prompt_id = proxy + .send_request( + "session/prompt", + json!({ + "sessionId": session_id, + "prompt": [{ "type": "text", "text": "exit now" }] + }), + ) + .await; + + let (response, _seen) = proxy.read_response(prompt_id).await; + let error = response + .get("error") + .unwrap_or_else(|| panic!("pending prompt must fail with a JSON-RPC error: {response}")); + assert_eq!(error["code"], json!(-32603)); + assert_eq!(error["data"]["method"], json!("session/prompt")); + let reason = error["data"]["reason"].as_str().unwrap_or_default(); + assert!( + matches!( + reason, + "connection_terminated" | "incoming_transport_closed" + ), + "child failure must use a fixed SDK termination discriminator: {error}" + ); + assert!( + !error["message"] + .as_str() + .unwrap_or_default() + .contains(&marker), + "peer stderr leaked into the protocol error" + ); + + let (status, trailing, stderr) = proxy.finish(EXIT_WATCHDOG).await; + assert!( + !status.success(), + "an unexpectedly exiting harness must make the proxy exit nonzero" + ); + assert!( + trailing.is_empty(), + "the prompt must receive exactly one terminal outcome: {trailing:?}" + ); + assert_stderr_is_fixed_codes(&stderr, &marker); + assert_eq!( + String::from_utf8_lossy(&stderr).trim(), + "acp_harness_exited", + "the proxy must emit one fixed diagnostic, not the peer stderr tail" + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn client_eof_terminates_the_owned_harness_process_group() { + let root = TestRoot::new("eof"); + let marker = format!("fixture-benign-marker-{}", std::process::id()); + let mut proxy = Proxy::spawn(&root, "normal", &[("FAKE_ACP_SPAWN_DESCENDANT", "1")]); + let _ = proxy.initialize().await; + let (session_id, _) = proxy.new_session(&root.path).await; + let prompt_id = proxy + .send_request( + "session/prompt", + json!({ + "sessionId": session_id, + "prompt": [{ "type": "text", "text": "hold" }] + }), + ) + .await; + let update = proxy.read().await; + assert_eq!(update["method"], json!("session/update")); + + let events = read_events(&root.record_path()); + let pids = recorded_pids(&events); + assert!(pids.0.len() >= 2, "expected harness and descendant pids"); + + let started = Instant::now(); + proxy.close_stdin(); + let (status, trailing, stderr) = proxy.finish(EXIT_WATCHDOG).await; + let elapsed = started.elapsed(); + assert!( + elapsed < EXIT_WATCHDOG, + "EOF shutdown exceeded its bound: {elapsed:?}" + ); + assert!( + status.success(), + "client EOF should be a clean proxy exit: {status:?}, stderr={stderr:?}" + ); + let response = single_response(&trailing, prompt_id); + let cancelled = response["result"]["stopReason"] == json!("cancelled"); + assert!( + cancelled || response.get("error").is_some(), + "an EOF outcome must be cancellation or a typed error: {response}; stderr={}", + String::from_utf8_lossy(&stderr) + ); + assert_ne!(response["result"]["stopReason"], json!("end_turn")); + assert_stderr_is_fixed_codes(&stderr, &marker); + for pid in &pids.0 { + wait_process_gone(*pid); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn termination_signal_terminates_the_owned_harness_process_group() { + let root = TestRoot::new("signal"); + let marker = format!("fixture-benign-marker-{}", std::process::id()); + let mut proxy = Proxy::spawn(&root, "normal", &[("FAKE_ACP_SPAWN_DESCENDANT", "1")]); + let _ = proxy.initialize().await; + let (session_id, _) = proxy.new_session(&root.path).await; + + let prompt_id = proxy + .send_request( + "session/prompt", + json!({ + "sessionId": session_id, + "prompt": [{ "type": "text", "text": "hold" }] + }), + ) + .await; + let update = proxy.read().await; + assert_eq!(update["method"], json!("session/update")); + + let events = read_events(&root.record_path()); + let pids = recorded_pids(&events); + + // SAFETY: the pid is the live proxy child owned by this test. + let sent = unsafe { libc::kill(proxy.pid() as i32, libc::SIGTERM) }; + assert_eq!(sent, 0, "send SIGTERM to the proxy"); + + let started = Instant::now(); + let (status, trailing, stderr) = proxy.finish(EXIT_WATCHDOG).await; + let elapsed = started.elapsed(); + assert!( + elapsed < EXIT_WATCHDOG, + "signal shutdown exceeded its bound: {elapsed:?}" + ); + assert_eq!( + status.code(), + Some(130), + "SIGTERM should map to the fixed cancellation exit code, stderr={stderr:?}" + ); + let response = single_response(&trailing, prompt_id); + let cancelled = response["result"]["stopReason"] == json!("cancelled"); + assert!( + cancelled || response.get("error").is_some(), + "a signal outcome must be cancellation or a typed error: {response}" + ); + assert_ne!(response["result"]["stopReason"], json!("end_turn")); + assert_stderr_is_fixed_codes(&stderr, &marker); + for pid in &pids.0 { + wait_process_gone(*pid); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn harness_that_ignores_eof_is_bounded_by_owned_termination() { + let root = TestRoot::new("stubborn"); + let marker = format!("fixture-benign-marker-{}", std::process::id()); + let mut proxy = Proxy::spawn(&root, "stubborn", &[("FAKE_ACP_SPAWN_DESCENDANT", "1")]); + let _ = proxy.initialize().await; + let (session_id, _) = proxy.new_session(&root.path).await; + let prompt_id = proxy + .send_request( + "session/prompt", + json!({ + "sessionId": session_id, + "prompt": [{ "type": "text", "text": "never finishes" }] + }), + ) + .await; + let update = proxy.read().await; + assert_eq!(update["method"], json!("session/update")); + + let events = read_events(&root.record_path()); + let pids = recorded_pids(&events); + + let started = Instant::now(); + proxy.close_stdin(); + let (status, trailing, stderr) = proxy.finish(EXIT_WATCHDOG).await; + let elapsed = started.elapsed(); + assert!( + elapsed < EXIT_WATCHDOG, + "non-cooperative harness shutdown exceeded its bound: {elapsed:?}" + ); + assert!( + status.success(), + "client EOF remains a clean proxy exit even when the harness is stubborn: {status:?}" + ); + let response = single_response(&trailing, prompt_id); + assert!( + response.get("error").is_some() || response["result"]["stopReason"] == json!("cancelled"), + "the pending prompt must receive exactly one terminal outcome: {response}" + ); + assert_stderr_is_fixed_codes(&stderr, &marker); + for pid in &pids.0 { + wait_process_gone(*pid); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn prompt_response_ahead_of_a_coalesced_update_stays_ordered() { + let root = TestRoot::new("coalesced"); + let marker = format!("fixture-benign-marker-{}", std::process::id()); + let mut proxy = Proxy::spawn(&root, "coalesced", &[]); + let _ = proxy.initialize().await; + let (session_id, _) = proxy.new_session(&root.path).await; + + let prompt_id = proxy + .send_request( + "session/prompt", + json!({ + "sessionId": session_id, + "prompt": [{ "type": "text", "text": "answer then notify" }] + }), + ) + .await; + + let first = proxy.read().await; + assert_eq!( + first.get("id"), + Some(&json!(prompt_id)), + "the prompt response must precede the update the harness wrote after it: {first}" + ); + assert_eq!(first["result"]["stopReason"], json!("end_turn")); + + let second = proxy.read().await; + assert_eq!(second["method"], json!("session/update")); + assert_eq!(second["params"]["sessionId"], json!(session_id)); + assert_eq!( + second["params"]["update"]["content"]["text"], + json!("after-response") + ); + + proxy.close_stdin(); + let (status, trailing, stderr) = proxy.finish(EXIT_WATCHDOG).await; + assert!(status.success(), "{status:?}"); + assert!( + trailing.is_empty(), + "the prompt must receive exactly one terminal outcome: {trailing:?}" + ); + assert_stderr_is_fixed_codes(&stderr, &marker); + let events = read_events(&root.record_path()); + assert_eq!(events_named(&events, "session/prompt").len(), 1); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn permission_response_ahead_of_a_coalesced_cancel_stays_ordered() { + let root = TestRoot::new("reply-cancel"); + let marker = format!("fixture-benign-marker-{}", std::process::id()); + let mut proxy = Proxy::spawn(&root, "normal", &[]); + let _ = proxy.initialize().await; + let (session_id, _) = proxy.new_session(&root.path).await; + + let prompt_id = proxy + .send_request( + "session/prompt", + json!({ + "sessionId": session_id, + "prompt": [{ "type": "text", "text": "reply then cancel" }] + }), + ) + .await; + + let permission_id = loop { + let message = proxy.read().await; + if message.get("method") == Some(&json!("session/request_permission")) { + break message["id"].clone(); + } + }; + + proxy + .send_batch(&[ + json!({ + "jsonrpc": "2.0", + "id": permission_id, + "result": { + "outcome": { "outcome": "selected", "optionId": "allow" } + } + }), + json!({ + "jsonrpc": "2.0", + "method": "session/cancel", + "params": { "sessionId": session_id } + }), + ]) + .await; + + let (response, _seen) = proxy.read_response(prompt_id).await; + assert_eq!( + response["result"]["stopReason"], + json!("end_turn"), + "the permission response must reach the harness before the coalesced cancel: {response}" + ); + + proxy.close_stdin(); + let (status, trailing, stderr) = proxy.finish(EXIT_WATCHDOG).await; + assert!(status.success(), "{status:?}"); + assert!( + trailing.is_empty(), + "the prompt must receive exactly one terminal outcome: {trailing:?}" + ); + assert_stderr_is_fixed_codes(&stderr, &marker); + + let events = read_events(&root.record_path()); + assert!( + events_named(&events, "unmatched_response").is_empty(), + "the harness received the coalesced pair out of order: {events:?}" + ); + let permission = events + .iter() + .position(|event| event["event"] == json!("permission_response")) + .expect("harness recorded the permission response"); + let cancel = events + .iter() + .position(|event| event["event"] == json!("session/cancel")) + .expect("harness recorded the cancel notification"); + assert!( + permission < cancel, + "the permission response must be forwarded before the later cancel: {events:?}" + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn upstream_output_failure_terminates_the_owned_harness() { + let root = TestRoot::new("upstream-output"); + let marker = format!("fixture-benign-marker-{}", std::process::id()); + let mut proxy = Proxy::spawn(&root, "hold", &[("FAKE_ACP_SPAWN_DESCENDANT", "1")]); + let _ = proxy.initialize().await; + let (session_id, _) = proxy.new_session(&root.path).await; + let _ = proxy + .send_request( + "session/prompt", + json!({ + "sessionId": session_id, + "prompt": [{ "type": "text", "text": "hold while the client leaves" }] + }), + ) + .await; + let update = proxy.read().await; + assert_eq!(update["method"], json!("session/update")); + + let events = read_events(&root.record_path()); + let pids = recorded_pids(&events); + + // Break the client-facing output, then force one proxy write into it. The + // upstream connection can finish before its foreground publishes, so the + // owned harness driver must still be bounded and killed. + proxy.close_stdout_reader(); + let _ = proxy + .send_request("session/new", json!({ "cwd": root.path, "mcpServers": [] })) + .await; + + let started = Instant::now(); + let (status, stderr) = proxy.finish_without_stdout(EXIT_WATCHDOG).await; + assert!( + started.elapsed() < EXIT_WATCHDOG, + "a broken client transport must not park the owned harness driver" + ); + assert_eq!( + status.code(), + Some(1), + "a broken client transport is a fixed proxy failure: {status:?}, stderr={stderr:?}" + ); + assert_eq!( + String::from_utf8_lossy(&stderr).trim(), + "acp_proxy_failed", + "the proxy must emit one fixed code" + ); + assert_stderr_is_fixed_codes(&stderr, &marker); + for pid in &pids.0 { + wait_process_gone(*pid); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn shutdown_with_a_harness_that_stops_reading_is_bounded() { + let root = TestRoot::new("blocked"); + let marker = format!("fixture-benign-marker-{}", std::process::id()); + let mut proxy = Proxy::spawn(&root, "blocked", &[("FAKE_ACP_SPAWN_DESCENDANT", "1")]); + let _ = proxy.initialize().await; + let (session_id, _) = proxy.new_session(&root.path).await; + + proxy + .send_notification("fixture/block", json!({ "reason": "test" })) + .await; + wait_for_event(&root.record_path(), "stdin_blocked"); + + // Fixture-only traffic: enough bytes to fill the harness stdin pipe while + // the harness keeps stdout open and never reads again. + let payload = "x".repeat(8 * 1024); + for _ in 0..48 { + proxy + .send_notification("fixture/bulk", json!({ "payload": payload })) + .await; + } + let events = read_events(&root.record_path()); + let pids = recorded_pids(&events); + + let started = Instant::now(); + proxy.close_stdin(); + let (status, _trailing, stderr) = proxy.finish(EXIT_WATCHDOG).await; + let elapsed = started.elapsed(); + assert!( + elapsed < SHUTDOWN_HARD_BOUND + SHUTDOWN_SCHEDULING_ALLOWANCE, + "a drain blocked on harness stdin backpressure must be bounded by the \ + absolute shutdown deadline: {elapsed:?}" + ); + assert!( + status.success(), + "client EOF remains a clean proxy exit even when the drain is blocked: {status:?}" + ); + assert_stderr_is_fixed_codes(&stderr, &marker); + for pid in &pids.0 { + wait_process_gone(*pid); + } + let events = read_events(&root.record_path()); + assert!( + events_named(&events, "stdin_eof").is_empty(), + "the fixture acknowledged an EOF it never read: {events:?}" + ); + assert_eq!(events_named(&events, "stdin_blocked").len(), 1); + let _ = session_id; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn client_eof_with_a_nonwritable_output_is_still_bounded() { + let root = TestRoot::new("eof-dead-output"); + let marker = format!("fixture-benign-marker-{}", std::process::id()); + let mut proxy = Proxy::spawn(&root, "hold", &[("FAKE_ACP_SPAWN_DESCENDANT", "1")]); + let _ = proxy.initialize().await; + let (session_id, _) = proxy.new_session(&root.path).await; + let _ = proxy + .send_request( + "session/prompt", + json!({ + "sessionId": session_id, + "prompt": [{ "type": "text", "text": "pending at EOF" }] + }), + ) + .await; + let update = proxy.read().await; + assert_eq!(update["method"], json!("session/update")); + let events = read_events(&root.record_path()); + let pids = recorded_pids(&events); + + // The trigger starts the one absolute shutdown budget. + let started = Instant::now(); + proxy.close_stdin(); + // The fixture acknowledges the proxy's shutdown cancellation; only then is + // the EOF cause established before the output pipe disappears. The held + // prompt is still pending, so its fixed fallback must physically write + // after the reader is gone: that write failure is guaranteed, not timed. + wait_for_event(&root.record_path(), "session/cancel"); + proxy.close_stdout_reader(); + + let (status, stderr) = proxy.finish_without_stdout(EXIT_WATCHDOG).await; + let elapsed = started.elapsed(); + assert!( + elapsed < SHUTDOWN_HARD_BOUND + SHUTDOWN_SCHEDULING_ALLOWANCE, + "EOF shutdown with a non-writable output exceeded its bound: {elapsed:?}" + ); + assert_eq!( + status.code(), + Some(1), + "a physical output failure must not be reported as a clean EOF: \ + {status:?}, stderr={stderr:?}" + ); + assert_eq!( + String::from_utf8_lossy(&stderr).trim(), + "acp_proxy_failed", + "the upstream driver failure shares the one fixed transport code" + ); + assert_stderr_is_fixed_codes(&stderr, &marker); + for pid in &pids.0 { + wait_process_gone(*pid); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn session_load_with_an_empty_v1_response_tracks_the_requested_session() { + let root = TestRoot::new("load"); + let marker = format!("fixture-benign-marker-{}", std::process::id()); + let mut proxy = Proxy::spawn(&root, "cancel", &[]); + let _ = proxy.initialize().await; + + let load_id = proxy + .send_request( + "session/load", + json!({ + "sessionId": "fixture-resume-42", + "cwd": root.path, + "mcpServers": [] + }), + ) + .await; + let (load_response, seen) = proxy.read_response(load_id).await; + assert!(seen.is_empty(), "{seen:?}"); + assert_eq!( + load_response["result"], + json!({}), + "ACP v1 session/load succeeds without a response session id" + ); + + let (created_session, _) = proxy.new_session(&root.path).await; + assert_ne!(created_session, "fixture-resume-42"); + + let resume_id = proxy + .send_request( + "session/resume", + json!({ + "sessionId": "fixture-resume-7", + "cwd": root.path, + "mcpServers": [] + }), + ) + .await; + let (resume_response, seen) = proxy.read_response(resume_id).await; + assert!(seen.is_empty(), "{seen:?}"); + assert_eq!( + resume_response["result"], + json!({}), + "ACP v1 session/resume succeeds without a response session id" + ); + + let loaded_prompt = proxy + .send_request( + "session/prompt", + json!({ + "sessionId": "fixture-resume-42", + "prompt": [{ "type": "text", "text": "loaded session" }] + }), + ) + .await; + let loaded_update = proxy.read().await; + assert_eq!(loaded_update["method"], json!("session/update")); + assert_eq!( + loaded_update["params"]["sessionId"], + json!("fixture-resume-42") + ); + + let created_prompt = proxy + .send_request( + "session/prompt", + json!({ + "sessionId": created_session, + "prompt": [{ "type": "text", "text": "created session" }] + }), + ) + .await; + let created_update = proxy.read().await; + assert_eq!(created_update["method"], json!("session/update")); + assert_eq!( + created_update["params"]["sessionId"], + json!(created_session) + ); + + proxy.close_stdin(); + let (status, trailing, stderr) = proxy.finish(EXIT_WATCHDOG).await; + assert!(status.success(), "{status:?}"); + single_response(&trailing, loaded_prompt); + single_response(&trailing, created_prompt); + assert_stderr_is_fixed_codes(&stderr, &marker); + + let events = read_events(&root.record_path()); + let loads = events_named(&events, "session/load"); + assert_eq!(loads.len(), 1); + assert_eq!(loads[0]["data"]["sessionId"], json!("fixture-resume-42")); + assert_eq!(loads[0]["data"]["params"]["cwd"], json!(root.path)); + + let cancels = events_named(&events, "session/cancel"); + let cancelled_ids: Vec<&Value> = cancels + .iter() + .map(|event| &event["data"]["sessionId"]) + .collect(); + assert_eq!( + cancels.len(), + 3, + "every live session must be cancelled exactly once: {cancels:?}" + ); + assert!( + cancelled_ids.contains(&&json!("fixture-resume-42")), + "the loaded session must be cancelled by its request id: {cancels:?}" + ); + assert!( + cancelled_ids.contains(&&json!("fixture-resume-7")), + "the resumed session must be cancelled by its request id: {cancels:?}" + ); + assert!( + cancelled_ids.contains(&&json!(created_session)), + "the created session must be cancelled by its response id: {cancels:?}" + ); + assert!(events_named(&events, "unmatched_response").is_empty()); +} + +fn wait_for_event(path: &Path, name: &str) { + let needle = format!("\"event\":\"{name}\""); + let deadline = Instant::now() + READY_BOUND; + while Instant::now() < deadline { + if fs::read_to_string(path) + .map(|text| text.contains(&needle)) + .unwrap_or(false) + { + return; + } + std::thread::sleep(Duration::from_millis(10)); + } + panic!("fixture did not acknowledge {name} at {}", path.display()); +} + +/// Requests queued before a coalesced permission answer. The bridge is still +/// forwarding this accepted prefix when the client closes its input, so the +/// answer is guaranteed to be waiting behind an earlier accepted backlog. +const QUEUED_PREFIX_REQUESTS: usize = 512; + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn queued_permission_answer_is_forwarded_before_the_synthetic_cancel() { + let root = TestRoot::new("eof-permission"); + let marker = format!("fixture-benign-marker-{}", std::process::id()); + let mut proxy = Proxy::spawn(&root, "normal", &[]); + let _ = proxy.initialize().await; + let (session_id, _) = proxy.new_session(&root.path).await; + let prompt_id = proxy + .send_request( + "session/prompt", + json!({ + "sessionId": session_id, + "prompt": [{ "type": "text", "text": "answer then eof" }] + }), + ) + .await; + + let permission_id = loop { + let message = proxy.read().await; + if message.get("method") == Some(&json!("session/request_permission")) { + break message["id"].clone(); + } + }; + + // One system write: an accepted request prefix, the permission answer, and + // then client EOF. The synthetic shutdown cancel must not overtake the + // answer the proxy already accepted. + let mut batch = Vec::with_capacity(QUEUED_PREFIX_REQUESTS + 1); + for offset in 0..QUEUED_PREFIX_REQUESTS { + batch.push(json!({ + "jsonrpc": "2.0", + "id": 10_000 + offset, + "method": "fixture/noop", + "params": { "n": offset } + })); + } + batch.push(json!({ + "jsonrpc": "2.0", + "id": permission_id, + "result": { "outcome": { "outcome": "selected", "optionId": "allow" } } + })); + proxy.send_batch(&batch).await; + proxy.close_stdin(); + + // Keep reading while the proxy shuts down. The queued fixed errors and the + // prompt result must physically drain here; otherwise `finish`, which + // waits for process exit before reading, would itself block the flush. + let mut drained = Vec::new(); + let response = loop { + let message = proxy.read().await; + if message.get("id") == Some(&json!(prompt_id)) + && (message.get("result").is_some() || message.get("error").is_some()) + { + break message; + } + drained.push(message); + }; + let (status, trailing, stderr) = proxy.finish(EXIT_WATCHDOG).await; + assert!( + status.success(), + "client EOF must stay clean: {status:?}, stderr={}", + String::from_utf8_lossy(&stderr) + ); + assert_eq!( + response["result"]["stopReason"], + json!("end_turn"), + "the permission answer must reach the harness before the shutdown sweep: {response}" + ); + assert!( + trailing + .iter() + .chain(drained.iter()) + .all(|message| message.get("id") != Some(&json!(prompt_id))), + "the prompt received a second terminal outcome: {trailing:?}" + ); + assert_stderr_is_fixed_codes(&stderr, &marker); + + let events = read_events(&root.record_path()); + assert_eq!( + events_named(&events, "permission_response").len(), + 1, + "the coalesced permission answer must reach the harness exactly once: {events:?}" + ); + let permission = events + .iter() + .position(|event| event["event"] == json!("permission_response")) + .expect("harness recorded the permission response"); + let cancel = events + .iter() + .position(|event| event["event"] == json!("session/cancel")) + .expect("harness recorded the synthetic cancel"); + assert!( + permission < cancel, + "the accepted permission answer must precede the synthetic cancel: {events:?}" + ); + assert!( + events_named(&events, "unmatched_response").is_empty(), + "the harness received the answer out of order: {events:?}" + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn shutdown_forwards_an_earlier_update_before_its_prompt_result() { + let root = TestRoot::new("update-before-result"); + let marker = format!("fixture-benign-marker-{}", std::process::id()); + let mut proxy = Proxy::spawn(&root, "reply_update_then_exit", &[]); + let _ = proxy.initialize().await; + let (session_id, _) = proxy.new_session(&root.path).await; + let prompt_id = proxy + .send_request( + "session/prompt", + json!({ + "sessionId": session_id, + "prompt": [{ "type": "text", "text": "update then result" }] + }), + ) + .await; + let working = proxy.read().await; + assert_eq!(working["method"], json!("session/update")); + + proxy.close_stdin(); + let (status, trailing, stderr) = proxy.finish(EXIT_WATCHDOG).await; + assert!(status.success(), "{status:?}, stderr={stderr:?}"); + + let response = single_response(&trailing, prompt_id); + assert_eq!( + response["result"]["stopReason"], + json!("end_turn"), + "the recorded peer result must survive shutdown: {trailing:?}" + ); + let update = trailing + .iter() + .position(|message| { + message.get("method") == Some(&json!("session/update")) + && message["params"]["update"]["content"]["text"] == json!("before-result") + }) + .unwrap_or_else(|| { + panic!("the earlier update was not forwarded before the proxy exited: {trailing:?}") + }); + let result = trailing + .iter() + .position(|message| { + message.get("id") == Some(&json!(prompt_id)) + && (message.get("result").is_some() || message.get("error").is_some()) + }) + .expect("prompt result in trailing output"); + assert!( + update < result, + "the fallback settlement overtook an earlier update: {trailing:?}" + ); + assert_stderr_is_fixed_codes(&stderr, &marker); + + let events = read_events(&root.record_path()); + assert_eq!(events_named(&events, "session/cancel").len(), 1); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn in_flight_session_load_completes_and_is_cancelled_once_during_shutdown() { + let root = TestRoot::new("in-flight-load"); + let marker = format!("fixture-benign-marker-{}", std::process::id()); + let mut proxy = Proxy::spawn(&root, "delayed_load", &[]); + let _ = proxy.initialize().await; + + let load_id = proxy + .send_request( + "session/load", + json!({ + "sessionId": "fixture-inflight-load", + "cwd": root.path, + "mcpServers": [] + }), + ) + .await; + // The harness has received the request and is about to write its `{}` + // success. Close the client input so that success is delivered while the + // bridge is already settling. + wait_for_event(&root.record_path(), "session/load"); + proxy.close_stdin(); + + let started = Instant::now(); + let (status, trailing, stderr) = proxy.finish(EXIT_WATCHDOG).await; + assert!( + started.elapsed() < SHUTDOWN_HARD_BOUND + SHUTDOWN_SCHEDULING_ALLOWANCE, + "an in-flight setup must settle inside the bounded shutdown: {:?}", + started.elapsed() + ); + assert!(status.success(), "{status:?}, stderr={stderr:?}"); + + // The harness genuinely answered the load downstream, but a setup whose + // completion is processed after shutdown is refused deliberately: the SDK + // notification route proves queue admission, not application receipt of + // the cancellation. + let events = read_events(&root.record_path()); + let responded = events_named(&events, "setup_responded"); + assert_eq!( + responded.len(), + 1, + "the fixture must have answered the load exactly once: {events:?}" + ); + assert_eq!(responded[0]["data"]["method"], json!("session/load")); + assert_eq!( + responded[0]["data"]["sessionId"], + json!("fixture-inflight-load") + ); + + let response = single_response(&trailing, load_id); + assert_eq!( + response["error"]["code"], + json!(-32603), + "the late setup must receive one typed refusal: {response}" + ); + assert_eq!( + response["error"]["data"]["method"], + json!("session/load"), + "the refusal must stay correlated with the request: {response}" + ); + assert_eq!( + response["error"]["data"]["reason"], + json!("proxy_shutting_down"), + "the deliberate refusal is not a peer termination: {response}" + ); + assert_stderr_is_fixed_codes(&stderr, &marker); + + let cancels = events_named(&events, "session/cancel"); + assert_eq!( + cancels.len(), + 1, + "the requested load id must be cancelled exactly once: {cancels:?}" + ); + assert_eq!( + cancels[0]["data"]["sessionId"], + json!("fixture-inflight-load") + ); + assert_eq!(events_named(&events, "session/load").len(), 1); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn blocked_stdin_keeps_a_late_setup_cancel_away_and_still_refuses_once() { + let root = TestRoot::new("blocked-late-load"); + let marker = format!("fixture-benign-marker-{}", std::process::id()); + let mut proxy = Proxy::spawn( + &root, + "blocked_late_load", + &[("FAKE_ACP_SPAWN_DESCENDANT", "1")], + ); + let _ = proxy.initialize().await; + let events = read_events(&root.record_path()); + let pids = recorded_pids(&events); + assert!(pids.0.len() >= 2, "expected harness and descendant pids"); + + let load_id = proxy + .send_request( + "session/load", + json!({ + "sessionId": "fixture-blocked-load", + "cwd": root.path, + "mcpServers": [] + }), + ) + .await; + // The fixture records the request before its delay. The client then fills + // the harness stdin pipe with accepted traffic and stops reading output at + // the test side, so the synthetic cancel can never reach the application. + wait_for_event(&root.record_path(), "session/load"); + let payload = "x".repeat(8 * 1024); + let mut batch = Vec::new(); + batch.push(json!({ + "jsonrpc": "2.0", + "method": "fixture/block", + "params": { "reason": "late-setup" } + })); + for _ in 0..48 { + batch.push(json!({ + "jsonrpc": "2.0", + "method": "fixture/bulk", + "params": { "payload": payload } + })); + } + proxy.send_batch(&batch).await; + + let started = Instant::now(); + proxy.close_stdin(); + // The delayed answer proves the setup genuinely completed downstream after + // the shutdown cause. + wait_for_event(&root.record_path(), "setup_responded"); + + let (status, trailing, stderr) = proxy.finish(EXIT_WATCHDOG).await; + let elapsed = started.elapsed(); + assert!( + elapsed >= SHUTDOWN_HARD_BOUND + && elapsed < SHUTDOWN_HARD_BOUND + SHUTDOWN_SCHEDULING_ALLOWANCE, + "a cancel that cannot reach a blocked harness must end at the one \ + absolute deadline: {elapsed:?}" + ); + assert!( + status.success(), + "the client-facing sink stayed writable, so the fixed refusal is a \ + clean proxy exit: {status:?}, stderr={stderr:?}" + ); + let response = single_response(&trailing, load_id); + assert_eq!(response["error"]["code"], json!(-32603)); + assert_eq!(response["error"]["data"]["method"], json!("session/load")); + assert_eq!( + response["error"]["data"]["reason"], + json!("proxy_shutting_down"), + "exactly one deliberate refusal despite the blocked cancel: {response}" + ); + assert_stderr_is_fixed_codes(&stderr, &marker); + + let events = read_events(&root.record_path()); + assert_eq!(events_named(&events, "session/load").len(), 1); + let responded = events_named(&events, "setup_responded"); + assert_eq!( + responded.len(), + 1, + "the late setup must genuinely succeed downstream: {events:?}" + ); + assert_eq!( + responded[0]["data"]["sessionId"], + json!("fixture-blocked-load") + ); + assert!( + events_named(&events, "session/cancel").is_empty(), + "the blocked stdin must keep the cancellation away from the harness: {events:?}" + ); + assert_eq!(events_named(&events, "stdin_blocked").len(), 1); + for pid in &pids.0 { + wait_process_gone(*pid); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn shutdown_flushes_a_pending_result_after_a_paused_client_resumes_reading() { + let root = TestRoot::new("paused-reader"); + let marker = format!("fixture-benign-marker-{}", std::process::id()); + let mut proxy = Proxy::spawn(&root, "flood", &[]); + let _ = proxy.initialize().await; + let (session_id, _) = proxy.new_session(&root.path).await; + let prompt_id = proxy + .send_request( + "session/prompt", + json!({ + "sessionId": session_id, + "prompt": [{ "type": "text", "text": "flood then cancel" }] + }), + ) + .await; + let first = proxy.read().await; + assert_eq!(first["method"], json!("session/update")); + let first_text = first["params"]["update"]["content"]["text"] + .as_str() + .unwrap_or_default(); + assert!( + first_text.starts_with("flood-000-"), + "the fixture backlog must start with the first update: {}", + &first_text[..first_text.len().min(32)] + ); + + // Stop reading for longer than the old one-second flush grace, then resume + // well inside the absolute hard bound. + let started = Instant::now(); + proxy.close_stdin(); + tokio::time::sleep(Duration::from_millis(1500)).await; + + let mut result = None; + while result.is_none() { + let message = proxy.read().await; + if message.get("id") == Some(&json!(prompt_id)) + && (message.get("result").is_some() || message.get("error").is_some()) + { + result = Some(message); + } + } + let result = result.expect("prompt result after resuming"); + assert!( + started.elapsed() < SHUTDOWN_HARD_BOUND, + "the physical flush must finish after the reader resumes and before the hard bound" + ); + let (status, trailing, stderr) = proxy.finish(EXIT_WATCHDOG).await; + assert!(status.success(), "{status:?}, stderr={stderr:?}"); + assert_eq!( + result["result"]["stopReason"], + json!("cancelled"), + "the pending prompt must settle from the harness answer: {result}" + ); + let duplicates = trailing + .iter() + .filter(|message| { + message.get("id") == Some(&json!(prompt_id)) + && (message.get("result").is_some() || message.get("error").is_some()) + }) + .count(); + assert_eq!(duplicates, 0, "the pending result was read exactly once"); + assert_stderr_is_fixed_codes(&stderr, &marker); + + let events = read_events(&root.record_path()); + assert_eq!(events_named(&events, "flood_complete").len(), 1); + assert_eq!(events_named(&events, "session/cancel").len(), 1); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn shutdown_without_a_reading_client_reports_failure_not_clean_success() { + let root = TestRoot::new("blocked-reader"); + let marker = format!("fixture-benign-marker-{}", std::process::id()); + let mut proxy = Proxy::spawn(&root, "flood", &[("FAKE_ACP_SPAWN_DESCENDANT", "1")]); + let _ = proxy.initialize().await; + let (session_id, _) = proxy.new_session(&root.path).await; + let _ = proxy + .send_request( + "session/prompt", + json!({ + "sessionId": session_id, + "prompt": [{ "type": "text", "text": "never read" }] + }), + ) + .await; + let first = proxy.read().await; + assert_eq!(first["method"], json!("session/update")); + let events = read_events(&root.record_path()); + let pids = recorded_pids(&events); + + // The client never reads again. The accepted report backlog cannot drain + // before the absolute deadline, so the proxy must not claim a clean exit. + let started = Instant::now(); + proxy.close_stdin(); + let (status, stderr) = proxy.finish_without_stdout(Duration::from_secs(12)).await; + let elapsed = started.elapsed(); + assert_eq!( + status.code(), + Some(1), + "an unflushed output must be a fixed proxy failure: {status:?}, stderr={stderr:?}" + ); + assert_eq!( + String::from_utf8_lossy(&stderr).trim(), + "acp_proxy_failed", + "the proxy must emit one fixed diagnostic, not a clean acknowledgement" + ); + assert!( + elapsed >= SHUTDOWN_HARD_BOUND, + "the hard deadline, not an earlier claim, must bound the failed flush: {elapsed:?}" + ); + assert!( + elapsed < SHUTDOWN_HARD_BOUND + SHUTDOWN_SCHEDULING_ALLOWANCE, + "the forced drop must exit within the measured scheduling allowance: {elapsed:?}" + ); + assert_stderr_is_fixed_codes(&stderr, &marker); + for pid in &pids.0 { + wait_process_gone(*pid); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn missing_harness_fails_bounded_with_a_fixed_code() { + let mut child = Command::new(binary()) + .args([ + "acp", + "proxy", + "--", + "/definitely/missing/rustscript-acp-harness", + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .kill_on_drop(true) + .spawn() + .expect("spawn acp proxy with a missing harness"); + drop(child.stdin.take()); + let output = tokio::time::timeout(Duration::from_secs(10), child.wait_with_output()) + .await + .expect("missing harness handling must be bounded") + .expect("wait for acp proxy"); + assert_eq!(output.status.code(), Some(1)); + assert!(output.stdout.is_empty(), "stdout must stay protocol-only"); + assert_eq!( + String::from_utf8_lossy(&output.stderr).trim(), + "acp_harness_unavailable" + ); +} + +#[test] +fn acp_proxy_cli_keeps_the_harness_argv_exact_and_documents_read_only() { + use rustscript_agent::cli::{CliError, CliInvocation, parse_cli_args}; + + let invocation = parse_cli_args( + [ + "acp", + "proxy", + "--read-only", + "--", + "/opt/fixture-harness", + "--flag", + "hello world", + "--acp", + ] + .map(OsString::from), + ) + .expect("valid acp proxy invocation"); + let CliInvocation::AcpProxy(config) = invocation else { + panic!("acp proxy parsed as the wrong command"); + }; + assert_eq!(config.command(), Path::new("/opt/fixture-harness")); + assert_eq!( + config.arguments(), + &[ + "--flag".to_owned(), + "hello world".to_owned(), + "--acp".to_owned() + ] + ); + assert!(config.read_only()); + + assert!(matches!( + parse_cli_args(["acp", "--help"].map(OsString::from)), + Ok(CliInvocation::Help) + )); + let usage = rustscript_agent::cli::cli_usage(); + assert!( + usage.contains("acp proxy [--read-only] -- HARNESS"), + "the ACP proxy shape must stay documented: {usage}" + ); + assert!( + usage.contains("--read-only selects the read-only profile for injected RustScript tools"), + "--read-only must document its scope: {usage}" + ); + for invalid in [ + vec!["acp", "proxy"], + vec![ + "acp", + "proxy", + "--read-only", + "--read-only", + "--", + "/bin/true", + ], + vec!["acp", "proxy", "--unknown", "--", "/bin/true"], + vec!["acp", "proxy", "--"], + vec!["acp", "unknown"], + ] { + assert_eq!( + parse_cli_args(invalid.into_iter().map(OsString::from)), + Err(CliError::InvalidArguments), + "ambiguous ACP CLI form must be rejected" + ); + } + + assert!(matches!( + parse_cli_args(["auth", "status"].map(OsString::from)), + Ok(CliInvocation::Auth(_)) + )); + assert!(matches!( + parse_cli_args( + [ + "tools", + "serve", + "--stdio", + "--workspace", + "/fixture/workspace" + ] + .map(OsString::from) + ), + Ok(CliInvocation::ToolsServe(_)) + )); +} + +#[test] +fn acp_proxy_config_enforces_bounded_harness_argv() { + use rustscript_agent::acp::config::{ + AcpProxyConfig, MAX_HARNESS_ARGUMENT_BYTES, MAX_HARNESS_ARGUMENTS, MAX_HARNESS_ARGV_BYTES, + }; + + assert!( + AcpProxyConfig::new(PathBuf::new(), Vec::new(), false).is_err(), + "an empty harness command is invalid" + ); + assert!( + AcpProxyConfig::new( + PathBuf::from("/bin/true"), + vec!["ok".to_owned(); MAX_HARNESS_ARGUMENTS + 1], + false + ) + .is_err() + ); + assert!( + AcpProxyConfig::new( + PathBuf::from("/bin/true"), + vec!["x".repeat(MAX_HARNESS_ARGUMENT_BYTES + 1)], + false + ) + .is_err() + ); + assert!( + AcpProxyConfig::new( + PathBuf::from("/bin/true"), + vec![ + "x".repeat(MAX_HARNESS_ARGUMENT_BYTES); + MAX_HARNESS_ARGV_BYTES / MAX_HARNESS_ARGUMENT_BYTES + 1 + ], + false + ) + .is_err() + ); + let valid = AcpProxyConfig::new(PathBuf::from("/bin/true"), vec![], true) + .expect("valid bounded config"); + assert!(valid.read_only()); +} + +const RESOURCE_LINE_BYTES: usize = 1024 * 1024; + +#[tokio::test] +async fn resource_client_line_limit_is_checked_before_newline() { + let root = TestRoot::new("client-line-limit"); + let mut proxy = Proxy::spawn(&root, "normal", &[]); + let _ = proxy.initialize().await; + let head = br#"{"jsonrpc":"2.0","id":43,"method":"fixture/echo","params":{"text":""#; + let tail = b"\"}}"; + let mut line = head.to_vec(); + line.resize(RESOURCE_LINE_BYTES - tail.len(), b'x'); + line.extend_from_slice(tail); + line.push(b'\n'); + proxy + .stdin + .as_mut() + .unwrap() + .write_all(&line) + .await + .unwrap(); + assert_eq!(proxy.read_response(43).await.0["error"]["code"], -32601); + + line.pop(); + line.push(b' '); + proxy + .stdin + .as_mut() + .unwrap() + .write_all(&line) + .await + .unwrap(); + // Leave stdin open: the proxy must not wait for LF or EOF. + let (status, trailing, stderr) = proxy.finish(Duration::from_secs(8)).await; + assert!(!status.success()); + assert!(trailing.is_empty()); + assert_eq!(stderr, b"acp_proxy_failed\n"); +} + +#[tokio::test] +async fn resource_harness_line_limit_is_checked_before_newline() { + let root = TestRoot::new("harness-line-limit"); + let mut proxy = Proxy::spawn(&root, "normal", &[]); + let _ = proxy.initialize().await; + let accepted = exchange( + &mut proxy, + json!(9), + "fixture/wire_size", + &json!({ + "bytes": RESOURCE_LINE_BYTES, "newline": true, + }), + ) + .await; + assert!(accepted["result"]["text"].as_str().unwrap().len() > RESOURCE_LINE_BYTES - 100); + let pids = recorded_pids(&read_events(&root.record_path())); + let id = proxy + .send_request( + "fixture/wire_size", + json!({ + "bytes": RESOURCE_LINE_BYTES + 1, "newline": false, + }), + ) + .await; + let (status, trailing, stderr) = proxy.finish(Duration::from_secs(8)).await; + assert!(!status.success()); + assert_eq!(stderr, b"acp_harness_exited\n"); + assert!(single_response(&trailing, id).get("error").is_some()); + for pid in &pids.0 { + wait_process_gone(*pid); + } +} + +#[tokio::test] +async fn resource_malformed_input_stops_without_reflecting_raw_data() { + for invalid in [ + "{\"provider\":\"synthetic-provider-secret\"\n", + "{\"jsonrpc\":\"not-2.0\",\"id\":17,\"method\":\"fixture/noop\"}\n", + ] { + let root = TestRoot::new("parse-error"); + let mut proxy = Proxy::spawn(&root, "normal", &[]); + let _ = proxy.initialize().await; + proxy + .stdin + .as_mut() + .unwrap() + .write_all(invalid.as_bytes()) + .await + .unwrap(); + let (status, trailing, stderr) = proxy.finish(Duration::from_secs(8)).await; + assert!(!status.success()); + assert_eq!(stderr, b"acp_proxy_failed\n"); + assert!( + trailing.is_empty(), + "malformed bytes must never be reflected" + ); + } +} + +#[tokio::test] +async fn resource_duplicate_active_id_stops_before_forwarding_the_second_request() { + let root = TestRoot::new("duplicate-request-id"); + let mut proxy = Proxy::spawn(&root, "normal", &[]); + let _ = proxy.initialize().await; + let id = proxy + .send_request("fixture/hold", json!({ "barrier": true })) + .await; + wait_for_event(&root.record_path(), "held_barrier"); + proxy + .send(json!({ "jsonrpc": "2.0", "id": id, "method": "fixture/noop" })) + .await; + let (status, trailing, stderr) = proxy.finish(Duration::from_secs(8)).await; + assert!(!status.success()); + assert_eq!(stderr, b"acp_proxy_failed\n"); + assert!(single_response(&trailing, id).get("error").is_some()); + assert!(events_named(&read_events(&root.record_path()), "unsupported_request").is_empty()); +} + +#[tokio::test] +async fn resource_same_number_in_opposite_directions_is_independent_and_reusable() { + let root = TestRoot::new("request-id-overlap"); + let mut proxy = Proxy::spawn(&root, "numeric_overlap", &[]); + let _ = proxy.initialize().await; + for value in ["first", "second"] { + proxy + .send(json!({ "jsonrpc": "2.0", "id": 71, "method": "fixture/hold" })) + .await; + let reverse = proxy.read().await; + assert_eq!(reverse["method"], "fixture/client_request"); + proxy + .respond(&reverse["id"], json!({ "echo": value })) + .await; + let (forward, _) = proxy.read_response(71).await; + assert_eq!(forward["result"]["peerResult"]["echo"], value); + } + proxy.close_stdin(); + let (status, trailing, stderr) = proxy.finish(EXIT_WATCHDOG).await; + assert!(status.success()); + assert!(trailing.is_empty() && stderr.is_empty()); + assert_eq!( + events_named(&read_events(&root.record_path()), "numeric_response").len(), + 2 + ); +} + +#[tokio::test] +async fn resource_notification_receipts_preserve_params_and_fifo_on_the_wire() { + let root = TestRoot::new("notification-receipts"); + let mut proxy = Proxy::spawn(&root, "normal", &[]); + let _ = proxy.initialize().await; + let params = [ + Value::Null, + json!({"_meta": {"fixture": "ordinary"}, "extra": ["value"]}), + json!(["rustscript-acp-write-receipt", 77]), + ]; + for value in ¶ms { + proxy + .send_notification("fixture/notice", value.clone()) + .await; + } + let barrier = proxy.send_request("fixture/barrier", json!({})).await; + assert_eq!( + proxy.read_response(barrier).await.0["error"]["code"], + -32601 + ); + proxy.close_stdin(); + let (status, trailing, stderr) = proxy.finish(EXIT_WATCHDOG).await; + assert!(status.success() && trailing.is_empty() && stderr.is_empty()); + let events = read_events(&root.record_path()); + let observed: Vec<_> = events_named(&events, "unsupported_request") + .into_iter() + .map(|event| (&event["data"]["method"], &event["data"]["params"])) + .collect(); + assert_eq!( + observed, + vec![ + (&json!("fixture/notice"), ¶ms[0]), + (&json!("fixture/notice"), ¶ms[1]), + (&json!("fixture/notice"), ¶ms[2]), + (&json!("fixture/barrier"), &json!({})), + ] + ); +} + +#[tokio::test] +async fn resource_pending_window_releases_on_reply_and_settles_the_accepted_prefix() { + const WINDOW: i64 = 1024; + let root = TestRoot::new("pending-window"); + let mut proxy = Proxy::spawn(&root, "normal", &[]); + let _ = proxy.initialize().await; + let requests = (1..=WINDOW) + .map(|id| { + json!({ + "jsonrpc": "2.0", "id": id, "method": "fixture/hold", + "params": { "barrier": id == WINDOW }, + }) + }) + .collect::>(); + proxy.send_batch(&requests).await; + wait_for_event(&root.record_path(), "held_barrier"); + proxy.send_notification("fixture/release", json!({})).await; + assert_eq!(proxy.read_response(1).await.0["result"]["released"], true); + proxy + .send(json!({ "jsonrpc": "2.0", "id": 1, "method": "fixture/hold" })) + .await; + proxy + .send(json!({ "jsonrpc": "2.0", "id": WINDOW + 1, "method": "fixture/noop" })) + .await; + let mut out = String::new(); + tokio::time::timeout( + Duration::from_secs(8), + proxy.stdout.as_mut().unwrap().read_to_string(&mut out), + ) + .await + .unwrap() + .unwrap(); + let drained = out + .lines() + .map(|line| serde_json::from_str::(line).unwrap()) + .collect::>(); + let (status, trailing, stderr) = proxy.finish(EXIT_WATCHDOG).await; + assert!(!status.success()); + assert_eq!(stderr, b"acp_proxy_failed\n"); + assert!(trailing.is_empty()); + assert_eq!(drained.len(), WINDOW as usize); + for id in 1..=WINDOW { + assert!(single_response(&drained, id).get("error").is_some()); + } + assert!(events_named(&read_events(&root.record_path()), "unsupported_request").is_empty()); +} + +#[tokio::test] +async fn resource_session_capacity_includes_setup_and_reuses_existing_identity() { + let root = TestRoot::new("session-capacity"); + let mut proxy = Proxy::spawn(&root, "normal", &[]); + let _ = proxy.initialize().await; + for _ in 0..31 { + proxy.new_session(&root.path).await; + } + let held = proxy + .send_request( + "session/new", + json!({ + "cwd": root.path, "mcpServers": [], "_meta": { "hold": true }, + }), + ) + .await; + wait_for_event(&root.record_path(), "setup_held"); + let refused = exchange( + &mut proxy, + json!(70), + "session/load", + &json!({ + "sessionId": "not-admitted", "cwd": root.path, "mcpServers": [], + }), + ) + .await; + assert_eq!(refused["error"]["data"]["reason"], "proxy_session_limit"); + for method in ["session/load", "session/resume"] { + let response = exchange( + &mut proxy, + json!(70), + method, + &json!({ + "sessionId": "fixture-session-1", "cwd": root.path, "mcpServers": [], + }), + ) + .await; + assert!(response.get("result").is_some()); + } + proxy.send_notification("fixture/release", json!({})).await; + assert!(proxy.read_response(held).await.0.get("result").is_some()); + assert_eq!(proxy.new_session(&root.path).await.0, "fixture-session-32"); + let refused = exchange( + &mut proxy, + json!(70), + "session/new", + &json!({ + "cwd": root.path, "mcpServers": [], + }), + ) + .await; + assert_eq!(refused["error"]["data"]["reason"], "proxy_session_limit"); + let events = finish_session_mcp(proxy, &root).await; + assert_eq!(events_named(&events, "session/cancel").len(), 32); + assert_eq!(events_named(&events, "setup_wire").len(), 35); +} + +#[tokio::test] +async fn resource_stderr_is_drained_without_leaking_child_environment() { + let root = TestRoot::new("stderr-bounded"); + let marker = "fake-credential-not-for-diagnostics"; + let mut proxy = Proxy::spawn(&root, "exit_on_prompt", &[("FAKE_ACP_DUMMY_AUTH", marker)]); + let _ = proxy.initialize().await; + let (session, _) = proxy.new_session(&root.path).await; + assert_eq!( + exchange(&mut proxy, json!(70), "fixture/stderr", &json!({})).await["result"]["drained"], + true + ); + let id = proxy + .send_request( + "session/prompt", + json!({ "sessionId": session, "prompt": [] }), + ) + .await; + let (status, trailing, stderr) = proxy.finish(EXIT_WATCHDOG).await; + assert!(!status.success()); + assert_eq!(stderr, b"acp_harness_exited\n"); + assert!(single_response(&trailing, id).get("error").is_some()); +} + +/// The readiness decisions are timing-sensitive inside `run_proxy`'s foreground +/// and cannot be produced deterministically through a packaged process: a +/// missing harness fails during spawn, before the client can be guaranteed to +/// have one request queued. `acp_proxy_bridge` compiles the real bridge source +/// into this test binary and drives `drive_upstream` with an owned readiness +/// channel instead of reimplementing its phases. The packaged cases above still +/// cover the observable ordering and lifecycle of the binary. +#[allow(dead_code)] +#[path = "acp_proxy_bridge/mod.rs"] +mod internal_bridge; diff --git a/tests/acp_sdk_contract_tests.rs b/tests/acp_sdk_contract_tests.rs new file mode 100644 index 00000000..87a65df3 --- /dev/null +++ b/tests/acp_sdk_contract_tests.rs @@ -0,0 +1,457 @@ +//! Compile-time and value-level contract for the official ACP v1 and MCP SDKs. +//! +//! These tests make no network calls. They pin the API surface the ACP proxy and +//! MCP tool server are built on, so a dependency upgrade that changes the proxy +//! process boundary, the stdio declaration shape, or the MCP server handler +//! contract fails here first. +//! +//! The SDK's stable `Proxy`/`Conductor` roles require the schema's +//! `unstable_proxy_chains` types. `agent-client-protocol` 5.x force-enables +//! that schema feature internally; it is an upstream prerequisite, not a +//! project opt-in and not a user-facing proxy-chain contract. All other +//! unstable, HTTP/auth, and rmcp client surfaces stay unselected. + +use std::path::Path; +use std::sync::Arc; + +use agent_client_protocol::schema::ProtocolVersion; +use agent_client_protocol::v1::schema::{ + AgentCapabilities, LoadSessionRequest, LoadSessionResponse, McpServer, McpServerStdio, + NewSessionRequest, NewSessionResponse, ResumeSessionRequest, ResumeSessionResponse, + SessionCapabilities, SessionResumeCapabilities, +}; +use agent_client_protocol::{ + AcpAgent, AcpAgentConfig, Agent, Client, Conductor, ConnectTo, JsonRpcMessage, JsonRpcRequest, + JsonRpcResponse, Proxy, UntypedMessage, +}; +use rmcp::model::{CallToolResult, ContentBlock, ServerCapabilities, ServerConfig}; +use rmcp::{ServerHandler, ServiceExt}; +use serde_json::{Map, Value, json}; + +/// An agent component serves a client. +fn assert_connects_to_client>(_value: &C) {} + +/// A client component connects to an agent. +fn assert_connects_to_agent>(_value: &C) {} + +/// A proxy component connects to a conductor. +fn assert_connects_to_conductor>(_value: &C) {} + +/// The two halves of the proxy process path type-check together: the proxy +/// connects to a conductor while the spawned downstream agent serves a client. +/// This is compile-only; it never opens a transport or spawns a process. +fn assert_proxy_process_composition(_proxy: &P, _agent: &A) +where + P: ConnectTo, + A: ConnectTo, +{ +} + +/// Every `ServerHandler` is a servable MCP server. +fn assert_servable>() {} + +/// An absolute Linux CI workspace path. These tests never create or touch it. +const TEST_WORKSPACE: &str = "/home/runner/work/rustscript-agent/workspace"; + +/// Compile-time proof that a request type owns the expected typed response. +fn assert_request_owns_response() +where + Req: JsonRpcRequest, + Resp: JsonRpcResponse, +{ +} + +/// The one stdio declaration exercised inside each session request envelope. +/// +/// The explicit empty environment list is deliberate: Task 7 must not copy the +/// parent environment into the injected server declaration. +fn stdio_tools_server() -> McpServer { + McpServer::Stdio( + McpServerStdio::new("rustscript-tools", "/opt/rustscript/bin/rustscript-agent") + .args(vec![ + "tools".to_owned(), + "serve".to_owned(), + "--stdio".to_owned(), + ]) + .env(Vec::new()), + ) +} + +/// Non-secret request metadata with a nested object, so `_meta` round-tripping +/// is checked as data rather than only as a present-or-absent key. +fn request_meta(trace: &str) -> Map { + let mut meta = Map::new(); + meta.insert( + "caller".to_owned(), + json!({ + "trace": trace, + "keep": {"nested": true} + }), + ); + meta +} + +/// A caller session payload with a benign unknown top-level key and an unknown +/// extension on every MCP declaration. This is intentionally the raw untyped +/// shape accepted at the proxy's untyped session boundary. +fn caller_session_params(method: &str) -> Value { + let mut params = json!({ + "cwd": TEST_WORKSPACE, + "mcpServers": [ + { + "name": "caller-http-tools", + "type": "http", + "url": "http://127.0.0.1:8765/mcp", + "headers": [], + "_meta": {"caller": {"keep": "http-declaration-meta"}}, + "x-declaration-extension": {"mode": "read-only", "revision": 7} + }, + { + "name": "caller-stdio-tools", + "command": "/opt/caller/bin/mcp-stdio-after", + "args": ["--stdio"], + "env": [{"name": "CALLER_FLAG", "value": "kept"}], + "x-declaration-extension": {"mode": "read-only", "revision": 7} + } + ], + "_meta": {"caller": {"request": "keep-me"}}, + "x-caller-trace": {"id": "trace-001", "hops": [1, 2, 3]} + }); + if method != "session/new" { + params["sessionId"] = json!("session-existing-01"); + } + params +} + +/// Parse through the pinned typed SDK type and re-encode through its public +/// `JsonRpcMessage` API, producing exactly what a typed round trip would send. +fn typed_reencode(method: &str, params: &Value) -> Value { + let request = R::parse_message(method, params).expect("parse typed session request"); + request + .to_untyped_message() + .expect("re-encode typed session request") + .into_parts() + .1 +} + +#[derive(Clone, Default)] +struct ContractServer; + +impl ServerHandler for ContractServer { + fn get_info(&self) -> ServerConfig { + ServerConfig::new(ServerCapabilities::builder().enable_tools().build()) + .with_instructions("contract") + } + + async fn list_tools( + &self, + _request: Option, + _context: rmcp::service::RequestContext, + ) -> Result { + Ok(rmcp::model::ListToolsResult::with_all_items(Vec::new())) + } + + async fn call_tool( + &self, + _request: rmcp::model::CallToolRequestParams, + _context: rmcp::service::RequestContext, + ) -> Result { + Ok(CallToolResult::success(vec![ContentBlock::text("ok")]).into()) + } +} + +#[test] +fn stable_v1_roles_and_process_transport_are_available() { + // `LATEST` only exists while draft v2 is disabled, so this assertion is a + // compile-time guard against enabling `unstable_protocol_v2`. + assert_eq!(ProtocolVersion::LATEST, ProtocolVersion::V1); + assert_eq!(ProtocolVersion::LATEST.as_u16(), 1); + + let agent = AcpAgent::new(AcpAgentConfig::new("/bin/true").args(["--acp", "--verbose"])); + assert_eq!(agent.config().command(), Path::new("/bin/true")); + assert_eq!(agent.config().arguments(), ["--acp", "--verbose"]); + assert!(agent.config().environment().is_empty()); + + assert_connects_to_client(&Agent.v1()); + assert_connects_to_agent(&Client.v1()); + // The stable Proxy/Conductor process path is the required proxy role. + // Its schema proxy-chain types are force-enabled inside the SDK, which is + // the only accepted unstable schema prerequisite; this project selects no + // unstable ACP feature itself. + assert_connects_to_conductor(&Proxy.v1()); + assert_connects_to_client(&agent); + assert_proxy_process_composition(&Proxy.v1(), &agent); +} + +/// Returns the one-line dependency declaration for `name` in Cargo.toml. +fn dependency_declaration<'a>(manifest: &'a str, name: &str) -> &'a str { + let prefix = format!("{name} ="); + manifest + .lines() + .find(|line| line.trim_start().starts_with(&prefix)) + .unwrap_or_else(|| panic!("missing {name} dependency declaration")) +} + +#[test] +fn direct_dependency_features_stay_on_the_stable_v1_server_boundary() { + let manifest = include_str!("../Cargo.toml"); + + let acp = dependency_declaration(manifest, "agent-client-protocol"); + assert!(acp.contains("default-features = false")); + assert!(acp.contains(r#"features = ["process", "stdio"]"#)); + for forbidden in [ + "unstable_protocol_v2", + "unstable_mcp_over_acp", + "unstable_auth_status", + "unstable_llm_providers", + ] { + assert!( + !acp.contains(forbidden), + "ACP feature `{forbidden}` must stay off" + ); + } + + let rmcp = dependency_declaration(manifest, "rmcp"); + assert!(rmcp.contains("default-features = false")); + assert!(rmcp.contains(r#"features = ["server", "macros", "transport-io"]"#)); + for forbidden in ["client", "http", "reqwest", "oauth"] { + assert!( + !rmcp.contains(forbidden), + "rmcp feature `{forbidden}` must stay off" + ); + } +} + +#[test] +fn stdio_mcp_declaration_matches_the_stable_v1_wire_shape() { + let server = McpServer::Stdio( + McpServerStdio::new("rustscript-tools", "/opt/bin/rustscript-agent") + .args(vec![ + "tools".to_owned(), + "serve".to_owned(), + "--stdio".to_owned(), + ]) + .env(Vec::new()), + ); + let value = serde_json::to_value(&server).expect("serialize stdio server"); + // Stable v1 serializes stdio declarations untagged; the tagged form is + // accepted on input, which keeps this compatible with other ACP peers. + assert_eq!( + value, + serde_json::json!({ + "name": "rustscript-tools", + "command": "/opt/bin/rustscript-agent", + "args": ["tools", "serve", "--stdio"], + "env": [], + }) + ); + + let untagged: McpServer = serde_json::from_value(value.clone()).expect("parse untagged"); + assert_eq!(untagged, server); + + let mut tagged = value; + tagged["type"] = serde_json::json!("stdio"); + let tagged: McpServer = serde_json::from_value(tagged).expect("parse tagged"); + assert_eq!(tagged, server); +} + +#[test] +fn rmcp_server_handler_contract_advertises_tools_servable_over_stdio() { + let server = Arc::new(ContractServer); + let info = server.get_info(); + assert!(info.capabilities.tools.is_some()); + assert_eq!(info.instructions.as_deref(), Some("contract")); + + assert_servable::(); + // The stdio transport constructor is the boundary the binary uses. + let (_stdin, _stdout) = rmcp::transport::stdio(); +} + +#[test] +fn typed_v1_session_requests_own_the_stable_new_load_and_resume_envelopes() { + // The response associated types are part of the typed owning request + // contract, not just the request payload structs. + assert_request_owns_response::(); + assert_request_owns_response::(); + assert_request_owns_response::(); + + // Exact method selection is a public trait property of the typed request. + assert!(NewSessionRequest::matches_method("session/new")); + assert!(LoadSessionRequest::matches_method("session/load")); + assert!(ResumeSessionRequest::matches_method("session/resume")); + assert!(!NewSessionRequest::matches_method("session/load")); + assert!(!LoadSessionRequest::matches_method("session/new")); + assert!(!ResumeSessionRequest::matches_method("session/load")); + + // A near-miss method must not parse as any of the three typed requests. + assert!(NewSessionRequest::parse_message("session/load", &json!({})).is_err()); + assert!(LoadSessionRequest::parse_message("session/resume", &json!({})).is_err()); + assert!(ResumeSessionRequest::parse_message("session/new", &json!({})).is_err()); + + let new_request = NewSessionRequest::new(TEST_WORKSPACE) + .mcp_servers(vec![stdio_tools_server()]) + .meta(request_meta("new-trace")); + assert_eq!(new_request.method(), "session/new"); + let new_message = new_request + .to_untyped_message() + .expect("encode session/new request"); + assert_eq!(new_message.method(), "session/new"); + assert_eq!( + new_message.params(), + &json!({ + "cwd": TEST_WORKSPACE, + "mcpServers": [{ + "name": "rustscript-tools", + "command": "/opt/rustscript/bin/rustscript-agent", + "args": ["tools", "serve", "--stdio"], + "env": [] + }], + "_meta": { + "caller": {"trace": "new-trace", "keep": {"nested": true}} + } + }) + ); + assert!(new_message.params().get("sessionId").is_none()); + + let parsed_new = NewSessionRequest::parse_message(new_message.method(), new_message.params()) + .expect("parse typed session/new request"); + assert_eq!(parsed_new.cwd.as_path(), Path::new(TEST_WORKSPACE)); + assert_eq!(parsed_new.mcp_servers, vec![stdio_tools_server()]); + assert_eq!(parsed_new.meta.as_ref(), Some(&request_meta("new-trace"))); + + let load_request = LoadSessionRequest::new("session-load-01", TEST_WORKSPACE) + .mcp_servers(vec![stdio_tools_server()]) + .meta(request_meta("load-trace")); + assert_eq!(load_request.method(), "session/load"); + let load_message = load_request + .to_untyped_message() + .expect("encode session/load request"); + assert_eq!(load_message.method(), "session/load"); + assert_eq!( + load_message.params(), + &json!({ + "mcpServers": [{ + "name": "rustscript-tools", + "command": "/opt/rustscript/bin/rustscript-agent", + "args": ["tools", "serve", "--stdio"], + "env": [] + }], + "cwd": TEST_WORKSPACE, + "sessionId": "session-load-01", + "_meta": { + "caller": {"trace": "load-trace", "keep": {"nested": true}} + } + }) + ); + + let resume_request = ResumeSessionRequest::new("session-resume-01", TEST_WORKSPACE) + .mcp_servers(vec![stdio_tools_server()]) + .meta(request_meta("resume-trace")); + assert_eq!(resume_request.method(), "session/resume"); + let resume_message = resume_request + .to_untyped_message() + .expect("encode session/resume request"); + assert_eq!(resume_message.method(), "session/resume"); + assert_eq!( + resume_message.params(), + &json!({ + "sessionId": "session-resume-01", + "cwd": TEST_WORKSPACE, + "mcpServers": [{ + "name": "rustscript-tools", + "command": "/opt/rustscript/bin/rustscript-agent", + "args": ["tools", "serve", "--stdio"], + "env": [] + }], + "_meta": { + "caller": {"trace": "resume-trace", "keep": {"nested": true}} + } + }) + ); + + let parsed_load = + LoadSessionRequest::parse_message(load_message.method(), load_message.params()) + .expect("parse typed session/load request"); + let parsed_resume = + ResumeSessionRequest::parse_message(resume_message.method(), resume_message.params()) + .expect("parse typed session/resume request"); + assert_eq!(parsed_load.session_id.to_string(), "session-load-01"); + assert_eq!(parsed_resume.session_id.to_string(), "session-resume-01"); + assert_eq!(parsed_load.cwd, parsed_resume.cwd); + assert_eq!(parsed_load.cwd.as_path(), Path::new(TEST_WORKSPACE)); +} + +#[test] +fn stable_v1_session_capabilities_expose_load_and_resume_independently() { + // `loadSession` is the top-level capability for session/load; `resume` is + // the stable per-session capability for session/resume. Both compile + // without any unstable feature. + let capabilities = AgentCapabilities::new() + .load_session(true) + .session_capabilities(SessionCapabilities::new().resume(SessionResumeCapabilities::new())); + assert!(capabilities.load_session); + assert!(capabilities.session_capabilities.resume.is_some()); + + let value = serde_json::to_value(&capabilities).expect("encode agent capabilities"); + assert_eq!(value["loadSession"], json!(true)); + assert_eq!(value["sessionCapabilities"], json!({"resume": {}})); + + let decoded: AgentCapabilities = + serde_json::from_value(value).expect("decode agent capabilities"); + assert!(decoded.load_session); + assert!(decoded.session_capabilities.resume.is_some()); +} + +#[test] +fn session_requests_round_trip_untyped_payloads_and_typed_v1_fields() { + type TypedRoundtrip = fn(&str, &Value) -> Value; + let cases: [(&str, TypedRoundtrip); 3] = [ + ("session/new", typed_reencode::), + ("session/load", typed_reencode::), + ("session/resume", typed_reencode::), + ]; + + for (method, typed_roundtrip) in cases { + let source = caller_session_params(method); + let boundary: UntypedMessage = serde_json::from_value(json!({ + "method": method, + "params": source.clone(), + })) + .expect("decode untyped session request"); + assert_eq!(boundary.method(), method); + assert_eq!( + boundary.params(), + &source, + "untyped boundary must preserve the caller payload verbatim for {method}" + ); + + let typed = typed_roundtrip(method, &source); + assert_eq!(typed["cwd"], source["cwd"]); + assert_eq!(typed.get("sessionId"), source.get("sessionId")); + let original_servers = source["mcpServers"].as_array().expect("fixture mcpServers"); + assert_eq!( + typed["mcpServers"] + .as_array() + .expect("typed mcpServers") + .len(), + original_servers.len() + ); + for (index, original) in original_servers.iter().enumerate() { + for key in [ + "name", "type", "url", "headers", "command", "args", "env", "_meta", + ] { + if let Some(expected) = original.get(key) { + assert_eq!( + typed["mcpServers"][index].get(key), + Some(expected), + "known key `{key}` changed in typed re-encoding of {method}" + ); + } + } + } + assert_eq!( + typed["_meta"], source["_meta"], + "declared request _meta must survive typed re-encoding of {method}" + ); + } +} diff --git a/tests/fixtures/acp/build.rs b/tests/fixtures/acp/build.rs new file mode 100644 index 00000000..56e78e58 --- /dev/null +++ b/tests/fixtures/acp/build.rs @@ -0,0 +1,35 @@ +use std::{fs, path::Path, process::Command}; + +/// Compile the same fake peer for the packaged ACP transport and MCP tests. +pub fn compile_fake_agent(binary: &Path) { + let current = std::env::current_exe().expect("resolve current test executable"); + let deps = current.parent().expect("cargo deps directory"); + let serde_json = fs::read_dir(deps) + .expect("read cargo deps directory") + .filter_map(Result::ok) + .map(|entry| entry.path()) + .filter(|path| { + path.file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| name.starts_with("libserde_json-") && name.ends_with(".rlib")) + }) + .min() + .expect("cargo built a serde_json rlib for this test profile"); + let rustc = std::env::var_os("RUSTC").unwrap_or_else(|| "rustc".into()); + let output = Command::new(rustc) + .arg("--edition=2021") + .arg(Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/acp/fake_agent.rs")) + .arg("--extern") + .arg(format!("serde_json={}", serde_json.display())) + .arg("-L") + .arg(format!("dependency={}", deps.display())) + .arg("-o") + .arg(binary) + .output() + .expect("run rustc for the ACP fixture harness"); + assert!( + output.status.success(), + "fixture harness did not compile: {}", + String::from_utf8_lossy(&output.stderr) + ); +} diff --git a/tests/fixtures/acp/fake_agent.rs b/tests/fixtures/acp/fake_agent.rs new file mode 100644 index 00000000..c0a06f34 --- /dev/null +++ b/tests/fixtures/acp/fake_agent.rs @@ -0,0 +1,653 @@ +//! Test-only deterministic ACP v1 downstream harness. +//! +//! This fixture is compiled by `tests/acp_proxy_tests.rs` with `rustc` so the +//! integration tests can exercise the packaged `rustscript-agent acp proxy` +//! binary over real pipes without adding a second shipped binary target. +//! +//! It speaks one JSON-RPC object per line using `serde_json`. It is a peer +//! implementation for tests, not production transport code; the production +//! path uses `agent-client-protocol` framing only. +//! +//! Modes (`FAKE_ACP_MODE`): +//! - `normal` (default): initialize, session/new, session/prompt with +//! streamed updates and one permission request. +//! - `cancel`: prompt emits one update and stays pending until +//! `session/cancel` names that session. +//! - `exit_on_prompt`: record the prompt, write the stderr marker, exit 3 +//! without answering so the proxy must fail the pending request upstream. +//! - `coalesced`: answer the prompt and emit a `session/update` in one write so +//! the proxy must keep the response ahead of the notification. +//! - `hold`: answer `session/new` and `initialize`, stream one update for a +//! prompt, then ignore both cancellation and the prompt while keeping stdout +//! open; exit on stdin EOF. +//! - `stubborn`: like `hold` for prompts, but also ignore stdin EOF for a long +//! time so the proxy must terminate the owned process group. +//! - `blocked`: stop reading stdin when `fixture/block` arrives, keeping stdout +//! open, so forwarded traffic fills the pipe and the proxy must enforce its +//! shutdown deadline. +//! - `reply_update_then_exit`: hold one prompt, then on `session/cancel` write a +//! `session/update` followed by the prompt result in one system write and exit, +//! exposing a settlement that must not overtake the earlier update. +//! - `delayed_load`: answer `session/load` and `session/resume` with `{}` after a +//! short delay, so a setup accepted before shutdown completes while the proxy +//! is already settling. +//! - `blocked_late_load`: the same delayed setup answer, then block on the +//! `fixture/block` notification without reading stdin again, so a filled pipe +//! keeps the proxy's synthetic cancellation away from this application. +//! - `flood`: stream a known, finite update backlog for one prompt before holding +//! it, so a client that stops reading blocks the proxy's physical stdout flush. +//! - `own_mcp`: start the session's injected stdio server and drive real tools. +//! +//! `FAKE_ACP_RECORD` is a JSONL event log: every received request or +//! notification is appended as `{"event": , "data": }`. Tests +//! assert the recorded declarations and payloads after the proxy exits. + +use std::collections::HashMap; +use std::env; +use std::fs::{File, OpenOptions}; +use std::io::{self, BufRead, Write}; +use std::process::Command; +use std::time::Duration; + +use serde_json::{Value, json}; + +mod owning_mcp; + +const DEFAULT_MARKER: &str = "fixture-benign-stderr-marker"; +/// Number of `session/update` notifications `flood` streams for one prompt. +const FLOOD_UPDATES: usize = 96; +/// Text payload of each flooded update, before JSON framing. +const FLOOD_TEXT_BYTES: usize = 16 * 1024; +/// Delay before a `delayed_load` setup response, measured from the request. +const DELAYED_LOAD: Duration = Duration::from_millis(250); + +struct PendingPrompt { + session_id: String, + prompt_id: Value, +} + +struct Harness { + mode: String, + events: Option, + out: io::Stdout, + sessions: HashMap, + next_session: u64, + next_permission: u64, + mcp: Option, +} + +impl Harness { + fn record(&mut self, event: &str, data: Value) { + if let Some(file) = self.events.as_mut() { + let line = json!({ "event": event, "data": data }); + let _ = writeln!(file, "{line}"); + let _ = file.flush(); + } + } + + fn send(&mut self, message: Value) { + let line = serde_json::to_string(&message).expect("serialize fixture message"); + let result = self + .out + .write_all(format!("{line}\n").as_bytes()) + .and_then(|()| self.out.flush()); + if let Err(error) = result { + // The proxy may stop reading its child's stdout during teardown. + // Keep serving stdin so the test can still assert what the proxy + // forwarded before it closed the connection. + self.record( + "stdout_write_error", + json!({ "kind": error.kind().to_string() }), + ); + } + } + + /// Write two protocol lines in one system write. This is the same-write + /// peer shape that exposes an unordered settlement overtaking a later + /// notification. + fn send_pair(&mut self, first: Value, second: Value) { + let first = serde_json::to_string(&first).expect("serialize fixture message"); + let second = serde_json::to_string(&second).expect("serialize fixture message"); + let result = self + .out + .write_all(format!("{first}\n{second}\n").as_bytes()) + .and_then(|()| self.out.flush()); + if let Err(error) = result { + self.record( + "stdout_write_error", + json!({ "kind": error.kind().to_string() }), + ); + } + } + + fn respond(&mut self, id: &Value, result: Value) { + self.send(json!({ "jsonrpc": "2.0", "id": id, "result": result })); + } + + fn respond_error(&mut self, id: &Value, code: i64, message: &str) { + self.send(json!({ + "jsonrpc": "2.0", + "id": id, + "error": { "code": code, "message": message } + })); + } + + fn update_message(&self, session_id: &str, update: Value) -> Value { + json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": { "sessionId": session_id, "update": update } + }) + } + + fn update(&mut self, session_id: &str, update: Value) { + let message = self.update_message(session_id, update); + self.send(message); + } + + fn initialize(&mut self, id: &Value, params: &Value) { + self.record("initialize", params.clone()); + let version = params + .get("protocolVersion") + .cloned() + .unwrap_or_else(|| json!(1)); + self.respond( + id, + json!({ + "protocolVersion": version, + "agentCapabilities": { + "loadSession": self.mode != "resume_only", + "sessionCapabilities": if self.mode == "load_only" { + json!({ "_meta": { "fixture": "no-resume" } }) + } else { + json!({ "resume": {}, "_meta": { "fixture": "resume" } }) + }, + "promptCapabilities": { + "image": false, + "audio": false, + "embeddedContext": false + } + }, + "agentInfo": { + "name": "fake-acp-harness", + "title": "Fake ACP Harness", + "version": "0.1.0" + }, + "_meta": { "fixture": "agent-meta" } + }), + ); + } + + fn new_session(&mut self, method: &str, id: &Value, params: &Value) { + if method != "session/new" { + // ACP v1 `session/load` and `session/resume` responses carry no + // session id: the request already names the session. + let session_id = params + .get("sessionId") + .and_then(Value::as_str) + .unwrap_or_default() + .to_owned(); + self.record(method, json!({ "params": params, "sessionId": session_id })); + if matches!(self.mode.as_str(), "delayed_load" | "blocked_late_load") { + // Complete a setup that was accepted before shutdown while the + // proxy is already settling. + std::thread::sleep(DELAYED_LOAD); + } + self.respond(id, json!({})); + self.record( + "setup_responded", + json!({ "method": method, "sessionId": session_id }), + ); + return; + } + self.next_session += 1; + let session_id = format!("fixture-session-{}", self.next_session); + self.record(method, json!({ "params": params, "sessionId": session_id })); + if self.mode == "own_mcp" { + match owning_mcp::start(self, params) { + Ok(mcp) => self.mcp = Some(mcp), + Err(error) => { + self.record("mcp_error", json!(error)); + self.respond_error(id, -32603, &error); + return; + } + } + } + self.respond(id, json!({ "sessionId": session_id })); + } + + fn prompt(&mut self, id: &Value, params: &Value) { + let session_id = params + .get("sessionId") + .and_then(Value::as_str) + .expect("prompt sessionId") + .to_owned(); + self.record("session/prompt", params.clone()); + if self.mode == "own_mcp" { + let result = match self.mcp.take() { + Some(mut mcp) => { + let result = mcp.turn(self, &session_id); + self.mcp = Some(mcp); + result + } + None => Err("no owned MCP server".to_owned()), + }; + match result { + Ok(()) => self.respond(id, json!({ "stopReason": "end_turn" })), + Err(error) => { + self.record("mcp_error", json!(error)); + self.respond_error(id, -32603, &error); + } + } + return; + } + + if self.mode == "exit_on_prompt" { + self.record("prompt_exit", json!({ "sessionId": session_id })); + let marker = + env::var("FAKE_ACP_STDERR_MARKER").unwrap_or_else(|_| DEFAULT_MARKER.to_owned()); + eprintln!("{marker}"); + std::process::exit(3); + } + + if self.mode == "coalesced" { + let response = json!({ + "jsonrpc": "2.0", + "id": id, + "result": { "stopReason": "end_turn" } + }); + let update = self.update_message( + &session_id, + json!({ + "sessionUpdate": "agent_message_chunk", + "content": { "type": "text", "text": "after-response" } + }), + ); + self.send_pair(response, update); + return; + } + + if self.mode == "flood" { + // A known, finite backlog: the proxy must read all of it and hand + // it to the client sink, but a client that stops reading blocks the + // physical flush well before the proxy's hard bound. + for index in 0..FLOOD_UPDATES { + let prefix = format!("flood-{index:03}-"); + let padding = "x".repeat(FLOOD_TEXT_BYTES.saturating_sub(prefix.len())); + self.update( + &session_id, + json!({ + "sessionUpdate": "agent_message_chunk", + "content": { "type": "text", "text": format!("{prefix}{padding}") } + }), + ); + } + self.record( + "flood_complete", + json!({ "updates": FLOOD_UPDATES, "textBytes": FLOOD_TEXT_BYTES }), + ); + self.sessions.insert( + format!("prompt:{id}"), + PendingPrompt { + session_id, + prompt_id: id.clone(), + }, + ); + return; + } + + self.update( + &session_id, + json!({ + "sessionUpdate": "agent_message_chunk", + "content": { "type": "text", "text": "working" } + }), + ); + + if matches!( + self.mode.as_str(), + "cancel" | "hold" | "stubborn" | "reply_update_then_exit" + ) { + self.sessions.insert( + format!("prompt:{id}"), + PendingPrompt { + session_id, + prompt_id: id.clone(), + }, + ); + return; + } + + self.update( + &session_id, + json!({ + "sessionUpdate": "tool_call", + "toolCallId": "fixture-call-1", + "title": "Fixture read", + "kind": "read", + "status": "pending" + }), + ); + self.update( + &session_id, + json!({ + "sessionUpdate": "tool_call_update", + "toolCallId": "fixture-call-1", + "status": "in_progress" + }), + ); + + self.next_permission += 1; + let permission_id = json!(format!("fixture-permission-{}", self.next_permission)); + self.record( + "permission_request", + json!({ "sessionId": session_id, "permissionId": permission_id }), + ); + self.sessions.insert( + permission_id.to_string(), + PendingPrompt { + session_id: session_id.clone(), + prompt_id: id.clone(), + }, + ); + self.send(json!({ + "jsonrpc": "2.0", + "id": permission_id, + "method": "session/request_permission", + "params": { + "sessionId": session_id, + "toolCall": { + "toolCallId": "fixture-call-1", + "title": "Fixture read", + "kind": "read", + "status": "pending" + }, + "options": [ + { "optionId": "allow", "name": "Allow", "kind": "allow_once" }, + { "optionId": "deny", "name": "Deny", "kind": "reject_once" } + ] + } + })); + } + + fn cancel(&mut self, params: &Value) { + let session_id = params + .get("sessionId") + .and_then(Value::as_str) + .unwrap_or_default() + .to_owned(); + self.record("session/cancel", params.clone()); + + if self.mode == "reply_update_then_exit" { + let key = self + .sessions + .iter() + .find(|(_, pending)| pending.session_id == session_id) + .map(|(key, _)| key.clone()); + if let Some(key) = key { + let pending = self + .sessions + .remove(&key) + .expect("pending prompt observed above"); + // One system write: the earlier update and the prompt result + // are both read before the proxy observes the harness exit. + let update = self.update_message( + &pending.session_id, + json!({ + "sessionUpdate": "agent_message_chunk", + "content": { "type": "text", "text": "before-result" } + }), + ); + let response = json!({ + "jsonrpc": "2.0", + "id": pending.prompt_id, + "result": { "stopReason": "end_turn" } + }); + self.send_pair(update, response); + } + std::process::exit(0); + } + + if matches!(self.mode.as_str(), "hold" | "stubborn") { + // Deliberately non-cooperative: the pending prompt stays pending. + return; + } + let key = self + .sessions + .iter() + .find(|(_, pending)| pending.session_id == session_id) + .map(|(key, _)| key.clone()); + if let Some(key) = key { + let pending = self + .sessions + .remove(&key) + .expect("pending prompt observed above"); + self.respond(&pending.prompt_id, json!({ "stopReason": "cancelled" })); + } + } + + fn permission_response(&mut self, id: &Value, message: &Value) { + self.record( + "permission_response", + json!({ + "id": id, + "result": message.get("result").cloned(), + "error": message.get("error").cloned(), + }), + ); + let Some(pending) = self.sessions.remove(&id.to_string()) else { + self.record("unmatched_response", message.clone()); + return; + }; + self.update( + &pending.session_id, + json!({ + "sessionUpdate": "tool_call_update", + "toolCallId": "fixture-call-1", + "status": "completed" + }), + ); + self.update( + &pending.session_id, + json!({ + "sessionUpdate": "agent_message_chunk", + "content": { "type": "text", "text": "done" } + }), + ); + self.respond(&pending.prompt_id, json!({ "stopReason": "end_turn" })); + } +} + +fn main() { + let mode = env::var("FAKE_ACP_MODE").unwrap_or_else(|_| "normal".to_owned()); + let events = env::var_os("FAKE_ACP_RECORD") + .and_then(|path| OpenOptions::new().create(true).append(true).open(path).ok()); + let marker = env::var("FAKE_ACP_STDERR_MARKER").unwrap_or_else(|_| DEFAULT_MARKER.to_owned()); + eprintln!("{marker}"); + + let mut harness = Harness { + mode, + events, + out: io::stdout(), + sessions: HashMap::new(), + next_session: 0, + next_permission: 0, + mcp: None, + }; + let args: Vec = env::args().skip(1).collect(); + harness.record( + "start", + json!({ + "pid": std::process::id(), + "args": args, + "mode": harness.mode.clone() + }), + ); + + if env::var_os("FAKE_ACP_SPAWN_DESCENDANT").is_some() { + match Command::new("sleep").arg("120").spawn() { + Ok(child) => harness.record("descendant", json!({ "pid": child.id() })), + Err(error) => harness.record( + "descendant_error", + json!({ "error": error.kind().to_string() }), + ), + } + } + + let stdin = io::stdin(); + let mut held = None; + for line in stdin.lock().lines() { + let Ok(line) = line else { break }; + if line.trim().is_empty() { + continue; + } + let message: Value = match serde_json::from_str(&line) { + Ok(message) => message, + Err(error) => { + harness.record("parse_error", json!({ "error": error.to_string() })); + continue; + } + }; + let method = message.get("method").and_then(Value::as_str); + let id = message.get("id"); + match method { + Some("fixture/wire_size") => { + let id = id.expect("wire size request id"); + let bytes = message["params"]["bytes"].as_u64().unwrap() as usize; + let head = format!(r#"{{"jsonrpc":"2.0","id":{id},"result":{{"text":""#); + let tail = "\"}}"; + let padding = "x".repeat(bytes - head.len() - tail.len()); + write!(harness.out, "{head}{padding}{tail}").ok(); + if message["params"]["newline"] == true { + writeln!(harness.out).ok(); + } + harness.out.flush().ok(); + } + Some("fixture/hold") => { + held.get_or_insert_with(|| id.expect("held request id").clone()); + if message["params"]["barrier"] == true { + harness.record("held_barrier", json!({})); + } + if harness.mode == "numeric_overlap" { + harness.send(json!({ "jsonrpc": "2.0", "id": 71, + "method": "fixture/client_request", "params": {} })); + } + } + Some("fixture/release") => { + if let Some(id) = held.take() { + harness.respond(&id, json!({ "released": true })); + } + } + Some("fixture/stderr") => { + let secret = env::var("FAKE_ACP_DUMMY_AUTH").unwrap(); + let mut stderr = io::stderr().lock(); + for _ in 0..128 { + stderr.write_all(&[b'x'; 4096]).unwrap(); + } + writeln!(stderr, "Bearer {secret}").unwrap(); + harness.respond(id.unwrap(), json!({ "drained": true })); + } + Some("initialize") => { + if let Some(id) = id { + harness.initialize(id, message.get("params").unwrap_or(&Value::Null)); + } else { + harness.record("initialize_without_id", message.clone()); + } + } + Some(method @ ("session/new" | "session/load" | "session/resume")) => { + harness.record("setup_wire", message.clone()); + if let Some(id) = id { + if message["params"]["_meta"]["hold"] == true { + held = Some(id.clone()); + harness.record("setup_held", json!({})); + continue; + } + if matches!( + (harness.mode.as_str(), method), + ("load_only", "session/resume") | ("resume_only", "session/load") + ) { + harness.respond_error(id, -32601, "method not found"); + } else { + harness.new_session( + method, + id, + message.get("params").unwrap_or(&Value::Null), + ); + } + } + } + Some("session/prompt") => { + if let Some(id) = id { + harness.prompt(id, message.get("params").unwrap_or(&Value::Null)); + } + } + Some("notifications/initialized") => { + harness.record( + "notifications/initialized", + message.get("params").cloned().unwrap_or(Value::Null), + ); + } + Some("fixture/block") => { + harness.record( + "stdin_blocked", + message.get("params").cloned().unwrap_or(Value::Null), + ); + if matches!(harness.mode.as_str(), "blocked" | "blocked_late_load") { + // Keep stdout open and stop reading stdin entirely. The + // proxy must not be able to finish a protocol drain once + // forwarded traffic fills this pipe. + loop { + std::thread::sleep(std::time::Duration::from_secs(60)); + } + } + } + Some("session/cancel") => { + harness.cancel(message.get("params").unwrap_or(&Value::Null)); + } + Some(method) => { + harness.record( + "unsupported_request", + json!({ "method": method, "id": id, "params": message.get("params") }), + ); + if let Some(id) = id { + harness.respond_error(id, -32601, "method not found"); + } + } + None => { + let Some(id) = id else { + harness.record("stray_message", message.clone()); + continue; + }; + if harness.mode == "numeric_overlap" && id == &json!(71) { + harness.record("numeric_response", message.clone()); + if let Some(id) = held.take() { + harness.respond(&id, json!({ "peerResult": message["result"] })); + } + } else if id.as_str().map(|id| id.starts_with("fixture-permission-")) == Some(true) + { + harness.permission_response(id, &message); + } else { + harness.record("unmatched_response", message.clone()); + } + } + } + } + + harness.record("stdin_eof", json!({ "mode": harness.mode.clone() })); + if let Some(mcp) = harness.mcp.take() { + if let Err(error) = mcp.finish(&mut harness) { + harness.record("mcp_error", json!(error)); + eprintln!("{error}"); + std::process::exit(1); + } + } + if matches!( + harness.mode.as_str(), + "stubborn" | "blocked" | "blocked_late_load" + ) { + harness.record("stubborn_sleep", json!({})); + loop { + std::thread::sleep(std::time::Duration::from_secs(60)); + } + } +} diff --git a/tests/fixtures/acp/owning_mcp.rs b/tests/fixtures/acp/owning_mcp.rs new file mode 100644 index 00000000..45254e37 --- /dev/null +++ b/tests/fixtures/acp/owning_mcp.rs @@ -0,0 +1,247 @@ +//! MCP client for the test-only `own_mcp` ACP harness mode. + +use std::fs::File; +use std::io::{BufRead, BufReader, Write}; +use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio}; +use std::time::{Duration, Instant}; + +use serde_json::{json, Value}; + +use super::Harness; + +type Result = std::result::Result; + +pub(super) struct Mcp { + child: Child, + input: Option, + output: BufReader, + next_id: u32, +} + +pub(super) fn start(harness: &mut Harness, params: &Value) -> Result { + let declaration = params["mcpServers"] + .as_array() + .and_then(|servers| match servers.as_slice() { + [server] if server["name"] == "rustscript-tools" => Some(server), + _ => None, + }) + .ok_or("missing injected rustscript-tools declaration")?; + let command = declaration["command"] + .as_str() + .ok_or("missing MCP command")?; + let args = declaration["args"].as_array().ok_or("missing MCP args")?; + let env = declaration["env"].as_array().ok_or("missing MCP env")?; + let mut launch = Command::new(command); + for arg in args { + launch.arg(arg.as_str().ok_or("invalid MCP arg")?); + } + for entry in env { + launch.env( + entry["name"].as_str().ok_or("invalid MCP env name")?, + entry["value"].as_str().ok_or("invalid MCP env value")?, + ); + } + // Leave cwd at the unrelated launch directory: only the declaration's + // workspace argument may direct the server to the session files. + // The proxy deliberately doesn't expose harness stderr. Capture the MCP + // process's teardown diagnostic directly without putting it on either wire. + let record = std::env::var_os("FAKE_ACP_RECORD").ok_or("missing harness event log path")?; + let stderr_path = std::path::Path::new(&record).with_extension("mcp.stderr"); + let stderr = File::create(stderr_path).map_err(|error| format!("open MCP stderr: {error}"))?; + let mut child = launch + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(stderr) + .spawn() + .map_err(|error| format!("launch declared MCP server: {error}"))?; + harness.record( + "mcp_started", + json!({"pid": child.id(), "declaration": declaration}), + ); + let mut mcp = Mcp { + input: child.stdin.take(), + output: BufReader::new(child.stdout.take().expect("piped MCP stdout")), + child, + next_id: 1, + }; + let result = mcp.request( + "initialize", + json!({ + "protocolVersion": "2025-06-18", "capabilities": {}, + "clientInfo": {"name": "owning-acp-fixture", "version": "1"} + }), + )?; + harness.record("mcp_initialize", result); + mcp.send(json!({"jsonrpc": "2.0", "method": "notifications/initialized"}))?; + let catalog = mcp.request("tools/list", json!({}))?; + let names: Vec<_> = catalog["tools"] + .as_array() + .ok_or("missing MCP tools array")? + .iter() + .map(|tool| &tool["name"]) + .collect(); + harness.record("mcp_catalog", json!(names)); + Ok(mcp) +} + +impl Mcp { + fn send(&mut self, message: Value) -> Result<()> { + let input = self.input.as_mut().expect("MCP input open"); + writeln!(input, "{message}") + .and_then(|()| input.flush()) + .map_err(|error| format!("write MCP stdin: {error}")) + } + + fn request(&mut self, method: &str, params: Value) -> Result { + let id = self.next_id; + self.next_id += 1; + self.send(json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}))?; + let mut line = String::new(); + let count = self + .output + .read_line(&mut line) + .map_err(|error| format!("read MCP response for {method} ({id}): {error}"))?; + if count == 0 { + return Err(format!("MCP EOF during {method} ({id})")); + } + let mut message: Value = serde_json::from_str(&line) + .map_err(|error| format!("invalid MCP response for {method} ({id}): {error}"))?; + if message["jsonrpc"] != "2.0" || message["id"] != id || message.get("error").is_some() { + return Err(format!( + "unexpected MCP response for {method} ({id}): {message}" + )); + } + if !message["result"].is_object() { + return Err(format!("missing MCP result for {method} ({id}): {message}")); + } + Ok(message["result"].take()) + } + + fn call(&mut self, name: &str, arguments: Value) -> Result { + self.request("tools/call", json!({"name": name, "arguments": arguments})) + .map_err(|error| format!("{name}: {error}")) + } + + fn success(&mut self, name: &str, arguments: Value) -> Result { + let result = self.call(name, arguments)?; + if result["isError"] != false { + return Err(format!("{name} failed: {result}")); + } + Ok(result) + } + + pub(super) fn turn(&mut self, harness: &mut Harness, session: &str) -> Result<()> { + begin(harness, session, "write_file", "edit"); + self.success( + "write_file", + json!({ + "path": "acp-note.txt", "content": "written by the owning harness\n" + }), + )?; + complete(harness, session, "write_file", None); + // Both the typed rejection and the untouched sibling canary are + // checked by the ACP client after it has shut the process tree down. + let outside = self.call( + "write_file", + json!({"path": "../outside.txt", "content": "unexpected write\n"}), + )?; + harness.record("outside_write", outside); + + begin(harness, session, "read_file", "read"); + let read = self.success("read_file", json!({"path": "seed.txt"}))?; + let text = read["content"][0]["text"] + .as_str() + .ok_or("missing MCP read text")?; + complete(harness, session, "read_file", Some(text)); + + begin(harness, session, "terminal", "execute"); + // The shell prints its real PID and the written file, then execs a + // finite sleeper with the same PID. It stays live for the EOF sweep. + let terminal = self.success("terminal", json!({ + "argv": ["/bin/sh", "-c", "IFS= read -r line < acp-note.txt && printf '%s\\n%s\\n' \"$$\" \"$line\" && exec /bin/sleep 25"], + "background": true, "timeout_ms": 25000 + }))?; + let process_id = terminal["structuredContent"]["process_id"] + .as_str() + .ok_or("missing terminal process handle")?; + let until = Instant::now() + Duration::from_secs(3); + loop { + let poll = self.success( + "process", + json!({"action": "poll", "process_id": process_id}), + )?; + let state = &poll["structuredContent"]; + if state["status"] != "running" { + return Err(format!("terminal stopped before ACP EOF: {state}")); + } + if let Some((pid, text)) = state["stdout"] + .as_str() + .and_then(|out| out.split_once('\n')) + { + if text.ends_with('\n') { + let pid: u32 = pid.parse().map_err(|_| "invalid terminal PID")?; + harness.record( + "terminal_ready", + json!({"pid": pid, "processId": process_id, "text": text}), + ); + complete(harness, session, "terminal", Some(text)); + break; + } + } + if Instant::now() >= until { + return Err("timed out waiting for terminal output".into()); + } + } + harness.update( + session, + json!({"sessionUpdate": "agent_message_chunk", "content": { + "type": "text", "text": "Fake harness completed its tool turn." + }}), + ); + Ok(()) + } + + pub(super) fn finish(mut self, harness: &mut Harness) -> Result<()> { + drop(self.input.take()); + let status = self + .child + .wait() + .map_err(|error| format!("wait for MCP EOF: {error}"))?; + harness.record( + "mcp_exit", + json!({"pid": self.child.id(), "code": status.code()}), + ); + if !status.success() { + return Err(format!("MCP did not exit cleanly on EOF: {status}")); + } + Ok(()) + } +} + +impl Drop for Mcp { + fn drop(&mut self) { + // Unwind a failed initialize. Successful turns take the EOF path in + // finish; an already reaped child must not be signalled. + if !matches!(self.child.try_wait(), Ok(Some(_))) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } + } +} + +fn begin(harness: &mut Harness, session: &str, tool: &str, kind: &str) { + harness.update( + session, + json!({"sessionUpdate": "tool_call", "toolCallId": tool, + "title": tool, "kind": kind, "status": "in_progress"}), + ); +} + +fn complete(harness: &mut Harness, session: &str, tool: &str, text: Option<&str>) { + let mut update = + json!({"sessionUpdate": "tool_call_update", "toolCallId": tool, "status": "completed"}); + if let Some(text) = text { + update["content"] = json!([{"type": "content", "content": {"type": "text", "text": text}}]); + } + harness.update(session, update); +} From 67a81c258fa0231a1c059dccd87822e4f84717fb Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 29 Nov 2026 01:27:19 +0800 Subject: [PATCH 04/14] docs(acp): document tool-provider mode and verify release packaging Document launch, configuration, workspace tool access, and harness ownership. Keep guide consistency and packaged command checks with the documented interface. --- README.md | 9 +- docs/acp-mode.md | 136 ++++++++++++++++++++++++++ docs/configuration.md | 94 +++++++++++++++--- tests/cases/docs_consistency_tests.rs | 121 ++++++++++++++++++++++- tests/release_packaging_tests.rs | 94 ++++++++++++++++++ 5 files changed, 436 insertions(+), 18 deletions(-) create mode 100644 docs/acp-mode.md diff --git a/README.md b/README.md index 6661d108..e47564d8 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # rustscript-agent -`rustscript-agent` is a standalone agent runtime with **agent policy in RustScript and authority/durability in Rust**. RSS programs own the model loop, provider adaptation, tool routing, approval policy, and compaction decisions; the Rust host owns admission, capabilities, durable state, effect commits, and transport. +`rustscript-agent` is a standalone agent runtime with **agent policy in RustScript and authority/durability in Rust**. In the bundled runtime, RSS programs own the model loop, provider adaptation, tool routing, approval policy, and compaction decisions; the Rust host owns admission, capabilities, durable state, effect commits, and transport. ## Core properties @@ -33,6 +33,13 @@ HTTP / Telegram -> durable messages, events, receipts, and publications ``` +### Use an external harness from an ACP editor + +In [ACP mode](docs/acp-mode.md), RustScript Agent is an ACP v1 stdio proxy and +MCP tool provider. Configure your editor to launch the proxy in front of a +compatible harness. The harness owns the model, provider login, and usage charges; +RustScript supplies tools scoped to the ACP session's working directory. + ## Documentation - [Architecture](docs/architecture.md) — RSS/native ownership, typed boundaries, lifecycle, effects, replay, and capability fences diff --git a/docs/acp-mode.md b/docs/acp-mode.md new file mode 100644 index 00000000..687d724e --- /dev/null +++ b/docs/acp-mode.md @@ -0,0 +1,136 @@ +# ACP mode: use an external harness with RustScript tools + +RustScript Agent acts as the **ACP proxy and MCP tool provider**. Your editor +speaks Agent Client Protocol (ACP) to the proxy, and the external harness +calls RustScript tools over Model Context Protocol (MCP). The harness owns the +LLM API calls, credentials, model selection, reasoning loop, permissions, and +any usage charges. No RustScript Agent provider login is required in this +mode. Use the harness's own authentication flow; keep credentials out of the +launch arguments and editor configuration. + +## Launch from an editor + +Configure an ACP client to launch `rustscript-agent acp proxy`. Put proxy +options before `--` and the harness executable and arguments after it. The +proxy launches the harness directly, without a shell. If your editor cannot +find either executable on its `PATH`, use its absolute path instead. + +**Gemini CLI:** [Gemini CLI's ACP guide](https://geminicli.com/docs/cli/acp-mode/) +documents `gemini --acp`. Configure the command as follows: + +```sh +rustscript-agent acp proxy --read-only -- gemini --acp +``` + +For an editor with separate executable and argument fields, use the values +below. The field names in your editor may differ. + +```json +{ + "command": "rustscript-agent", + "args": ["acp", "proxy", "--read-only", "--", "gemini", "--acp"] +} +``` + +**Claude Agent SDK adapter:** Install the executable using the +[Claude Agent ACP adapter instructions](https://github.com/agentclientprotocol/claude-agent-acp). +The [official package manifest](https://github.com/agentclientprotocol/claude-agent-acp/blob/main/package.json) +lists the package `@agentclientprotocol/claude-agent-acp` and the executable +`claude-agent-acp`. Launch the adapter, not the interactive `claude` command: + +```sh +rustscript-agent acp proxy --read-only -- claude-agent-acp +``` + +These are launch syntax examples, not results from authenticated end-to-end +compatibility tests. Use the harness's supported version and check its MCP and +permission settings if RustScript tools do not appear. + +## Compatibility and session setup + +The initial release supports **ACP v1 over local stdio** on both sides of the +proxy. ACP v2, remote ACP transports, and native MCP-over-ACP are out of scope. +The harness needs to accept and launch stdio MCP servers declared during ACP +session setup. A working ACP handshake alone does not establish tool support. + +The session's `cwd` must be an absolute path to an existing local directory. +It defines the RustScript tool workspace, regardless of where the editor +launched the proxy. The proxy resolves it to a canonical path for the MCP +server and leaves the original `cwd` in the forwarded ACP request. + +On `session/new`, the proxy appends one `rustscript-tools` MCP declaration to +`mcpServers`, preserving the caller's existing declarations in order. It does +likewise on `session/load` and `session/resume` only when the harness advertises +the corresponding capability. A caller declaration named `rustscript-tools` +conflicts with the injected server and is rejected. The declaration uses the +running RustScript Agent executable with `tools serve --stdio --workspace` and +the canonical path. You do not need to configure a second binary or add the +same server manually. The harness controls when it starts and stops the MCP +process; an appended declaration does not guarantee a distinct process. + +```text +ACP client/editor <-- ACP v1 stdio --> rustscript-agent acp proxy + | + ACP v1 stdio + | + v + External harness <---> LLM API + | + MCP stdio + | + v + rustscript-agent tools serve + | + v + RSS registry + capability hosts +``` + +```text +Editor -> Proxy -> Harness: initialize and negotiate ACP v1 +Editor -> Proxy: session/new with cwd and mcpServers +Proxy -> Harness: session/new with rustscript-tools appended +Harness -> Tool server: start tools serve; MCP initialize and tools/list +Editor -> Proxy -> Harness: session/prompt +Harness <-> LLM API: inference and tool selection +Harness <-> Tool server: tools/call and tool result, when selected +Harness -> Proxy -> Editor: session updates and prompt result +``` + +## Tool access and lifecycle + +- **Read-only (`--read-only`):** RustScript advertises only `read_file` and + `search_files` and rejects writes and process calls before execution. Files + read by the tools can still become part of the context that the harness + sends to its model. +- **Coding (default):** RustScript also exposes `write_file`, `patch`, + `terminal`, and `process`. These tools can change workspace files and start + commands with the local user's privileges. Use coding mode only with a + trusted harness and a workspace you intend it to modify. The RustScript + capability bounds are not an OS sandbox for commands. + +The flag only applies to injected RustScript tools. It does not restrict the +harness, its built-in tools, or other MCP servers, and it does not make the +session offline. Review the harness's own permission settings before using +it. This mode does not use the RustScript gateway's provider loop, durable +approvals, or replay. + +The proxy owns its direct harness child. Client EOF or a termination signal +initiates bounded shutdown: the proxy attempts to cancel active sessions and +terminates its child if needed. This is not a guarantee about arbitrary +harness grandchildren or other processes started outside RustScript's control. +Keep protocol frames on stdout and diagnostics on stderr for both the ACP and +MCP stdio connections. + +## Troubleshooting + +| Symptom | What to check | +| --- | --- | +| No ACP handshake or `acp_harness_unavailable` | Check the executable path and enter the harness's ACP mode explicitly. A normal interactive CLI or a v2-only peer is not an ACP v1 stdio agent. | +| MCP declaration rejected or RustScript tools missing | Use `mcpServers: []` in `session/new` or `session/load` if there are no caller servers. `invalid_mcp_servers` means the list is missing or malformed for that method; `mcp_server_name_conflict` means a caller entry is already named `rustscript-tools`. Check that the harness accepts session-supplied stdio MCP servers and that its policy permits starting the injected executable. | +| `invalid_workspace` | Set the editor's session `cwd` to a resolvable absolute directory on the machine running the proxy. Changing the proxy's launch directory does not fix an invalid session `cwd`. | +| Write or process tool absent or denied | With `--read-only`, the RustScript server does not offer those tools and refuses explicit calls. Change the proxy launch profile and reconnect only if you intend to allow writes or execution. A denial from the harness itself must be handled through the harness's permissions. | +| `acp_harness_exited` or the connection drops | Check the harness for startup, authentication, or runtime failures using its own diagnostics. The proxy reports a fixed error code, not the harness's stderr output. Reconnect from the client after resolving the issue. | +| JSON-RPC parse error or startup banner in the stream | Ensure the client, harness, and any launcher keep banners and debug messages off protocol stdout. Do not merge stderr into stdout. | + +See the [configuration reference](configuration.md) for the direct MCP launch +syntax and tool-server diagnostics. diff --git a/docs/configuration.md b/docs/configuration.md index 8265ed5a..da36abb2 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -1,25 +1,27 @@ # rustscript-agent configuration reference This document is the canonical configuration reference for this revision of -`rustscript-agent`. It lists **only** configuration that exists in this -revision: every environment variable the binaries read, every native +`rustscript-agent`. It lists **only** inputs that exist in this +revision: environment variables read by binaries or test code, every native `AgentGatewayConfig` field, and the capability-policy defaults the gateway passes through to the `pd-vm` core. Reserved-but-unimplemented configuration is called out explicitly in [Reserved configuration](#reserved-configuration) and must not be treated as real. A drift guard (`tests/cases/docs_consistency_tests.rs`) compares this document -against `src/` in both directions: a variable that the binaries read but this -document misses, or a variable this document advertises that no binary reads, +against `src/` in both directions: a variable accounted for in source but +missing here, or one documented here without a corresponding source entry, fails the test suite. ## Configuration sources | Source | Owns | Read by | | --- | --- | --- | -| Gateway environment variables (`RUSTSCRIPT_AGENT_*`, except the separately listed home override) | gateway process settings | `rustscript-agent-gateway` binary (`src/bin/rustscript-agent-gateway.rs`) | +| [Gateway environment variables](#environment-variables-gateway-binary) | gateway process settings | `rustscript-agent-gateway` binary (`src/bin/rustscript-agent-gateway.rs`) | +| [MCP tool server environment](#mcp-tool-server-environment) | stderr tracing and internal readiness/diagnostic inputs | `rustscript-agent tools serve` | | Agent home (`RUSTSCRIPT_AGENT_HOME`) | library config/auth path resolver, always-attached gateway provider operator auth home, and optional gateway workspace host (only when explicitly set) | library path resolver and gateway home wiring | -| CLI arguments (`--script`, `--allow-host`) | one run | `rustscript-agent` binary (`src/bin/rustscript-agent.rs`) | +| Runner CLI arguments (`--script`, `--allow-host`) | one script run | `rustscript-agent` binary (`src/bin/rustscript-agent.rs`) | +| [ACP and MCP CLI arguments](acp-mode.md) | harness launch and RustScript tool profile or workspace | `rustscript-agent acp proxy` and `rustscript-agent tools serve` | | Native `AgentGatewayConfig` fields | embedding code | library API; the gateway binary maps a fixed subset from environment variables | RSS programs never read ambient configuration: all bounds reach the VM @@ -48,7 +50,12 @@ YAML field path), never the full Display prose. A loader sample of both documents (an empty-credential config/auth pair decoded by the bounded loaders) ships under [docs/examples/](examples/). -## Environment variables (gateway binary) +## Environment variables + +### Environment variables (gateway binary) + +The gateway reads the agent-home override, managed-workspace settings, +plugin-control settings, and the gateway variables listed in the table below. ### Agent home (library bootstrap and gateway workspace host) @@ -191,6 +198,8 @@ RUSTSCRIPT_AGENT_STATE_DB=/var/lib/rustscript-agent/state.db \ cargo run --release --bin rustscript-agent-gateway ``` +### Test scratch inputs + `RUSTSCRIPT_AGENT_TEST_TMP` is an **internal test input, not a production setting**: it is read only by `#[cfg(test)]` code and test fixtures in this repository to select a writable scratch directory, no binary reads it, and it @@ -203,10 +212,69 @@ setting**. The workspace Telegram unit fixture requires this input to select isolated test scratch storage. It is confined to `#[cfg(test)]` code and does not configure a packaged gateway. +### MCP tool server environment + +`RUSTSCRIPT_AGENT_TOOLS_TRACE` enables tool-server tracing on stderr when +present (even if empty). When unset, the tracing threshold is `WARN`. Raw +MCP payload logging stays disabled. This variable has no gateway alias. + +The tool server also reads two internal test inputs in default builds: +`RUSTSCRIPT_AGENT_TEST_READY_MARKER` enables a readiness marker on stderr, and +`RUSTSCRIPT_AGENT_TEST_READY_FILE` requests a file-based readiness signal. +Leave both unset in normal use. + +`RUSTSCRIPT_AGENT_TEST_DIAGNOSTIC_FLOOD` exercises the tool server's stderr +diagnostic path in test or `workspace-io-fault` builds only. + +### Shared capability test hooks + +The process and execution-gate inputs below belong to the shared capability +code, not to gateway or MCP configuration. They are available only in test or +`workspace-io-fault` builds on platforms that compile the corresponding code +paths. They are not deployment settings: + +- Process launch: `RUSTSCRIPT_AGENT_TEST_SPAWN_PARK_FILE`, + `RUSTSCRIPT_AGENT_TEST_SPAWN_RELEASE_FILE`, + `RUSTSCRIPT_AGENT_TEST_SPAWN_BEFORE_RECORD_PARK_FILE`, + `RUSTSCRIPT_AGENT_TEST_SPAWN_BEFORE_RECORD_RELEASE_FILE`, + `RUSTSCRIPT_AGENT_TEST_SPAWN_BEFORE_RELEASE_PARK_FILE`, and + `RUSTSCRIPT_AGENT_TEST_SPAWN_BEFORE_RELEASE_RELEASE_FILE`. +- Execution gate: `RUSTSCRIPT_AGENT_TEST_GATE_FORCE_AMBIGUOUS`, + `RUSTSCRIPT_AGENT_TEST_GATE_RELEASE_FAILURE_MARKER`, + `RUSTSCRIPT_AGENT_TEST_GATE_AFTER_RELEASE_PARK_FILE`, and + `RUSTSCRIPT_AGENT_TEST_GATE_AFTER_RELEASE_RELEASE_FILE`. +- Process cleanup: `RUSTSCRIPT_AGENT_TEST_OWNED_CLEANUP_PARK_FILE`, + `RUSTSCRIPT_AGENT_TEST_OWNED_CLEANUP_RELEASE_FILE`, + `RUSTSCRIPT_AGENT_TEST_RETAINED_ATTEMPT_MARKER`, + `RUSTSCRIPT_AGENT_TEST_RETAINED_DECISION_PARK_FILE`, + `RUSTSCRIPT_AGENT_TEST_RETAINED_DECISION_RELEASE_FILE`, + `RUSTSCRIPT_AGENT_TEST_SWEEP_MARKER`, + `RUSTSCRIPT_AGENT_TEST_SWEEP_REAP_PARK_FILE`, and + `RUSTSCRIPT_AGENT_TEST_SWEEP_REAP_RELEASE_FILE`. + +## ACP proxy and MCP tool server + +```text +rustscript-agent acp proxy [--read-only] -- HARNESS [ARG ...] +rustscript-agent tools serve --stdio --workspace ABSOLUTE_PATH [--read-only] +``` + +The proxy passes the harness executable and arguments directly, without a +shell. The ACP client's session `cwd` determines the workspace for injected +RustScript tools. `--workspace` is for direct MCP launches; the proxy fills it +in automatically. The default coding profile permits writes and process +execution. `--read-only` limits the RustScript MCP server to file reads and +searches; it does not limit the harness or its other tools. + +ACP mode does not need a RustScript Agent provider login or the gateway's +provider settings. Configure authentication, model selection, and permissions +in the external harness. See [ACP mode](acp-mode.md) for editor launch examples, +compatibility, and troubleshooting. + ## CLI arguments (runner binary) -`rustscript-agent` is the single-run runner: it compiles one script and -drives its exported `run(context)` to completion with no gateway. +In single-run mode, `rustscript-agent` compiles one script and drives its +exported `run(context)` to completion with no gateway. | Argument | Type | Default | Notes | | --- | --- | --- | --- | @@ -501,9 +569,9 @@ The following configuration does **not** exist in this revision. It is listed only to reserve the namespace and to make the roadmap explicit; no binary reads these names and setting them has no effect. -- **A6 parallel tools / subagents (排除)** remains out of scope and defines - no configuration. Tool approval is implemented through the `approvals` - settings above and durable approval records; a general-purpose harness layer - beyond tool approval is not part of the current product. +- **A6 parallel tools / subagents (排除)** remains out of scope for the bundled + gateway run loop and defines no configuration. The gateway uses the + `approvals` settings above and durable approval records; an external ACP + harness uses its own permission policy. - A job **scheduler** is not implemented: job CRUD/pause/resume/latest-output routes exist, but scheduled execution defines no configuration. diff --git a/tests/cases/docs_consistency_tests.rs b/tests/cases/docs_consistency_tests.rs index 1e758c21..66d27f4b 100644 --- a/tests/cases/docs_consistency_tests.rs +++ b/tests/cases/docs_consistency_tests.rs @@ -54,13 +54,13 @@ fn env_names_in(text: &str) -> Vec { } /// Extracts the canonical environment-variable section of -/// `docs/configuration.md`: from the `## Environment variables (gateway -/// binary)` heading up to the next `## ` heading. +/// `docs/configuration.md`: from the `## Environment variables` heading +/// up to the next `## ` heading. fn canonical_env_section() -> String { let configuration = read_relative("docs/configuration.md"); let start = configuration - .find("## Environment variables (gateway binary)") - .unwrap_or_else(|| panic!("configuration.md must keep the canonical env table heading")); + .find("## Environment variables\n") + .unwrap_or_else(|| panic!("configuration.md must keep the canonical env section heading")); let rest = &configuration[start..]; let end = rest[1..] .find("\n## ") @@ -178,6 +178,7 @@ fn every_agent_gateway_config_field_is_documented() { fn readme_links_the_canonical_docs() { let readme = read_relative("README.md"); for target in [ + "docs/acp-mode.md", "docs/api.md", "docs/architecture.md", "docs/configuration.md", @@ -192,10 +193,122 @@ fn readme_links_the_canonical_docs() { } } +fn acp_section<'a>(guide: &'a str, heading: &str) -> &'a str { + guide + .split_once(&format!("\n## {heading}\n")) + .unwrap_or_else(|| panic!("ACP guide is missing the {heading:?} section")) + .1 + .split("\n## ") + .next() + .unwrap() +} + +#[test] +fn acp_guide_documents_the_tool_provider_contract() { + let guide = read_relative("docs/acp-mode.md"); + let overview = guide.split("\n## ").next().unwrap(); + let setup = acp_section(&guide, "Compatibility and session setup"); + let profiles = acp_section(&guide, "Tool access and lifecycle"); + let require = |passage: &str, anchors: &[&str]| { + let passage = passage.split_whitespace().collect::>().join(" "); + for anchor in anchors { + assert!(passage.contains(anchor), "ACP guide is missing {anchor:?}"); + } + }; + + require( + overview, + &[ + "ACP proxy and MCP tool provider", + "harness owns", + "LLM API", + "credentials", + "model selection", + "reasoning loop", + "usage charges", + "No RustScript Agent provider login", + ], + ); + let versions = setup.trim_start().split("\n\n").next().unwrap(); + let (supported, excluded) = versions + .split_once("ACP v2") + .expect("ACP guide must address ACP v2"); + require(supported, &["supports", "ACP v1", "local stdio"]); + require(excluded, &["out of scope"]); + require( + setup, + &[ + "`cwd`", + "absolute path", + "existing local directory", + "tool workspace", + ], + ); + + let (read_only, coding) = profiles + .split_once("**Coding") + .expect("ACP guide must describe coding mode"); + require( + read_only, + &[ + "`--read-only`", + "`read_file`", + "`search_files`", + "rejects writes and process calls", + ], + ); + require( + coding, + &[ + "(default)", + "local user's privileges", + "not an OS sandbox", + "only applies to injected RustScript tools", + ], + ); +} + +#[test] +fn acp_guide_has_sourced_harness_launch_examples() { + let guide = read_relative("docs/acp-mode.md"); + let launch = acp_section(&guide, "Launch from an editor"); + for (args, source) in [ + ("gemini --acp", "https://geminicli.com/docs/cli/acp-mode/"), + ( + "claude-agent-acp", + "https://github.com/agentclientprotocol/claude-agent-acp", + ), + ] { + let command = format!("rustscript-agent acp proxy --read-only -- {args}"); + assert!( + launch.lines().any(|line| line == command), + "ACP guide is missing the {args} launch command" + ); + assert!( + launch.contains(&format!("]({source})")), + "ACP guide is missing the upstream source for {args}" + ); + } + let (_, json) = launch + .split_once("\n```json\n") + .expect("ACP guide must have a JSON editor example"); + let (json, _) = json + .split_once("\n```\n") + .expect("editor example must close its code fence"); + let editor_config: serde_json::Value = + serde_json::from_str(json).expect("editor example must be valid JSON"); + assert_eq!(editor_config["command"], "rustscript-agent"); + assert_eq!( + editor_config["args"], + serde_json::json!(["acp", "proxy", "--read-only", "--", "gemini", "--acp"]) + ); +} + #[test] fn relative_markdown_links_resolve() { let files = [ "README.md", + "docs/acp-mode.md", "docs/api.md", "docs/architecture.md", "docs/configuration.md", diff --git a/tests/release_packaging_tests.rs b/tests/release_packaging_tests.rs index 14bbb213..cf4b9606 100644 --- a/tests/release_packaging_tests.rs +++ b/tests/release_packaging_tests.rs @@ -521,6 +521,100 @@ fn package_contains_exact_unique_inventory_modes_and_source_bytes() { } } +#[test] +#[cfg(target_os = "linux")] +fn packaged_runner_exposes_acp_and_mcp_help() { + let scratch = Scratch::new("cli-help"); + let runner = Path::new(env!("CARGO_BIN_EXE_rustscript-agent")); + let gateway = Path::new(env!("CARGO_BIN_EXE_rustscript-agent-gateway")); + let output_dir = scratch.0.join("out"); + let extract_dir = scratch.0.join("extract"); + let empty_cwd = scratch.0.join("empty"); + for directory in [&output_dir, &extract_dir, &empty_cwd] { + fs::create_dir(directory).unwrap(); + } + + let output = run_packager("v0.1.0", runner.parent().unwrap(), &output_dir); + assert!( + output.status.success(), + "packager failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + let root = "rustscript-agent-v0.1.0-x86_64-unknown-linux-gnu"; + let output = Command::new("tar") + .arg("-xzf") + .arg(output_dir.join(format!("{root}.tar.gz"))) + .arg("-C") + .arg(&extract_dir) + .output() + .expect("extract release archive"); + assert!( + output.status.success(), + "extraction failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + + let bin = extract_dir.join(root).join("bin"); + let names = fs::read_dir(&bin) + .unwrap() + .map(|entry| entry.unwrap().file_name()) + .collect::>(); + assert_eq!( + names, + BTreeSet::from(["rustscript-agent".into(), "rustscript-agent-gateway".into()]) + ); + for source in [runner, gateway] { + let extracted = bin.join(source.file_name().unwrap()); + let output = Command::new("cmp") + .arg(source) + .arg(&extracted) + .output() + .expect("compare built and extracted binary bytes"); + assert!( + output.status.success(), + "{} differs from its build input: {}{}", + extracted.display(), + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + } + + let acp_usage = "rustscript-agent acp proxy "; + let mcp_usage = "rustscript-agent tools serve --stdio "; + for (args, usages) in [ + (&["--help"][..], &[acp_usage, mcp_usage][..]), + (&["acp", "proxy", "--help"][..], &[acp_usage][..]), + (&["tools", "serve", "--help"][..], &[mcp_usage][..]), + ] { + let output = Command::new(bin.join("rustscript-agent")) + .args(args) + .current_dir(&empty_cwd) + .env_clear() + .envs( + ["TMPDIR", "TMP", "TEMP"] + .into_iter() + .filter_map(|key| std::env::var_os(key).map(|value| (key, value))), + ) + .output() + .expect("run extracted rustscript-agent help"); + assert!( + output.status.success() && output.stderr.is_empty(), + "help {args:?} returned {}: {}", + output.status, + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8(output.stdout).expect("help stdout is UTF-8"); + for usage in usages { + assert!( + stdout + .lines() + .any(|line| line.trim_start().starts_with(usage)), + "help {args:?} missing usage {usage:?}: {stdout}" + ); + } + } +} + #[test] fn verifier_rejects_duplicate_raw_member_names() { let scratch = Scratch::new("duplicate-raw"); From 52e5e44e80e7ba6b2941be9209e0b24834c74b4c Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 29 Nov 2026 06:19:52 +0800 Subject: [PATCH 05/14] test(auth): compare bundled public JSON structurally --- tests/auth_bundle_tests.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/tests/auth_bundle_tests.rs b/tests/auth_bundle_tests.rs index 525e25fc..6efb7912 100644 --- a/tests/auth_bundle_tests.rs +++ b/tests/auth_bundle_tests.rs @@ -389,10 +389,13 @@ pub fn run(home: resource, command: map) -> AuthEntryResult { move |child| AuthHost::new(home, child) }) .expect("only json::encode is admitted for ordinary public data"); - assert_eq!( - field(&value, "status"), - &Value::string(r#"{"count":2,"label":"public"}"#) - ); + let status = match field(&value, "status") { + Value::String(status) => { + serde_json::from_str::(status).expect("serialized public data") + } + other => panic!("expected serialized public data, got {other:?}"), + }; + assert_eq!(status, serde_json::json!({ "count": 2, "label": "public" })); let denied = bundle_error( AuthEntryRunner::from_bundle( "bad_builtin.rss", From 1eae2ccad6b6ff35e618b5615b4096df58c50a14 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 29 Nov 2026 07:18:36 +0800 Subject: [PATCH 06/14] test(auth): compare logout reports structurally --- tests/auth_cli_subprocess_tests.rs | 36 +++++++++++++++++------------- 1 file changed, 21 insertions(+), 15 deletions(-) diff --git a/tests/auth_cli_subprocess_tests.rs b/tests/auth_cli_subprocess_tests.rs index 31d42987..cdc4fbab 100644 --- a/tests/auth_cli_subprocess_tests.rs +++ b/tests/auth_cli_subprocess_tests.rs @@ -947,6 +947,20 @@ fn installed_status_and_config_check_use_guest_default_and_reference_policy() { #[test] fn installed_logout_mutates_only_its_home_and_repeats_as_absent() { + let assert_logout_report = |stdout: &[u8], credential_id: &str, status: &str| { + let line = stdout + .strip_suffix(b"\n") + .expect("LF-terminated logout report"); + assert!( + !line.contains(&b'\n') && !line.contains(&b'\r'), + "expected a single logout report line" + ); + let report: serde_json::Value = serde_json::from_slice(line).expect("JSON logout report"); + assert_eq!( + report, + serde_json::json!({"credential_id": credential_id, "status": status}) + ); + }; let area = TestArea::new("logout-isolation"); let selected = area.home("selected-home"); let peer_home = area.home("peer-home"); @@ -990,10 +1004,7 @@ fn installed_logout_mutates_only_its_home_and_repeats_as_absent() { let logout = area.invoke(&selected, &["auth", "logout", "fixture-codex"]); assert_eq!(logout.status.code(), Some(0)); - assert_eq!( - String::from_utf8(logout.stdout.clone()).expect("logout report"), - "{\"credential_id\":\"fixture-codex\",\"status\":\"deleted\"}\n" - ); + assert_logout_report(&logout.stdout, "fixture-codex", "deleted"); assert!(logout.stderr.is_empty()); assert_redacted(&logout, &selected); let selected_after: serde_yaml::Value = @@ -1015,19 +1026,13 @@ fn installed_logout_mutates_only_its_home_and_repeats_as_absent() { let repeated = area.invoke(&selected, &["auth", "logout", "fixture-codex"]); assert_eq!(repeated.status.code(), Some(0)); - assert_eq!( - String::from_utf8(repeated.stdout.clone()).expect("repeat logout report"), - "{\"credential_id\":\"fixture-codex\",\"status\":\"already_absent\"}\n" - ); + assert_logout_report(&repeated.stdout, "fixture-codex", "already_absent"); assert!(repeated.stderr.is_empty()); assert_redacted(&repeated, &selected); let orphan_logout = area.invoke(&selected, &["auth", "logout", "orphan-credential"]); assert_eq!(orphan_logout.status.code(), Some(0)); - assert_eq!( - String::from_utf8(orphan_logout.stdout.clone()).expect("orphan logout report"), - "{\"credential_id\":\"orphan-credential\",\"status\":\"deleted\"}\n" - ); + assert_logout_report(&orphan_logout.stdout, "orphan-credential", "deleted"); let expected_after_orphan = { let mut credentials = expected_credentials.clone(); credentials @@ -1047,9 +1052,10 @@ fn installed_logout_mutates_only_its_home_and_repeats_as_absent() { ); let orphan_repeated = area.invoke(&selected, &["auth", "logout", "orphan-credential"]); assert_eq!(orphan_repeated.status.code(), Some(0)); - assert_eq!( - String::from_utf8(orphan_repeated.stdout.clone()).expect("repeat orphan report"), - "{\"credential_id\":\"orphan-credential\",\"status\":\"already_absent\"}\n" + assert_logout_report( + &orphan_repeated.stdout, + "orphan-credential", + "already_absent", ); assert_redacted(&orphan_logout, &selected); assert_redacted(&orphan_repeated, &selected); From 7e3b255881f7a07129a124334a936e98e57ffbf7 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 29 Nov 2026 09:05:18 +0800 Subject: [PATCH 07/14] test(plugins): compare schema property keys without order --- tests/cases/plugin_schema_sync_tests.rs | 40 +++++++++++-------------- 1 file changed, 17 insertions(+), 23 deletions(-) diff --git a/tests/cases/plugin_schema_sync_tests.rs b/tests/cases/plugin_schema_sync_tests.rs index 91d3ee56..4f89d541 100644 --- a/tests/cases/plugin_schema_sync_tests.rs +++ b/tests/cases/plugin_schema_sync_tests.rs @@ -64,22 +64,28 @@ fn assert_schema_and_parser(name: &str, yaml: &str, accept: bool) { assert_eq!(parser_ok, accept, "parser acceptance drifted for {yaml}"); } -#[test] -fn schema_enums_and_fields_match_the_parser_contract() { - let manifest = load("plugin-manifest.schema.yaml"); - let properties: Vec = manifest["properties"] +fn assert_property_keys(schema: &serde_json::Value, expected: &[&str]) { + // Schema object member order is not part of the field contract. + let mut actual: Vec<_> = schema["properties"] .as_object() .unwrap() .keys() - .cloned() + .map(String::as_str) .collect(); + let mut expected = expected.to_vec(); + actual.sort_unstable(); + expected.sort_unstable(); assert_eq!( - properties, - MANIFEST_FIELDS - .iter() - .map(|item| (*item).to_string()) - .collect::>() + actual, expected, + "property keys drifted for {}", + schema["$id"] ); +} + +#[test] +fn schema_enums_and_fields_match_the_parser_contract() { + let manifest = load("plugin-manifest.schema.yaml"); + assert_property_keys(&manifest, MANIFEST_FIELDS); let kinds: Vec = manifest["properties"]["kind"]["enum"] .as_array() .unwrap() @@ -121,19 +127,7 @@ fn schema_enums_and_fields_match_the_parser_contract() { .collect::>() ); let lock = load("plugin-graph-lock.schema.yaml"); - let lock_fields: Vec = lock["properties"] - .as_object() - .unwrap() - .keys() - .cloned() - .collect(); - assert_eq!( - lock_fields, - GRAPH_LOCK_FIELDS - .iter() - .map(|item| (*item).to_string()) - .collect::>() - ); + assert_property_keys(&lock, GRAPH_LOCK_FIELDS); assert!( fs::read_to_string(schema_dir().join("README.md")) .unwrap() From 101e4ada41fd78052c984a30923f5d31f3207e72 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 29 Nov 2026 09:19:28 +0800 Subject: [PATCH 08/14] fix(plugins): preserve canonical state document bytes --- src/plugins/state.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/plugins/state.rs b/src/plugins/state.rs index 04d897a1..e1ec943f 100644 --- a/src/plugins/state.rs +++ b/src/plugins/state.rs @@ -107,7 +107,7 @@ impl PluginStatePayload { } let mut entries = 0usize; validate_value(&value, 0, &mut entries)?; - let canonical_json = serde_json::to_string(&value).map_err(|_| { + let canonical_json = crate::json_canonical::to_canonical_string(&value).map_err(|_| { PluginStateError::new( "plugin_state_invalid_document", "state document is not encodable", From a8b49a9d96153b03d0762f3252e46e9d303d53a2 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 29 Nov 2026 10:45:14 +0800 Subject: [PATCH 09/14] test(plugins): emit canonical signed state receipts --- tests/plugin_state_migration_tests.rs | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/tests/plugin_state_migration_tests.rs b/tests/plugin_state_migration_tests.rs index 419316f8..43d09e77 100644 --- a/tests/plugin_state_migration_tests.rs +++ b/tests/plugin_state_migration_tests.rs @@ -800,13 +800,20 @@ pub fn run(context: map) -> map { let reread_revision: int = reread.revision; let reread_document: string = reread.document; let same: bool = written_ok && reread_ok && reread_revision == written_revision && reread_document == document; - let mut error: map = {}; - if written_ok == false { - error = failure_detail(written.error); + if same => { + // The write is staged here; durable publication is checked after commit. + let result: map = { ok: true, content: "state", data: { revision: written_revision, schema: written.schema, durable: written.durable }, truncated: false, artifacts: [] }; + commit(token, result) + } else if written_ok == false => { + commit(token, failure(written.error)) + } else => { + // Committing a failure here would still publish the staged write. + if reread_ok == false => { + failure(reread.error) + } else => { + { ok: false, content: "", data: {}, error: { code: "state_reread_mismatch", message: "staged state did not match the write" }, truncated: false, artifacts: [] } + } } - // The write is staged here; durable publication is checked after commit. - let result: map = { ok: same, content: "state", data: { revision: written_revision, schema: written.schema, durable: written.durable }, error: error, truncated: false, artifacts: [] }; - commit(token, result) } else => { failure(meta.error) } From eb153b577c1309f72cdc69393c43ba71a7b23b2f Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 29 Nov 2026 11:53:04 +0800 Subject: [PATCH 10/14] test(effects): wait for managed group exit within cleanup cutoff Group SIGKILL may finish asynchronously after the owned root is reaped. Poll the real stopped-drain fixture group within its original cleanup cutoff, keeping the root reap and ownership assertions at cleanup return. --- src/effects/managed_authority_tests.rs | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/src/effects/managed_authority_tests.rs b/src/effects/managed_authority_tests.rs index 9da38ffb..1cb925ff 100644 --- a/src/effects/managed_authority_tests.rs +++ b/src/effects/managed_authority_tests.rs @@ -1888,15 +1888,28 @@ async fn managed_open_group_proof_observes_exited_root_without_signal_or_reap() let descendant_alive_after_proof = live_group_member(pid); let table_after_proof = processes.table_len(); let generation_after_proof = processes.generation_for_test(); - // The authorized cleanup keeps its own kill and must really reap - // the child it killed together with its live descendant. - let cleanup = processes - .reap_managed_within(std::time::Instant::now() + std::time::Duration::from_secs(5)); + // The authorized cleanup signals the group and reaps the owned root. + let cleanup_cutoff = std::time::Instant::now() + std::time::Duration::from_secs(5); + let cleanup = processes.reap_managed_within(cleanup_cutoff); let retained_after_cleanup = probe.retained(); let table_after_cleanup = processes.table_len(); let generation_after_cleanup = processes.generation_for_test(); let root_gone = !Path::new(&format!("/proc/{pid}")).exists(); - let group_gone = !live_group_member(pid); + // SIGKILL can still be taking effect in descendants after the root + // has been reaped. Observe their exit within the same cutoff. + let group_gone = loop { + if std::time::Instant::now() >= cleanup_cutoff { + break false; + } + if !live_group_member(pid) { + break std::time::Instant::now() < cleanup_cutoff; + } + std::thread::sleep( + cleanup_cutoff + .saturating_duration_since(std::time::Instant::now()) + .min(std::time::Duration::from_millis(10)), + ); + }; *stop_slot.lock().unwrap() = Some(( branch, binding, @@ -2188,7 +2201,7 @@ async fn managed_open_group_proof_observes_exited_root_without_signal_or_reap() ); assert!( stop.group_gone, - "the authorized cleanup killed and reaped the live descendant: pid={stop_pid}" + "the authorized cleanup left no live descendant by its cutoff: pid={stop_pid}" ); assert_eq!( stop.writer_phase, From 08c0d3807807700f04fb4dcb5fcf72be00c3aa1b Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 29 Nov 2026 14:21:02 +0800 Subject: [PATCH 11/14] test(process): exercise published spawn retention policy Use the standalone MCP settlement policy in the RSS commit-failure fixture. Keep the default abort policy in the other cases, and assert that replay of the unresolved call never reaches a second OS spawn. --- tests/rss_process_tool_tests.rs | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/tests/rss_process_tool_tests.rs b/tests/rss_process_tool_tests.rs index 1c0dc04d..84b548d0 100644 --- a/tests/rss_process_tool_tests.rs +++ b/tests/rss_process_tool_tests.rs @@ -18,7 +18,7 @@ use rustscript_agent::capabilities::{ ApprovalGate, ArtifactCapability, ArtifactLimits, CancellationFlag, CapabilityLifecycle, CapabilityOwner, CapabilityRisk, DurableStarted, DurableToolLifecycle, LifecycleClock, LifecycleError, LifecycleLimits, NeverCancelled, PrepareMetadata, PrepareOutcome, - ProcessCapability, ProcessLimits, SystemClock, TokenIssuer, UuidIssuer, + ProcessCapability, ProcessLimits, PublishedTokenPolicy, SystemClock, TokenIssuer, UuidIssuer, }; use rustscript_agent::config::ProcessToolConfig; use rustscript_agent::{ @@ -346,6 +346,7 @@ fn build_lifecycle( cancellation: Arc, clock: Arc, deadline_ms: u64, + published_token_policy: PublishedTokenPolicy, ) -> CapabilityLifecycle { CapabilityLifecycle::builder() .owner(owner()) @@ -362,6 +363,7 @@ fn build_lifecycle( .durable(durable) .approval(approval) .cancellation(cancellation) + .published_token_policy(published_token_policy) .build() .expect("lifecycle") } @@ -433,6 +435,7 @@ fn run_rss_exec_with_runner( Arc::clone(&exec.cancellation), Arc::clone(&exec.clock), exec.deadline_ms, + PublishedTokenPolicy::Abort, )), }; let processes = match exec.shared_processes.clone() { @@ -2136,6 +2139,8 @@ fn commit_failure_after_background_spawn_retains_owned_child_for_cleanup() { let clock = Arc::new(SystemClock); let deadline_ms = clock.now_ms() + 60_000; let durable = MemoryDurable::new(); + // A published spawn survives a failed receipt write under the standalone + // MCP settlement policy. The default policy retracts token-owned resources. let lifecycle = Arc::new(build_lifecycle( &fixture.root, Arc::clone(&durable), @@ -2143,6 +2148,7 @@ fn commit_failure_after_background_spawn_retains_owned_child_for_cleanup() { Arc::new(NeverCancelled), Arc::clone(&clock) as Arc, deadline_ms, + PublishedTokenPolicy::RetainForSettlement, )); let processes = Arc::new( ProcessCapability::new(lifecycle.as_ref().clone(), owner(), process_limits(&config)) @@ -2197,6 +2203,11 @@ fn commit_failure_after_background_spawn_retains_owned_child_for_cleanup() { // The published child stays owned by the run table and is reaped by the // ordinary bounded cleanup rather than a retraction of the effect. assert_eq!(processes.table_len(), 1); + let repeated_spawn = Arc::new(AtomicBool::new(false)); + processes.set_os_spawn_observer({ + let repeated_spawn = Arc::clone(&repeated_spawn); + Arc::new(move || repeated_spawn.store(true, Ordering::SeqCst)) + }); let replay = run_rss_exec( &fixture, &config, @@ -2217,6 +2228,10 @@ fn commit_failure_after_background_spawn_retains_owned_child_for_cleanup() { }, ); assert_eq!(error_code(&replay.result), "unresolved_call"); + assert!( + !repeated_spawn.load(Ordering::SeqCst), + "reentering an unresolved call must not attempt another OS spawn" + ); spawn_pids_cleanup(&processes, &pids); assert_eq!(processes.table_len(), 0); } @@ -2653,6 +2668,7 @@ fn foreground_cancel_during_initial_stdin_write_cleans_process_group() { flag.clone(), clock, deadline_ms, + PublishedTokenPolicy::Abort, )); let processes = Arc::new( ProcessCapability::new(lifecycle.as_ref().clone(), owner(), process_limits(&config)) From f44f83f8c42520bc757e884c3e6d877446b584ae Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 29 Nov 2026 15:57:21 +0800 Subject: [PATCH 12/14] test(mcp): order write publication after the VM epoch advances Hold the publication gate until cancellation reaches the VM epoch watcher. Confirm that the guest never commits and compare the returned receipt with the durable settlement. --- tests/mcp_sol_lifecycle_tests.rs | 39 ++++++++++++++++++++++++++++---- 1 file changed, 35 insertions(+), 4 deletions(-) diff --git a/tests/mcp_sol_lifecycle_tests.rs b/tests/mcp_sol_lifecycle_tests.rs index b0b097d5..44a013d9 100644 --- a/tests/mcp_sol_lifecycle_tests.rs +++ b/tests/mcp_sol_lifecycle_tests.rs @@ -1064,6 +1064,13 @@ fn published_write_receipt_survives_a_vm_stop_before_tool_commit() { let gate = Arc::clone(&gate); Arc::new(move || gate.block()) }); + let guest_commits = Arc::new(AtomicU64::new(0)); + executor.set_commit_observer_for_test({ + let guest_commits = Arc::clone(&guest_commits); + Arc::new(move |_token| { + guest_commits.fetch_add(1, Ordering::SeqCst); + }) + }); let worker = { let executor = Arc::clone(&executor); std::thread::spawn(move || { @@ -1076,10 +1083,34 @@ fn published_write_receipt_survives_a_vm_stop_before_tool_commit() { }; gate.wait_started(); - assert!(executor.cancel_call("p1-published-write")); + let cancelled = executor.cancel_call("p1-published-write"); + // Keep the host call blocked until the watcher advances the VM epoch. + // Release and join the worker even if cancellation or the wait fails. + let deadline = Instant::now() + Duration::from_secs(10); + let epoch_advanced = cancelled + && loop { + if executor.call_epoch_advanced_for_test("p1-published-write") == Some(true) { + break true; + } + if Instant::now() >= deadline { + break false; + } + std::thread::sleep(Duration::from_millis(10)); + }; gate.release(); - let result = worker.join().expect("worker thread").expect("receipt"); + let result = worker.join(); + assert!(cancelled, "the active write must accept cancellation"); + assert!( + epoch_advanced, + "timed out waiting for the write's VM epoch to advance" + ); + let result = result.expect("worker thread").expect("receipt"); + assert_eq!( + guest_commits.load(Ordering::SeqCst), + 0, + "the guest must stop before tool_commit: {result:?}" + ); assert!( result.ok, "a rename that happened must not be reported as a cancellation: {result:?}" @@ -1092,8 +1123,8 @@ fn published_write_receipt_survives_a_vm_stop_before_tool_commit() { "the published write receipt must keep the effect identity: {result:?}" ); let committed = executor - .committed_receipt_for_test("p1-published-write") - .expect("durable published receipt"); + .durable_committed_receipt_for_test("p1-published-write") + .expect("the guard must durably commit the published write receipt"); assert_eq!( serde_json::to_value(&result).expect("serialize returned result"), serde_json::to_value(&committed).expect("serialize committed receipt"), From 9eaf9d4485bf513afebd0c315fe0bea3269a6140 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 29 Nov 2026 22:39:50 +0800 Subject: [PATCH 13/14] test(rss): exercise result artifact retention policy Use the standalone MCP publication policy only in the RSS read-file retention fixture. Check that the failed commit never persists a result and that its exact artifact remains with the original bytes and bound owner metadata. --- tests/cases/rss_file_tool_tests.rs | 76 +++++++++++++++++++++++++----- 1 file changed, 64 insertions(+), 12 deletions(-) diff --git a/tests/cases/rss_file_tool_tests.rs b/tests/cases/rss_file_tool_tests.rs index 71445509..1d55e8e3 100644 --- a/tests/cases/rss_file_tool_tests.rs +++ b/tests/cases/rss_file_tool_tests.rs @@ -15,7 +15,8 @@ use rustscript_agent::capabilities::{ ApprovalGate, ArtifactCapability, ArtifactLimits, CancellationFlag, CapabilityLifecycle, CapabilityOwner, CapabilityRisk, DurableStarted, DurableToolLifecycle, FilesystemCapability, FilesystemLimits, LifecycleClock, LifecycleError, LifecycleLimits, NeverCancelled, - PrepareMetadata, SystemClock, TokenIssuer, UuidIssuer, positive_duration_ms, + PrepareMetadata, PublishedTokenPolicy, SystemClock, TokenIssuer, UuidIssuer, + positive_duration_ms, }; use rustscript_agent::config::FileToolConfig; use rustscript_agent::{AgentConfig, AgentHostBridges, AgentRunner, ToolResult}; @@ -65,6 +66,7 @@ struct MemoryDurable { parent_ok: Mutex, active: Mutex, fail_next_commit: AtomicBool, + failed_result: Mutex>, } impl MemoryDurable { @@ -75,6 +77,7 @@ impl MemoryDurable { parent_ok: Mutex::new(true), active: Mutex::new(true), fail_next_commit: AtomicBool::new(false), + failed_result: Mutex::new(None), }) } @@ -132,6 +135,7 @@ impl DurableToolLifecycle for MemoryDurable { fn commit_result(&self, call_id: &str, result: &Value) -> Result { if self.fail_next_commit.load(Ordering::SeqCst) { + *self.failed_result.lock().expect("failed result") = Some(result.clone()); return Err(LifecycleError::ResultCommitFailed( "injected result failure".to_string(), )); @@ -259,6 +263,7 @@ fn build_lifecycle( cancellation: Arc, clock: Arc, deadline_ms: u64, + published_token_policy: PublishedTokenPolicy, ) -> CapabilityLifecycle { CapabilityLifecycle::builder() .owner(owner()) @@ -275,6 +280,7 @@ fn build_lifecycle( .durable(durable) .approval(approval) .cancellation(cancellation) + .published_token_policy(published_token_policy) .build() .expect("lifecycle") } @@ -393,6 +399,15 @@ fn default_artifact_limits() -> ArtifactLimits { } fn run_rss_exec(fixture: &Fixture, config: &FileToolConfig, exec: RssExec) -> RssRun { + run_rss_exec_with_policy(fixture, config, exec, PublishedTokenPolicy::default()) +} + +fn run_rss_exec_with_policy( + fixture: &Fixture, + config: &FileToolConfig, + exec: RssExec, + published_token_policy: PublishedTokenPolicy, +) -> RssRun { let lifecycle = Arc::new(build_lifecycle( &fixture.root, Arc::clone(&exec.durable), @@ -400,6 +415,7 @@ fn run_rss_exec(fixture: &Fixture, config: &FileToolConfig, exec: RssExec) -> Rs exec.cancellation, exec.clock, exec.deadline_ms, + published_token_policy, )); let fs_cap = FilesystemCapability::new( lifecycle.as_ref().clone(), @@ -2583,8 +2599,10 @@ fn search_fake_clock_overflow_uses_nested_capability_error_envelope() { #[test] fn published_result_artifact_is_retained_when_commit_fails() { - let fixture = Fixture::new("artifact-rollback"); - fs::write(fixture.root.join("wide.txt"), "你好世界".repeat(80)).unwrap(); + const CALL_ID: &str = "call-artifact-commit-fail"; + let fixture = Fixture::new("artifact-retention"); + let content = "你好世界".repeat(80); + fs::write(fixture.root.join("wide.txt"), &content).unwrap(); let mut config = fixture.config(); config.max_output_bytes = 200; config.max_search_output_bytes = 200; @@ -2593,22 +2611,56 @@ fn published_result_artifact_is_retained_when_commit_fails() { config.artifact_store.max_total_bytes = 16384; let durable = MemoryDurable::new(); durable.fail_next_commit(); - let rss = run_rss_tool( - "read_file_entry.rss", + let clock = Arc::new(TraversalClock); + let deadline_ms = clock.now_ms() + 60_000; + let rss = run_rss_exec_with_policy( &fixture, &config, - "read_file", - json!({"path": "wide.txt"}), - Arc::clone(&durable), - Arc::new(AllowAll), - Arc::new(NeverCancelled), - true, + RssExec { + module: "read_file_entry.rss", + tool_name: "read_file", + arguments: json!({"path": "wide.txt"}), + durable: Arc::clone(&durable), + approval: Arc::new(AllowAll), + cancellation: Arc::new(NeverCancelled), + clock, + deadline_ms, + install_artifacts: true, + artifact_limits: default_artifact_limits(), + call_id: CALL_ID.to_string(), + }, + // This is the standalone MCP contract; the managed default retracts + // the result artifact on a failed durable commit. + PublishedTokenPolicy::RetainForSettlement, ); assert_eq!(rss.result["ok"], json!(false), "rss={}", rss.result); assert_eq!(rss.result["error"]["code"], json!("result_commit_failed")); assert_eq!( - rss.artifacts.as_ref().expect("rss store").stored_len(), + durable + .replay_result("run-test", CALL_ID, "read_file") + .unwrap(), + None, + "the failed commit must not leave a durable result" + ); + let failed_result = durable.failed_result.lock().expect("failed result"); + let attempted = failed_result.as_ref().expect("attempted durable commit"); + assert_eq!(attempted["ok"], json!(true)); + let id = attempted["artifacts"][0] + .as_str() + .expect("the attempted commit references the published artifact"); + + let artifacts = rss.artifacts.as_ref().expect("rss store"); + assert_eq!( + artifacts.stored_len(), 1, "an artifact that crossed the publication fence must not be retracted by a later commit-storage failure" ); + let (bytes, metadata) = artifacts + .stored(id) + .expect("retained artifact from this commit"); + assert_eq!(bytes, content.as_bytes()); + assert_eq!( + metadata, + json!({"call_id": CALL_ID, "run": "run-test", "owner": owner().key()}) + ); } From 681ea5a1499fa880d54801fcc068d76a915e50b7 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 30 Nov 2026 01:16:40 +0800 Subject: [PATCH 14/14] test(service): compare RunLimits as JSON values --- tests/service_tests.rs | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/tests/service_tests.rs b/tests/service_tests.rs index 7e017067..53be746c 100644 --- a/tests/service_tests.rs +++ b/tests/service_tests.rs @@ -1377,7 +1377,7 @@ async fn terminal_contexts_and_registries_are_cleaned_by_the_lifecycle_janitor() } #[test] -fn run_limits_validate_zero_overflow_and_workspace_paths_and_serialize_deterministically() { +fn run_limits_validate_zero_overflow_and_workspace_paths_and_serialize_to_json() { let workspace = std::env::current_dir().expect("the test workspace should exist"); assert!(RunLimits::new(0, 1, 1, &workspace).is_err()); assert!(RunLimits::new(1, 0, 1, &workspace).is_err()); @@ -1387,12 +1387,17 @@ fn run_limits_validate_zero_overflow_and_workspace_paths_and_serialize_determini assert!(RunLimits::new(1, 1, 1, Path::new("/path/that/does/not/exist")).is_err()); let limits = RunLimits::new(3, 4, 1024, &workspace).expect("valid limits should pass"); + let canonical_workspace = workspace + .canonicalize() + .expect("workspace should canonicalize"); assert_eq!( - limits.to_json().to_string(), - format!( - "{{\"max_tool_calls\":4,\"max_tool_output_bytes\":1024,\"max_turns\":3,\"workspace_root\":\"{}\"}}", - workspace.display() - ) + limits.to_json(), + json!({ + "max_tool_calls": 4, + "max_tool_output_bytes": 1024, + "max_turns": 3, + "workspace_root": canonical_workspace.to_string_lossy(), + }) ); }