Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 22 additions & 17 deletions docs/guides/native-candidate.md
Original file line number Diff line number Diff line change
Expand Up @@ -5483,23 +5483,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. The command says the same when the owner exits while the command is still waiting for the lock, for example during the project's own `hack down`: nothing has been sent at that point. The owner accepts each command with one byte before it does anything for it, and it drops a command it cannot accept. So the command also says nothing ran when the owner closed the connection without even that byte: for example, the request reached the owner's queue but the owner ended through that `hack down` without taking it, or the owner refused the request. Once the owner has accepted a command, every failure keeps "unconfirmed". A command's answer carries up to 1 MiB of output on each stream. A project started by an earlier prerelease keeps working after you upgrade: its owner does not advertise acceptance, so commands are sent to it as before, without this proof, and a failure after sending stays unconfirmed. Any other
authored failure keeps its report, "completion is unconfirmed" included. A compose
project's one-off `run` is answered by its owner, which waits at most 15 seconds on
its only loop, within one 15-second bound for its selection and admission before its
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
Expand Down
23 changes: 22 additions & 1 deletion packages/runtime-core/src/interactive_exec_cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,19 @@ pub fn command(candidate: &Candidate, args: &[&str]) -> Result<i32, CandidateErr
let frontend = File::from(unsafe { OwnedFd::from_raw_fd(3) });
hack_runtime_core::provider::private_input::validate_duplex(&frontend)?;
let mut report = frontend.try_clone().map_err(|_| invalid())?;
// HACK-2742: stderr is the user's terminal, so a lease wait that lasts about
// 3 s is reported on the control channel as one value-free event line, ahead
// of the final report; the CLI prints its own progress line for it.
let events = std::sync::Mutex::new(frontend.try_clone().map_err(|_| invalid())?);
interactive_exec::report_lease_waits_to(Box::new(move |line| {
if let Some(holder) = line.strip_prefix("hack.lease-wait:begin ") {
let event = serde_json::json!({"version":1,"event":"lease-wait","holder":holder});
if let (Ok(mut file), Ok(mut bytes)) = (events.lock(), serde_json::to_vec(&event)) {
bytes.push(b'\n');
let _ = file.write_all(&bytes);
}
}
}));
let result = interactive_exec::execute(candidate, &options, frontend.into());
let (code, value) = match result {
Ok(completion) => (
Expand All @@ -86,7 +99,15 @@ pub fn command(candidate: &Candidate, args: &[&str]) -> Result<i32, CandidateErr
),
Err(error) => (
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())?;
Expand Down
81 changes: 81 additions & 0 deletions packages/runtime-core/src/provider/engine/command_lease_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -496,6 +496,80 @@ 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 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!(
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);
// 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();
}

/// 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
Expand Down Expand Up @@ -523,5 +597,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();
}
85 changes: 85 additions & 0 deletions packages/runtime-core/src/provider/graph/foreground/transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1239,6 +1239,91 @@ pub(super) fn write_extension(
}
write_bounded(stream, request, budget, APPEND_REQUEST_LIMIT)
}
/// [`write`] for a reply frame of up to `limit` bytes. A native authored command
/// reply carries two output streams of up to 1 MiB each in base64, beyond the
/// request bound (HACK-2742 review).
#[cfg(feature = "native-config-plan")]
pub(in crate::provider::graph) fn write_limited<T: Serialize>(
stream: &mut UnixStream,
value: &T,
budget: Duration,
limit: usize,
) -> Result<(), CandidateError> {
write_bounded(stream, value, budget, limit)?;
stream.shutdown(Shutdown::Write).map_err(|_| refused())
}

/// Send one marker byte ahead of any frame. An error means the byte was not
/// queued for the peer; a success means the peer will read it before anything
/// sent after it, even if this side then closes.
#[cfg(feature = "native-config-plan")]
pub(in crate::provider::graph) fn send_marker(
stream: &UnixStream,
marker: u8,
budget: Duration,
) -> Result<(), CandidateError> {
let deadline = Instant::now() + budget;
loop {
wait_io(stream.as_raw_fd(), libc::POLLOUT, deadline)?;
// SAFETY: one readable byte, and the stream owns the FD. Nonblocking send
// keeps the deadline; NOSIGNAL keeps a disconnect local.
let n = unsafe {
libc::send(
stream.as_raw_fd(),
(&marker as *const u8).cast(),
1,
libc::MSG_DONTWAIT | libc::MSG_NOSIGNAL,
)
};
if n == 1 {
return Ok(());
}
if n < 0
&& matches!(
std::io::Error::last_os_error().kind(),
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::Interrupted
)
{
continue;
}
return Err(refused());
}
}

/// The peer's first byte, consumed, or `None` when the peer closed the stream
/// without sending one (an end of file, or a reset or disconnect with nothing
/// queued: queued bytes are always read before such an error is reported). A
/// timeout or any other failure is an error and proves nothing.
#[cfg(feature = "native-config-plan")]
pub(in crate::provider::graph) fn receive_marker(
stream: &UnixStream,
deadline: Instant,
) -> Result<Option<u8>, CandidateError> {
loop {
wait_io(stream.as_raw_fd(), libc::POLLIN, deadline)?;
let mut byte = 0_u8;
// SAFETY: one writable byte, and the stream owns the FD. MSG_DONTWAIT
// keeps a readiness race within the deadline.
let count = unsafe {
libc::recv(
stream.as_raw_fd(),
(&mut byte as *mut u8).cast(),
1,
libc::MSG_DONTWAIT,
)
};
match count {
1 => return Ok(Some(byte)),
0 => return Ok(None),
_ => match std::io::Error::last_os_error().raw_os_error() {
Some(libc::ECONNRESET | libc::ENOTCONN | libc::EPIPE) => return Ok(None),
Some(libc::EAGAIN | libc::EINTR) => continue,
_ => return Err(refused()),
},
}
}
}

pub(super) fn write_job<T: Serialize>(
stream: &mut UnixStream,
value: &T,
Expand Down
13 changes: 13 additions & 0 deletions packages/runtime-core/src/provider/graph/interactive_exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 <holder>`, 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<dyn Fn(&str) + Send + Sync>) -> 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",
Expand Down
Loading
Loading