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 1/5] 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 2/5] 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 3/5] 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 4/5] 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 5/5] 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(