Skip to content
Open
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
30 changes: 27 additions & 3 deletions src/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,9 @@ fn write_cache(path: &Path, cache: &Cache) -> anyhow::Result<()> {
Ok(())
}

/// Reads only local state; discovery continues in a child with closed streams.
/// Reads only local state. A due check continues in a child with closed
/// streams only when `may_detach` allows it: on Windows both stdout and stderr
/// must be consoles, so a redirected run leaves the check to a later one.
/// Call before starting the runtime, including for help and version invocations.
pub fn on_invocation() {
if std::env::var_os("PROOFLINE_NO_UPDATE_CHECK").is_some_and(|value| value == "1") {
Expand All @@ -99,7 +101,7 @@ pub fn on_invocation() {
return;
};
let interactive = std::io::stderr().is_terminal() && std::io::stdout().is_terminal();
if let Ok(Some(notice)) = prepare_check(&path, &args, interactive, start_check) {
if let Ok(Some(notice)) = prepare_check(&path, &args, interactive, may_detach(), start_check) {
crate::say(&notice);
} else {
// Missing or failed advisory discovery never changes the command result.
Expand Down Expand Up @@ -150,6 +152,7 @@ fn prepare_check(
path: &Path,
args: &[std::ffi::OsString],
interactive: bool,
detach: bool,
launch: impl FnOnce() -> anyhow::Result<()>,
) -> anyhow::Result<Option<String>> {
let directory = path.parent().context("update cache has no directory")?;
Expand All @@ -171,7 +174,8 @@ fn prepare_check(
latest: None,
});
let notice = suggestion(&cache, args, interactive);
if cache.checked <= now() && now().saturating_sub(cache.checked) < DAY {
// Without a detachable child, leave the attempt to a later invocation.
if !detach || (cache.checked <= now() && now().saturating_sub(cache.checked) < DAY) {
return Ok(notice);
}
// Record the attempt first, so an offline machine does not fork on every command.
Expand All @@ -188,6 +192,26 @@ fn prepare_check(
Ok(notice)
}

/// Whether a discovery child can outlive this invocation unnoticed. A Windows
/// child inherits every inheritable handle (rust-lang/rust#54760), including
/// this process's redirected stdout and stderr, so whoever reads the output
/// (`$(...)`, a pipe, a CI runner, an MCP host) would wait for the checker to
/// exit. Std limits inheritance only through unstable or unsafe APIs, so on
/// Windows discovery waits for an invocation whose output is a console.
fn may_detach() -> bool {
detachable(
cfg!(windows),
std::io::stdout().is_terminal(),
std::io::stderr().is_terminal(),
)
}

/// One redirected stream is enough to hold a reader: `$o = proofline ...`
/// captures only stdout while stderr stays on the console.
const fn detachable(windows: bool, stdout_is_console: bool, stderr_is_console: bool) -> bool {
!windows || (stdout_is_console && stderr_is_console)
}

fn checker_command(executable: &Path) -> Command {
let mut command = Command::new(executable);
command.env_clear();
Expand Down
50 changes: 48 additions & 2 deletions src/update/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ fn installer_directory_and_bounded_cache() {
)
.unwrap();
// A fresh cached result schedules no child, and survives the next invocation.
prepare_check(&cache, &["--json".into()], true, || {
prepare_check(&cache, &["--json".into()], true, true, || {
anyhow::bail!("a fresh cache must not launch discovery")
})
.unwrap();
Expand All @@ -101,6 +101,41 @@ fn installer_directory_and_bounded_cache() {
assert!(read_cache(&cache).is_err());
}

#[test]
fn windows_detaches_only_when_both_output_streams_are_consoles() {
// `$o = proofline ...` pipes stdout while stderr stays on the console.
assert!(!detachable(true, false, true));
assert!(!detachable(true, true, false));
assert!(!detachable(true, false, false));
assert!(detachable(true, true, true));
for (stdout, stderr) in [(false, false), (false, true), (true, false), (true, true)] {
assert!(detachable(false, stdout, stderr));
}
}

#[test]
fn an_invocation_that_cannot_detach_leaves_discovery_to_the_next_one() {
let directory = tempfile::tempdir().unwrap();
let cache = directory.path().join("update.json");
// `prepare_check` ignores launch errors, so only a panic proves no launch.
let notice = prepare_check(&cache, &["status".into()], false, false, || {
unreachable!("an invocation that cannot detach must not launch discovery")
})
.unwrap();
assert!(notice.is_none());
// No attempt is recorded, so the next invocation that can detach still checks.
assert!(read_cache(&cache).is_err());
let mut launched = false;
// Only `detach` decides: a redirected (non-interactive) run still checks.
prepare_check(&cache, &["status".into()], false, true, || {
launched = true;
Ok(())
})
.unwrap();
assert!(launched);
assert!(read_cache(&cache).is_ok());
}

#[tokio::test]
async fn discovery_rejects_bad_bounded_and_offline_responses() {
use axum::{Router, routing::get};
Expand Down Expand Up @@ -229,7 +264,10 @@ async fn detached_discovery_is_serialized_and_notices_arrive_on_the_next_invocat
.env(CACHE, &path)
.env(ADDRESS, address);
let notice = tokio::task::spawn_blocking(move || {
prepare_check(&path, &["status".into()], true, || spawn_check(worker))
// Output is piped to the test, as under `$(...)` or a CI runner.
prepare_check(&path, &["status".into()], true, may_detach(), || {
spawn_check(worker)
})
})
.await
.unwrap()
Expand Down Expand Up @@ -297,6 +335,14 @@ async fn detached_discovery_is_serialized_and_notices_arrive_on_the_next_invocat
.contains("run 'proofline update'")
);
}
if cfg!(windows) {
// A Windows child would hold the piped output open, so these
// invocations neither start discovery nor record an attempt.
assert_eq!(received.load(Ordering::SeqCst), 0);
assert!(read_cache(&cache).is_err());
server.abort();
return;
}
tokio::time::timeout(Duration::from_secs(5), async {
while received.load(Ordering::SeqCst) == 0 {
tokio::time::sleep(Duration::from_millis(10)).await;
Expand Down
19 changes: 19 additions & 0 deletions tests/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,25 @@
use std::process::Command;
use std::time::{SystemTime, UNIX_EPOCH};

/// A Windows discovery child would inherit the captured output pipe and keep
/// the reader waiting, so a captured run with no cache records no attempt.
#[cfg(windows)]
#[test]
fn captured_windows_invocation_leaves_discovery_to_a_console_run() {
let directory = tempfile::tempdir().unwrap();
// `output()` pipes stdout and stderr, as `$(...)` or a CI step does.
let version = Command::new(env!("CARGO_BIN_EXE_proofline"))
.arg("--version")
.env_remove("PROOFLINE_NO_UPDATE_CHECK")
.env("LOCALAPPDATA", directory.path())
.output()
.unwrap();
assert!(version.status.success());
// The lock proves the decision ran; the missing cache proves it said no.
assert!(directory.path().join("proofline/update.lock").exists());
assert!(!directory.path().join("proofline/update.json").exists());
}

#[test]
fn cached_update_preserves_schema_help_and_source_installation() {
let directory = tempfile::tempdir().unwrap();
Expand Down