From 878f30bb019da073ee55b456049596ac67333df3 Mon Sep 17 00:00:00 2001 From: dec0iiyy <216844381+dec0iiyy@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:17:10 +0300 Subject: [PATCH 1/2] bench: pace the origin of a TUN download to model a slow link protocol-run takes origin_rate_kib_s and origin_burst_bytes for a TUN download. The origin then writes that many bytes at once, at that average rate, with TCP_NODELAY, so the engine's remote socket sees separate arrivals the way it does on a link slower than the engine. Unpaced runs are CPU-bound and hide what one arrival costs: the same download takes about ten times the engine CPU per GiB at 6 MiB/s in single segments. --- crates/xray-bench/src/protocol_bench.rs | 107 ++++++++++++++++- crates/xray-bench/src/stream_transport.rs | 140 ++++++++++++++++++++++ 2 files changed, 244 insertions(+), 3 deletions(-) diff --git a/crates/xray-bench/src/protocol_bench.rs b/crates/xray-bench/src/protocol_bench.rs index fc0372da9..b47ade95a 100644 --- a/crates/xray-bench/src/protocol_bench.rs +++ b/crates/xray-bench/src/protocol_bench.rs @@ -25,6 +25,14 @@ struct Request { client_preface: bool, #[serde(default)] client_env: std::collections::BTreeMap, + /// Average rate, in KiB/s, at which the origin of a TUN download writes. + /// Stands in for a link slower than the engine; absent means unpaced. + #[serde(default)] + origin_rate_kib_s: Option, + /// Bytes the paced origin writes at once: how many arrive together at + /// the engine's remote socket. Defaults to one 1448-byte segment. + #[serde(default)] + origin_burst_bytes: Option, } #[derive(Deserialize)] @@ -58,6 +66,17 @@ fn io_error(source: io::Error) -> BenchError { } } +/// One MSS of a 1500-byte IPv4 path with TCP timestamps. +const DEFAULT_ORIGIN_BURST_BYTES: usize = 1448; + +fn origin_pace(r: &Request) -> Option { + r.origin_rate_kib_s + .map(|rate| stream_transport::OriginPace { + bytes_per_second: u64::from(rate) * 1024, + burst_bytes: r.origin_burst_bytes.unwrap_or(DEFAULT_ORIGIN_BURST_BYTES), + }) +} + fn validate(r: &Request) -> Result<(), BenchError> { if !matches!(r.path.as_str(), "socks" | "tun") || !matches!( @@ -74,6 +93,13 @@ fn validate(r: &Request) -> Result<(), BenchError> { || (r.path == "tun" && (r.prepare_client || r.warmup)) || (r.client_preface && (r.path != "socks" || matches!(r.traffic.as_str(), "tcp-latency" | "udp"))) + || ((r.origin_rate_kib_s.is_some() || r.origin_burst_bytes.is_some()) + && (r.path != "tun" || r.traffic != "download")) + || (r.origin_burst_bytes.is_some() && r.origin_rate_kib_s.is_none()) + || r.origin_rate_kib_s + .is_some_and(|rate| !(1..=1024 * 1024).contains(&rate)) + || r.origin_burst_bytes + .is_some_and(|burst| !(1..=65536).contains(&burst)) { return Err(invalid("invalid bounded protocol benchmark request")); } @@ -242,7 +268,13 @@ pub async fn run(args: Vec) -> Result<(), BenchError> { run_tcp_freedom_workload_on(socks, &options, local_non_loopback_ipv4()?).await? } (Some(fd), traffic) => { - run_tun_bulk(fd.raw(), &options, StreamBenchTraffic::parse(traffic)?).await? + run_tun_bulk( + fd.raw(), + &options, + StreamBenchTraffic::parse(traffic)?, + origin_pace(&r), + ) + .await? } (None, traffic) => { stream_transport::run_workload_with_preface_on( @@ -309,6 +341,8 @@ pub async fn run(args: Vec) -> Result<(), BenchError> { "client_cpu_total_millis":samples.last().unwrap().cpu_millis, "engine_binary":prepared.binary,"engine_sha256":engine_sha256, "client_env":r.client_env, + "origin_rate_kib_s":r.origin_rate_kib_s, + "origin_burst_bytes":origin_pace(&r).map(|pace| pace.burst_bytes), "tun_fd_buffers":link_buffers, "latency_us":if matches!(r.traffic.as_str(), "udp" | "tcp-latency") {summarize_latency_us(outcome.latencies_us.clone())} else {None}, "ready_latency_us":if r.path=="tun" && !matches!(r.traffic.as_str(), "udp" | "tcp-latency") {summarize_latency_us(outcome.latencies_us)} else {None}, @@ -534,6 +568,7 @@ async fn run_tun_bulk( fd: RawFd, options: &BenchOptions, traffic: StreamBenchTraffic, + origin_pace: Option, ) -> Result { let listener = TcpListener::bind((local_non_loopback_ipv4()?, 0)) .await @@ -544,8 +579,28 @@ async fn run_tun_bulk( let iterations = options.iterations; let count = options.connections; let server = tokio::spawn(async move { - stream_transport::run_target_server(listener, traffic, server_template, iterations, count) - .await + match origin_pace { + Some(pace) => { + stream_transport::run_paced_download_server( + listener, + server_template, + iterations, + count, + pace, + ) + .await + } + None => { + stream_transport::run_target_server( + listener, + traffic, + server_template, + iterations, + count, + ) + .await + } + } }); // Abort the local fixture on error/timeout; its JoinSet cancels child flows. struct Abort(tokio::task::AbortHandle); @@ -748,6 +803,8 @@ mod tests { warmup: false, client_preface: false, client_env: Default::default(), + origin_rate_kib_s: None, + origin_burst_bytes: None, }; assert!(validate(&r).is_ok()); r.warmup = true; @@ -778,6 +835,50 @@ mod tests { assert!(validate(&r).is_err()); } + #[test] + fn origin_pace_is_bounded_and_only_for_tun_downloads() { + let mut r: Request = serde_json::from_value(json!({ + "binary":"engine", "config":{}, "path":"tun", "traffic":"download", + "connections":1, "iterations":1, "payload_size":1024, "output":"result", + "origin_rate_kib_s":6144 + })) + .unwrap(); + assert!(validate(&r).is_ok()); + let pace = origin_pace(&r).unwrap(); + assert_eq!(pace.bytes_per_second, 6144 * 1024); + assert_eq!(pace.burst_bytes, DEFAULT_ORIGIN_BURST_BYTES); + + r.origin_burst_bytes = Some(4 * 1448); + assert!(validate(&r).is_ok()); + assert_eq!(origin_pace(&r).unwrap().burst_bytes, 4 * 1448); + r.origin_burst_bytes = Some(0); + assert!(validate(&r).is_err()); + r.origin_burst_bytes = Some(65537); + assert!(validate(&r).is_err()); + r.origin_burst_bytes = None; + + r.origin_rate_kib_s = Some(0); + assert!(validate(&r).is_err()); + r.origin_rate_kib_s = Some(1024 * 1024 + 1); + assert!(validate(&r).is_err()); + r.origin_rate_kib_s = Some(6144); + + r.traffic = "upload".into(); + assert!(validate(&r).is_err()); + r.traffic = "download".into(); + r.path = "socks".into(); + assert!(validate(&r).is_err()); + r.path = "tun".into(); + + // A burst size without a rate paces nothing. + r.origin_rate_kib_s = None; + r.origin_burst_bytes = Some(1448); + assert!(validate(&r).is_err()); + r.origin_burst_bytes = None; + assert!(validate(&r).is_ok()); + assert!(origin_pace(&r).is_none()); + } + #[test] fn old_requests_keep_cold_direct_launch_defaults() { let r: Request = serde_json::from_value(json!({ diff --git a/crates/xray-bench/src/stream_transport.rs b/crates/xray-bench/src/stream_transport.rs index 60db72771..fbe5aaf42 100644 --- a/crates/xray-bench/src/stream_transport.rs +++ b/crates/xray-bench/src/stream_transport.rs @@ -629,6 +629,98 @@ pub(super) async fn run_target_server( .await } +/// How a download origin spaces its writes to stand in for a link slower +/// than the engine: `burst_bytes` at a time, `bytes_per_second` on average. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) struct OriginPace { + pub(super) bytes_per_second: u64, + pub(super) burst_bytes: usize, +} + +/// A download-only target whose flows write at `pace`. `TCP_NODELAY` keeps +/// every burst a separate arrival at the engine's remote socket. +pub(super) async fn run_paced_download_server( + listener: TcpListener, + template: Arc>, + iterations: usize, + connections: usize, + pace: OriginPace, +) -> Result<(), BenchError> { + let io_error = |action: &'static str| { + move |source| BenchError::Io { + action: action.to_owned(), + source, + } + }; + let mut workers = JoinSet::new(); + for _ in 0..connections { + let (mut stream, _) = listener + .accept() + .await + .map_err(io_error("accepting paced download connection"))?; + let template = Arc::clone(&template); + workers.spawn(async move { + stream + .set_nodelay(true) + .map_err(io_error("disabling Nagle on paced download"))?; + stream + .write_all(&[READY_BYTE]) + .await + .map_err(io_error("writing paced download ready marker"))?; + write_pattern_paced(&mut stream, &template, iterations, pace) + .await + .map_err(io_error("writing paced benchmark download")) + }); + } + while let Some(result) = workers.join_next().await { + result.map_err(|error| { + BenchError::InvalidArguments(format!("paced download flow failed: {error}")) + })??; + } + Ok(()) +} + +async fn write_pattern_paced( + writer: &mut W, + template: &[u8], + iterations: usize, + pace: OriginPace, +) -> std::io::Result<()> +where + W: AsyncWrite + Unpin, +{ + const TIMER_GRANULARITY: std::time::Duration = std::time::Duration::from_millis(1); + let total = template.len() * iterations; + let started = Instant::now(); + let mut sent = 0_usize; + while sent < total { + let offset = sent % template.len(); + let end = template + .len() + .min(offset + pace.burst_bytes) + .min(offset + total - sent); + writer.write_all(&template[offset..end]).await?; + sent += end - offset; + let due = started + + std::time::Duration::from_secs_f64(sent as f64 / pace.bytes_per_second as f64); + loop { + let left = due.saturating_duration_since(Instant::now()); + if left.is_zero() { + break; + } + // Tokio timers tick once a millisecond, and bursts of a few + // megabytes per second are closer together than that: sleep + // through whole ticks and yield through the rest. + if left > 2 * TIMER_GRANULARITY { + tokio::time::sleep(left - TIMER_GRANULARITY).await; + } else { + tokio::task::yield_now().await; + } + } + } + Ok(()) +} + async fn run_target_server_with_preface( listener: TcpListener, traffic: StreamBenchTraffic, @@ -1543,6 +1635,54 @@ mod tests { .unwrap(); } + #[tokio::test] + async fn paced_download_keeps_the_rate_and_the_burst_size() { + let template = Arc::new((0..=255_u8).collect::>()); + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap(); + let addr = listener.local_addr().unwrap(); + // 4 KiB at 64 KiB/s in 256-byte bursts: 16 bursts over 62.5 ms. + let pace = OriginPace { + bytes_per_second: 64 * 1024, + burst_bytes: 256, + }; + let server = tokio::spawn(run_paced_download_server( + listener, + Arc::clone(&template), + 16, + 1, + pace, + )); + let mut client = TcpStream::connect(addr).await.unwrap(); + let started = Instant::now(); + let mut ready = [0]; + client.read_exact(&mut ready).await.unwrap(); + assert_eq!(ready[0], READY_BYTE); + + let mut received = Vec::new(); + let mut largest_read = 0; + let mut buffer = [0; 4096]; + while received.len() < 16 * template.len() { + let read = client.read(&mut buffer).await.unwrap(); + assert_ne!(read, 0, "paced download closed early"); + largest_read = largest_read.max(read); + received.extend_from_slice(&buffer[..read]); + } + let elapsed = started.elapsed(); + server.await.unwrap().unwrap(); + + assert!(received + .chunks(template.len()) + .all(|chunk| chunk == &template[..])); + // The last burst is due 15/16 of the way through the nominal time. + assert!( + elapsed >= std::time::Duration::from_millis(55), + "{elapsed:?}" + ); + assert!(elapsed < std::time::Duration::from_secs(2), "{elapsed:?}"); + // A reader that keeps up sees separate bursts, not one stream. + assert!(largest_read < received.len(), "{largest_read}"); + } + #[tokio::test] async fn packet_up_replays_one_acknowledged_payload_per_iteration() { let template = b"packet"; From 54d0a64734f8ddafd85268eb726b7188ff67bd05 Mon Sep 17 00:00:00 2001 From: dec0iiyy <216844381+dec0iiyy@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:21:41 +0300 Subject: [PATCH 2/2] perf(tun): read a trickling TCP download in batches on the battery profiles A TUN TCP download costs a chain of wake-ups per read of the remote: the bridge task reads the socket and hands the bytes to the stack, the stack writes them to the TUN descriptor, the host's ACKs come back. When the remote delivers one segment at a time, as on a link slower than the engine, the chain runs per segment: about 8 system calls and 2.8 context switches each, and ten times the CPU per GiB of a CPU-bound download. On LowMemory, Mobile and MobilePlus the read that follows a read below 8 KiB now waits 1 ms. It waits only in a one-way stream (no upload since the previous read) whose reads are at most 5 ms apart and that has run so for 25 ms, which keeps the wait a small share of the time the data took to arrive. Request/response exchanges, short responses and streams whose reads already carry several segments are read as before; Desktop and Throughput are unchanged. macOS, M4 Pro, Freedom, one flow, Mobile, engine CPU per GiB, medians of five runs: 16.3 s to 8.6 s at 6 MiB/s, 13.3 s to 4.2 s at 50 MiB/s and 7.2 s to 2.7 s at 200 MiB/s for single-segment arrivals; 7.0 s to 5.8 s at 6 MiB/s for four-segment arrivals. Throughput, the unpaced download, 1 MiB/s and 1 KiB / 64 KiB echo latency are unchanged; peak footprint is 0.5 MiB higher at 50 MiB/s. --- CHANGELOG.md | 19 +++ crates/xray-core-rs/src/tun.rs | 53 +++++- crates/xray-core-rs/src/tun_download.rs | 207 ++++++++++++++++++++++++ docs/architecture.md | 17 ++ docs/benchmarks.md | 17 ++ 5 files changed, 307 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 996ae9577..e1cf92b0f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,25 @@ long-term supported release series. ## Unreleased +- A TCP download through TUN that arrives one segment at a time no longer + pays the whole chain of wake-ups, from the remote socket to the TUN + descriptor, for every segment. On the `LowMemory`, `Mobile` and + `MobilePlus` profiles the read of a flow's remote that follows a read below + 8 KiB waits 1 ms, so that it takes several segments at once. It waits only + in a one-way stream (nothing uploaded since the previous read) whose reads + are at most 5 ms apart and that has run so for 25 ms: a request/response + exchange, a response that arrives within 25 ms and a stream whose reads + already carry several segments are read as before, and so is everything on + `Desktop` and `Throughput`. On macOS (M4 Pro, Freedom, one flow, `Mobile`, + medians of five runs) the engine's CPU per GiB falls from 16.3 s to 8.6 s + at 6 MiB/s, from 13.3 s to 4.2 s at 50 MiB/s and from 7.2 s to 2.7 s at + 200 MiB/s when the segments arrive singly, and from 7.0 s to 5.8 s at + 6 MiB/s when they arrive four at a time. Throughput is unchanged at every + rate, as are the unpaced download, a download at 1 MiB/s and the latency of + a 1 KiB and of a 64 KiB echo; the peak footprint is 0.5 MiB higher at + 50 MiB/s. Not measured on a device yet. `xray-bench protocol-run` takes + `origin_rate_kib_s` and `origin_burst_bytes` for a TUN download, which pace + its origin to stand in for a link slower than the engine. - The DNS resolver and the system SRV/TXT lookups refuse a name longer than 255 octets, the limit Xray-core's DNS client applies through Go's `dnsmessage`. A name was read for up to 32 labels and pointers, about 2 KB, diff --git a/crates/xray-core-rs/src/tun.rs b/crates/xray-core-rs/src/tun.rs index 26a2c6472..2e40c3b23 100644 --- a/crates/xray-core-rs/src/tun.rs +++ b/crates/xray-core-rs/src/tun.rs @@ -159,9 +159,13 @@ mod backpressure_tests; #[path = "tun_download.rs"] mod download; use download::{ - read_remote_batch, send_remote_data, DownloadDelivery, PendingDownload, RemoteReadEnd, + read_remote_batch_after, send_remote_data, DownloadCoalescePolicy, DownloadCoalescer, + DownloadDelivery, PendingDownload, RemoteReadEnd, MOBILE_DOWNLOAD_COALESCE_POLICY, }; +#[cfg(test)] +use download::read_remote_batch; + #[path = "tun_dns.rs"] mod dns_proxy; use dns_proxy::{DnsTcpAction, DnsUdpAction, TunDnsMode}; @@ -237,6 +241,9 @@ struct TcpUploadBridgePolicy { struct TunRuntimePolicy { flows: FlowBudgetPolicy, tcp_upload: TcpUploadBridgePolicy, + /// Set on the profiles of battery-powered hosts, where the CPU time of a + /// download that trickles in matters more than one millisecond. + tcp_download_coalesce: Option, } const MOBILE_FLOW_BUDGET_POLICY: FlowBudgetPolicy = FlowBudgetPolicy { @@ -340,26 +347,31 @@ const LOW_MEMORY_TCP_UPLOAD_BRIDGE_POLICY: TcpUploadBridgePolicy = TcpUploadBrid const MOBILE_TUN_RUNTIME_POLICY: TunRuntimePolicy = TunRuntimePolicy { flows: MOBILE_FLOW_BUDGET_POLICY, tcp_upload: MOBILE_TCP_UPLOAD_BRIDGE_POLICY, + tcp_download_coalesce: Some(MOBILE_DOWNLOAD_COALESCE_POLICY), }; const MOBILE_PLUS_TUN_RUNTIME_POLICY: TunRuntimePolicy = TunRuntimePolicy { flows: MOBILE_PLUS_FLOW_BUDGET_POLICY, tcp_upload: MOBILE_TCP_UPLOAD_BRIDGE_POLICY, + tcp_download_coalesce: Some(MOBILE_DOWNLOAD_COALESCE_POLICY), }; const DESKTOP_TUN_RUNTIME_POLICY: TunRuntimePolicy = TunRuntimePolicy { flows: DESKTOP_FLOW_BUDGET_POLICY, tcp_upload: DEFAULT_TCP_UPLOAD_BRIDGE_POLICY, + tcp_download_coalesce: None, }; const LOW_MEMORY_TUN_RUNTIME_POLICY: TunRuntimePolicy = TunRuntimePolicy { flows: LOW_MEMORY_FLOW_BUDGET_POLICY, tcp_upload: LOW_MEMORY_TCP_UPLOAD_BRIDGE_POLICY, + tcp_download_coalesce: Some(MOBILE_DOWNLOAD_COALESCE_POLICY), }; const THROUGHPUT_TUN_RUNTIME_POLICY: TunRuntimePolicy = TunRuntimePolicy { flows: THROUGHPUT_FLOW_BUDGET_POLICY, tcp_upload: DEFAULT_TCP_UPLOAD_BRIDGE_POLICY, + tcp_download_coalesce: None, }; #[cfg(any( @@ -4028,6 +4040,8 @@ where // loop consumes the task's cooperative budget before download can run. let idle_sleep = tokio::time::sleep(idle_timeout); tokio::pin!(idle_sleep); + let mut download_coalescer = + DownloadCoalescer::new(context.runtime_policy.tcp_download_coalesce); let termination = 'bridge: loop { let upload = async { @@ -4095,7 +4109,7 @@ where () = &mut idle_sleep => break 'bridge TcpBridgeTermination::Graceful, wrote = &mut upload, if upload_open => { match wrote { - Ok(true) => {}, + Ok(true) => download_coalescer.record_upload(), Ok(false) => { upload_open = false; // Packet-up transports may leave their independent @@ -4115,12 +4129,18 @@ where } idle_sleep.as_mut().reset(TokioInstant::now() + active_idle_timeout); } - (data, end) = read_remote_batch(remote_reader, TCP_DOWNLOAD_CHUNK_SIZE), if pending_download.is_none() => { + (data, end) = read_remote_batch_after( + remote_reader, + TCP_DOWNLOAD_CHUNK_SIZE, + download_coalescer.read_not_before(), + ), if pending_download.is_none() => { remote_read_end = end; let read = data.len(); if read == 0 { continue; } + let read_at = TokioInstant::now(); + download_coalescer.record_read(read_at, read); timing.record_first_byte(context.tun.as_ref(), target); context.tun.record_tcp_remote_read(read); traffic.record_downlink(read as u64); @@ -4129,9 +4149,7 @@ where operation_timeout, context.send_remote_data(handle, generation, data), ))); - idle_sleep - .as_mut() - .reset(TokioInstant::now() + active_idle_timeout); + idle_sleep.as_mut().reset(read_at + active_idle_timeout); } } } @@ -8254,6 +8272,29 @@ mod tests { } } + #[test] + fn only_battery_profiles_delay_reads_of_a_trickling_download() { + for (profile, delays) in [ + (TunRuntimeProfile::Mobile, true), + (TunRuntimeProfile::MobilePlus, true), + (TunRuntimeProfile::LowMemory, true), + (TunRuntimeProfile::Desktop, false), + (TunRuntimeProfile::Throughput, false), + ] { + let policy = tun_runtime_policy_for_options(TunRuntimeOptions::with_profile(profile)); + assert_eq!( + policy.tcp_download_coalesce, + delays.then_some(MOBILE_DOWNLOAD_COALESCE_POLICY), + "{profile:?}" + ); + } + // One delay must stay a small share of the time a stream has run, and + // delayed reads must still count as one stream. + let policy = MOBILE_DOWNLOAD_COALESCE_POLICY; + assert!(policy.delay * 20 <= policy.min_stream_age); + assert!(policy.delay * 2 < policy.max_read_gap); + } + #[test] fn flow_upload_reservations_free_the_flow_before_the_shared_budget() { let mut budget = test_flow_budget(256); diff --git a/crates/xray-core-rs/src/tun_download.rs b/crates/xray-core-rs/src/tun_download.rs index fbd54f737..daf727249 100644 --- a/crates/xray-core-rs/src/tun_download.rs +++ b/crates/xray-core-rs/src/tun_download.rs @@ -46,6 +46,103 @@ pub(super) async fn read_remote_batch( .await } +/// [`read_remote_batch`] that does not start before `not_before`. The wait +/// reads nothing, so dropping the future during it loses no data. +pub(super) async fn read_remote_batch_after( + reader: &mut R, + limit: usize, + not_before: Option, +) -> (Bytes, Option) { + if let Some(not_before) = not_before { + tokio::time::sleep_until(not_before).await; + } + read_remote_batch(reader, limit).await +} + +/// When a one-way download trickles in one segment at a time, every segment +/// costs the whole chain of wake-ups from the remote socket to the TUN +/// descriptor, and that chain, not the bytes, is what the CPU time goes to. +/// After a small read of such a stream the next read waits for `delay`, so +/// that it takes several segments at once. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) struct DownloadCoalescePolicy { + /// How long the read after a small one waits. + pub(super) delay: Duration, + /// A read below this drained the socket; a larger one already carried + /// several segments and the next read follows at once. + pub(super) small_read_bytes: usize, + /// Reads further apart than this do not belong to one stream. + pub(super) max_read_gap: Duration, + /// How long a stream must have run before a read waits. It keeps `delay` + /// a small share of the stream's duration: a response that arrives in + /// less time than this is never delayed. + pub(super) min_stream_age: Duration, +} + +pub(super) const MOBILE_DOWNLOAD_COALESCE_POLICY: DownloadCoalescePolicy = DownloadCoalescePolicy { + delay: Duration::from_millis(1), + small_read_bytes: 8 * 1024, + max_read_gap: Duration::from_millis(5), + min_stream_age: Duration::from_millis(25), +}; + +/// Decides, read by read, whether the next read of one flow's remote waits. +/// A stream is a run of reads no further apart than `max_read_gap` with no +/// client upload between them: a request/response exchange uploads between +/// its reads and therefore never waits. +#[derive(Debug)] +pub(super) struct DownloadCoalescer { + policy: Option, + stream_started_at: Option, + last_read_at: Option, + upload_since_read: bool, + read_not_before: Option, +} + +impl DownloadCoalescer { + pub(super) fn new(policy: Option) -> Self { + Self { + policy, + stream_started_at: None, + last_read_at: None, + upload_since_read: false, + read_not_before: None, + } + } + + /// The client wrote to the remote: what the remote sends next answers + /// that write, so a wait already armed is dropped. + pub(super) fn record_upload(&mut self) { + self.upload_since_read = true; + self.read_not_before = None; + } + + pub(super) fn record_read(&mut self, now: TokioInstant, bytes: usize) { + let Some(policy) = self.policy else { + return; + }; + let continues = !self.upload_since_read + && self + .last_read_at + .is_some_and(|last| now.duration_since(last) <= policy.max_read_gap); + let started = match self.stream_started_at { + Some(started) if continues => started, + _ => now, + }; + self.stream_started_at = Some(started); + self.last_read_at = Some(now); + self.upload_since_read = false; + self.read_not_before = (bytes < policy.small_read_bytes + && now.duration_since(started) >= policy.min_stream_age) + .then(|| now + policy.delay); + } + + /// The instant the next read may start, if it has to wait. + pub(super) fn read_not_before(&self) -> Option { + self.read_not_before + } +} + #[derive(Debug)] pub(super) struct DownloadDelivery { accepted: tokio::sync::oneshot::Sender<()>, @@ -116,3 +213,113 @@ pub(super) async fn send_remote_data( pub(super) type PendingDownload<'a> = std::pin::Pin>> + Send + 'a>>; + +#[cfg(test)] +mod tests { + use super::*; + + const POLICY: DownloadCoalescePolicy = MOBILE_DOWNLOAD_COALESCE_POLICY; + const SEGMENT: usize = 1448; + + fn ms(millis: u64) -> Duration { + Duration::from_millis(millis) + } + + /// One segment per millisecond from `start` until the stream is old + /// enough to wait; returns the instant of the last read. + fn trickle_until_waiting( + coalescer: &mut DownloadCoalescer, + start: TokioInstant, + ) -> TokioInstant { + let mut at = start; + while at.duration_since(start) < POLICY.min_stream_age { + coalescer.record_read(at, SEGMENT); + assert_eq!(coalescer.read_not_before(), None); + at += ms(1); + } + coalescer.record_read(at, SEGMENT); + assert_eq!(coalescer.read_not_before(), Some(at + POLICY.delay)); + at + } + + #[test] + fn long_one_way_trickle_delays_the_next_read() { + let mut coalescer = DownloadCoalescer::new(Some(POLICY)); + let at = trickle_until_waiting(&mut coalescer, TokioInstant::now()); + + // The delayed reads keep the stream going, so it keeps waiting. + let next = at + POLICY.delay + ms(1); + coalescer.record_read(next, 4 * SEGMENT); + assert_eq!(coalescer.read_not_before(), Some(next + POLICY.delay)); + } + + #[test] + fn read_that_carried_several_segments_is_followed_at_once() { + let mut coalescer = DownloadCoalescer::new(Some(POLICY)); + let at = trickle_until_waiting(&mut coalescer, TokioInstant::now()); + + coalescer.record_read(at + ms(2), POLICY.small_read_bytes); + assert_eq!(coalescer.read_not_before(), None); + } + + #[test] + fn upload_drops_an_armed_wait_and_restarts_the_stream() { + let mut coalescer = DownloadCoalescer::new(Some(POLICY)); + let at = trickle_until_waiting(&mut coalescer, TokioInstant::now()); + + coalescer.record_upload(); + assert_eq!(coalescer.read_not_before(), None); + + // The answer to that upload starts a new stream, however soon it comes. + coalescer.record_read(at + ms(1), SEGMENT); + assert_eq!(coalescer.read_not_before(), None); + trickle_until_waiting(&mut coalescer, at + ms(1)); + } + + #[test] + fn pause_longer_than_the_gap_restarts_the_stream() { + let mut coalescer = DownloadCoalescer::new(Some(POLICY)); + let at = trickle_until_waiting(&mut coalescer, TokioInstant::now()); + + let resumed = at + POLICY.max_read_gap + ms(1); + coalescer.record_read(resumed, SEGMENT); + assert_eq!(coalescer.read_not_before(), None); + trickle_until_waiting(&mut coalescer, resumed); + } + + #[test] + fn without_a_policy_no_read_waits() { + let mut coalescer = DownloadCoalescer::new(None); + let start = TokioInstant::now(); + for millis in 0..100 { + coalescer.record_read(start + ms(millis), SEGMENT); + assert_eq!(coalescer.read_not_before(), None); + } + } + + #[tokio::test(start_paused = true)] + async fn delayed_read_waits_for_its_instant_and_loses_nothing_when_dropped() { + let (mut remote, mut local) = tokio::io::duplex(64); + remote.write_all(b"abc").await.unwrap(); + + // Dropped during the wait: the bytes stay in the reader. + let far = TokioInstant::now() + Duration::from_secs(60); + assert!(read_remote_batch_after(&mut local, 16, Some(far)) + .now_or_never() + .is_none()); + + let started = TokioInstant::now(); + let (data, end) = read_remote_batch_after(&mut local, 16, Some(started + ms(1))).await; + assert_eq!(started.elapsed(), ms(1)); + assert_eq!(&data[..], b"abc"); + assert_eq!(end, None); + + let (data, end) = { + remote.write_all(b"d").await.unwrap(); + read_remote_batch_after(&mut local, 16, None).await + }; + assert_eq!(started.elapsed(), ms(1)); + assert_eq!(&data[..], b"d"); + assert_eq!(end, None); + } +} diff --git a/docs/architecture.md b/docs/architecture.md index 60429f21c..c013b2ddb 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -174,6 +174,23 @@ shared limit plus 8 KiB per flow (8 MiB on `Mobile` at a 1500-byte MTU). A datagram over a limit is dropped, as one that finds its queue full, and counted in `udp_channel_dropped_packets`; the flow stays up. +A TCP download costs the CPU a chain of wake-ups for every read of the remote: +the bridge task reads the socket and hands the bytes to the stack, the stack +writes them to the TUN descriptor, and the host's acknowledgements come back +through it. When the remote delivers one segment at a time, a link slower than +the engine being the usual reason, that chain runs for every segment, and the +same download takes several times the CPU it takes when segments arrive +together. On the `LowMemory`, `Mobile` and `MobilePlus` profiles the bridge +therefore lets such a stream collect: after a read below 8 KiB, the next read +of that flow's remote waits 1 ms. It does so only when the stream is one-way +(nothing was uploaded since the previous read), its reads are at most 5 ms +apart, and it has run that way for 25 ms, which keeps the wait a small share of +the time the data took to arrive. A request/response exchange, a response that +arrives within 25 ms and a stream whose reads already carry several segments +are read as before; so is every flow on `Desktop` and `Throughput`. An +outbound over kernel TCP is acknowledged by the host's stack whenever the +bridge reads, so the wait does not slow the sender. + A TCP flow holds buffers only for what it carries. Its smoltcp socket starts with an 8 KiB receive buffer (two segments at least) and no send buffer, so a SYN that is never completed, a flow whose outbound is still connecting and a diff --git a/docs/benchmarks.md b/docs/benchmarks.md index 7dc7bdb00..a8a5e4e26 100644 --- a/docs/benchmarks.md +++ b/docs/benchmarks.md @@ -91,6 +91,23 @@ timer instead of 1 ms sleeps. Earlier TUN TCP echo latencies of about 2.7 ms were mostly driver wakeup delay, not client latency: one client measured a 2,719 µs median with the old driver and 75 µs with the new one. +An unpaced TUN download is CPU-bound: the origin writes as fast as the client +reads, every read carries many segments, and the result says what a byte +costs. What an arrival costs shows only when the link is slower than the +client. For a TUN download a `protocol-run` request may therefore set +`origin_rate_kib_s`, the average rate at which the origin writes, and +`origin_burst_bytes`, how much it writes at once (one 1448-byte segment when +absent); the origin sets `TCP_NODELAY`, so each burst is a separate arrival at +the client's remote socket. Both values are echoed in the result. Compare +engine CPU per GiB between such runs, not throughput, which the pace fixes: + +```json +{"binary": "target/release/xray-rust", "config": {"outbounds": [{"protocol": "freedom"}]}, + "path": "tun", "traffic": "download", "connections": 1, "iterations": 512, "payload_size": 65536, + "output": "out", "client_env": {"XRAY_TUN_PROFILE": "mobile"}, + "origin_rate_kib_s": 6144, "origin_burst_bytes": 1448} +``` + ```sh # Python >=3.11; Go 1.27.3 must be on PATH for reference identity verification. python3 scripts/run-migration-benchmarks.py \