Allow daemon updates to restore pinned packages to latest stable (#45780)

## Why

`codex app-server daemon update` previously required a latest-channel installation, leaving pinned and local managed packages unable to return to production updates through that command.

## What changed

- Allow explicit updates to restore managed packages to the latest stable release while preserving the automatic-update preference. Extend legacy migration to local and pinned packages when the published installer and release support it.
- Bind restoration to the selected release with a single-use updater authorization and installer guards. Scheduled updates and ordinary updater socket requests continue to respect pins.
- Restart a running daemon when its selected package changes, even if the binary and version are identical; leave stopped daemons stopped.
- Reject incompatible production packages before selecting them, resolve Windows junction targets for ownership checks, and show the restoration command after installing a pinned CLI package.

## Testing

Extend daemon and installer tests to cover local-package migration, restoration with automatic updates enabled or disabled, same-binary package restarts, stopped-daemon preservation, selection races, incompatible releases, and socket requests that must not undo pins.

GitOrigin-RevId: d64520c1190b5c7bac084fb4a1b6b24998b08dfa
This commit is contained in:
Eric Traut authored and copyberry committed 2026-09-15 19:51:06 +00:00
1 parent c0316291ca
commit 321dcf5a6f
18 files changed
+509 -118

No files matched your search

+7 -8
View File
@@ -58,14 +58,13 @@ Positive minute intervals have no configured cap. `daemon restart` applies the
enabled state; the next updater wait reads a new interval. The preference does enabled state; the next updater wait reads a new interval. The preference does
not affect an explicit `codex update` command or `daemon update`. not affect an explicit `codex update` command or `daemon update`.
`daemon update` checks the latest stable release once, even with automatic `daemon update` selects the latest stable release, even with automatic updates
updates disabled. It requires an installer-owned latest-channel package in either disabled. It also returns pinned or local managed packages to production update
the dedicated daemon root or the retained legacy root. JSON reports `updated`, eligibility, preserving the automatic-update preference. Legacy installations
`noUpdate`, or `unsupported`, with installed migrate to the dedicated root once the published installer and release support
and running versions. The updater owns scheduled and manual installs. A manual migration. JSON reports `updated`, `noUpdate`, or `unsupported`, with installed
update restarts a running managed daemon, so active or queued work may be and running versions. A running daemon restarts, so active or queued work may be
interrupted. interrupted; a stopped daemon stays stopped. Installer errors return nonzero.
Accepted updates continue if the CLI exits. Installer errors return nonzero.
The updater uses saved network settings; CLI `-c` overrides do not reach it. The updater uses saved network settings; CLI `-c` overrides do not reach it.
For all managed app-server shutdowns, including explicit stop and restart and For all managed app-server shutdowns, including explicit stop and restart and
@@ -32,7 +32,11 @@ pub(crate) fn pid_backend(paths: BackendPaths) -> PidBackend {
} }
pub(crate) fn pid_update_loop_backend(paths: BackendPaths) -> PidBackend { pub(crate) fn pid_update_loop_backend(paths: BackendPaths) -> PidBackend {
PidBackend::new_update_loop(paths.codex_bin, paths.update_pid_file) PidBackend::new_update_loop(
paths.codex_bin,
paths.update_pid_file,
/*restore_release*/ None,
)
} }
pub(crate) async fn append_stderr_log_tail_context(pid_file: &Path, context: &mut String) { pub(crate) async fn append_stderr_log_tail_context(pid_file: &Path, context: &mut String) {
+22 -12
View File
@@ -78,11 +78,11 @@ enum PidFileState {
Running(PidRecord), Running(PidRecord),
} }
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone)]
#[cfg_attr(not(any(unix, windows)), allow(dead_code))] #[cfg_attr(not(any(unix, windows)), allow(dead_code))]
enum PidCommandKind { enum PidCommandKind {
AppServer { remote_control_enabled: bool }, AppServer { remote_control_enabled: bool },
UpdateLoop, UpdateLoop { restore_release: Option<String> },
} }
impl PidBackend { impl PidBackend {
@@ -107,13 +107,17 @@ impl PidBackend {
} }
} }
pub(crate) fn new_update_loop(codex_bin: PathBuf, pid_file: PathBuf) -> Self { pub(crate) fn new_update_loop(
codex_bin: PathBuf,
pid_file: PathBuf,
restore_release: Option<String>,
) -> Self {
let lock_file = pid_file.with_extension("pid.lock"); let lock_file = pid_file.with_extension("pid.lock");
Self { Self {
codex_bin, codex_bin,
pid_file, pid_file,
lock_file, lock_file,
command_kind: PidCommandKind::UpdateLoop, command_kind: PidCommandKind::UpdateLoop { restore_release },
} }
} }
@@ -190,7 +194,7 @@ impl PidBackend {
tracing::warn!(%pid, %err, "managed app-server shutdown request failed; waiting for force deadline"); tracing::warn!(%pid, %err, "managed app-server shutdown request failed; waiting for force deadline");
} }
} }
PidCommandKind::UpdateLoop => { PidCommandKind::UpdateLoop { .. } => {
fs::write(self.pid_file.with_extension("shutdown"), pid.to_string()) fs::write(self.pid_file.with_extension("shutdown"), pid.to_string())
.await .await
.context("failed to request updater shutdown")?; .context("failed to request updater shutdown")?;
@@ -358,15 +362,21 @@ impl PidBackend {
} }
#[cfg(any(unix, windows))] #[cfg(any(unix, windows))]
fn command_args(&self) -> Vec<&'static str> { fn command_args(&self) -> Vec<&str> {
match self.command_kind { match &self.command_kind {
PidCommandKind::AppServer { PidCommandKind::AppServer {
remote_control_enabled: true, remote_control_enabled: true,
} => vec!["app-server", "--remote-control", "--listen", "unix://"], } => vec!["app-server", "--remote-control", "--listen", "unix://"],
PidCommandKind::AppServer { PidCommandKind::AppServer {
remote_control_enabled: false, remote_control_enabled: false,
} => vec!["app-server", "--listen", "unix://"], } => vec!["app-server", "--listen", "unix://"],
PidCommandKind::UpdateLoop => vec!["app-server", "daemon", "pid-update-loop"], PidCommandKind::UpdateLoop { restore_release } => {
let mut args = vec!["app-server", "daemon", "pid-update-loop"];
if let Some(release) = restore_release {
args.extend(["--restore-release", release.as_str()]);
}
args
}
} }
} }
@@ -379,7 +389,7 @@ impl PidBackend {
PidCommandKind::AppServer { PidCommandKind::AppServer {
remote_control_enabled: true, remote_control_enabled: true,
} }
| PidCommandKind::UpdateLoop => None, | PidCommandKind::UpdateLoop { .. } => None,
} }
} }
@@ -387,9 +397,9 @@ impl PidBackend {
match self.command_kind { match self.command_kind {
PidCommandKind::AppServer { .. } => terminate_process(pid), PidCommandKind::AppServer { .. } => terminate_process(pid),
#[cfg(unix)] #[cfg(unix)]
PidCommandKind::UpdateLoop => terminate_process_group(pid), PidCommandKind::UpdateLoop { .. } => terminate_process_group(pid),
#[cfg(not(unix))] #[cfg(not(unix))]
PidCommandKind::UpdateLoop => terminate_process(pid), PidCommandKind::UpdateLoop { .. } => terminate_process(pid),
} }
} }
@@ -397,7 +407,7 @@ impl PidBackend {
fn force_terminate_process(&self, pid: u32) -> Result<()> { fn force_terminate_process(&self, pid: u32) -> Result<()> {
match self.command_kind { match self.command_kind {
PidCommandKind::AppServer { .. } => force_terminate_process(pid), PidCommandKind::AppServer { .. } => force_terminate_process(pid),
PidCommandKind::UpdateLoop => force_terminate_process_group(pid), PidCommandKind::UpdateLoop { .. } => force_terminate_process_group(pid),
} }
} }
@@ -205,7 +205,7 @@ impl PidBackend {
// Never retry inside the parent's Job Object: that would report a // Never retry inside the parent's Job Object: that would report a
// successful launch that dies when the terminal/SSH session closes. // successful launch that dies when the terminal/SSH session closes.
command.creation_flags(DETACHED_PROCESS | CREATE_BREAKAWAY_FROM_JOB); command.creation_flags(DETACHED_PROCESS | CREATE_BREAKAWAY_FROM_JOB);
if matches!(self.command_kind, PidCommandKind::UpdateLoop) { if matches!(self.command_kind, PidCommandKind::UpdateLoop { .. }) {
match fs::remove_file(self.pid_file.with_extension("ready")).await { match fs::remove_file(self.pid_file.with_extension("ready")).await {
Ok(()) => {} Ok(()) => {}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
@@ -216,7 +216,7 @@ impl PidBackend {
PidCommandKind::AppServer { .. } => { PidCommandKind::AppServer { .. } => {
command.env(codex_app_server_transport::DAEMON_SHUTDOWN_SOCKET_ENV, "1"); command.env(codex_app_server_transport::DAEMON_SHUTDOWN_SOCKET_ENV, "1");
} }
PidCommandKind::UpdateLoop => { PidCommandKind::UpdateLoop { .. } => {
let shutdown_file = self.pid_file.with_extension("shutdown"); let shutdown_file = self.pid_file.with_extension("shutdown");
match fs::remove_file(&shutdown_file).await { match fs::remove_file(&shutdown_file).await {
Ok(()) => {} Ok(()) => {}
@@ -311,7 +311,7 @@ impl PidBackend {
}); });
} }
#[cfg(windows)] #[cfg(windows)]
if matches!(self.command_kind, PidCommandKind::UpdateLoop) { if matches!(self.command_kind, PidCommandKind::UpdateLoop { .. }) {
self.finish_updater_start(&record, replacement.as_ref()) self.finish_updater_start(&record, replacement.as_ref())
.await?; .await?;
} }
@@ -434,7 +434,11 @@ async fn shutdown_grace_handles_process_exit() {
/*remote_control_enabled*/ false, /*remote_control_enabled*/ false,
); );
#[cfg(windows)] #[cfg(windows)]
let backend = PidBackend::new_update_loop(temp.path().join("codex"), pid_file); let backend = PidBackend::new_update_loop(
temp.path().join("codex"),
pid_file,
/*restore_release*/ None,
);
let result = tokio::time::timeout( let result = tokio::time::timeout(
Duration::from_secs(3), Duration::from_secs(3),
backend.stop_with_grace(grace_seconds), backend.stop_with_grace(grace_seconds),
@@ -503,7 +507,11 @@ async fn stopping_updater_signals_its_installer_process_group() {
) )
.await .await
.expect("write pid file"); .expect("write pid file");
let backend = PidBackend::new_update_loop(temp.path().join("codex"), pid_file); let backend = PidBackend::new_update_loop(
temp.path().join("codex"),
pid_file,
/*restore_release*/ None,
);
backend.stop().await.expect("stop updater"); backend.stop().await.expect("stop updater");
// The backend normally reaps the shim, so a second wait may return ECHILD. // The backend normally reaps the shim, so a second wait may return ECHILD.
let _ = child.wait(); let _ = child.wait();
@@ -542,8 +550,11 @@ async fn exited_unreaped_updater_is_reaped() {
process_identity, process_identity,
executable_identity: None, executable_identity: None,
}; };
let backend = let backend = PidBackend::new_update_loop(
PidBackend::new_update_loop(temp.path().join("codex"), temp.path().join("updater.pid")); temp.path().join("codex"),
temp.path().join("updater.pid"),
/*restore_release*/ None,
);
child.kill().expect("terminate updater shim"); child.kill().expect("terminate updater shim");
let deadline = tokio::time::Instant::now() + Duration::from_secs(5); let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
let result = loop { let result = loop {
@@ -569,7 +580,9 @@ fn update_loop_uses_hidden_app_server_subcommand() {
codex_bin: "codex".into(), codex_bin: "codex".into(),
pid_file: "updater.pid".into(), pid_file: "updater.pid".into(),
lock_file: "updater.pid.lock".into(), lock_file: "updater.pid.lock".into(),
command_kind: PidCommandKind::UpdateLoop, command_kind: PidCommandKind::UpdateLoop {
restore_release: None,
},
}; };
assert_eq!( assert_eq!(
@@ -692,6 +705,7 @@ async fn failed_updater_handoff_preserves_predecessor_record() {
let backend = PidBackend::new_update_loop( let backend = PidBackend::new_update_loop(
temp.path().join("missing-codex.exe"), temp.path().join("missing-codex.exe"),
state_dir.join("updater.pid"), state_dir.join("updater.pid"),
/*restore_release*/ None,
); );
let record = PidRecord { let record = PidRecord {
pid: std::process::id(), pid: std::process::id(),
@@ -738,6 +752,7 @@ async fn updater_readiness_and_post_publication_failure_preserve_ownership() {
let backend = PidBackend::new_update_loop( let backend = PidBackend::new_update_loop(
temp.path().join("codex.exe"), temp.path().join("codex.exe"),
temp.path().join("updater.pid"), temp.path().join("updater.pid"),
/*restore_release*/ None,
); );
let _lock = backend let _lock = backend
.acquire_reservation_lock() .acquire_reservation_lock()
+2 -1
View File
@@ -268,11 +268,12 @@ pub async fn set_remote_control(mode: RemoteControlMode) -> Result<RemoteControl
pub async fn run_pid_update_loop( pub async fn run_pid_update_loop(
http_client_factory: codex_http_client::HttpClientFactory, http_client_factory: codex_http_client::HttpClientFactory,
restore_release: Option<String>,
) -> Result<()> { ) -> Result<()> {
ensure_supported_platform()?; ensure_supported_platform()?;
#[cfg(windows)] #[cfg(windows)]
backend::windows::ensure_not_elevated()?; backend::windows::ensure_not_elevated()?;
update_loop::run(http_client_factory).await update_loop::run(http_client_factory, restore_release).await
} }
pub async fn update( pub async fn update(
+47 -15
View File
@@ -60,7 +60,7 @@ pub(crate) async fn request(daemon: &Daemon) -> Result<UpdateOutput> {
connection connection
} else { } else {
let settings = daemon.load_settings().await?; let settings = daemon.load_settings().await?;
if !daemon.is_stable_standalone_release()? if !supported(daemon)?
|| (daemon.running_backend_instance(&settings).await?.is_none() || (daemon.running_backend_instance(&settings).await?.is_none()
&& client::probe(&daemon.socket_path).await.is_ok()) && client::probe(&daemon.socket_path).await.is_ok())
{ {
@@ -70,8 +70,16 @@ pub(crate) async fn request(daemon: &Daemon) -> Result<UpdateOutput> {
.stop() .stop()
.await?; .await?;
let current_exe = std::env::current_exe()?; let current_exe = std::env::current_exe()?;
let worker = crate::backend::pid_update_loop_backend( let paths = daemon.backend_paths_with_bin(&settings, &current_exe);
daemon.backend_paths_with_bin(&settings, &current_exe), let restore_release = if daemon.is_stable_standalone_release()? {
None
} else {
Some(selected_release(daemon)?.2)
};
let worker = crate::backend::PidBackend::new_update_loop(
paths.codex_bin,
paths.update_pid_file,
restore_release,
); );
worker.start().await?; worker.start().await?;
let deadline = tokio::time::Instant::now() + Duration::from_secs(30); let deadline = tokio::time::Instant::now() + Duration::from_secs(30);
@@ -120,11 +128,38 @@ pub(crate) async fn request(daemon: &Daemon) -> Result<UpdateOutput> {
transport?; transport?;
let outcome: std::result::Result<UpdateOutput, String> = let outcome: std::result::Result<UpdateOutput, String> =
serde_json::from_slice(&response).context("invalid response from daemon updater")?; serde_json::from_slice(&response).context("invalid response from daemon updater")?;
return outcome.map_err(anyhow::Error::msg); let outcome = outcome.map_err(anyhow::Error::msg)?;
if outcome.status == UpdateStatus::Unsupported && supported(daemon)? {
// A scheduled or older updater cannot authorize restoring a pin.
// Replace it under the writable operation lock, even with identical bytes.
let _operation_lock = daemon.acquire_operation_lock().await?;
let settings = daemon.load_settings().await?;
let worker = crate::backend::pid_update_loop_backend(daemon.backend_paths(&settings));
if !daemon.is_stable_standalone_release()? {
worker.stop().await?;
continue 'request;
}
}
return Ok(outcome);
} }
} }
const UNSUPPORTED_MESSAGE: &str = "This command requires a CLI-managed daemon and a stable latest-channel standalone install; update this installation with its owning installer."; pub(super) fn supported(daemon: &Daemon) -> Result<bool> {
if daemon.is_stable_standalone_release()? {
return Ok(true);
}
let Ok((root, release, _)) = selected_release(daemon) else {
return Ok(false);
};
let bin = daemon.current_managed_codex_bin()?;
Ok(std::fs::canonicalize(root.join("releases"))
.is_ok_and(|releases| release.parent() == Some(releases.as_path()))
&& bin.is_file()
&& std::fs::canonicalize(bin).is_ok_and(|bin| bin.starts_with(&release)))
}
const UNSUPPORTED_MESSAGE: &str =
"This command requires a daemon package selected from its managed releases directory.";
pub(super) async fn unsupported(daemon: &Daemon) -> Result<UpdateOutput> { pub(super) async fn unsupported(daemon: &Daemon) -> Result<UpdateOutput> {
let managed_codex_path = daemon.current_managed_codex_bin()?; let managed_codex_path = daemon.current_managed_codex_bin()?;
@@ -146,6 +181,7 @@ pub(super) async fn handle_request(
daemon: &Daemon, daemon: &Daemon,
running_updater_identity: &crate::managed_install::ExecutableIdentity, running_updater_identity: &crate::managed_install::ExecutableIdentity,
terminate: &mut Signal, terminate: &mut Signal,
trigger: UpdateTrigger<'_>,
) -> Result<RequestDisposition> { ) -> Result<RequestDisposition> {
#[cfg(windows)] #[cfg(windows)]
if connection.ensure_non_elevated_peer().is_err() { if connection.ensure_non_elevated_peer().is_err() {
@@ -159,7 +195,7 @@ pub(super) async fn handle_request(
{ {
return Ok(RequestDisposition::Unchanged); return Ok(RequestDisposition::Unchanged);
} }
let result = run(http, daemon, running_updater_identity, terminate).await; let result = run(http, daemon, running_updater_identity, terminate, trigger).await;
let interrupted = result.as_ref().err().is_some_and(|err| { let interrupted = result.as_ref().err().is_some_and(|err| {
err.downcast_ref::<std::io::Error>() err.downcast_ref::<std::io::Error>()
.is_some_and(|err| err.kind() == std::io::ErrorKind::Interrupted) .is_some_and(|err| err.kind() == std::io::ErrorKind::Interrupted)
@@ -192,10 +228,12 @@ pub(super) async fn run(
daemon: &Daemon, daemon: &Daemon,
running_updater_identity: &crate::managed_install::ExecutableIdentity, running_updater_identity: &crate::managed_install::ExecutableIdentity,
terminate: &mut Signal, terminate: &mut Signal,
trigger: UpdateTrigger<'_>,
) -> Result<UpdateOutput> { ) -> Result<UpdateOutput> {
let settings = daemon.load_settings().await?; let settings = daemon.load_settings().await?;
let managed_running = daemon.running_backend_instance(&settings).await?.is_some(); let managed_running = daemon.running_backend_instance(&settings).await?.is_some();
if !daemon.is_stable_standalone_release()? if !(daemon.is_stable_standalone_release()?
|| matches!(trigger, UpdateTrigger::RestoreProduction(_)) && supported(daemon)?)
|| (!managed_running && client::probe(&daemon.socket_path).await.is_ok()) || (!managed_running && client::probe(&daemon.socket_path).await.is_ok())
{ {
return unsupported(daemon).await; return unsupported(daemon).await;
@@ -204,14 +242,8 @@ pub(super) async fn run(
let managed_codex_path = daemon.current_managed_codex_bin()?; let managed_codex_path = daemon.current_managed_codex_bin()?;
let (_, previous_release, _) = selected_release(daemon)?; let (_, previous_release, _) = selected_release(daemon)?;
let previous_identity = executable_identity(&managed_codex_path).await?; let previous_identity = executable_identity(&managed_codex_path).await?;
let (control, restart) = update_once( let (control, restart) =
http, update_once(http, daemon, running_updater_identity, terminate, trigger).await?;
daemon,
running_updater_identity,
terminate,
UpdateTrigger::Manual,
)
.await?;
if matches!(control, UpdateLoopControl::Stop) { if matches!(control, UpdateLoopControl::Stop) {
return Err(std::io::Error::from(std::io::ErrorKind::Interrupted).into()); return Err(std::io::Error::from(std::io::ErrorKind::Interrupted).into());
} }
+1 -1
View File
@@ -24,7 +24,7 @@ pub(super) async fn run(http: &impl InstallerHttp, legacy: &Daemon) -> Result<Up
let _operation_lock = legacy.acquire_operation_lock().await?; let _operation_lock = legacy.acquire_operation_lock().await?;
let previous = selected_release(legacy)?; let previous = selected_release(legacy)?;
anyhow::ensure!( anyhow::ensure!(
previous.0.ends_with("standalone") && legacy.is_stable_standalone_release()?, previous.0.ends_with("standalone") && super::manual_update::supported(legacy)?,
"daemon selection changed; retry the update" "daemon selection changed; retry the update"
); );
let home = previous let home = previous
@@ -72,7 +72,7 @@ pub async fn update_from_cli(
.ok() .ok()
.map(|info| info.app_server_version), .map(|info| info.app_server_version),
managed_codex_path, managed_codex_path,
message: "The CLI package is selected and pinned.".to_string(), message: "The CLI package is selected and pinned. Run `codex app-server daemon update` to return to production updates.".to_string(),
})) }))
} }
+71 -28
View File
@@ -49,7 +49,7 @@ pub(crate) async fn request_manual_update(
.pid_file .pid_file
.file_name() .file_name()
.is_some_and(|name| name == crate::LEGACY_PID_FILE_NAME) .is_some_and(|name| name == crate::LEGACY_PID_FILE_NAME)
&& daemon.is_stable_standalone_release()? && manual_update::supported(daemon)?
{ {
let http = RouteAwareClientPool::new_without_request_logging( let http = RouteAwareClientPool::new_without_request_logging(
http_client_factory, http_client_factory,
@@ -67,7 +67,10 @@ const INSTALL_URL: &str = "https://chatgpt.com/codex/install.sh";
#[cfg(windows)] #[cfg(windows)]
const INSTALL_URL: &str = "https://chatgpt.com/codex/install.ps1"; const INSTALL_URL: &str = "https://chatgpt.com/codex/install.ps1";
pub(crate) async fn run(http_client_factory: HttpClientFactory) -> Result<()> { pub(crate) async fn run(
http_client_factory: HttpClientFactory,
restore_release: Option<String>,
) -> Result<()> {
let http = RouteAwareClientPool::new_without_request_logging( let http = RouteAwareClientPool::new_without_request_logging(
http_client_factory, http_client_factory,
ClientRouteClass::Other, ClientRouteClass::Other,
@@ -76,6 +79,7 @@ pub(crate) async fn run(http_client_factory: HttpClientFactory) -> Result<()> {
&http, &http,
&Daemon::from_environment()?, &Daemon::from_environment()?,
&current_updater_identity().await?, &current_updater_identity().await?,
restore_release,
) )
.await .await
} }
@@ -84,6 +88,7 @@ async fn run_with_http(
http: &impl InstallerHttp, http: &impl InstallerHttp,
daemon: &Daemon, daemon: &Daemon,
running_updater_identity: &ExecutableIdentity, running_updater_identity: &ExecutableIdentity,
mut restore_release: Option<String>,
) -> Result<()> { ) -> Result<()> {
#[cfg(unix)] #[cfg(unix)]
let mut terminate = let mut terminate =
@@ -136,7 +141,7 @@ async fn run_with_http(
.map(|settings| settings.auto_update_enabled) .map(|settings| settings.auto_update_enabled)
.unwrap_or(true); .unwrap_or(true);
let mut next_check = Instant::now() let mut next_check = Instant::now()
+ if needs_managed_handoff || !auto_update_enabled { + if restore_release.is_some() || needs_managed_handoff || !auto_update_enabled {
Duration::from_secs(15) Duration::from_secs(15)
} else { } else {
INITIAL_UPDATE_DELAY INITIAL_UPDATE_DELAY
@@ -148,7 +153,11 @@ async fn run_with_http(
_ = terminate.recv() => return Ok(()), _ = terminate.recv() => return Ok(()),
connection = listener.as_mut().context("updater listener closed")?.accept() => { connection = listener.as_mut().context("updater listener closed")?.accept() => {
let connection = connection.context("failed to accept updater request")?; let connection = connection.context("failed to accept updater request")?;
let disposition = match manual_update::handle_request(connection, http, daemon, running_updater_identity, &mut terminate).await { // Only a manual CLI launch under the operation lock supplies this
// single-use authority. Ordinary socket requests cannot undo a pin.
let restoration = restore_release.take();
let trigger = restoration.as_deref().map_or(UpdateTrigger::Manual, UpdateTrigger::RestoreProduction);
let disposition = match manual_update::handle_request(connection, http, daemon, running_updater_identity, &mut terminate, trigger).await {
Ok(manual_update::RequestDisposition::Stop) => return Ok(()), Ok(manual_update::RequestDisposition::Stop) => return Ok(()),
Ok(disposition) => disposition, Ok(disposition) => disposition,
Err(_) => manual_update::RequestDisposition::Continue, Err(_) => manual_update::RequestDisposition::Continue,
@@ -168,6 +177,10 @@ async fn run_with_http(
next_check = Instant::now(); next_check = Instant::now();
} }
_ = sleep_until(next_check) => { _ = sleep_until(next_check) => {
// The authorizing CLI may have exited before sending its request.
if restore_release.is_some() {
return Ok(());
}
match UpdaterSettings::load(&daemon.settings_file).await { match UpdaterSettings::load(&daemon.settings_file).await {
Ok(settings) if !settings.auto_update_enabled => return Ok(()), Ok(settings) if !settings.auto_update_enabled => return Ok(()),
Err(_) => { Err(_) => {
@@ -284,9 +297,10 @@ enum UpdateLoopControl {
} }
#[derive(Clone, Copy, PartialEq, Eq)] #[derive(Clone, Copy, PartialEq, Eq)]
enum UpdateTrigger { enum UpdateTrigger<'a> {
Scheduled, Scheduled,
Manual, Manual,
RestoreProduction(&'a str),
} }
async fn update_once( async fn update_once(
@@ -294,7 +308,7 @@ async fn update_once(
daemon: &Daemon, daemon: &Daemon,
running_updater_identity: &ExecutableIdentity, running_updater_identity: &ExecutableIdentity,
terminate: &mut Signal, terminate: &mut Signal,
trigger: UpdateTrigger, trigger: UpdateTrigger<'_>,
) -> Result<(UpdateLoopControl, Option<RestartIfRunningOutcome>)> { ) -> Result<(UpdateLoopControl, Option<RestartIfRunningOutcome>)> {
if trigger == UpdateTrigger::Scheduled if trigger == UpdateTrigger::Scheduled
&& !UpdaterSettings::load(&daemon.settings_file) && !UpdaterSettings::load(&daemon.settings_file)
@@ -308,20 +322,36 @@ async fn update_once(
// latest-channel marker. Retry after the interval instead of exiting. // latest-channel marker. Retry after the interval instead of exiting.
return Ok((UpdateLoopControl::Continue, None)); return Ok((UpdateLoopControl::Continue, None));
} }
let (package_root, _, previous_release) = selected_release(daemon)?; let (package_root, previous_selection, previous_release) = selected_release(daemon)?;
let codex_home = package_root let codex_home = package_root
.parent() .parent()
.and_then(Path::parent) .and_then(Path::parent)
.context("daemon package root has no Codex home")?; .context("daemon package root has no Codex home")?;
let (installer_mode, installer_guard) =
if let UpdateTrigger::RestoreProduction(expected) = trigger {
anyhow::ensure!(
previous_release == expected,
"daemon selection changed; retry the update"
);
(
InstallerMode::RestoreProduction(&previous_release),
"CODEX_INSTALL_IF_CURRENT",
)
} else {
(
InstallerMode::Update(&previous_release),
"CODEX_INSTALL_IF_LATEST",
)
};
let script = tokio::select! { let script = tokio::select! {
result = fetch_installer_script(http) => result?, result = fetch_installer_script(http) => result?,
_ = terminate.recv() => return Ok((UpdateLoopControl::Stop, None)), _ = terminate.recv() => return Ok((UpdateLoopControl::Stop, None)),
}; };
anyhow::ensure!( anyhow::ensure!(
script script
.windows(b"CODEX_INSTALL_IF_LATEST".len()) .windows(installer_guard.len())
.any(|window| window == b"CODEX_INSTALL_IF_LATEST"), .any(|window| window == installer_guard.as_bytes()),
"standalone installer does not support guarded updates" "standalone installer does not support {installer_guard} guarded updates"
); );
if package_root.ends_with("app-server-daemon") { if package_root.ends_with("app-server-daemon") {
anyhow::ensure!( anyhow::ensure!(
@@ -347,22 +377,20 @@ async fn update_once(
); );
#[cfg(unix)] #[cfg(unix)]
if matches!( if matches!(
run_installer_script( run_installer_script(&script, installer_mode, &package_root, terminate.recv()).await?,
&script,
InstallerMode::Update(&previous_release),
&package_root,
terminate.recv()
)
.await?,
UpdateLoopControl::Stop UpdateLoopControl::Stop
) { ) {
return Ok((UpdateLoopControl::Stop, None)); return Ok((UpdateLoopControl::Stop, None));
} }
#[cfg(windows)] #[cfg(windows)]
tokio::select! { tokio::select! {
result = run_installer_script(&script, InstallerMode::Update(&previous_release), &package_root) => { result?; }, result = run_installer_script(&script, installer_mode, &package_root) => { result?; },
_ = terminate.recv() => return Ok((UpdateLoopControl::Stop, None)), _ = terminate.recv() => return Ok((UpdateLoopControl::Stop, None)),
} }
anyhow::ensure!(
trigger == UpdateTrigger::Scheduled || daemon.is_stable_standalone_release()?,
"installer did not select a stable latest release; retry the update"
);
if release_selection_unstable(daemon, trigger)? { if release_selection_unstable(daemon, trigger)? {
return Ok((UpdateLoopControl::Continue, None)); return Ok((UpdateLoopControl::Continue, None));
} }
@@ -370,7 +398,16 @@ async fn update_once(
let managed_codex_bin = let managed_codex_bin =
resolved_managed_codex_bin(&daemon.current_managed_codex_bin()?).await?; resolved_managed_codex_bin(&daemon.current_managed_codex_bin()?).await?;
let restart_mode = match trigger { let restart_mode = match trigger {
UpdateTrigger::Manual => RestartMode::IfBinaryOrVersionChanged, // The package can contain different resources even when its CLI binary
// is identical. A release change must also replace the running process.
UpdateTrigger::Manual | UpdateTrigger::RestoreProduction(_)
if selected_release(daemon)?.1 != previous_selection =>
{
RestartMode::Always
}
UpdateTrigger::Manual | UpdateTrigger::RestoreProduction(_) => {
RestartMode::IfBinaryOrVersionChanged
}
UpdateTrigger::Scheduled UpdateTrigger::Scheduled
if executable_identity(&managed_codex_bin).await? != *running_updater_identity => if executable_identity(&managed_codex_bin).await? != *running_updater_identity =>
{ {
@@ -405,7 +442,7 @@ async fn update_once(
)); ));
} }
RestartIfRunningOutcome::AlreadyCurrent RestartIfRunningOutcome::AlreadyCurrent
if trigger == UpdateTrigger::Manual if trigger != UpdateTrigger::Scheduled
&& restart_mode == RestartMode::IfBinaryOrVersionChanged => && restart_mode == RestartMode::IfBinaryOrVersionChanged =>
{ {
anyhow::ensure!( anyhow::ensure!(
@@ -421,7 +458,7 @@ async fn update_once(
} }
RestartIfRunningOutcome::NotReady | RestartIfRunningOutcome::AlreadyCurrent => { RestartIfRunningOutcome::NotReady | RestartIfRunningOutcome::AlreadyCurrent => {
anyhow::ensure!( anyhow::ensure!(
trigger != UpdateTrigger::Manual, trigger == UpdateTrigger::Scheduled,
"managed daemon could not restart; retry when it is ready" "managed daemon could not restart; retry when it is ready"
); );
return Ok(( return Ok((
@@ -437,12 +474,15 @@ async fn update_once(
} }
} }
fn release_selection_unstable(daemon: &Daemon, trigger: UpdateTrigger) -> Result<bool> { fn release_selection_unstable(daemon: &Daemon, trigger: UpdateTrigger<'_>) -> Result<bool> {
if daemon.is_stable_standalone_release()? { if daemon.is_stable_standalone_release()?
|| matches!(trigger, UpdateTrigger::RestoreProduction(_))
&& manual_update::supported(daemon)?
{
return Ok(false); return Ok(false);
} }
anyhow::ensure!( anyhow::ensure!(
trigger != UpdateTrigger::Manual, trigger == UpdateTrigger::Scheduled,
"standalone install selection changed during the update" "standalone install selection changed during the update"
); );
Ok(true) Ok(true)
@@ -485,6 +525,7 @@ pub(crate) fn reexec_managed_updater(managed_codex_bin: &std::path::Path) -> Res
enum InstallerMode<'a> { enum InstallerMode<'a> {
Update(&'a str), Update(&'a str),
RestoreProduction(&'a str),
Migration, Migration,
} }
@@ -509,9 +550,10 @@ async fn run_installer_script(
.kill_on_drop(true); .kill_on_drop(true);
command command
}; };
let (guard, previous_release, defer_selection) = match mode { let (latest_guard, current_guard, previous_release, defer_selection) = match mode {
InstallerMode::Update(release) => ("1", release, "0"), InstallerMode::Update(release) => ("1", "0", release, "0"),
InstallerMode::Migration => ("0", "", "1"), InstallerMode::RestoreProduction(release) => ("0", "1", release, "0"),
InstallerMode::Migration => ("0", "0", "", "1"),
}; };
let mut child = command let mut child = command
.env( .env(
@@ -532,7 +574,8 @@ async fn run_installer_script(
) )
.env("CODEX_RELEASE", "latest") .env("CODEX_RELEASE", "latest")
.env("CODEX_NON_INTERACTIVE", "1") .env("CODEX_NON_INTERACTIVE", "1")
.env("CODEX_INSTALL_IF_LATEST", guard) .env("CODEX_INSTALL_IF_LATEST", latest_guard)
.env("CODEX_INSTALL_IF_CURRENT", current_guard)
.env("CODEX_UPDATE_FROM_RELEASE", previous_release) .env("CODEX_UPDATE_FROM_RELEASE", previous_release)
.kill_on_drop(true) .kill_on_drop(true)
.stdin(Stdio::piped()) .stdin(Stdio::piped())
@@ -57,9 +57,19 @@ struct FakeInstallerHttp {
#[cfg(unix)] #[cfg(unix)]
#[tokio::test] #[tokio::test]
async fn explicit_update_migrates_running_and_stopped_installations() { async fn explicit_update_migrates_running_and_stopped_installations() {
for running in [false, true] { for (running, local) in [(false, false), (true, false), (false, true), (true, true)] {
let home = TempDir::new().unwrap(); let home = TempDir::new().unwrap();
let (legacy, release) = manual_update_daemon(&home); let (legacy, release) = manual_update_daemon(&home);
let root = home.path().join("packages/standalone");
if local {
let package = root.join("releases/local-development");
std::fs::create_dir(&package).unwrap();
std::fs::copy(&legacy.managed_codex_bin, package.join("codex")).unwrap();
std::fs::remove_file(root.join("current")).unwrap();
std::os::unix::fs::symlink(&package, root.join("current")).unwrap();
std::fs::remove_file(root.join("auto-update-version")).unwrap();
}
let previous = root.join("current").canonicalize().unwrap();
let scheduled = FakeInstallerHttp::new(InstallerResponse::Success( let scheduled = FakeInstallerHttp::new(InstallerResponse::Success(
b"# CODEX_INSTALL_IF_LATEST\ntest \"$CODEX_INSTALL_DEFER_SELECTION\" = 0 && test \"$CODEX_INSTALL_DAEMON_ONLY\" = 0\n".to_vec(), b"# CODEX_INSTALL_IF_LATEST\ntest \"$CODEX_INSTALL_DEFER_SELECTION\" = 0 && test \"$CODEX_INSTALL_DAEMON_ONLY\" = 0\n".to_vec(),
)); ));
@@ -74,7 +84,14 @@ async fn explicit_update_migrates_running_and_stopped_installations() {
) )
.await .await
.unwrap(); .unwrap();
assert_eq!(scheduled.requested_urls(), vec![INSTALL_URL.to_string()]); assert_eq!(
scheduled.requested_urls(),
if local {
vec![]
} else {
vec![INSTALL_URL.to_string()]
}
);
assert_eq!( assert_eq!(
crate::managed_install::package_root(home.path()), crate::managed_install::package_root(home.path()),
home.path().join("packages/standalone") home.path().join("packages/standalone")
@@ -109,6 +126,7 @@ async fn explicit_update_migrates_running_and_stopped_installations() {
r#"# CODEX_INSTALL_DEFER_SELECTION r#"# CODEX_INSTALL_DEFER_SELECTION
set -eu set -eu
test "$CODEX_INSTALL_DEFER_SELECTION" = 1 test "$CODEX_INSTALL_DEFER_SELECTION" = 1
test "$CODEX_INSTALL_IF_CURRENT" = 0
test "$CODEX_INSTALL_DAEMON_ONLY" = 1 test "$CODEX_INSTALL_DAEMON_ONLY" = 1
test "$CODEX_INSTALL_IF_LATEST" = 0 test "$CODEX_INSTALL_IF_LATEST" = 0
root="$CODEX_HOME/packages/app-server-daemon" root="$CODEX_HOME/packages/app-server-daemon"
@@ -152,6 +170,7 @@ printf '{release}' > "$root/auto-update-version"
dedicated.clone() dedicated.clone()
); );
assert!(!dedicated.join(".migration-current").exists()); assert!(!dedicated.join(".migration-current").exists());
assert_eq!(root.join("current").canonicalize().unwrap(), previous);
assert_eq!( assert_eq!(
std::fs::read(&legacy.managed_codex_bin).unwrap(), std::fs::read(&legacy.managed_codex_bin).unwrap(),
legacy_bin legacy_bin
@@ -377,10 +396,9 @@ async fn manual_request_recovers_when_one_shot_updater_exits() {
.await .await
.expect("remove exited updater socket"); .expect("remove exited updater socket");
}); });
// Without the marker, the ordinary startup path reports unsupported. A // Without the selected executable, the startup path reports unsupported. A
// retry that only waits for a successor would time out instead. // retry that only waits for a successor would time out instead.
std::fs::remove_file(home.path().join("packages/standalone/auto-update-version")) std::fs::remove_file(&daemon.managed_codex_bin).expect("remove selected binary");
.expect("remove latest marker");
let result = tokio::time::timeout( let result = tokio::time::timeout(
Duration::from_secs(5), Duration::from_secs(5),
super::manual_update::request(&daemon), super::manual_update::request(&daemon),
@@ -407,8 +425,15 @@ async fn unsupported_request_preserves_updater_schedule() {
let socket_path = daemon.manual_update_socket_path(); let socket_path = daemon.manual_update_socket_path();
let http = FakeInstallerHttp::new(InstallerResponse::Success(Vec::new())); let http = FakeInstallerHttp::new(InstallerResponse::Success(Vec::new()));
let updater_daemon = std::sync::Arc::clone(&daemon); let updater_daemon = std::sync::Arc::clone(&daemon);
let worker = let worker = tokio::spawn(async move {
tokio::spawn(async move { super::run_with_http(&http, &updater_daemon, &identity).await }); super::run_with_http(
&http,
&updater_daemon,
&identity,
/*restore_release*/ None,
)
.await
});
let deadline = tokio::time::Instant::now() + Duration::from_secs(5); let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
while !socket_path.exists() { while !socket_path.exists() {
assert!( assert!(
@@ -417,8 +442,23 @@ async fn unsupported_request_preserves_updater_schedule() {
); );
tokio::time::sleep(Duration::from_millis(20)).await; tokio::time::sleep(Duration::from_millis(20)).await;
} }
std::fs::remove_file(home.path().join("packages/standalone/auto-update-version")) // An external installer can pin while this ordinary worker still listens.
.expect("remove latest selection"); // Raw IPC must not gain the manual CLI's authority to restore production.
let marker = super::selected_release(&daemon)
.unwrap()
.0
.join("auto-update-version");
let previous_marker = std::fs::read(&marker).unwrap();
std::fs::remove_file(&marker).unwrap();
let mut pinned = codex_uds::UnixStream::connect(&socket_path).await.unwrap();
pinned.write_all(b"update\n").await.unwrap();
let mut response = Vec::new();
pinned.read_to_end(&mut response).await.unwrap();
let response: Result<UpdateOutput, String> = serde_json::from_slice(&response).unwrap();
assert_eq!(response.unwrap().status, UpdateStatus::Unsupported);
assert!(!marker.exists());
std::fs::write(&marker, previous_marker).unwrap();
std::fs::remove_file(&daemon.managed_codex_bin).expect("remove selected binary");
let mut malformed = codex_uds::UnixStream::connect(&socket_path) let mut malformed = codex_uds::UnixStream::connect(&socket_path)
.await .await
.expect("connect malformed request"); .expect("connect malformed request");
@@ -473,7 +513,7 @@ async fn test_control_server(
let version = if std::fs::read_to_string( let version = if std::fs::read_to_string(
crate::managed_install::package_root(&codex_home).join("auto-update-version"), crate::managed_install::package_root(&codex_home).join("auto-update-version"),
) )
.expect("selected release") .unwrap_or_default()
.starts_with("1.1.0") .starts_with("1.1.0")
{ {
"1.1.0" "1.1.0"
@@ -498,11 +538,39 @@ async fn test_control_server(
#[cfg(unix)] #[cfg(unix)]
#[tokio::test] #[tokio::test]
async fn manual_update_restarts_managed_daemon_with_automatic_updates_disabled() { async fn manual_update_restarts_managed_daemon_with_automatic_updates_disabled() {
check_manual_update_restart("standalone").await;
}
#[cfg(unix)]
#[tokio::test]
async fn manual_update_restarts_local_daemon_with_automatic_updates_disabled() {
check_manual_update_restart("app-server-daemon").await;
}
#[cfg(unix)]
async fn check_manual_update_restart(package_directory: &str) {
use tokio::io::AsyncReadExt; use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt; use tokio::io::AsyncWriteExt;
let local_package = package_directory == "app-server-daemon";
let home = TempDir::new().expect("home"); let home = TempDir::new().expect("home");
let (daemon, release) = manual_update_daemon(&home); let (mut daemon, mut release) = manual_update_daemon(&home);
let standalone = home.path().join("packages").join(package_directory);
if local_package {
std::fs::rename(home.path().join("packages/standalone"), &standalone).unwrap();
let local = format!("local-development-{release}");
std::fs::rename(
standalone.join("releases").join(&release),
standalone.join("releases").join(&local),
)
.unwrap();
std::fs::remove_file(standalone.join("current")).unwrap();
std::os::unix::fs::symlink(format!("releases/{local}"), standalone.join("current"))
.unwrap();
std::fs::remove_file(standalone.join("auto-update-version")).unwrap();
daemon.managed_codex_bin = standalone.join("current/codex");
release = local;
}
let daemon = std::sync::Arc::new(daemon); let daemon = std::sync::Arc::new(daemon);
std::fs::create_dir_all(daemon.settings_file.parent().expect("state directory")) std::fs::create_dir_all(daemon.settings_file.parent().expect("state directory"))
.expect("state directory"); .expect("state directory");
@@ -524,23 +592,44 @@ async fn manual_update_restarts_managed_daemon_with_automatic_updates_disabled()
.expect("PID") .expect("PID")
}; };
let before = current_pid(); let before = current_pid();
let next = release.replacen("1.0.0", "1.1.0", 1); let version = if local_package { "1.0.0" } else { "1.1.0" };
let standalone = home.path().join("packages/standalone"); let next = release
.trim_start_matches("local-development-")
.replacen("1.0.0", version, 1);
let guard = if local_package {
"CODEX_INSTALL_IF_CURRENT"
} else {
"CODEX_INSTALL_IF_LATEST"
};
let install_binary = if local_package {
// Same binary and version, but a different package: it must still restart.
format!(
"cp '{root}/releases/{release}/codex' '{root}/releases/{next}/bin/codex'",
root = standalone.display()
)
} else {
format!(
r#"printf '#!/bin/sh\nif [ "$1" = --version ]; then echo codex 1.1.0; else exec sleep 30; fi\n' > '{root}/releases/{next}/bin/codex'"#,
root = standalone.display()
)
};
let ready = home.path().join("installer-ready"); let ready = home.path().join("installer-ready");
let proceed = home.path().join("installer-proceed"); let proceed = home.path().join("installer-proceed");
let script = format!( let script = format!(
"#!/bin/sh\n# CODEX_INSTALL_IF_LATEST\ntest \"$CODEX_INSTALL_IF_LATEST\" = 1 || exit 4\nif [ \"$CODEX_UPDATE_FROM_RELEASE\" = '{next}' ]; then exit 0; fi\ntest \"$CODEX_UPDATE_FROM_RELEASE\" = '{release}' || exit 5\ntouch '{ready}'\nwhile [ ! -e '{proceed}' ]; do sleep .05; done\nmkdir -p '{root}/releases/{next}/bin'\nprintf '#!/bin/sh\\nif [ \"$1\" = --version ]; then echo codex 1.1.0; else exec sleep 30; fi\\n' > '{root}/releases/{next}/bin/codex'\nchmod +x '{root}/releases/{next}/bin/codex'\nln -sfn 'releases/{next}' '{root}/current'\nprintf '{next}' > '{root}/auto-update-version'\n", "#!/bin/sh\n# CODEX_INSTALL_IF_LATEST CODEX_INSTALL_IF_CURRENT CODEX_INSTALL_DAEMON_ONLY\nif [ \"$CODEX_UPDATE_FROM_RELEASE\" = '{next}' ]; then exit 0; fi\ntest \"${guard}\" = 1 || exit 4\ntest \"$CODEX_UPDATE_FROM_RELEASE\" = '{release}' || exit 5\ntouch '{ready}'\nwhile [ ! -e '{proceed}' ]; do sleep .05; done\nmkdir -p '{root}/releases/{next}/bin'\n{install_binary}\nchmod +x '{root}/releases/{next}/bin/codex'\nln -sfn 'releases/{next}' '{root}/current'\nprintf '{next}' > '{root}/auto-update-version'\n",
root = standalone.display(), root = standalone.display(),
ready = ready.display(), ready = ready.display(),
proceed = proceed.display(), proceed = proceed.display(),
); );
let http = FakeInstallerHttp::new(InstallerResponse::Success(script.into_bytes())); let http = FakeInstallerHttp::new(InstallerResponse::Success(script.into_bytes()));
let updater_daemon = std::sync::Arc::clone(&daemon); let updater_daemon = std::sync::Arc::clone(&daemon);
let restore_release = local_package.then(|| release.clone());
let worker = tokio::spawn(async move { let worker = tokio::spawn(async move {
super::run_with_http( super::run_with_http(
&http, &http,
&updater_daemon, &updater_daemon,
&executable_identity_from_bytes(b"updater"), &executable_identity_from_bytes(b"updater"),
restore_release,
) )
.await .await
}); });
@@ -574,8 +663,8 @@ async fn manual_update_restarts_managed_daemon_with_automatic_updates_disabled()
.expect("first request task") .expect("first request task")
.expect("manual update"); .expect("manual update");
assert_eq!(output.status, UpdateStatus::Updated); assert_eq!(output.status, UpdateStatus::Updated);
assert_eq!(output.installed_version.as_deref(), Some("1.1.0")); assert_eq!(output.installed_version.as_deref(), Some(version));
assert_eq!(output.running_version.as_deref(), Some("1.1.0")); assert_eq!(output.running_version.as_deref(), Some(version));
assert_eq!( assert_eq!(
output.managed_codex_path, output.managed_codex_path,
standalone.join("current/bin/codex") standalone.join("current/bin/codex")
@@ -600,7 +689,7 @@ async fn manual_update_restarts_managed_daemon_with_automatic_updates_disabled()
.expect("updater task") .expect("updater task")
.expect("updater loop"); .expect("updater loop");
let no_op = FakeInstallerHttp::new(InstallerResponse::Success( let no_op = FakeInstallerHttp::new(InstallerResponse::Success(
b"#!/bin/sh\n# CODEX_INSTALL_IF_LATEST\nexit 0\n".to_vec(), b"#!/bin/sh\n# CODEX_INSTALL_IF_LATEST CODEX_INSTALL_DAEMON_ONLY\nexit 0\n".to_vec(),
)); ));
use std::io::Write; use std::io::Write;
std::fs::OpenOptions::new() std::fs::OpenOptions::new()
@@ -618,6 +707,7 @@ async fn manual_update_restarts_managed_daemon_with_automatic_updates_disabled()
&daemon, &daemon,
&executable_identity_from_bytes(b"updater"), &executable_identity_from_bytes(b"updater"),
&mut test_terminate(), &mut test_terminate(),
super::UpdateTrigger::Manual,
) )
.await .await
.expect("retry with stale running binary"); .expect("retry with stale running binary");
@@ -635,6 +725,7 @@ async fn powershell_installer_is_noninteractive_and_reports_script_failure() {
function Test-Installer { function Test-Installer {
if ($env:CODEX_NON_INTERACTIVE -ne '1') { throw 'interactive installer' } if ($env:CODEX_NON_INTERACTIVE -ne '1') { throw 'interactive installer' }
if ($env:CODEX_INSTALL_DAEMON_ONLY -ne '1') { throw 'wrong package destination' } if ($env:CODEX_INSTALL_DAEMON_ONLY -ne '1') { throw 'wrong package destination' }
if ($env:CODEX_INSTALL_IF_CURRENT -ne '1' -or $env:CODEX_INSTALL_IF_LATEST -ne '0') { throw 'wrong update guard' }
} }
Test-Installer Test-Installer
"# "#
@@ -645,7 +736,7 @@ Test-Installer
.expect("fetch installer"); .expect("fetch installer");
super::run_installer_script( super::run_installer_script(
&script, &script,
super::InstallerMode::Update("0.150.0-x86_64-pc-windows-msvc"), super::InstallerMode::RestoreProduction("0.150.0-x86_64-pc-windows-msvc"),
std::path::Path::new("packages/app-server-daemon"), std::path::Path::new("packages/app-server-daemon"),
) )
.await .await
@@ -659,7 +750,7 @@ Test-Installer
assert!( assert!(
super::run_installer_script( super::run_installer_script(
&script, &script,
super::InstallerMode::Update("0.150.0-x86_64-pc-windows-msvc"), super::InstallerMode::RestoreProduction("0.150.0-x86_64-pc-windows-msvc"),
std::path::Path::new("packages/app-server-daemon") std::path::Path::new("packages/app-server-daemon")
) )
.await .await
@@ -692,6 +783,7 @@ async fn update_rejects_a_package_root_change_during_download() {
&daemon, &daemon,
&identity, &identity,
&mut test_terminate(), &mut test_terminate(),
super::UpdateTrigger::Manual,
) )
.await .await
.unwrap_err(); .unwrap_err();
@@ -702,7 +794,7 @@ async fn update_rejects_a_package_root_change_during_download() {
#[tokio::test] #[tokio::test]
async fn daemon_owned_updates_require_and_request_an_isolated_installer() { async fn daemon_owned_updates_require_and_request_an_isolated_installer() {
let home = TempDir::new().unwrap(); let home = TempDir::new().unwrap();
let (mut daemon, _) = manual_update_daemon(&home); let (mut daemon, release) = manual_update_daemon(&home);
let root = home.path().join("packages/app-server-daemon"); let root = home.path().join("packages/app-server-daemon");
std::fs::rename(home.path().join("packages/standalone"), &root).unwrap(); std::fs::rename(home.path().join("packages/standalone"), &root).unwrap();
daemon.managed_codex_bin = root.join("current/codex"); daemon.managed_codex_bin = root.join("current/codex");
@@ -712,7 +804,13 @@ async fn daemon_owned_updates_require_and_request_an_isolated_installer() {
let old = FakeInstallerHttp::new(InstallerResponse::Success( let old = FakeInstallerHttp::new(InstallerResponse::Success(
b"# CODEX_INSTALL_IF_LATEST\nexit 0\n".to_vec(), b"# CODEX_INSTALL_IF_LATEST\nexit 0\n".to_vec(),
)); ));
let error = manual_update_once(&old, &daemon, &identity, &mut test_terminate()) let error = manual_update_once(
&old,
&daemon,
&identity,
&mut test_terminate(),
super::UpdateTrigger::Manual,
)
.await .await
.unwrap_err(); .unwrap_err();
assert!( assert!(
@@ -721,11 +819,73 @@ async fn daemon_owned_updates_require_and_request_an_isolated_installer() {
.contains("does not support daemon-owned packages") .contains("does not support daemon-owned packages")
); );
let current = FakeInstallerHttp::new(InstallerResponse::Success( let current = FakeInstallerHttp::new(InstallerResponse::Success(
b"# CODEX_INSTALL_IF_LATEST\ntest \"$CODEX_INSTALL_DAEMON_ONLY\" = 1\n".to_vec(), b"# CODEX_INSTALL_IF_LATEST\ntest \"$CODEX_INSTALL_IF_LATEST\" = 1 && test \"$CODEX_INSTALL_DAEMON_ONLY\" = 1\n".to_vec(),
)); ));
let output = manual_update_once(&current, &daemon, &identity, &mut test_terminate()) let output = manual_update_once(
&current,
&daemon,
&identity,
&mut test_terminate(),
super::UpdateTrigger::Manual,
)
.await .await
.unwrap(); .unwrap();
assert_eq!(output.status, UpdateStatus::NoUpdate); assert_eq!(output.status, UpdateStatus::NoUpdate);
assert!(!home.path().join("packages/standalone").exists()); assert!(!home.path().join("packages/standalone").exists());
// Reuse the stopped daemon to verify explicit unpinning with either preference.
let marker = root.join("auto-update-version");
let no_op = FakeInstallerHttp::new(InstallerResponse::Success(
b"# CODEX_INSTALL_IF_CURRENT CODEX_INSTALL_DAEMON_ONLY\nexit 0\n".to_vec(),
));
let script = format!(
r#"# CODEX_INSTALL_IF_CURRENT CODEX_INSTALL_DAEMON_ONLY
set -eu
test "$CODEX_INSTALL_IF_CURRENT" = 1
test "$CODEX_INSTALL_IF_LATEST" = 0
test "$CODEX_INSTALL_DAEMON_ONLY" = 1
test "$CODEX_RELEASE" = latest
test "$CODEX_UPDATE_FROM_RELEASE" = '{release}'
printf '%s' '{release}' > '{marker}'
"#,
marker = marker.display()
);
let restore = FakeInstallerHttp::new(InstallerResponse::Success(script.into_bytes()));
for auto_update_enabled in [false, true] {
let settings = format!(r#"{{"updater":{{"autoUpdateEnabled":{auto_update_enabled}}}}}"#);
std::fs::write(&daemon.settings_file, &settings).unwrap();
std::fs::remove_file(&marker).unwrap();
let error = manual_update_once(
&no_op,
&daemon,
&identity,
&mut test_terminate(),
super::UpdateTrigger::RestoreProduction(&release),
)
.await
.unwrap_err();
assert!(
error
.to_string()
.contains("did not select a stable latest release")
);
assert!(!marker.exists());
let restored = manual_update_once(
&restore,
&daemon,
&identity,
&mut test_terminate(),
super::UpdateTrigger::RestoreProduction(&release),
)
.await
.unwrap();
// Restoring eligibility for the same package still reports noUpdate.
assert_eq!(restored, output);
assert!(!daemon.pid_file.exists());
assert!(daemon.is_stable_standalone_release().unwrap());
assert_eq!(
std::fs::read_to_string(&daemon.settings_file).unwrap(),
settings
);
}
} }
+1 -1
View File
@@ -23,7 +23,7 @@ pub(crate) fn confirm_install(request: &InstallRequest, yes: bool) -> Result<boo
fn describe_install(request: &InstallRequest) -> String { fn describe_install(request: &InstallRequest) -> String {
let mut message = format!( let mut message = format!(
"Replace installed daemon version {} with CLI version {} from {}.\nThe daemon package will be installed in {}.\nThe selected package will be pinned.", "Replace installed daemon version {} with CLI version {} from {}.\nThe daemon package will be installed in {}.\nThe selected package will be pinned. Run `codex app-server daemon update` to return to production updates.",
request.installed_version.as_deref().unwrap_or("unknown"), request.installed_version.as_deref().unwrap_or("unknown"),
request.version, request.version,
request.source.display(), request.source.display(),
+1 -1
View File
@@ -12,7 +12,7 @@ fn running_daemon_replacement_prompt() {
insta::assert_snapshot!(describe_install(&request), @r" insta::assert_snapshot!(describe_install(&request), @r"
Replace installed daemon version 0.152.0 with CLI version 0.0.0 from /cli/package. Replace installed daemon version 0.152.0 with CLI version 0.0.0 from /cli/package.
The daemon package will be installed in /home/packages/app-server-daemon. The daemon package will be installed in /home/packages/app-server-daemon.
The selected package will be pinned. The selected package will be pinned. Run `codex app-server daemon update` to return to production updates.
The running daemon will restart; active or queued work may be interrupted. The running daemon will restart; active or queued work may be interrupted.
"); ");
} }
+15 -1
View File
@@ -821,6 +821,9 @@ enum AppServerDaemonSubcommand {
/// Check support for daemon-owned packages without starting the updater. /// Check support for daemon-owned packages without starting the updater.
#[arg(long, hide = true)] #[arg(long, hide = true)]
check_package_ownership: bool, check_package_ownership: bool,
/// Authorize one production restoration of this selected release.
#[arg(long, hide = true)]
restore_release: Option<String>,
}, },
} }
@@ -1434,12 +1437,14 @@ async fn cli_main(
} }
AppServerDaemonSubcommand::PidUpdateLoop { AppServerDaemonSubcommand::PidUpdateLoop {
check_package_ownership: true, check_package_ownership: true,
..
} => return Ok(()), } => return Ok(()),
AppServerDaemonSubcommand::Update { AppServerDaemonSubcommand::Update {
from_cli: false, .. from_cli: false, ..
} }
| AppServerDaemonSubcommand::PidUpdateLoop { | AppServerDaemonSubcommand::PidUpdateLoop {
check_package_ownership: false, check_package_ownership: false,
..
} => { } => {
let cli_overrides = root_config_overrides let cli_overrides = root_config_overrides
.parse_overrides() .parse_overrides()
@@ -1458,7 +1463,16 @@ async fn cli_main(
codex_app_server_daemon::update(http_client_factory).await?; codex_app_server_daemon::update(http_client_factory).await?;
println!("{}", serde_json::to_string(&output)?); println!("{}", serde_json::to_string(&output)?);
} else { } else {
codex_app_server_daemon::run_pid_update_loop(http_client_factory) let AppServerDaemonSubcommand::PidUpdateLoop {
restore_release, ..
} = daemon_cli.subcommand
else {
unreachable!()
};
codex_app_server_daemon::run_pid_update_loop(
http_client_factory,
restore_release,
)
.await?; .await?;
} }
} }
+1 -2
View File
@@ -353,7 +353,6 @@ fn managed_start_keeps_updater_on_marker_mismatch_but_stops_it_for_pin() -> Resu
std::fs::write(&marker, "0.1.0-other-target")?; std::fs::write(&marker, "0.1.0-other-target")?;
assert_eq!(daemon.lifecycle("start")?["status"], "alreadyRunning"); assert_eq!(daemon.lifecycle("start")?["status"], "alreadyRunning");
assert_eq!(daemon.pid("app-server-updater.pid")?, updater_pid); assert_eq!(daemon.pid("app-server-updater.pid")?, updater_pid);
assert_eq!(daemon.lifecycle("update")?["status"], "unsupported");
std::thread::sleep(Duration::from_millis(250)); std::thread::sleep(Duration::from_millis(250));
let updater_state = Command::new("/bin/ps") let updater_state = Command::new("/bin/ps")
.args(["-p", &updater_pid.to_string(), "-o", "stat="]) .args(["-p", &updater_pid.to_string(), "-o", "stat="])
@@ -457,7 +456,7 @@ fn manual_update_rejects_an_unowned_installation() -> Result<()> {
daemon daemon
.home .home
.path() .path()
.join("packages/standalone/auto-update-version"), .join("packages/standalone/current/bin/codex"),
)?; )?;
assert_eq!(daemon.lifecycle("update")?["status"], "unsupported"); assert_eq!(daemon.lifecycle("update")?["status"], "unsupported");
+47 -11
View File
@@ -507,7 +507,8 @@ function Move-OldStandaloneBinIfApproved {
} }
function Add-JunctionSupportType { function Add-JunctionSupportType {
if (([System.Management.Automation.PSTypeName]'CodexInstaller.Junction').Type) { # Older installer types remain loaded when users rerun irm | iex in one session.
if (([System.Management.Automation.PSTypeName]'CodexInstaller.JunctionV2').Type) {
return return
} }
@@ -521,7 +522,7 @@ using Microsoft.Win32.SafeHandles;
namespace CodexInstaller namespace CodexInstaller
{ {
public static class Junction public static class JunctionV2
{ {
private const uint GENERIC_WRITE = 0x40000000; private const uint GENERIC_WRITE = 0x40000000;
private const uint FILE_SHARE_READ = 0x00000001; private const uint FILE_SHARE_READ = 0x00000001;
@@ -555,6 +556,25 @@ namespace CodexInstaller
out int lpBytesReturned, out int lpBytesReturned,
IntPtr lpOverlapped); IntPtr lpOverlapped);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern uint GetFinalPathNameByHandleW(
SafeFileHandle file, StringBuilder path, uint length, uint flags);
public static string ResolveDirectory(string path)
{
using (SafeFileHandle handle = CreateFileW(
path, 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
IntPtr.Zero, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, IntPtr.Zero))
{
if (handle.IsInvalid) { throw new Win32Exception(Marshal.GetLastWin32Error()); }
StringBuilder resolved = new StringBuilder(32768);
uint length = GetFinalPathNameByHandleW(handle, resolved, (uint)resolved.Capacity, 0);
if (length == 0) { throw new Win32Exception(Marshal.GetLastWin32Error()); }
if (length >= resolved.Capacity) { throw new IOException("Resolved path is too long."); }
return resolved.ToString().TrimEnd('\\');
}
}
public static void SetTarget(string linkPath, string targetPath) public static void SetTarget(string linkPath, string targetPath)
{ {
string substituteName = "\\??\\" + Path.GetFullPath(targetPath); string substituteName = "\\??\\" + Path.GetFullPath(targetPath);
@@ -626,7 +646,7 @@ function Set-JunctionTarget {
) )
Add-JunctionSupportType Add-JunctionSupportType
[CodexInstaller.Junction]::SetTarget($LinkPath, $TargetPath) [CodexInstaller.JunctionV2]::SetTarget($LinkPath, $TargetPath)
} }
function Test-IsJunction { function Test-IsJunction {
@@ -656,14 +676,15 @@ function Ensure-Junction {
$item = Get-Item -LiteralPath $LinkPath -Force $item = Get-Item -LiteralPath $LinkPath -Force
if (Test-IsJunction -Path $LinkPath) { if (Test-IsJunction -Path $LinkPath) {
$existingTarget = [string]$item.Target Add-JunctionSupportType
$existingTarget = [CodexInstaller.JunctionV2]::ResolveDirectory($LinkPath)
if (-not [string]::IsNullOrWhiteSpace($InstallerOwnedTargetPrefix)) { if (-not [string]::IsNullOrWhiteSpace($InstallerOwnedTargetPrefix)) {
$ownedTargetPrefix = $InstallerOwnedTargetPrefix.TrimEnd("\\") $ownedTargetPrefix = [CodexInstaller.JunctionV2]::ResolveDirectory($InstallerOwnedTargetPrefix) + "\"
if (-not $existingTarget.StartsWith($ownedTargetPrefix, [System.StringComparison]::OrdinalIgnoreCase)) { if (-not $existingTarget.StartsWith($ownedTargetPrefix, [System.StringComparison]::OrdinalIgnoreCase)) {
throw "Refusing to retarget junction at $LinkPath because it is not managed by this installer." throw "Refusing to retarget junction at $LinkPath because it is not managed by this installer."
} }
} }
if ($existingTarget.Equals($TargetPath, [System.StringComparison]::OrdinalIgnoreCase)) { if ($existingTarget.Equals([CodexInstaller.JunctionV2]::ResolveDirectory($TargetPath), [System.StringComparison]::OrdinalIgnoreCase)) {
return return
} }
@@ -957,7 +978,7 @@ try {
$updaterRecord = Join-Path $codexHome "app-server-daemon\app-server-updater.pid" $updaterRecord = Join-Path $codexHome "app-server-daemon\app-server-updater.pid"
if ($daemonOnly) { $updaterRecord = Join-Path $codexHome "app-server-daemon\daemon-updater.pid" } if ($daemonOnly) { $updaterRecord = Join-Path $codexHome "app-server-daemon\daemon-updater.pid" }
$oldUpdaterParent = $false $oldUpdaterParent = $false
if ($Release -eq "latest" -and $env:CODEX_INSTALL_IF_LATEST -ne "1" -and (Test-Path -LiteralPath $updaterRecord)) { if ($Release -eq "latest" -and $env:CODEX_INSTALL_IF_LATEST -ne "1" -and $env:CODEX_INSTALL_IF_CURRENT -ne "1" -and (Test-Path -LiteralPath $updaterRecord)) {
$updaterPid = $null $updaterPid = $null
$updaterStartTime = $null $updaterStartTime = $null
try { try {
@@ -985,17 +1006,25 @@ try {
} }
} }
} }
if ($env:CODEX_INSTALL_IF_LATEST -eq "1" -or $oldUpdaterParent) { if ($env:CODEX_INSTALL_IF_LATEST -eq "1" -or $env:CODEX_INSTALL_IF_CURRENT -eq "1" -or $oldUpdaterParent) {
$previousRelease = if ($oldUpdaterParent -and (Test-Path -LiteralPath $autoUpdateVersion)) { $previousRelease = if ($oldUpdaterParent -and (Test-Path -LiteralPath $autoUpdateVersion)) {
[System.IO.File]::ReadAllText($autoUpdateVersion) [System.IO.File]::ReadAllText($autoUpdateVersion)
} else { } else {
$env:CODEX_UPDATE_FROM_RELEASE $env:CODEX_UPDATE_FROM_RELEASE
} }
Add-JunctionSupportType
$currentTarget = if (Test-Path -LiteralPath $currentDir) { (Get-Item -LiteralPath $currentDir).Target } else { $null } $currentTarget = if (Test-Path -LiteralPath $currentDir) { (Get-Item -LiteralPath $currentDir).Target } else { $null }
if ($Release -ne "latest" -or [string]::IsNullOrEmpty($previousRelease) -or [string]::IsNullOrEmpty($currentTarget) -or if ($Release -ne "latest" -or [string]::IsNullOrEmpty($previousRelease) -or [string]::IsNullOrEmpty($currentTarget) -or
-not (Test-Path -LiteralPath $autoUpdateVersion) -or -not (Test-Path -LiteralPath (Join-Path $releasesDir $previousRelease)) -or
[System.IO.File]::ReadAllText($autoUpdateVersion) -cne $previousRelease -or [CodexInstaller.JunctionV2]::ResolveDirectory($currentDir) -ne [CodexInstaller.JunctionV2]::ResolveDirectory((Join-Path $releasesDir $previousRelease))) {
[System.IO.Path]::GetFullPath($currentTarget) -ne [System.IO.Path]::GetFullPath((Join-Path $releasesDir $previousRelease))) { if ($env:CODEX_INSTALL_IF_CURRENT -eq "1") { throw "Daemon selection changed; retry the update." }
$script:guardRejected = $true
return
}
# Explicit daemon updates may leave a local or pinned release.
if ($env:CODEX_INSTALL_IF_CURRENT -ne "1" -and
(-not (Test-Path -LiteralPath $autoUpdateVersion) -or
[System.IO.File]::ReadAllText($autoUpdateVersion) -cne $previousRelease)) {
$script:guardRejected = $true $script:guardRejected = $true
return return
} }
@@ -1069,6 +1098,13 @@ try {
if ($deferSelection -and (Get-Item -LiteralPath (Join-Path $standaloneRoot "current") -Force -ErrorAction SilentlyContinue)) { if ($deferSelection -and (Get-Item -LiteralPath (Join-Path $standaloneRoot "current") -Force -ErrorAction SilentlyContinue)) {
throw "A dedicated daemon is already selected; retry the update." throw "A dedicated daemon is already selected; retry the update."
} }
if ($daemonOnly -and -not $deferSelection) {
$installedCodex = Join-Path $releaseDir $(if ($installLayout -eq "Package") { "bin\codex.exe" } else { "codex.exe" })
& $installedCodex app-server daemon pid-update-loop --check-package-ownership | Out-Null
if ($LASTEXITCODE -ne 0) {
throw "The production release does not support daemon-owned packages; the current selection was left unchanged."
}
}
Ensure-Junction -LinkPath $currentDir -TargetPath $releaseDir -InstallerOwnedTargetPrefix $releasesDir Ensure-Junction -LinkPath $currentDir -TargetPath $releaseDir -InstallerOwnedTargetPrefix $releasesDir
if ($Release -eq "latest") { if ($Release -eq "latest") {
$tempMarker = "$autoUpdateVersion.tmp.$PID" $tempMarker = "$autoUpdateVersion.tmp.$PID"
+22 -3
View File
@@ -1177,7 +1177,7 @@ if [ "$DAEMON_ONLY" = "1" ]; then
updater_record="$CODEX_HOME_DIR/app-server-daemon/daemon-updater.pid" updater_record="$CODEX_HOME_DIR/app-server-daemon/daemon-updater.pid"
fi fi
old_updater_parent="false" old_updater_parent="false"
if [ "${CODEX_INSTALL_IF_LATEST:-}" != "1" ] && [ -f "$updater_record" ]; then if [ "${CODEX_INSTALL_IF_LATEST:-}" != "1" ] && [ "${CODEX_INSTALL_IF_CURRENT:-}" != "1" ] && [ -f "$updater_record" ]; then
updater_pid="$(sed -n 's/.*"pid"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' "$updater_record" | head -n 1)" updater_pid="$(sed -n 's/.*"pid"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' "$updater_record" | head -n 1)"
recorded_start="$(sed -n 's/.*"processStartTime"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$updater_record" | head -n 1)" recorded_start="$(sed -n 's/.*"processStartTime"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$updater_record" | head -n 1)"
if [ -r "/proc/$$/stat" ]; then if [ -r "/proc/$$/stat" ]; then
@@ -1201,7 +1201,7 @@ if [ "${CODEX_INSTALL_IF_LATEST:-}" != "1" ] && [ -f "$updater_record" ]; then
exit 0 exit 0
fi fi
fi fi
if [ "${CODEX_INSTALL_IF_LATEST:-}" = "1" ] || [ "$old_updater_parent" = "true" ]; then if [ "${CODEX_INSTALL_IF_LATEST:-}" = "1" ] || [ "${CODEX_INSTALL_IF_CURRENT:-}" = "1" ] || [ "$old_updater_parent" = "true" ]; then
guarded_release="${CODEX_UPDATE_FROM_RELEASE:-}" guarded_release="${CODEX_UPDATE_FROM_RELEASE:-}"
if [ "$old_updater_parent" = "true" ]; then if [ "$old_updater_parent" = "true" ]; then
guarded_release="$(cat "$AUTO_UPDATE_VERSION" 2>/dev/null || true)" guarded_release="$(cat "$AUTO_UPDATE_VERSION" 2>/dev/null || true)"
@@ -1209,8 +1209,17 @@ if [ "${CODEX_INSTALL_IF_LATEST:-}" = "1" ] || [ "$old_updater_parent" = "true"
current_release_dir="$(cd -P "$CURRENT_LINK" 2>/dev/null && pwd)" || exit 0 current_release_dir="$(cd -P "$CURRENT_LINK" 2>/dev/null && pwd)" || exit 0
releases_dir="$(cd -P "$RELEASES_DIR" 2>/dev/null && pwd)" || exit 0 releases_dir="$(cd -P "$RELEASES_DIR" 2>/dev/null && pwd)" || exit 0
if [ "$RELEASE" != "latest" ] || [ -z "$guarded_release" ] || if [ "$RELEASE" != "latest" ] || [ -z "$guarded_release" ] ||
[ "$(cat "$AUTO_UPDATE_VERSION" 2>/dev/null || true)" != "$guarded_release" ] ||
[ "$current_release_dir" != "$releases_dir/$guarded_release" ]; then [ "$current_release_dir" != "$releases_dir/$guarded_release" ]; then
if [ "${CODEX_INSTALL_IF_CURRENT:-}" = "1" ]; then
echo "Daemon selection changed; retry the update." >&2
exit 1
fi
exit 0
fi
# An explicit daemon update may leave a local or pinned release. Scheduled
# updates still require the selected release to follow the latest channel.
if [ "${CODEX_INSTALL_IF_CURRENT:-}" != "1" ] &&
[ "$(cat "$AUTO_UPDATE_VERSION" 2>/dev/null || true)" != "$guarded_release" ]; then
exit 0 exit 0
fi fi
fi fi
@@ -1249,6 +1258,16 @@ if ! release_dir_is_complete "$release_dir" "$resolved_version" "$vendor_target"
echo "Installed Codex command did not report expected version $resolved_version." >&2 echo "Installed Codex command did not report expected version $resolved_version." >&2
exit 1 exit 1
fi fi
if [ "$DAEMON_ONLY" = "1" ] && [ "${CODEX_INSTALL_DEFER_SELECTION:-0}" != "1" ]; then
installed_codex="$release_dir/codex"
if [ "$install_layout" = "package" ]; then
installed_codex="$release_dir/bin/codex"
fi
if ! "$installed_codex" app-server daemon pid-update-loop --check-package-ownership >/dev/null 2>&1; then
echo "The production release does not support daemon-owned packages; the current selection was left unchanged." >&2
exit 1
fi
fi
update_current_link "$release_dir" update_current_link "$release_dir"
if [ "$RELEASE" = "latest" ]; then if [ "$RELEASE" = "latest" ]; then
printf '%s' "$release_name" > "$AUTO_UPDATE_VERSION.tmp.$$" printf '%s' "$release_name" > "$AUTO_UPDATE_VERSION.tmp.$$"
+60 -1
View File
@@ -183,6 +183,63 @@ class InstallShTest(unittest.TestCase):
(daemon / "current").resolve(), daemon / "releases" / release_name (daemon / "current").resolve(), daemon / "releases" / release_name
) )
self.assertEqual((daemon / "auto-update-version").read_text(), release_name) self.assertEqual((daemon / "auto-update-version").read_text(), release_name)
options["daemon_only"] = True
local = daemon / "releases/local-development"
local.mkdir()
(daemon / "current").unlink()
(daemon / "current").symlink_to(local)
marker = daemon / "auto-update-version"
marker.unlink()
scheduled, _ = run_installer_in(
root, "latest", update_guard_from_release=local.name, **options
)
self.assertEqual(scheduled.returncode, 0, scheduled.stderr)
self.assertEqual((daemon / "current").resolve(), local)
self.assertFalse(marker.exists())
raced, _ = run_installer_in(
root,
"latest",
update_guard_from_release="a-different-release",
manual_update=True,
**options,
)
self.assertNotEqual(raced.returncode, 0, raced.stderr)
self.assertEqual((daemon / "current").resolve(), local)
self.assertFalse(marker.exists())
binary = daemon / "releases" / release_name / "bin/codex"
contents = binary.read_text()
binary.write_text(
'#!/bin/sh\n[ "$1" = "--version" ] || exit 2\n'
f"echo codex-cli {VERSION}\n"
)
incompatible, _ = run_installer_in(
root,
"latest",
update_guard_from_release=local.name,
manual_update=True,
**options,
)
self.assertNotEqual(incompatible.returncode, 0)
self.assertIn("does not support daemon-owned packages", incompatible.stderr)
self.assertEqual((daemon / "current").resolve(), local)
self.assertFalse(marker.exists())
binary.write_text(contents)
restored, _ = run_installer_in(
root,
"latest",
update_guard_from_release=local.name,
manual_update=True,
**options,
)
self.assertEqual(restored.returncode, 0, restored.stderr)
self.assertEqual(
(daemon / "current").resolve(), daemon / "releases" / release_name
)
self.assertEqual(marker.read_text(), release_name)
self.assertEqual(visible.resolve(), original) self.assertEqual(visible.resolve(), original)
self.assertTrue(pending.is_symlink()) self.assertTrue(pending.is_symlink())
self.assertEqual(profile.read_text(), "unchanged profile\n") self.assertEqual(profile.read_text(), "unchanged profile\n")
@@ -672,6 +729,7 @@ def run_installer_in(
old_updater_parent_pid: int | None = None, old_updater_parent_pid: int | None = None,
fail_ps: bool = False, fail_ps: bool = False,
daemon_only: bool = False, daemon_only: bool = False,
manual_update: bool = False,
) -> tuple[subprocess.CompletedProcess[str], list[str]]: ) -> tuple[subprocess.CompletedProcess[str], list[str]]:
bin_dir = root / "bin" bin_dir = root / "bin"
bin_dir.mkdir(exist_ok=True) bin_dir.mkdir(exist_ok=True)
@@ -831,11 +889,12 @@ def run_installer_in(
"SHELL": "/bin/sh", "SHELL": "/bin/sh",
} }
) )
env["CODEX_INSTALL_IF_CURRENT"] = "1" if manual_update else "0"
if update_guard_from_release is None: if update_guard_from_release is None:
env.pop("CODEX_INSTALL_IF_LATEST", None) env.pop("CODEX_INSTALL_IF_LATEST", None)
env.pop("CODEX_UPDATE_FROM_RELEASE", None) env.pop("CODEX_UPDATE_FROM_RELEASE", None)
else: else:
env["CODEX_INSTALL_IF_LATEST"] = "1" env["CODEX_INSTALL_IF_LATEST"] = "0" if manual_update else "1"
env["CODEX_UPDATE_FROM_RELEASE"] = update_guard_from_release env["CODEX_UPDATE_FROM_RELEASE"] = update_guard_from_release
if old_updater_parent_pid is not None: if old_updater_parent_pid is not None:
env["CODEX_TEST_PARENT_PID"] = str(old_updater_parent_pid) env["CODEX_TEST_PARENT_PID"] = str(old_updater_parent_pid)