From 5c4f16771a1e8b685b43fd740be582c0f2950187 Mon Sep 17 00:00:00 2001 From: Dimitri Kennedy <344842+roodboi@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:14:49 -0500 Subject: [PATCH 01/11] fix(native): let authored hack run and interactive exec wait out another project's stop (HACK-2742) HACK-2739 made an authored finite `hack exec` wait for the provider lease in its requesting process. Authored one-off `hack run` and authored interactive `hack exec` still had only the owner's 15 s wait and reported its expiry as unconfirmed. In all three, the owner's guard (a pending signal, its own `hack down`, a changed publication or pin) could end that wait with a plain refusal, which the CLI also reported as unconfirmed although nothing ran. - `native::foreground::one_off` and `::interactive` wait up to 35 s for a free lease before they send; the interactive one passes its frontend leash as the check. - All three owner paths go through `exec::owner_command_engine`, which answers `graph_authored_exec_lease_busy`, `graph_authored_run_lease_busy` or `graph_authored_command_not_started` for a wait that ended before acquisition; later failures keep their codes. - `hack run` gets the 85 s request bound (was 45 s), the progress line, the not-run refusals and the released admission slot. - The interactive child sends its lease-wait report on its control channel as one closed event line, and its refusal report names the holder; the CLI prints the progress line and an honest refusal. - ExecStopWait.tla gains the owner's cancel (Cancellable, CancelUnconfirmed) with three controls; earlier state counts unchanged. Co-Authored-By: Claude Opus 5.5 --- docs/guides/native-candidate.md | 39 ++-- .../runtime-core/src/interactive_exec_cli.rs | 23 ++- .../provider/engine/command_lease_tests.rs | 68 +++++++ .../src/provider/graph/interactive_exec.rs | 13 ++ .../src/provider/graph/native/foreground.rs | 20 ++ .../src/provider/graph/native/runtime.rs | 2 + .../src/provider/graph/native/runtime/exec.rs | 93 +++++++-- .../graph/native/runtime/exec_tests.rs | 144 +++++++++++--- .../src/provider/graph/native/runtime/run.rs | 7 +- .../runtime-core/src/provider/lifecycle.rs | 27 ++- packages/runtime-core/src/provider/state.rs | 31 +++ scripts/lib/tla-runtime-models.ts | 32 +++ src/backends/native-authored-project-exec.ts | 48 +---- .../native-authored-project-oneoff.ts | 70 +++++-- src/backends/native-command-lease.ts | 155 ++++++++++++++- src/backends/native-interactive-exec.ts | 115 ++++++++++- src/backends/native-runtime-client.ts | 8 +- src/backends/native-start-lease.ts | 10 + tests/fixtures/native-interactive-frontend.py | 16 +- tests/fixtures/native-interactive-frontend.ts | 3 +- tests/fixtures/native-interactive-runtime.py | 11 ++ .../tla/native-command-lease/COVERAGE.md | 60 +++++- .../tla/native-command-lease/ExecStopWait.tla | 42 +++- .../authored-cancel-old.cfg | 4 + .../authored-cancel-reach.cfg | 4 + .../native-command-lease/authored-cancel.cfg | 8 + .../authored-honest-no-wait.cfg | 2 +- .../tla/native-command-lease/authored-old.cfg | 2 +- .../authored-outlasts-stop.cfg | 2 +- .../authored-peer-race.cfg | 2 +- .../authored-peer-refused.cfg | 2 +- .../authored-ran-after-stop.cfg | 2 +- .../exec-outlasts-stop.cfg | 2 +- .../exec-past-bound-honest.cfg | 2 +- .../native-command-lease/exec-past-bound.cfg | 2 +- .../exec-ran-after-peer.cfg | 2 +- .../exec-ran-after-stop.cfg | 2 +- .../exec-unconfirmed-after-send.cfg | 2 +- .../native-command-lease/honest-old-bound.cfg | 2 +- .../native-command-lease/old-exec-bound.cfg | 2 +- .../native-command-lease/send-while-held.cfg | 2 +- tests/native-authored-project-exec.test.ts | 31 +++ tests/native-authored-project-oneoff.test.ts | 183 +++++++++++++++++- tests/native-command-lease.test.ts | 63 ++++++ tests/native-interactive-exec.test.ts | 96 ++++++++- tests/native-runtime-client.test.ts | 13 ++ 46 files changed, 1284 insertions(+), 185 deletions(-) create mode 100644 tests/models/tla/native-command-lease/authored-cancel-old.cfg create mode 100644 tests/models/tla/native-command-lease/authored-cancel-reach.cfg create mode 100644 tests/models/tla/native-command-lease/authored-cancel.cfg diff --git a/docs/guides/native-candidate.md b/docs/guides/native-candidate.md index 29f6b48ddb..27826e0254 100644 --- a/docs/guides/native-candidate.md +++ b/docs/guides/native-candidate.md @@ -5452,23 +5452,28 @@ which covers the whole 35-second wait. "Unconfirmed" is kept for outcomes where refresh or exec that was sent and whose answer did not arrive or did not match. For compose-backed exec the 30-second budget starts after that wait. -An authored project's exec (`hack.project.json`) sends one request to the project's -owner. Before it sends anything, the requesting command waits up to the same 35 -seconds for the provider lease to be free, prints the same single progress line, and -refuses the same way on expiry, with `nothing ran`. When nothing holds the lease this -is one lock attempt, so exec is as fast as before. The owner then takes the lease on -its only loop and waits at most 15 seconds, inside the authored 30-second budget, so -a long wait never holds up that owner's own `hack down` or restart ticks. If another -holder took the lease between the two waits and the owner's wait expires, the owner -answers `graph_authored_exec_lease_busy` before it reads its journal or touches a -container, and exec says `nothing ran` with `Holder: unavailable.` and `Retry hack -exec once the holder finishes.` Any other authored exec failure keeps its report, -"completion is unconfirmed" included. An authored project's one-off `run`, -interactive exec and a compose project's one-off `run` are answered by the project's -owner, which waits at most 15 seconds on its only loop (inside the authored -30-second budget, or for a compose `run` within one 15-second bound for its -selection and admission before its job is reserved). A pending Ctrl-C or `hack down` -ends the owner's wait at once without starting the command. When fresh values are delivered through private stdin, output that is still arriving +An authored project's (`hack.project.json`) finite exec, interactive exec and one-off +`hack run` each send one request to the project's owner. Before it sends anything, +the requesting command waits up to the same 35 seconds for the provider lease to be +free, prints the same single progress line, and refuses the same way on expiry, with +`nothing ran`. When nothing holds the lease this is one lock attempt, so the command +is as fast as before. The finite exec and `hack run` requests have an 85-second +frontend bound: that wait, 5 seconds to send and the owner's fixed 40-second answer. +The owner then takes the lease on its only loop and waits at most 15 seconds, inside +the authored 30-second budget, so a long wait never holds up that owner's own +`hack down` or restart ticks. If another holder took the lease between the two waits +and the owner's wait expires, the owner answers `graph_authored_exec_lease_busy` (or +`graph_authored_run_lease_busy`) before it reads its journal or touches a container, +and the command says `nothing ran` with `Holder: unavailable.` and `Retry hack exec +once the holder finishes.` A pending Ctrl-C of the owner, its `hack down`, or a +changed owner publication ends the owner's wait at once; the owner then answers +`graph_authored_command_not_started`, and the command says it did not start, that +nothing ran, and to check `hack ps` and retry once the project is up. Any other +authored failure keeps its report, "completion is unconfirmed" included. A compose +project's one-off `run` is answered by its owner, which waits at most 15 seconds on +its only loop, within one 15-second bound for its selection and admission before its +job is reserved; a pending Ctrl-C or `hack down` ends that wait at once without +starting the command. When fresh values are delivered through private stdin, output that is still arriving or already queued when that budget ends is read to the end, so a command that finished on a busy host returns its exit code (see below). `--env` and `--profile` changes are refused. A command name such as `bun` uses the selected container's PATH; no host PATH or implicit shell is used. For diff --git a/packages/runtime-core/src/interactive_exec_cli.rs b/packages/runtime-core/src/interactive_exec_cli.rs index 0c3cb0c1a9..fe58b4f933 100644 --- a/packages/runtime-core/src/interactive_exec_cli.rs +++ b/packages/runtime-core/src/interactive_exec_cli.rs @@ -78,6 +78,19 @@ pub fn command(candidate: &Candidate, args: &[&str]) -> Result ( @@ -86,7 +99,15 @@ pub fn command(candidate: &Candidate, args: &[&str]) -> Result ( 1, - serde_json::json!({"version":1,"outcome":"refused","code":error.code,"session":error.session()}), + match interactive_exec::lease_refusal_holder(&error) { + // An expired lease wait names its holder as a closed token. + Some(holder) => { + serde_json::json!({"version":1,"outcome":"refused","code":error.code,"session":error.session(),"holder":holder}) + } + None => { + serde_json::json!({"version":1,"outcome":"refused","code":error.code,"session":error.session()}) + } + }, ), }; let bytes = serde_json::to_vec(&value).map_err(|_| invalid())?; diff --git a/packages/runtime-core/src/provider/engine/command_lease_tests.rs b/packages/runtime-core/src/provider/engine/command_lease_tests.rs index 45e3e5478f..f81fd43b2d 100644 --- a/packages/runtime-core/src/provider/engine/command_lease_tests.rs +++ b/packages/runtime-core/src/provider/engine/command_lease_tests.rs @@ -481,6 +481,74 @@ fn the_authored_exec_request_wait_is_one_attempt_when_free_and_inert_without_a_p assert!(!empty.state_root.join("run/smolvm/operation.lock").exists()); } +/// HACK-2742: the interactive requester passes its frontend leash. A refusal from +/// that check ends the wait within one backoff step and is returned as is, not +/// swallowed into "go on to the owner". +#[test] +fn a_refused_requester_check_ends_the_wait_with_its_own_error() { + use crate::provider::lifecycle::await_free_command_lease_checked; + let (_home, candidate) = running_pool(); + let (release, holder) = hold_lease_as_project_stop(&candidate, Duration::from_secs(30)); + let started = Instant::now(); + let check = refuses_after(Duration::from_millis(200), "interactive_frontend_gone"); + let ended = + await_free_command_lease_checked(&candidate, started + Duration::from_secs(30), &check) + .err() + .unwrap(); + assert_eq!(ended.code, "interactive_frontend_gone"); + assert!(started.elapsed() >= Duration::from_millis(200)); + assert!(started.elapsed() < Duration::from_secs(2)); + // A check that passes leaves the bounded wait and its holder-named refusal. + let busy = await_free_command_lease_checked( + &candidate, + Instant::now() + Duration::from_millis(300), + &|| Ok(()), + ) + .err() + .unwrap(); + assert_eq!(busy.message, PROJECT_STOP_REFUSAL); + // The interactive refusal report names that holder as its closed token. + assert_eq!( + crate::provider::graph::interactive_exec::lease_refusal_holder(&busy), + Some("project-stop") + ); + assert_eq!( + crate::provider::graph::interactive_exec::lease_refusal_holder(&ended), + None + ); + release.send(()).unwrap(); + holder.join().unwrap(); +} + +/// HACK-2742, the call site: `native::foreground::one_off`, the requesting side of +/// an authored one-off `hack run`, waits out the stop before it contacts the +/// owner, as the finite exec does. +#[cfg(feature = "native-config-plan")] +#[test] +fn the_authored_run_requester_waits_before_it_contacts_the_owner() { + let (_home, candidate) = running_pool(); + let hold = Duration::from_millis(600); + let (_release, holder) = hold_lease_as_project_stop(&candidate, hold); + let started = Instant::now(); + let after = crate::provider::graph::native::foreground::one_off( + &candidate, + &"a".repeat(32), + "web", + &["true".to_owned()], + None, + ) + .err() + .unwrap(); + assert!( + started.elapsed() >= hold - Duration::from_millis(50), + "contacted the owner before the stop released: {:?} ({})", + started.elapsed(), + after.code + ); + assert_ne!(after.code, "provider_busy", "{}", after.message); + holder.join().unwrap(); +} + /// HACK-2739, the call site: `native::foreground::exec`, the requesting side of an /// authored `hack exec`, waits out the stop before it loads the owner's pin. This /// fixture has no owner, so it then refuses with something other than diff --git a/packages/runtime-core/src/provider/graph/interactive_exec.rs b/packages/runtime-core/src/provider/graph/interactive_exec.rs index eaaa780e18..54026cf06b 100644 --- a/packages/runtime-core/src/provider/graph/interactive_exec.rs +++ b/packages/runtime-core/src/provider/graph/interactive_exec.rs @@ -15,6 +15,19 @@ pub struct Options<'a> { pub expected_container: Option<&'a str>, pub expected_generation: Option<&'a str>, } +/// Send this process's lease-wait report (`hack.lease-wait:begin `, then +/// `hack.lease-wait:end`) to `sink` instead of stderr, which an interactive exec +/// shares with the user's terminal (HACK-2742). False if a sink was already set. +pub fn report_lease_waits_to(sink: Box) -> bool { + crate::provider::state::report_lease_waits_to(sink) +} + +/// The closed holder token an expired lease wait names, for the value-free +/// refusal report (HACK-2742). `None` for any other refusal or an unknown holder. +pub fn lease_refusal_holder(error: &CandidateError) -> Option<&'static str> { + crate::provider::state::lease_refusal_holder(error) +} + fn refused() -> CandidateError { CandidateError::new( "interactive_exec_refused", diff --git a/packages/runtime-core/src/provider/graph/native/foreground.rs b/packages/runtime-core/src/provider/graph/native/foreground.rs index b240f1e4fa..b70fdaef71 100644 --- a/packages/runtime-core/src/provider/graph/native/foreground.rs +++ b/packages/runtime-core/src/provider/graph/native/foreground.rs @@ -666,6 +666,13 @@ pub fn one_off( if !selected.valid() { return Err(refused()); } + // HACK-2742: as for exec (HACK-2739), wait out another project's stop here, + // before anything is sent; the owner's own wait stays short. + #[cfg(target_os = "macos")] + crate::provider::lifecycle::await_free_command_lease( + candidate, + Instant::now() + crate::provider::lifecycle::COMMAND_REQUEST_LEASE_WAIT, + )?; request_selected(candidate, run, Action::Run, None, None, Some(selected)) } /// The live owner creates and starts under its normal guards, then returns the @@ -698,6 +705,15 @@ pub(in crate::provider) fn interactive( { return Err(refused()); } + // HACK-2742: wait out another project's stop before anything is sent, as a + // finite exec does (HACK-2739). The frontend's leash ends the wait. A + // refusal here comes before dispatch, so it carries no session. + #[cfg(target_os = "macos")] + crate::provider::lifecycle::await_free_command_lease_checked( + candidate, + Instant::now() + crate::provider::lifecycle::COMMAND_REQUEST_LEASE_WAIT, + &|| leash.check(), + )?; let mut stream = pin.connect()?; let _lifetime = leash.watch_control(&stream)?; let input = Request { @@ -744,6 +760,10 @@ pub(in crate::provider) fn interactive( result.map_err(|_: CandidateError| CandidateError::new("session_cleanup_uncertain", "Interactive session handoff changed; the session was retained and no start was replayed.").with_session(&session.session)) } Outcome::InteractiveRefused { session } if session == options.session => Err(CandidateError::new("session_cleanup_uncertain", "Interactive admission ended after its durable intent; the session was retained and no start was replayed.").with_session(&session)), + // HACK-2742: the owner's pre-effect wait refusals keep their own code, + // because the interactive report carries only one code and the CLI + // reads it as "nothing ran". Every other pre-intent refusal is wrapped. + Outcome::Refused { code, .. } if descriptor.is_none() && runtime::owner_pre_effect_code(&code).is_some() => Err(CandidateError::new(runtime::owner_pre_effect_code(&code).ok_or_else(refused)?, "The owner refused the interactive exec before it started; nothing ran.")), Outcome::Refused { code, .. } if descriptor.is_none() => Err(refused().with_cause_code(code)), _ => Err(uncertain(refused())), } diff --git a/packages/runtime-core/src/provider/graph/native/runtime.rs b/packages/runtime-core/src/provider/graph/native/runtime.rs index be4901ba80..4221f05b08 100644 --- a/packages/runtime-core/src/provider/graph/native/runtime.rs +++ b/packages/runtime-core/src/provider/graph/native/runtime.rs @@ -13,6 +13,8 @@ pub(super) use exec::ServiceExec; pub(super) use exec::execute as service_exec; #[cfg(target_os = "macos")] pub(super) use exec::interactive as interactive_exec; +#[cfg(target_os = "macos")] +pub(super) use exec::owner_pre_effect_code; #[cfg(any(target_os = "macos", test))] mod run; #[cfg(target_os = "macos")] diff --git a/packages/runtime-core/src/provider/graph/native/runtime/exec.rs b/packages/runtime-core/src/provider/graph/native/runtime/exec.rs index 9675df9479..893b84eda4 100644 --- a/packages/runtime-core/src/provider/graph/native/runtime/exec.rs +++ b/packages/runtime-core/src/provider/graph/native/runtime/exec.rs @@ -75,18 +75,88 @@ impl ServiceExec { /// `provider_busy` from anywhere else keeps its own code. pub(super) const OWNER_EXEC_LEASE_BUSY: &str = "graph_authored_exec_lease_busy"; -/// Maps only the owner's expired lease wait to [`OWNER_EXEC_LEASE_BUSY`]. -pub(super) fn owner_lease_refusal(error: CandidateError) -> CandidateError { - if error.code == "provider_busy" { +/// [`OWNER_EXEC_LEASE_BUSY`] for an authored one-off `hack run` (HACK-2742). +pub(super) const OWNER_RUN_LEASE_BUSY: &str = "graph_authored_run_lease_busy"; + +/// The owner's answer code when its own check ended an authored command before +/// it took the lease (HACK-2742): a pending signal (its `hack down`, a Ctrl-C of +/// the foreground owner), or a changed publication or pin. The check runs before +/// the wait and before every lease attempt, so nothing was read, touched or +/// started. Without this code the owner's plain `refused()` reached the CLI as +/// "unconfirmed". +pub(super) const OWNER_COMMAND_NOT_STARTED: &str = "graph_authored_command_not_started"; + +/// The owner's pre-effect wait code that `code` names, if it is one. +pub(in crate::provider::graph::native) fn owner_pre_effect_code( + code: &str, +) -> Option<&'static str> { + [ + OWNER_EXEC_LEASE_BUSY, + OWNER_RUN_LEASE_BUSY, + OWNER_COMMAND_NOT_STARTED, + ] + .into_iter() + .find(|known| *known == code) +} + +/// Which authored command the owner answers, for its lease code. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) enum OwnerCommand { + /// Finite and interactive `hack exec`. + Exec, + /// One-off `hack run`. + Run, +} + +/// The pre-effect code for a failure of the owner's own wait: its check refused +/// (`guard_refused`), or the lease stayed busy. Any other failure keeps its code. +pub(super) fn owner_wait_refusal( + error: CandidateError, + guard_refused: bool, + command: OwnerCommand, +) -> CandidateError { + if guard_refused { + CandidateError::new( + OWNER_COMMAND_NOT_STARTED, + "The owner's check ended an authored command before it took the provider lease; nothing ran.", + ) + } else if error.code == "provider_busy" { CandidateError::new( - OWNER_EXEC_LEASE_BUSY, - "The owner's authored exec could not acquire the provider lease; nothing ran.", + match command { + OwnerCommand::Exec => OWNER_EXEC_LEASE_BUSY, + OwnerCommand::Run => OWNER_RUN_LEASE_BUSY, + }, + "The owner's authored command could not acquire the provider lease; nothing ran.", ) } else { error } } +/// The owner's guard and lease wait for one authored command, with their +/// pre-effect codes (HACK-2739, HACK-2742). The guard runs first, then before +/// every lease attempt and once after acquisition, so a pending signal ends the +/// wait within one backoff step. The wait counts against the command's fixed +/// `deadline` and is capped at `COMMAND_LEASE_WAIT`: it runs on the owner's only +/// loop, and the requester has already waited out a longer holder before it +/// sent the request. Nothing before the returned engine has an effect. +#[cfg(target_os = "macos")] +pub(super) fn owner_command_engine<'a>( + candidate: &'a Candidate, + deadline: Instant, + guard: &dyn Fn() -> Result<(), CandidateError>, + command: OwnerCommand, +) -> Result, CandidateError> { + let guard_refused = Cell::new(false); + let checked = || { + guard().inspect_err(|_| guard_refused.set(true))?; + Ok(()) + }; + checked().map_err(|error| owner_wait_refusal(error, true, command))?; + Engine::connect_command_until(candidate, deadline, &checked) + .map_err(|error| owner_wait_refusal(error, guard_refused.get(), command)) +} + #[cfg(target_os = "macos")] pub(in crate::provider::graph::native) fn execute( candidate: &Candidate, @@ -97,14 +167,12 @@ pub(in crate::provider::graph::native) fn execute( if !selected.valid() { return Err(refused()); } - guard()?; let deadline = Instant::now() + Duration::from_secs(30); // The owner loop's guard (signals, publication, pin) runs before every lease // attempt, and the wait counts against this 30 s budget (HACK-2669). The // requester already waited out a longer holder before it sent this // (HACK-2739), so this wait only covers a holder that took the lease since. - let engine = - Engine::connect_command_until(candidate, deadline, guard).map_err(owner_lease_refusal)?; + let engine = owner_command_engine(candidate, deadline, guard, OwnerCommand::Exec)?; let (receipt, _) = journal::load( candidate, expected.review.scope().run, @@ -211,11 +279,12 @@ pub(in crate::provider::graph::native) fn interactive( if !selected.valid() { return Err(refused()); } - guard()?; let deadline = Instant::now() + Duration::from_secs(30); - // The owner loop's guard (signals, publication, pin) runs before every lease - // attempt, and the wait counts against this 30 s budget (HACK-2669). - let engine = Engine::connect_command_until(candidate, deadline, guard)?; + // The owner loop's guard (signals, publication, pin, client disconnect) runs + // before every lease attempt, and the wait counts against this 30 s budget + // (HACK-2669). Its failures are pre-intent: no session receipt exists yet, + // so they carry their own codes (HACK-2742). + let engine = owner_command_engine(candidate, deadline, guard, OwnerCommand::Exec)?; let (receipt, _) = journal::load( candidate, expected.review.scope().run, diff --git a/packages/runtime-core/src/provider/graph/native/runtime/exec_tests.rs b/packages/runtime-core/src/provider/graph/native/runtime/exec_tests.rs index c141c4c5a1..15a3c3a147 100644 --- a/packages/runtime-core/src/provider/graph/native/runtime/exec_tests.rs +++ b/packages/runtime-core/src/provider/graph/native/runtime/exec_tests.rs @@ -177,48 +177,142 @@ fn finite_exec_refuses_changed_member_or_data_before_command_and_withholds_resta } } -/// HACK-2739: only the owner's expired lease wait gets the pre-effect code, and -/// that code passes the requester's closed reply-code filter unchanged. +/// HACK-2739 and HACK-2742: only the owner's expired lease wait and its own +/// refused check get pre-effect codes, and those codes pass the requester's +/// closed reply-code filter unchanged. #[test] -fn the_owners_exec_lease_refusal_has_its_own_pre_effect_code() { - let mapped = exec::owner_lease_refusal(CandidateError::new("provider_busy", "held")); - assert_eq!(mapped.code, exec::OWNER_EXEC_LEASE_BUSY); - assert!( - (1..=64).contains(&mapped.code.len()) - && mapped - .code - .bytes() - .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_') - ); +fn the_owners_wait_refusals_have_their_own_pre_effect_codes() { + use exec::{OwnerCommand, owner_wait_refusal}; + let busy = || CandidateError::new("provider_busy", "held"); + let cases = [ + ( + owner_wait_refusal(busy(), false, OwnerCommand::Exec), + exec::OWNER_EXEC_LEASE_BUSY, + ), + ( + owner_wait_refusal(busy(), false, OwnerCommand::Run), + exec::OWNER_RUN_LEASE_BUSY, + ), + // A refused check wins: the wait ended because of it, before any effect. + ( + owner_wait_refusal(busy(), true, OwnerCommand::Run), + exec::OWNER_COMMAND_NOT_STARTED, + ), + ( + owner_wait_refusal(refused(), true, OwnerCommand::Exec), + exec::OWNER_COMMAND_NOT_STARTED, + ), + ]; + for (mapped, code) in cases { + assert_eq!(mapped.code, code); + assert!( + (1..=64).contains(&mapped.code.len()) + && mapped + .code + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_') + ); + } for code in [ "provider_acquisition_cancelled", "native_graph_foreground", "managed_environment_expired", + "runtime_not_running", ] { - assert_eq!( - exec::owner_lease_refusal(CandidateError::new(code, "kept")).code, - code - ); + for command in [OwnerCommand::Exec, OwnerCommand::Run] { + assert_eq!( + owner_wait_refusal(CandidateError::new(code, "kept"), false, command).code, + code + ); + } } } -/// HACK-2739: the owner's own wait, on a real flock held as a project stop, ends in -/// that code (scaled: a 300 ms budget for the owner's 15 s bound). +/// HACK-2739 and HACK-2742: the owner's own wait, on a real flock held as a +/// project stop, ends in each command's lease code (scaled: a 300 ms budget for +/// the owner's 15 s bound). #[cfg(target_os = "macos")] #[test] -fn the_owners_exec_lease_wait_expires_with_the_pre_effect_code() { +fn the_owners_lease_wait_expires_with_each_commands_pre_effect_code() { use crate::provider::engine::command_lease_tests::{hold_lease_as_project_stop, running_pool}; let (_home, candidate) = running_pool(); let (release, holder) = hold_lease_as_project_stop(&candidate, Duration::from_secs(30)); - let refused = Engine::connect_command_until( + for (command, code) in [ + (exec::OwnerCommand::Exec, exec::OWNER_EXEC_LEASE_BUSY), + (exec::OwnerCommand::Run, exec::OWNER_RUN_LEASE_BUSY), + ] { + let refused = exec::owner_command_engine( + &candidate, + Instant::now() + Duration::from_millis(300), + &|| Ok(()), + command, + ) + .err() + .unwrap(); + assert_eq!(refused.code, code); + } + release.send(()).unwrap(); + holder.join().unwrap(); +} + +/// HACK-2742: a pending signal or `hack down` (the owner's check refusing) ends the +/// owner's wait within one backoff step, and the answer says nothing started +/// instead of the plain `refused()` that the CLI reported as "unconfirmed". A +/// check that refuses before the wait gets the same code. +#[cfg(target_os = "macos")] +#[test] +fn a_refused_owner_check_ends_the_wait_as_not_started() { + use crate::provider::engine::command_lease_tests::{ + hold_lease_as_project_stop, refuses_after, running_pool, + }; + let (_home, candidate) = running_pool(); + let (release, holder) = hold_lease_as_project_stop(&candidate, Duration::from_secs(30)); + for command in [exec::OwnerCommand::Exec, exec::OwnerCommand::Run] { + let started = Instant::now(); + let guard = refuses_after(Duration::from_millis(200), "native_graph_foreground"); + let ended = exec::owner_command_engine( + &candidate, + started + Duration::from_secs(30), + &guard, + command, + ) + .err() + .unwrap(); + assert_eq!(ended.code, exec::OWNER_COMMAND_NOT_STARTED); + assert!(started.elapsed() >= Duration::from_millis(200)); + assert!( + started.elapsed() < Duration::from_secs(2), + "the check did not end the wait: {:?}", + started.elapsed() + ); + let at_once = exec::owner_command_engine( + &candidate, + Instant::now() + Duration::from_secs(30), + &|| Err(refused()), + command, + ) + .err() + .unwrap(); + assert_eq!(at_once.code, exec::OWNER_COMMAND_NOT_STARTED); + } + release.send(()).unwrap(); + holder.join().unwrap(); +} + +/// HACK-2742: once the lease is free, a later failure keeps its own code (this +/// fixture's post-acquisition liveness refusal), so only the wait is relabelled. +#[cfg(target_os = "macos")] +#[test] +fn an_owner_failure_after_acquisition_keeps_its_code() { + use crate::provider::engine::command_lease_tests::{PAST_ACQUISITION, running_pool}; + let (_home, candidate) = running_pool(); + let refused = exec::owner_command_engine( &candidate, - Instant::now() + Duration::from_millis(300), + Instant::now() + Duration::from_secs(30), &|| Ok(()), + exec::OwnerCommand::Run, ) - .map_err(exec::owner_lease_refusal) .err() .unwrap(); - assert_eq!(refused.code, exec::OWNER_EXEC_LEASE_BUSY); - release.send(()).unwrap(); - holder.join().unwrap(); + assert_eq!(refused.code, PAST_ACQUISITION, "{}", refused.message); } diff --git a/packages/runtime-core/src/provider/graph/native/runtime/run.rs b/packages/runtime-core/src/provider/graph/native/runtime/run.rs index 8d217ef201..2ecf1365c1 100644 --- a/packages/runtime-core/src/provider/graph/native/runtime/run.rs +++ b/packages/runtime-core/src/provider/graph/native/runtime/run.rs @@ -293,11 +293,12 @@ pub(in crate::provider::graph::native) fn execute( if !selected.valid() { return Err(refused()); } - guard()?; let deadline = Instant::now() + Duration::from_secs(30); // The owner loop's guard (signals, publication, pin) runs before every lease - // attempt, and the wait counts against this 30 s budget (HACK-2669). - let engine = Engine::connect_command_until(candidate, deadline, guard)?; + // attempt, and the wait counts against this 30 s budget (HACK-2669). The + // requester waited out a longer holder before it sent this, and the wait's + // failures carry pre-effect codes (HACK-2742): no record or container exists yet. + let engine = exec::owner_command_engine(candidate, deadline, guard, exec::OwnerCommand::Run)?; let (receipt, root) = journal::load( candidate, expected.review.scope().run, diff --git a/packages/runtime-core/src/provider/lifecycle.rs b/packages/runtime-core/src/provider/lifecycle.rs index 3555b5a829..3b7cf386f2 100644 --- a/packages/runtime-core/src/provider/lifecycle.rs +++ b/packages/runtime-core/src/provider/lifecycle.rs @@ -423,8 +423,9 @@ pub(super) const COMMAND_LEASE_WAIT: Duration = Duration::from_secs(15); /// still costs only its own hold, and an uncontended acquisition returns at once. pub(super) const COMMAND_REQUEST_LEASE_WAIT: Duration = START_LEASE_WAIT; -/// The requesting process of an authored `hack exec` waits here, before it sends -/// anything to its owner, until the provider lease is free (HACK-2739). The owner +/// The requesting process of an authored `hack exec` (HACK-2739), one-off +/// `hack run` and interactive `hack exec` (HACK-2742) waits here, before it sends +/// anything to its owner, until the provider lease is free. The owner /// answers on its only loop thread, where its own wait keeps `COMMAND_LEASE_WAIT` /// inside a fixed 30 s budget that the requester reads for a fixed 40 s, so the /// wait for another project's stop belongs on this side, as the Compose @@ -452,18 +453,34 @@ pub(super) const COMMAND_REQUEST_LEASE_WAIT: Duration = START_LEASE_WAIT; /// /// The lease can be taken again between this wait and the owner's acquisition. /// The owner then waits its own 15 s, and on expiry answers with a pre-effect -/// code of its own (`graph_authored_exec_lease_busy`). +/// code of its own (`graph_authored_exec_lease_busy` or +/// `graph_authored_run_lease_busy`); if its own check ends that wait (a pending +/// signal, its `hack down`), it answers `graph_authored_command_not_started`. #[cfg(all(target_os = "macos", any(test, feature = "native-config-plan")))] pub(in crate::provider) fn await_free_command_lease( candidate: &Candidate, deadline: Instant, +) -> Result<(), CandidateError> { + await_free_command_lease_checked(candidate, deadline, &|| Ok(())) +} + +/// [`await_free_command_lease`] with the caller's `check`, which runs before every +/// lock attempt (HACK-2742): an interactive exec passes its frontend leash, so a +/// frontend that is gone ends the wait within one backoff step. A refusal from +/// `check` is returned as is; nothing was sent. +#[cfg(all(target_os = "macos", any(test, feature = "native-config-plan")))] +pub(in crate::provider) fn await_free_command_lease_checked( + candidate: &Candidate, + deadline: Instant, + check: &dyn Fn() -> Result<(), CandidateError>, ) -> Result<(), CandidateError> { let lease = super::engine::command_lease_deadline(Instant::now(), deadline, COMMAND_REQUEST_LEASE_WAIT); let root = root(candidate); + let check_refused = std::cell::Cell::new(false); match state::wait_for_acquisition( lease, - || Ok(()), + || check().inspect_err(|_| check_refused.set(true)), || state::Lock::acquire_existing(&root), state::acquisition_expired, ) { @@ -471,7 +488,7 @@ pub(in crate::provider) fn await_free_command_lease( drop(lock); Ok(()) } - Err(error) if error.code == "provider_busy" => Err(error), + Err(error) if error.code == "provider_busy" || check_refused.get() => Err(error), Err(_) => Ok(()), } } diff --git a/packages/runtime-core/src/provider/state.rs b/packages/runtime-core/src/provider/state.rs index 9da6820752..b68a61cd4f 100644 --- a/packages/runtime-core/src/provider/state.rs +++ b/packages/runtime-core/src/provider/state.rs @@ -223,11 +223,42 @@ pub(super) fn wait_for_acquisition( LEASE_WAIT_REPORT_AFTER, &mut |line| eprintln!("{line}"), ) + } else if let Some(sink) = LEASE_WAIT_SINK.get() { + wait_reporting( + deadline, + before_attempt, + acquire, + expired, + LEASE_WAIT_REPORT_AFTER, + &mut |line| sink(line), + ) } else { wait_quietly(deadline, before_attempt, acquire, expired) } } +type LeaseWaitSink = Box; + +/// Where this process's lease-wait report goes when its stderr is not the +/// frontend's (HACK-2742). `graph exec-interactive` inherits the user's terminal +/// as stderr, so it sends the same two report lines to its private control +/// channel instead, where the CLI prints the one progress line. Set at most once, +/// before any wait; the environment's stderr report takes precedence. +static LEASE_WAIT_SINK: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// Install [`LEASE_WAIT_SINK`]; false if one was already installed. +pub(crate) fn report_lease_waits_to(sink: LeaseWaitSink) -> bool { + LEASE_WAIT_SINK.set(sink).is_ok() +} + +/// The closed holder token a lease refusal names (`project-stop`, …), or `None` +/// for any other error or an unknown holder. +pub(crate) fn lease_refusal_holder(error: &CandidateError) -> Option<&'static str> { + (error.code == "provider_busy") + .then(|| holder_token(&error.message)) + .filter(|token| *token != "unknown") +} + /// How long a reporting waiter waits out contention before it says so: longer /// than the brief holds of `hack ps` or a ready owner's tick, which need no line. pub(super) const LEASE_WAIT_REPORT_AFTER: Duration = Duration::from_secs(3); diff --git a/scripts/lib/tla-runtime-models.ts b/scripts/lib/tla-runtime-models.ts index af45c8899a..ff07c90411 100644 --- a/scripts/lib/tla-runtime-models.ts +++ b/scripts/lib/tla-runtime-models.ts @@ -2382,6 +2382,38 @@ const contracts: readonly ModelContract[] = [ invariant: "NeverRanAfterStop", fields: ['report = "ran"', "sent = TRUE", "held = 31"], }, + { + // HACK-2742: the owner's check (a pending signal, its own + // `hack down`) may end its wait. That refusal sent nothing and is + // reported as not run; "unconfirmed" still only follows a send. The + // same shape covers authored `hack run` and interactive `hack exec`. + name: "authored-cancel", + module: "ExecStopWait", + negative: false, + states: 335, + }, + { + // The report before the fix: the owner's plain refusal read as + // "unconfirmed" although nothing was sent. + name: "authored-cancel-old", + module: "ExecStopWait", + negative: true, + invariant: "UnconfirmedOnlyAfterSend", + fields: [ + "cancelled = TRUE", + 'phase = "refused"', + 'report = "unconfirmed"', + "sent = FALSE", + ], + }, + { + // The owner's check ending its wait is reachable, as not run. + name: "authored-cancel-reach", + module: "ExecStopWait", + negative: true, + invariant: "NeverCancelled", + fields: ["cancelled = TRUE", 'report = "not-run"', "sent = FALSE"], + }, ], }, { diff --git a/src/backends/native-authored-project-exec.ts b/src/backends/native-authored-project-exec.ts index 43d482a731..67ead917f5 100644 --- a/src/backends/native-authored-project-exec.ts +++ b/src/backends/native-authored-project-exec.ts @@ -1,4 +1,3 @@ -import { noteNativeExitConfirmed } from "../lib/background-command/native-exit.ts"; import { isRecord } from "../lib/guards.ts"; import { keys } from "../lib/native-compose-private-state.ts"; import { nativeAuthoredExecOptions } from "./native-authored-exec-options.ts"; @@ -18,10 +17,8 @@ import { withPinnedRuntimeBinary, } from "./native-authored-runtime-binary.ts"; import { - isNativeCommandLeaseRefusal, - isNativeOwnerAuthoredExecLeaseRefusal, - NATIVE_COMMAND_LEASE_WAIT_SECONDS, - nativeCommandLeaseRefusal, + NATIVE_AUTHORED_COMMAND_REQUEST_TIMEOUT_MS, + nativeAuthoredCommandNotRun, nativeCommandLeaseWaitReporter, } from "./native-command-lease.ts"; import { @@ -42,44 +39,7 @@ const CONTAINER = /^[a-f0-9]{64}$/; * and a 5 s margin. It was 45 s before that wait. */ export const NATIVE_AUTHORED_EXEC_REQUEST_TIMEOUT_MS = - (NATIVE_COMMAND_LEASE_WAIT_SECONDS + 5 + 40 + 5) * 1000; - -/** - * The plain refusal for a request whose lease wait expired before anything ran - * (HACK-2739), or undefined. Two refusals are pre-effect: the requesting - * process's own wait, which ends before anything is sent (a raw - * `provider_busy` that names the holder), and the owner's own wait, which is - * the first thing the owner does for the exec (its code, forwarded as the - * cause of `native_graph_foreground`, names no holder). Every other failure - * keeps the unconfirmed report. No guest process exists for a command that - * never ran, so this also releases a native background command's admission - * slot, as the Compose exec does. - */ -async function authoredExecLeaseRefusal( - error: unknown -): Promise { - if ( - !( - isNativeCommandLeaseRefusal(error) || - isNativeOwnerAuthoredExecLeaseRefusal(error) - ) - ) { - return; - } - const refusal = nativeCommandLeaseRefusal({ - nativeMessage: isNativeCommandLeaseRefusal(error) - ? error.nativeMessage - : undefined, - command: "hack exec", - stage: "authored", - // The wire codes as they arrived: the requester's raw `provider_busy`, or - // the owner's code as the cause of `native_graph_foreground`. - nativeCode: error.nativeCode, - nativeCauseCode: error.nativeCauseCode, - }); - await noteNativeExitConfirmed(); - return refusal; -} + NATIVE_AUTHORED_COMMAND_REQUEST_TIMEOUT_MS; function refused(): never { throw new Error( @@ -291,7 +251,7 @@ export async function nativeAuthoredProjectExec(input: { } catch (error) { // Returned, not thrown: the held saved-status owner reports any // failure thrown inside it as an unconfirmed artifact failure. - const notRun = await authoredExecLeaseRefusal(error); + const notRun = await nativeAuthoredCommandNotRun(error, "hack exec"); if (notRun) { return notRun; } diff --git a/src/backends/native-authored-project-oneoff.ts b/src/backends/native-authored-project-oneoff.ts index ee1a5cf0ae..f6b7c4dad5 100644 --- a/src/backends/native-authored-project-oneoff.ts +++ b/src/backends/native-authored-project-oneoff.ts @@ -16,8 +16,14 @@ import { unstartedNativeAuthoredProject, withPinnedRuntimeBinary, } from "./native-authored-runtime-binary.ts"; +import { + NATIVE_AUTHORED_COMMAND_REQUEST_TIMEOUT_MS, + nativeAuthoredCommandNotRun, + nativeCommandLeaseWaitReporter, +} from "./native-command-lease.ts"; import { invokeNativeRuntime, + NativeRuntimeRequestError, type NativeRuntimeSelection, } from "./native-runtime-client.ts"; @@ -133,6 +139,8 @@ export async function nativeAuthoredProjectRun(input: { readonly invoke?: typeof invokeNativeRuntime; /** Control seam; production uses the held saved-read owner. */ readonly withStatus?: typeof withNativeAuthoredProjectStatus; + /** The lease-wait progress line; the CLI prints it once (HACK-2742). */ + readonly onLeaseWait?: (holder: string) => void; }): Promise { const runtime = { ...input.runtime }, scope = { ...input.scope }, @@ -141,6 +149,7 @@ export async function nativeAuthoredProjectRun(input: { workdir = input.workdir, signal = input.signal, invoke = input.invoke ?? invokeNativeRuntime, + onLeaseWait = nativeCommandLeaseWaitReporter({ given: input.onLeaseWait }), withStatus = input.withStatus ?? withNativeAuthoredProjectStatus; const active = () => { if (signal?.aborted) { @@ -175,26 +184,41 @@ export async function nativeAuthoredProjectRun(input: { await check(); // No await separates this final path/descriptor admission from real spawn. pin.checkSync(); - const value = await invoke({ - runtime, - cwd: scope.projectRoot, - args: [ - "graph", - "native", - "one-off", - "--run-id", - receipt.review.provenance.run, - "--service", - service, - ...(workdir === undefined ? [] : ["--workdir", workdir]), - "--json", - "--", - ...command, - ], - timeoutMs: 45_000, - signal, - boundNativeAuthoredOneOffDrain: true, - }); + let value: unknown; + try { + value = await invoke({ + runtime, + cwd: scope.projectRoot, + args: [ + "graph", + "native", + "one-off", + "--run-id", + receipt.review.provenance.run, + "--service", + service, + ...(workdir === undefined ? [] : ["--workdir", workdir]), + "--json", + "--", + ...command, + ], + // The requesting process first waits up to 35 s for a free provider + // lease, which another project's stop holds for its whole stop + // (HACK-2742), then sends and reads the owner's answer for 40 s. + timeoutMs: NATIVE_AUTHORED_COMMAND_REQUEST_TIMEOUT_MS, + signal, + onLeaseWait, + boundNativeAuthoredOneOffDrain: true, + }); + } catch (error) { + // Returned, not thrown: the held saved-status owner reports any + // failure thrown inside it as an unconfirmed artifact failure. + const notRun = await nativeAuthoredCommandNotRun(error, "hack run"); + if (notRun) { + return notRun; + } + throw error; + } await check(); const result = parseNativeAuthoredOneOff(value, receipt, service); await check(); @@ -203,7 +227,11 @@ export async function nativeAuthoredProjectRun(input: { ); }); active(); - if (result instanceof NativeAuthoredProjectNotStartedError) { + if ( + result instanceof NativeAuthoredProjectNotStartedError || + // Only a refusal that nothing ran is returned as this type (HACK-2742). + result instanceof NativeRuntimeRequestError + ) { throw result; } return result; diff --git a/src/backends/native-command-lease.ts b/src/backends/native-command-lease.ts index 01b38f1436..b2f9de2930 100644 --- a/src/backends/native-command-lease.ts +++ b/src/backends/native-command-lease.ts @@ -17,6 +17,7 @@ * the lease is taken again before the owner acquires it, the owner's own short * wait ends in a pre-effect code that also reads as "nothing ran". */ +import { noteNativeExitConfirmed } from "../lib/background-command/native-exit.ts"; import { NativeRuntimeRequestError } from "./native-runtime-client.ts"; import { NATIVE_START_LEASE_WAIT_SECONDS, @@ -28,6 +29,14 @@ import { export const NATIVE_COMMAND_LEASE_WAIT_SECONDS = NATIVE_START_LEASE_WAIT_SECONDS; +/** + * The bound of an authored `graph native exec` or `graph native one-off` + * request: the requesting process's lease wait (35 s, HACK-2739, HACK-2742), + * 5 s to send, the fixed 40 s read of the owner's answer, and a 5 s margin. + */ +export const NATIVE_AUTHORED_COMMAND_REQUEST_TIMEOUT_MS = + (NATIVE_COMMAND_LEASE_WAIT_SECONDS + 5 + 40 + 5) * 1000; + /** The commands whose requesting process waits this bound, as the user ran them. */ export type NativeLeaseCommand = "hack exec" | "hack run"; @@ -165,21 +174,147 @@ export function nativeCommandLeaseRefusal(opts: { readonly nativeCode?: string; readonly nativeCauseCode?: string; }): NativeRuntimeRequestError { - const holder = nativeStartLeaseHolder(opts.nativeMessage); - const outcome = - opts.stage === "exec" ? "the command did not run" : "nothing ran"; const error = new NativeRuntimeRequestError({ nativeCode: opts.nativeCode ?? "provider_busy", nativeCauseCode: opts.nativeCauseCode, nativeMessage: opts.nativeMessage, - message: [ - `${opts.command} could not acquire the native runtime lock (provider_busy); ${outcome}.`, - `Holder: ${holder ?? "unavailable"}.`, - holder - ? `Retry ${opts.command} once that ${holder} finishes.` - : `Retry ${opts.command} once the holder finishes.`, - ].join("\n"), + message: nativeCommandLeaseRefusalMessage({ + command: opts.command, + stage: opts.stage, + holder: nativeStartLeaseHolder(opts.nativeMessage), + }), }); notRunRefusals.add(error); return error; } + +/** + * The three lines of a lease refusal; `holder` is the recorded holder's words + * (`project stop`), or undefined when no holder is known. + */ +export function nativeCommandLeaseRefusalMessage(opts: { + readonly command: NativeLeaseCommand; + readonly stage: NativeLeaseStage; + readonly holder: string | undefined; +}): string { + const outcome = + opts.stage === "exec" ? "the command did not run" : "nothing ran"; + return [ + `${opts.command} could not acquire the native runtime lock (provider_busy); ${outcome}.`, + `Holder: ${opts.holder ?? "unavailable"}.`, + opts.holder + ? `Retry ${opts.command} once that ${opts.holder} finishes.` + : `Retry ${opts.command} once the holder finishes.`, + ].join("\n"); +} + +/** + * The authored owner's answer when its own lease wait for a one-off `hack run` + * expired (`OWNER_RUN_LEASE_BUSY` in `native/runtime/exec.rs`, HACK-2742). + */ +export const NATIVE_OWNER_AUTHORED_RUN_LEASE_BUSY = + "graph_authored_run_lease_busy"; + +/** + * The authored owner's answer when its own check (a pending signal, its + * `hack down`, a changed publication or pin) ended an exec or run before it + * took the lease (`OWNER_COMMAND_NOT_STARTED`, HACK-2742). Nothing ran. + */ +export const NATIVE_OWNER_AUTHORED_COMMAND_NOT_STARTED = + "graph_authored_command_not_started"; + +const OWNER_LEASE_CODES: readonly string[] = [ + NATIVE_OWNER_AUTHORED_EXEC_LEASE_BUSY, + NATIVE_OWNER_AUTHORED_RUN_LEASE_BUSY, +]; + +/** The two lines of an authored command its owner ended before it started. */ +export function nativeCommandNotStartedMessage( + command: NativeLeaseCommand +): string { + return [ + `${command} did not start: the project's owner stopped or changed while the command waited for the native runtime lock (${NATIVE_OWNER_AUTHORED_COMMAND_NOT_STARTED}); nothing ran.`, + `Check hack ps, then retry ${command} once the project is up.`, + ].join("\n"); +} + +/** + * The CLI message for an authored owner's pre-effect code, as an interactive + * exec's report or a finite request's cause carries it, or undefined for any + * other code (HACK-2742). + */ +export function nativeOwnerPreEffectMessage( + code: string, + command: NativeLeaseCommand +): string | undefined { + if (code === NATIVE_OWNER_AUTHORED_COMMAND_NOT_STARTED) { + return nativeCommandNotStartedMessage(command); + } + if (OWNER_LEASE_CODES.includes(code)) { + return nativeCommandLeaseRefusalMessage({ + command, + stage: "authored", + holder: undefined, + }); + } + return; +} + +/** + * The plain refusal for an authored exec or one-off run that never started + * (HACK-2739, HACK-2742), or undefined. Three refusals are pre-effect: the + * requesting process's own lease wait, which ends before anything is sent (a + * raw `provider_busy` that names the holder), the owner's own lease wait, and + * the owner's own check ending that wait (each an owner code, forwarded as the + * cause of `native_graph_foreground`, naming no holder). Every other failure + * keeps the unconfirmed report. The refusal keeps the wire code and cause as + * they arrived, and is marked as not run. + */ +export function nativeAuthoredCommandNotRunRefusal( + error: unknown, + command: NativeLeaseCommand +): NativeRuntimeRequestError | undefined { + if (isNativeCommandLeaseRefusal(error)) { + return nativeCommandLeaseRefusal({ + nativeMessage: error.nativeMessage, + command, + stage: "authored", + }); + } + if ( + !( + error instanceof NativeRuntimeRequestError && + error.nativeCode === "native_graph_foreground" && + error.nativeCauseCode !== undefined + ) + ) { + return; + } + const message = nativeOwnerPreEffectMessage(error.nativeCauseCode, command); + if (!message) { + return; + } + const refusal = new NativeRuntimeRequestError({ + nativeCode: error.nativeCode, + nativeCauseCode: error.nativeCauseCode, + message, + }); + notRunRefusals.add(refusal); + return refusal; +} + +/** + * {@link nativeAuthoredCommandNotRunRefusal}, and for a refusal also release a + * native background command's admission slot: no guest process exists for a + * command that never ran, as for the Compose exec. + */ +export async function nativeAuthoredCommandNotRun( + error: unknown, + command: NativeLeaseCommand +): Promise { + const refusal = nativeAuthoredCommandNotRunRefusal(error, command); + if (refusal) { + await noteNativeExitConfirmed(); + } + return refusal; +} diff --git a/src/backends/native-interactive-exec.ts b/src/backends/native-interactive-exec.ts index 568eae4ae5..bd17b61fc5 100644 --- a/src/backends/native-interactive-exec.ts +++ b/src/backends/native-interactive-exec.ts @@ -5,14 +5,22 @@ import { isRecord } from "../lib/guards.ts"; import { keys } from "../lib/native-compose-private-state.ts"; import { openTerminalControl } from "../lib/tty-process-group.ts"; import { withPinnedRuntimeBinary } from "./native-authored-runtime-binary.ts"; +import { + nativeCommandLeaseRefusalMessage, + nativeCommandLeaseWaitReporter, + nativeOwnerPreEffectMessage, +} from "./native-command-lease.ts"; import { invokeNativeRuntime, NATIVE_EXEC_ENVIRONMENT_CHANGED_MESSAGE, type NativeRuntimeSelection, } from "./native-runtime-client.ts"; +import { nativeLeaseHolderWords } from "./native-start-lease.ts"; const UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; const CODE = /^[a-z][a-z0-9_]{0,63}$/; +/** The runtime's closed lease-holder token (`project-stop`, …). */ +const HOLDER = /^[a-z][a-z-]{0,31}$/; function refused(): never { throw new ClosedCliError( "Native interactive exec could not confirm its terminal or session; no request was replayed." @@ -44,6 +52,8 @@ type Report = { session?: string; retained: boolean; failure?: string; + /** The holder token an expired lease wait names (HACK-2742). */ + holder?: string; }; export function parseInteractiveReport(value: unknown): Report { if (!isRecord(value) || value.version !== 1) { @@ -70,7 +80,12 @@ export function parseInteractiveReport(value: unknown): Report { } if ( value.outcome === "refused" && - keys(value, "code,outcome,session,version") && + (keys(value, "code,outcome,session,version") || + // HACK-2742: an expired lease wait also names its holder's closed token. + (keys(value, "code,holder,outcome,session,version") && + value.code === "provider_busy" && + typeof value.holder === "string" && + HOLDER.test(value.holder))) && typeof value.code === "string" && CODE.test(value.code) && (value.session === null || @@ -81,10 +96,37 @@ export function parseInteractiveReport(value: unknown): Report { retained: value.session !== null, ...(typeof value.session === "string" ? { session: value.session } : {}), failure: value.code, + ...(typeof value.holder === "string" ? { holder: value.holder } : {}), }; } return refused(); } + +/** + * The control channel's lease-wait event, which the runtime writes ahead of + * its final report while it waits for the lock (HACK-2742): the holder's closed + * token, or undefined when `line` is not that event. + */ +export function parseInteractiveLeaseWaitEvent( + line: string +): string | undefined { + try { + const value: unknown = JSON.parse(line); + if ( + isRecord(value) && + keys(value, "event,holder,version") && + value.version === 1 && + value.event === "lease-wait" && + typeof value.holder === "string" && + HOLDER.test(value.holder) + ) { + return value.holder; + } + } catch { + // Not an event; the final report is parsed on its own. + } + return; +} function quote(value: string): string { return `'${value.replaceAll("'", "'\\''")}'`; } @@ -108,6 +150,11 @@ type InteractiveOptions = { readonly expectedContainer?: string; readonly expectedGeneration?: string; readonly signal?: AbortSignal; + /** + * The lease-wait progress line of an authored (`native`) exec, printed once + * (HACK-2742). A Compose exec's own 15 s wait prints none. + */ + readonly onLeaseWait?: (holder: string) => void; }; export async function nativeInteractiveExec( @@ -231,7 +278,25 @@ async function runInteractiveChild( await new Promise((resolve) => child.once("close", () => resolve())); return refused(); } - const chunks: Buffer[] = []; + // The final report is one line. Lease-wait event lines may come first + // (HACK-2742); they are consumed as they arrive and never parsed as a report. + let pending = ""; + let reportText = ""; + const onLeaseWait = opts.native + ? nativeCommandLeaseWaitReporter({ given: opts.onLeaseWait }) + : undefined; + const takeLines = (final: boolean) => { + const lines = pending.split("\n"); + pending = final ? "" : (lines.pop() ?? ""); + for (const line of lines) { + const holder = parseInteractiveLeaseWaitEvent(line); + if (holder !== undefined) { + onLeaseWait?.(holder); + } else if (line.length > 0) { + reportText += `${line}\n`; + } + } + }; let size = 0; let invalid = false; let killTimer: ReturnType | undefined; @@ -255,7 +320,8 @@ async function runInteractiveChild( invalid = true; cancel(); } else { - chunks.push(chunk); + pending += chunk.toString("utf8"); + takeLines(false); } }); control.on("error", () => { @@ -281,11 +347,10 @@ async function runInteractiveChild( cancel(); } exit = await ended; + takeLines(true); if (!invalid) { try { - report = parseInteractiveReport( - JSON.parse(Buffer.concat(chunks).toString("utf8")) - ); + report = parseInteractiveReport(JSON.parse(reportText)); } catch { /* A lost child leaves durable evidence for the query below. */ } @@ -395,13 +460,45 @@ async function finishInteractiveReport({ await reportRetainedSessions(opts, check, remedy, session); } if (report.failure) { - process.stderr.write(`${interactiveRefusalMessage(report.failure)}\n`); + process.stderr.write( + `${interactiveRefusalMessage(report.failure, { + native: opts.native, + holder: report.holder, + retained: report.retained, + })}\n` + ); } return restorationFailed && report.code === 0 ? 1 : report.code; } -/** The terminal line for a refused interactive exec; the report carries only its code. */ -export function interactiveRefusalMessage(code: string): string { +/** + * The terminal line for a refused interactive exec; the report carries only its + * code (and, for an expired lease wait, the holder's token). For an authored + * (`native`) exec refused before its session existed (`retained` false), the + * requester's expired lease wait and the owner's pre-effect wait codes mean + * nothing ran (HACK-2742). + */ +export function interactiveRefusalMessage( + code: string, + context: { + readonly native?: boolean; + readonly holder?: string; + readonly retained?: boolean; + } = {} +): string { + if (context.native && !context.retained) { + if (code === "provider_busy") { + return nativeCommandLeaseRefusalMessage({ + command: "hack exec", + stage: "authored", + holder: nativeLeaseHolderWords(context.holder), + }); + } + const owner = nativeOwnerPreEffectMessage(code, "hack exec"); + if (owner) { + return owner; + } + } if (code === "graph_service_exec_environment_changed") { // HACK-2740: fresh values for a service that started without them. No // command ran, so this is not an uncertain outcome. diff --git a/src/backends/native-runtime-client.ts b/src/backends/native-runtime-client.ts index 512e46cee8..90ff9e9434 100644 --- a/src/backends/native-runtime-client.ts +++ b/src/backends/native-runtime-client.ts @@ -1377,9 +1377,11 @@ function nativeFailureCause(input: { (input.code === "native_graph_foreground" && (input.cause === NATIVE_RUNTIME_NOT_RUNNING || input.cause === "graph_status_changed" || - // The authored owner's pre-effect exec lease refusal (HACK-2739), - // `NATIVE_OWNER_AUTHORED_EXEC_LEASE_BUSY` in native-command-lease.ts. - input.cause === "graph_authored_exec_lease_busy")) + // The authored owner's pre-effect wait refusals (HACK-2739, HACK-2742), + // `NATIVE_OWNER_AUTHORED_*` in native-command-lease.ts. + input.cause === "graph_authored_exec_lease_busy" || + input.cause === "graph_authored_run_lease_busy" || + input.cause === "graph_authored_command_not_started")) ? input.cause : undefined; } diff --git a/src/backends/native-start-lease.ts b/src/backends/native-start-lease.ts index eee1f7eb43..fd93e0e105 100644 --- a/src/backends/native-start-lease.ts +++ b/src/backends/native-start-lease.ts @@ -88,6 +88,16 @@ export function nativeStartLeaseWaitLine(token: string | undefined): string { return `Waiting for the native runtime lock, held by ${nativeLeaseHolderPhrase(token)}. This start continues once it is released (up to ${NATIVE_START_LEASE_WAIT_SECONDS} s).`; } +/** + * The holder's words (`project stop`) for the runtime's closed holder token, as + * a refusal names it; undefined for an unknown token (HACK-2742). + */ +export function nativeLeaseHolderWords( + token: string | undefined +): string | undefined { + return token === undefined ? undefined : HOLDER_WORDS[token]; +} + /** * The holder a progress line names, with its article, for the runtime's closed * holder token. An unknown token names no holder. diff --git a/tests/fixtures/native-interactive-frontend.py b/tests/fixtures/native-interactive-frontend.py index 60396ba7eb..1e92bfa7bf 100644 --- a/tests/fixtures/native-interactive-frontend.py +++ b/tests/fixtures/native-interactive-frontend.py @@ -91,7 +91,7 @@ def record(control, master, output, expected, timeout, mode): protected_keys = json.loads(sys.argv[2]) command = sys.argv[3:] assert all(os.environ.get(key) == "synthetic-parent-key-canary" for key in protected_keys) -for mode in ("normal", "child-kill", "frontend-kill", "cancel", "refused", "old-launcher", "retained", "retained-zero", "cleared"): +for mode in ("normal", "child-kill", "frontend-kill", "cancel", "refused", "old-launcher", "retained", "retained-zero", "cleared", "native-lease", "native-not-started"): for name in ("reader.pid", "reader.closed", "session.queried", "session.cleared"): try: os.unlink(os.path.join(root, name)) @@ -172,6 +172,18 @@ def session(): assert b"session_cleanup_uncertain" not in output, repr(output) if mode in ("normal", "retained", "retained-zero"): assert output == b"child-ready\n", repr(output) + elif mode in ("native-lease", "native-not-started"): + # HACK-2742: one progress line from the fd-3 event, then a refusal + # that says nothing ran; no session was created or queried. + assert not os.path.exists(os.path.join(root, "session.queried")) + assert output.count(b"Waiting for the native runtime lock, held by a project stop.") == 1, repr(output) + assert b"nothing ran." in output, repr(output) + assert b"could not confirm admission or completion" not in output, repr(output) + assert b"session_cleanup_uncertain" not in output, repr(output) + if mode == "native-lease": + assert b"Holder: project stop." in output, repr(output) + else: + assert b"graph_authored_command_not_started" in output, repr(output) elif mode == "cleared": assert b"No receipt is currently retained for session" in output assert b"without a result" not in output @@ -242,4 +254,4 @@ def session(): control.close() os.close(master) os.close(slave) -print("Frontend PTY: nine lifetime and five selection cases passed") +print("Frontend PTY: eleven lifetime and five selection cases passed") diff --git a/tests/fixtures/native-interactive-frontend.ts b/tests/fixtures/native-interactive-frontend.ts index 0e358a038d..8312b23741 100644 --- a/tests/fixtures/native-interactive-frontend.ts +++ b/tests/fixtures/native-interactive-frontend.ts @@ -24,6 +24,7 @@ process.exitCode = await nativeInteractiveExec({ namespace: "d".repeat(64), service: "web", command: [mode], - native: false, + // HACK-2742: `native-*` modes are an authored project's interactive exec. + native: mode.startsWith("native-"), payload: new TextEncoder().encode("synthetic-private-envelope-canary"), }); diff --git a/tests/fixtures/native-interactive-runtime.py b/tests/fixtures/native-interactive-runtime.py index 2b10aa74a0..e85bf1393b 100644 --- a/tests/fixtures/native-interactive-runtime.py +++ b/tests/fixtures/native-interactive-runtime.py @@ -40,6 +40,17 @@ file.write(str(os.getpid())) os.write(1, b"child-ready\n") mode = sys.argv[-1] +if mode in ("native-lease", "native-not-started"): + # HACK-2742: an authored exec's lease-wait event comes first on fd 3, then + # its pre-dispatch refusal (no session) with the holder's closed token. + assert "--native" in sys.argv + control.sendall(json.dumps({"version": 1, "event": "lease-wait", "holder": "project-stop"}).encode() + b"\n") + if mode == "native-lease": + report = {"version": 1, "outcome": "refused", "code": "provider_busy", "session": None, "holder": "project-stop"} + else: + report = {"version": 1, "outcome": "refused", "code": "graph_authored_command_not_started", "session": None} + control.sendall(json.dumps(report).encode() + b"\n") + sys.exit(1) if mode in ("refused", "old-launcher"): code = "graph_service_exec_launcher" if mode == "old-launcher" else "interactive_exec_refused" control.sendall(json.dumps({"version": 1, "outcome": "refused", "code": code, "session": None}).encode() + b"\n") diff --git a/tests/models/tla/native-command-lease/COVERAGE.md b/tests/models/tla/native-command-lease/COVERAGE.md index d2c56bc09e..d0db8f176d 100644 --- a/tests/models/tla/native-command-lease/COVERAGE.md +++ b/tests/models/tla/native-command-lease/COVERAGE.md @@ -31,7 +31,9 @@ nothing would hold Ctrl-C, `hack down` and the restart tick for up to 15 s | `service_exec` (`graph exec`, finite exec) | requesting CLI | `Engine::connect_command_request` (35 s, HACK-2729) | expiry of fresh per-command values (`managed.deadline()`), if any | exec timeout starts after acquisition; frontend 95 s | | `service_exec::interactive` (compose) | CLI | `Engine::connect_command_until` | the frontend's `live` check | counts against the interactive deadline | | `native::foreground::exec` (authored finite exec, `graph native exec`) | requesting CLI | `lifecycle::await_free_command_lease` (35 s, HACK-2739): waits for a free lease and releases it, no engine connection | none (Ctrl-C ends the process) | before the send; then the fixed 40 s read; frontend 85 s | -| `native::runtime::exec::execute`, `exec::interactive`, `run::execute` (authored) | owner loop | `Engine::connect_command_until` | the owner's guard: signals, publication, pin (and client disconnect for interactive) | counts against the fixed 30 s budget; `execute` maps its expiry to `graph_authored_exec_lease_busy` (HACK-2739) | +| `native::foreground::one_off` (authored `hack run`) | requesting CLI | `await_free_command_lease` (35 s, HACK-2742) | none | before the send; then the fixed 40 s read; frontend 85 s | +| `native::foreground::interactive` (authored interactive exec) | interactive child | `await_free_command_lease_checked` (35 s, HACK-2742) | the frontend leash | before the send | +| `native::runtime::exec::execute`, `exec::interactive`, `run::execute` (authored) | owner loop | `Engine::connect_command_until` | the owner's guard: signals, publication, pin (and client disconnect for interactive) | counts against the fixed 30 s budget; `owner_command_engine` maps its expiry to `graph_authored_exec_lease_busy` or `graph_authored_run_lease_busy` (HACK-2739, HACK-2742) and a refused guard to `graph_authored_command_not_started` (HACK-2742) | The authored paths keep the wait inside their 30 s budget on purpose: the native requester (`request_selected`) reads the owner's answer for a fixed @@ -228,8 +230,60 @@ Tests: unconfirmed with the slot held. `tests/native-runtime-client.test.ts`: the owner's code survives the client's closed cause filter. -Not changed: authored one-off `run` and interactive exec keep only the -owner's 15 s wait, and still report an expiry as unconfirmed. +## Authored `hack run`, interactive exec and the owner's own check (HACK-2742) + +HACK-2739 left two authored commands with only the owner's 15 s wait: +one-off `hack run` (`native::foreground::one_off`, owner side +`native/runtime/run.rs`) and interactive `hack exec` +(`native::foreground::interactive`, owner side `exec.rs` `interactive`). Both +reported an expired wait as unconfirmed. A third case covered all three: the +owner's guard (a pending signal, its own `hack down`, a changed publication or +pin) runs before every lease attempt, so it can end the owner's wait. It +returned the plain `refused()`, which the CLI also reported as unconfirmed, +although nothing had been read, touched or started. + +- Both requesters now call `await_free_command_lease` before they send. The + interactive one passes its frontend leash as the check + (`await_free_command_lease_checked`), so a frontend that is gone ends the + wait. A refused check is returned as is. +- All three owner paths go through `exec::owner_command_engine`. It runs the + guard, then `connect_command_until`, and relabels only those failures: + `graph_authored_exec_lease_busy` or `graph_authored_run_lease_busy` when the + lease stayed busy, and `graph_authored_command_not_started` when the guard + refused. Later failures keep their codes. +- `hack run` now has the same 85 s frontend bound as the finite exec (it was + 45 s), its progress line, its not-run refusals and its released admission + slot. +- The interactive child's stderr is the user's terminal, so its lease-wait + report goes to its control channel (fd 3) as one closed event line ahead of + the final report. The CLI prints the usual progress line for an authored + exec. The final refusal report also carries the holder's closed token for + an expired requester wait. The requester forwards the owner's pre-effect + codes as the report code, which carries only one code. + +`ExecStopWait.tla` gains `Cancellable` (the owner's check may end the owner +wait) and `CancelUnconfirmed` (the report before the fix). Every earlier +config sets both to `FALSE`; their state counts are unchanged. + +| Config | Constants | Result | Shows | +| --- | --- | --- | --- | +| `authored-cancel` | `SecondBound = 15`, `Holders = 2`, `Cancellable = TRUE` | 335 distinct states, no error; `NoSendWhileHeld`, `UnconfirmedOnlyAfterSend`, `NotRunMeansNotSent` and `Settles` hold | A cancelled owner wait sent nothing and is reported as not run | +| `authored-cancel-old` | `CancelUnconfirmed = TRUE` | `UnconfirmedOnlyAfterSend` violated: `cancelled = TRUE`, `report = "unconfirmed"`, `sent = FALSE` | The report before the fix | +| `authored-cancel-reach` | `Cancellable = TRUE` | `NeverCancelled` violated: `cancelled = TRUE`, `report = "not-run"` | The cancel is reachable, so the positive control is not vacuous | + +The model's two waits stand for each command's requester and owner waits; the +run and interactive paths have the same shape as the finite exec. + +Tests: `command_lease_tests.rs` (the `one_off` call site waits out the stop; +a refused requester check ends the wait with its own error; the refusal's +holder token), `exec_tests.rs` (`owner_wait_refusal` codes; the owner's lease +wait per command; a guard that refuses during or before the wait ends it as +not started within 2 s; a later failure keeps its code), +`tests/native-authored-project-oneoff.test.ts`, `native-command-lease`, +`native-authored-project-exec` (the not-started message), +`native-interactive-exec` (the event line, the report's holder field, the +messages, and a PTY case each for a lease refusal and a not-started refusal), +`native-runtime-client` (the new causes pass the closed filter). ## Code and tests diff --git a/tests/models/tla/native-command-lease/ExecStopWait.tla b/tests/models/tla/native-command-lease/ExecStopWait.tla index 15bde06429..50d1300be4 100644 --- a/tests/models/tla/native-command-lease/ExecStopWait.tla +++ b/tests/models/tla/native-command-lease/ExecStopWait.tla @@ -32,16 +32,25 @@ (* a second holder that arrives while the first wait is still running; that *) (* holder only lengthens a wait that sends nothing, and its expiry is the *) (* same not-run refusal that a StopHold past Bound already reaches. *) +(* *) +(* HACK-2742. The authored owner's check (a pending signal, its own `hack *) +(* down`) runs before every lease attempt, so it can end the owner's wait *) +(* (Cancellable = TRUE). Nothing was sent. CancelUnconfirmed = TRUE is the *) +(* report before the fix, which called that refusal "unconfirmed". The same *) +(* model covers authored one-off `hack run` and interactive `hack exec`: *) +(* their requester and owner waits have the same shape. *) EXTENDS Naturals CONSTANTS Bound, SecondBound, Probe, StopHold, ExpiryUnconfirmed, Holders, - EnforceLease -VARIABLES holder, holds, phase, elapsed, held, sent, sentHeld, report -vars == <> + EnforceLease, Cancellable, CancelUnconfirmed +VARIABLES holder, holds, phase, elapsed, held, sent, sentHeld, report, + cancelled +vars == <> Init == /\ holder = "stop" /\ holds = 1 /\ phase = IF Probe THEN "refresh" ELSE "exec" /\ elapsed = 0 /\ held = 0 /\ sent = FALSE /\ sentHeld = FALSE - /\ report = "none" + /\ report = "none" /\ cancelled = FALSE Waiting == phase \in {"refresh", "exec"} @@ -50,21 +59,22 @@ PhaseBound == IF phase = "refresh" THEN Bound ELSE SecondBound \* The current holder releases the lease, at the latest after StopHold ticks. Release == /\ holder \in {"stop", "peer"} /\ holder' = "free" - /\ UNCHANGED <> + /\ UNCHANGED <> \* A second holder takes the free lease after the refresh, before the exec \* (for the authored path: after the requester's wait, before the owner's). \* It is not enabled during the first wait. PeerTake == /\ phase = "exec" /\ holder = "free" /\ holds < Holders /\ holder' = "peer" /\ holds' = holds + 1 /\ held' = 0 - /\ UNCHANGED <> + /\ UNCHANGED <> \* Time passes for the waiter only while someone else holds the lease: the \* waiter polls every 5 to 50 ms, so it does not sit on a free lease. Tick == /\ Waiting /\ elapsed < PhaseBound /\ holder # "free" /\ held < StopHold /\ elapsed' = elapsed + 1 /\ held' = held + 1 - /\ UNCHANGED <> + /\ UNCHANGED <> \* The refresh reads under the lease and releases it, sending nothing yet; \* the exec's own wait starts with its own budget. The exec takes the lease @@ -75,21 +85,30 @@ Acquire == /\ Waiting /\ elapsed < PhaseBound /\ phase' = IF phase = "refresh" THEN "exec" ELSE "sent" /\ sent' = (phase = "exec") /\ sentHeld' = (phase = "exec" /\ holder # "free") - /\ UNCHANGED <> + /\ UNCHANGED <> \* At the bound the wait refuses: provider_busy naming the holder for the \* requester, its own pre-effect code for the authored owner. Expire == /\ Waiting /\ elapsed = PhaseBound /\ phase' = "refused" /\ report' = IF ExpiryUnconfirmed THEN "unconfirmed" ELSE "not-run" + /\ UNCHANGED <> + +\* HACK-2742: the authored owner's check (a pending signal, its `hack down`) +\* ends its own wait before acquisition; it answers its not-started code. +Cancel == /\ Cancellable /\ phase = "exec" + /\ phase' = "refused" /\ cancelled' = TRUE + /\ report' = IF CancelUnconfirmed THEN "unconfirmed" ELSE "not-run" /\ UNCHANGED <> \* The command's reply arrives, or is lost after the send. Finish == /\ phase = "sent" /\ phase' = "done" /\ report' \in {"ran", "unconfirmed"} - /\ UNCHANGED <> + /\ UNCHANGED <> -Next == Release \/ PeerTake \/ Tick \/ Acquire \/ Expire \/ Finish +Next == Release \/ PeerTake \/ Tick \/ Acquire \/ Expire \/ Cancel \/ Finish Spec == Init /\ [][Next]_vars /\ WF_vars(Acquire \/ Tick \/ Expire \/ Finish) /\ WF_vars(Release) @@ -99,6 +118,7 @@ TypeOK == /\ holder \in {"stop", "peer", "free"} /\ holds \in 1..Holders /\ elapsed \in 0..MaxBound /\ held \in 0..StopHold /\ sent \in BOOLEAN /\ sentHeld \in BOOLEAN /\ report \in {"none", "ran", "unconfirmed", "not-run"} + /\ cancelled \in BOOLEAN \* The command is sent only while no one else holds the lease. NoSendWhileHeld == ~sentHeld \* "unconfirmed" only when the command was sent, so effects may have happened. @@ -117,4 +137,6 @@ NeverUnconfirmed == report # "unconfirmed" \* Reachability: the second wait refuses as not run, with nothing sent. NeverRefusedAtSecondWait == ~(phase = "refused" /\ elapsed = SecondBound /\ report = "not-run" /\ holds = 2) +\* Reachability (HACK-2742): the owner's check ends its wait as not run. +NeverCancelled == ~(cancelled /\ report = "not-run") ============================================================================= diff --git a/tests/models/tla/native-command-lease/authored-cancel-old.cfg b/tests/models/tla/native-command-lease/authored-cancel-old.cfg new file mode 100644 index 0000000000..151edcde71 --- /dev/null +++ b/tests/models/tla/native-command-lease/authored-cancel-old.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CONSTANTS Bound = 35 SecondBound = 15 Probe = TRUE StopHold = 31 ExpiryUnconfirmed = FALSE Holders = 2 EnforceLease = TRUE Cancellable = TRUE CancelUnconfirmed = TRUE +INVARIANT UnconfirmedOnlyAfterSend +CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/native-command-lease/authored-cancel-reach.cfg b/tests/models/tla/native-command-lease/authored-cancel-reach.cfg new file mode 100644 index 0000000000..1fc18a860a --- /dev/null +++ b/tests/models/tla/native-command-lease/authored-cancel-reach.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CONSTANTS Bound = 35 SecondBound = 15 Probe = TRUE StopHold = 31 ExpiryUnconfirmed = FALSE Holders = 2 EnforceLease = TRUE Cancellable = TRUE CancelUnconfirmed = FALSE +INVARIANT NeverCancelled +CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/native-command-lease/authored-cancel.cfg b/tests/models/tla/native-command-lease/authored-cancel.cfg new file mode 100644 index 0000000000..d9c8d454d2 --- /dev/null +++ b/tests/models/tla/native-command-lease/authored-cancel.cfg @@ -0,0 +1,8 @@ +SPECIFICATION Spec +CONSTANTS Bound = 35 SecondBound = 15 Probe = TRUE StopHold = 31 ExpiryUnconfirmed = FALSE Holders = 2 EnforceLease = TRUE Cancellable = TRUE CancelUnconfirmed = FALSE +INVARIANT TypeOK +INVARIANT NoSendWhileHeld +INVARIANT UnconfirmedOnlyAfterSend +INVARIANT NotRunMeansNotSent +PROPERTY Settles +CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/native-command-lease/authored-honest-no-wait.cfg b/tests/models/tla/native-command-lease/authored-honest-no-wait.cfg index 2460517501..d852f78b70 100644 --- a/tests/models/tla/native-command-lease/authored-honest-no-wait.cfg +++ b/tests/models/tla/native-command-lease/authored-honest-no-wait.cfg @@ -1,4 +1,4 @@ SPECIFICATION Spec -CONSTANTS Bound = 35 SecondBound = 15 Probe = FALSE StopHold = 31 ExpiryUnconfirmed = FALSE Holders = 1 EnforceLease = TRUE +CONSTANTS Bound = 35 SecondBound = 15 Probe = FALSE StopHold = 31 ExpiryUnconfirmed = FALSE Holders = 1 EnforceLease = TRUE Cancellable = FALSE CancelUnconfirmed = FALSE INVARIANT StopNeverRefuses CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/native-command-lease/authored-old.cfg b/tests/models/tla/native-command-lease/authored-old.cfg index 5d9e24fc70..0f2433a137 100644 --- a/tests/models/tla/native-command-lease/authored-old.cfg +++ b/tests/models/tla/native-command-lease/authored-old.cfg @@ -1,4 +1,4 @@ SPECIFICATION Spec -CONSTANTS Bound = 35 SecondBound = 15 Probe = FALSE StopHold = 31 ExpiryUnconfirmed = TRUE Holders = 1 EnforceLease = TRUE +CONSTANTS Bound = 35 SecondBound = 15 Probe = FALSE StopHold = 31 ExpiryUnconfirmed = TRUE Holders = 1 EnforceLease = TRUE Cancellable = FALSE CancelUnconfirmed = FALSE INVARIANT UnconfirmedOnlyAfterSend CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/native-command-lease/authored-outlasts-stop.cfg b/tests/models/tla/native-command-lease/authored-outlasts-stop.cfg index 01e6bbbd6e..ebafa59392 100644 --- a/tests/models/tla/native-command-lease/authored-outlasts-stop.cfg +++ b/tests/models/tla/native-command-lease/authored-outlasts-stop.cfg @@ -1,5 +1,5 @@ SPECIFICATION Spec -CONSTANTS Bound = 35 SecondBound = 15 Probe = TRUE StopHold = 31 ExpiryUnconfirmed = FALSE Holders = 1 EnforceLease = TRUE +CONSTANTS Bound = 35 SecondBound = 15 Probe = TRUE StopHold = 31 ExpiryUnconfirmed = FALSE Holders = 1 EnforceLease = TRUE Cancellable = FALSE CancelUnconfirmed = FALSE INVARIANT TypeOK INVARIANT NoSendWhileHeld INVARIANT UnconfirmedOnlyAfterSend diff --git a/tests/models/tla/native-command-lease/authored-peer-race.cfg b/tests/models/tla/native-command-lease/authored-peer-race.cfg index fd1e69c2c3..a131bbc0b4 100644 --- a/tests/models/tla/native-command-lease/authored-peer-race.cfg +++ b/tests/models/tla/native-command-lease/authored-peer-race.cfg @@ -1,5 +1,5 @@ SPECIFICATION Spec -CONSTANTS Bound = 35 SecondBound = 15 Probe = TRUE StopHold = 40 ExpiryUnconfirmed = FALSE Holders = 2 EnforceLease = TRUE +CONSTANTS Bound = 35 SecondBound = 15 Probe = TRUE StopHold = 40 ExpiryUnconfirmed = FALSE Holders = 2 EnforceLease = TRUE Cancellable = FALSE CancelUnconfirmed = FALSE INVARIANT TypeOK INVARIANT NoSendWhileHeld INVARIANT UnconfirmedOnlyAfterSend diff --git a/tests/models/tla/native-command-lease/authored-peer-refused.cfg b/tests/models/tla/native-command-lease/authored-peer-refused.cfg index d37db2f8c3..feb04f0cdf 100644 --- a/tests/models/tla/native-command-lease/authored-peer-refused.cfg +++ b/tests/models/tla/native-command-lease/authored-peer-refused.cfg @@ -1,4 +1,4 @@ SPECIFICATION Spec -CONSTANTS Bound = 35 SecondBound = 15 Probe = TRUE StopHold = 31 ExpiryUnconfirmed = FALSE Holders = 2 EnforceLease = TRUE +CONSTANTS Bound = 35 SecondBound = 15 Probe = TRUE StopHold = 31 ExpiryUnconfirmed = FALSE Holders = 2 EnforceLease = TRUE Cancellable = FALSE CancelUnconfirmed = FALSE INVARIANT NeverRefusedAtSecondWait CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/native-command-lease/authored-ran-after-stop.cfg b/tests/models/tla/native-command-lease/authored-ran-after-stop.cfg index eeb9a12e9f..bcb82e614d 100644 --- a/tests/models/tla/native-command-lease/authored-ran-after-stop.cfg +++ b/tests/models/tla/native-command-lease/authored-ran-after-stop.cfg @@ -1,4 +1,4 @@ SPECIFICATION Spec -CONSTANTS Bound = 35 SecondBound = 15 Probe = TRUE StopHold = 31 ExpiryUnconfirmed = FALSE Holders = 1 EnforceLease = TRUE +CONSTANTS Bound = 35 SecondBound = 15 Probe = TRUE StopHold = 31 ExpiryUnconfirmed = FALSE Holders = 1 EnforceLease = TRUE Cancellable = FALSE CancelUnconfirmed = FALSE INVARIANT NeverRanAfterStop CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/native-command-lease/exec-outlasts-stop.cfg b/tests/models/tla/native-command-lease/exec-outlasts-stop.cfg index 52fe0a5f5b..340fc93877 100644 --- a/tests/models/tla/native-command-lease/exec-outlasts-stop.cfg +++ b/tests/models/tla/native-command-lease/exec-outlasts-stop.cfg @@ -1,5 +1,5 @@ SPECIFICATION Spec -CONSTANTS Bound = 35 SecondBound = 35 Probe = TRUE StopHold = 31 ExpiryUnconfirmed = FALSE Holders = 2 EnforceLease = TRUE +CONSTANTS Bound = 35 SecondBound = 35 Probe = TRUE StopHold = 31 ExpiryUnconfirmed = FALSE Holders = 2 EnforceLease = TRUE Cancellable = FALSE CancelUnconfirmed = FALSE INVARIANT TypeOK INVARIANT NoSendWhileHeld INVARIANT UnconfirmedOnlyAfterSend diff --git a/tests/models/tla/native-command-lease/exec-past-bound-honest.cfg b/tests/models/tla/native-command-lease/exec-past-bound-honest.cfg index f4f6176696..832c0ed32a 100644 --- a/tests/models/tla/native-command-lease/exec-past-bound-honest.cfg +++ b/tests/models/tla/native-command-lease/exec-past-bound-honest.cfg @@ -1,5 +1,5 @@ SPECIFICATION Spec -CONSTANTS Bound = 35 SecondBound = 35 Probe = TRUE StopHold = 40 ExpiryUnconfirmed = FALSE Holders = 2 EnforceLease = TRUE +CONSTANTS Bound = 35 SecondBound = 35 Probe = TRUE StopHold = 40 ExpiryUnconfirmed = FALSE Holders = 2 EnforceLease = TRUE Cancellable = FALSE CancelUnconfirmed = FALSE INVARIANT TypeOK INVARIANT NoSendWhileHeld INVARIANT UnconfirmedOnlyAfterSend diff --git a/tests/models/tla/native-command-lease/exec-past-bound.cfg b/tests/models/tla/native-command-lease/exec-past-bound.cfg index 85340c895f..cdd063f324 100644 --- a/tests/models/tla/native-command-lease/exec-past-bound.cfg +++ b/tests/models/tla/native-command-lease/exec-past-bound.cfg @@ -1,4 +1,4 @@ SPECIFICATION Spec -CONSTANTS Bound = 35 SecondBound = 35 Probe = TRUE StopHold = 40 ExpiryUnconfirmed = FALSE Holders = 2 EnforceLease = TRUE +CONSTANTS Bound = 35 SecondBound = 35 Probe = TRUE StopHold = 40 ExpiryUnconfirmed = FALSE Holders = 2 EnforceLease = TRUE Cancellable = FALSE CancelUnconfirmed = FALSE INVARIANT StopNeverRefuses CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/native-command-lease/exec-ran-after-peer.cfg b/tests/models/tla/native-command-lease/exec-ran-after-peer.cfg index cbcb48b3b3..7a5322414f 100644 --- a/tests/models/tla/native-command-lease/exec-ran-after-peer.cfg +++ b/tests/models/tla/native-command-lease/exec-ran-after-peer.cfg @@ -1,4 +1,4 @@ SPECIFICATION Spec -CONSTANTS Bound = 35 SecondBound = 35 Probe = TRUE StopHold = 31 ExpiryUnconfirmed = FALSE Holders = 2 EnforceLease = TRUE +CONSTANTS Bound = 35 SecondBound = 35 Probe = TRUE StopHold = 31 ExpiryUnconfirmed = FALSE Holders = 2 EnforceLease = TRUE Cancellable = FALSE CancelUnconfirmed = FALSE INVARIANT NeverRanAfterPeer CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/native-command-lease/exec-ran-after-stop.cfg b/tests/models/tla/native-command-lease/exec-ran-after-stop.cfg index b35ed54618..183a99c312 100644 --- a/tests/models/tla/native-command-lease/exec-ran-after-stop.cfg +++ b/tests/models/tla/native-command-lease/exec-ran-after-stop.cfg @@ -1,4 +1,4 @@ SPECIFICATION Spec -CONSTANTS Bound = 35 SecondBound = 35 Probe = TRUE StopHold = 31 ExpiryUnconfirmed = FALSE Holders = 1 EnforceLease = TRUE +CONSTANTS Bound = 35 SecondBound = 35 Probe = TRUE StopHold = 31 ExpiryUnconfirmed = FALSE Holders = 1 EnforceLease = TRUE Cancellable = FALSE CancelUnconfirmed = FALSE INVARIANT NeverRanAfterStop CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/native-command-lease/exec-unconfirmed-after-send.cfg b/tests/models/tla/native-command-lease/exec-unconfirmed-after-send.cfg index 005d45b0b8..9269ed95d6 100644 --- a/tests/models/tla/native-command-lease/exec-unconfirmed-after-send.cfg +++ b/tests/models/tla/native-command-lease/exec-unconfirmed-after-send.cfg @@ -1,4 +1,4 @@ SPECIFICATION Spec -CONSTANTS Bound = 35 SecondBound = 35 Probe = TRUE StopHold = 31 ExpiryUnconfirmed = FALSE Holders = 2 EnforceLease = TRUE +CONSTANTS Bound = 35 SecondBound = 35 Probe = TRUE StopHold = 31 ExpiryUnconfirmed = FALSE Holders = 2 EnforceLease = TRUE Cancellable = FALSE CancelUnconfirmed = FALSE INVARIANT NeverUnconfirmed CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/native-command-lease/honest-old-bound.cfg b/tests/models/tla/native-command-lease/honest-old-bound.cfg index 6632c22e47..84450e04c1 100644 --- a/tests/models/tla/native-command-lease/honest-old-bound.cfg +++ b/tests/models/tla/native-command-lease/honest-old-bound.cfg @@ -1,4 +1,4 @@ SPECIFICATION Spec -CONSTANTS Bound = 15 SecondBound = 15 Probe = TRUE StopHold = 31 ExpiryUnconfirmed = FALSE Holders = 1 EnforceLease = TRUE +CONSTANTS Bound = 15 SecondBound = 15 Probe = TRUE StopHold = 31 ExpiryUnconfirmed = FALSE Holders = 1 EnforceLease = TRUE Cancellable = FALSE CancelUnconfirmed = FALSE INVARIANT StopNeverRefuses CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/native-command-lease/old-exec-bound.cfg b/tests/models/tla/native-command-lease/old-exec-bound.cfg index bb76fb9404..9674f46a0d 100644 --- a/tests/models/tla/native-command-lease/old-exec-bound.cfg +++ b/tests/models/tla/native-command-lease/old-exec-bound.cfg @@ -1,4 +1,4 @@ SPECIFICATION Spec -CONSTANTS Bound = 15 SecondBound = 15 Probe = TRUE StopHold = 31 ExpiryUnconfirmed = TRUE Holders = 1 EnforceLease = TRUE +CONSTANTS Bound = 15 SecondBound = 15 Probe = TRUE StopHold = 31 ExpiryUnconfirmed = TRUE Holders = 1 EnforceLease = TRUE Cancellable = FALSE CancelUnconfirmed = FALSE INVARIANT UnconfirmedOnlyAfterSend CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/native-command-lease/send-while-held.cfg b/tests/models/tla/native-command-lease/send-while-held.cfg index 9c22b59bf9..08469d58c1 100644 --- a/tests/models/tla/native-command-lease/send-while-held.cfg +++ b/tests/models/tla/native-command-lease/send-while-held.cfg @@ -1,4 +1,4 @@ SPECIFICATION Spec -CONSTANTS Bound = 35 SecondBound = 35 Probe = TRUE StopHold = 31 ExpiryUnconfirmed = FALSE Holders = 2 EnforceLease = FALSE +CONSTANTS Bound = 35 SecondBound = 35 Probe = TRUE StopHold = 31 ExpiryUnconfirmed = FALSE Holders = 2 EnforceLease = FALSE Cancellable = FALSE CancelUnconfirmed = FALSE INVARIANT NoSendWhileHeld CHECK_DEADLOCK FALSE diff --git a/tests/native-authored-project-exec.test.ts b/tests/native-authored-project-exec.test.ts index 1440942cd1..24b40aa131 100644 --- a/tests/native-authored-project-exec.test.ts +++ b/tests/native-authored-project-exec.test.ts @@ -384,6 +384,37 @@ test("HACK-2739: an authored exec that waits for the lock prints exactly one pro ]); })); +test("HACK-2742: an owner check that ended the exec's wait (a pending signal or hack down) says nothing ran", async () => + owned("authored exec owner not started", async () => { + const f = await fixture(); + const refused = await nativeAuthoredProjectExec({ + ...f, + service: "web", + command, + invoke: async () => { + throw new NativeRuntimeRequestError({ + message: "refused", + nativeCode: "native_graph_foreground", + nativeCauseCode: "graph_authored_command_not_started", + }); + }, + }).catch((value: unknown) => value); + expect(isNativeCommandNotRun(refused)).toBe(true); + const failure = nativeAuthoredCommandFailure({ + error: refused, + operation: "exec", + }); + expect(failure.message.split("\n")).toEqual([ + "hack exec did not start: the project's owner stopped or changed while the command waited for the native runtime lock (graph_authored_command_not_started); nothing ran.", + "Check hack ps, then retry hack exec once the project is up.", + ]); + expect(failure.detail).toEqual({ + status: "not_run", + nativeCode: "native_graph_foreground", + nativeCauseCode: "graph_authored_command_not_started", + }); + })); + test.each([ { name: "the requester's own expired wait", diff --git a/tests/native-authored-project-oneoff.test.ts b/tests/native-authored-project-oneoff.test.ts index aad7ae801f..8b76ac6788 100644 --- a/tests/native-authored-project-oneoff.test.ts +++ b/tests/native-authored-project-oneoff.test.ts @@ -23,9 +23,23 @@ import { withNativeAuthoredProjectStatus, } from "../src/backends/native-authored-project-run.ts"; import { NativeAuthoredProjectNotStartedError } from "../src/backends/native-authored-runtime-binary.ts"; +import { + isNativeCommandNotRun, + NATIVE_AUTHORED_COMMAND_REQUEST_TIMEOUT_MS, + NATIVE_OWNER_AUTHORED_COMMAND_NOT_STARTED, + NATIVE_OWNER_AUTHORED_RUN_LEASE_BUSY, + nativeCommandLeaseWaitReporter, +} from "../src/backends/native-command-lease.ts"; import { NATIVE_RUN_EMPTY_SELECTION_REFUSAL } from "../src/backends/native-project-one-off.ts"; -import { invokeNativeRuntime } from "../src/backends/native-runtime-client.ts"; -import { tryNativeAuthoredCommand } from "../src/lib/native-authored-command.ts"; +import { + invokeNativeRuntime, + NativeRuntimeRequestError, +} from "../src/backends/native-runtime-client.ts"; +import { NATIVE_EXIT_CONFIRMED_ENV } from "../src/lib/background-command/native-exit.ts"; +import { + nativeAuthoredCommandFailure, + tryNativeAuthoredCommand, +} from "../src/lib/native-authored-command.ts"; import type { NativeComposeCommandOptions } from "../src/lib/native-compose-command.ts"; import { captureCompletedJobFixtureCommand } from "./e2e/scenarios/native-compose-adoption-job-worktrees.ts"; @@ -257,7 +271,13 @@ test("finite authored run preserves literal argv, binary streams and nonzero exi expect(input.privateInput).toBeUndefined(); expect(input.boundNativeAuthoredOneOffDrain).toBe(true); expect(input.boundNativeAuthoredExecDrain).toBeUndefined(); - expect(input.timeoutMs).toBe(45_000); + // HACK-2742: the requester's 35 s lease wait, 5 s send, 40 s read, margin; + // the same bound as the authored finite exec. + expect(input.timeoutMs).toBe( + NATIVE_AUTHORED_COMMAND_REQUEST_TIMEOUT_MS + ); + expect(input.timeoutMs).toBe(85_000); + expect(input.onLeaseWait).toBeFunction(); return f.reply; }, }); @@ -279,6 +299,163 @@ test("finite authored run preserves literal argv, binary streams and nonzero exi ).toEqual(result); })); +const PROJECT_STOP = + "Provider lease acquisition refused; recorded holder: project stop; no operation was admitted."; + +test("HACK-2742: an authored run that waits for the lock prints exactly one progress line", async () => + owned(async () => { + const f = await fixture(); + const lines: string[] = []; + const result = await nativeAuthoredProjectRun({ + ...f, + service: "web", + command, + workdir: "/app", + onLeaseWait: nativeCommandLeaseWaitReporter({ + write: (line) => lines.push(line), + }), + invoke: async (input) => { + input.onLeaseWait?.("project-stop"); + input.onLeaseWait?.("project-stop"); + return f.reply; + }, + }); + expect(result.exitCode).toBe(3); + expect(lines).toEqual([ + "Waiting for the native runtime lock, held by a project stop. This command continues once it is released (up to 35 s).", + ]); + })); + +test.each([ + { + name: "the requester's own expired wait", + error: () => + new NativeRuntimeRequestError({ + message: "busy", + nativeCode: "provider_busy", + nativeMessage: PROJECT_STOP, + }), + lines: [ + "hack run could not acquire the native runtime lock (provider_busy); nothing ran.", + "Holder: project stop.", + "Retry hack run once that project stop finishes.", + ], + detail: { status: "not_run", nativeCode: "provider_busy" }, + }, + { + name: "the owner's own expired wait", + error: () => + new NativeRuntimeRequestError({ + message: "refused", + nativeCode: "native_graph_foreground", + nativeCauseCode: NATIVE_OWNER_AUTHORED_RUN_LEASE_BUSY, + }), + lines: [ + "hack run could not acquire the native runtime lock (provider_busy); nothing ran.", + "Holder: unavailable.", + "Retry hack run once the holder finishes.", + ], + detail: { + status: "not_run", + nativeCode: "native_graph_foreground", + nativeCauseCode: NATIVE_OWNER_AUTHORED_RUN_LEASE_BUSY, + }, + }, + { + name: "the owner's check ending its wait (a pending signal or hack down)", + error: () => + new NativeRuntimeRequestError({ + message: "refused", + nativeCode: "native_graph_foreground", + nativeCauseCode: NATIVE_OWNER_AUTHORED_COMMAND_NOT_STARTED, + }), + lines: [ + "hack run did not start: the project's owner stopped or changed while the command waited for the native runtime lock (graph_authored_command_not_started); nothing ran.", + "Check hack ps, then retry hack run once the project is up.", + ], + detail: { + status: "not_run", + nativeCode: "native_graph_foreground", + nativeCauseCode: NATIVE_OWNER_AUTHORED_COMMAND_NOT_STARTED, + }, + }, +])("HACK-2742: $name is an honest run refusal that nothing ran, and releases the slot", async ({ + error, + lines, + detail, +}) => + owned(async () => { + const f = await fixture(); + const confirmed = join(f.scope.projectRoot, "exit-confirmed"); + const previous = process.env[NATIVE_EXIT_CONFIRMED_ENV]; + process.env[NATIVE_EXIT_CONFIRMED_ENV] = confirmed; + try { + const refused = await nativeAuthoredProjectRun({ + ...f, + service: "web", + command, + invoke: async () => { + throw error(); + }, + }).catch((value: unknown) => value); + expect(isNativeCommandNotRun(refused)).toBe(true); + const failure = nativeAuthoredCommandFailure({ + error: refused, + operation: "run", + }); + expect(failure.code).toBe("E_LIFECYCLE_FAILED"); + expect(failure.message).toBe(lines.join("\n")); + expect(failure.message).not.toContain("unconfirmed"); + expect(failure.detail).toEqual(detail); + expect(await Bun.file(confirmed).exists()).toBe(true); + } finally { + if (previous === undefined) { + delete process.env[NATIVE_EXIT_CONFIRMED_ENV]; + } else { + process.env[NATIVE_EXIT_CONFIRMED_ENV] = previous; + } + } + })); + +test.each([ + ["native_graph_foreground", "provider_busy"], + ["native_graph_foreground", "native_graph_foreground"], + ["native_graph_foreground", undefined], + ["engine_protocol", undefined], +] as const)("HACK-2742: any other run failure (%s caused by %s) stays unconfirmed and holds the slot", async (nativeCode, nativeCauseCode) => + owned(async () => { + const f = await fixture(); + const confirmed = join(f.scope.projectRoot, "exit-confirmed"); + const previous = process.env[NATIVE_EXIT_CONFIRMED_ENV]; + process.env[NATIVE_EXIT_CONFIRMED_ENV] = confirmed; + try { + const refused = await nativeAuthoredProjectRun({ + ...f, + service: "web", + command, + invoke: async () => { + throw new NativeRuntimeRequestError({ + message: "x", + nativeCode, + nativeCauseCode, + }); + }, + }).catch((value: unknown) => value); + expect(isNativeCommandNotRun(refused)).toBe(false); + expect( + nativeAuthoredCommandFailure({ error: refused, operation: "run" }) + .message + ).toContain("completion is unconfirmed"); + expect(await Bun.file(confirmed).exists()).toBe(false); + } finally { + if (previous === undefined) { + delete process.env[NATIVE_EXIT_CONFIRMED_ENV]; + } else { + process.env[NATIVE_EXIT_CONFIRMED_ENV] = previous; + } + } + })); + test.each([ false, true, diff --git a/tests/native-command-lease.test.ts b/tests/native-command-lease.test.ts index b9726c4f78..6f8512beaf 100644 --- a/tests/native-command-lease.test.ts +++ b/tests/native-command-lease.test.ts @@ -6,8 +6,11 @@ import { isNativeOwnerAuthoredExecLeaseRefusal, isNativeOwnerRefreshLeaseRefusal, NATIVE_COMMAND_LEASE_WAIT_SECONDS, + NATIVE_OWNER_AUTHORED_COMMAND_NOT_STARTED, NATIVE_OWNER_AUTHORED_EXEC_LEASE_BUSY, + NATIVE_OWNER_AUTHORED_RUN_LEASE_BUSY, NATIVE_OWNER_REFRESH_LEASE_BUSY, + nativeAuthoredCommandNotRunRefusal, nativeCommandLeaseRefusal, nativeCommandLeaseWaitLine, nativeCommandLeaseWaitReporter, @@ -179,6 +182,66 @@ test("HACK-2739: an authored exec's lease refusal says nothing ran, and only the ).toBe(false); }); +test("HACK-2742: only the authored owner's exact pre-effect causes are not-run refusals", () => { + for (const [cause, command, first] of [ + [ + NATIVE_OWNER_AUTHORED_RUN_LEASE_BUSY, + "hack run", + "hack run could not acquire the native runtime lock (provider_busy); nothing ran.", + ], + [ + NATIVE_OWNER_AUTHORED_EXEC_LEASE_BUSY, + "hack exec", + "hack exec could not acquire the native runtime lock (provider_busy); nothing ran.", + ], + [ + NATIVE_OWNER_AUTHORED_COMMAND_NOT_STARTED, + "hack run", + "hack run did not start: the project's owner stopped or changed while the command waited for the native runtime lock (graph_authored_command_not_started); nothing ran.", + ], + ] as const) { + const refusal = nativeAuthoredCommandNotRunRefusal( + new NativeRuntimeRequestError({ + message: "x", + nativeCode: "native_graph_foreground", + nativeCauseCode: cause, + }), + command + ); + expect(isNativeCommandNotRun(refusal)).toBe(true); + expect(refusal?.message.split("\n")[0]).toBe(first); + expect(refusal?.nativeCode).toBe("native_graph_foreground"); + expect(refusal?.nativeCauseCode).toBe(cause); + } + const raw = nativeAuthoredCommandNotRunRefusal( + new NativeRuntimeRequestError({ + message: "busy", + nativeCode: "provider_busy", + nativeMessage: PROJECT_STOP, + }), + "hack run" + ); + expect(raw?.message.split("\n")[1]).toBe("Holder: project stop."); + for (const [nativeCode, nativeCauseCode] of [ + ["native_graph_foreground", "provider_busy"], + ["native_graph_foreground", "native_graph_foreground"], + ["native_graph_foreground", undefined], + ["graph_owner_recovery", NATIVE_OWNER_AUTHORED_COMMAND_NOT_STARTED], + [NATIVE_OWNER_AUTHORED_COMMAND_NOT_STARTED, undefined], + ] as const) { + expect( + nativeAuthoredCommandNotRunRefusal( + new NativeRuntimeRequestError({ + message: "x", + nativeCode, + nativeCauseCode, + }), + "hack exec" + ) + ).toBeUndefined(); + } +}); + test("HACK-2739: the authored exec request outlasts the requester's wait and the owner's fixed read", () => { // Wait, 5 s to send, the fixed 40 s read of the owner's answer. expect(NATIVE_AUTHORED_EXEC_REQUEST_TIMEOUT_MS).toBeGreaterThanOrEqual( diff --git a/tests/native-interactive-exec.test.ts b/tests/native-interactive-exec.test.ts index ac9ac1a975..5608d855cc 100644 --- a/tests/native-interactive-exec.test.ts +++ b/tests/native-interactive-exec.test.ts @@ -4,6 +4,7 @@ import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { interactiveRefusalMessage, + parseInteractiveLeaseWaitEvent, parseInteractiveReport, } from "../src/backends/native-interactive-exec.ts"; import { nativeFailureMessage } from "../src/backends/native-runtime-client.ts"; @@ -38,6 +39,99 @@ test("an env change since up names the restart, not an uncertain outcome (HACK-2 "could not confirm admission or completion" ); }); +test("HACK-2742: an authored interactive exec refused before dispatch says nothing ran", () => { + const lease = parseInteractiveReport({ + version: 1, + outcome: "refused", + code: "provider_busy", + session: null, + holder: "project-stop", + }); + expect(lease).toEqual({ + code: 1, + retained: false, + failure: "provider_busy", + holder: "project-stop", + }); + expect( + interactiveRefusalMessage("provider_busy", { + native: true, + holder: lease.holder, + retained: lease.retained, + }).split("\n") + ).toEqual([ + "hack exec could not acquire the native runtime lock (provider_busy); nothing ran.", + "Holder: project stop.", + "Retry hack exec once that project stop finishes.", + ]); + expect( + interactiveRefusalMessage("graph_authored_exec_lease_busy", { + native: true, + }).split("\n") + ).toEqual([ + "hack exec could not acquire the native runtime lock (provider_busy); nothing ran.", + "Holder: unavailable.", + "Retry hack exec once the holder finishes.", + ]); + expect( + interactiveRefusalMessage("graph_authored_command_not_started", { + native: true, + }) + ).toContain("(graph_authored_command_not_started); nothing ran."); + // A Compose exec, or a refusal after its session existed, keeps the old line. + for (const context of [{ native: false }, { native: true, retained: true }]) { + expect(interactiveRefusalMessage("provider_busy", context)).toContain( + "could not confirm admission or completion" + ); + } + // The holder field is closed: only with provider_busy, only a token. + for (const bad of [ + { code: "graph_authored_exec_lease_busy", holder: "project-stop" }, + { code: "provider_busy", holder: "Project Stop" }, + { code: "provider_busy", holder: 7 }, + ]) { + expect(() => + parseInteractiveReport({ + version: 1, + outcome: "refused", + session: null, + ...bad, + }) + ).toThrow(); + } +}); +test("HACK-2742: only the closed lease-wait event line is an event", () => { + expect( + parseInteractiveLeaseWaitEvent( + JSON.stringify({ + version: 1, + event: "lease-wait", + holder: "project-stop", + }) + ) + ).toBe("project-stop"); + for (const line of [ + "", + "not json", + JSON.stringify({ version: 2, event: "lease-wait", holder: "start" }), + JSON.stringify({ version: 1, event: "other", holder: "start" }), + JSON.stringify({ version: 1, event: "lease-wait", holder: "x y" }), + JSON.stringify({ + version: 1, + event: "lease-wait", + holder: "start", + extra: 1, + }), + JSON.stringify({ + version: 1, + outcome: "refused", + code: "x", + session: null, + }), + ]) { + expect(parseInteractiveLeaseWaitEvent(line)).toBeUndefined(); + } +}); test("interactive report is closed, value-free and preserves command status", () => { expect( parseInteractiveReport({ @@ -154,7 +248,7 @@ test.skipIf(process.platform !== "linux" && process.platform !== "darwin")( expect(code, err + out).toBe(0); if (cmd[0] === python) { expect(out).toBe( - "Frontend PTY: nine lifetime and five selection cases passed\n" + "Frontend PTY: eleven lifetime and five selection cases passed\n" ); } } diff --git a/tests/native-runtime-client.test.ts b/tests/native-runtime-client.test.ts index 428123f50b..4dd8a7f0dd 100644 --- a/tests/native-runtime-client.test.ts +++ b/tests/native-runtime-client.test.ts @@ -197,6 +197,8 @@ if (process.argv.includes("plan-change-unsafe")) { console.error(JSON.stringify( if (process.argv.includes("structured")) { console.error(JSON.stringify({code:"source_conflict",message:"synthetic-secret-diagnostic"})); process.exit(23); } if (process.argv.includes("foreground-stopped")) { console.error(JSON.stringify({code:"native_graph_foreground",cause_code:"runtime_not_running",message:"synthetic-secret-diagnostic"})); process.exit(23); } if (process.argv.includes("foreground-other")) { console.error(JSON.stringify({code:"native_graph_foreground",cause_code:"engine_protocol",message:"synthetic-secret-diagnostic"})); process.exit(23); } +if (process.argv.includes("foreground-run-lease")) { console.error(JSON.stringify({code:"native_graph_foreground",cause_code:"graph_authored_run_lease_busy",message:"synthetic-secret-diagnostic"})); process.exit(23); } +if (process.argv.includes("foreground-not-started")) { console.error(JSON.stringify({code:"native_graph_foreground",cause_code:"graph_authored_command_not_started",message:"synthetic-secret-diagnostic"})); process.exit(23); } if (process.argv.includes("foreground-exec-lease")) { console.error(JSON.stringify({code:"native_graph_foreground",cause_code:"graph_authored_exec_lease_busy",message:"synthetic-secret-diagnostic"})); process.exit(23); } if (process.argv.includes("one-off-fail")) { console.error(JSON.stringify({code:"graph_one_off_failed",cause_code:"graph_one_off_cancelled",message:"synthetic-secret-diagnostic"})); process.exit(23); } if (process.argv.includes("one-off-unsafe")) { console.error(JSON.stringify({code:"graph_one_off_failed",cause_code:"synthetic-secret-diagnostic",message:"synthetic-secret-diagnostic"})); process.exit(23); } @@ -1267,6 +1269,17 @@ bunTest.each([ stopped: false, cause: "graph_authored_exec_lease_busy", }, + // HACK-2742: the owner's run lease and refused-check codes. + { + argument: "foreground-run-lease", + stopped: false, + cause: "graph_authored_run_lease_busy", + }, + { + argument: "foreground-not-started", + stopped: false, + cause: "graph_authored_command_not_started", + }, ])( "authored control failure preserves only its closed causes: $argument", async ({ argument, stopped, cause }) => { From 8b0bca629ca420c2360ef69ea1e317ac3f5d4d20 Mon Sep 17 00:00:00 2001 From: Dimitri Kennedy <344842+roodboi@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:36:09 -0500 Subject: [PATCH 02/11] fix(native): gate the interactive-only owner code lookup to macOS (HACK-2742) The Linux all-features test build compiles the authored exec module but not the macOS interactive requester that reads owner_pre_effect_code, so clippy reported it as dead code. Co-Authored-By: Claude Opus 5.5 --- .../runtime-core/src/provider/graph/native/runtime/exec.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/runtime-core/src/provider/graph/native/runtime/exec.rs b/packages/runtime-core/src/provider/graph/native/runtime/exec.rs index 893b84eda4..29207d3fea 100644 --- a/packages/runtime-core/src/provider/graph/native/runtime/exec.rs +++ b/packages/runtime-core/src/provider/graph/native/runtime/exec.rs @@ -86,7 +86,9 @@ pub(super) const OWNER_RUN_LEASE_BUSY: &str = "graph_authored_run_lease_busy"; /// "unconfirmed". pub(super) const OWNER_COMMAND_NOT_STARTED: &str = "graph_authored_command_not_started"; -/// The owner's pre-effect wait code that `code` names, if it is one. +/// The owner's pre-effect wait code that `code` names, if it is one. Only the +/// macOS interactive requester reads it. +#[cfg(target_os = "macos")] pub(in crate::provider::graph::native) fn owner_pre_effect_code( code: &str, ) -> Option<&'static str> { From 91a6a1b2e420e55106be7dd2b935e1586be8be78 Mon Sep 17 00:00:00 2001 From: Dimitri Kennedy <344842+roodboi@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:51:26 -0500 Subject: [PATCH 03/11] test(runtime-core): give the command-lease wait-out tests poll slack (HACK-2741) The authored exec requester test (HACK-2739) and its compose sibling in command_lease_tests held the lease for 600 ms against a 700 ms bound. The retry loop sleeps up to 50 ms and checks the deadline before each attempt, so on a hosted macOS runner the caller could give up just as the lock was freed (provider_busy after about 0.75 s on next). As in #1280, the hold stays and the positive case gets 500 ms of slack, ten capped poll intervals; the expiry case asserts its exact refusal only after its deadline has passed. Co-Authored-By: Claude Opus 5.5 --- .../provider/engine/command_lease_tests.rs | 32 ++++++++++++------- 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/packages/runtime-core/src/provider/engine/command_lease_tests.rs b/packages/runtime-core/src/provider/engine/command_lease_tests.rs index 45e3e5478f..91a0b3e664 100644 --- a/packages/runtime-core/src/provider/engine/command_lease_tests.rs +++ b/packages/runtime-core/src/provider/engine/command_lease_tests.rs @@ -348,10 +348,10 @@ fn the_requesting_side_of_exec_waits_as_long_as_a_start_and_the_owner_side_keeps assert_eq!(command_lease_deadline(now, near, COMMAND_LEASE_WAIT), near); } -/// HACK-2729, scaled 50 times (15 s is 300 ms, 35 s is 700 ms): a project stop holds -/// the lease for 600 ms. At the owner-side bound the wait refuses with the exact -/// project-stop refusal the CLI reads; the requesting side's bound outlasts the -/// stop and acquires right after it, before any check of its own. +/// HACK-2729, scaled (the owner's 15 s is 300 ms): a project stop holds the lease +/// for 600 ms. At the owner-side bound the wait refuses with the exact +/// project-stop refusal the CLI reads; the requesting side's longer bound +/// outlasts the stop and acquires right after it, before any check of its own. #[test] fn a_requested_command_waits_out_a_project_stop_that_the_owner_bound_refuses() { let (_home, candidate) = running_pool(); @@ -367,9 +367,11 @@ fn a_requested_command_waits_out_a_project_stop_that_the_owner_bound_refuses() { assert_eq!(refused.message, PROJECT_STOP_REFUSAL); assert!(started.elapsed() < hold); + // The backoff caps at 50 ms and is not scaled with the hold. Allow ten poll + // intervals for the holder to run, unlock and be observed on CI (HACK-2741). let after = Engine::connect_command_request( &candidate, - Instant::now() + Duration::from_millis(700), + started + hold + Duration::from_millis(500), &|| Ok(()), ) .err() @@ -401,11 +403,11 @@ fn a_requested_command_refuses_a_stop_past_its_bound_naming_it() { holder.join().unwrap(); } -/// HACK-2739, scaled 50 times (35 s is 700 ms): the requesting process of an -/// authored `hack exec` waits for a free lease before it sends anything to its -/// owner. It outlasts a project stop held for 600 ms, then returns, having -/// released the lease. It opens no engine connection, so unlike -/// `connect_command_request` it reaches no post-acquisition check. +/// HACK-2739: the requesting process of an authored `hack exec` waits for a free +/// lease before it sends anything to its owner. It outlasts a project stop held +/// for 600 ms, then returns, having released the lease. It opens no engine +/// connection, so unlike `connect_command_request` it reaches no +/// post-acquisition check. #[test] fn the_authored_exec_request_waits_out_a_project_stop_and_releases_the_lease() { use crate::provider::lifecycle::await_free_command_lease; @@ -413,7 +415,10 @@ fn the_authored_exec_request_waits_out_a_project_stop_and_releases_the_lease() { let hold = Duration::from_millis(600); let (_release, holder) = hold_lease_as_project_stop(&candidate, hold); let started = Instant::now(); - await_free_command_lease(&candidate, started + Duration::from_millis(700)).unwrap(); + // The backoff caps at 50 ms and is not scaled with the hold. Allow ten poll + // intervals for the holder to run, unlock and be observed on CI (HACK-2741). + let deadline = started + hold + Duration::from_millis(500); + await_free_command_lease(&candidate, deadline).unwrap(); assert!( started.elapsed() >= hold - Duration::from_millis(50), "returned before the stop released: {:?}", @@ -433,9 +438,12 @@ fn the_authored_exec_request_refuses_a_stop_past_its_bound_naming_it() { let (_home, candidate) = running_pool(); let (release, holder) = hold_lease_as_project_stop(&candidate, Duration::from_secs(30)); let started = Instant::now(); - let refused = await_free_command_lease(&candidate, started + Duration::from_millis(300)) + let deadline = started + Duration::from_millis(300); + let refused = await_free_command_lease(&candidate, deadline) .err() .unwrap(); + // The exact refusal is asserted only once the deadline has passed. + assert!(Instant::now() >= deadline); assert_eq!(refused.code, "provider_busy"); assert_eq!(refused.message, PROJECT_STOP_REFUSAL); assert!(refused.cause_code.is_none()); From 8c139fdcf385229efba05eb0b47f0c18d9ae59f4 Mon Sep 17 00:00:00 2001 From: Dimitri Kennedy <344842+roodboi@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:55:32 -0500 Subject: [PATCH 04/11] test(runtime-core): assert the exact lease refusal only after its deadline (HACK-2742) As in #1280 and #1286: the expiry cases this branch added (the interactive requester's checked wait and the owner's wait per command) now assert that their deadline passed before they check the exact refusal. Co-Authored-By: Claude Opus 5.5 --- .../src/provider/engine/command_lease_tests.rs | 13 ++++++------- .../provider/graph/native/runtime/exec_tests.rs | 14 ++++++-------- 2 files changed, 12 insertions(+), 15 deletions(-) diff --git a/packages/runtime-core/src/provider/engine/command_lease_tests.rs b/packages/runtime-core/src/provider/engine/command_lease_tests.rs index 41407adfa6..bab49943f6 100644 --- a/packages/runtime-core/src/provider/engine/command_lease_tests.rs +++ b/packages/runtime-core/src/provider/engine/command_lease_tests.rs @@ -507,13 +507,12 @@ fn a_refused_requester_check_ends_the_wait_with_its_own_error() { assert!(started.elapsed() >= Duration::from_millis(200)); assert!(started.elapsed() < Duration::from_secs(2)); // A check that passes leaves the bounded wait and its holder-named refusal. - let busy = await_free_command_lease_checked( - &candidate, - Instant::now() + Duration::from_millis(300), - &|| Ok(()), - ) - .err() - .unwrap(); + let deadline = Instant::now() + Duration::from_millis(300); + let busy = await_free_command_lease_checked(&candidate, deadline, &|| Ok(())) + .err() + .unwrap(); + // The exact refusal is asserted only once the deadline has passed (HACK-2741). + assert!(Instant::now() >= deadline); assert_eq!(busy.message, PROJECT_STOP_REFUSAL); // The interactive refusal report names that holder as its closed token. assert_eq!( diff --git a/packages/runtime-core/src/provider/graph/native/runtime/exec_tests.rs b/packages/runtime-core/src/provider/graph/native/runtime/exec_tests.rs index 15a3c3a147..f6f3c87a17 100644 --- a/packages/runtime-core/src/provider/graph/native/runtime/exec_tests.rs +++ b/packages/runtime-core/src/provider/graph/native/runtime/exec_tests.rs @@ -241,14 +241,12 @@ fn the_owners_lease_wait_expires_with_each_commands_pre_effect_code() { (exec::OwnerCommand::Exec, exec::OWNER_EXEC_LEASE_BUSY), (exec::OwnerCommand::Run, exec::OWNER_RUN_LEASE_BUSY), ] { - let refused = exec::owner_command_engine( - &candidate, - Instant::now() + Duration::from_millis(300), - &|| Ok(()), - command, - ) - .err() - .unwrap(); + let deadline = Instant::now() + Duration::from_millis(300); + let refused = exec::owner_command_engine(&candidate, deadline, &|| Ok(()), command) + .err() + .unwrap(); + // The exact refusal is asserted only once the deadline has passed (HACK-2741). + assert!(Instant::now() >= deadline); assert_eq!(refused.code, code); } release.send(()).unwrap(); From 73a1a6137f3b78b32421ff1d50ba8d623d343985 Mon Sep 17 00:00:00 2001 From: Dimitri Kennedy <344842+roodboi@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:47:59 -0500 Subject: [PATCH 05/11] fix(native): report an authored command whose owner left before the send as not started (HACK-2742) VM row 4: Y's own `hack down` ran while a Y `hack run` waited for the lease. After the wait, the requester found the owner's pin gone (Pin::load or pin.connect in request_selected, pin.connect in the interactive requester) and returned the plain refusal, which the CLI reported as "unconfirmed", although nothing had been sent. Every requester failure before the request is written now answers graph_authored_command_not_started: for finite exec and run as the cause of the native_graph_foreground refusal, for interactive exec as the report code. Status, observe, logs and cleanup keep their refusals. A failure after the write, including an owner that accepted and then exited, keeps "unconfirmed". The CLI's not-started line now says the owner stopped or changed before the command was sent or started. Review L4: the call sites go through owner_exec_engine and run::owner_engine, and tests check that each passes its own command; the interactive requester's forwarding of owner codes is a tested function. Co-Authored-By: Claude Opus 5.5 --- docs/guides/native-candidate.md | 2 +- .../provider/engine/command_lease_tests.rs | 14 +++ .../src/provider/graph/native/foreground.rs | 70 ++++++++++++--- .../provider/graph/native/foreground/tests.rs | 85 +++++++++++++++++++ .../src/provider/graph/native/runtime.rs | 2 +- .../src/provider/graph/native/runtime/exec.rs | 18 +++- .../graph/native/runtime/exec_tests.rs | 27 ++++++ .../src/provider/graph/native/runtime/run.rs | 12 ++- src/backends/native-command-lease.ts | 6 +- tests/native-authored-project-exec.test.ts | 2 +- tests/native-authored-project-oneoff.test.ts | 2 +- tests/native-command-lease.test.ts | 2 +- 12 files changed, 218 insertions(+), 24 deletions(-) diff --git a/docs/guides/native-candidate.md b/docs/guides/native-candidate.md index 27826e0254..6803f95c53 100644 --- a/docs/guides/native-candidate.md +++ b/docs/guides/native-candidate.md @@ -5468,7 +5468,7 @@ and the command says `nothing ran` with `Holder: unavailable.` and `Retry hack e once the holder finishes.` A pending Ctrl-C of the owner, its `hack down`, or a changed owner publication ends the owner's wait at once; the owner then answers `graph_authored_command_not_started`, and the command says it did not start, that -nothing ran, and to check `hack ps` and retry once the project is up. Any other +nothing ran, and to check `hack ps` and retry once the project is up. The command says the same when the owner exits while the command is still waiting for the lock, for example during the project's own `hack down`: nothing has been sent at that point. A failure after the request is sent keeps "unconfirmed". Any other authored failure keeps its report, "completion is unconfirmed" included. A compose project's one-off `run` is answered by its owner, which waits at most 15 seconds on its only loop, within one 15-second bound for its selection and admission before its diff --git a/packages/runtime-core/src/provider/engine/command_lease_tests.rs b/packages/runtime-core/src/provider/engine/command_lease_tests.rs index bab49943f6..636690606f 100644 --- a/packages/runtime-core/src/provider/engine/command_lease_tests.rs +++ b/packages/runtime-core/src/provider/engine/command_lease_tests.rs @@ -553,6 +553,13 @@ fn the_authored_run_requester_waits_before_it_contacts_the_owner() { after.code ); assert_ne!(after.code, "provider_busy", "{}", after.message); + // HACK-2742 review: no owner pin, so nothing was sent; the CLI reads this pair + // as "did not start, nothing ran". + assert_eq!(after.code, "native_graph_foreground", "{}", after.message); + assert_eq!( + after.cause_code.as_deref(), + Some("graph_authored_command_not_started") + ); holder.join().unwrap(); } @@ -583,5 +590,12 @@ fn the_authored_exec_requester_waits_before_it_contacts_the_owner() { after.code ); assert_ne!(after.code, "provider_busy", "{}", after.message); + // HACK-2742 review: no owner pin, so nothing was sent; the CLI reads this pair + // as "did not start, nothing ran". + assert_eq!(after.code, "native_graph_foreground", "{}", after.message); + assert_eq!( + after.cause_code.as_deref(), + Some("graph_authored_command_not_started") + ); holder.join().unwrap(); } diff --git a/packages/runtime-core/src/provider/graph/native/foreground.rs b/packages/runtime-core/src/provider/graph/native/foreground.rs index b70fdaef71..cf61827ec7 100644 --- a/packages/runtime-core/src/provider/graph/native/foreground.rs +++ b/packages/runtime-core/src/provider/graph/native/foreground.rs @@ -22,6 +22,37 @@ fn refused() -> CandidateError { "Native foreground ownership is changed, unavailable or uncertain; its exact evidence was preserved. Use tagged native control for a live owner; no recovery or replay was attempted.", ) } +/// A finite command's requester failed before it wrote its request (HACK-2742 +/// review): nothing was sent, so nothing ran. It reaches the CLI as the owner's +/// not-started code under this module's refusal, as the owner's own refusal +/// does. Failures after the write keep their codes ("unconfirmed"). +fn command_not_sent(_error: CandidateError) -> CandidateError { + refused().with_cause_code(runtime::OWNER_COMMAND_NOT_STARTED.to_owned()) +} + +/// [`command_not_sent`] for an interactive exec, whose value-free report +/// carries one code, so the owner's not-started code is that code. +fn interactive_not_sent(_error: CandidateError) -> CandidateError { + CandidateError::new( + runtime::OWNER_COMMAND_NOT_STARTED, + "The interactive exec was not sent to its owner; nothing ran.", + ) +} + +/// The requester's answer for an owner's pre-intent `Refused { code }` of an +/// interactive exec. The owner's pre-effect wait codes keep their own code, +/// because the interactive report carries only one code and the CLI reads it +/// as "nothing ran" (HACK-2742). Every other code is wrapped as before. +fn interactive_owner_refusal(code: String) -> CandidateError { + match runtime::owner_pre_effect_code(&code) { + Some(known) => CandidateError::new( + known, + "The owner refused the interactive exec before it started; nothing ran.", + ), + None => refused().with_cause_code(code), + } +} + /// Whether the run's foreground owner process is still running (see `owner::holds_lock`). pub(in crate::provider) fn owner_running(candidate: &Candidate, run: &str) -> Option { owner::holds_lock(candidate, run) @@ -694,16 +725,18 @@ pub(in crate::provider) fn interactive( if !selected.valid() { return Err(refused()); } - let pin = owner::Pin::load(candidate, run)?; + // Everything before the request is written is pre-send: a pin or owner that + // is gone or changed answers the owner's not-started code (HACK-2742 review). + let pin = owner::Pin::load(candidate, run).map_err(interactive_not_sent)?; let review = pin.review(); - let expected = journal::read_control(candidate, review)?; + let expected = journal::read_control(candidate, review).map_err(interactive_not_sent)?; if ( expected.owner.as_str(), review.review_id(), review.scope().namespace, ) != pins { - return Err(refused()); + return Err(interactive_not_sent(refused())); } // HACK-2742: wait out another project's stop before anything is sent, as a // finite exec does (HACK-2739). The frontend's leash ends the wait. A @@ -714,8 +747,10 @@ pub(in crate::provider) fn interactive( Instant::now() + crate::provider::lifecycle::COMMAND_REQUEST_LEASE_WAIT, &|| leash.check(), )?; - let mut stream = pin.connect()?; - let _lifetime = leash.watch_control(&stream)?; + // The owner may have exited during that wait (its own `hack down`): its pin + // no longer connects, and nothing was sent. + let mut stream = pin.connect().map_err(interactive_not_sent)?; + let _lifetime = leash.watch_control(&stream).map_err(interactive_not_sent)?; let input = Request { version: 2, kind: RequestKind::NativeGraphControl, @@ -760,11 +795,7 @@ pub(in crate::provider) fn interactive( result.map_err(|_: CandidateError| CandidateError::new("session_cleanup_uncertain", "Interactive session handoff changed; the session was retained and no start was replayed.").with_session(&session.session)) } Outcome::InteractiveRefused { session } if session == options.session => Err(CandidateError::new("session_cleanup_uncertain", "Interactive admission ended after its durable intent; the session was retained and no start was replayed.").with_session(&session)), - // HACK-2742: the owner's pre-effect wait refusals keep their own code, - // because the interactive report carries only one code and the CLI - // reads it as "nothing ran". Every other pre-intent refusal is wrapped. - Outcome::Refused { code, .. } if descriptor.is_none() && runtime::owner_pre_effect_code(&code).is_some() => Err(CandidateError::new(runtime::owner_pre_effect_code(&code).ok_or_else(refused)?, "The owner refused the interactive exec before it started; nothing ran.")), - Outcome::Refused { code, .. } if descriptor.is_none() => Err(refused().with_cause_code(code)), + Outcome::Refused { code, .. } if descriptor.is_none() => Err(interactive_owner_refusal(code)), _ => Err(uncertain(refused())), } } @@ -776,10 +807,23 @@ fn request_selected( exec_selected: Option, one_off_selected: Option, ) -> Result { - let pin = owner::Pin::load(candidate, run)?; + // For a command (exec, one-off run), every failure before the request is + // written is pre-send. The owner may have exited while the requester waited + // for the lease (its own `hack down`, HACK-2742 review): its pin is gone or no + // longer connects. Those answer the owner's not-started code so the CLI says + // nothing ran. Status, observe, logs and cleanup keep their own refusals. + let command = matches!(action, Action::Exec | Action::Run); + let not_sent = |error: CandidateError| { + if command { + command_not_sent(error) + } else { + error + } + }; + let pin = owner::Pin::load(candidate, run).map_err(not_sent)?; let review = pin.review(); - let expected = journal::read_control(candidate, review)?; - let mut stream = pin.connect()?; + let expected = journal::read_control(candidate, review).map_err(not_sent)?; + let mut stream = pin.connect().map_err(not_sent)?; let input = Request { version: 2, kind: RequestKind::NativeGraphControl, diff --git a/packages/runtime-core/src/provider/graph/native/foreground/tests.rs b/packages/runtime-core/src/provider/graph/native/foreground/tests.rs index 253077ad76..b7a184d0f4 100644 --- a/packages/runtime-core/src/provider/graph/native/foreground/tests.rs +++ b/packages/runtime-core/src/provider/graph/native/foreground/tests.rs @@ -1614,3 +1614,88 @@ fn presentation_observation_never_satisfies_readiness_status() { .is_err() ); } + +/// HACK-2742 review (L4): the interactive requester forwards the owner's +/// pre-effect wait codes as their own code, because the interactive report +/// carries only one code; every other owner refusal is wrapped as before. +#[test] +fn the_interactive_requester_forwards_only_the_owners_pre_effect_codes() { + for code in [ + "graph_authored_exec_lease_busy", + "graph_authored_run_lease_busy", + "graph_authored_command_not_started", + ] { + let forwarded = interactive_owner_refusal(code.to_owned()); + assert_eq!(forwarded.code, code); + assert!(forwarded.cause_code.is_none()); + assert!(forwarded.session().is_none()); + } + for code in [ + "provider_busy", + "engine_protocol", + "native_graph_foreground", + ] { + let wrapped = interactive_owner_refusal(code.to_owned()); + assert_eq!(wrapped.code, "native_graph_foreground"); + assert_eq!(wrapped.cause_code.as_deref(), Some(code)); + } +} + +/// HACK-2742 review (VM row 4): the owner exited while the requester waited for +/// the lease (its own `hack down`), so its pin is gone. Every requester failure +/// before the request is written answers the not-started code: for finite exec +/// and run as the cause of this module's refusal, for interactive exec as the +/// report code with no session. Nothing was sent. Status and logs keep theirs. +#[test] +fn a_requester_whose_owner_is_gone_before_the_write_answers_not_started() { + use crate::provider::{graph::interactive_exec::Options, interactive_terminal::Leash}; + use std::os::unix::net::UnixStream; + + let fixture = Fixture::new(); + let receipt = fixture.receipt(); + // No publication: the owner's pin does not exist. + for result in [ + exec(&fixture.candidate, RUN, "web", &["true".into()], None), + one_off(&fixture.candidate, RUN, "web", &["true".into()], None), + ] { + let error = result.err().unwrap(); + assert_eq!(error.code, "native_graph_foreground", "{}", error.message); + assert_eq!( + error.cause_code.as_deref(), + Some("graph_authored_command_not_started") + ); + } + let status = request( + &fixture.candidate, + RequestOptions { + run: RUN, + action: Action::Status, + }, + ) + .err() + .unwrap(); + assert!(status.cause_code.is_none(), "{}", status.code); + + let (input, mut frontend) = UnixStream::pair().unwrap(); + frontend.write_all(&[0; 4]).unwrap(); + let (leash, _) = Leash::receive(input.into()).unwrap(); + let argv = vec!["tool".into()]; + let options = Options { + session: "12345678-abcd-abcd-abcd-123456789abc", + run: RUN, + service: "web", + owner: &receipt.owner, + plan: receipt.review.review_id(), + namespace: receipt.review.scope().namespace, + native: true, + argv: &argv, + workdir: None, + expected_container: None, + expected_generation: None, + }; + let error = interactive(&fixture.candidate, &options, [43, 91], &leash) + .err() + .unwrap(); + assert_eq!(error.code, "graph_authored_command_not_started"); + assert!(error.session().is_none()); +} diff --git a/packages/runtime-core/src/provider/graph/native/runtime.rs b/packages/runtime-core/src/provider/graph/native/runtime.rs index 4221f05b08..a595a901c4 100644 --- a/packages/runtime-core/src/provider/graph/native/runtime.rs +++ b/packages/runtime-core/src/provider/graph/native/runtime.rs @@ -14,7 +14,7 @@ pub(super) use exec::execute as service_exec; #[cfg(target_os = "macos")] pub(super) use exec::interactive as interactive_exec; #[cfg(target_os = "macos")] -pub(super) use exec::owner_pre_effect_code; +pub(super) use exec::{OWNER_COMMAND_NOT_STARTED, owner_pre_effect_code}; #[cfg(any(target_os = "macos", test))] mod run; #[cfg(target_os = "macos")] diff --git a/packages/runtime-core/src/provider/graph/native/runtime/exec.rs b/packages/runtime-core/src/provider/graph/native/runtime/exec.rs index 29207d3fea..7f1b8caadf 100644 --- a/packages/runtime-core/src/provider/graph/native/runtime/exec.rs +++ b/packages/runtime-core/src/provider/graph/native/runtime/exec.rs @@ -84,7 +84,8 @@ pub(super) const OWNER_RUN_LEASE_BUSY: &str = "graph_authored_run_lease_busy"; /// the wait and before every lease attempt, so nothing was read, touched or /// started. Without this code the owner's plain `refused()` reached the CLI as /// "unconfirmed". -pub(super) const OWNER_COMMAND_NOT_STARTED: &str = "graph_authored_command_not_started"; +pub(in crate::provider::graph::native) const OWNER_COMMAND_NOT_STARTED: &str = + "graph_authored_command_not_started"; /// The owner's pre-effect wait code that `code` names, if it is one. Only the /// macOS interactive requester reads it. @@ -159,6 +160,17 @@ pub(super) fn owner_command_engine<'a>( .map_err(|error| owner_wait_refusal(error, guard_refused.get(), command)) } +/// The owner's guard and lease wait for a finite or interactive exec, with the +/// exec's own lease code. +#[cfg(target_os = "macos")] +pub(super) fn owner_exec_engine<'a>( + candidate: &'a Candidate, + deadline: Instant, + guard: &dyn Fn() -> Result<(), CandidateError>, +) -> Result, CandidateError> { + owner_command_engine(candidate, deadline, guard, OwnerCommand::Exec) +} + #[cfg(target_os = "macos")] pub(in crate::provider::graph::native) fn execute( candidate: &Candidate, @@ -174,7 +186,7 @@ pub(in crate::provider::graph::native) fn execute( // attempt, and the wait counts against this 30 s budget (HACK-2669). The // requester already waited out a longer holder before it sent this // (HACK-2739), so this wait only covers a holder that took the lease since. - let engine = owner_command_engine(candidate, deadline, guard, OwnerCommand::Exec)?; + let engine = owner_exec_engine(candidate, deadline, guard)?; let (receipt, _) = journal::load( candidate, expected.review.scope().run, @@ -286,7 +298,7 @@ pub(in crate::provider::graph::native) fn interactive( // before every lease attempt, and the wait counts against this 30 s budget // (HACK-2669). Its failures are pre-intent: no session receipt exists yet, // so they carry their own codes (HACK-2742). - let engine = owner_command_engine(candidate, deadline, guard, OwnerCommand::Exec)?; + let engine = owner_exec_engine(candidate, deadline, guard)?; let (receipt, _) = journal::load( candidate, expected.review.scope().run, diff --git a/packages/runtime-core/src/provider/graph/native/runtime/exec_tests.rs b/packages/runtime-core/src/provider/graph/native/runtime/exec_tests.rs index f6f3c87a17..fe5ee19996 100644 --- a/packages/runtime-core/src/provider/graph/native/runtime/exec_tests.rs +++ b/packages/runtime-core/src/provider/graph/native/runtime/exec_tests.rs @@ -249,6 +249,33 @@ fn the_owners_lease_wait_expires_with_each_commands_pre_effect_code() { assert!(Instant::now() >= deadline); assert_eq!(refused.code, code); } + // HACK-2742 review (L4): each call site passes its own command. `exec::execute` + // and `exec::interactive` go through `owner_exec_engine`; `run::execute` goes + // through `run::owner_engine`. + for (code, refused) in [ + ( + exec::OWNER_EXEC_LEASE_BUSY, + exec::owner_exec_engine( + &candidate, + Instant::now() + Duration::from_millis(300), + &|| Ok(()), + ) + .err() + .unwrap(), + ), + ( + exec::OWNER_RUN_LEASE_BUSY, + run::owner_engine( + &candidate, + Instant::now() + Duration::from_millis(300), + &|| Ok(()), + ) + .err() + .unwrap(), + ), + ] { + assert_eq!(refused.code, code); + } release.send(()).unwrap(); holder.join().unwrap(); } diff --git a/packages/runtime-core/src/provider/graph/native/runtime/run.rs b/packages/runtime-core/src/provider/graph/native/runtime/run.rs index 2ecf1365c1..fd5a15ad68 100644 --- a/packages/runtime-core/src/provider/graph/native/runtime/run.rs +++ b/packages/runtime-core/src/provider/graph/native/runtime/run.rs @@ -283,6 +283,16 @@ fn one_off_config( Ok(config) } +/// The owner's guard and lease wait for a one-off, with the run's own lease code. +#[cfg(target_os = "macos")] +pub(super) fn owner_engine<'a>( + candidate: &'a Candidate, + deadline: Instant, + guard: &dyn Fn() -> Result<(), CandidateError>, +) -> Result, CandidateError> { + exec::owner_command_engine(candidate, deadline, guard, exec::OwnerCommand::Run) +} + #[cfg(target_os = "macos")] pub(in crate::provider::graph::native) fn execute( candidate: &Candidate, @@ -298,7 +308,7 @@ pub(in crate::provider::graph::native) fn execute( // attempt, and the wait counts against this 30 s budget (HACK-2669). The // requester waited out a longer holder before it sent this, and the wait's // failures carry pre-effect codes (HACK-2742): no record or container exists yet. - let engine = exec::owner_command_engine(candidate, deadline, guard, exec::OwnerCommand::Run)?; + let engine = owner_engine(candidate, deadline, guard)?; let (receipt, root) = journal::load( candidate, expected.review.scope().run, diff --git a/src/backends/native-command-lease.ts b/src/backends/native-command-lease.ts index b2f9de2930..d4fcefb30d 100644 --- a/src/backends/native-command-lease.ts +++ b/src/backends/native-command-lease.ts @@ -218,7 +218,9 @@ export const NATIVE_OWNER_AUTHORED_RUN_LEASE_BUSY = /** * The authored owner's answer when its own check (a pending signal, its * `hack down`, a changed publication or pin) ended an exec or run before it - * took the lease (`OWNER_COMMAND_NOT_STARTED`, HACK-2742). Nothing ran. + * took the lease (`OWNER_COMMAND_NOT_STARTED`, HACK-2742). The requester gives + * the same code when it failed before it wrote its request, for example because + * the owner exited during the requester's lease wait (VM row 4). Nothing ran. */ export const NATIVE_OWNER_AUTHORED_COMMAND_NOT_STARTED = "graph_authored_command_not_started"; @@ -233,7 +235,7 @@ export function nativeCommandNotStartedMessage( command: NativeLeaseCommand ): string { return [ - `${command} did not start: the project's owner stopped or changed while the command waited for the native runtime lock (${NATIVE_OWNER_AUTHORED_COMMAND_NOT_STARTED}); nothing ran.`, + `${command} did not start: the project's owner stopped or changed before the command was sent or started (${NATIVE_OWNER_AUTHORED_COMMAND_NOT_STARTED}); nothing ran.`, `Check hack ps, then retry ${command} once the project is up.`, ].join("\n"); } diff --git a/tests/native-authored-project-exec.test.ts b/tests/native-authored-project-exec.test.ts index 24b40aa131..2c59dcfa7b 100644 --- a/tests/native-authored-project-exec.test.ts +++ b/tests/native-authored-project-exec.test.ts @@ -405,7 +405,7 @@ test("HACK-2742: an owner check that ended the exec's wait (a pending signal or operation: "exec", }); expect(failure.message.split("\n")).toEqual([ - "hack exec did not start: the project's owner stopped or changed while the command waited for the native runtime lock (graph_authored_command_not_started); nothing ran.", + "hack exec did not start: the project's owner stopped or changed before the command was sent or started (graph_authored_command_not_started); nothing ran.", "Check hack ps, then retry hack exec once the project is up.", ]); expect(failure.detail).toEqual({ diff --git a/tests/native-authored-project-oneoff.test.ts b/tests/native-authored-project-oneoff.test.ts index 8b76ac6788..f39666b506 100644 --- a/tests/native-authored-project-oneoff.test.ts +++ b/tests/native-authored-project-oneoff.test.ts @@ -370,7 +370,7 @@ test.each([ nativeCauseCode: NATIVE_OWNER_AUTHORED_COMMAND_NOT_STARTED, }), lines: [ - "hack run did not start: the project's owner stopped or changed while the command waited for the native runtime lock (graph_authored_command_not_started); nothing ran.", + "hack run did not start: the project's owner stopped or changed before the command was sent or started (graph_authored_command_not_started); nothing ran.", "Check hack ps, then retry hack run once the project is up.", ], detail: { diff --git a/tests/native-command-lease.test.ts b/tests/native-command-lease.test.ts index 6f8512beaf..541faa26b4 100644 --- a/tests/native-command-lease.test.ts +++ b/tests/native-command-lease.test.ts @@ -197,7 +197,7 @@ test("HACK-2742: only the authored owner's exact pre-effect causes are not-run r [ NATIVE_OWNER_AUTHORED_COMMAND_NOT_STARTED, "hack run", - "hack run did not start: the project's owner stopped or changed while the command waited for the native runtime lock (graph_authored_command_not_started); nothing ran.", + "hack run did not start: the project's owner stopped or changed before the command was sent or started (graph_authored_command_not_started); nothing ran.", ], ] as const) { const refusal = nativeAuthoredCommandNotRunRefusal( From 6fb7d9bab25a91a9a0ca5640bce5b389cded726e Mon Sep 17 00:00:00 2001 From: Dimitri Kennedy <344842+roodboi@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:27:46 -0500 Subject: [PATCH 06/11] fix(native): prove an authored request the ending owner never took (HACK-2742) VM row 4, later rounds: the requester connected while Y's owner was busy in its own `hack down` cleanup, so its request sat in the listen backlog. The owner then saved its run as removed, retired its publication and exited without accepting it. The requester's read (or write) failed after the send, and the CLI said "unconfirmed" (run) or "could not confirm admission" (interactive), although nothing ran. The owner serves one request at a time and answers each before it takes the next, and it leaves its loop only through a cleanup that saves the run as removed and then retires its publication. So a connection the owner closed without a single byte of answer, followed by that retirement and a removed run, was never processed. The finite requester now peeks for the first byte (consuming nothing) and the interactive handoff tells a close with nothing received apart; with that owner evidence both answer graph_authored_command_not_started. An owner that is still published, or that sent any part of an answer, keeps "unconfirmed". Tests reproduce the row deterministically: a requester left in the backlog of an owner that ends through cleanup (finite exec, run and interactive), plus a stale pin with a dead socket, an owner that read the request and dropped it while still published, and a partial answer. Co-Authored-By: Claude Opus 5.5 --- docs/guides/native-candidate.md | 2 +- .../src/provider/graph/native/foreground.rs | 131 +++++++++++++-- .../provider/graph/native/foreground/tests.rs | 153 ++++++++++++++++++ .../src/provider/interactive_handoff.rs | 28 +++- 4 files changed, 303 insertions(+), 11 deletions(-) diff --git a/docs/guides/native-candidate.md b/docs/guides/native-candidate.md index 6803f95c53..31d1974e43 100644 --- a/docs/guides/native-candidate.md +++ b/docs/guides/native-candidate.md @@ -5468,7 +5468,7 @@ and the command says `nothing ran` with `Holder: unavailable.` and `Retry hack e once the holder finishes.` A pending Ctrl-C of the owner, its `hack down`, or a changed owner publication ends the owner's wait at once; the owner then answers `graph_authored_command_not_started`, and the command says it did not start, that -nothing ran, and to check `hack ps` and retry once the project is up. The command says the same when the owner exits while the command is still waiting for the lock, for example during the project's own `hack down`: nothing has been sent at that point. A failure after the request is sent keeps "unconfirmed". Any other +nothing ran, and to check `hack ps` and retry once the project is up. The command says the same when the owner exits while the command is still waiting for the lock, for example during the project's own `hack down`: nothing has been sent at that point. It also says the same when the request reached the owner's queue but the owner ended through that `hack down` without taking it: the owner closed the connection without a byte of answer, retired its publication and saved its run as removed, which proves it never processed the request. Every other failure after the request is sent keeps "unconfirmed". Any other authored failure keeps its report, "completion is unconfirmed" included. A compose project's one-off `run` is answered by its owner, which waits at most 15 seconds on its only loop, within one 15-second bound for its selection and admission before its diff --git a/packages/runtime-core/src/provider/graph/native/foreground.rs b/packages/runtime-core/src/provider/graph/native/foreground.rs index cf61827ec7..6756320c50 100644 --- a/packages/runtime-core/src/provider/graph/native/foreground.rs +++ b/packages/runtime-core/src/provider/graph/native/foreground.rs @@ -30,6 +30,85 @@ fn command_not_sent(_error: CandidateError) -> CandidateError { refused().with_cause_code(runtime::OWNER_COMMAND_NOT_STARTED.to_owned()) } +/// Whether the owner closed `stream` before it sent a single byte of its answer +/// (HACK-2742 review). Waits until `deadline` for the first byte or the close, +/// and consumes nothing: a peeked byte is left for the reply reader. A timeout +/// or any other error is not a proof and answers false. +fn closed_unanswered(stream: &std::os::unix::net::UnixStream, deadline: Instant) -> bool { + use std::os::fd::AsRawFd; + loop { + let remaining = deadline.saturating_duration_since(Instant::now()); + let mut descriptor = libc::pollfd { + fd: stream.as_raw_fd(), + events: libc::POLLIN, + revents: 0, + }; + let timeout = i32::try_from(remaining.as_millis()).unwrap_or(i32::MAX); + // SAFETY: one valid pollfd for a descriptor the stream owns. + let ready = unsafe { libc::poll(&mut descriptor, 1, timeout) }; + if ready < 0 { + if std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted { + continue; + } + return false; + } + if ready == 0 { + return false; + } + let mut byte = [0_u8; 1]; + // SAFETY: one writable byte; MSG_PEEK leaves it queued for the reader. + let count = unsafe { + libc::recv( + stream.as_raw_fd(), + byte.as_mut_ptr().cast(), + 1, + libc::MSG_PEEK | libc::MSG_DONTWAIT, + ) + }; + if count == 0 { + return true; + } + if count > 0 { + return false; + } + match std::io::Error::last_os_error().raw_os_error() { + Some(libc::ECONNRESET | libc::ENOTCONN | libc::EPIPE) => return true, + Some(libc::EAGAIN | libc::EINTR) => continue, + _ => return false, + } + } +} + +/// Whether the owner ended through its normal cleanup and so never processed a +/// request it left unanswered (HACK-2742 review). The owner serves one request +/// at a time on its only loop and writes each answer before it accepts the +/// next. It returns from that loop only after a cleanup, which saves the run as +/// removed and then retires its publication. A connection it closed without a +/// byte of answer, followed by that retirement, was therefore never processed: +/// it was still in the listen backlog, or its request never fully arrived. An +/// owner that failed instead keeps its publication, so this answers false. The +/// retirement is awaited briefly, because the connection can close as the +/// process exits a moment after its files are removed. +fn owner_ended_unanswered( + candidate: &Candidate, + pin: &owner::Pin, + review: &native_input::Review, +) -> bool { + let deadline = Instant::now() + Duration::from_secs(2); + loop { + if pin.verify_retired().is_ok() + && journal::read_control(candidate, review) + .is_ok_and(|receipt| receipt.phase == Phase::Removed) + { + return true; + } + if Instant::now() >= deadline { + return false; + } + std::thread::sleep(Duration::from_millis(20)); + } +} + /// [`command_not_sent`] for an interactive exec, whose value-free report /// carries one code, so the owner's not-started code is that code. fn interactive_not_sent(_error: CandidateError) -> CandidateError { @@ -767,12 +846,29 @@ pub(in crate::provider) fn interactive( // the owner stopped before its durable intent. Correlate only this attempt; // a validated pre-intent refusal below remains unscoped. let uncertain = |error: CandidateError| error.with_session(options.session); - transport::write(&mut stream, &input, Duration::from_secs(5)).map_err(uncertain)?; + // HACK-2742 review (VM row 4): an owner that never accepted this connection + // and then ended through its cleanup closes it unanswered. Only then, with + // the owner's own retirement and removed run as evidence, is the attempt + // proven unprocessed and reported with no session. + let unanswered = |error: CandidateError| { + if owner_ended_unanswered(candidate, &pin, review) { + interactive_not_sent(error) + } else { + uncertain(error) + } + }; + transport::write(&mut stream, &input, Duration::from_secs(5)).map_err(unanswered)?; let descriptor = crate::provider::interactive_handoff::receive( &stream, std::time::Instant::now() + Duration::from_secs(40), ) - .map_err(uncertain)?; + .map_err(|error| { + if error.code == crate::provider::interactive_handoff::CLOSED_UNANSWERED { + unanswered(error) + } else { + uncertain(error) + } + })?; let reply: Reply = transport::read(&mut stream, Duration::from_secs(5), LIMIT).map_err(uncertain)?; reply @@ -836,15 +932,32 @@ fn request_selected( exec: exec_selected.clone(), one_off: one_off_selected.clone(), }; - transport::write(&mut stream, &input, Duration::from_secs(5))?; - let command = matches!(action, Action::Exec | Action::Run); + // HACK-2742 review (VM row 4, later rounds): the owner may have taken this + // connection into its listen backlog and then exited through its cleanup + // without ever accepting it. The write, or the first read, then fails with + // nothing answered. For a command that is proven unprocessed only when the + // owner closed the connection without a single byte of answer and then + // retired its publication with its run removed (`owner_ended_unanswered`). + let unanswered = |error: CandidateError| { + if command && owner_ended_unanswered(candidate, &pin, review) { + command_not_sent(error) + } else { + error + } + }; + transport::write(&mut stream, &input, Duration::from_secs(5)).map_err(unanswered)?; + let budget = if command { + Duration::from_secs(40) + } else { + Duration::from_secs(30) + }; + let started = Instant::now(); + if command && closed_unanswered(&stream, started + budget) { + return Err(unanswered(refused())); + } let reply: Reply = transport::read( &mut stream, - if command { - Duration::from_secs(40) - } else { - Duration::from_secs(30) - }, + budget.saturating_sub(started.elapsed()), if command { 4 * 1024 * 1024 } else if action == Action::Logs { diff --git a/packages/runtime-core/src/provider/graph/native/foreground/tests.rs b/packages/runtime-core/src/provider/graph/native/foreground/tests.rs index b7a184d0f4..6ee7960be7 100644 --- a/packages/runtime-core/src/provider/graph/native/foreground/tests.rs +++ b/packages/runtime-core/src/provider/graph/native/foreground/tests.rs @@ -1699,3 +1699,156 @@ fn a_requester_whose_owner_is_gone_before_the_write_answers_not_started() { assert_eq!(error.code, "graph_authored_command_not_started"); assert!(error.session().is_none()); } + +/// Wait until the owner's listener holds a connection it has not accepted. +fn pending_connection(publication: &owner::Publication) { + use std::os::fd::AsRawFd; + let mut descriptor = libc::pollfd { + fd: publication.descriptor().as_raw_fd(), + events: libc::POLLIN, + revents: 0, + }; + // SAFETY: one valid pollfd for the listener the publication owns. + let ready = unsafe { libc::poll(&mut descriptor, 1, 5000) }; + assert_eq!(ready, 1, "the requester never connected"); +} + +/// The owner's normal end: its run saved as removed, then its publication +/// retired and its listener closed, with any backlog connection unaccepted. +fn end_through_cleanup(publication: owner::Publication, root: &std::path::Path, receipt: &Receipt) { + let mut publication = publication; + journal::save(root, &removed(receipt.clone())).unwrap(); + publication.finish().unwrap(); + drop(publication); +} + +/// HACK-2742 review, VM row 4 reproduced: the requester connected while the +/// owner was busy in its own `hack down` cleanup and wrote its request into the +/// listen backlog; the owner then saved its run removed, retired and closed the +/// listener without accepting it. Nothing was processed, so finite exec and run +/// answer not-started instead of an unconfirmed completion. +#[test] +fn a_command_left_in_the_backlog_of_an_owner_that_ended_through_cleanup_is_not_started() { + for action in [Action::Exec, Action::Run] { + let fixture = Fixture::new(); + let receipt = admitted(fixture.receipt()); + let publication = owner::Publication::bind(&fixture.candidate, &receipt.review).unwrap(); + let root = journal::reserve(&fixture.candidate, &receipt).unwrap(); + std::thread::scope(|scope| { + let caller = scope.spawn(|| match action { + Action::Exec => exec(&fixture.candidate, RUN, "web", &["true".into()], None), + _ => one_off(&fixture.candidate, RUN, "web", &["true".into()], None), + }); + pending_connection(&publication); + end_through_cleanup(publication, &root, &receipt); + let error = caller.join().unwrap().err().unwrap(); + assert_eq!(error.code, "native_graph_foreground", "{}", error.message); + assert_eq!( + error.cause_code.as_deref(), + Some("graph_authored_command_not_started") + ); + }); + } +} + +/// HACK-2742 review: the same end without the owner's evidence stays +/// unconfirmed. An owner that accepted and read the request, then dropped the +/// connection unanswered but is still published, may have processed it; an +/// owner that sent part of an answer before it ended did process it. +#[test] +fn an_unanswered_command_without_a_clean_owner_end_stays_unconfirmed() { + for case in ["alive", "partial"] { + let fixture = Fixture::new(); + let receipt = admitted(fixture.receipt()); + let publication = owner::Publication::bind(&fixture.candidate, &receipt.review).unwrap(); + let root = journal::reserve(&fixture.candidate, &receipt).unwrap(); + std::thread::scope(|scope| { + let caller = + scope.spawn(|| exec(&fixture.candidate, RUN, "web", &["true".into()], None)); + let mut stream = accepted(&publication, &receipt.review); + if case == "partial" { + stream.write_all(&[0, 0, 0]).unwrap(); + } + drop(stream); + if case == "partial" { + end_through_cleanup(publication, &root, &receipt); + let error = caller.join().unwrap().err().unwrap(); + assert!(error.cause_code.is_none(), "{case}: {}", error.code); + } else { + let error = caller.join().unwrap().err().unwrap(); + assert!(error.cause_code.is_none(), "{case}: {}", error.code); + let mut publication = publication; + publication.finish().unwrap(); + } + }); + } +} + +/// HACK-2742 review: a stale pin whose socket is gone refuses the connect before +/// anything is sent, so it answers not-started too. +#[test] +fn a_stale_pin_with_a_dead_socket_is_not_started() { + let fixture = Fixture::new(); + let receipt = admitted(fixture.receipt()); + let _publication = owner::Publication::bind(&fixture.candidate, &receipt.review).unwrap(); + fs::remove_file(fixture.owner_root().join("control.sock")).unwrap(); + let error = exec(&fixture.candidate, RUN, "web", &["true".into()], None) + .err() + .unwrap(); + assert_eq!( + error.cause_code.as_deref(), + Some("graph_authored_command_not_started") + ); +} + +/// HACK-2742 review, VM row 4b reproduced: the interactive request left in the +/// backlog of an owner that ended through cleanup answers not-started with no +/// session; while that owner is still published, the same unanswered close +/// stays session-correlated (uncertain). +#[test] +fn an_interactive_request_left_in_the_backlog_of_an_ended_owner_is_not_started() { + use crate::provider::{graph::interactive_exec::Options, interactive_terminal::Leash}; + use std::os::unix::net::UnixStream; + const SESSION: &str = "12345678-abcd-abcd-abcd-123456789abc"; + for ended in [true, false] { + let fixture = Fixture::new(); + let receipt = admitted(fixture.receipt()); + let publication = owner::Publication::bind(&fixture.candidate, &receipt.review).unwrap(); + let root = journal::reserve(&fixture.candidate, &receipt).unwrap(); + let (input, mut frontend) = UnixStream::pair().unwrap(); + frontend.write_all(&[0; 4]).unwrap(); + let (leash, _) = Leash::receive(input.into()).unwrap(); + let argv = vec!["tool".into()]; + let options = Options { + session: SESSION, + run: RUN, + service: "web", + owner: &receipt.owner, + plan: receipt.review.review_id(), + namespace: receipt.review.scope().namespace, + native: true, + argv: &argv, + workdir: None, + expected_container: None, + expected_generation: None, + }; + std::thread::scope(|scope| { + let caller = + scope.spawn(|| interactive(&fixture.candidate, &options, [43, 91], &leash)); + if ended { + pending_connection(&publication); + end_through_cleanup(publication, &root, &receipt); + let error = caller.join().unwrap().err().unwrap(); + assert_eq!(error.code, "graph_authored_command_not_started"); + assert!(error.session().is_none()); + } else { + let stream = accepted(&publication, &receipt.review); + drop(stream); + let error = caller.join().unwrap().err().unwrap(); + assert_eq!(error.session(), Some(SESSION)); + let mut publication = publication; + publication.finish().unwrap(); + } + }); + } +} diff --git a/packages/runtime-core/src/provider/interactive_handoff.rs b/packages/runtime-core/src/provider/interactive_handoff.rs index 26a5f38500..6a23bcc363 100644 --- a/packages/runtime-core/src/provider/interactive_handoff.rs +++ b/packages/runtime-core/src/provider/interactive_handoff.rs @@ -164,6 +164,16 @@ fn copied_rights(bytes: &[u8], copied: usize) -> (Vec, bool) { (descriptors, invalid) } +/// The code of a handoff whose peer closed before it sent a single byte. +pub(super) const CLOSED_UNANSWERED: &str = "interactive_handoff_closed"; + +fn closed_unanswered() -> CandidateError { + CandidateError::new( + CLOSED_UNANSWERED, + "The interactive owner closed the connection before it answered.", + ) +} + /// Received descriptors are owned immediately, including on truncated/invalid /// messages. No descriptor is exposed until its count, type and CLOEXEC are valid. /// Darwin may install additional rights that it does not copy out on truncation. @@ -203,7 +213,23 @@ pub(super) fn receive( continue; } if count < 0 { - return Err(refused()); + // HACK-2742 review: a reset before anything was received is told + // apart, so the caller can prove (with the owner's own evidence) + // that nothing was processed. + return Err( + if matches!( + io::Error::last_os_error().raw_os_error(), + Some(libc::ECONNRESET | libc::ENOTCONN) + ) { + closed_unanswered() + } else { + refused() + }, + ); + } + if count == 0 && message.msg_controllen == 0 { + // The peer closed before it sent a byte, with no descriptor. + return Err(closed_unanswered()); } // SAFETY: ancillary is initialized storage of this exact byte size; // the parser borrows it and never reads beyond the returned length. From 4a7a1b5d20e6447cf60af0f800e4e2df0e442173 Mon Sep 17 00:00:00 2001 From: Dimitri Kennedy <344842+roodboi@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:08:22 -0500 Subject: [PATCH 07/11] fix(native): never read a recovered or started request as not started (HACK-2742) The backlog proof treated an unanswered close followed by a retired publication and a removed run as proof that nothing ran. Two rare paths could satisfy it falsely: - Dead-owner recovery saves the run removed and archives the publication as `control-.retired.sock` / `owner-.retired.json`, which looked like the owner's own retirement. The proof now also requires that no archived publication path exists (`verify_retired_by_owner`). - An interactive session the owner had started, whose descriptor handoff then failed with no byte sent, closed the connection unanswered. The owner now sends an empty handoff and the bound reply in that case, so the requester answers a retained session; and the requester's proof also requires that no retained receipt exists for this session. Tests: a recovery-archived retirement stays unconfirmed (both archive names), and a present session receipt stays session-correlated. Both fail with the guards disabled. Co-Authored-By: Claude Opus 5.5 --- .../src/provider/graph/native/foreground.rs | 33 +++++-- .../provider/graph/native/foreground/owner.rs | 18 ++++ .../provider/graph/native/foreground/tests.rs | 85 +++++++++++++++++++ 3 files changed, 129 insertions(+), 7 deletions(-) diff --git a/packages/runtime-core/src/provider/graph/native/foreground.rs b/packages/runtime-core/src/provider/graph/native/foreground.rs index 6756320c50..99cb9a7dbb 100644 --- a/packages/runtime-core/src/provider/graph/native/foreground.rs +++ b/packages/runtime-core/src/provider/graph/native/foreground.rs @@ -86,21 +86,29 @@ fn closed_unanswered(stream: &std::os::unix::net::UnixStream, deadline: Instant) /// removed and then retires its publication. A connection it closed without a /// byte of answer, followed by that retirement, was therefore never processed: /// it was still in the listen backlog, or its request never fully arrived. An -/// owner that failed instead keeps its publication, so this answers false. The -/// retirement is awaited briefly, because the connection can close as the -/// process exits a moment after its files are removed. +/// owner that failed instead keeps its publication, so this answers false; so +/// does a publication that another process's dead-owner recovery retired, which +/// it archives rather than deletes (`verify_retired_by_owner`). For an +/// interactive `session`, a retained session receipt also answers false: the +/// owner had started that session. The retirement is awaited briefly, because +/// the connection can close as the process exits a moment after its files are +/// removed. fn owner_ended_unanswered( candidate: &Candidate, pin: &owner::Pin, review: &native_input::Review, + session: Option<&str>, ) -> bool { let deadline = Instant::now() + Duration::from_secs(2); loop { - if pin.verify_retired().is_ok() + if pin.verify_retired_by_owner().is_ok() && journal::read_control(candidate, review) .is_ok_and(|receipt| receipt.phase == Phase::Removed) { - return true; + return session.is_none_or(|session| { + crate::provider::interactive_session::retained(candidate) + .is_ok_and(|records| records.iter().all(|record| record.session != session)) + }); } if Instant::now() >= deadline { return false; @@ -691,6 +699,17 @@ pub fn serve_with_storage_tool( std::time::Instant::now() + Duration::from_secs(5), ) .is_err() + // HACK-2742 review: the session may already have started. Never + // leave this connection closed with no byte, which the requester + // could read as an unprocessed request: send an empty handoff and + // then the bound reply, which the requester answers as a retained + // session (no descriptor) or the owner's own pre-effect refusal. + && crate::provider::interactive_handoff::send( + &stream, + None, + std::time::Instant::now() + Duration::from_secs(5), + ) + .is_err() { continue; } @@ -851,7 +870,7 @@ pub(in crate::provider) fn interactive( // the owner's own retirement and removed run as evidence, is the attempt // proven unprocessed and reported with no session. let unanswered = |error: CandidateError| { - if owner_ended_unanswered(candidate, &pin, review) { + if owner_ended_unanswered(candidate, &pin, review, Some(options.session)) { interactive_not_sent(error) } else { uncertain(error) @@ -939,7 +958,7 @@ fn request_selected( // owner closed the connection without a single byte of answer and then // retired its publication with its run removed (`owner_ended_unanswered`). let unanswered = |error: CandidateError| { - if command && owner_ended_unanswered(candidate, &pin, review) { + if command && owner_ended_unanswered(candidate, &pin, review, None) { command_not_sent(error) } else { error diff --git a/packages/runtime-core/src/provider/graph/native/foreground/owner.rs b/packages/runtime-core/src/provider/graph/native/foreground/owner.rs index aa7abf1391..5335cc4539 100644 --- a/packages/runtime-core/src/provider/graph/native/foreground/owner.rs +++ b/packages/runtime-core/src/provider/graph/native/foreground/owner.rs @@ -291,6 +291,24 @@ impl Pin { pub(super) fn review(&self) -> &native_input::Review { &self.record.review } + /// [`Self::verify_retired`], and the retirement was the owner's own `finish()` + /// rather than another process's dead-owner recovery (HACK-2742 review). The + /// owner deletes its socket and owner record; recovery moves them aside as + /// `control-.retired.sock` and `owner-.retired.json`, so any such + /// archive in the owner root refuses. + pub(super) fn verify_retired_by_owner(&self) -> Result<(), CandidateError> { + self.verify_retired()?; + for entry in fs::read_dir(&self.root).map_err(|_| refused())? { + let name = entry.map_err(|_| refused())?.file_name(); + let name = name.to_string_lossy(); + if (name.starts_with("control-") && name.ends_with(".retired.sock")) + || (name.starts_with("owner-") && name.ends_with(".retired.json")) + { + return Err(refused()); + } + } + Ok(()) + } /// The caller already authenticated its retained connection before the owner /// retired. Absence grants no new connection, process or cleanup authority. pub(super) fn verify_retired(&self) -> Result<(), CandidateError> { diff --git a/packages/runtime-core/src/provider/graph/native/foreground/tests.rs b/packages/runtime-core/src/provider/graph/native/foreground/tests.rs index 6ee7960be7..846d8d9127 100644 --- a/packages/runtime-core/src/provider/graph/native/foreground/tests.rs +++ b/packages/runtime-core/src/provider/graph/native/foreground/tests.rs @@ -1852,3 +1852,88 @@ fn an_interactive_request_left_in_the_backlog_of_an_ended_owner_is_not_started() }); } } + +/// HACK-2742 re-review (L1): dead-owner recovery saves the run removed and +/// archives the publication rather than deleting it, which otherwise looks like +/// the owner's own retirement. While either archive path is present the owner's +/// clean end is not proven, so the unanswered backlog request stays unconfirmed. +#[test] +fn a_backlog_request_after_a_recovery_archived_retirement_stays_unconfirmed() { + for archive in [ + "control-feedface.retired.sock", + "owner-feedface.retired.json", + ] { + let fixture = Fixture::new(); + let receipt = admitted(fixture.receipt()); + let publication = owner::Publication::bind(&fixture.candidate, &receipt.review).unwrap(); + let root = journal::reserve(&fixture.candidate, &receipt).unwrap(); + fs::write(fixture.owner_root().join(archive), b"").unwrap(); + std::thread::scope(|scope| { + let caller = + scope.spawn(|| exec(&fixture.candidate, RUN, "web", &["true".into()], None)); + pending_connection(&publication); + end_through_cleanup(publication, &root, &receipt); + let error = caller.join().unwrap().err().unwrap(); + assert_eq!(error.code, "native_graph_foreground", "{archive}"); + assert!( + error.cause_code.is_none(), + "{archive}: {:?}", + error.cause_code + ); + }); + } +} + +/// HACK-2742 re-review (L2): a retained receipt for this exact session means the +/// owner had admitted it, so even an unanswered close followed by the owner's +/// clean end stays session-correlated (uncertain), never not-started. +#[test] +fn an_unanswered_interactive_request_with_its_session_receipt_stays_uncertain() { + use crate::provider::{ + graph::interactive_exec::Options, + interactive_session::{self, Backend, Binding}, + interactive_terminal::Leash, + }; + use std::os::unix::net::UnixStream; + const SESSION: &str = "12345678-abcd-abcd-abcd-123456789abc"; + let fixture = Fixture::new(); + let receipt = admitted(fixture.receipt()); + let publication = owner::Publication::bind(&fixture.candidate, &receipt.review).unwrap(); + let root = journal::reserve(&fixture.candidate, &receipt).unwrap(); + let binding = Binding { + backend: Backend::Authored, + namespace: "a".repeat(64), + run: RUN.into(), + owner: "c".repeat(32), + boot: "00000000-0000-4000-8000-000000000001".into(), + container: "d".repeat(64), + generation: "2026-11-12T01:02:03.123456789Z".into(), + service: "web".into(), + }; + drop(interactive_session::admit(&fixture.candidate, binding, SESSION).unwrap()); + let (input, mut frontend) = UnixStream::pair().unwrap(); + frontend.write_all(&[0; 4]).unwrap(); + let (leash, _) = Leash::receive(input.into()).unwrap(); + let argv = vec!["tool".into()]; + let options = Options { + session: SESSION, + run: RUN, + service: "web", + owner: &receipt.owner, + plan: receipt.review.review_id(), + namespace: receipt.review.scope().namespace, + native: true, + argv: &argv, + workdir: None, + expected_container: None, + expected_generation: None, + }; + std::thread::scope(|scope| { + let caller = scope.spawn(|| interactive(&fixture.candidate, &options, [43, 91], &leash)); + pending_connection(&publication); + end_through_cleanup(publication, &root, &receipt); + let error = caller.join().unwrap().err().unwrap(); + assert_ne!(error.code, "graph_authored_command_not_started"); + assert_eq!(error.session(), Some(SESSION)); + }); +} From bedbedf81b08d7c37f56abb5acc89f2eeeedbe63 Mon Sep 17 00:00:00 2001 From: Dimitri Kennedy <344842+roodboi@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:37:15 -0500 Subject: [PATCH 08/11] test(runtime-core): assert only the outcome of a recovery-archived backlog request (HACK-2742) The test closes the owner's listener as soon as the connection is pending, so the requester's write races the close. When the write loses, the error is the transport's `graph_owner_recovery`; when the read loses, it is `native_graph_foreground`. Both are correct. The test now rules out only the not-started answer (code and cause), whichever step fails first. Co-Authored-By: Claude Opus 5.5 --- .../src/provider/graph/native/foreground/tests.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/runtime-core/src/provider/graph/native/foreground/tests.rs b/packages/runtime-core/src/provider/graph/native/foreground/tests.rs index 846d8d9127..fecc97cbaf 100644 --- a/packages/runtime-core/src/provider/graph/native/foreground/tests.rs +++ b/packages/runtime-core/src/provider/graph/native/foreground/tests.rs @@ -1874,7 +1874,12 @@ fn a_backlog_request_after_a_recovery_archived_retirement_stays_unconfirmed() { pending_connection(&publication); end_through_cleanup(publication, &root, &receipt); let error = caller.join().unwrap().err().unwrap(); - assert_eq!(error.code, "native_graph_foreground", "{archive}"); + // The failing step races the listener's close (write or read), so + // the code differs; only the not-started answer is ruled out. + assert_ne!( + error.code, "graph_authored_command_not_started", + "{archive}" + ); assert!( error.cause_code.is_none(), "{archive}: {:?}", From 93b7a2ccb8fbfa2edfa1c12ebfe5ce06a65f0bc9 Mon Sep 17 00:00:00 2001 From: Dimitri Kennedy <344842+roodboi@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:18:17 -0500 Subject: [PATCH 09/11] fix(native): deliver full command replies and prove not-started by owner acceptance (HACK-2742) Codex review P1: a command whose stdout reached the 1 MiB cap produced a reply of about 2.8 MB of base64. The owner serialized it into the 1,081,344-byte request buffer, so the write failed with nothing sent, and the error was ignored. If the owner then ended through its cleanup, the requester's proof ("closed with no byte, then retired by the owner, run removed") reported the command as not started although it had run. Replies: a command reply is written with its own 4 MiB bound, which holds two capped streams and their receipt (checked at compile time), the size the requester already reads. A failed reply write is reported value-free on the owner's standard error. Proof: the owner now accepts each command with one byte, after it read and validated the request and before any effect, and drops a command whose byte it cannot queue. Commands carry request version 3; status, observe, logs and cleanup keep version 2, and the owner still serves version-2 commands from older requesters without the byte. A requester reports not started only when the connection closed with no byte at all, which proves for this request alone that it never began. Any close after acceptance stays unconfirmed. The interactive requester also requires that its frontend leash still holds, so a local shutdown by the leash watcher is never read as the owner's close. The retirement, recovery-archive and session-receipt checks, and the handoff's closed-unanswered code, are removed: the byte replaces them. An owner started by an earlier prerelease refuses version 3 by closing, so an authored exec or run against it reports not started (true) until the project is restarted; the guide says so. Tests: a capped reply is refused by the request bound and delivered whole by the reply writer; a command taken but not accepted is not started while the owner is still published; an accepted command closed before its reply stays unconfirmed even when the owner then ends through cleanup; backlog requests are not started whatever retired the publication; interactive requests are not started only without acceptance, and a leash shutdown stays uncertain (fails with the leash check removed). Co-Authored-By: Claude Opus 5.5 --- docs/guides/native-candidate.md | 2 +- .../provider/graph/foreground/transport.rs | 85 +++++ .../src/provider/graph/native/foreground.rs | 252 +++++++------- .../provider/graph/native/foreground/owner.rs | 18 - .../provider/graph/native/foreground/tests.rs | 318 +++++++++++++----- .../src/provider/interactive_handoff.rs | 28 +- 6 files changed, 435 insertions(+), 268 deletions(-) diff --git a/docs/guides/native-candidate.md b/docs/guides/native-candidate.md index 162afb8b5f..925bbaf443 100644 --- a/docs/guides/native-candidate.md +++ b/docs/guides/native-candidate.md @@ -5489,7 +5489,7 @@ and the command says `nothing ran` with `Holder: unavailable.` and `Retry hack e once the holder finishes.` A pending Ctrl-C of the owner, its `hack down`, or a changed owner publication ends the owner's wait at once; the owner then answers `graph_authored_command_not_started`, and the command says it did not start, that -nothing ran, and to check `hack ps` and retry once the project is up. The command says the same when the owner exits while the command is still waiting for the lock, for example during the project's own `hack down`: nothing has been sent at that point. It also says the same when the request reached the owner's queue but the owner ended through that `hack down` without taking it: the owner closed the connection without a byte of answer, retired its publication and saved its run as removed, which proves it never processed the request. Every other failure after the request is sent keeps "unconfirmed". Any other +nothing ran, and to check `hack ps` and retry once the project is up. The command says the same when the owner exits while the command is still waiting for the lock, for example during the project's own `hack down`: nothing has been sent at that point. The owner accepts each command with one byte before it does anything for it, and it drops a command it cannot accept. So the command also says nothing ran when the owner closed the connection without even that byte: for example, the request reached the owner's queue but the owner ended through that `hack down` without taking it, or the owner refused the request. Once the owner has accepted a command, every failure keeps "unconfirmed". A command's answer carries up to 1 MiB of output on each stream. A project started by an earlier prerelease does not accept commands this way: restart it after you upgrade. Until then, an authored exec or run against it says nothing ran. Any other authored failure keeps its report, "completion is unconfirmed" included. A compose project's one-off `run` is answered by its owner, which waits at most 15 seconds on its only loop, within one 15-second bound for its selection and admission before its diff --git a/packages/runtime-core/src/provider/graph/foreground/transport.rs b/packages/runtime-core/src/provider/graph/foreground/transport.rs index 7e454449d3..30cafa5c3e 100644 --- a/packages/runtime-core/src/provider/graph/foreground/transport.rs +++ b/packages/runtime-core/src/provider/graph/foreground/transport.rs @@ -1239,6 +1239,91 @@ pub(super) fn write_extension( } write_bounded(stream, request, budget, APPEND_REQUEST_LIMIT) } +/// [`write`] for a reply frame of up to `limit` bytes. A native authored command +/// reply carries two output streams of up to 1 MiB each in base64, beyond the +/// request bound (HACK-2742 review). +#[cfg(feature = "native-config-plan")] +pub(in crate::provider::graph) fn write_limited( + stream: &mut UnixStream, + value: &T, + budget: Duration, + limit: usize, +) -> Result<(), CandidateError> { + write_bounded(stream, value, budget, limit)?; + stream.shutdown(Shutdown::Write).map_err(|_| refused()) +} + +/// Send one marker byte ahead of any frame. An error means the byte was not +/// queued for the peer; a success means the peer will read it before anything +/// sent after it, even if this side then closes. +#[cfg(feature = "native-config-plan")] +pub(in crate::provider::graph) fn send_marker( + stream: &UnixStream, + marker: u8, + budget: Duration, +) -> Result<(), CandidateError> { + let deadline = Instant::now() + budget; + loop { + wait_io(stream.as_raw_fd(), libc::POLLOUT, deadline)?; + // SAFETY: one readable byte, and the stream owns the FD. Nonblocking send + // keeps the deadline; NOSIGNAL keeps a disconnect local. + let n = unsafe { + libc::send( + stream.as_raw_fd(), + (&marker as *const u8).cast(), + 1, + libc::MSG_DONTWAIT | libc::MSG_NOSIGNAL, + ) + }; + if n == 1 { + return Ok(()); + } + if n < 0 + && matches!( + std::io::Error::last_os_error().kind(), + std::io::ErrorKind::WouldBlock | std::io::ErrorKind::Interrupted + ) + { + continue; + } + return Err(refused()); + } +} + +/// The peer's first byte, consumed, or `None` when the peer closed the stream +/// without sending one (an end of file, or a reset or disconnect with nothing +/// queued: queued bytes are always read before such an error is reported). A +/// timeout or any other failure is an error and proves nothing. +#[cfg(feature = "native-config-plan")] +pub(in crate::provider::graph) fn receive_marker( + stream: &UnixStream, + deadline: Instant, +) -> Result, CandidateError> { + loop { + wait_io(stream.as_raw_fd(), libc::POLLIN, deadline)?; + let mut byte = 0_u8; + // SAFETY: one writable byte, and the stream owns the FD. MSG_DONTWAIT + // keeps a readiness race within the deadline. + let count = unsafe { + libc::recv( + stream.as_raw_fd(), + (&mut byte as *mut u8).cast(), + 1, + libc::MSG_DONTWAIT, + ) + }; + match count { + 1 => return Ok(Some(byte)), + 0 => return Ok(None), + _ => match std::io::Error::last_os_error().raw_os_error() { + Some(libc::ECONNRESET | libc::ENOTCONN | libc::EPIPE) => return Ok(None), + Some(libc::EAGAIN | libc::EINTR) => continue, + _ => return Err(refused()), + }, + } + } +} + pub(super) fn write_job( stream: &mut UnixStream, value: &T, diff --git a/packages/runtime-core/src/provider/graph/native/foreground.rs b/packages/runtime-core/src/provider/graph/native/foreground.rs index 99cb9a7dbb..f1e19f70f5 100644 --- a/packages/runtime-core/src/provider/graph/native/foreground.rs +++ b/packages/runtime-core/src/provider/graph/native/foreground.rs @@ -30,90 +30,65 @@ fn command_not_sent(_error: CandidateError) -> CandidateError { refused().with_cause_code(runtime::OWNER_COMMAND_NOT_STARTED.to_owned()) } -/// Whether the owner closed `stream` before it sent a single byte of its answer -/// (HACK-2742 review). Waits until `deadline` for the first byte or the close, -/// and consumes nothing: a peeked byte is left for the reply reader. A timeout -/// or any other error is not a proof and answers false. -fn closed_unanswered(stream: &std::os::unix::net::UnixStream, deadline: Instant) -> bool { - use std::os::fd::AsRawFd; - loop { - let remaining = deadline.saturating_duration_since(Instant::now()); - let mut descriptor = libc::pollfd { - fd: stream.as_raw_fd(), - events: libc::POLLIN, - revents: 0, - }; - let timeout = i32::try_from(remaining.as_millis()).unwrap_or(i32::MAX); - // SAFETY: one valid pollfd for a descriptor the stream owns. - let ready = unsafe { libc::poll(&mut descriptor, 1, timeout) }; - if ready < 0 { - if std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted { - continue; - } - return false; - } - if ready == 0 { - return false; - } - let mut byte = [0_u8; 1]; - // SAFETY: one writable byte; MSG_PEEK leaves it queued for the reader. - let count = unsafe { - libc::recv( - stream.as_raw_fd(), - byte.as_mut_ptr().cast(), - 1, - libc::MSG_PEEK | libc::MSG_DONTWAIT, - ) - }; - if count == 0 { - return true; - } - if count > 0 { - return false; - } - match std::io::Error::last_os_error().raw_os_error() { - Some(libc::ECONNRESET | libc::ENOTCONN | libc::EPIPE) => return true, - Some(libc::EAGAIN | libc::EINTR) => continue, - _ => return false, - } +/// The request version of a command (exec, interactive exec, one-off run) that +/// the owner accepts before it starts (HACK-2742 review). Status, observe, logs +/// and cleanup keep version 2, as does any request from an older requester. An +/// older owner refuses this version unprocessed, by closing the connection. +const ACCEPTING_VERSION: u32 = 3; + +/// The byte an owner sends for an [`ACCEPTING_VERSION`] command after it read +/// and validated the request and before any effect: no lease wait, journal +/// read, container contact or session admission comes first, and an owner that +/// cannot queue the byte drops the request unstarted. So a requester that sees +/// the connection close with no byte at all has proof, for this request alone, +/// that nothing ran: the owner never took it from its listen backlog, refused +/// it, or ended before accepting it. Retirement or receipts are not needed for +/// that proof; any close after this byte stays unconfirmed. +const ACCEPTED: u8 = 0xAC; + +/// A command reply: two streams of up to 1 MiB in base64 (1,398,104 bytes each, +/// `runtime::exec::valid_stream`) with a bounded receipt in its envelope. The +/// request bound used by [`transport::write`] is smaller, and an oversized reply +/// would fail to serialize with nothing sent (HACK-2742 review). +const COMMAND_REPLY_LIMIT: usize = 4 * 1024 * 1024; +const _: () = assert!(2 * 1_398_104 + 4 * LIMIT < COMMAND_REPLY_LIMIT); + +/// Write the owner's reply. A command reply has its own bound. A failed write +/// leaves the requester with an accepted request and no answer, which it reports +/// as unconfirmed; the failure is also reported value-free on the owner's +/// standard error, so it is not silent. +fn deliver_reply( + stream: &mut std::os::unix::net::UnixStream, + reply: &Reply, + action: Action, +) -> Result<(), CandidateError> { + let written = if action.command() { + transport::write_limited(stream, reply, Duration::from_secs(5), COMMAND_REPLY_LIMIT) + } else { + transport::write(stream, reply, Duration::from_secs(5)) + }; + if let Err(error) = &written { + eprintln!( + "Native graph owner could not deliver its {} reply ({}); the requester reports the outcome unconfirmed.", + action.word(), + error.code + ); } + written } -/// Whether the owner ended through its normal cleanup and so never processed a -/// request it left unanswered (HACK-2742 review). The owner serves one request -/// at a time on its only loop and writes each answer before it accepts the -/// next. It returns from that loop only after a cleanup, which saves the run as -/// removed and then retires its publication. A connection it closed without a -/// byte of answer, followed by that retirement, was therefore never processed: -/// it was still in the listen backlog, or its request never fully arrived. An -/// owner that failed instead keeps its publication, so this answers false; so -/// does a publication that another process's dead-owner recovery retired, which -/// it archives rather than deletes (`verify_retired_by_owner`). For an -/// interactive `session`, a retained session receipt also answers false: the -/// owner had started that session. The retirement is awaited briefly, because -/// the connection can close as the process exits a moment after its files are -/// removed. -fn owner_ended_unanswered( - candidate: &Candidate, - pin: &owner::Pin, - review: &native_input::Review, - session: Option<&str>, -) -> bool { - let deadline = Instant::now() + Duration::from_secs(2); - loop { - if pin.verify_retired_by_owner().is_ok() - && journal::read_control(candidate, review) - .is_ok_and(|receipt| receipt.phase == Phase::Removed) - { - return session.is_none_or(|session| { - crate::provider::interactive_session::retained(candidate) - .is_ok_and(|records| records.iter().all(|record| record.session != session)) - }); - } - if Instant::now() >= deadline { - return false; - } - std::thread::sleep(Duration::from_millis(20)); +/// For an [`ACCEPTING_VERSION`] command, wait for the owner's [`ACCEPTED`] byte. +/// `Ok(false)` is the proof that the owner closed with no byte, so nothing ran; +/// `Ok(true)` means it accepted and the reply follows. Any other byte, a timeout +/// or another error is unconfirmed. +fn owner_accepted( + stream: &std::os::unix::net::UnixStream, + deadline: Instant, +) -> Result { + match transport::receive_marker(stream, deadline)? { + None => Ok(false), + Some(ACCEPTED) => Ok(true), + Some(_) => Err(refused()), } } @@ -162,6 +137,23 @@ pub enum Action { InteractiveExec, Run, } +impl Action { + /// A command the owner runs: these carry [`ACCEPTING_VERSION`]. + fn command(self) -> bool { + matches!(self, Self::Exec | Self::InteractiveExec | Self::Run) + } + fn word(self) -> &'static str { + match self { + Self::Status => "status", + Self::Observe => "observe", + Self::Cleanup => "cleanup", + Self::Logs => "logs", + Self::Exec => "exec", + Self::InteractiveExec => "interactive exec", + Self::Run => "run", + } + } +} #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] struct LogsSelection { @@ -205,7 +197,7 @@ struct Request { } impl Request { fn validate(&self, review: &native_input::Review) -> Result<(), CandidateError> { - if self.version != 2 + if !(self.version == 2 || self.version == ACCEPTING_VERSION && self.action.command()) || self.run != review.scope().run || self.review != review.review_id() || match self.session.as_deref() { @@ -588,6 +580,13 @@ pub fn serve_with_storage_tool( continue; } publication.verify()?; + // HACK-2742 review: accept the command before any effect. If the byte + // cannot be queued (the requester is gone), drop the request unstarted. + if request.version == ACCEPTING_VERSION + && transport::send_marker(&stream, ACCEPTED, Duration::from_secs(5)).is_err() + { + continue; + } let mut attached = None; let result = match request.action { Action::InteractiveExec => { @@ -683,7 +682,7 @@ pub fn serve_with_storage_tool( // Retire before writing on the retained authenticated stream. Clients // verify both absent publication paths and the exact durable Removed journal. publication.finish()?; - let _ = transport::write(&mut stream, &reply, Duration::from_secs(5)); + let _ = deliver_reply(&mut stream, &reply, request.action); let Outcome::Cleaned { receipt } = reply.result else { return Err(refused()); }; @@ -699,11 +698,10 @@ pub fn serve_with_storage_tool( std::time::Instant::now() + Duration::from_secs(5), ) .is_err() - // HACK-2742 review: the session may already have started. Never - // leave this connection closed with no byte, which the requester - // could read as an unprocessed request: send an empty handoff and - // then the bound reply, which the requester answers as a retained - // session (no descriptor) or the owner's own pre-effect refusal. + // HACK-2742 review: the session may already have started. Send an + // empty handoff and then the bound reply, which the requester + // answers as a retained session (no descriptor) or the owner's own + // pre-effect refusal, rather than an unexplained close. && crate::provider::interactive_handoff::send( &stream, None, @@ -714,7 +712,7 @@ pub fn serve_with_storage_tool( continue; } } - let _ = transport::write(&mut stream, &reply, Duration::from_secs(5)); + let _ = deliver_reply(&mut stream, &reply, request.action); } } @@ -850,7 +848,7 @@ pub(in crate::provider) fn interactive( let mut stream = pin.connect().map_err(interactive_not_sent)?; let _lifetime = leash.watch_control(&stream).map_err(interactive_not_sent)?; let input = Request { - version: 2, + version: ACCEPTING_VERSION, kind: RequestKind::NativeGraphControl, run: run.into(), review: review.review_id().into(), @@ -865,29 +863,24 @@ pub(in crate::provider) fn interactive( // the owner stopped before its durable intent. Correlate only this attempt; // a validated pre-intent refusal below remains unscoped. let uncertain = |error: CandidateError| error.with_session(options.session); - // HACK-2742 review (VM row 4): an owner that never accepted this connection - // and then ended through its cleanup closes it unanswered. Only then, with - // the owner's own retirement and removed run as evidence, is the attempt - // proven unprocessed and reported with no session. - let unanswered = |error: CandidateError| { - if owner_ended_unanswered(candidate, &pin, review, Some(options.session)) { - interactive_not_sent(error) - } else { - uncertain(error) + let deadline = std::time::Instant::now() + Duration::from_secs(40); + let written = transport::write(&mut stream, &input, Duration::from_secs(5)); + // HACK-2742 review: the owner accepts before it admits the session. A close + // with no byte proves it never did, so nothing ran and no session exists, + // provided this side did not close the stream itself: the leash watcher + // shuts it down only once the frontend is gone, and that loss is permanent, + // so a leash that still holds after the close proves the close was the + // owner's. A write failure alone proves nothing until that answer arrives. + match owner_accepted(&stream, deadline) { + Ok(true) => {} + Ok(false) if leash.check().is_ok() => { + return Err(interactive_not_sent(written.err().unwrap_or_else(refused))); } - }; - transport::write(&mut stream, &input, Duration::from_secs(5)).map_err(unanswered)?; - let descriptor = crate::provider::interactive_handoff::receive( - &stream, - std::time::Instant::now() + Duration::from_secs(40), - ) - .map_err(|error| { - if error.code == crate::provider::interactive_handoff::CLOSED_UNANSWERED { - unanswered(error) - } else { - uncertain(error) - } - })?; + Ok(false) => return Err(uncertain(written.err().unwrap_or_else(refused))), + Err(error) => return Err(uncertain(written.err().unwrap_or(error))), + } + let descriptor = + crate::provider::interactive_handoff::receive(&stream, deadline).map_err(uncertain)?; let reply: Reply = transport::read(&mut stream, Duration::from_secs(5), LIMIT).map_err(uncertain)?; reply @@ -940,7 +933,7 @@ fn request_selected( let expected = journal::read_control(candidate, review).map_err(not_sent)?; let mut stream = pin.connect().map_err(not_sent)?; let input = Request { - version: 2, + version: if command { ACCEPTING_VERSION } else { 2 }, kind: RequestKind::NativeGraphControl, run: run.into(), review: review.review_id().into(), @@ -951,34 +944,33 @@ fn request_selected( exec: exec_selected.clone(), one_off: one_off_selected.clone(), }; - // HACK-2742 review (VM row 4, later rounds): the owner may have taken this - // connection into its listen backlog and then exited through its cleanup - // without ever accepting it. The write, or the first read, then fails with - // nothing answered. For a command that is proven unprocessed only when the - // owner closed the connection without a single byte of answer and then - // retired its publication with its run removed (`owner_ended_unanswered`). - let unanswered = |error: CandidateError| { - if command && owner_ended_unanswered(candidate, &pin, review, None) { - command_not_sent(error) - } else { - error - } - }; - transport::write(&mut stream, &input, Duration::from_secs(5)).map_err(unanswered)?; + let written = transport::write(&mut stream, &input, Duration::from_secs(5)); let budget = if command { Duration::from_secs(40) } else { Duration::from_secs(30) }; let started = Instant::now(); - if command && closed_unanswered(&stream, started + budget) { - return Err(unanswered(refused())); + if command { + // HACK-2742 review (VM row 4): the owner may have left this connection in + // its listen backlog and ended, or refused the request, without taking + // it. It accepts a command before any effect, so a close with no byte at + // all proves that nothing ran (`ACCEPTED`). A write failure alone proves + // nothing until that answer arrives; everything after acceptance stays + // unconfirmed. + match owner_accepted(&stream, started + budget) { + Ok(true) => {} + Ok(false) => return Err(command_not_sent(written.err().unwrap_or_else(refused))), + Err(error) => return Err(written.err().unwrap_or(error)), + } + } else { + written?; } let reply: Reply = transport::read( &mut stream, budget.saturating_sub(started.elapsed()), if command { - 4 * 1024 * 1024 + COMMAND_REPLY_LIMIT } else if action == Action::Logs { 128 * 1024 } else { diff --git a/packages/runtime-core/src/provider/graph/native/foreground/owner.rs b/packages/runtime-core/src/provider/graph/native/foreground/owner.rs index 5335cc4539..aa7abf1391 100644 --- a/packages/runtime-core/src/provider/graph/native/foreground/owner.rs +++ b/packages/runtime-core/src/provider/graph/native/foreground/owner.rs @@ -291,24 +291,6 @@ impl Pin { pub(super) fn review(&self) -> &native_input::Review { &self.record.review } - /// [`Self::verify_retired`], and the retirement was the owner's own `finish()` - /// rather than another process's dead-owner recovery (HACK-2742 review). The - /// owner deletes its socket and owner record; recovery moves them aside as - /// `control-.retired.sock` and `owner-.retired.json`, so any such - /// archive in the owner root refuses. - pub(super) fn verify_retired_by_owner(&self) -> Result<(), CandidateError> { - self.verify_retired()?; - for entry in fs::read_dir(&self.root).map_err(|_| refused())? { - let name = entry.map_err(|_| refused())?.file_name(); - let name = name.to_string_lossy(); - if (name.starts_with("control-") && name.ends_with(".retired.sock")) - || (name.starts_with("owner-") && name.ends_with(".retired.json")) - { - return Err(refused()); - } - } - Ok(()) - } /// The caller already authenticated its retained connection before the owner /// retired. Absence grants no new connection, process or cleanup authority. pub(super) fn verify_retired(&self) -> Result<(), CandidateError> { diff --git a/packages/runtime-core/src/provider/graph/native/foreground/tests.rs b/packages/runtime-core/src/provider/graph/native/foreground/tests.rs index fecc97cbaf..0b20582999 100644 --- a/packages/runtime-core/src/provider/graph/native/foreground/tests.rs +++ b/packages/runtime-core/src/provider/graph/native/foreground/tests.rs @@ -172,6 +172,9 @@ fn real_compiler_review_crosses_authenticated_native_socket_without_compose_fiel }; let input: Request = transport::read(&mut stream, Duration::from_secs(1), 4096).unwrap(); input.validate(&receipt.review).unwrap(); + if input.version == ACCEPTING_VERSION { + transport::send_marker(&stream, ACCEPTED, Duration::from_secs(1)).unwrap(); + } assert!(matches!(input.action, Action::Status)); transport::write( &mut stream, @@ -749,10 +752,24 @@ fn changed(mut receipt: Receipt, field: &str) -> Receipt { receipt.validate(RUN, &receipt.owner).unwrap(); receipt } +/// The owner side of one request, as the serve loop does it: take the +/// connection, read and validate the request and, for a command, accept it. fn accepted( publication: &owner::Publication, review: &native_input::Review, ) -> std::os::unix::net::UnixStream { + let (stream, input) = taken(publication, review); + if input.version == ACCEPTING_VERSION { + transport::send_marker(&stream, ACCEPTED, Duration::from_secs(1)).unwrap(); + } + stream +} + +/// Take and validate one request without accepting it. +fn taken( + publication: &owner::Publication, + review: &native_input::Review, +) -> (std::os::unix::net::UnixStream, Request) { let deadline = Instant::now() + Duration::from_secs(2); let mut stream = loop { if let Some(stream) = publication.accept().unwrap() { @@ -763,7 +780,7 @@ fn accepted( }; let input: Request = transport::read(&mut stream, Duration::from_secs(1), 4096).unwrap(); input.validate(review).unwrap(); - stream + (stream, input) } #[test] @@ -1010,6 +1027,9 @@ fn finite_logs_wire_authenticates_the_live_native_owner_and_exact_member() { }; let input: Request = transport::read(&mut stream, Duration::from_secs(2), 4096).unwrap(); input.validate(&receipt.review).unwrap(); + if input.version == ACCEPTING_VERSION { + transport::send_marker(&stream, ACCEPTED, Duration::from_secs(1)).unwrap(); + } assert!(input.action == Action::Logs); assert_eq!(input.logs.as_ref().unwrap().service, "web"); assert_eq!(input.logs.as_ref().unwrap().tail, 17); @@ -1190,6 +1210,9 @@ fn interactive_handoff_failures_keep_only_the_attempted_session() { let request: Request = transport::read(&mut stream, Duration::from_secs(1), LIMIT).unwrap(); request.validate(&receipt.review).unwrap(); + if request.version == ACCEPTING_VERSION { + transport::send_marker(&stream, ACCEPTED, Duration::from_secs(1)).unwrap(); + } assert_eq!(request.session.as_deref(), Some(SESSION)); if case != "disconnect-before-descriptor" { let (attached, _engine) = UnixStream::pair().unwrap(); @@ -1295,6 +1318,9 @@ fn finite_exec_wire_authenticates_owner_member_and_binary_nonzero_completion() { }; let input: Request = transport::read(&mut stream, Duration::from_secs(2), 4096).unwrap(); input.validate(&receipt.review).unwrap(); + if input.version == ACCEPTING_VERSION { + transport::send_marker(&stream, ACCEPTED, Duration::from_secs(1)).unwrap(); + } assert!(input.action == Action::Exec); assert!(input.logs.is_none()); let selected = input.exec.as_ref().unwrap(); @@ -1382,6 +1408,9 @@ fn finite_one_off_wire_authenticates_owner_member_fresh_container_and_binary_non }; let input: Request = transport::read(&mut stream, Duration::from_secs(2), 4096).unwrap(); input.validate(&receipt.review).unwrap(); + if input.version == ACCEPTING_VERSION { + transport::send_marker(&stream, ACCEPTED, Duration::from_secs(1)).unwrap(); + } assert!(input.action == Action::Run); assert!(input.logs.is_none()); assert!(input.exec.is_none()); @@ -1751,39 +1780,6 @@ fn a_command_left_in_the_backlog_of_an_owner_that_ended_through_cleanup_is_not_s } } -/// HACK-2742 review: the same end without the owner's evidence stays -/// unconfirmed. An owner that accepted and read the request, then dropped the -/// connection unanswered but is still published, may have processed it; an -/// owner that sent part of an answer before it ended did process it. -#[test] -fn an_unanswered_command_without_a_clean_owner_end_stays_unconfirmed() { - for case in ["alive", "partial"] { - let fixture = Fixture::new(); - let receipt = admitted(fixture.receipt()); - let publication = owner::Publication::bind(&fixture.candidate, &receipt.review).unwrap(); - let root = journal::reserve(&fixture.candidate, &receipt).unwrap(); - std::thread::scope(|scope| { - let caller = - scope.spawn(|| exec(&fixture.candidate, RUN, "web", &["true".into()], None)); - let mut stream = accepted(&publication, &receipt.review); - if case == "partial" { - stream.write_all(&[0, 0, 0]).unwrap(); - } - drop(stream); - if case == "partial" { - end_through_cleanup(publication, &root, &receipt); - let error = caller.join().unwrap().err().unwrap(); - assert!(error.cause_code.is_none(), "{case}: {}", error.code); - } else { - let error = caller.join().unwrap().err().unwrap(); - assert!(error.cause_code.is_none(), "{case}: {}", error.code); - let mut publication = publication; - publication.finish().unwrap(); - } - }); - } -} - /// HACK-2742 review: a stale pin whose socket is gone refuses the connect before /// anything is sent, so it answers not-started too. #[test] @@ -1853,12 +1849,73 @@ fn an_interactive_request_left_in_the_backlog_of_an_ended_owner_is_not_started() } } -/// HACK-2742 re-review (L1): dead-owner recovery saves the run removed and -/// archives the publication rather than deleting it, which otherwise looks like -/// the owner's own retirement. While either archive path is present the owner's -/// clean end is not proven, so the unanswered backlog request stays unconfirmed. +/// HACK-2742 review (P1): the not-started proof is the owner's own acceptance of +/// this request, not its retirement. An owner that took and read the request but +/// closed without accepting it never started it, even while it stays published. #[test] -fn a_backlog_request_after_a_recovery_archived_retirement_stays_unconfirmed() { +fn a_command_the_owner_took_but_never_accepted_is_not_started() { + for action in [Action::Exec, Action::Run] { + let fixture = Fixture::new(); + let receipt = admitted(fixture.receipt()); + let mut publication = + owner::Publication::bind(&fixture.candidate, &receipt.review).unwrap(); + journal::reserve(&fixture.candidate, &receipt).unwrap(); + std::thread::scope(|scope| { + let caller = scope.spawn(|| match action { + Action::Exec => exec(&fixture.candidate, RUN, "web", &["true".into()], None), + _ => one_off(&fixture.candidate, RUN, "web", &["true".into()], None), + }); + let (stream, input) = taken(&publication, &receipt.review); + assert_eq!(input.version, ACCEPTING_VERSION); + drop(stream); + let error = caller.join().unwrap().err().unwrap(); + assert_eq!(error.code, "native_graph_foreground"); + assert_eq!( + error.cause_code.as_deref(), + Some("graph_authored_command_not_started") + ); + }); + publication.finish().unwrap(); + } +} + +/// HACK-2742 review (P1): once the owner accepted a command, a missing or partial +/// answer stays unconfirmed, even when the owner then ends through its normal +/// cleanup within moments (the lost-large-reply case Codex found). +#[test] +fn an_accepted_command_without_its_reply_stays_unconfirmed() { + for case in ["closed-then-cleanup", "partial"] { + let fixture = Fixture::new(); + let receipt = admitted(fixture.receipt()); + let publication = owner::Publication::bind(&fixture.candidate, &receipt.review).unwrap(); + let root = journal::reserve(&fixture.candidate, &receipt).unwrap(); + std::thread::scope(|scope| { + let caller = + scope.spawn(|| exec(&fixture.candidate, RUN, "web", &["true".into()], None)); + let mut stream = accepted(&publication, &receipt.review); + if case == "partial" { + stream.write_all(&[0, 0, 0]).unwrap(); + } + drop(stream); + if case == "closed-then-cleanup" { + end_through_cleanup(publication, &root, &receipt); + let error = caller.join().unwrap().err().unwrap(); + assert!(error.cause_code.is_none(), "{case}: {}", error.code); + } else { + let error = caller.join().unwrap().err().unwrap(); + assert!(error.cause_code.is_none(), "{case}: {}", error.code); + let mut publication = publication; + publication.finish().unwrap(); + } + }); + } +} + +/// HACK-2742 review: a backlog request was never accepted, so it is not started +/// however the publication was then retired, including a dead-owner recovery +/// that archives the publication files instead of deleting them. +#[test] +fn a_backlog_request_is_not_started_whatever_retired_the_publication() { for archive in [ "control-feedface.retired.sock", "owner-feedface.retired.json", @@ -1874,71 +1931,148 @@ fn a_backlog_request_after_a_recovery_archived_retirement_stays_unconfirmed() { pending_connection(&publication); end_through_cleanup(publication, &root, &receipt); let error = caller.join().unwrap().err().unwrap(); - // The failing step races the listener's close (write or read), so - // the code differs; only the not-started answer is ruled out. - assert_ne!( - error.code, "graph_authored_command_not_started", + assert_eq!(error.code, "native_graph_foreground", "{archive}"); + assert_eq!( + error.cause_code.as_deref(), + Some("graph_authored_command_not_started"), "{archive}" ); - assert!( - error.cause_code.is_none(), - "{archive}: {:?}", - error.cause_code - ); }); } } -/// HACK-2742 re-review (L2): a retained receipt for this exact session means the -/// owner had admitted it, so even an unanswered close followed by the owner's -/// clean end stays session-correlated (uncertain), never not-started. +/// HACK-2742 review: the interactive request the owner accepted and then left +/// unanswered stays session-correlated (uncertain); the one it took without +/// accepting is not started, with no session, while the owner is still published. +/// A close of this side's own stream by the leash watcher, once the frontend is +/// gone, is never read as the owner's close. #[test] -fn an_unanswered_interactive_request_with_its_session_receipt_stays_uncertain() { - use crate::provider::{ - graph::interactive_exec::Options, - interactive_session::{self, Backend, Binding}, - interactive_terminal::Leash, - }; +fn an_interactive_request_is_not_started_only_without_the_owners_acceptance() { + use crate::provider::{graph::interactive_exec::Options, interactive_terminal::Leash}; use std::os::unix::net::UnixStream; const SESSION: &str = "12345678-abcd-abcd-abcd-123456789abc"; + for case in ["accepted", "not-accepted", "frontend-gone"] { + let fixture = Fixture::new(); + let receipt = admitted(fixture.receipt()); + let mut publication = + owner::Publication::bind(&fixture.candidate, &receipt.review).unwrap(); + journal::reserve(&fixture.candidate, &receipt).unwrap(); + let (input, mut frontend) = UnixStream::pair().unwrap(); + frontend.write_all(&[0; 4]).unwrap(); + let (leash, _) = Leash::receive(input.into()).unwrap(); + let argv = vec!["tool".into()]; + let options = Options { + session: SESSION, + run: RUN, + service: "web", + owner: &receipt.owner, + plan: receipt.review.review_id(), + namespace: receipt.review.scope().namespace, + native: true, + argv: &argv, + workdir: None, + expected_container: None, + expected_generation: None, + }; + std::thread::scope(|scope| { + let caller = + scope.spawn(|| interactive(&fixture.candidate, &options, [43, 91], &leash)); + let error = match case { + "accepted" => { + drop(accepted(&publication, &receipt.review)); + caller.join().unwrap().err().unwrap() + } + "not-accepted" => { + drop(taken(&publication, &receipt.review)); + caller.join().unwrap().err().unwrap() + } + _ => { + // The owner holds the request unanswered while the frontend + // goes away; the watcher then shuts this side down. + let (stream, _) = taken(&publication, &receipt.review); + drop(frontend); + let error = caller.join().unwrap().err().unwrap(); + drop(stream); + error + } + }; + if case == "not-accepted" { + assert_eq!(error.code, "graph_authored_command_not_started"); + assert!(error.session().is_none()); + } else { + assert_ne!(error.code, "graph_authored_command_not_started", "{case}"); + assert_eq!(error.session(), Some(SESSION), "{case}"); + } + }); + publication.finish().unwrap(); + } +} + +/// HACK-2742 review (P1): a command reply at the output cap, 1 MiB on each +/// stream (1,398,104 bytes of base64 each), is beyond the request bound and was +/// lost before any byte was sent. The owner's reply writer now delivers it, and +/// the requester reads it whole. +#[test] +fn a_command_reply_at_the_output_cap_is_delivered() { + use base64::Engine as _; let fixture = Fixture::new(); - let receipt = admitted(fixture.receipt()); - let publication = owner::Publication::bind(&fixture.candidate, &receipt.review).unwrap(); - let root = journal::reserve(&fixture.candidate, &receipt).unwrap(); - let binding = Binding { - backend: Backend::Authored, - namespace: "a".repeat(64), + let mut receipt = fixture.receipt(); + receipt.phase = Phase::ReadyObserved; + for (index, resource) in receipt.resources.values_mut().enumerate() { + resource.id = Some(format!("{:064x}", index + 1)); + resource.phase = if resource.kind == Kind::Container { + "started" + } else { + "created" + } + .into(); + } + let stream_at_cap = base64::engine::general_purpose::STANDARD.encode(vec![0xA5; 1024 * 1024]); + assert_eq!(stream_at_cap.len(), 1_398_104); + let reply = Reply { + version: 2, + kind: ReplyKind::NativeGraphControlReply, run: RUN.into(), - owner: "c".repeat(32), - boot: "00000000-0000-4000-8000-000000000001".into(), - container: "d".repeat(64), - generation: "2026-11-12T01:02:03.123456789Z".into(), - service: "web".into(), - }; - drop(interactive_session::admit(&fixture.candidate, binding, SESSION).unwrap()); - let (input, mut frontend) = UnixStream::pair().unwrap(); - frontend.write_all(&[0; 4]).unwrap(); - let (leash, _) = Leash::receive(input.into()).unwrap(); - let argv = vec!["tool".into()]; - let options = Options { - session: SESSION, - run: RUN, - service: "web", - owner: &receipt.owner, - plan: receipt.review.review_id(), - namespace: receipt.review.scope().namespace, - native: true, - argv: &argv, - workdir: None, - expected_container: None, - expected_generation: None, + review: receipt.review.review_id().into(), + result: Outcome::Exec { + exec: runtime::ServiceExec { + receipt: receipt.clone(), + service: "web".into(), + container: receipt.resources["container:web"].id.clone().unwrap(), + exit_code: 0, + stdout_base64: stream_at_cap.clone(), + stderr_base64: stream_at_cap.clone(), + truncated: true, + }, + }, }; + // The request bound cannot carry it: this was the lost reply. + let (mut small, _peer) = std::os::unix::net::UnixStream::pair().unwrap(); + assert!(transport::write(&mut small, &reply, Duration::from_secs(1)).is_err()); + + let mut publication = owner::Publication::bind(&fixture.candidate, &receipt.review).unwrap(); + journal::reserve(&fixture.candidate, &receipt).unwrap(); std::thread::scope(|scope| { - let caller = scope.spawn(|| interactive(&fixture.candidate, &options, [43, 91], &leash)); - pending_connection(&publication); - end_through_cleanup(publication, &root, &receipt); - let error = caller.join().unwrap().err().unwrap(); - assert_ne!(error.code, "graph_authored_command_not_started"); - assert_eq!(error.session(), Some(SESSION)); + let caller = scope.spawn(|| exec(&fixture.candidate, RUN, "web", &["true".into()], None)); + let mut stream = accepted(&publication, &receipt.review); + let selected = runtime::ExecSelection { + service: "web".into(), + argv: vec!["true".into()], + workdir: None, + }; + reply + .validate(&receipt, Action::Exec, None, Some(&selected), None) + .unwrap(); + deliver_reply(&mut stream, &reply, Action::Exec).unwrap(); + let value = caller.join().unwrap().unwrap(); + assert_eq!( + value["result"]["exec"]["stdout_base64"], + stream_at_cap.as_str() + ); + assert_eq!( + value["result"]["exec"]["stderr_base64"], + stream_at_cap.as_str() + ); }); + publication.finish().unwrap(); } diff --git a/packages/runtime-core/src/provider/interactive_handoff.rs b/packages/runtime-core/src/provider/interactive_handoff.rs index 6a23bcc363..26a5f38500 100644 --- a/packages/runtime-core/src/provider/interactive_handoff.rs +++ b/packages/runtime-core/src/provider/interactive_handoff.rs @@ -164,16 +164,6 @@ fn copied_rights(bytes: &[u8], copied: usize) -> (Vec, bool) { (descriptors, invalid) } -/// The code of a handoff whose peer closed before it sent a single byte. -pub(super) const CLOSED_UNANSWERED: &str = "interactive_handoff_closed"; - -fn closed_unanswered() -> CandidateError { - CandidateError::new( - CLOSED_UNANSWERED, - "The interactive owner closed the connection before it answered.", - ) -} - /// Received descriptors are owned immediately, including on truncated/invalid /// messages. No descriptor is exposed until its count, type and CLOEXEC are valid. /// Darwin may install additional rights that it does not copy out on truncation. @@ -213,23 +203,7 @@ pub(super) fn receive( continue; } if count < 0 { - // HACK-2742 review: a reset before anything was received is told - // apart, so the caller can prove (with the owner's own evidence) - // that nothing was processed. - return Err( - if matches!( - io::Error::last_os_error().raw_os_error(), - Some(libc::ECONNRESET | libc::ENOTCONN) - ) { - closed_unanswered() - } else { - refused() - }, - ); - } - if count == 0 && message.msg_controllen == 0 { - // The peer closed before it sent a byte, with no descriptor. - return Err(closed_unanswered()); + return Err(refused()); } // SAFETY: ancillary is initialized storage of this exact byte size; // the parser borrows it and never reads beyond the returned length. From a3cd4b456142675ef1350b7f5dd3717f0f21e35b Mon Sep 17 00:00:00 2001 From: Dimitri Kennedy <344842+roodboi@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:55:20 -0500 Subject: [PATCH 10/11] fix(native): send version-3 commands only to owners that advertise acceptance (HACK-2742) Protocol review M1: an owner started by an earlier prerelease validates `version == 2` and closes on anything else, so a new requester's version-3 command against it was refused as "not started" for every authored exec and run until the project restarted. The owner now publishes record version 5, the same session-qualified record as version 4, which advertises acceptance. A requester sends a version-3 command, and waits for the acceptance byte, only to such an owner. Any older owner gets version 2 exactly as before: its commands run, and only the new not-started proof is missing (a failure after the send stays unconfirmed). Dead-owner recovery reads version 5 like version 4. Review lows: - The reply bound's compile-time check uses the receipt maximum (`state::MAX_RECEIPT_BYTES`, 1 MiB) plus an envelope margin. - The owner loop's per-request step is now `Loop::answer`, unchanged in behaviour, so one real request can be driven through it. A test holds the provider lease as another project's stop, sends a version-3 exec and run, and shows that when the acceptance byte arrives the lease is still the stop's, the journal root (state and one-off records) is unchanged and the owner is still waiting; its pending signal then ends the wait and it answers not started. Tests: an owner from before the upgrade (record version 4) receives version 2 and still runs exec and run, and gets no not-started proof. Model: `CommandAccept.tla` covers the acceptance step. The positive control holds that "not started" is reported only without the byte, and is true, and that every failure after it is unconfirmed. The old retirement rule and a missing leash check each violate an invariant. Row 4 and Codex's case are reachable. Co-Authored-By: Claude Opus 5.5 --- docs/guides/native-candidate.md | 2 +- .../src/provider/graph/native/foreground.rs | 154 +++++++++--- .../provider/graph/native/foreground/owner.rs | 34 ++- .../provider/graph/native/foreground/tests.rs | 238 ++++++++++++++++++ packages/runtime-core/src/provider/state.rs | 3 +- scripts/lib/tla-runtime-models.ts | 56 +++++ .../tla/native-command-lease/COVERAGE.md | 48 ++++ .../native-command-lease/CommandAccept.tla | 124 +++++++++ .../accept-backlog-reach.cfg | 4 + .../accept-lost-reply-reach.cfg | 4 + .../accept-no-leash-check.cfg | 4 + .../accept-old-retirement.cfg | 4 + .../native-command-lease/accept-positive.cfg | 4 + 13 files changed, 633 insertions(+), 46 deletions(-) create mode 100644 tests/models/tla/native-command-lease/CommandAccept.tla create mode 100644 tests/models/tla/native-command-lease/accept-backlog-reach.cfg create mode 100644 tests/models/tla/native-command-lease/accept-lost-reply-reach.cfg create mode 100644 tests/models/tla/native-command-lease/accept-no-leash-check.cfg create mode 100644 tests/models/tla/native-command-lease/accept-old-retirement.cfg create mode 100644 tests/models/tla/native-command-lease/accept-positive.cfg diff --git a/docs/guides/native-candidate.md b/docs/guides/native-candidate.md index 925bbaf443..8e7189a38b 100644 --- a/docs/guides/native-candidate.md +++ b/docs/guides/native-candidate.md @@ -5489,7 +5489,7 @@ and the command says `nothing ran` with `Holder: unavailable.` and `Retry hack e once the holder finishes.` A pending Ctrl-C of the owner, its `hack down`, or a changed owner publication ends the owner's wait at once; the owner then answers `graph_authored_command_not_started`, and the command says it did not start, that -nothing ran, and to check `hack ps` and retry once the project is up. The command says the same when the owner exits while the command is still waiting for the lock, for example during the project's own `hack down`: nothing has been sent at that point. The owner accepts each command with one byte before it does anything for it, and it drops a command it cannot accept. So the command also says nothing ran when the owner closed the connection without even that byte: for example, the request reached the owner's queue but the owner ended through that `hack down` without taking it, or the owner refused the request. Once the owner has accepted a command, every failure keeps "unconfirmed". A command's answer carries up to 1 MiB of output on each stream. A project started by an earlier prerelease does not accept commands this way: restart it after you upgrade. Until then, an authored exec or run against it says nothing ran. Any other +nothing ran, and to check `hack ps` and retry once the project is up. The command says the same when the owner exits while the command is still waiting for the lock, for example during the project's own `hack down`: nothing has been sent at that point. The owner accepts each command with one byte before it does anything for it, and it drops a command it cannot accept. So the command also says nothing ran when the owner closed the connection without even that byte: for example, the request reached the owner's queue but the owner ended through that `hack down` without taking it, or the owner refused the request. Once the owner has accepted a command, every failure keeps "unconfirmed". A command's answer carries up to 1 MiB of output on each stream. A project started by an earlier prerelease keeps working after you upgrade: its owner does not advertise acceptance, so commands are sent to it as before, without this proof, and a failure after sending stays unconfirmed. Any other authored failure keeps its report, "completion is unconfirmed" included. A compose project's one-off `run` is answered by its owner, which waits at most 15 seconds on its only loop, within one 15-second bound for its selection and admission before its diff --git a/packages/runtime-core/src/provider/graph/native/foreground.rs b/packages/runtime-core/src/provider/graph/native/foreground.rs index f1e19f70f5..396120df8c 100644 --- a/packages/runtime-core/src/provider/graph/native/foreground.rs +++ b/packages/runtime-core/src/provider/graph/native/foreground.rs @@ -33,7 +33,9 @@ fn command_not_sent(_error: CandidateError) -> CandidateError { /// The request version of a command (exec, interactive exec, one-off run) that /// the owner accepts before it starts (HACK-2742 review). Status, observe, logs /// and cleanup keep version 2, as does any request from an older requester. An -/// older owner refuses this version unprocessed, by closing the connection. +/// older owner would refuse this version by closing, so a requester sends it +/// only to an owner whose publication advertises acceptance +/// (`owner::ACCEPTING_RECORD_VERSION`); any other owner gets version 2, as before. const ACCEPTING_VERSION: u32 = 3; /// The byte an owner sends for an [`ACCEPTING_VERSION`] command after it read @@ -47,11 +49,15 @@ const ACCEPTING_VERSION: u32 = 3; const ACCEPTED: u8 = 0xAC; /// A command reply: two streams of up to 1 MiB in base64 (1,398,104 bytes each, -/// `runtime::exec::valid_stream`) with a bounded receipt in its envelope. The -/// request bound used by [`transport::write`] is smaller, and an oversized reply -/// would fail to serialize with nothing sent (HACK-2742 review). +/// `runtime::exec::valid_stream`) with one receipt (at most +/// `state::MAX_RECEIPT_BYTES`) and a small envelope. The request bound used by +/// [`transport::write`] is smaller, and an oversized reply would fail to +/// serialize with nothing sent (HACK-2742 review). const COMMAND_REPLY_LIMIT: usize = 4 * 1024 * 1024; -const _: () = assert!(2 * 1_398_104 + 4 * LIMIT < COMMAND_REPLY_LIMIT); +const _: () = assert!( + 2 * 1_398_104 + crate::provider::state::MAX_RECEIPT_BYTES as usize + 64 * 1024 + < COMMAND_REPLY_LIMIT +); /// Write the owner's reply. A command reply has its own bound. A failed write /// leaves the requester with an accepted request and no answer, which it reports @@ -568,16 +574,75 @@ pub fn serve_with_storage_tool( } _ => {} } - let Some(mut stream) = publication.accept()? else { + let Some(stream) = publication.accept()? else { continue; }; + let served = Loop { + candidate, + review: &review, + run: &run, + receipt: &receipt, + publication: &publication, + read_pin: &read_pin, + pending: &|| signals.pending(), + clean: &clean, + }; + if let Answered::Cleaned { mut stream, reply } = served.answer(stream)? { + // Retire before writing on the retained authenticated stream. Clients + // verify both absent publication paths and the exact durable Removed journal. + publication.finish()?; + let _ = deliver_reply(&mut stream, &reply, Action::Cleanup); + let Outcome::Cleaned { receipt } = reply.result else { + return Err(refused()); + }; + return Ok(receipt); + } + } +} + +/// What the owner's loop answers one request with (HACK-2742 review): its +/// context is borrowed from the loop, so one real request can be driven +/// through it in a test. +struct Loop<'a> { + candidate: &'a Candidate, + review: &'a native_input::Review, + run: &'a str, + receipt: &'a Receipt, + publication: &'a owner::Publication, + read_pin: &'a selection::ReadPin, + /// A pending signal of the owner (its Ctrl-C or `hack down`). + pending: &'a dyn Fn() -> bool, + clean: &'a dyn Fn() -> Result, +} +enum Answered { + /// The request was answered or dropped; serve the next one. + Next, + /// A cleanup completed: the loop retires the publication, then replies. + Cleaned { + stream: std::os::unix::net::UnixStream, + reply: Box, + }, +} +impl Loop<'_> { + fn answer( + &self, + mut stream: std::os::unix::net::UnixStream, + ) -> Result { + let (candidate, receipt, run, publication, read_pin, pending) = ( + self.candidate, + self.receipt, + self.run, + self.publication, + self.read_pin, + self.pending, + ); let request: Request = match transport::read(&mut stream, Duration::from_secs(5), 512 * 1024) { Ok(request) => request, - Err(_) => continue, + Err(_) => return Ok(Answered::Next), }; - if request.validate(&review).is_err() { - continue; + if request.validate(self.review).is_err() { + return Ok(Answered::Next); } publication.verify()?; // HACK-2742 review: accept the command before any effect. If the byte @@ -585,7 +650,7 @@ pub fn serve_with_storage_tool( if request.version == ACCEPTING_VERSION && transport::send_marker(&stream, ACCEPTED, Duration::from_secs(5)).is_err() { - continue; + return Ok(Answered::Next); } let mut attached = None; let result = match request.action { @@ -594,14 +659,14 @@ pub fn serve_with_storage_tool( let client = transport::ClientWatch::half_closed(&stream)?; let check = || { publication.verify()?; - if signals.pending() || client.disconnected() { + if pending() || client.disconnected() { return Err(refused()); } read_pin.verify(candidate) }; match runtime::interactive_exec( candidate, - &receipt, + receipt, selected, request.console_size.ok_or_else(refused)?, request.session.as_deref().ok_or_else(refused)?, @@ -620,33 +685,33 @@ pub fn serve_with_storage_tool( Err(error) => Err(error), } } - Action::Status => inspect(candidate, &run).map(|snapshot| Outcome::Status { snapshot }), + Action::Status => inspect(candidate, run).map(|snapshot| Outcome::Status { snapshot }), Action::Observe => { - runtime::status(candidate, &run).map(|snapshot| Outcome::Observed { snapshot }) + runtime::status(candidate, run).map(|snapshot| Outcome::Observed { snapshot }) } - Action::Cleanup => clean().map(|receipt| Outcome::Cleaned { receipt }), + Action::Cleanup => (self.clean)().map(|receipt| Outcome::Cleaned { receipt }), Action::Exec => { let selected = request.exec.as_ref().ok_or_else(refused)?; let check = || { publication.verify()?; - if signals.pending() { + if pending() { return Err(refused()); } read_pin.verify(candidate) }; - runtime::service_exec(candidate, &receipt, selected, &check) + runtime::service_exec(candidate, receipt, selected, &check) .map(|exec| Outcome::Exec { exec }) } Action::Run => { let selected = request.one_off.as_ref().ok_or_else(refused)?; let check = || { publication.verify()?; - if signals.pending() { + if pending() { return Err(refused()); } read_pin.verify(candidate) }; - runtime::service_run(candidate, &receipt, selected, &check) + runtime::service_run(candidate, receipt, selected, &check) .map(|one_off| Outcome::OneOff { one_off }) } Action::Logs => { @@ -655,7 +720,7 @@ pub fn serve_with_storage_tool( publication.verify()?; read_pin.verify(candidate) }; - runtime::logs(candidate, &receipt, &logs.service, logs.tail, &check) + runtime::logs(candidate, receipt, &logs.service, logs.tail, &check) .map(|logs| Outcome::Logs { logs }) } }; @@ -667,26 +732,22 @@ pub fn serve_with_storage_tool( let reply = Reply { version: 2, kind: ReplyKind::NativeGraphControlReply, - run: run.clone(), - review: review.review_id().into(), + run: run.to_owned(), + review: self.review.review_id().into(), result, }; reply.validate( - &receipt, + receipt, request.action, request.logs.as_ref(), request.exec.as_ref(), request.one_off.as_ref(), )?; if cleaned { - // Retire before writing on the retained authenticated stream. Clients - // verify both absent publication paths and the exact durable Removed journal. - publication.finish()?; - let _ = deliver_reply(&mut stream, &reply, request.action); - let Outcome::Cleaned { receipt } = reply.result else { - return Err(refused()); - }; - return Ok(receipt); + return Ok(Answered::Cleaned { + stream, + reply: Box::new(reply), + }); } if request.action == Action::InteractiveExec { // The connected stream is handed over before the bound reply; its @@ -709,10 +770,11 @@ pub fn serve_with_storage_tool( ) .is_err() { - continue; + return Ok(Answered::Next); } } let _ = deliver_reply(&mut stream, &reply, request.action); + Ok(Answered::Next) } } @@ -847,8 +909,9 @@ pub(in crate::provider) fn interactive( // no longer connects, and nothing was sent. let mut stream = pin.connect().map_err(interactive_not_sent)?; let _lifetime = leash.watch_control(&stream).map_err(interactive_not_sent)?; + let accepting = pin.accepts_commands(); let input = Request { - version: ACCEPTING_VERSION, + version: if accepting { ACCEPTING_VERSION } else { 2 }, kind: RequestKind::NativeGraphControl, run: run.into(), review: review.review_id().into(), @@ -871,13 +934,19 @@ pub(in crate::provider) fn interactive( // shuts it down only once the frontend is gone, and that loss is permanent, // so a leash that still holds after the close proves the close was the // owner's. A write failure alone proves nothing until that answer arrives. - match owner_accepted(&stream, deadline) { - Ok(true) => {} - Ok(false) if leash.check().is_ok() => { - return Err(interactive_not_sent(written.err().unwrap_or_else(refused))); + // An owner that does not advertise acceptance (started before the upgrade) + // gets version 2 as before, and a failure after the write stays uncertain. + if accepting { + match owner_accepted(&stream, deadline) { + Ok(true) => {} + Ok(false) if leash.check().is_ok() => { + return Err(interactive_not_sent(written.err().unwrap_or_else(refused))); + } + Ok(false) => return Err(uncertain(written.err().unwrap_or_else(refused))), + Err(error) => return Err(uncertain(written.err().unwrap_or(error))), } - Ok(false) => return Err(uncertain(written.err().unwrap_or_else(refused))), - Err(error) => return Err(uncertain(written.err().unwrap_or(error))), + } else { + written.map_err(uncertain)?; } let descriptor = crate::provider::interactive_handoff::receive(&stream, deadline).map_err(uncertain)?; @@ -932,8 +1001,11 @@ fn request_selected( let review = pin.review(); let expected = journal::read_control(candidate, review).map_err(not_sent)?; let mut stream = pin.connect().map_err(not_sent)?; + // Only an owner that advertises acceptance gets the version-3 command and + // its not-started proof; an older owner serves version 2 as before. + let accepting = command && pin.accepts_commands(); let input = Request { - version: if command { ACCEPTING_VERSION } else { 2 }, + version: if accepting { ACCEPTING_VERSION } else { 2 }, kind: RequestKind::NativeGraphControl, run: run.into(), review: review.review_id().into(), @@ -951,7 +1023,7 @@ fn request_selected( Duration::from_secs(30) }; let started = Instant::now(); - if command { + if accepting { // HACK-2742 review (VM row 4): the owner may have left this connection in // its listen backlog and ended, or refused the request, without taking // it. It accepts a command before any effect, so a close with no byte at diff --git a/packages/runtime-core/src/provider/graph/native/foreground/owner.rs b/packages/runtime-core/src/provider/graph/native/foreground/owner.rs index aa7abf1391..e599b3d414 100644 --- a/packages/runtime-core/src/provider/graph/native/foreground/owner.rs +++ b/packages/runtime-core/src/provider/graph/native/foreground/owner.rs @@ -64,6 +64,13 @@ impl BootQualifiedRecord { ) } } +/// The owner record version that advertises command acceptance (HACK-2742 +/// review): the same session-qualified record as version 4, from an owner that +/// accepts version-3 commands with its acceptance byte. A requester sends those +/// only to such an owner; an owner of version 4 or earlier gets the version-2 +/// commands it serves, without the not-started proof. +pub(super) const ACCEPTING_RECORD_VERSION: u32 = 5; +const ACCEPTING_RECORD_VERSION_U64: u64 = ACCEPTING_RECORD_VERSION as u64; /// Version4 has no calendar qualifier: exact process incarnation remains a separate fence. #[derive(Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -121,7 +128,7 @@ fn decode(bytes: &[u8]) -> Result<(Record, Option), CandidateError> { } Ok(record.into_record()) } - Some(4) => { + Some(4 | ACCEPTING_RECORD_VERSION_U64) => { let record: SessionQualifiedRecord = serde_json::from_slice(bytes).map_err(|_| refused())?; if record.process.start_micros == 0 { @@ -291,6 +298,10 @@ impl Pin { pub(super) fn review(&self) -> &native_input::Review { &self.record.review } + /// Whether this owner advertises command acceptance in its publication. + pub(super) fn accepts_commands(&self) -> bool { + self.record.version == ACCEPTING_RECORD_VERSION + } /// The caller already authenticated its retained connection before the owner /// retired. Absence grants no new connection, process or cleanup authority. pub(super) fn verify_retired(&self) -> Result<(), CandidateError> { @@ -387,7 +398,7 @@ impl RecoverySelection { .validate(record.review.scope()) .map_err(|_| refused())?; // SAFETY: geteuid has no preconditions; private state remains same-user. - if !matches!(record.version, 3 | 4) + if !matches!(record.version, 3 | 4 | ACCEPTING_RECORD_VERSION) || record.candidate != candidate.checkout || record.review.scope().run != run || record.process.uid != unsafe { libc::geteuid() } @@ -574,6 +585,23 @@ impl Publication { pub(super) fn bind( candidate: &Candidate, review: &native_input::Review, + ) -> Result { + Self::bind_as(candidate, review, ACCEPTING_RECORD_VERSION) + } + /// An owner as an earlier prerelease published it (record version 4): it + /// does not accept commands (HACK-2742 review), so requesters send it the + /// version-2 commands it serves. + #[cfg(test)] + pub(super) fn bind_legacy( + candidate: &Candidate, + review: &native_input::Review, + ) -> Result { + Self::bind_as(candidate, review, 4) + } + fn bind_as( + candidate: &Candidate, + review: &native_input::Review, + version: u32, ) -> Result { review.validate(review.scope()).map_err(|_| refused())?; let host_boot_uuid = host_boot::read()?; @@ -593,7 +621,7 @@ impl Publication { .map_err(|_| refused())?; listener.set_nonblocking(true).map_err(|_| refused())?; let record = SessionQualifiedRecord { - version: 4, + version, kind: Kind::NativeGraphOwner, candidate: candidate.checkout.clone(), review: review.clone(), diff --git a/packages/runtime-core/src/provider/graph/native/foreground/tests.rs b/packages/runtime-core/src/provider/graph/native/foreground/tests.rs index 0b20582999..fbafc58792 100644 --- a/packages/runtime-core/src/provider/graph/native/foreground/tests.rs +++ b/packages/runtime-core/src/provider/graph/native/foreground/tests.rs @@ -2076,3 +2076,241 @@ fn a_command_reply_at_the_output_cap_is_delivered() { }); publication.finish().unwrap(); } + +/// A ready receipt whose containers have engine ids, as the finite wire tests use. +fn ready_receipt(fixture: &Fixture) -> Receipt { + let mut receipt = fixture.receipt(); + receipt.phase = Phase::ReadyObserved; + for (index, resource) in receipt.resources.values_mut().enumerate() { + resource.id = Some(format!("{:064x}", index + 1)); + resource.phase = if resource.kind == Kind::Container { + "started" + } else { + "created" + } + .into(); + } + receipt +} + +/// HACK-2742 review (M1): an owner started by an earlier prerelease publishes +/// record version 4 and serves only version-2 commands. The requester sends it +/// version 2 with no acceptance byte expected, so exec and run work as before. +#[test] +fn an_owner_from_before_the_upgrade_still_runs_exec_and_run() { + for action in [Action::Exec, Action::Run] { + let fixture = Fixture::new(); + let receipt = ready_receipt(&fixture); + let mut publication = + owner::Publication::bind_legacy(&fixture.candidate, &receipt.review).unwrap(); + journal::reserve(&fixture.candidate, &receipt).unwrap(); + assert!( + !owner::Pin::load(&fixture.candidate, RUN) + .unwrap() + .accepts_commands() + ); + std::thread::scope(|scope| { + let caller = scope.spawn(|| match action { + Action::Exec => exec(&fixture.candidate, RUN, "web", &["true".into()], None), + _ => one_off(&fixture.candidate, RUN, "web", &["true".into()], None), + }); + let (mut stream, input) = taken(&publication, &receipt.review); + // The version an old owner validates: it would close on any other. + assert_eq!(input.version, 2); + let container = receipt.resources["container:web"].id.clone().unwrap(); + let result = match action { + Action::Exec => Outcome::Exec { + exec: runtime::ServiceExec { + receipt: receipt.clone(), + service: "web".into(), + container, + exit_code: 17, + stdout_base64: "AP9B".into(), + stderr_base64: String::new(), + truncated: false, + }, + }, + _ => Outcome::OneOff { + one_off: runtime::ServiceRun { + receipt: receipt.clone(), + service: "web".into(), + member: container, + container: "f".repeat(64), + name: format!("hkn-{RUN}-oneoff-{}", "a".repeat(32)), + exit_code: 17, + stdout_base64: "AP9B".into(), + stderr_base64: String::new(), + truncated: false, + }, + }, + }; + let reply = Reply { + version: 2, + kind: ReplyKind::NativeGraphControlReply, + run: RUN.into(), + review: receipt.review.review_id().into(), + result, + }; + // An old owner wrote replies with the request bound. + transport::write(&mut stream, &reply, Duration::from_secs(2)).unwrap(); + let value = caller.join().unwrap().unwrap(); + let key = if action == Action::Exec { + "exec" + } else { + "one_off" + }; + assert_eq!(value["result"][key]["exit_code"], 17, "{key}"); + }); + publication.finish().unwrap(); + } +} + +/// HACK-2742 review (M1): against an owner from before the upgrade, a close +/// after the write proves nothing, so it stays unconfirmed (it was not started +/// before the fix either way; only the new proof is missing). +#[test] +fn an_owner_from_before_the_upgrade_gets_no_not_started_proof() { + let fixture = Fixture::new(); + let receipt = admitted(fixture.receipt()); + let mut publication = + owner::Publication::bind_legacy(&fixture.candidate, &receipt.review).unwrap(); + journal::reserve(&fixture.candidate, &receipt).unwrap(); + std::thread::scope(|scope| { + let caller = scope.spawn(|| exec(&fixture.candidate, RUN, "web", &["true".into()], None)); + drop(taken(&publication, &receipt.review)); + let error = caller.join().unwrap().err().unwrap(); + assert!(error.cause_code.is_none(), "{}", error.code); + }); + publication.finish().unwrap(); +} + +/// HACK-2742 review (L2): the real per-request step of the owner's loop sends the +/// acceptance byte before any effect. While another project's stop holds the +/// provider lease, the requester receives the byte; at that moment the owner has +/// not taken the lease, not touched the journal and written no one-off record, +/// and it is still waiting. Its pending signal then ends the wait, and it +/// answers not started. +#[test] +fn the_owner_loop_accepts_a_command_before_any_effect() { + use crate::provider::engine::command_lease_tests::hold_lease_as_project_stop; + use std::sync::atomic::{AtomicBool, Ordering}; + for action in [Action::Exec, Action::Run] { + let fixture = Fixture::new(); + let receipt = ready_receipt(&fixture); + let publication = owner::Publication::bind(&fixture.candidate, &receipt.review).unwrap(); + let root = journal::reserve(&fixture.candidate, &receipt).unwrap(); + journal::save(&root, &receipt).unwrap(); + // The journal root (its `state.json` and any `one-off` record directory). + let snapshot = || { + let mut names: Vec = fs::read_dir(&root) + .unwrap() + .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + names.sort(); + (names, fs::read(root.join("state.json")).unwrap()) + }; + let journal_before = snapshot(); + let prepared = fixture.prepared(); + let read_pin = prepared.read_pin(); + // A running pool, so the owner's engine reaches its lease wait (without + // one it refuses `runtime_not_running` first). + let mut pool = state::Owner::create( + &fixture.candidate, + crate::provider::Profile::Development, + None, + Default::default(), + ) + .unwrap(); + let pool_alias = pool.short_home.clone(); + pool.phase = "running".into(); + pool.guest_boot_id = Some("a1234567-1234-4123-8123-a12345678901".into()); + pool.save(&fixture.candidate).unwrap(); + let (release, holder) = + hold_lease_as_project_stop(&fixture.candidate, Duration::from_secs(30)); + let signalled = AtomicBool::new(false); + let pending = || signalled.load(Ordering::Acquire); + let clean = || Err(refused()); + let review = receipt.review.clone(); + std::thread::scope(|scope| { + let owner = scope.spawn(|| { + let served = Loop { + candidate: &fixture.candidate, + review: &review, + run: RUN, + receipt: &receipt, + publication: &publication, + read_pin: &read_pin, + pending: &pending, + clean: &clean, + }; + let deadline = Instant::now() + Duration::from_secs(5); + let stream = loop { + if let Some(stream) = publication.accept().unwrap() { + break stream; + } + assert!(Instant::now() < deadline); + std::thread::sleep(Duration::from_millis(5)); + }; + matches!(served.answer(stream), Ok(Answered::Next)) + }); + let pin = owner::Pin::load(&fixture.candidate, RUN).unwrap(); + assert!(pin.accepts_commands()); + let mut stream = pin.connect().unwrap(); + let selected = runtime::ExecSelection { + service: "web".into(), + argv: vec!["true".into()], + workdir: None, + }; + let request = Request { + version: ACCEPTING_VERSION, + kind: RequestKind::NativeGraphControl, + run: RUN.into(), + review: review.review_id().into(), + action, + console_size: None, + session: None, + logs: None, + exec: (action == Action::Exec).then(|| selected.clone()), + one_off: (action == Action::Run).then(|| runtime::RunSelection { + service: "web".into(), + argv: vec!["true".into()], + workdir: None, + }), + }; + transport::write(&mut stream, &request, Duration::from_secs(2)).unwrap(); + let marker = + transport::receive_marker(&stream, Instant::now() + Duration::from_secs(5)) + .unwrap(); + assert_eq!(marker, Some(ACCEPTED)); + // Nothing effectful yet: the lease is still the stop's (the holder has + // not been released), the journal is unchanged, there is no one-off + // record, and the owner has not answered. + assert!(!holder.is_finished()); + assert_eq!(snapshot(), journal_before); + assert!(!root.join("one-off").exists()); + std::thread::sleep(Duration::from_millis(300)); + assert!( + !owner.is_finished(), + "the owner answered before its lease wait" + ); + // Its pending signal ends the wait before acquisition: not started. + signalled.store(true, Ordering::Release); + let reply: Reply = + transport::read(&mut stream, Duration::from_secs(5), COMMAND_REPLY_LIMIT).unwrap(); + assert!(owner.join().unwrap()); + match reply.result { + Outcome::Refused { code, .. } => { + assert_eq!(code, "graph_authored_command_not_started", "{code}") + } + _ => panic!("expected the owner's not-started refusal"), + } + }); + release.send(()).unwrap(); + holder.join().unwrap(); + let mut publication = publication; + publication.finish().unwrap(); + if fs::read_link(&pool_alias).is_ok_and(|target| target.starts_with(&fixture.root)) { + fs::remove_file(&pool_alias).unwrap(); + } + } +} diff --git a/packages/runtime-core/src/provider/state.rs b/packages/runtime-core/src/provider/state.rs index b68a61cd4f..19e25c72bc 100644 --- a/packages/runtime-core/src/provider/state.rs +++ b/packages/runtime-core/src/provider/state.rs @@ -8,7 +8,8 @@ use std::os::unix::fs::{DirBuilderExt, FileExt, MetadataExt, OpenOptionsExt}; use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; -const MAX_RECEIPT_BYTES: u64 = 1024 * 1024; +/// The largest receipt `read_bounded` reads back from private state. +pub(crate) const MAX_RECEIPT_BYTES: u64 = 1024 * 1024; pub fn io(error: std::io::Error) -> CandidateError { CandidateError::new("provider_state", error.to_string()) diff --git a/scripts/lib/tla-runtime-models.ts b/scripts/lib/tla-runtime-models.ts index c25b5e1c34..903d89988a 100644 --- a/scripts/lib/tla-runtime-models.ts +++ b/scripts/lib/tla-runtime-models.ts @@ -22,6 +22,7 @@ type ModelContract = { | "PreReady" | "RetainedGuard" | "ExecStopWait" + | "CommandAccept" | "ServingExit"; readonly negative: boolean; readonly states?: number; @@ -2414,6 +2415,61 @@ const contracts: readonly ModelContract[] = [ invariant: "NeverCancelled", fields: ["cancelled = TRUE", 'report = "not-run"', "sent = FALSE"], }, + { + // HACK-2742 review (Codex P1): the owner accepts each authored command + // with one byte before any effect. "not started" only without that + // byte, the command never began, and after it every failure is + // "unconfirmed". + name: "accept-positive", + module: "CommandAccept", + negative: false, + states: 68, + }, + { + // The rule before the fix, "closed with no byte of answer, then the + // owner's own cleanup": a command whose reply was lost after it ran, + // followed by the owner's `hack down`, is reported as not started. + name: "accept-old-retirement", + module: "CommandAccept", + negative: true, + invariant: "NothingRanWhenNotStarted", + fields: [ + 'report = "not-started"', + "started = TRUE", + 'owner = "cleanup"', + ], + }, + { + // Without the interactive leash check, this side's own shutdown hides + // a queued accept byte and reads as the owner's close. + name: "accept-no-leash-check", + module: "CommandAccept", + negative: true, + invariant: "NotStartedOnlyWithoutAccept", + fields: ['report = "not-started"', "accepted = TRUE", "local = TRUE"], + }, + { + // VM row 4 stays reachable: a backlog request the owner never took, + // then its cleanup, is reported as not started. + name: "accept-backlog-reach", + module: "CommandAccept", + negative: true, + invariant: "NeverBacklogNotStarted", + fields: ['report = "not-started"', "took = FALSE", 'owner = "cleanup"'], + }, + { + // Codex's case is reachable and reported as unconfirmed. + name: "accept-lost-reply-reach", + module: "CommandAccept", + negative: true, + invariant: "NeverLostReplyUnconfirmed", + fields: [ + 'report = "unconfirmed"', + "started = TRUE", + "replied = FALSE", + 'owner = "cleanup"', + ], + }, ], }, { diff --git a/tests/models/tla/native-command-lease/COVERAGE.md b/tests/models/tla/native-command-lease/COVERAGE.md index 4b8ae17803..5d33bc9ae2 100644 --- a/tests/models/tla/native-command-lease/COVERAGE.md +++ b/tests/models/tla/native-command-lease/COVERAGE.md @@ -289,6 +289,54 @@ not started within 2 s; a later failure keeps its code), messages, and a PTY case each for a lease refusal and a not-started refusal), `native-runtime-client` (the new causes pass the closed filter). +## The owner's acceptance of a command (HACK-2742 review) + +Codex found that "not started" after the request was sent rested on the +owner's retirement: a connection closed with no byte of answer, then the +owner's own cleanup. A command that ran but whose reply was lost (a reply +past the request bound failed to serialize with nothing sent), followed by the +owner's `hack down`, matched it. The owner now accepts each command (request +version 3) with one byte after it read and validated the request and before +any effect, and drops a command whose byte it cannot queue. The requester +says not started (`graph_authored_command_not_started`) only when the +connection closed with no byte at all. The interactive requester also needs +its frontend leash to hold, because its own watcher's shutdown can hide a +queued byte. The owner advertises acceptance in its publication (owner record +version 5); a requester sends version 3 only to such an owner, and an owner +started by an earlier prerelease gets version 2 as before, without the proof. + +`CommandAccept.tla` models one command on one connection: the owner takes, +drops, accepts, starts, replies or loses the reply, fails, or ends between +requests through its cleanup or a failure (a backlog connection then closes +unread); the requester may shut down (the leash watcher) and decides once the +connection ended. `AcceptRule = FALSE` is the retirement rule before the fix; +`LeashCheck = FALSE` drops the leash check. + +| Config | Constants | Result | Shows | +| --- | --- | --- | --- | +| `accept-positive` | `AcceptRule = TRUE`, `LeashCheck = TRUE` | 68 distinct states, no error; `StartOnlyAfterAccept`, `NotStartedOnlyWithoutAccept`, `NothingRanWhenNotStarted` and `UnconfirmedAfterAccept` hold | "not started" only without the byte and true; after it every failure is unconfirmed | +| `accept-old-retirement` | `AcceptRule = FALSE` | `NothingRanWhenNotStarted` violated: `report = "not-started"`, `started = TRUE`, `owner = "cleanup"` | Codex's case under the old rule | +| `accept-no-leash-check` | `LeashCheck = FALSE` | `NotStartedOnlyWithoutAccept` violated: `report = "not-started"`, `accepted = TRUE`, `local = TRUE` | A local shutdown read as the owner's close | +| `accept-backlog-reach` | positive constants | `NeverBacklogNotStarted` violated: `report = "not-started"`, `took = FALSE`, `owner = "cleanup"` | VM row 4 is reachable and reported as not started | +| `accept-lost-reply-reach` | positive constants | `NeverLostReplyUnconfirmed` violated: `report = "unconfirmed"`, `started = TRUE`, `replied = FALSE`, `owner = "cleanup"` | Codex's case is reachable and unconfirmed | + +The model covers an owner that advertises acceptance. The version choice is +not modelled: against an owner of record version 4 the requester sends +version 2 and keeps the behaviour from before the fix, where every failure +after the send is unconfirmed. + +Tests: `native/foreground/tests.rs` (a capped reply is refused by the request +bound and delivered whole by the reply writer; a command taken but not +accepted is not started while the owner is published; an accepted command +closed before its reply stays unconfirmed, also after the owner's cleanup; a +backlog request is not started whatever retired the publication; interactive +requests are not started only without acceptance, and a leash shutdown stays +uncertain; an owner from before the upgrade, publishing record version 4, +still runs exec and run on version 2 and gets no not-started proof; and the +real per-request step of the owner's loop sends the byte while another +project's stop still holds the lease, with the journal and one-off records +unchanged, before its pending signal ends the wait as not started). + ## Code and tests - `provider/lifecycle.rs`: `COMMAND_LEASE_WAIT`. diff --git a/tests/models/tla/native-command-lease/CommandAccept.tla b/tests/models/tla/native-command-lease/CommandAccept.tla new file mode 100644 index 0000000000..8664dea021 --- /dev/null +++ b/tests/models/tla/native-command-lease/CommandAccept.tla @@ -0,0 +1,124 @@ +---------------------------- MODULE CommandAccept ---------------------------- +(* HACK-2742 review (Codex P1). One authored command (exec, one-off run or *) +(* interactive exec) on one connection to the project's owner. The owner *) +(* serves one request at a time on its only loop: it takes the connection *) +(* from its listen backlog, reads and validates the request, queues one *) +(* accept byte, and only then starts the command. If it cannot queue the *) +(* byte (this side is gone) or refuses the request, it closes with no byte. *) +(* After acceptance the reply may be delivered or lost (its write failed, or *) +(* the owner failed). Between requests the owner may end through its own *) +(* cleanup (publication retired, run removed) or fail (publication kept). A *) +(* connection still in the backlog closes unread when the owner ends. *) +(* *) +(* The requester decides once the connection ended. AcceptRule = TRUE is the *) +(* fix: "not started" only when no byte at all arrived; after the byte every *) +(* failure is "unconfirmed". AcceptRule = FALSE is the rule before it, which *) +(* had no accept byte and read "closed with no byte of answer, then retired *) +(* by the owner's own cleanup" as not started: Codex's case, a reply lost *) +(* after the command ran followed by the owner's `hack down`, breaks it. *) +(* *) +(* For interactive exec this side's leash watcher shuts the stream down once *) +(* the frontend is gone (Shutdown). That local close can hide a queued byte, *) +(* so with LeashCheck = TRUE a requester that shut down never claims "not *) +(* started". LeashCheck = FALSE is the negative control without that check. *) +EXTENDS Naturals +CONSTANTS AcceptRule, LeashCheck +VARIABLES conn, took, accepted, started, replied, owner, local, report +vars == <> + +Init == /\ conn = "queued" /\ took = FALSE /\ accepted = FALSE + /\ started = FALSE /\ replied = FALSE /\ owner = "live" + /\ local = FALSE /\ report = "none" + +Live == owner = "live" + +\* The owner takes the connection from its backlog and reads the request. +Take == /\ Live /\ conn = "queued" /\ conn' = "taken" /\ took' = TRUE + /\ UNCHANGED <> + +\* It refuses the request, or cannot queue the accept byte: close, no byte. +Drop == /\ Live /\ conn = "taken" /\ conn' = "closed" + /\ UNCHANGED <> + +\* It queues the accept byte. A side that shut down makes that send fail. +Accept == /\ Live /\ conn = "taken" /\ ~local + /\ conn' = "accepted" /\ accepted' = TRUE + /\ UNCHANGED <> + +\* Effects may start only after acceptance. +Start == /\ Live /\ conn = "accepted" /\ ~started /\ started' = TRUE + /\ UNCHANGED <> + +\* The reply is delivered. +Reply == /\ Live /\ conn = "accepted" /\ started + /\ conn' = "replied" /\ replied' = TRUE + /\ UNCHANGED <> + +\* No reply after acceptance: a failure before the start, a lost reply write. +Lose == /\ Live /\ conn = "accepted" /\ conn' = "closed" + /\ UNCHANGED <> + +\* The owner fails during the request; the connection closes. +Crash == /\ Live /\ conn \in {"taken", "accepted"} + /\ owner' = "failed" /\ conn' = "closed" + /\ UNCHANGED <> + +\* Between requests the owner ends: its cleanup, or a failure. A backlog +\* connection closes unread. +End == /\ Live /\ conn \in {"queued", "closed", "replied"} + /\ owner' \in {"cleanup", "failed"} + /\ conn' = IF conn = "queued" THEN "closed" ELSE conn + /\ UNCHANGED <> + +\* The interactive leash watcher shuts this side down (frontend gone). +Shutdown == /\ report = "none" /\ ~local /\ local' = TRUE + /\ UNCHANGED <> + +\* What the requester can read first: the accept byte, unless its own +\* shutdown hid it. +SawByte == accepted /\ ~local + +NewReport == IF replied /\ ~local THEN "ran" + ELSE IF ~SawByte /\ (~local \/ ~LeashCheck) THEN "not-started" + ELSE "unconfirmed" + +\* The rule before the fix: no answer byte, then the owner's own cleanup. +OldReport == IF replied /\ ~local THEN "ran" + ELSE IF owner = "cleanup" THEN "not-started" + ELSE "unconfirmed" + +\* The requester decides once the connection ended, or it shut down. The +\* old rule's short wait for the retirement is the interleaving of End. +Decide == /\ report = "none" + /\ conn \in {"closed", "replied"} \/ local + /\ report' = IF AcceptRule THEN NewReport ELSE OldReport + /\ UNCHANGED <> + +Next == Take \/ Drop \/ Accept \/ Start \/ Reply \/ Lose \/ Crash \/ End + \/ Shutdown \/ Decide +Spec == Init /\ [][Next]_vars + +TypeOK == /\ conn \in {"queued", "taken", "accepted", "replied", "closed"} + /\ took \in BOOLEAN /\ accepted \in BOOLEAN /\ started \in BOOLEAN + /\ replied \in BOOLEAN /\ owner \in {"live", "cleanup", "failed"} + /\ local \in BOOLEAN + /\ report \in {"none", "ran", "unconfirmed", "not-started"} +\* The owner starts only what it accepted. +StartOnlyAfterAccept == started => accepted +\* "not started" only when no accept byte was sent. +NotStartedOnlyWithoutAccept == report = "not-started" => ~accepted +\* "not started" is true: the command never began. +NothingRanWhenNotStarted == report = "not-started" => ~started +\* After the accept byte, every failure is "unconfirmed". +UnconfirmedAfterAccept == + (accepted /\ report \notin {"none", "ran"}) => report = "unconfirmed" +\* Reachability (VM row 4): a backlog request the owner never took, then its +\* own cleanup, is reported as not started. +NeverBacklogNotStarted == ~(report = "not-started" /\ ~took + /\ owner = "cleanup") +\* Reachability (Codex's case): the command ran, its reply was lost and the +\* owner then ended through its cleanup; it is reported as unconfirmed. +NeverLostReplyUnconfirmed == ~(report = "unconfirmed" /\ started /\ ~replied + /\ owner = "cleanup") +============================================================================= diff --git a/tests/models/tla/native-command-lease/accept-backlog-reach.cfg b/tests/models/tla/native-command-lease/accept-backlog-reach.cfg new file mode 100644 index 0000000000..941535c2c6 --- /dev/null +++ b/tests/models/tla/native-command-lease/accept-backlog-reach.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CONSTANTS AcceptRule = TRUE LeashCheck = TRUE +INVARIANT NeverBacklogNotStarted +CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/native-command-lease/accept-lost-reply-reach.cfg b/tests/models/tla/native-command-lease/accept-lost-reply-reach.cfg new file mode 100644 index 0000000000..e845510fcb --- /dev/null +++ b/tests/models/tla/native-command-lease/accept-lost-reply-reach.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CONSTANTS AcceptRule = TRUE LeashCheck = TRUE +INVARIANT NeverLostReplyUnconfirmed +CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/native-command-lease/accept-no-leash-check.cfg b/tests/models/tla/native-command-lease/accept-no-leash-check.cfg new file mode 100644 index 0000000000..1925e2c4e2 --- /dev/null +++ b/tests/models/tla/native-command-lease/accept-no-leash-check.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CONSTANTS AcceptRule = TRUE LeashCheck = FALSE +INVARIANT NotStartedOnlyWithoutAccept +CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/native-command-lease/accept-old-retirement.cfg b/tests/models/tla/native-command-lease/accept-old-retirement.cfg new file mode 100644 index 0000000000..5e06944197 --- /dev/null +++ b/tests/models/tla/native-command-lease/accept-old-retirement.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CONSTANTS AcceptRule = FALSE LeashCheck = TRUE +INVARIANT NothingRanWhenNotStarted +CHECK_DEADLOCK FALSE diff --git a/tests/models/tla/native-command-lease/accept-positive.cfg b/tests/models/tla/native-command-lease/accept-positive.cfg new file mode 100644 index 0000000000..3092bda329 --- /dev/null +++ b/tests/models/tla/native-command-lease/accept-positive.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CONSTANTS AcceptRule = TRUE LeashCheck = TRUE +INVARIANTS TypeOK StartOnlyAfterAccept NotStartedOnlyWithoutAccept NothingRanWhenNotStarted UnconfirmedAfterAccept +CHECK_DEADLOCK FALSE From 3a9a382ead6296ca874e96a368bff301c4fd52f3 Mon Sep 17 00:00:00 2001 From: Dimitri Kennedy <344842+roodboi@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:17:47 -0500 Subject: [PATCH 11/11] test(runtime-core): pin owner record version 5 in the publication codec tests (HACK-2742) The publication now writes record version 5, which advertises command acceptance. The codec tests asserted version 4 and used 5 as the unknown future version; they now assert 5 and use 6. Co-Authored-By: Claude Opus 5.5 --- .../src/provider/graph/native/foreground/tests.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/runtime-core/src/provider/graph/native/foreground/tests.rs b/packages/runtime-core/src/provider/graph/native/foreground/tests.rs index fbafc58792..1776c36c7d 100644 --- a/packages/runtime-core/src/provider/graph/native/foreground/tests.rs +++ b/packages/runtime-core/src/provider/graph/native/foreground/tests.rs @@ -378,14 +378,15 @@ fn owner_codec_refuses_legacy_kind_unknown_fields_and_wrong_process_incarnation( } #[test] -fn publication_four_binds_session_and_preserves_closed_legacy_live_codecs() { +fn publication_five_binds_session_and_preserves_closed_legacy_live_codecs() { let fixture = Fixture::new(); let review = fixture.receipt().review; let publication = owner::Publication::bind(&fixture.candidate, &review).unwrap(); let file = fixture.owner_root().join("owner.json"); let bytes = fs::read(&file).unwrap(); let qualified: Value = serde_json::from_slice(&bytes).unwrap(); - assert_eq!(qualified["version"], 4); + // Version 5: the session-qualified record of an owner that accepts commands. + assert_eq!(qualified["version"], 5); assert!( qualified["host_boot_uuid"] == serde_json::to_value(host_boot::read().unwrap()).unwrap(), "Publication must retain the observed boot qualifier" @@ -488,7 +489,7 @@ fn session_codec_refuses_missing_mixed_downgraded_and_unknown_qualifiers() { "micros" => bad["host_boot_micros"] = json!(1), "v3" => bad["version"] = json!(3), "v2" => bad["version"] = json!(2), - "future" => bad["version"] = json!(5), + "future" => bad["version"] = json!(6), _ => unreachable!(), } fs::write(&file, serde_json::to_vec(&bad).unwrap()).unwrap();