test(runtime): coordinate races and allocate UDP independently

Use request barriers to select the updater provider instead of millisecond
sleep races. Allocate the integration test's UDP port through UDP rather than
assuming the OS accepts the separately allocated TCP port.

Refresh RTP baselines at the actual warm switch and compare modular progress.
Keep media reuse deadlines and add failing phase/cycle context. This improves
test causality without claiming the reported intermittent capture failure fixed.
This commit is contained in:
AAA committed 2026-11-24 12:06:34 -05:00
1 parent 98c2642b4a
commit 3713fc4cd8
5 files changed
+59 -35

No files matched your search

@@ -72,6 +72,8 @@ async fn shadow_flows_preserve_source_clock_and_warm_outputs() -> Result<()> {
.await
.context("two actual outgoing SRs for warm A/V")?;
let original_pc = f.driver.pairs[&sink].pc.clone();
let audio_at_switch = f.observed(&warm_audio.1, MediaKind::Audio).unwrap().2;
let video_at_switch = f.observed(&warm_video.1, MediaKind::Video).unwrap().2;
f.plans
.last_mut()
.unwrap()
@@ -90,12 +92,12 @@ async fn shadow_flows_preserve_source_clock_and_warm_outputs() -> Result<()> {
.await;
f.until(|f| {
f.observed(&warm_audio.1, MediaKind::Audio)
.is_some_and(|p| p.2.wrapping_sub(before_audio.2) > 9600)
.is_some_and(|p| (p.2.wrapping_sub(audio_at_switch) as i32) > 9600)
&& f.observed(&warm_video.1, MediaKind::Video)
.is_some_and(|p| p.2.wrapping_sub(before_video.2) > 18000)
.is_some_and(|p| (p.2.wrapping_sub(video_at_switch) as i32) > 18000)
})
.await
.context("selected candidate keeps emitting")?;
.context("selected candidate advances both RTP clocks after warm commit")?;
anyhow::ensure!(
f.output(warm_flow, MediaKind::Audio) == warm_audio
&& f.output(warm_flow, MediaKind::Video) == warm_video,
@@ -677,7 +677,8 @@ async fn repeated_media_leases_keep_sibling_av_and_use_fresh_rtp() -> Result<()>
})
})
})
.await?;
.await
.context("initial sibling and replaceable flows emit audio and video")?;
let sibling_audio = fixture.output(sibling, MediaKind::Audio);
let sibling_video = fixture.output(sibling, MediaKind::Video);
let stream = fixture.output(binding.id, MediaKind::Video).1;
@@ -693,7 +694,7 @@ async fn repeated_media_leases_keep_sibling_av_and_use_fresh_rtp() -> Result<()>
.lines()
.filter(|line| line.starts_with("m="))
.count();
for _ in 0..8 {
for cycle in 1..=8 {
fixture
.plans
.last_mut()
@@ -719,7 +720,8 @@ async fn repeated_media_leases_keep_sibling_av_and_use_fresh_rtp() -> Result<()>
}
Ok::<_, anyhow::Error>(())
})
.await??;
.await
.with_context(|| format!("cycle {cycle}: retired audio/video outputs become reusable"))??;
binding.id = Uuid::new_v4();
fixture.plans.last_mut().unwrap().outgoing.push(binding);
fixture
@@ -742,7 +744,8 @@ async fn repeated_media_leases_keep_sibling_av_and_use_fresh_rtp() -> Result<()>
&& f.observed(&stream, MediaKind::Video)
.is_some_and(|packet| packet.1 != previous_video.1)
})
.await?;
.await
.with_context(|| format!("cycle {cycle}: reused stream emits fresh audio/video SSRCs"))?;
previous_audio = fixture.observed(&stream, MediaKind::Audio).unwrap();
previous_video = fixture.observed(&stream, MediaKind::Video).unwrap();
ensure!(
@@ -424,6 +424,7 @@ async fn cancelled_driver_pair_retirement_keeps_real_child_joins() -> Result<()>
drop(retirement); // Driver's stop select cancels this exact work future.
assert!(driver.pairs.is_empty());
driver.retire_pair(id, crate::diagnostics::RetirementReason::PeerFailed).await;
log::warn!(target: "piik.rtc", "synthetic unrelated UDP warning");
let mut bytes = Vec::new();
crate::diagnostics::snapshot().unwrap().write_archive(&mut bytes, "test", "test", "test")?;
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes))?;
@@ -433,7 +434,9 @@ async fn cancelled_driver_pair_retirement_keeps_real_child_joins() -> Result<()>
let mut retirements = Vec::new();
for line in lines.lines() {
let record: serde_json::Value = serde_json::from_str(line)?;
if record["target"] != "piik.rtc" { continue; }
if record["target"] != "piik.rtc" || record["level"] != "INFO" {
continue;
}
let detail: serde_json::Value = serde_json::from_str(record["message"].as_str().unwrap())?;
if detail["pair"] == alias && detail["event"]["stage"] == "retirement_started" {
retirements.push(detail);
@@ -16,6 +16,7 @@ use ring::{
use std::{
fs,
io::Write,
ops::RangeInclusive,
sync::atomic::{AtomicUsize, Ordering},
time::Duration,
};
@@ -95,7 +96,8 @@ struct Provider {
signature: Vec<u8>,
body: Vec<u8>,
corrupt: bool,
delay: Duration,
blocked_requests: Option<RangeInclusive<usize>>,
first_requests: Option<Arc<tokio::sync::Barrier>>,
requests: Arc<AtomicUsize>,
disconnected: Arc<AtomicUsize>,
}
@@ -113,19 +115,30 @@ async fn provider_signature(AxumState(provider): AxumState<Provider>) -> Vec<u8>
provider.signature
}
async fn provider_body(AxumState(provider): AxumState<Provider>) -> Response {
provider.requests.fetch_add(1, Ordering::SeqCst);
let request = provider.requests.fetch_add(1, Ordering::SeqCst);
let lease = BodyLease(provider.disconnected);
// Both providers must start before either can win prefix selection.
if request == 0 {
if let Some(barrier) = provider.first_requests {
barrier.wait().await;
}
}
let blocked = provider
.blocked_requests
.is_some_and(|range| range.contains(&request));
let mut bytes = provider.body;
if provider.corrupt {
bytes[0] ^= 1;
}
let lease = BodyLease(provider.disconnected);
let stream = futures_util::stream::unfold(
(bytes, 0, lease),
move |(bytes, offset, lease)| async move {
if offset == bytes.len() {
return None;
}
tokio::time::sleep(provider.delay).await;
if blocked {
std::future::pending::<()>().await;
}
let end = (offset + 4096).min(bytes.len());
let chunk = Bytes::copy_from_slice(&bytes[offset..end]);
Some((Ok::<_, std::io::Error>(chunk), (bytes, end, lease)))
@@ -148,7 +161,10 @@ impl Drop for Fixture {
}
}
async fn fixture(delays: [Duration; 2], corrupt: [bool; 2]) -> Fixture {
async fn fixture(
blocked_requests: [Option<RangeInclusive<usize>>; 2],
corrupt: [bool; 2],
) -> Fixture {
let directory = tempfile::tempdir().unwrap();
let root = directory.path().join("app");
let data_root = directory.path().join("data");
@@ -179,12 +195,17 @@ async fn fixture(delays: [Duration; 2], corrupt: [bool; 2]) -> Fixture {
let index = serde_json::to_vec(&serde_json::json!({"schema":1,"version":"v3.0.1","revision":SOURCE,
"targets":{"windows-amd64":{"artifact":"piik-app-windows-amd64.zip","size":body.len(),"sha256":hash}}})).unwrap();
let signature = key.sign(&index).as_ref().to_vec();
let first_requests = blocked_requests
.iter()
.any(Option::is_some)
.then(|| Arc::new(tokio::sync::Barrier::new(2)));
let providers = [0, 1].map(|index_number| Provider {
index: index.clone(),
signature: signature.clone(),
body: body.clone(),
corrupt: corrupt[index_number],
delay: delays[index_number],
blocked_requests: blocked_requests[index_number].clone(),
first_requests: first_requests.clone(),
requests: Default::default(),
disconnected: Default::default(),
});
@@ -289,11 +310,8 @@ async fn wait_state(client: &reqwest::Client, origin: &str, expected: &str) -> s
#[tokio::test]
#[cfg(windows)]
async fn local_http_owns_signed_download_and_cancel_without_retiring_the_app() {
let fixture = fixture(
[Duration::from_millis(12), Duration::from_millis(1)],
[false, false],
)
.await;
// The first operation chooses AtomGit. Later responses stay open for cancel and shutdown.
let fixture = fixture([Some(0..=usize::MAX), Some(1..=usize::MAX)], [false; 2]).await;
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let origin = format!("http://{}", listener.local_addr().unwrap());
let (stop, stopped) = oneshot::channel();
@@ -433,7 +451,7 @@ async fn local_http_owns_signed_download_and_cancel_without_retiring_the_app() {
#[tokio::test]
#[cfg(windows)]
async fn failed_optional_download_keeps_app_running_and_can_be_dismissed() {
let fixture = fixture([Duration::ZERO; 2], [true; 2]).await;
let fixture = fixture([None, None], [true; 2]).await;
let (closing, observer) = watch::channel(false);
let owner = Owner::new(&fixture.config, closing.clone());
let download = || Request::Download {
@@ -470,11 +488,7 @@ async fn failed_optional_download_keeps_app_running_and_can_be_dismissed() {
#[tokio::test]
async fn corrupted_winner_uses_only_one_fallback_and_never_accepts_bad_signatures() {
let fixture = fixture(
[Duration::from_millis(1), Duration::from_millis(12)],
[true, false],
)
.await;
let fixture = fixture([None, Some(0..=0)], [true, false]).await;
let Config::Enabled(options) = &fixture.config.update else {
unreachable!()
};
@@ -510,8 +524,11 @@ async fn corrupted_winner_uses_only_one_fallback_and_never_accepts_bad_signature
.await
.is_err());
assert_eq!(
fixture.providers[0].requests.load(Ordering::SeqCst),
1,
fixture
.providers
.each_ref()
.map(|provider| provider.requests.load(Ordering::SeqCst)),
[1, 2],
"Invalid signatures never start package downloads"
);
}
@@ -550,11 +567,7 @@ fn complete_bundle_extraction_rejects_traversal() {
#[cfg(windows)]
#[tokio::test]
async fn local_archive_write_error_does_not_retry_the_mirror() {
let fixture = fixture(
[Duration::from_millis(1), Duration::from_millis(12)],
[false; 2],
)
.await;
let fixture = fixture([None, Some(0..=0)], [false; 2]).await;
let Config::Enabled(options) = &fixture.config.update else {
unreachable!()
};
@@ -595,7 +608,7 @@ async fn local_archive_write_error_does_not_retry_the_mirror() {
#[tokio::test]
#[cfg(windows)]
async fn unmanaged_directories_and_data_inside_the_bundle_stay_manual() {
let mut fixture = fixture([Duration::ZERO; 2], [false; 2]).await;
let mut fixture = fixture([None, None], [false; 2]).await;
let closing = watch::channel(false).0;
fs::write(fixture.config.assets.join("personal.txt"), b"user content").unwrap();
assert_eq!(
@@ -2,7 +2,7 @@ use futures_util::{SinkExt, StreamExt};
use piik_channel_core::{conversation::SessionSigner, wire::CHANNEL_PROTOCOL};
use piik_channel_prototype::domain::Domain;
use serde_json::{json, Value};
use std::{path::Path, process::Stdio, time::Duration};
use std::{net::UdpSocket, path::Path, process::Stdio, time::Duration};
use tokio::{
io::{AsyncBufReadExt, BufReader},
net::TcpStream,
@@ -34,7 +34,6 @@ fn server(data: &Path, frontend: &Path) -> Command {
.env("PIIK_CHANNEL_SERVICE_TRANSIT", "false")
.env("PIIK_CHANNEL_DATA_DIR", data)
.env("PIIK_CHANNEL_WEB_DIR", frontend)
.env_remove("PIIK_CHANNEL_UDP_PORT")
.env_remove("PIIK_CHANNEL_UDP_PUBLIC_ADDRESS")
.env_remove("PIIK_CHANNEL_INVITATION_ORIGIN")
.env_remove("PIIK_CHANNEL_WEB_ORIGIN")
@@ -45,6 +44,10 @@ fn server(data: &Path, frontend: &Path) -> Command {
}
async fn launch(mut command: Command) -> (Child, String) {
let udp = UdpSocket::bind("127.0.0.1:0").expect("Allocate a test UDP port");
let udp_port = udp.local_addr().unwrap().port();
command.env("PIIK_CHANNEL_UDP_PORT", udp_port.to_string());
drop(udp);
let mut process = command.spawn().unwrap();
let mut lines = BufReader::new(process.stdout.take().unwrap()).lines();
let line = timeout(DEADLINE, async {