From bc43602139a87df05559b97f1fad2123a07e3f84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 5 Sep 2026 09:11:29 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix:=20blob=20stream=20resets=20?= =?UTF-8?q?on=20write=20stall,=20client-stream=20routing=20without=20a=20V?= =?UTF-8?q?alue=20clone?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A blob body that makes no progress for AI_BLOB_WRITE_STALL_SECS is reset rather than parking the copy task and an open fd for the connection's life. Ref #27 --- README.md | 5 ++- src/ai/server.rs | 67 +++++++++++++++++++++++++++++------- src/constant.rs | 8 +++++ tests/ai_bridge.rs | 66 +++++++++++++++++++++++++++++++---- tests/limits_completeness.rs | 4 +++ 5 files changed, 130 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index 483e900..df194a4 100644 --- a/README.md +++ b/README.md @@ -3659,7 +3659,10 @@ is finished. Those bytes are *not* a frame: they carry no length prefix and the itself, so it is what will actually arrive rather than what a row remembers. On `err` nothing follows the frame at all. A read that breaks after its header resets the stream instead of finishing it, so a truncated file is never -mistaken for a complete one. +mistaken for a complete one. A body that makes no progress for 30 s — a +service that opened the stream and then stopped reading — is reset the same +way rather than finished; the clock is per write, not over the transfer, so a +slow-but-reading service is never cut off. | `code` | Meaning | | ------ | ------- | diff --git a/src/ai/server.rs b/src/ai/server.rs index 11d646c..9c06230 100644 --- a/src/ai/server.rs +++ b/src/ai/server.rs @@ -20,7 +20,8 @@ use crate::ai::protocol::{ use crate::ai::registry::{AiRegistry, WorkerSnapshot, clamp_concurrency}; use crate::ai::tls; use crate::constant::{ - AI_HANDSHAKE_TIMEOUT_SECS, AI_MAX_FRAME_BYTES, AI_PROTOCOL, REQUEST_TIMEOUT_SECS, + AI_BLOB_WRITE_STALL_SECS, AI_HANDSHAKE_TIMEOUT_SECS, AI_MAX_FRAME_BYTES, AI_PROTOCOL, + REQUEST_TIMEOUT_SECS, }; use crate::database::Database; use crate::domain::course::Course; @@ -350,24 +351,33 @@ async fn serve_client_stream( .and_then(Value::as_str) .unwrap_or_default() .to_string(); - let api_err = match serde_json::from_value::(raw.clone()) { - Ok(request) => { - let response = match read_api(&inner, request).await { + // Routed on the shape's required field rather than by parsing one and + // falling back to the other: that fallback cloned the whole `Value` on + // every api read. `path` still wins when a frame carries both. + if raw.get("path").is_some() { + let response = match serde_json::from_value::(raw) { + Ok(request) => match read_api(&inner, request).await { Ok(response) => response, Err((code, message)) => refusal(id, code, message), - }; - answer(&mut send, response).await; - return; + }, + Err(e) => refusal(id, "malformed", e.to_string()), + }; + answer(&mut send, response).await; + return; + } + if raw.get("file").is_some() { + match serde_json::from_value::(raw) { + Ok(request) => serve_blob(&inner, &mut send, request).await, + Err(e) => answer(&mut send, refusal(id, "malformed", e.to_string())).await, } - Err(e) => e, - }; - if let Ok(request) = serde_json::from_value::(raw) { - serve_blob(&inner, &mut send, request).await; return; } // Neither shape. Reported as the api-read refusal it has always been — // `path` is the field a frame this far off most likely meant to carry. - answer(&mut send, refusal(id, "malformed", api_err.to_string())).await; + let api_err = serde_json::from_value::(raw) + .err() + .map_or_else(String::new, |e| e.to_string()); + answer(&mut send, refusal(id, "malformed", api_err)).await; } /// Answer one blob read: the [`BlobResponse`] header frame, then — on `Ok` — @@ -382,7 +392,7 @@ async fn serve_blob(inner: &Inner, send: &mut quinn::SendStream, request: BlobRe Ok((header, mut file)) => { if let Err(e) = write_frame(send, &header).await { tracing::warn!("could not answer an AI service's blob read {id}: {e}"); - } else if let Err(e) = tokio::io::copy(&mut file, send).await { + } else if let Err(e) = write_blob_body(&mut file, send).await { // The header already promised `size` bytes, so a short body // would read as a silently truncated file. Reset instead: the // service sees a broken stream and can ask again. @@ -405,6 +415,37 @@ async fn serve_blob(inner: &Inner, send: &mut quinn::SendStream, request: BlobRe let _ = send.finish(); } +/// Copy the blob to the stream, one 64 KiB chunk at a time, giving each write +/// [`AI_BLOB_WRITE_STALL_SECS`] to make progress. +/// +/// The deadline is per write, not over the transfer: a service that reads +/// slowly keeps getting fresh time, while one that opens the stream and never +/// reads blocks on the QUIC stream window and is cut loose instead of parking +/// this task and the open file for the connection's life. +async fn write_blob_body( + file: &mut tokio::fs::File, + send: &mut quinn::SendStream, +) -> std::io::Result<()> { + let mut buf = [0u8; 64 * 1024]; + loop { + let n = tokio::io::AsyncReadExt::read(file, &mut buf).await?; + if n == 0 { + return Ok(()); + } + tokio::time::timeout( + Duration::from_secs(AI_BLOB_WRITE_STALL_SECS), + send.write_all(&buf[..n]), + ) + .await + .map_err(|_| { + std::io::Error::new( + std::io::ErrorKind::TimedOut, + format!("no progress for {AI_BLOB_WRITE_STALL_SECS}s"), + ) + })??; + } +} + /// Resolve, authorize and open one blob. `Err` is the refusal that becomes a /// [`BlobResponse::Err`] code. /// diff --git a/src/constant.rs b/src/constant.rs index f11a14f..22769b1 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -535,6 +535,14 @@ pub const AI_DEFAULT_CONCURRENT_PER_WORKER: usize = 8; pub const AI_IDLE_TIMEOUT_SECS: u64 = 30; pub const AI_KEEPALIVE_SECS: u64 = 10; +/// How long a blob body may make *no* progress before its stream is reset. +/// A STALL bound, not a transfer cap: the clock is per write, so a slow peer +/// that keeps reading streams a whole `max_file_bytes` file for as long as it +/// takes, while a service that opens a blob stream and never reads it stops +/// pinning a task and an open file descriptor once the QUIC stream window +/// fills. A wall-clock deadline on the transfer could not tell the two apart. +pub const AI_BLOB_WRITE_STALL_SECS: u64 = 30; + /// The capability an AI service declares to answer chatbot turns. The bridge /// routes a chat request to any worker carrying it; with none registered the /// chat endpoints report the service as unavailable. diff --git a/tests/ai_bridge.rs b/tests/ai_bridge.rs index 7c2c09a..db5493f 100644 --- a/tests/ai_bridge.rs +++ b/tests/ai_bridge.rs @@ -1958,13 +1958,14 @@ async fn a_course_note_file_download_stays_out_of_the_read_scope() { // route and then read the bytes back over real QUIC. use hezarfen_backend::ai::protocol::{BlobRequest, BlobResponse}; +use hezarfen_backend::constant::AI_BLOB_WRITE_STALL_SECS; -/// 200 KiB of deterministic pseudo-random bytes — well past one QUIC datagram, -/// so a passing read proves the copy really streamed rather than fitting in a -/// single write. -fn blob_bytes() -> Vec { +/// `len` bytes of deterministic pseudo-random data. The default 200 KiB is +/// well past one QUIC datagram, so a passing read proves the copy really +/// streamed rather than fitting in a single write. +fn blob_bytes(len: usize) -> Vec { let mut state = 0x2545_F491_4F6C_DD1Du64; - (0..200 * 1024) + (0..len) .map(|_| { state ^= state << 13; state ^= state >> 7; @@ -2018,7 +2019,7 @@ async fn a_service_streams_a_course_note_file_on_behalf_of_an_enrolled_student() let (service, student, note, _course, _foreign, app, _db, teacher) = course_notes_fixture(&bridge).await; - let uploaded = blob_bytes(); + let uploaded = blob_bytes(200 * 1024); let res = common::upload_file_at( &app, &teacher, @@ -2154,3 +2155,56 @@ async fn a_personal_notes_file_is_invisible_to_the_blob_stream() { ); } } + +#[tokio::test] +async fn a_body_nobody_reads_is_reset_rather_than_left_streaming_forever() { + // A service that opens a blob stream and then never reads it used to park + // the copy task and an open file descriptor for the connection's whole + // life: past the QUIC stream window nothing drains and the copy had no + // deadline. The bound is per write, so this is the only shape it cuts — a + // slow-but-reading service keeps earning fresh time. + // + // Spends ~AI_BLOB_WRITE_STALL_SECS of wall clock by construction: the + // stall itself is what is under test, so there is nothing to poll for. + let bridge = bridge().await; + let (service, student, note, _course, _foreign, app, _db, teacher) = + course_notes_fixture(&bridge).await; + + // Past quinn's default 1.25 MiB stream receive window and under the + // default `max_file_bytes` (5 MiB), so the server blocks mid-body. + let uploaded = blob_bytes(3 * 1024 * 1024); + let res = common::upload_file_at( + &app, + &teacher, + &format!("/course-notes/{note}/files"), + "big.pdf", + "application/pdf", + &uploaded, + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let file = common::id_of(&res.body); + + let (mut send, mut recv) = service.conn.open_bi().await.expect("blob stream"); + write_frame(&mut send, &blob_of(&file, Some(&student))) + .await + .expect("write BlobRequest"); + let _ = send.finish(); + let header: BlobResponse = read_frame(&mut recv).await.expect("read BlobResponse"); + assert!( + matches!(header, BlobResponse::Ok { .. }), + "the read was authorized: {}", + blob_refusal(header) + ); + + // Nothing is read off `recv` until well past the stall bound. + tokio::time::sleep(Duration::from_secs(AI_BLOB_WRITE_STALL_SECS + 3)).await; + let err = tokio::time::timeout(Duration::from_secs(5), recv.read_to_end(8 * 1024 * 1024)) + .await + .expect("the stream must already be resolved, not still parked") + .expect_err("a stalled body must never FIN"); + assert!( + matches!(err, quinn::ReadToEndError::Read(quinn::ReadError::Reset(_))), + "expected a reset, got {err:?}" + ); +} diff --git a/tests/limits_completeness.rs b/tests/limits_completeness.rs index 206d7dd..05bde63 100644 --- a/tests/limits_completeness.rs +++ b/tests/limits_completeness.rs @@ -101,6 +101,10 @@ const EXCLUDED: &[(&str, &str)] = &[ ), ("AI_IDLE_TIMEOUT_SECS", "QUIC connection idle timeout"), ("AI_KEEPALIVE_SECS", "QUIC connection keepalive"), + ( + "AI_BLOB_WRITE_STALL_SECS", + "how long a blob body may stall before its QUIC stream is reset", + ), ("AI_HANDSHAKE_TIMEOUT_SECS", "AI service handshake deadline"), ( "AI_API_ALLOWLIST",