Blob stream resets on write stall, client-stream routing without a Value clone
Browse files at this commitbc43602139a87df05559b97f1fad2123a07e3f84Parent: 6d3456a- fix
- blob stream resets on write stall, client-stream routing without a Value clone
5 changed files +130 -20
- README.md +4 -1
- src/ai/server.rs +54 -13
- src/constant.rs +8 -0
- tests/ai_bridge.rs +60 -6
- tests/limits_completeness.rs +4 -0
README.mdmodified+4 -1
| @@ -3659,7 +3659,10 @@ is finished. Those bytes are *not* a frame: they carry no length prefix and the | |||
| 3659 | itself, so it is what will actually arrive rather than what a row remembers. | 3659 | itself, so it is what will actually arrive rather than what a row remembers. |
| 3660 | On `err` nothing follows the frame at all. A read that breaks after its header | 3660 | On `err` nothing follows the frame at all. A read that breaks after its header |
| 3661 | resets the stream instead of finishing it, so a truncated file is never | 3661 | resets the stream instead of finishing it, so a truncated file is never |
| 3662 | -mistaken for a complete one. | 3662 | +mistaken for a complete one. A body that makes no progress for 30 s — a |
| 3663 | +service that opened the stream and then stopped reading — is reset the same | ||
| 3664 | +way rather than finished; the clock is per write, not over the transfer, so a | ||
| 3665 | +slow-but-reading service is never cut off. | ||
| 3663 | 3666 | ||
| 3664 | | `code` | Meaning | | 3667 | | `code` | Meaning | |
| 3665 | | ------ | ------- | | 3668 | | ------ | ------- | |
src/ai/server.rsmodified+54 -13
| @@ -20,7 +20,8 @@ use crate::ai::protocol::{ | |||
| 20 | use crate::ai::registry::{AiRegistry, WorkerSnapshot, clamp_concurrency}; | 20 | use crate::ai::registry::{AiRegistry, WorkerSnapshot, clamp_concurrency}; |
| 21 | use crate::ai::tls; | 21 | use crate::ai::tls; |
| 22 | use crate::constant::{ | 22 | use crate::constant::{ |
| 23 | - AI_HANDSHAKE_TIMEOUT_SECS, AI_MAX_FRAME_BYTES, AI_PROTOCOL, REQUEST_TIMEOUT_SECS, | 23 | + AI_BLOB_WRITE_STALL_SECS, AI_HANDSHAKE_TIMEOUT_SECS, AI_MAX_FRAME_BYTES, AI_PROTOCOL, |
| 24 | + REQUEST_TIMEOUT_SECS, | ||
| 24 | }; | 25 | }; |
| 25 | use crate::database::Database; | 26 | use crate::database::Database; |
| 26 | use crate::domain::course::Course; | 27 | use crate::domain::course::Course; |
| @@ -350,24 +351,33 @@ async fn serve_client_stream( | |||
| 350 | .and_then(Value::as_str) | 351 | .and_then(Value::as_str) |
| 351 | .unwrap_or_default() | 352 | .unwrap_or_default() |
| 352 | .to_string(); | 353 | .to_string(); |
| 353 | - let api_err = match serde_json::from_value::<ApiRequest>(raw.clone()) { | 354 | + // Routed on the shape's required field rather than by parsing one and |
| 354 | - Ok(request) => { | 355 | + // falling back to the other: that fallback cloned the whole `Value` on |
| 355 | - let response = match read_api(&inner, request).await { | 356 | + // every api read. `path` still wins when a frame carries both. |
| 357 | + if raw.get("path").is_some() { | ||
| 358 | + let response = match serde_json::from_value::<ApiRequest>(raw) { | ||
| 359 | + Ok(request) => match read_api(&inner, request).await { | ||
| 356 | Ok(response) => response, | 360 | Ok(response) => response, |
| 357 | Err((code, message)) => refusal(id, code, message), | 361 | Err((code, message)) => refusal(id, code, message), |
| 358 | - }; | 362 | + }, |
| 359 | - answer(&mut send, response).await; | 363 | + Err(e) => refusal(id, "malformed", e.to_string()), |
| 360 | - return; | 364 | + }; |
| 365 | + answer(&mut send, response).await; | ||
| 366 | + return; | ||
| 367 | + } | ||
| 368 | + if raw.get("file").is_some() { | ||
| 369 | + match serde_json::from_value::<BlobRequest>(raw) { | ||
| 370 | + Ok(request) => serve_blob(&inner, &mut send, request).await, | ||
| 371 | + Err(e) => answer(&mut send, refusal(id, "malformed", e.to_string())).await, | ||
| 361 | } | 372 | } |
| 362 | - Err(e) => e, | ||
| 363 | - }; | ||
| 364 | - if let Ok(request) = serde_json::from_value::<BlobRequest>(raw) { | ||
| 365 | - serve_blob(&inner, &mut send, request).await; | ||
| 366 | return; | 373 | return; |
| 367 | } | 374 | } |
| 368 | // Neither shape. Reported as the api-read refusal it has always been — | 375 | // Neither shape. Reported as the api-read refusal it has always been — |
| 369 | // `path` is the field a frame this far off most likely meant to carry. | 376 | // `path` is the field a frame this far off most likely meant to carry. |
| 370 | - answer(&mut send, refusal(id, "malformed", api_err.to_string())).await; | 377 | + let api_err = serde_json::from_value::<ApiRequest>(raw) |
| 378 | + .err() | ||
| 379 | + .map_or_else(String::new, |e| e.to_string()); | ||
| 380 | + answer(&mut send, refusal(id, "malformed", api_err)).await; | ||
| 371 | } | 381 | } |
| 372 | 382 | ||
| 373 | /// Answer one blob read: the [`BlobResponse`] header frame, then — on `Ok` — | 383 | /// 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 | |||
| 382 | Ok((header, mut file)) => { | 392 | Ok((header, mut file)) => { |
| 383 | if let Err(e) = write_frame(send, &header).await { | 393 | if let Err(e) = write_frame(send, &header).await { |
| 384 | tracing::warn!("could not answer an AI service's blob read {id}: {e}"); | 394 | tracing::warn!("could not answer an AI service's blob read {id}: {e}"); |
| 385 | - } else if let Err(e) = tokio::io::copy(&mut file, send).await { | 395 | + } else if let Err(e) = write_blob_body(&mut file, send).await { |
| 386 | // The header already promised `size` bytes, so a short body | 396 | // The header already promised `size` bytes, so a short body |
| 387 | // would read as a silently truncated file. Reset instead: the | 397 | // would read as a silently truncated file. Reset instead: the |
| 388 | // service sees a broken stream and can ask again. | 398 | // 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 | |||
| 405 | let _ = send.finish(); | 415 | let _ = send.finish(); |
| 406 | } | 416 | } |
| 407 | 417 | ||
| 418 | +/// Copy the blob to the stream, one 64 KiB chunk at a time, giving each write | ||
| 419 | +/// [`AI_BLOB_WRITE_STALL_SECS`] to make progress. | ||
| 420 | +/// | ||
| 421 | +/// The deadline is per write, not over the transfer: a service that reads | ||
| 422 | +/// slowly keeps getting fresh time, while one that opens the stream and never | ||
| 423 | +/// reads blocks on the QUIC stream window and is cut loose instead of parking | ||
| 424 | +/// this task and the open file for the connection's life. | ||
| 425 | +async fn write_blob_body( | ||
| 426 | + file: &mut tokio::fs::File, | ||
| 427 | + send: &mut quinn::SendStream, | ||
| 428 | +) -> std::io::Result<()> { | ||
| 429 | + let mut buf = [0u8; 64 * 1024]; | ||
| 430 | + loop { | ||
| 431 | + let n = tokio::io::AsyncReadExt::read(file, &mut buf).await?; | ||
| 432 | + if n == 0 { | ||
| 433 | + return Ok(()); | ||
| 434 | + } | ||
| 435 | + tokio::time::timeout( | ||
| 436 | + Duration::from_secs(AI_BLOB_WRITE_STALL_SECS), | ||
| 437 | + send.write_all(&buf[..n]), | ||
| 438 | + ) | ||
| 439 | + .await | ||
| 440 | + .map_err(|_| { | ||
| 441 | + std::io::Error::new( | ||
| 442 | + std::io::ErrorKind::TimedOut, | ||
| 443 | + format!("no progress for {AI_BLOB_WRITE_STALL_SECS}s"), | ||
| 444 | + ) | ||
| 445 | + })??; | ||
| 446 | + } | ||
| 447 | +} | ||
| 448 | + | ||
| 408 | /// Resolve, authorize and open one blob. `Err` is the refusal that becomes a | 449 | /// Resolve, authorize and open one blob. `Err` is the refusal that becomes a |
| 409 | /// [`BlobResponse::Err`] code. | 450 | /// [`BlobResponse::Err`] code. |
| 410 | /// | 451 | /// |
src/constant.rsmodified+8 -0
| @@ -535,6 +535,14 @@ pub const AI_DEFAULT_CONCURRENT_PER_WORKER: usize = 8; | |||
| 535 | pub const AI_IDLE_TIMEOUT_SECS: u64 = 30; | 535 | pub const AI_IDLE_TIMEOUT_SECS: u64 = 30; |
| 536 | pub const AI_KEEPALIVE_SECS: u64 = 10; | 536 | pub const AI_KEEPALIVE_SECS: u64 = 10; |
| 537 | 537 | ||
| 538 | +/// How long a blob body may make *no* progress before its stream is reset. | ||
| 539 | +/// A STALL bound, not a transfer cap: the clock is per write, so a slow peer | ||
| 540 | +/// that keeps reading streams a whole `max_file_bytes` file for as long as it | ||
| 541 | +/// takes, while a service that opens a blob stream and never reads it stops | ||
| 542 | +/// pinning a task and an open file descriptor once the QUIC stream window | ||
| 543 | +/// fills. A wall-clock deadline on the transfer could not tell the two apart. | ||
| 544 | +pub const AI_BLOB_WRITE_STALL_SECS: u64 = 30; | ||
| 545 | + | ||
| 538 | /// The capability an AI service declares to answer chatbot turns. The bridge | 546 | /// The capability an AI service declares to answer chatbot turns. The bridge |
| 539 | /// routes a chat request to any worker carrying it; with none registered the | 547 | /// routes a chat request to any worker carrying it; with none registered the |
| 540 | /// chat endpoints report the service as unavailable. | 548 | /// chat endpoints report the service as unavailable. |
tests/ai_bridge.rsmodified+60 -6
| @@ -1958,13 +1958,14 @@ async fn a_course_note_file_download_stays_out_of_the_read_scope() { | |||
| 1958 | // route and then read the bytes back over real QUIC. | 1958 | // route and then read the bytes back over real QUIC. |
| 1959 | 1959 | ||
| 1960 | use hezarfen_backend::ai::protocol::{BlobRequest, BlobResponse}; | 1960 | use hezarfen_backend::ai::protocol::{BlobRequest, BlobResponse}; |
| 1961 | +use hezarfen_backend::constant::AI_BLOB_WRITE_STALL_SECS; | ||
| 1961 | 1962 | ||
| 1962 | -/// 200 KiB of deterministic pseudo-random bytes — well past one QUIC datagram, | 1963 | +/// `len` bytes of deterministic pseudo-random data. The default 200 KiB is |
| 1963 | -/// so a passing read proves the copy really streamed rather than fitting in a | 1964 | +/// well past one QUIC datagram, so a passing read proves the copy really |
| 1964 | -/// single write. | 1965 | +/// streamed rather than fitting in a single write. |
| 1965 | -fn blob_bytes() -> Vec<u8> { | 1966 | +fn blob_bytes(len: usize) -> Vec<u8> { |
| 1966 | let mut state = 0x2545_F491_4F6C_DD1Du64; | 1967 | let mut state = 0x2545_F491_4F6C_DD1Du64; |
| 1967 | - (0..200 * 1024) | 1968 | + (0..len) |
| 1968 | .map(|_| { | 1969 | .map(|_| { |
| 1969 | state ^= state << 13; | 1970 | state ^= state << 13; |
| 1970 | state ^= state >> 7; | 1971 | state ^= state >> 7; |
| @@ -2018,7 +2019,7 @@ async fn a_service_streams_a_course_note_file_on_behalf_of_an_enrolled_student() | |||
| 2018 | let (service, student, note, _course, _foreign, app, _db, teacher) = | 2019 | let (service, student, note, _course, _foreign, app, _db, teacher) = |
| 2019 | course_notes_fixture(&bridge).await; | 2020 | course_notes_fixture(&bridge).await; |
| 2020 | 2021 | ||
| 2021 | - let uploaded = blob_bytes(); | 2022 | + let uploaded = blob_bytes(200 * 1024); |
| 2022 | let res = common::upload_file_at( | 2023 | let res = common::upload_file_at( |
| 2023 | &app, | 2024 | &app, |
| 2024 | &teacher, | 2025 | &teacher, |
| @@ -2154,3 +2155,56 @@ async fn a_personal_notes_file_is_invisible_to_the_blob_stream() { | |||
| 2154 | ); | 2155 | ); |
| 2155 | } | 2156 | } |
| 2156 | } | 2157 | } |
| 2158 | + | ||
| 2159 | +#[tokio::test] | ||
| 2160 | +async fn a_body_nobody_reads_is_reset_rather_than_left_streaming_forever() { | ||
| 2161 | + // A service that opens a blob stream and then never reads it used to park | ||
| 2162 | + // the copy task and an open file descriptor for the connection's whole | ||
| 2163 | + // life: past the QUIC stream window nothing drains and the copy had no | ||
| 2164 | + // deadline. The bound is per write, so this is the only shape it cuts — a | ||
| 2165 | + // slow-but-reading service keeps earning fresh time. | ||
| 2166 | + // | ||
| 2167 | + // Spends ~AI_BLOB_WRITE_STALL_SECS of wall clock by construction: the | ||
| 2168 | + // stall itself is what is under test, so there is nothing to poll for. | ||
| 2169 | + let bridge = bridge().await; | ||
| 2170 | + let (service, student, note, _course, _foreign, app, _db, teacher) = | ||
| 2171 | + course_notes_fixture(&bridge).await; | ||
| 2172 | + | ||
| 2173 | + // Past quinn's default 1.25 MiB stream receive window and under the | ||
| 2174 | + // default `max_file_bytes` (5 MiB), so the server blocks mid-body. | ||
| 2175 | + let uploaded = blob_bytes(3 * 1024 * 1024); | ||
| 2176 | + let res = common::upload_file_at( | ||
| 2177 | + &app, | ||
| 2178 | + &teacher, | ||
| 2179 | + &format!("/course-notes/{note}/files"), | ||
| 2180 | + "big.pdf", | ||
| 2181 | + "application/pdf", | ||
| 2182 | + &uploaded, | ||
| 2183 | + ) | ||
| 2184 | + .await; | ||
| 2185 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 2186 | + let file = common::id_of(&res.body); | ||
| 2187 | + | ||
| 2188 | + let (mut send, mut recv) = service.conn.open_bi().await.expect("blob stream"); | ||
| 2189 | + write_frame(&mut send, &blob_of(&file, Some(&student))) | ||
| 2190 | + .await | ||
| 2191 | + .expect("write BlobRequest"); | ||
| 2192 | + let _ = send.finish(); | ||
| 2193 | + let header: BlobResponse = read_frame(&mut recv).await.expect("read BlobResponse"); | ||
| 2194 | + assert!( | ||
| 2195 | + matches!(header, BlobResponse::Ok { .. }), | ||
| 2196 | + "the read was authorized: {}", | ||
| 2197 | + blob_refusal(header) | ||
| 2198 | + ); | ||
| 2199 | + | ||
| 2200 | + // Nothing is read off `recv` until well past the stall bound. | ||
| 2201 | + tokio::time::sleep(Duration::from_secs(AI_BLOB_WRITE_STALL_SECS + 3)).await; | ||
| 2202 | + let err = tokio::time::timeout(Duration::from_secs(5), recv.read_to_end(8 * 1024 * 1024)) | ||
| 2203 | + .await | ||
| 2204 | + .expect("the stream must already be resolved, not still parked") | ||
| 2205 | + .expect_err("a stalled body must never FIN"); | ||
| 2206 | + assert!( | ||
| 2207 | + matches!(err, quinn::ReadToEndError::Read(quinn::ReadError::Reset(_))), | ||
| 2208 | + "expected a reset, got {err:?}" | ||
| 2209 | + ); | ||
| 2210 | +} | ||
tests/limits_completeness.rsmodified+4 -0
| @@ -101,6 +101,10 @@ const EXCLUDED: &[(&str, &str)] = &[ | |||
| 101 | ), | 101 | ), |
| 102 | ("AI_IDLE_TIMEOUT_SECS", "QUIC connection idle timeout"), | 102 | ("AI_IDLE_TIMEOUT_SECS", "QUIC connection idle timeout"), |
| 103 | ("AI_KEEPALIVE_SECS", "QUIC connection keepalive"), | 103 | ("AI_KEEPALIVE_SECS", "QUIC connection keepalive"), |
| 104 | + ( | ||
| 105 | + "AI_BLOB_WRITE_STALL_SECS", | ||
| 106 | + "how long a blob body may stall before its QUIC stream is reset", | ||
| 107 | + ), | ||
| 104 | ("AI_HANDSHAKE_TIMEOUT_SECS", "AI service handshake deadline"), | 108 | ("AI_HANDSHAKE_TIMEOUT_SECS", "AI service handshake deadline"), |
| 105 | ( | 109 | ( |
| 106 | "AI_API_ALLOWLIST", | 110 | "AI_API_ALLOWLIST", |