mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:31:09 +00:00
Bundle Linux voice runtimes and improve audio reliability (#44714)
## Why Linux voice needs system ALSA plugins and enough buffering to accommodate PipeWire graph cycles without losing capture samples. Voice startup failures also need actionable diagnostics without exposing native error details. ## What changed - Build and bundle GNU voice helpers and runtimes with primary Linux musl release archives, and sign the archives. Keep Python wheels free of these libraries to preserve `manylinux_2_17` compatibility. - Discover ALSA plugins in fixed system directories and increase Linux capture and playback buffering to support larger PipeWire graph cycles. - Report voice failures by stage, preserve negotiation timeout classification, and discard native error sources. Suppress the misleading `requested` closure message after failure cleanup. - Add explicit Windows MSVC, pkgconf, and CMake toolchain configuration and preserve host architecture in native build environments. ## Testing Add coverage for Linux release assembly, ALSA plugin discovery, PipeWire capture and playback, classified startup failures, failure cleanup rendering, and Windows build environment handling. GitOrigin-RevId: d805eace96a669ce3a4489f12e2db6f68f9f7f53
This commit is contained in:
1 parent
08e49689b8
commit
da20788df9
27 files changed
+578
-70
No files matched your search
@@ -25,12 +25,28 @@ const RUNTIME_INITIALIZATION_DEADLINE: Duration = Duration::from_secs(/*secs*/ 3
|
||||
pub enum ConnectionError {
|
||||
NegotiationTimedOut,
|
||||
Failed,
|
||||
HelperStartup,
|
||||
RuntimeInitialization,
|
||||
Transport,
|
||||
AudioDevices,
|
||||
AudioControls,
|
||||
AudioSession,
|
||||
Shutdown,
|
||||
}
|
||||
impl std::fmt::Display for ConnectionError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::NegotiationTimedOut => "voice negotiation timed out",
|
||||
Self::Failed => "voice connection failed",
|
||||
Self::HelperStartup => "voice helper could not start",
|
||||
Self::RuntimeInitialization => "voice audio runtime could not initialize",
|
||||
Self::Transport => "voice transport could not connect",
|
||||
Self::AudioDevices => {
|
||||
"voice audio devices could not open; check microphone and speaker setup"
|
||||
}
|
||||
Self::AudioControls => "voice audio controls failed",
|
||||
Self::AudioSession => "voice audio session stopped unexpectedly",
|
||||
Self::Shutdown => "voice helper could not shut down cleanly",
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -149,6 +165,16 @@ impl VoiceHost {
|
||||
"voice helper must be inside the physical package"
|
||||
);
|
||||
let environment = child_environment(std::env::vars_os());
|
||||
#[cfg(target_os = "linux")]
|
||||
let environment = {
|
||||
let mut environment = environment;
|
||||
if let Some(directory) =
|
||||
crate::linux_alsa::plugin_directory(crate::linux_alsa::PLUGIN_DIRECTORIES)
|
||||
{
|
||||
environment.insert("ALSA_PLUGIN_DIR".to_owned(), directory.to_owned());
|
||||
}
|
||||
environment
|
||||
};
|
||||
let SpawnedProcess {
|
||||
session,
|
||||
stdout_rx,
|
||||
|
||||
@@ -14,6 +14,7 @@ fn forwards_only_explicit_device_network_and_os_inputs() {
|
||||
("DYLD_INSERT_LIBRARIES", "loader"),
|
||||
("PATH", "project"),
|
||||
("GST_PLUGIN_PATH", "plugins"),
|
||||
("ALSA_PLUGIN_DIR", "untrusted-alsa-plugins"),
|
||||
("GST_REGISTRY", "untrusted-registry"),
|
||||
("GST_REGISTRY_FORK", "yes"),
|
||||
("OPENAI_API_KEY", "secret"),
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
mod client;
|
||||
mod helper_exit;
|
||||
#[cfg(any(target_os = "linux", test))]
|
||||
mod linux_alsa;
|
||||
mod message_reader;
|
||||
mod protocol;
|
||||
mod session;
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
//! Locate system ALSA plugins for the statically linked Linux voice helper.
|
||||
//!
|
||||
//! Bazel's ALSA defaults to /usr/lib/alsa-lib. Distribution plugins may instead
|
||||
//! live in a multiarch or lib64 directory. Only fixed system paths are admitted;
|
||||
//! caller-provided plugin directories and loader search paths remain excluded.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) const PLUGIN_DIRECTORIES: &[&str] = &[
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
"/usr/lib/x86_64-linux-gnu/alsa-lib",
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
"/usr/lib/aarch64-linux-gnu/alsa-lib",
|
||||
"/usr/lib64/alsa-lib",
|
||||
"/usr/lib/alsa-lib",
|
||||
];
|
||||
|
||||
pub(crate) fn plugin_directory<'a>(candidates: &[&'a str]) -> Option<&'a str> {
|
||||
candidates
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|path| Path::new(path).is_dir())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "linux_alsa_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,38 @@
|
||||
//! Verify fallback among installed layouts while ignoring non-directory entries.
|
||||
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::plugin_directory;
|
||||
|
||||
#[test]
|
||||
fn discovers_available_layout_without_selecting_a_file() -> std::io::Result<()> {
|
||||
let root = std::env::temp_dir().join(format!(
|
||||
"codex-alsa-{}-{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos()
|
||||
));
|
||||
std::fs::create_dir(&root)?;
|
||||
let multiarch = root.join("multiarch");
|
||||
let lib64 = root.join("lib64");
|
||||
let generic = root.join("generic");
|
||||
let candidates = [
|
||||
multiarch.to_str().unwrap(),
|
||||
lib64.to_str().unwrap(),
|
||||
generic.to_str().unwrap(),
|
||||
];
|
||||
|
||||
assert_eq!(plugin_directory(&candidates), None);
|
||||
std::fs::create_dir(&generic)?;
|
||||
assert_eq!(plugin_directory(&candidates), Some(candidates[2]));
|
||||
std::fs::write(&lib64, "not a directory")?;
|
||||
assert_eq!(plugin_directory(&candidates), Some(candidates[2]));
|
||||
std::fs::remove_file(&lib64)?;
|
||||
std::fs::create_dir(&lib64)?;
|
||||
assert_eq!(plugin_directory(&candidates), Some(candidates[1]));
|
||||
std::fs::create_dir(&multiarch)?;
|
||||
assert_eq!(plugin_directory(&candidates), Some(candidates[0]));
|
||||
std::fs::remove_dir_all(root)
|
||||
}
|
||||
@@ -16,6 +16,7 @@ use futures::future::Abortable;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::AudioControls;
|
||||
use crate::ConnectionError;
|
||||
use crate::SessionDescription;
|
||||
use crate::VoiceHost;
|
||||
|
||||
@@ -134,30 +135,37 @@ impl RealtimeWebrtcSession {
|
||||
.spawn(move || {
|
||||
let task = async {
|
||||
let host = report_failure(
|
||||
"connect",
|
||||
ConnectionError::HelperStartup,
|
||||
VoiceHost::connect(&package, &build_commit).await,
|
||||
)?;
|
||||
let host =
|
||||
report_failure("initialize_runtime", host.initialize_runtime().await)?;
|
||||
let host = report_failure(
|
||||
ConnectionError::RuntimeInitialization,
|
||||
host.initialize_runtime().await,
|
||||
)?;
|
||||
let (host, sdp) =
|
||||
report_failure("start_transport", host.start_transport().await)?;
|
||||
report_failure(ConnectionError::Transport, host.start_transport().await)?;
|
||||
offer
|
||||
.send(sdp.into_sdp())
|
||||
.send(Ok(sdp.into_sdp()))
|
||||
.map_err(|_| anyhow::anyhow!("voice startup cancelled"))?;
|
||||
run(host, receiver, &state, &controls).await
|
||||
};
|
||||
let result = runtime.block_on(Abortable::new(Abortable::new(task, abort), stopped));
|
||||
if !matches!(result, Err(_) | Ok(Err(_)) | Ok(Ok(Ok(())))) {
|
||||
if let Ok(Ok(Err(error))) = result {
|
||||
let failure = error
|
||||
.downcast_ref::<ConnectionError>()
|
||||
.copied()
|
||||
.unwrap_or(ConnectionError::Failed);
|
||||
let _ = offer.try_send(Err(failure));
|
||||
*state
|
||||
.error
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) =
|
||||
Some("Voice helper stopped unexpectedly.".into());
|
||||
Some(failure.to_string());
|
||||
}
|
||||
})?;
|
||||
let offer_sdp = result
|
||||
.recv_timeout(STARTUP_WAIT)
|
||||
.map_err(|_| anyhow::anyhow!("voice startup failed"))?;
|
||||
.map_err(|_| anyhow::anyhow!("voice startup failed"))??;
|
||||
Ok(StartedRealtimeWebrtcSession { offer_sdp, handle })
|
||||
}
|
||||
}
|
||||
@@ -267,35 +275,39 @@ async fn run(
|
||||
biased;
|
||||
command = commands.recv() => match command {
|
||||
Some(Command::Answer(sdp, complete)) if !connected => {
|
||||
host = match host.apply_answer(sdp).await {
|
||||
let startup = async {
|
||||
let mut host = report_failure(ConnectionError::Transport, host.apply_answer(sdp).await)?;
|
||||
host = report_failure(ConnectionError::AudioDevices, host.open_devices().await)?;
|
||||
let applied = startup_controls(&mut commands, controls, |initial| {
|
||||
host.begin_audio_controls(initial)
|
||||
});
|
||||
let applied = report_failure(ConnectionError::AudioControls, applied)?;
|
||||
report_failure(ConnectionError::AudioControls, applied.await)?;
|
||||
Ok::<_, anyhow::Error>(host)
|
||||
}.await;
|
||||
host = match startup {
|
||||
Ok(host) => host,
|
||||
Err(error) => {
|
||||
let failure = error.downcast_ref::<crate::ConnectionError>()
|
||||
.copied().unwrap_or(crate::ConnectionError::Failed);
|
||||
let failure = error.downcast_ref::<ConnectionError>()
|
||||
.copied().unwrap_or(ConnectionError::Failed);
|
||||
let _ = complete.send(Err(failure));
|
||||
// This failure is delivered by the startup completion only.
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
host = report_failure("open_devices", host.open_devices().await)?;
|
||||
let applied = startup_controls(&mut commands, controls, |initial| {
|
||||
host.begin_audio_controls(initial)
|
||||
});
|
||||
let applied = report_failure("queue_startup_controls", applied)?;
|
||||
report_failure("apply_startup_controls", applied.await)?;
|
||||
connected = true;
|
||||
let _ = complete.send(Ok(()));
|
||||
}
|
||||
Some(Command::Controls(next)) => {
|
||||
if connected {
|
||||
report_failure("set_audio_controls", host.set_audio_controls(next).await)?;
|
||||
report_failure(ConnectionError::AudioControls, host.set_audio_controls(next).await)?;
|
||||
}
|
||||
}
|
||||
Some(Command::Answer(..)) => anyhow::bail!("voice answer already applied"),
|
||||
None => return report_failure("close", host.close().await),
|
||||
None => return report_failure(ConnectionError::Shutdown, host.close().await),
|
||||
},
|
||||
_ = poll.tick() => {
|
||||
let audio = report_failure("inspect_audio", host.inspect_audio().await)?;
|
||||
let audio = report_failure(ConnectionError::AudioSession, host.inspect_audio().await)?;
|
||||
state.microphone.fetch_max(audio.microphone_peak, Ordering::Release);
|
||||
state.speaker.fetch_max(audio.speaker_peak, Ordering::Release);
|
||||
}
|
||||
@@ -304,8 +316,8 @@ async fn run(
|
||||
}
|
||||
|
||||
// Keep diagnostics bounded and independent of untyped native, SDP, or device error text.
|
||||
fn report_failure<T>(stage: &'static str, result: Result<T>) -> Result<T> {
|
||||
result.inspect_err(|error| {
|
||||
fn report_failure<T>(stage: ConnectionError, result: Result<T>) -> Result<T> {
|
||||
result.map_err(|error| {
|
||||
let kind = if error.is::<tokio::time::error::Elapsed>() {
|
||||
"timeout"
|
||||
} else if let Some(error) = error.downcast_ref::<std::io::Error>() {
|
||||
@@ -319,7 +331,13 @@ fn report_failure<T>(stage: &'static str, result: Result<T>) -> Result<T> {
|
||||
} else {
|
||||
"other"
|
||||
};
|
||||
tracing::warn!(stage, kind, "voice session operation failed");
|
||||
tracing::warn!(?stage, kind, "voice session operation failed");
|
||||
let failure = error
|
||||
.downcast_ref::<ConnectionError>()
|
||||
.copied()
|
||||
.unwrap_or(stage);
|
||||
// Replace the original error instead of retaining a potentially sensitive source chain.
|
||||
anyhow::Error::new(failure)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -198,3 +198,26 @@ async fn startup_completion_preserves_classified_failure() {
|
||||
assert_eq!(handle.take_error(), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classified_errors_discard_sensitive_sources_but_preserve_retry_classification() {
|
||||
let error = report_failure::<()>(
|
||||
ConnectionError::AudioDevices,
|
||||
Err(anyhow::anyhow!("synthetic-secret-sdp-device-path")),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
format!("{error:#}"),
|
||||
ConnectionError::AudioDevices.to_string()
|
||||
);
|
||||
assert!(!format!("{error:?}").contains("synthetic-secret"));
|
||||
let error = report_failure::<()>(
|
||||
ConnectionError::Transport,
|
||||
Err(ConnectionError::NegotiationTimedOut.into()),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
error.downcast_ref::<ConnectionError>(),
|
||||
Some(&ConnectionError::NegotiationTimedOut)
|
||||
);
|
||||
}
|
||||
@@ -153,6 +153,9 @@ fn helper() -> Result<()> {
|
||||
if root.join("hold-initialization").exists() {
|
||||
wait_for(|| root.join("release").exists())?;
|
||||
}
|
||||
if root.join("fail-initialization").exists() {
|
||||
anyhow::bail!("synthetic private runtime diagnostic");
|
||||
}
|
||||
stage = Stage::Offer;
|
||||
Message::RuntimeReady {}
|
||||
}
|
||||
@@ -176,6 +179,9 @@ fn helper() -> Result<()> {
|
||||
Message::TransportReady {}
|
||||
}
|
||||
Message::OpenDevices {} if stage == Stage::Devices => {
|
||||
if root.join("fail-devices").exists() {
|
||||
anyhow::bail!("synthetic private device diagnostic");
|
||||
}
|
||||
stage = Stage::Controls;
|
||||
Message::DevicesOpened {}
|
||||
}
|
||||
|
||||
@@ -67,7 +67,10 @@ fn startup_controls_meters_and_helper_loss() -> Result<()> {
|
||||
error = handle.take_error();
|
||||
error.is_some()
|
||||
})?;
|
||||
assert_eq!(error.as_deref(), Some("Voice helper stopped unexpectedly."));
|
||||
assert_eq!(
|
||||
error.as_deref(),
|
||||
Some("voice audio session stopped unexpectedly")
|
||||
);
|
||||
assert_eq!(handle.take_error(), None);
|
||||
Ok(())
|
||||
}
|
||||
@@ -107,3 +110,47 @@ fn last_owner_drop_reaps_helper() -> Result<()> {
|
||||
drop(started);
|
||||
common::wait_for_helper_reaped(&root)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn device_failure_reaches_startup_completion_without_duplicate_error() -> Result<()> {
|
||||
let Some(root) =
|
||||
common::package("device_failure_reaches_startup_completion_without_duplicate_error")?
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
fs::write(root.join("fail-devices"), [])?;
|
||||
fs::write(root.join("release"), [])?;
|
||||
let (_abort, registration) = AbortHandle::new_pair();
|
||||
let started = RealtimeWebrtcSession::start(registration)?;
|
||||
assert_eq!(
|
||||
started.handle.apply_answer_sdp("synthetic-answer".into()),
|
||||
Err(codex_realtime_webrtc::ConnectionError::AudioDevices)
|
||||
);
|
||||
#[cfg(unix)]
|
||||
common::wait_for_helper_reaped(&root)?;
|
||||
assert_eq!(started.handle.take_error(), None);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_failure_reaches_offer_caller_without_native_error_text() -> Result<()> {
|
||||
let Some(root) =
|
||||
common::package("runtime_failure_reaches_offer_caller_without_native_error_text")?
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
fs::write(root.join("fail-initialization"), [])?;
|
||||
let (_abort, registration) = AbortHandle::new_pair();
|
||||
let error = RealtimeWebrtcSession::start(registration).unwrap_err();
|
||||
assert_eq!(
|
||||
error.downcast_ref::<codex_realtime_webrtc::ConnectionError>(),
|
||||
Some(&codex_realtime_webrtc::ConnectionError::RuntimeInitialization)
|
||||
);
|
||||
assert_eq!(
|
||||
format!("{error:#}"),
|
||||
"voice audio runtime could not initialize"
|
||||
);
|
||||
#[cfg(unix)]
|
||||
common::wait_for_helper_reaped(&root)?;
|
||||
Ok(())
|
||||
}
|
||||
Reference in new issue
Block a user