diff --git a/crates/voelin-core/src/link/tests.rs b/crates/voelin-core/src/link/tests.rs index 711cce5..7a4e229 100644 --- a/crates/voelin-core/src/link/tests.rs +++ b/crates/voelin-core/src/link/tests.rs @@ -1962,20 +1962,38 @@ async fn a_scope_bigger_than_the_channel_is_sent_in_bigger_chunks() { const CHANNELS: u64 = 5_000; let (conns, mut seen) = mpsc::unbounded_channel(); let connector = LinkConnector::new(Arc::new(Recorder(conns)), &["ts3server"]); - let (mut params, _media) = connect_params("ts3server://fake.test?port=9987"); + let (mut params, mut media) = connect_params("ts3server://fake.test?port=9987"); params.credential = Credential::Foreign { kind: "teamspeak", blob: Default::default() }; params.push_capacity = 1; let connecting = tokio::spawn(connector.connect(params)); let inner = within("the link to be asked", seen.recv()).await; - inner.events.send(connected(everything())).unwrap(); + // Made before the link is told it is connected: the connector waits only + // 250 ms for the first snapshot, and making 5,000 channels can take longer + // than that on a busy machine, which left the session without them. let mut big = presence(); for id in 100..100 + CHANNELS { let channel = ChannelInfo { id, name: format!("c{id}"), ..Default::default() }; big.channels.insert(id, channel); } + inner.events.send(connected(everything())).unwrap(); inner.events.send(LinkEvent::Presence(Box::new(big))).unwrap(); let connected = within("a session", async { connecting.await.ok().and_then(Result::ok) }).await; let (session, mut pushes) = (connected.session, connected.pushes); + // The scope is sent whole only if the presence is in the host's state when + // it is asked for. The link takes its events in order, and a voice packet + // of one of the presence's clients comes through only once the presence + // is in: the packet says it is. + inner + .events + .send(LinkEvent::Audio(VoicePacket { + talker: TalkerId(8), + seq: 1, + codec: VoiceCodec::Voice, + whisper: false, + payload: OPUS_20_MS.to_vec(), + })) + .unwrap(); + within("the voice", media.recv()).await; let server = ScopeId::Server(1); session.request(subscribe(server)).await.unwrap(); @@ -2184,12 +2202,48 @@ async fn event_of( .await } +/// Asks for the file list of the lobby until the answer is one `wanted` takes, +/// one question at a time: the next goes out only when the last is answered. +/// Asked every few milliseconds instead, the answers fell behind the 16 +/// events the bus holds (and the host's work), and the one that counted was +/// lost in the backlog. +async fn ask_files_until( + cmd_tx: &mpsc::UnboundedSender, + bus: &mut broadcast::Receiver, + request: &mut crate::files::RequestId, + wanted: impl Fn(&Result, String>) -> bool, +) { + within("the file list to be answered as wanted", async { + loop { + *request += 1; + let dir = remote(10, None, "/"); + cmd_tx.send(LinkCmd::ListFiles { request: *request, dir }).ok()?; + let result = loop { + match bus.recv().await { + Ok(Event::FileList { request: answered, result, .. }) + if answered == *request => + { + break result; + } + Ok(_) | Err(broadcast::error::RecvError::Lagged(_)) => {} + Err(broadcast::error::RecvError::Closed) => return None, + } + }; + if wanted(&result) { + return Some(()); + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await; +} + /// `Server.features` narrows what the host offers (protocol 1.3, /// `docs/session-seam.md` 4.7), and a `HostUpdate` changes what is narrowed. #[tokio::test(flavor = "multi_thread")] async fn the_features_of_a_server_are_the_hosts_narrowed_by_the_servers_list() { use v1::entity::Kind; - use voelin_proto::test_util::{FakeConnector, eventually}; + use voelin_proto::test_util::FakeConnector; let connector = FakeConnector::new(); let host = connector.host(); @@ -2241,55 +2295,26 @@ async fn the_features_of_a_server_are_the_hosts_narrowed_by_the_servers_list() { }) .count() }; - let ask = |request| { - let dir = remote(10, None, "/"); - cmd_tx.send(LinkCmd::ListFiles { request, dir }).unwrap(); - }; let refusal = "not offered by this server: files"; let refused = - |event: &Event| matches!(event, Event::FileList { result: Err(why), .. } if why == refusal); + |result: &Result, String>| matches!(result, Err(why) if why == refusal); + let mut request = 0; // Refused here: nothing reaches the host. - ask(1); - loop { - let event = within("the refusal", async { bus.recv().await.ok() }).await; - if refused(&event) { - break; - } - } + ask_files_until(&cmd_tx, &mut bus, &mut request, refused).await; assert_eq!(file_lists(), 0); // The server lifts its list (an empty one keeps all the host's): files work. put_server(&[]); - let mut request = 1; - eventually(WAIT, "a file list to reach the host", || { - request += 1; - ask(request); - file_lists() > 0 - }) - .await; + ask_files_until(&cmd_tx, &mut bus, &mut request, |result| !refused(result)).await; + assert!(file_lists() > 0, "the answer did not come from the host"); - // The host narrows what it offers this user. A refusal counts only for a - // request made after the update: the earlier ones were answered by the host's - // wider set (or, before the server lifted its list, refused for that). + // The host narrows what it offers this user. Every question is answered + // before the next is asked, so those asked from here on are the ones the + // update can refuse; the earlier ones were answered by the host's wider set. let update = v1::HostUpdate { features: vec!["voice".into(), "chat".into()], limits: None }; handle.push(v1::Push { body: Some(v1::push::Body::HostUpdate(update)) }).unwrap(); - let after = request; - within("the narrower set to apply", async { - loop { - request += 1; - ask(request); - tokio::time::sleep(Duration::from_millis(20)).await; - while let Ok(event) = bus.try_recv() { - if matches!(&event, Event::FileList { request, .. } if *request > after) - && refused(&event) - { - return Some(()); - } - } - } - }) - .await; + ask_files_until(&cmd_tx, &mut bus, &mut request, refused).await; } /// A port that is no port is refused in words, not dropped: the connection diff --git a/crates/voelin-core/src/media.rs b/crates/voelin-core/src/media.rs index 38db2da..3d7c322 100644 --- a/crates/voelin-core/src/media.rs +++ b/crates/voelin-core/src/media.rs @@ -3257,9 +3257,13 @@ impl LocalPreview { } /// The first and last column of the rectangle in the middle row of a -/// decoded test pattern. Checks that pixels further than two columns from -/// its edges (which the codec blurs) have the colour of the rectangle or -/// the background. +/// decoded test pattern, after checking the row's structure: background, one +/// run of the rectangle, background. A pixel is whichever of the pattern's two +/// colours it is nearer to; it is not asked to be within some distance of one, +/// because an encoder that falls behind lowers its quality (the VP8 speed +/// control of the streamer does) and then moves a flat colour by 30 and more +/// per channel, still nowhere near the other colour. The two columns at each +/// edge, which the codec blurs, may be either. #[cfg(all(test, feature = "media-desktop"))] pub(crate) fn rectangle_span(picture: &VideoFrame) -> (u32, u32) { use voelin_media::capture::synthetic::{BACKGROUND, RECT_COLOR}; @@ -3270,15 +3274,23 @@ pub(crate) fn rectangle_span(picture: &VideoFrame) -> (u32, u32) { let i = ((y * picture.width + x) * 4) as usize; [rgba[i], rgba[i + 1], rgba[i + 2]] }; - let close = |p: [u8; 3], c: [u8; 3]| p.iter().zip(c).all(|(a, b)| a.abs_diff(b) <= 24); - let inside: Vec = (0..picture.width).filter(|&x| close(pixel(x), RECT_COLOR)).collect(); - let (&a, &b) = inside.first().zip(inside.last()).expect("no rectangle in the middle row"); - for x in 0..picture.width { - if x + 2 < a || x > b + 2 { - assert!(close(pixel(x), BACKGROUND), "pixel {x},{y} is {:?}", pixel(x)); - } else if (a + 2..=b.saturating_sub(2)).contains(&x) { - assert!(close(pixel(x), RECT_COLOR), "pixel {x},{y} is {:?}", pixel(x)); - } + let distance = |p: [u8; 3], c: [u8; 3]| -> u32 { + p.iter().zip(c).map(|(a, b)| u32::from(a.abs_diff(b)).pow(2)).sum() + }; + let rectangle = |x: u32| { + let p = pixel(x); + distance(p, RECT_COLOR) < distance(p, BACKGROUND) + }; + let a = (0..picture.width).find(|&x| rectangle(x)).expect("no rectangle in the middle row"); + let b = (0..picture.width).rfind(|&x| rectangle(x)).unwrap(); + // One run: everything between its ends, but the blurred edges, is the + // rectangle's. Whatever is outside is the background by the choice of a and b. + for x in a + 2..=b.saturating_sub(2) { + assert!( + rectangle(x), + "pixel {x},{y} is {:?}, in the middle of the rectangle (columns {a} to {b})", + pixel(x) + ); } (a, b) } @@ -3536,10 +3548,24 @@ mod tests { }; told(30).await; assert_eq!(streamer.bitrate_kbps(), 1105); - // Not per frame. - let count = lock(&sink.formats).len(); - tokio::time::sleep(Duration::from_millis(200)).await; - assert_eq!(lock(&sink.formats).len(), count); + // Not per frame. The sink is told when it is attached and again by the + // encoder before its first frame (the same format twice), so the count is + // taken once a frame has been handed over and compared after more have; + // the frames, not a pause, are what "per frame" counts. + let frames_by = |frames: u64| { + let streamer = &streamer; + async move { + let deadline = Instant::now() + Duration::from_secs(30); + while streamer.stats().layers[0].frames < frames { + assert!(Instant::now() < deadline, "{frames} frames: {:?}", streamer.stats()); + tokio::time::sleep(Duration::from_millis(20)).await; + } + } + }; + frames_by(1).await; + let (count, seen) = (lock(&sink.formats).len(), streamer.stats().layers[0].frames); + frames_by(seen + 5).await; + assert_eq!(lock(&sink.formats).len(), count, "told again within five frames"); // The stats follow the sink's being told, not the other way round. let deadline = Instant::now() + Duration::from_secs(10); while streamer.stats().layers[0].bitrate != auto_bitrate(640, 480, 30) { @@ -3716,15 +3742,35 @@ mod tests { assert!((60..=68).contains(&(b - a + 1)), "{spans:?}"); } assert_ne!(spans.first(), spans.last(), "the rectangle moves"); - let stats = preview.stats(); - assert!(stats.decoded >= 10 && stats.error.is_none(), "{stats:?}"); - assert_eq!(stats.codec, Some(Codec::Vp8)); + let (before_first, first) = (Instant::now(), preview.stats()); + let after_first = Instant::now(); + assert!(first.decoded >= 10 && first.error.is_none(), "{first:?}"); + assert_eq!(first.codec, Some(Codec::Vp8)); assert_eq!(preview.streamer().backend(), "synthetic"); - // Rates over the second since: the pattern's rate, its bitrate. + // The rates are the counters over the time since the call before. How + // long that was the test does not say (a busy machine stretches a second, + // and the rate of pictures it manages is not what is tested), but it lies + // between the two spans the test timed around it. tokio::time::sleep(Duration::from_secs(1)).await; - let stats = preview.stats(); - assert!((20..=40).contains(&stats.fps), "{stats:?}"); - assert!((100_000..5_000_000).contains(&stats.bitrate), "{stats:?}"); + let before_second = Instant::now(); + let second = preview.stats(); + let after_second = Instant::now(); + let longest = after_second.duration_since(before_first).as_secs_f64(); + let shortest = before_second.duration_since(after_first).as_secs_f64(); + let frames = (second.decoded - first.decoded) as f64; + let bits = (second.bytes - first.bytes) as f64 * 8.0; + assert!(frames > 0.0, "no picture in the second: {first:?} {second:?}"); + // (The pictures per second are rounded, the bits per second cut off.) + let fps = f64::from(second.fps); + assert!( + (frames / longest - 0.5..=frames / shortest + 0.5).contains(&fps), + "{frames} pictures in {shortest} to {longest} s are not {fps} a second" + ); + let bitrate = second.bitrate as f64; + assert!( + (bits / longest - 1.0..=bits / shortest).contains(&bitrate), + "{bits} bits in {shortest} to {longest} s are not {bitrate} a second" + ); } /// A VP8 decoder for the pipeline tests: fails (with errors, or giving @@ -4148,7 +4194,8 @@ mod tests { }; let streamer = Streamer::start(&codecs, config).await.unwrap(); let wait = |what: &str, done: &dyn Fn(&StreamerStats) -> bool| { - let deadline = Instant::now() + Duration::from_secs(5); + // What is waited for is a state; the deadline only ends a hang. + let deadline = Instant::now() + Duration::from_secs(30); loop { let stats = streamer.stats(); if done(&stats) { @@ -4158,15 +4205,18 @@ mod tests { std::thread::sleep(Duration::from_millis(20)); } }; - // The SineSource tone is 0.05; the second at half gain. + // The SineSource tone is 0.05; the second at half gain. The sources are metered + // before the mixer has made anything of them: the mix and the state of the + // sources are waited for too, not taken to be there with the meters. let near = |level: f32, want: f32| (level - want).abs() < want * 0.1; - let stats = wait("both tones", &|s| { + let stats = wait("both tones, mixed", &|s| { s.audio_sources.len() == 2 && near(s.audio_sources[0].level.peak, 0.05) && near(s.audio_sources[1].level.peak, 0.025) + && s.audio_sources.iter().all(|s| s.state == SourceState::Playing) + && s.audio_level.peak > 0.05 + && s.audio_limiter == 1.0 }); - assert!(stats.audio_sources.iter().all(|s| s.state == SourceState::Playing)); - assert!(stats.audio_level.peak > 0.05 && stats.audio_limiter == 1.0, "{stats:?}"); let first = stats.audio_sources[0].id; // Mute the first (kept: same id), drop the second, add the @@ -4182,19 +4232,31 @@ mod tests { streamer.reconfigure(&codecs, update).unwrap(); assert_eq!(streamer.audio_sources().len(), 3); let publisher = tap::publisher_id(); - let speak = std::thread::spawn(move || { - // 20 ms of a 0.2 tone every 20 ms, for a second. - let chunk: Vec = (0..960).map(|i| 0.2 * (i as f32 * 0.1).sin()).collect(); - for _ in 0..50 { - tap::microphone().publish(publisher, &chunk); - std::thread::sleep(Duration::from_millis(20)); + let heard = Arc::new(AtomicBool::new(false)); + let speak = std::thread::spawn({ + let heard = heard.clone(); + move || { + // 20 ms of a 0.2 tone every 20 ms, until the test has heard it: the + // source takes what is published only from when it runs, which a + // busy machine delays by any time (the cap ends a thread whose test + // failed first). + let cap = Instant::now() + Duration::from_secs(120); + let chunk: Vec = (0..960).map(|i| 0.2 * (i as f32 * 0.1).sin()).collect(); + while !heard.load(Ordering::Relaxed) && Instant::now() < cap { + tap::microphone().publish(publisher, &chunk); + std::thread::sleep(Duration::from_millis(20)); + } } }); let stats = wait("microphone in, tone muted", &|s| { s.audio_sources.len() == 3 && s.audio_sources[1].level.peak > 0.15 && s.audio_level.peak > 0.15 + && s.audio_sources[2].error.as_deref().is_some_and(|e| e.contains("no window")) + // Muted, and still metered: the tone's own level is read again. + && near(s.audio_sources[0].level.peak, 0.05) }); + heard.store(true, Ordering::Relaxed); speak.join().unwrap(); assert_eq!(stats.audio_sources[0].id, first, "the kept tone keeps its source"); assert!(stats.audio_sources[0].spec.muted); @@ -4226,9 +4288,15 @@ mod tests { assert!(streamer.has_audio(), "{:?}", streamer.audio_error()); let mut source = EncodedSource::new(streamer); let mut frames = Vec::new(); - let deadline = Instant::now() + Duration::from_secs(5); - while frames.iter().filter(|f: &&EncodedFrame| f.kind == MediaKind::Audio).count() < 10 { - assert!(Instant::now() < deadline, "no audio"); + // Ten frames of audio and one of video, whichever the encoders make first: + // 20 ms of audio is quickly made, and a busy machine can keep the video + // encoder from its first frame for longer than that. The deadline only ends + // a hang. + let deadline = Instant::now() + Duration::from_secs(30); + let count = + |frames: &[EncodedFrame], kind| frames.iter().filter(|f| f.kind == kind).count(); + while count(&frames, MediaKind::Audio) < 10 || count(&frames, MediaKind::Video) < 1 { + assert!(Instant::now() < deadline, "no audio or no video in {} frames", frames.len()); tokio::time::sleep(Duration::from_millis(20)).await; source.poll_frames(Instant::now(), &mut frames); } diff --git a/crates/voelin-core/src/stream.rs b/crates/voelin-core/src/stream.rs index f385e2c..893bed0 100644 --- a/crates/voelin-core/src/stream.rs +++ b/crates/voelin-core/src/stream.rs @@ -1342,7 +1342,11 @@ mod tests { .await .expect("the layer did not change"); sink.layer_format(0, format(9_000_000)); - tokio::time::sleep(Duration::from_millis(200)).await; + // The stream task takes its commands in order: its answer to this one + // (an error, nobody is viewer 65535) comes after all that the format + // above set going, and nothing is left to wait out. + handles[0].send(StreamCmd::Kick { viewer: u16::MAX }); + wait(&mut rx, |e| matches!(e, Event::Error { session: 1, .. }).then_some(())).await; assert!(!keyframes(), "nothing changed"); handles[0].send(StreamCmd::Stop); } diff --git a/crates/voelin-core/src/ts/identity.rs b/crates/voelin-core/src/ts/identity.rs index 8adbd9f..a26708e 100644 --- a/crates/voelin-core/src/ts/identity.rs +++ b/crates/voelin-core/src/ts/identity.rs @@ -259,7 +259,8 @@ pub fn from_blob(blob: &IdentityBlob) -> Result { } /// The TeamSpeak identity in `json`, the text [`to_blob`] writes and the key -/// store keeps; every reader of that text refuses it through here. +/// store keeps; voelin-core reads that text only through here (voelin-store +/// parses it too, for its own checks of a stored row). /// /// What does not read is refused in words that say how it is wrong /// (malformed, cut short, not an identity, unreadable) and where (line and diff --git a/crates/voelin-core/src/ts/voice.rs b/crates/voelin-core/src/ts/voice.rs index 24fcd9d..f20f224 100644 --- a/crates/voelin-core/src/ts/voice.rs +++ b/crates/voelin-core/src/ts/voice.rs @@ -1650,8 +1650,10 @@ mod account_tests { events, )); let mut packet = [0; 2048]; - let (_, first) = - timeout(Duration::from_secs(5), server.recv_from(&mut packet)).await.unwrap().unwrap(); + let (_, first) = timeout(Duration::from_secs(5), server.recv_from(&mut packet)) + .await + .expect("the first handshake packet within 5 s") + .unwrap(); // A logout/clear notification must cancel the old socket and restart. account.send_replace(None); let second = timeout(Duration::from_secs(5), async { @@ -1663,11 +1665,14 @@ mod account_tests { } }) .await - .unwrap(); + .expect("a handshake packet from a new socket within 5 s of the account change"); assert_ne!(first, second); // Losing the account authority fails closed immediately, not after connect timeout. drop(account); - timeout(Duration::from_secs(2), task).await.unwrap().unwrap(); + timeout(Duration::from_secs(2), task) + .await + .expect("the connection to end within 2 s of the account source closing") + .unwrap(); assert!( matches!(received.recv().await, Some(LinkEvent::Disconnected(Some(reason))) if reason == "account source closed") ); diff --git a/crates/voelin-core/tests/common/mod.rs b/crates/voelin-core/tests/common/mod.rs new file mode 100644 index 0000000..57dd5fb --- /dev/null +++ b/crates/voelin-core/tests/common/mod.rs @@ -0,0 +1,28 @@ +//! What more than one integration test of this crate needs (a test binary +//! that uses it declares `mod common;`). + +use std::path::{Path, PathBuf}; +use std::time::Duration; + +/// Wait until nothing has the SQLite database at `path` open any more, as when +/// the process that had it has ended: SQLite deletes the write-ahead log +/// (`-wal`) when the last connection closes. +/// +/// A dropped `Engine` is not that yet. Its task ends later, the history writer +/// is joined there, and closing the connection checkpoints the log under an +/// exclusive lock, with fsyncs. A connection opened meanwhile waits for the +/// lock only as long as the busy timeout (5 s) and then fails with +/// `DatabaseBusy`, which a loaded disk makes happen (with every fsync taking +/// 6 s it happens every time). +pub async fn closed(path: &Path) { + let mut wal = path.as_os_str().to_owned(); + wal.push("-wal"); + let wal = PathBuf::from(wal); + tokio::time::timeout(Duration::from_secs(120), async { + while wal.exists() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("the engine's database connection closed"); +} diff --git a/crates/voelin-core/tests/gateway.rs b/crates/voelin-core/tests/gateway.rs index 65e37ac..d4b254b 100644 --- a/crates/voelin-core/tests/gateway.rs +++ b/crates/voelin-core/tests/gateway.rs @@ -24,6 +24,8 @@ use voelin_gateway_proto::{ }; use voelin_model::{ChatMessage, ChatTarget, PresenceSnapshot}; +mod common; + const LOBBY: ChatTarget = ChatTarget::Channel(1); const ME: &str = "me-uid"; @@ -529,6 +531,8 @@ async fn history_on_open_paging_and_offline_messages() { assert_eq!(texts(&stored), ["m1", "m2", "m3", "m4", "m5", "while away 1", "while away 2"]); history.flush(); drop((engine, history)); + // Dropping the engine does not close the database yet (see `closed`). + common::closed(&path).await; // After a restart, with the gateway down: the stored page, found by the // gateway's URL, which is remembered with the server's id. @@ -812,7 +816,16 @@ async fn not_found_proxy() -> String { #[tokio::test(flavor = "multi_thread")] async fn the_next_published_gateway_is_used_when_one_fails() { let proxy = not_found_proxy().await; - let closed = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port(); + // A port that is taken and never listened on: connecting is refused at once, + // and no other test of this process can be given it meanwhile (one that was + // only free for a moment could be, the listeners of the others bind port 0). + let reserved = tokio::net::TcpSocket::new_v4().unwrap(); + reserved.bind("127.0.0.1:0".parse().unwrap()).unwrap(); + let closed = reserved.local_addr().unwrap().port(); + assert!( + tokio::net::TcpStream::connect(("127.0.0.1", closed)).await.is_err(), + "something listens on port {closed}" + ); let gw = FakeGateway::start().await; let path = temp_db("fallback"); let engine = Engine::start_with(Settings::in_memory(), History::open(&path).unwrap()); diff --git a/crates/voelin-core/tests/live.rs b/crates/voelin-core/tests/live.rs index 105aa04..5c637a6 100644 --- a/crates/voelin-core/tests/live.rs +++ b/crates/voelin-core/tests/live.rs @@ -1,8 +1,10 @@ //! Engine against the development servers (dev/docker-compose.yml). //! Runs only with `VOELIN_LIVE=1`; `scripts/it-smoke.sh` sets it. +use std::sync::LazyLock; use std::time::Duration; +use tokio::sync::RwLock; use tokio::sync::broadcast::Receiver; use tokio::time::{Instant, timeout_at}; use voelin_core::{ @@ -15,6 +17,17 @@ fn live() -> bool { std::env::var("VOELIN_LIVE").is_ok_and(|v| v == "1") } +/// The TeamSpeak 6 server's banners are the server's, and `ts6_banners` sets and +/// unsets them there. While it does, whatever else connects to the server is +/// told the addresses of those banners, and an engine fetches what it is told +/// (as it should): the requests of such an engine reached the HTTP server of +/// `ts6_banners`, which counts the requests of the engine under test, and the +/// test failed on `disabled policy must prevent HTTP requests` in every run +/// that had the tests of this file run side by side (as they do). The tests +/// that connect to the server hold this shared, `ts6_banners` exclusively: it +/// runs with the server to itself, and the others before or after it. +static TS6: LazyLock> = LazyLock::new(|| RwLock::new(())); + /// Wait for an event matching `f`, failing after 20 s. async fn wait_for( rx: &mut Receiver, @@ -131,6 +144,7 @@ async fn ts6_engine() { if !live() { return; } + let _server = TS6.read().await; engine_roundtrip("127.0.0.1:9988", query(voelin_query::Transport::Ssh, "127.0.0.1:10022")) .await; } @@ -258,6 +272,7 @@ async fn ts6_channel_joins() { if !live() { return; } + let _server = TS6.read().await; channel_joins("127.0.0.1:9988", query(voelin_query::Transport::Ssh, "127.0.0.1:10022")).await; } @@ -329,6 +344,7 @@ async fn ts6_banners() { if !live() { return; } + let _server = TS6.write().await; let voice_addr = std::env::var("VOELIN_BANNER_VOICE_ADDR").unwrap_or_else(|_| "127.0.0.1:9988".into()); let query_addr = @@ -512,6 +528,7 @@ async fn ts6_avatars() { if !live() { return; } + let _server = TS6.read().await; let voice_addr = std::env::var("VOELIN_BANNER_VOICE_ADDR").unwrap_or_else(|_| "127.0.0.1:9988".into()); let dir = std::env::temp_dir().join(format!("voelin-live-avatars-{}", std::process::id())); diff --git a/crates/voelin-core/tests/voice_features.rs b/crates/voelin-core/tests/voice_features.rs index 69f7d99..e869dea 100644 --- a/crates/voelin-core/tests/voice_features.rs +++ b/crates/voelin-core/tests/voice_features.rs @@ -3,7 +3,6 @@ //! in the client database). The round trips against real servers are in //! `scripts/it-smoke.sh` (`voelinctl engine`). -use std::path::{Path, PathBuf}; use std::time::Duration; use tokio::sync::broadcast; @@ -11,6 +10,10 @@ use voelin_core::settings::Settings; use voelin_core::{Command, Contact, DownloadTo, Engine, Event, History, Relation, TransferState}; use voelin_model::FileRef; +mod common; + +use common::closed; + async fn next(rx: &mut broadcast::Receiver, mut f: impl FnMut(Event) -> Option) -> T { tokio::time::timeout(Duration::from_secs(10), async { loop { @@ -23,29 +26,6 @@ async fn next(rx: &mut broadcast::Receiver, mut f: impl FnMut(Event) - .expect("event in time") } -/// Wait until nothing has the SQLite database at `path` open any more, as when -/// the process that had it has ended: SQLite deletes the write-ahead log -/// (`-wal`) when the last connection closes. -/// -/// A dropped `Engine` is not that yet. Its task ends later, the history writer -/// is joined there, and closing the connection checkpoints the log under an -/// exclusive lock, with fsyncs. A connection opened meanwhile waits for the -/// lock only as long as the busy timeout (5 s) and then fails with -/// `DatabaseBusy`, which a loaded disk makes happen (with every fsync taking -/// 6 s it happens every time). -async fn closed(path: &Path) { - let mut wal = path.as_os_str().to_owned(); - wal.push("-wal"); - let wal = PathBuf::from(wal); - tokio::time::timeout(Duration::from_secs(120), async { - while wal.exists() { - tokio::time::sleep(Duration::from_millis(10)).await; - } - }) - .await - .expect("the engine's database connection closed"); -} - #[tokio::test(flavor = "multi_thread")] async fn requests_without_voice_fail_with_their_ids() { let engine = Engine::start(); diff --git a/crates/voelin-media/src/studio/mod.rs b/crates/voelin-media/src/studio/mod.rs index a6d62d8..7879607 100644 --- a/crates/voelin-media/src/studio/mod.rs +++ b/crates/voelin-media/src/studio/mod.rs @@ -1180,19 +1180,32 @@ mod tests { scenes } + /// The first preview frame that `wanted` takes. The preview keeps the latest + /// frame only, so few older ones are waiting or on their way: the number of + /// frames looked at is the bound (the work), and the wait for each, which a + /// busy machine can stretch, only ends a hang. + fn preview_until( + preview: &Handoff, + wanted: impl Fn(&VideoFrame) -> bool, + ) -> Arc { + for _ in 0..20 { + let frame = preview.wait_timeout(Duration::from_secs(30)).expect("a preview frame"); + if wanted(&frame) { + return frame; + } + } + panic!("the preview never showed what was asked for"); + } + #[tokio::test] async fn it_composes_into_the_preview_and_follows_commands() { let studio = Studio::start(one_colour_scene()).await.unwrap(); let preview = studio.preview(); studio.apply(Command::SetPreview { width: 32, height: 24, fps: 60 }).await.unwrap(); - let started = Instant::now(); - let frame = loop { - if let Some(frame) = preview.wait_timeout(Duration::from_millis(200)) { - break frame; - } - assert!(started.elapsed() < Duration::from_secs(5), "no preview frame"); - }; - assert_eq!((frame.width, frame.height), (32, 24)); + // The studio composes from the moment it starts, at the size and rate the + // preview has then (480x270, 15 fps): a frame of that size can be the + // first one there is. + let frame = preview_until(&preview, |f| (f.width, f.height) == (32, 24)); let crate::frame::FrameData::Rgba(p) = &frame.data else { panic!("not RGBA") }; assert_eq!(&p.data[..4], &[9, 8, 7, 255]); @@ -1211,15 +1224,12 @@ mod tests { .unwrap(); studio.apply(Command::SetActiveScene { scene: break_id }).await.unwrap(); assert_eq!(studio.status().active_scene, break_id); - // The new scene's source draws. - let frame = loop { - let frame = preview.wait_timeout(Duration::from_secs(2)).expect("a preview frame"); - let crate::frame::FrameData::Rgba(p) = &frame.data else { panic!() }; - if p.data[..3] == [1, 2, 3] { - break frame; - } - assert!(started.elapsed() < Duration::from_secs(10), "the scene never switched"); - }; + // The new scene's source draws, from the first frame composed after the + // command. + let frame = preview_until( + &preview, + |f| matches!(&f.data, crate::frame::FrameData::Rgba(p) if p.data[..3] == [1, 2, 3]), + ); drop(frame); studio.apply(Command::RemoveScene { scene: break_id }).await.unwrap(); @@ -1402,9 +1412,16 @@ mod tests { assert_eq!((listed[0].width, listed[0].height), (64, 48)); let frames = capture.start(&SourceId::Studio, &CaptureOptions::default()).await.unwrap(); let mut frames = frames; - let frame = frames.recv_timeout(Duration::from_secs(5)).expect("a composed frame"); + // (The wait only ends a hang.) + let frame = frames.recv_timeout(Duration::from_secs(30)).expect("a composed frame"); assert_eq!((frame.width, frame.height), (64, 48)); - assert!(studio.shared.delivered.load(Ordering::Relaxed) > 0); + // A frame is counted once it has been handed over, so the count can still be + // behind when the frame is in the hands of the test. + let deadline = Instant::now() + Duration::from_secs(30); + while studio.shared.delivered.load(Ordering::Relaxed) == 0 { + assert!(Instant::now() < deadline, "the frame handed over was never counted"); + std::thread::sleep(Duration::from_millis(5)); + } capture.stop(); std::fs::remove_dir_all(&dir).ok(); } diff --git a/crates/voelin-platform/tests/proxy.rs b/crates/voelin-platform/tests/proxy.rs index bead427..f9a1ed0 100644 --- a/crates/voelin-platform/tests/proxy.rs +++ b/crates/voelin-platform/tests/proxy.rs @@ -85,6 +85,11 @@ fn on_a_bus_of_its_own() { let text = format!("{}{}", String::from_utf8_lossy(&run.stdout), String::from_utf8_lossy(&run.stderr)); if run.status.success() { + // A child that ran no test (its filter matched nothing) exits 0 as well. + assert!( + text.contains("test result: ok. 1 passed;"), + "the run on its own bus exited 0 without reporting `1 passed`:\n{text}" + ); return; } // The test ran and failed, or the bus never came up. diff --git a/docs/ci.md b/docs/ci.md index 538eb27..d388927 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -185,6 +185,12 @@ The tests that reach a server of their own go to `127.0.0.1` by name, not through `localhost`, so a machine where connections to `::1` hang (a development machine with a VPN does that) changes nothing for them. +A test that passes in the image and fails now and then on a busy runner or +development machine is another kind of failure, a test of the machine's load: +[testing/load.md](testing/load.md) says how to make a machine busy to +reproduce one, what the tests that failed that way assert now, and which are +known and left alone. + ### VoelinProtocol access The workspace depends on `voelin-identity` from the **private** repository diff --git a/docs/testing/load.md b/docs/testing/load.md new file mode 100644 index 0000000..a502a7c --- /dev/null +++ b/docs/testing/load.md @@ -0,0 +1,261 @@ +# Tests under load + +A test that passes alone and fails one run in a hundred when the machine is +busy is a test of the machine. The runner shares its CPUs with other jobs, and +a developer's machine with whatever else runs on it, so the suite has to give +the same answer on a busy machine as on an idle one. This page says how to +make a machine busy, what the fixes of `phase5/test-hygiene` did about the +tests that failed only then, and what is known and left alone. + +## The round of `phase5/test-hygiene` + +The branch is `phase5/test-hygiene`, from `2ffe5ff` (main with the session +seam, its follow-ups, the CI deploy key and `phase5/tests-under-runner`). It +settles the left-overs of the review of the seam follow-ups and of the +tests-under-runner round. The `mao-*` agents were not registered in the +session, so a general-purpose agent played `mao-implementer` (Sonnet 5.5), +attempt 1; an earlier run of the same task was cut off by a restart of the +orchestrator, left four commits and an uncommitted tree, and this attempt +judged those, kept what was right and finished the rest. No history was +rewritten; `THIRD_PARTY_NOTICES.md` is untouched (`Cargo.lock` did not change). + +| Commit | What | Whose | +|---|---|---| +| `e465a55` | Item 2: the fallback gateway test keeps its "closed" port bound | cut-off run, kept | +| `ac957a0` | Item 1: the history test of `gateway.rs` waits for the `-wal` file before it reopens (`tests/common/mod.rs`) | cut-off run, kept | +| `35408a3` | Item 5: the portal proxy test requires `1 passed` of its child | cut-off run, kept | +| `7e63092` | Item 4: `from_json`'s doc names voelin-core (voelin-store parses the text too: `keystore.rs` `check_teamspeak` and `level`, `store.rs` `list`) | cut-off run, kept | +| `0bc6aba` | Item 3: the account-change test names the step it timed out in | this attempt | +| `f9bfd5d` | Item 6: `rectangle_span` checks the pattern's structure | cut-off run's tree, committed | +| `25be433` | Item 6: the preview test checks its rates against its own timing | cut-off run's tree, committed | +| `81c40a4` | Item 6: `audio_sources_change_live` | cut-off run's tree, committed | +| `c5bb74f` | Item 6: the server-features test asks one question at a time | cut-off run's tree, committed | +| `7730460` | Item 6: the layer-format test waits for the stream task's answer | cut-off run's tree, committed | +| `9d04e01` | Item 6: the studio compose test waits for the frame it asks for | cut-off run's tree, committed | +| `92d02b0` | Beyond the list: the studio capture-backend test waits for the delivered count | cut-off run's tree, committed | +| `661a607` | Beyond the list: the scope test and `streamer_sends_opus` | cut-off run's tree, committed | +| `069fd2a` | Item 7: `ts6_banners` runs with the TeamSpeak 6 server to itself | cut-off run's tree, committed | +| `5c029a9` | Item 7: the smoke's `roundtrip` waits for its listener | cut-off run's tree, committed | +| `94195db` | rustfmt of four spots of the commits above | this attempt | +| `f508e5b` | Beyond the list: the automatic-bitrate test counts frames | this attempt | +| `ad80660` | The smoke script says which of its checks still flake | this attempt | +| `d4ccb8c`, `376925a` | `docs/testing/load.md` and the pointer in `docs/ci.md`; the record of the round, with the table of the checks | this attempt | + +Two hunks of the cut-off run's tree were dropped: the timing instrumentation of +the account-change test (`Instant`s and an `eprintln!` of the steps, replaced +by the named `expect`s of `0bc6aba`; its numbers are below) and a +`#[cfg(test)] FIRST_SNAPSHOT` of 5 s in `ts_session` (it keeps the lib tests +from running the 250 ms the engine really has; see "Seen and left alone"). The +commits "beyond the list" are fixes of tests that failed in this round's own +runs, each in a commit of its own, and can be dropped without touching the +others. + +What ran, on the final tree (the dev shell `dev rust-nightly -p cmake -p clang +-p pkg-config -p jq -p alsa-lib -p openssl -p libvpx -p dav1d -p pipewire -p +fontconfig -p freetype -p libxkbcommon -p expat -p dbus -p procps -p gnumake` +with the pinned 1.94 or the nightly of 2026-10-21 in front of `PATH`, and +`LIBCLANG_PATH`): + +| Check | Result | +|---|---| +| `cargo fmt $(scripts/own-crates.sh) -- --check`, `cargo clippy $(scripts/own-crates.sh) --all-targets --locked --no-deps -- -D warnings` | 1.94: clean at the head | +| The same on nightly | clippy is blocked at sites of the baseline (none in a line of this branch): `chunks_exact_to_as_chunks` (voelin-core `audio.rs` and `media.rs:4057`, voelin-media), `manual_checked_ops`, `unnecessary_sort_by` (voelin-media), `result_large_err` (`ts/voice.rs:476`); with those four allowed the three touched crates are clean with all targets. voelin-platform is clean. `rustfmt` differs at `history.rs`, `ffmpeg/encoder.rs`, `discovery.rs`, `chat.rs` and `voelinctl/src/engine.rs`, none changed here | +| Clippy alone, at each of the 16 commits above that touch Rust, checked out detached | 1.94, `voelin-core`, `voelin-media`, `voelin-platform`, all targets, `media-desktop`: clean at each. `rustfmt` was not clean at seven commits from `c5bb74f` to `069fd2a` (the commits that wrote the four spots `94195db` formats, and the shell-only `5c029a9` that sits on that tree); per-commit rustfmt waived by the orchestrator, fixed forward, no history rewrite | +| `cargo test -p voelin-core -p voelin-platform -p voelin-media --locked --no-fail-fast`, ten times in a row | 516 tests passed and 13 ignored in each of ten runs, 33 test binaries each; load average 89 to 29 from other jobs | +| The same with `--features voelin-core/media-desktop` (the tests of this round's `media` fixes only exist there; `cargo test --workspace` has it on through `voelin-ui`) | 551 passed and 14 ignored in each of ten runs; load average 21 to 25 | +| `cargo check --workspace --all-targets --locked` | passes (1.94) | +| The tests of the tables below, 100 runs each of the binary of `2ffe5ff` and of the final tree, and the whole lib binaries | The tables below | +| `scripts/it-smoke.sh ts3 ts6` | Below, "The live smoke" | + +## Making the machine busy + +The recipe of that round: 32 busy loops beside the run (the machine had 32 +threads), and the test binary started many times, a few at a time, so that +the tests of one binary also meet each other's load: + +```sh +# 1. Build the test binaries once and note their paths (the "executable" of +# the lib and of each integration test); run those, not `cargo test`. +cargo test -p voelin-core --features media-desktop --lib --no-run --message-format=json + +# 2. The busy loops, and 300 runs of one test, 8 at a time. (The +# whole binary, without --exact, is the better test of "under full +# load": every test of it runs at once.) +for _ in $(seq 32); do sh -c 'while :; do :; done' & done +trap 'kill $(jobs -p)' EXIT +seq 300 | xargs -P 8 -I{} sh -c ' --exact >/dev/null 2>&1 || echo FAIL' | sort | uniq -c +``` + +Compare a binary built before a change with one built after it, started +alternately in the same loop, so that both meet the same load. Write the load +average (`/proc/loadavg`) down with the result: other jobs on the shared +machine took it from the 32 loops' 32 to over 100 and, for minutes, to 250, +and some tests fail only above 150 (see below). A failure rate of one in a +hundred tests needs a few hundred runs to show; the whole binary shows its +flaky tests faster than each test alone, since its 275 tests compete. + +## What the fixes assert + +The rules the fixes of this round followed, in the order of preference: + +1. **Wait for the state or event the test is about.** A deadline only ends a + hang (30 s), it never decides the result. A pause (`sleep`) is never what a + test waits for, and a "nothing happened" check waits for something that + comes after it (a command the same task answers in order, a count of + frames), not for time to pass. +2. **Derive a time from the work.** Where a rate is checked, the bounds come + from timestamps taken by the test around the calls, not from a constant. +3. **Check structure, not values within a tolerance**, where a lossy or + adaptive component is involved: an encoder that falls behind lowers its + quality, and a tolerance only moves the load at which the test fails. +4. **Keep what you reserved.** A port that is "free" because a listener was + bound and dropped can be handed to another test of the process at once; + a socket that stays bound and never listens refuses connections for the + whole test. +5. **A test that changes the state of a shared server runs with the server to + itself** (a lock in the test binary), however the harness schedules it. + +## The load-only tests of the round + +100 runs of each test alone, the binary of the commit before the round +(`2ffe5ff`) and the one after it, started alternately 8 at a time beside 32 +busy loops (load average 34 to 81 during the runs), and 150 / 100 runs of the +whole lib binaries of `voelin-core` / `voelin-media`, 4 at a time beside the +same loops (load average 69 to 123). Failed runs, of the runs: + +| Test | Why it failed | It checks now | Alone, before / after | Notes | +|---|---|---|---|---| +| `media::tests::local_preview_decodes_the_pattern`, `stream::tests::test_pattern_through_stream_tasks` (`media::rectangle_span`) | The VP8 speed control lowers the quality when the encoder falls behind; flat colours moved by 30 and more per channel and failed the tolerance of 24 (one of 40 was tried and reverted) | Each pixel is the nearer of the pattern's two colours; the middle row is background, one run of the rectangle, background; the span's width and movement as before. The preview's `fps` and `bitrate` are the counters' change over the time between the two stats calls, which the test timed | 1 / 0 and 1 / 0 of 100 | In the whole lib binary, before: 6 and 4 failures in 150 runs; after: 0 | +| `media::tests::audio_sources_change_live` | The state, mix and limiter were asserted when the meters showed, not waited for; the microphone thread published for one second, which a busy machine delayed past | Waits for the state, the mix and the limiter with the meters; the microphone is fed until the test has heard it | 0 / 0 of 100 | In the whole lib binary, before: 2 failures in 150 runs | +| `link::tests::the_features_of_a_server_are_the_hosts_narrowed_by_the_servers_list` | The file list was asked for every 20 ms and the answers fell behind the 16 events of the bus | One question at a time, the next after the answer (`ask_files_until`) | 0 / 0 of 100 | In the whole lib binary, before: 1 failure in 150 runs | +| `stream::tests::layer_formats_reach_the_live_stream` | "Nothing changed" was a 200 ms sleep, short of the stream task on a busy machine | A command the task answers with an event, sent after the format, and waited for: the task takes its commands in order | 0 / 0 of 100 | The "late streamer-side keyframe request" of the runner round was never seen and is not proven; a request the viewer's side makes late is not covered | +| `studio::tests::it_composes_into_the_preview_and_follows_commands` | The first frame after `SetPreview` can be one composed at the studio's start size (480x270) before the command applied | `preview_until`: the first frame of the size and scene asked for, out of at most 20 | 0 / 0 of 100 | In the whole lib binary of `voelin-media`, before: 0 of 100 runs; seen 2 in 150 earlier in the round | +| `gateway.rs`: `the_next_published_gateway_is_used_when_one_fails` | The "closed" port was bound and dropped; another test of the binary could be given it | A socket kept bound without listening, checked to refuse | 0 / 0 of 100 | | +| `gateway.rs`: `history_on_open_paging_and_offline_messages` | Dropping an `Engine` does not close its database; reopening waited 5 s for the exclusive lock of the closing connection (`DatabaseBusy`) | Waits for the `-wal` file to go (`tests/common/mod.rs`, shared with `voice_features.rs`) | 0 / 0 of 100 | The same as `contacts_are_kept_in_the_database`, fixed in `0d67dd7`. Beside the busy loops it did not fail; with every fsync of the process delayed by 6 s (`strace -f -qq -e trace=fsync,fdatasync -e inject=fsync,fdatasync:delay_enter=6s`) the old test fails every time at the reopen with `DatabaseBusy` (`gateway.rs:536`), the new one passes | +| `voelin-platform` `proxy.rs`: `the_portal_names_the_proxy` | A child that ran no test (its `--exact` name matches none) exits 0 | The wrapper requires `test result: ok. 1 passed;` in the child's output | 0 / 0 of 100 | | + +Found by the same runs, beyond the list, and fixed in their own commits: + +| Test | Why it failed | It checks now | Alone, before / after | Notes | +|---|---|---|---|---| +| `studio::tests::packets_reach_the_outputs_and_the_studio_is_a_capture_backend` | The studio counts a frame as delivered after handing it over, so the count could still be 0 | Waits for the count | 2 / 0 of 100 | Whole `voelin-media` binary, before: 11 of 150 runs (9 of them this test), then 2 of 100; after: 0 of 100 | +| `link::tests::a_scope_bigger_than_the_channel_is_sent_in_bigger_chunks` | 5,000 channels were made after the connector's 250 ms wait for a first snapshot began; the scope was sent before the presence was in | The channels are made first; a voice packet through the link shows the presence is in | 0 / 0 of 100 | 3 failures of about 500 whole-binary runs before, 7 of 300 at a load average of 150 to 250 with the first half of the fix only (the channels first, no voice packet); too rare to count a rate after | +| `media::tests::streamer_sends_opus` | Ten frames of audio came before the first frame of video, which a busy machine delays | Waits for ten of audio and one of video | 0 / 0 of 100 | 2 failures of about 500 whole-binary runs before | +| `media::tests::an_automatic_bitrate_follows_the_stream` | The sink is told the format at `attach` and again by the encoder before its first frame; the test counted in between after a 200 ms pause | Counts after a frame has come and compares after five more | 2 of 900 before; 0 of 600 after | 1 of 150 in the final whole-binary run of the old test | + +The whole `voelin-core` lib binary failed 12 of 150 runs before and 1 of 150 +after (the last test of the table, fixed since), the `voelin-media` binary 2 +of 100 before and 0 of 100 after. + +## `ts::voice::account_tests::account_change_cancels_pending_handshake` + +Seen once in about 130 runs of the whole suite under load by the review of the +seam follow-ups; the failure was not kept. It did not fail again in this round +(it does not touch the test's code or the code it drives), neither alone nor +in the whole lib binary: + +- 600 runs alone, 8 at a time beside 32 busy loops (300 of the unchanged + binary, 300 of the timed one): 600 passed; 100 more before and 100 after + in the table above, 200 passed. +- It is in each whole-binary run of `voelin-core`: about 1,300 runs under + the busy loops in this round (150 of them of the final tree), in none of + which it failed (load average up to 250), and in the ten full runs of + `cargo test -p voelin-core -p voelin-platform -p voelin-media` of each kind + (with and without `media-desktop`) of the final tree. +- The test, timed (a throw-away build): the first handshake packet after + 12.5 ms (median; 34 ms at most), the packet of the new socket after an + account change 6.9 ms (33 ms at most), the end of the connection after the + account source closed 0.2 ms (9 ms at most), in the 300 runs beside the 32 + loops. Its deadlines are 5 s, 5 s and 2 s: 60 times or more the longest + step seen. + +The test and the code were read for a race and none was found: the account +watch has seen its version before the connection is made, so a change after +the first packet always restarts the connection; the restart opens a socket of +its own, so a packet from another port is the new connection's; and dropping +the sender makes `changed()` fail, which ends the loop with the reason the test +expects. The only ways the test can fail are its three deadlines. That is the +evidence for "only load": a failure needs a stall of seconds in one step, and +the machine's, not the test's, is the likelier source. The three timeouts now +say which step it was, so the next failure is attributable; if it is seen +again, keep the output and the load average (`/proc/loadavg`) and see which +of the three it names. + +## Seen and left alone + +These failed in the runs of an intermediate tree of this round at load +averages of 150 to 250 (other jobs on the machine as well as the 32 loops), +and not in the runs of the final tree at 35 to 120. None of them is among the +tests this round changed. + +- `link::tests::the_welcome_names_the_host_the_user_and_what_the_link_can_do`: + the test tells the connection that it is connected and, in the next + statement, gives it the snapshot; the session waits 250 ms for the snapshot + (`FIRST_SNAPSHOT` in `ts_session`), and at a load average of 250 the gap was + longer: the welcome had the user made up from the uid. Raising that constant + in test builds was tried and dropped: it stops the lib tests from running the + 250 ms the engine really has. +- `link::tests::what_the_link_reports_comes_back_as_events` (3 of 300 runs of + the whole lib binary), `link::tests::the_stream_tasks_reports_are_not_held_for_ever` + (2 of 300) and `stream::tests::layers_through_stream_tasks` (3 of 500): timing + of reports against the machine, not looked into further. None failed in the + 500 runs of the tree before the round, which ran at load averages up to 150. +- `media::tests::undecodable_video_is_noticed_through_the_pipeline` (1 of 100 + runs of the whole `voelin-core` lib binary of the final tree, four at a time + beside 32 busy loops, load average 106 to 146; the review's run): + `DecodeWatch` called a real VP8 stream undecodable because no picture was + decoded within 400 ms and 10 frames. Untouched by this round; it did not fail + in 150 before or 150 after runs of the interleaved A/B. + `stream::tests::layers_through_stream_tasks` failed again in the same 100. + +## The live smoke (`scripts/it-smoke.sh`) + +The engine stage (`voelin-core`'s `tests/live.rs`, with `stream_live` and +`media_live`) failed on `disabled policy must prevent HTTP requests` +(`ts6_banners`) in every run that reached it, while the six tests passed +one after the other. The cause was the test: it sets the TeamSpeak 6 server's +banners and counts the requests that reach its own HTTP server for them, and +the other tests of the file, which cargo runs side by side, connect engines to +the same server; the server tells each of them the banners' addresses and an +engine fetches what it is told, so their requests were counted. With the tests +in pairs against the development servers: `ts6_banners` alone passes (62 s), +with `ts6_avatars`, `ts6_engine` or `ts6_channel_joins` it fails. It is not +the engine (it should fetch what the server announces) and not the order of the +script's stages (the tests of one binary run side by side whatever the stage +before). The tests that connect to the TeamSpeak 6 server now hold a lock of +the binary shared, and `ts6_banners` holds it exclusively. + +Before the change, on `2ffe5ff`'s tests and script (the TeamSpeak 3 and 6 +dev servers of `dev/docker-compose.yml`, as a compose project of their own): +the `live` binary failed `ts6_banners` in each run that reached it, with the +six tests side by side (5 passed, 1 failed); the smoke +stopped at `FAIL: private message: the action failed` in its TeamSpeak 3 stage +(`the client is not on the server`) and, in its TeamSpeak 6 stage, at +`FAIL: gateway request {"config_set":...} was not answered`. After it, at the +head of the branch: `scripts/it-smoke.sh ts3 ts6`, three times in a row, the +`live` binary passing 6 of 6 (66 s) in each run that reached the engine stage: +two runs passed every stage (`all smoke tests passed`), one failed in its +TeamSpeak 6 stage at `FAIL: the directory did not list the stream`, below. + +What the smoke still does not do reliably, and was not changed for: + +- Each step that starts a background client and then a second one + (`roundtrip`) used to wait a fixed 3 s; a dev server that takes 4 s to + 13 s to let a client in made the action run before the listener was on the + server (`the client is not on the server`). It now waits for the listener's + `connected:` line. The server's own slowness is not removed. +- The stream directory check (step 10, TeamSpeak 6): the late viewer ends as + soon as it has 30 frames, and the `"title"` line the script looks for is + printed only if the viewer's own gateway session had connected and been + told of the directory by then. In the run that failed it had not (the + viewer's state stayed `observe=Connecting`): the stream was watched, 30 + frames came, and the stream was listed through TeamSpeak 6's own listing + (`streams: ...`), which says nothing about the gateway's directory. A fix is + in `voelinctl engine` (end the viewer when it has both) and was left out of a + round about tests. +- The gateway stage (`voelinctl gateway --engine`, step 8) has failed in a run + with `expected output did not appear` while the engine was still + `observe=Connecting`, before the change as well. That may be the same wait + for a gateway session; it was not looked into. +- `ts6_banners` alone takes 62 s, so the engine stage takes more than a + minute longer than the sum of the others. diff --git a/scripts/it-smoke.sh b/scripts/it-smoke.sh index 466ae84..413d3a8 100755 --- a/scripts/it-smoke.sh +++ b/scripts/it-smoke.sh @@ -379,6 +379,19 @@ features_check() { # TeamSpeak 6: an engine session streams; its stream registers in the # gateway's directory; a viewer that connects later finds it and watches it. +# +# Known to flake, not fixed: voelinctl engine ends the viewer as soon as it has +# the 30 frames (--expect-frames), and the `"title":"..."` line this checks is +# printed only when the viewer's own gateway session got connected and told +# of the directory before that. When the gateway session is still +# `observe=Connecting` at the 30th frame (seen once in three runs of the +# smoke, with the stream watched and the stream listed through TeamSpeak 6's +# own listing, `streams: ...`), the check fails with "the directory did not +# list the stream". The config_set of the gateway stage once failed ("expected +# output did not appear") with its engine still `observe=Connecting` too; +# that was not looked into. A fix for this one +# belongs in voelinctl (end the viewer on both), not here; see +# docs/testing/load.md. directory_check() { local svc=$1 addr=$2 url=$3 user=$4 streamer="dir-$$-$RANDOM" title="directory-$RANDOM" local out="$STATE_DIR/directory-stream.log" viewer_out="$STATE_DIR/directory-watch.log" @@ -413,12 +426,22 @@ server_uid() { "$VOELINCTL" identity show --identity "$id" | awk -v f="$field:" '$1 == f { print $2 }' } -# Run a background listener, then the action; both must succeed. +# Run a background listener, then the action; both must succeed. The action +# starts once the listener says it is on the server ("connected: N clients", +# which voelinctl engine prints for every action): a fixed pause of 3 s sent +# the poke, the private message or the avatar request to a client that was not +# on the server yet whenever the dev server was slow to let one in ("the +# client is not on the server"; a loaded dev server takes 4 to 13 s). roundtrip() { local what=$1 listen_log=$2 listener_cmd=$3 action_cmd=$4 eval "$listener_cmd" >"$listen_log" 2>&1 & local listener=$! - sleep 3 + for _ in $(seq 1 240); do + grep -q '^connected:' "$listen_log" 2>/dev/null && break + kill -0 "$listener" 2>/dev/null || break + sleep 0.25 + done + sleep 1 if ! eval "$action_cmd" >"$STATE_DIR/action.log" 2>&1; then cat "$STATE_DIR/action.log" "$listen_log" fail "$what: the action failed" @@ -536,6 +559,12 @@ done log "TeamSpeak session (voelin-core ts_session) against both servers: link conformance subset, chat, refused moves, poke, voice, files" VOELIN_LIVE=1 cargo test --quiet -p voelin-core --lib ts_session::live_tests -- --test-threads=1 2>&1 | grep -E "test result|panicked|timed out" || fail "TeamSpeak session tests failed" +# The engine tests of one binary run side by side and share the TeamSpeak 6 +# server: ts6_banners sets the server's banners, which every other engine that +# connects meanwhile fetches, so crates/voelin-core/tests/live.rs lets it run +# alone (a lock the TS6 tests hold, ts6_banners exclusively). It used to fail +# on `disabled policy must prevent HTTP requests` in every run of this stage. +# Not run with --test-threads=1: that hid the problem, it did not remove it. log "engine (voelin-core) against both servers, media pipeline through TS6" VOELIN_LIVE=1 cargo test --quiet -p voelin-core --features media-desktop --test live --test stream_live --test media_live 2>&1 | grep -E "test result|panicked|timed out" || fail "engine tests failed"