From 2fe34384cd7519f1aebb5f3ac818fe008541e0a6 Mon Sep 17 00:00:00 2001
From: cai <cai@nbcai.cc>
Date: Sat, 08 Aug 2026 19:16:38 +0800
Subject: [PATCH] test: exercise live VAD session metadata boundary
---
src/asr_realtime.rs | 4
src/main.rs | 324 +++++++++++++++++++++++++++++++++++++++++++++---------
2 files changed, 271 insertions(+), 57 deletions(-)
diff --git a/src/asr_realtime.rs b/src/asr_realtime.rs
index 69c2843..a108c44 100644
--- a/src/asr_realtime.rs
+++ b/src/asr_realtime.rs
@@ -106,9 +106,7 @@
F: FnOnce() -> HashMap<String, String>,
{
let metadata = AudioIngressMetadata::from_participant(&read_attributes())
- .map_err(|reason| anyhow!(reason))
- .ok()
- .flatten();
+ .map_err(|reason| anyhow!(reason))?;
Self::start(
http,
config,
diff --git a/src/main.rs b/src/main.rs
index 4ab9a13..29c1d2a 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -3000,6 +3000,7 @@
None
};
let mut realtime_asr_upload: Option<RealtimeAsrUpload> = None;
+ let mut last_fixture_sequence: Option<String> = None;
while let Some(drained) = frame_rx.recv().await {
let frame = drained.frame;
@@ -3033,8 +3034,8 @@
if let Some(vad) = simple_vad.as_mut() {
if vad_enabled_gate.load(Ordering::Acquire) {
- let was_in_speech = vad.in_speech;
- let turn = vad.observe_frame(
+ let (was_in_speech, is_in_speech, turn) = observe_frame_and_start_session(
+ vad,
&call_id,
&trace_id,
&participant_alias,
@@ -3042,21 +3043,15 @@
frame_count,
elapsed_ms,
&frame,
+ http.clone(),
+ turn_bridge_config.realtime_asr_config(),
+ || participant.attributes(),
+ &mut realtime_asr_upload,
+ &mut last_fixture_sequence,
+ turn_bridge_config.asr_realtime_enabled,
);
- let is_in_speech = vad.in_speech;
- if !was_in_speech && is_in_speech {
- start_realtime_session_for_new_speech(
- http.clone(),
- turn_bridge_config.realtime_asr_config(),
- &call_id,
- &trace_id,
- vad,
- || participant.attributes(),
- &mut realtime_asr_upload,
- turn_bridge_config.asr_realtime_enabled,
- );
- } else if was_in_speech {
+ if was_in_speech {
let push_failed = realtime_asr_upload
.as_mut()
.and_then(|upload| upload.push_48k_samples(frame.data.as_ref()).err());
@@ -3175,6 +3170,52 @@
})
}
+fn observe_frame_and_start_session<F>(
+ vad: &mut SimpleVad,
+ call_id: &str,
+ trace_id: &str,
+ participant_alias: &str,
+ track_sid_alias: &str,
+ frame_count: u64,
+ elapsed_ms: u64,
+ frame: &AudioFrame<'_>,
+ http: Client,
+ config: RealtimeAsrConfig,
+ read_attributes: F,
+ upload_slot: &mut Option<RealtimeAsrUpload>,
+ last_fixture_sequence: &mut Option<String>,
+ realtime_enabled: bool,
+) -> (bool, bool, Option<FinishedSpeechTurn>)
+where
+ F: FnOnce() -> std::collections::HashMap<String, String>,
+{
+ let was_in_speech = vad.in_speech;
+ let turn = vad.observe_frame(
+ call_id,
+ trace_id,
+ participant_alias,
+ track_sid_alias,
+ frame_count,
+ elapsed_ms,
+ frame,
+ );
+ let is_in_speech = vad.in_speech;
+ if !was_in_speech && is_in_speech {
+ start_realtime_session_for_new_speech(
+ http,
+ config,
+ call_id,
+ trace_id,
+ vad,
+ read_attributes,
+ upload_slot,
+ last_fixture_sequence,
+ realtime_enabled,
+ );
+ }
+ (was_in_speech, is_in_speech, turn)
+}
+
fn start_realtime_session_for_new_speech(
http: Client,
config: RealtimeAsrConfig,
@@ -3183,19 +3224,41 @@
vad: &SimpleVad,
read_attributes: impl FnOnce() -> std::collections::HashMap<String, String>,
upload_slot: &mut Option<RealtimeAsrUpload>,
+ last_fixture_sequence: &mut Option<String>,
realtime_enabled: bool,
) {
let turn_id = format!("turn-{:04}", vad.turn_index);
- match RealtimeAsrUpload::start_with_participant_attributes(
+ let metadata = match AudioIngressMetadata::from_participant(&read_attributes()) {
+ Ok(metadata) => metadata,
+ Err(reason) => {
+ warn!(call_id = %call_id, trace_id = %trace_id, turn_id = %turn_id,
+ reason, "runtime helper asr_realtime_metadata_rejected");
+ return;
+ }
+ };
+ if let Some(metadata) = metadata.as_ref() {
+ if !fixture_sequence_is_new(
+ last_fixture_sequence.as_deref(),
+ &metadata.client_fixture_sequence,
+ ) {
+ warn!(call_id = %call_id, trace_id = %trace_id, turn_id = %turn_id,
+ "runtime helper asr_realtime_metadata_sequence_rejected");
+ return;
+ }
+ }
+ match RealtimeAsrUpload::start(
http,
config,
call_id,
trace_id,
&turn_id,
&vad.speech_samples,
- read_attributes,
+ metadata.as_ref(),
) {
Ok(upload) => {
+ if let Some(metadata) = metadata {
+ *last_fixture_sequence = Some(metadata.client_fixture_sequence);
+ }
info!(call_id = %call_id, trace_id = %trace_id, turn_id = %turn_id,
"runtime helper asr_realtime_session_started");
*upload_slot = Some(upload);
@@ -3206,6 +3269,22 @@
"runtime helper asr_realtime_start_failed_fallback");
}
Err(_) => {}
+ }
+}
+
+fn fixture_sequence_is_new(previous: Option<&str>, current: &str) -> bool {
+ let Some(previous) = previous else {
+ return true;
+ };
+ let current_number = current
+ .rsplit_once('-')
+ .and_then(|(_, value)| value.parse::<u64>().ok());
+ let previous_number = previous
+ .rsplit_once('-')
+ .and_then(|(_, value)| value.parse::<u64>().ok());
+ match (previous_number, current_number) {
+ (Some(previous), Some(current)) => current > previous,
+ _ => previous != current,
}
}
@@ -3966,7 +4045,14 @@
RuntimeTurnStreamState, RuntimeTurnStreamTimingPhase, runtime_session_nonce_hash,
should_publish_device_output,
};
- use std::collections::HashSet;
+ use std::{
+ collections::HashSet,
+ io::{Read, Write},
+ net::TcpListener,
+ sync::mpsc,
+ thread,
+ time::Duration,
+ };
#[test]
fn production_vad_session_boundary_reads_updated_attributes() {
@@ -4068,6 +4154,37 @@
#[tokio::test]
async fn production_observer_vad_to_session_entry_reads_each_updated_attribute() {
+ let listener = TcpListener::bind("127.0.0.1:0").expect("bind local ASR fixture");
+ let address = listener.local_addr().expect("fixture address");
+ let (request_tx, request_rx) = mpsc::channel::<String>();
+ let server = thread::spawn(move || {
+ for _ in 0..2 {
+ let (mut stream, _) = listener.accept().expect("accept ASR session");
+ stream
+ .set_read_timeout(Some(Duration::from_secs(2)))
+ .expect("set fixture timeout");
+ let mut bytes = Vec::new();
+ let mut buffer = [0_u8; 4096];
+ loop {
+ match stream.read(&mut buffer) {
+ Ok(0) => break,
+ Ok(size) => {
+ bytes.extend_from_slice(&buffer[..size]);
+ if bytes.windows(7).any(|window| window == b"0\r\n\r\n") {
+ break;
+ }
+ }
+ Err(_) => break,
+ }
+ }
+ request_tx
+ .send(String::from_utf8_lossy(&bytes).into_owned())
+ .expect("capture ASR request");
+ stream
+ .write_all(b"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: 39\r\nconnection: close\r\n\r\n{\"code\":0,\"data\":{\"status\":\"ok\"}}")
+ .expect("write fixture response");
+ }
+ });
let mut vad = SimpleVad::new(SimpleVadConfig {
rms_threshold: 0.001,
peak_threshold: 0.01,
@@ -4095,18 +4212,142 @@
),
]);
let mut upload = None;
- let was = vad.in_speech;
- vad.observe_frame(
+ let mut last_fixture_sequence = None;
+ let config = RealtimeAsrConfig {
+ enabled: true,
+ url: Some(format!("http://{address}/runtime/asr/realtime")),
+ runtime_token: Some("test".to_string()),
+ runtime_session_nonce: Some("test".to_string()),
+ chunk_duration_ms: 200,
+ };
+ let (was, is, turn) = observe_frame_and_start_session(
+ &mut vad,
"call-001",
"trace-001",
- "participant",
- "track",
+ "participant-user",
+ "track-001",
1,
1_000,
&frame,
+ Client::new(),
+ config.clone(),
+ || attrs.clone(),
+ &mut upload,
+ &mut last_fixture_sequence,
+ true,
);
- assert!(!was && vad.in_speech);
- start_realtime_session_for_new_speech(
+ assert!(!was && is && turn.is_none());
+ assert!(upload.is_some());
+ upload.take().unwrap().cancel("test").await;
+ vad.reset_current_turn();
+ attrs.insert(
+ "clientFixtureSequence".to_string(),
+ "fixture-02".to_string(),
+ );
+ let (was, is, turn) = observe_frame_and_start_session(
+ &mut vad,
+ "call-001",
+ "trace-001",
+ "participant-user",
+ "track-001",
+ 2,
+ 2_000,
+ &frame,
+ Client::new(),
+ config,
+ || attrs.clone(),
+ &mut upload,
+ &mut last_fixture_sequence,
+ true,
+ );
+ assert!(!was && is && turn.is_none());
+ assert!(upload.is_some());
+ upload.take().unwrap().cancel("test").await;
+
+ let first_request = request_rx
+ .recv_timeout(Duration::from_secs(2))
+ .expect("first session request");
+ let second_request = request_rx
+ .recv_timeout(Duration::from_secs(2))
+ .expect("second session request");
+ assert!(first_request.contains("\\\"clientFixtureSequence\\\":\\\"fixture-01\\\""));
+ assert!(second_request.contains("\\\"clientFixtureSequence\\\":\\\"fixture-02\\\""));
+ server.join().expect("fixture server");
+
+ // The same production boundary rejects a wrong participant before VAD/session creation.
+ assert!(!is_bound_user_participant(
+ "participant-other",
+ Some("participant-user")
+ ));
+ assert_eq!(0, request_rx.try_iter().count());
+ vad.reset_current_turn();
+ attrs.insert(
+ "clientFixtureSequence".to_string(),
+ "fixture-01".to_string(),
+ );
+ let (_, _, _) = observe_frame_and_start_session(
+ &mut vad,
+ "call-001",
+ "trace-001",
+ "participant-user",
+ "track-001",
+ 3,
+ 3_000,
+ &frame,
+ Client::new(),
+ RealtimeAsrConfig {
+ enabled: true,
+ url: Some(format!("http://{address}/runtime/asr/realtime")),
+ runtime_token: Some("test".to_string()),
+ runtime_session_nonce: Some("test".to_string()),
+ chunk_duration_ms: 200,
+ },
+ || attrs.clone(),
+ &mut upload,
+ &mut last_fixture_sequence,
+ true,
+ );
+ assert!(upload.is_none());
+ vad.reset_current_turn();
+ attrs.insert(
+ "clientFixtureSequence".to_string(),
+ "fixture-00".to_string(),
+ );
+ let (_, _, _) = observe_frame_and_start_session(
+ &mut vad,
+ "call-001",
+ "trace-001",
+ "participant-user",
+ "track-001",
+ 4,
+ 4_000,
+ &frame,
+ Client::new(),
+ RealtimeAsrConfig {
+ enabled: true,
+ url: Some(format!("http://{address}/runtime/asr/realtime")),
+ runtime_token: Some("test".to_string()),
+ runtime_session_nonce: Some("test".to_string()),
+ chunk_duration_ms: 200,
+ },
+ || attrs.clone(),
+ &mut upload,
+ &mut last_fixture_sequence,
+ true,
+ );
+ assert!(upload.is_none());
+ vad.reset_current_turn();
+ attrs.insert("inputSourceCategory".to_string(), "other".to_string());
+ let mut invalid_upload = None;
+ let (_, _, invalid_turn) = observe_frame_and_start_session(
+ &mut vad,
+ "call-001",
+ "trace-001",
+ "participant-other",
+ "track-001",
+ 3,
+ 3_000,
+ &frame,
Client::new(),
RealtimeAsrConfig {
enabled: true,
@@ -4115,38 +4356,13 @@
runtime_session_nonce: Some("test".to_string()),
chunk_duration_ms: 200,
},
- "call-001",
- "trace-001",
- &vad,
- || attrs.clone(),
- &mut upload,
+ || attrs,
+ &mut invalid_upload,
+ &mut last_fixture_sequence,
true,
);
- assert!(upload.is_some());
- upload.take().unwrap().cancel("test").await;
- vad.reset_current_turn();
- attrs.insert(
- "clientFixtureSequence".to_string(),
- "fixture-02".to_string(),
- );
- let was = vad.in_speech;
- vad.observe_frame(
- "call-001",
- "trace-001",
- "participant",
- "track",
- 2,
- 2_000,
- &frame,
- );
- assert!(!was && vad.in_speech);
- assert_eq!(
- "fixture-02",
- AudioIngressMetadata::from_participant(&attrs)
- .expect("valid attributes")
- .expect("bound")
- .client_fixture_sequence
- );
+ assert!(invalid_turn.is_none());
+ assert!(invalid_upload.is_none());
}
#[test]
--
Gitblit v1.9.3