mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:31:09 +00:00
Keep voice sessions alive through mute and audio backlog (#44671)
## Why Audio queue saturation and processing delays could terminate voice sessions. Muted sessions also need outgoing audio to keep the peer alive. ## What changed - Drop stale or excess incoming, capture, render-reference, and playback audio so fresh audio can resume. Reset affected processing state while preserving queue bounds and mute generations. - Send paced, generated Opus silence while muted, without using device or processing buffers. - Add fixed helper exit stages and session failure categories to default TUI logs without logging raw native errors, SDP, or device error text. Preserve observed helper exit status for shutdown. ## Testing Extend tests to cover decoded mute silence and RTP sequence continuity, recovery after stale audio and queue saturation, and shutdown after observing helper output closure. Verify the helper's exit stage when the parent pipe closes during blocked startup. GitOrigin-RevId: 17d580a72acd4423fb0b4f5107d9b541b964d069
This commit is contained in:
1 parent
1b83e5cdf9
commit
28f43b0417
22 files changed
+514
-96
No files matched your search
@@ -19,6 +19,7 @@ futures = { workspace = true, features = ["std"] }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
tokio = { workspace = true, features = ["macros", "rt-multi-thread", "sync", "time"] }
|
||||
tracing = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
ctor = { workspace = true }
|
||||
|
||||
@@ -12,6 +12,7 @@ use codex_utils_pty::SpawnedProcess;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::time::timeout;
|
||||
|
||||
use crate::HelperExitStage;
|
||||
use crate::Message;
|
||||
use crate::encode_frame;
|
||||
use crate::message_reader::MessageReader;
|
||||
@@ -41,6 +42,7 @@ pub struct VoiceHost {
|
||||
process: ProcessHandle,
|
||||
output: MessageReader,
|
||||
exit: oneshot::Receiver<i32>,
|
||||
observed_exit: Option<Option<i32>>,
|
||||
}
|
||||
|
||||
impl VoiceHost {
|
||||
@@ -73,7 +75,7 @@ impl VoiceHost {
|
||||
.map_err(|_| anyhow::anyhow!("voice helper input unavailable"))?;
|
||||
let deadline = tokio::time::Instant::now() + DEADLINE;
|
||||
Ok(async move {
|
||||
let response = tokio::time::timeout_at(deadline, self.output.next()).await??;
|
||||
let response = tokio::time::timeout_at(deadline, self.next_response()).await??;
|
||||
ensure!(
|
||||
response == Message::AudioControlsApplied {},
|
||||
"unexpected voice helper response"
|
||||
@@ -166,6 +168,7 @@ impl VoiceHost {
|
||||
process: session,
|
||||
output: MessageReader::new(stdout_rx),
|
||||
exit: exit_rx,
|
||||
observed_exit: None,
|
||||
};
|
||||
host.exchange(
|
||||
Message::Hello {
|
||||
@@ -187,7 +190,11 @@ impl VoiceHost {
|
||||
if result.is_err() {
|
||||
self.process.terminate();
|
||||
}
|
||||
let code = timeout(DEADLINE, &mut self.exit).await??;
|
||||
let code = match self.observed_exit {
|
||||
Some(Some(code)) => code,
|
||||
Some(None) => anyhow::bail!("voice helper exit status unavailable"),
|
||||
None => timeout(DEADLINE, &mut self.exit).await??,
|
||||
};
|
||||
result?;
|
||||
ensure!(code == 0, "voice helper failed during shutdown");
|
||||
Ok(())
|
||||
@@ -213,10 +220,37 @@ impl VoiceHost {
|
||||
.send(encode_frame(&request)?)
|
||||
.await
|
||||
.map_err(|_| anyhow::anyhow!("voice helper input closed"))?;
|
||||
Ok(self.output.next().await?)
|
||||
self.next_response().await
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
async fn next_response(&mut self) -> Result<Message> {
|
||||
match self.output.next().await {
|
||||
Ok(response) => Ok(response),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::UnexpectedEof => {
|
||||
// The helper can exit just after closing stdout. Wait briefly for its
|
||||
// status; never log its untyped stderr, SDP, or native error text.
|
||||
let exit_code = match self.observed_exit {
|
||||
Some(status) => status,
|
||||
None => {
|
||||
match timeout(Duration::from_millis(/*millis*/ 250), &mut self.exit).await {
|
||||
Ok(status) => {
|
||||
let status = status.ok();
|
||||
self.observed_exit = Some(status);
|
||||
status
|
||||
}
|
||||
Err(_) => None,
|
||||
}
|
||||
}
|
||||
};
|
||||
let phase = exit_code.and_then(HelperExitStage::from_code);
|
||||
tracing::warn!(?phase, ?exit_code, "voice helper output closed");
|
||||
Err(error.into())
|
||||
}
|
||||
Err(error) => Err(error.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn child_environment(vars: impl Iterator<Item = (OsString, OsString)>) -> HashMap<String, String> {
|
||||
|
||||
@@ -50,6 +50,7 @@ async fn cancelling_initialization_terminates_the_owned_helper() -> anyhow::Resu
|
||||
process: spawned.session,
|
||||
output: crate::message_reader::MessageReader::new(spawned.stdout_rx),
|
||||
exit: unused_exit,
|
||||
observed_exit: None,
|
||||
};
|
||||
let mut initialization = Box::pin(host.initialize_runtime());
|
||||
std::future::poll_fn(|context| {
|
||||
@@ -83,6 +84,7 @@ async fn negotiation_timeout_waits_for_helper_exit_before_allowing_retry() -> an
|
||||
process: spawned.session,
|
||||
output: crate::message_reader::MessageReader::new(receiver),
|
||||
exit,
|
||||
observed_exit: None,
|
||||
};
|
||||
let answer = crate::SessionDescription::try_from("synthetic-answer".to_owned()).unwrap();
|
||||
let mut connection = Box::pin(host.apply_answer(answer));
|
||||
@@ -110,3 +112,32 @@ async fn negotiation_timeout_waits_for_helper_exit_before_allowing_retry() -> an
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn close_after_output_eof_reuses_observed_exit() -> anyhow::Result<()> {
|
||||
let spawned = codex_utils_pty::spawn_pipe_process(
|
||||
std::path::Path::new("/bin/sleep"),
|
||||
&["30".to_owned()],
|
||||
std::path::Path::new("/"),
|
||||
&child_environment(std::iter::empty()),
|
||||
/*arg0*/ &None,
|
||||
&[],
|
||||
)
|
||||
.await?;
|
||||
let (output, receiver) = tokio::sync::mpsc::channel(/*buffer*/ 1);
|
||||
drop(output);
|
||||
let (reaped, exit) = tokio::sync::oneshot::channel();
|
||||
let exit_code = crate::HelperExitStage::AudioService.code();
|
||||
reaped.send(exit_code).unwrap();
|
||||
let mut host = super::VoiceHost {
|
||||
process: spawned.session,
|
||||
output: crate::message_reader::MessageReader::new(receiver),
|
||||
exit,
|
||||
observed_exit: None,
|
||||
};
|
||||
assert!(host.next_response().await.is_err());
|
||||
assert_eq!(host.observed_exit, Some(Some(exit_code)));
|
||||
assert!(host.close().await.is_err());
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
//! Fixed helper exit phases for safe diagnostics when its framed output closes.
|
||||
//! The same-build handshake keeps these codes aligned between parent and helper.
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
#[repr(i32)]
|
||||
pub enum HelperExitStage {
|
||||
ControlRead = 20,
|
||||
ControlQueue = 21,
|
||||
ParentGone = 22,
|
||||
Runtime = 23,
|
||||
Transport = 24,
|
||||
OpenDevices = 25,
|
||||
AudioIngress = 26,
|
||||
AudioService = 27,
|
||||
InspectAudio = 28,
|
||||
AudioControls = 29,
|
||||
Reply = 30,
|
||||
Shutdown = 31,
|
||||
ControlSequence = 32,
|
||||
Playout = 33,
|
||||
Render = 35,
|
||||
Capture = 36,
|
||||
Device = 37,
|
||||
Send = 39,
|
||||
}
|
||||
|
||||
impl HelperExitStage {
|
||||
pub fn code(self) -> i32 {
|
||||
self as i32
|
||||
}
|
||||
|
||||
pub fn from_code(code: i32) -> Option<Self> {
|
||||
Some(match code {
|
||||
20 => Self::ControlRead,
|
||||
21 => Self::ControlQueue,
|
||||
22 => Self::ParentGone,
|
||||
23 => Self::Runtime,
|
||||
24 => Self::Transport,
|
||||
25 => Self::OpenDevices,
|
||||
26 => Self::AudioIngress,
|
||||
27 => Self::AudioService,
|
||||
28 => Self::InspectAudio,
|
||||
29 => Self::AudioControls,
|
||||
30 => Self::Reply,
|
||||
31 => Self::Shutdown,
|
||||
32 => Self::ControlSequence,
|
||||
33 => Self::Playout,
|
||||
35 => Self::Render,
|
||||
36 => Self::Capture,
|
||||
37 => Self::Device,
|
||||
39 => Self::Send,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
mod client;
|
||||
mod helper_exit;
|
||||
mod message_reader;
|
||||
mod protocol;
|
||||
mod session;
|
||||
|
||||
pub use client::ConnectionError;
|
||||
pub use client::VoiceHost;
|
||||
pub use helper_exit::HelperExitStage;
|
||||
pub use protocol::AudioControls;
|
||||
pub use protocol::AudioState;
|
||||
pub use protocol::MAX_FRAME_BYTES;
|
||||
|
||||
@@ -133,11 +133,14 @@ impl RealtimeWebrtcSession {
|
||||
.name("voice-session".into())
|
||||
.spawn(move || {
|
||||
let task = async {
|
||||
let host = VoiceHost::connect(&package, &build_commit)
|
||||
.await?
|
||||
.initialize_runtime()
|
||||
.await?;
|
||||
let (host, sdp) = host.start_transport().await?;
|
||||
let host = report_failure(
|
||||
"connect",
|
||||
VoiceHost::connect(&package, &build_commit).await,
|
||||
)?;
|
||||
let host =
|
||||
report_failure("initialize_runtime", host.initialize_runtime().await)?;
|
||||
let (host, sdp) =
|
||||
report_failure("start_transport", host.start_transport().await)?;
|
||||
offer
|
||||
.send(sdp.into_sdp())
|
||||
.map_err(|_| anyhow::anyhow!("voice startup cancelled"))?;
|
||||
@@ -274,24 +277,25 @@ async fn run(
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
host = host.open_devices().await?;
|
||||
host = report_failure("open_devices", host.open_devices().await)?;
|
||||
let applied = startup_controls(&mut commands, controls, |initial| {
|
||||
host.begin_audio_controls(initial)
|
||||
})?;
|
||||
applied.await?;
|
||||
});
|
||||
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 {
|
||||
host.set_audio_controls(next).await?;
|
||||
report_failure("set_audio_controls", host.set_audio_controls(next).await)?;
|
||||
}
|
||||
}
|
||||
Some(Command::Answer(..)) => anyhow::bail!("voice answer already applied"),
|
||||
None => return host.close().await,
|
||||
None => return report_failure("close", host.close().await),
|
||||
},
|
||||
_ = poll.tick() => {
|
||||
let audio = host.inspect_audio().await?;
|
||||
let audio = report_failure("inspect_audio", host.inspect_audio().await)?;
|
||||
state.microphone.fetch_max(audio.microphone_peak, Ordering::Release);
|
||||
state.speaker.fetch_max(audio.speaker_peak, Ordering::Release);
|
||||
}
|
||||
@@ -299,6 +303,26 @@ 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| {
|
||||
let kind = if error.is::<tokio::time::error::Elapsed>() {
|
||||
"timeout"
|
||||
} else if let Some(error) = error.downcast_ref::<std::io::Error>() {
|
||||
match error.kind() {
|
||||
std::io::ErrorKind::UnexpectedEof
|
||||
| std::io::ErrorKind::BrokenPipe
|
||||
| std::io::ErrorKind::ConnectionReset => "closed",
|
||||
std::io::ErrorKind::InvalidData => "protocol",
|
||||
_ => "io",
|
||||
}
|
||||
} else {
|
||||
"other"
|
||||
};
|
||||
tracing::warn!(stage, kind, "voice session operation failed");
|
||||
})
|
||||
}
|
||||
|
||||
// Devices are still disabled. The snapshot and request enqueue share the setters' lock;
|
||||
// later setters remain ordered after this request without waiting for its acknowledgement.
|
||||
fn startup_controls<T>(
|
||||
|
||||
Reference in new issue
Block a user