mirror of
https://github.com/openai/codex.git
synced 2026-12-05 01:00:54 +00:00
Fix daemon updater socket binding and bootstrap readiness on Unix (#53845)
## Why The updater bound its socket directly beneath `CODEX_HOME`, which can exceed Unix socket path limits. Bootstrap could also report success before the updater's manual-update socket was ready. ## What changed - Reuse the control socket's protected binding and cleanup guard for the updater, with a symlink at the advertised socket path. - Remove stale updater socket entries before startup while preserving regular files. - Wait up to 30 seconds for supported automatic updaters to publish their socket, without connecting as a readiness probe. Report updater exit or timeout with stderr log context. - Preserve compatibility with older updaters that lack the manual-update command. ## Testing Add Unix integration tests for updater readiness with a long `CODEX_HOME` path and bootstrap failure when a regular file blocks the updater socket, verifying that the file is preserved and the daemon remains running. GitOrigin-RevId: 57fdcbe4e6907ece68ba66178cf81f258527560c
This commit is contained in:
@@ -853,6 +853,19 @@ impl Daemon {
|
||||
backend::pid_update_loop_backend(self.backend_paths(&settings))
|
||||
.stop()
|
||||
.await?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::FileTypeExt;
|
||||
|
||||
// A stopped older updater can leave its socket behind. Remove only
|
||||
// the rendezvous entry before starting, so readiness cannot be stale.
|
||||
let path = self.manual_update_socket_path();
|
||||
if let Ok(metadata) = tokio::fs::symlink_metadata(&path).await
|
||||
&& (metadata.file_type().is_socket() || metadata.file_type().is_symlink())
|
||||
{
|
||||
tokio::fs::remove_file(path).await?;
|
||||
}
|
||||
}
|
||||
if let Some(backend) = self.running_backend_instance(&settings).await? {
|
||||
if let Err(err) = thread_recovery::discard_pending(self) {
|
||||
eprintln!("warning: failed to clear stale daemon recovery before bootstrap: {err}");
|
||||
@@ -866,6 +879,46 @@ impl Daemon {
|
||||
backend.start().await?;
|
||||
let info = self.wait_until_ready().await?;
|
||||
let auto_update_enabled = managed.ensure_managed_updater(&settings).await?;
|
||||
#[cfg(unix)]
|
||||
// Older automatic updaters have no manual request socket to wait for.
|
||||
if auto_update_enabled
|
||||
&& managed_install::supports_daemon_command(
|
||||
&managed.managed_codex_bin,
|
||||
&["update", "--help"],
|
||||
)
|
||||
.await
|
||||
{
|
||||
use std::os::unix::fs::FileTypeExt;
|
||||
|
||||
let updater = backend::pid_update_loop_backend(managed.backend_paths(&settings));
|
||||
let path = managed.manual_update_socket_path();
|
||||
// Match the manual-update client's startup allowance: the updater
|
||||
// verifies its executable before publishing its listener.
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(30);
|
||||
loop {
|
||||
// Do not connect: even an empty probe can consume a one-shot
|
||||
// updater's restore authority. Old updaters also publish sockets.
|
||||
let running = updater.is_starting_or_running().await?;
|
||||
if running
|
||||
&& tokio::fs::metadata(&path)
|
||||
.await
|
||||
.is_ok_and(|metadata| metadata.file_type().is_socket())
|
||||
{
|
||||
break;
|
||||
}
|
||||
if !running || tokio::time::Instant::now() >= deadline {
|
||||
let reason = if running { "timed out" } else { "exited" };
|
||||
let mut context = format!(
|
||||
"daemon updater {reason} before becoming ready on {}",
|
||||
path.display()
|
||||
);
|
||||
backend::append_stderr_log_tail_context(&managed.update_pid_file, &mut context)
|
||||
.await;
|
||||
return Err(anyhow!(context));
|
||||
}
|
||||
sleep(START_POLL_INTERVAL).await;
|
||||
}
|
||||
}
|
||||
let managed_codex_version = managed.managed_codex_version_best_effort().await;
|
||||
Ok(BootstrapOutput {
|
||||
status: BootstrapStatus::Bootstrapped,
|
||||
|
||||
@@ -130,10 +130,17 @@ async fn run_with_http(
|
||||
.context("updater socket has no parent")?,
|
||||
)
|
||||
.await?;
|
||||
if socket_path.exists() {
|
||||
tokio::fs::remove_file(&socket_path).await?;
|
||||
}
|
||||
let mut listener = Some(codex_uds::UnixListener::bind(&socket_path).await?);
|
||||
#[cfg(unix)]
|
||||
let (listener, _socket_guard) =
|
||||
codex_app_server_transport::bind_private_daemon_socket(&socket_path).await?;
|
||||
#[cfg(windows)]
|
||||
let listener = {
|
||||
if socket_path.exists() {
|
||||
tokio::fs::remove_file(&socket_path).await?;
|
||||
}
|
||||
codex_uds::UnixListener::bind(&socket_path).await?
|
||||
};
|
||||
let mut listener = Some(listener);
|
||||
#[cfg(windows)]
|
||||
updater.mark_ready().await?;
|
||||
let needs_managed_handoff =
|
||||
|
||||
@@ -23,6 +23,7 @@ pub use transport::AppServerTransportParseError;
|
||||
pub use transport::CHANNEL_CAPACITY;
|
||||
pub use transport::ConnectionOrigin;
|
||||
pub use transport::DaemonShutdownAccess;
|
||||
pub use transport::DaemonSocketFileGuard;
|
||||
pub use transport::REMOTE_CONTROL_DISABLED_ENV_VAR;
|
||||
pub use transport::RemoteControlDisabledByRequirements;
|
||||
pub use transport::RemoteControlEnableError;
|
||||
@@ -35,6 +36,7 @@ pub use transport::TransportEvent;
|
||||
pub use transport::acquire_app_server_startup_lock;
|
||||
pub use transport::app_server_control_socket_path;
|
||||
pub use transport::app_server_startup_lock_path;
|
||||
pub use transport::bind_private_daemon_socket;
|
||||
pub use transport::daemon_recovery_file_path;
|
||||
pub use transport::start_control_socket_acceptor;
|
||||
pub use transport::start_remote_control;
|
||||
|
||||
@@ -43,7 +43,9 @@ pub use remote_control::take_remote_control_disabled_env;
|
||||
pub use stdio::start_stdio_connection;
|
||||
pub use unix_socket::AppServerStartupLock;
|
||||
pub use unix_socket::DaemonShutdownAccess;
|
||||
pub use unix_socket::DaemonSocketFileGuard;
|
||||
pub use unix_socket::acquire_app_server_startup_lock;
|
||||
pub use unix_socket::bind_private_daemon_socket;
|
||||
pub use unix_socket::start_control_socket_acceptor;
|
||||
pub use websocket::start_websocket_acceptor;
|
||||
|
||||
|
||||
@@ -46,6 +46,27 @@ pub async fn start_control_socket_acceptor(
|
||||
shutdown_token: CancellationToken,
|
||||
daemon_shutdown_access: DaemonShutdownAccess,
|
||||
) -> IoResult<JoinHandle<()>> {
|
||||
let (listener, socket_guard) = bind_private_daemon_socket(socket_path.as_path()).await?;
|
||||
info!(
|
||||
socket_path = %socket_guard.socket_path.display(),
|
||||
"app-server control socket listening"
|
||||
);
|
||||
|
||||
Ok(tokio::spawn(run_control_socket_acceptor(
|
||||
listener,
|
||||
transport_event_tx,
|
||||
shutdown_token,
|
||||
socket_guard,
|
||||
daemon_shutdown_access,
|
||||
)))
|
||||
}
|
||||
|
||||
/// Binds a private daemon socket, retaining its advertised path as a rendezvous
|
||||
/// alias on Unix. Keep the guard alive for as long as the listener is in use.
|
||||
pub async fn bind_private_daemon_socket(
|
||||
socket_path: &Path,
|
||||
) -> IoResult<(UnixListener, DaemonSocketFileGuard)> {
|
||||
let socket_path = AbsolutePathBuf::from_absolute_path(socket_path)?;
|
||||
#[cfg(unix)]
|
||||
let (socket_path, rendezvous_path, mut startup_lock) = {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
@@ -99,7 +120,7 @@ pub async fn start_control_socket_acceptor(
|
||||
{
|
||||
startup_lock.remove_on_drop = true;
|
||||
}
|
||||
let socket_guard = ControlSocketFileGuard {
|
||||
let socket_guard = DaemonSocketFileGuard {
|
||||
socket_path,
|
||||
#[cfg(unix)]
|
||||
rendezvous_path,
|
||||
@@ -116,25 +137,14 @@ pub async fn start_control_socket_acceptor(
|
||||
)?;
|
||||
#[cfg(unix)]
|
||||
socket_guard._startup_lock._file.unlock()?;
|
||||
info!(
|
||||
socket_path = %socket_guard.socket_path.display(),
|
||||
"app-server control socket listening"
|
||||
);
|
||||
|
||||
Ok(tokio::spawn(run_control_socket_acceptor(
|
||||
listener,
|
||||
transport_event_tx,
|
||||
shutdown_token,
|
||||
socket_guard,
|
||||
daemon_shutdown_access,
|
||||
)))
|
||||
Ok((listener, socket_guard))
|
||||
}
|
||||
|
||||
async fn run_control_socket_acceptor(
|
||||
mut listener: UnixListener,
|
||||
transport_event_tx: mpsc::Sender<TransportEvent>,
|
||||
shutdown_token: CancellationToken,
|
||||
socket_guard: ControlSocketFileGuard,
|
||||
socket_guard: DaemonSocketFileGuard,
|
||||
daemon_shutdown_access: DaemonShutdownAccess,
|
||||
) {
|
||||
let _socket_guard = socket_guard;
|
||||
@@ -445,7 +455,8 @@ async fn set_control_socket_permissions(_socket_path: &Path) -> IoResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct ControlSocketFileGuard {
|
||||
/// Owns the socket files and startup lock until the listener is shut down.
|
||||
pub struct DaemonSocketFileGuard {
|
||||
socket_path: AbsolutePathBuf,
|
||||
#[cfg(unix)]
|
||||
rendezvous_path: AbsolutePathBuf,
|
||||
@@ -456,7 +467,7 @@ struct ControlSocketFileGuard {
|
||||
_directory_guard: std::os::windows::io::OwnedHandle,
|
||||
}
|
||||
|
||||
impl Drop for ControlSocketFileGuard {
|
||||
impl Drop for DaemonSocketFileGuard {
|
||||
fn drop(&mut self) {
|
||||
#[cfg(unix)]
|
||||
if std::fs::read_link(self.rendezvous_path.as_path())
|
||||
|
||||
@@ -171,6 +171,52 @@ fn managed_daemon_restarts_from_deleted_working_directory() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bootstrap_updater_is_ready_in_deep_codex_home() -> Result<()> {
|
||||
let mut daemon = TestDaemon::new()?;
|
||||
let deep_home = tempfile::Builder::new()
|
||||
.prefix(&"deep-codex-home-".repeat(8))
|
||||
.tempdir_in("/tmp")?;
|
||||
for name in ["packages", "app-server-daemon"] {
|
||||
std::fs::rename(daemon.home.path().join(name), deep_home.path().join(name))?;
|
||||
}
|
||||
daemon.home = deep_home;
|
||||
let state = daemon.home.path().join("app-server-daemon");
|
||||
std::fs::write(
|
||||
state.join("settings.json"),
|
||||
br#"{"shutdownGraceSeconds":0}"#,
|
||||
)?;
|
||||
let socket = state.join("app-server-updater.sock");
|
||||
let result = daemon.lifecycle("bootstrap")?;
|
||||
assert_eq!(result["autoUpdateEnabled"], true);
|
||||
assert_eq!(result["status"], "bootstrapped");
|
||||
signal(daemon.pid("app-server-updater.pid")?, /*signal*/ 0)?;
|
||||
let target = socket.canonicalize()?;
|
||||
let _connection = std::os::unix::net::UnixStream::connect(target)?;
|
||||
assert_eq!(daemon.lifecycle("version")?["status"], "running");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bootstrap_reports_updater_bind_failure() -> Result<()> {
|
||||
let daemon = TestDaemon::new()?;
|
||||
let state = daemon.home.path().join("app-server-daemon");
|
||||
std::fs::write(
|
||||
state.join("settings.json"),
|
||||
br#"{"shutdownGraceSeconds":0}"#,
|
||||
)?;
|
||||
let socket = state.join("app-server-updater.sock");
|
||||
std::fs::write(&socket, b"not a socket")?;
|
||||
let result = daemon
|
||||
.command()
|
||||
.args(["app-server", "daemon", "bootstrap"])
|
||||
.output()?;
|
||||
assert!(!result.status.success());
|
||||
assert_eq!(std::fs::read(socket)?, b"not a socket");
|
||||
assert_eq!(daemon.lifecycle("version")?["status"], "running");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_restart_applies_feature_overrides_and_preserves_saved_settings() -> Result<()> {
|
||||
let daemon = TestDaemon::new()?;
|
||||
|
||||
Reference in New Issue
Block a user