README Source History Refs Reviews Compare Notes Search Review guide feat(http): body streams end with an explicit outcome; record and body channels bounded
18f87e35507f24e2cee5f70565ac260d6844cf7c
Oliver Jan Krylow <oliver@bugabinga.net > · 26 Sep 2026
unsigned
Browse files Compare with HEAD
Changed files (6) Diff layout Auto Unified Split
.system/specs/SMH-SPEC-SPEC0001-smith-specification/index.md Modified +4 / −3 text lines
103 103 Every exchange is bounded and observable:Every exchange is bounded and observable:105 105 - request bodies above 16 MiB are rejected before send,- request bodies above 16 MiB are rejected before send,106 - - response bodies stop at 64 MiB; the stream closes at the bound ,106 + - response bodies stop at 64 MiB,107 107 - the response head arrives within 120 s or the exchange fails,- the response head arrives within 120 s or the exchange fails,108 - - a gap of 300 s between body chunks ends the stream ,109 - - body chunks are delivered as they arrive, never buffered to completion,108 + - a gap of 300 s between body chunks ends the body ,109 + - body chunks are delivered as they arrive over a bounded channel , never buffered to completion,110 110 - cancellation is observed at each chunk boundary; no chunk read after cancellation is delivered,- cancellation is observed at each chunk boundary; no chunk read after cancellation is delivered,
111 + - every body ends with one explicit outcome: complete, truncated at the bound, cancelled, or failed; a consumer can never mistake a cut-off body for a complete one,111 112 - non-2xx statuses are delivered as responses, never as transport errors.- non-2xx statuses are delivered as responses, never as transport errors.113 114 ### Model capabilities ### Model capabilities smith-ai/src/transport.rs Modified +61 / −49 text lines
12 12 use crate ::openai::OpenAiDecoder;use crate ::openai::OpenAiDecoder;13 13 use futures::StreamExt;use futures::StreamExt;14 14 use smith::error::{ProviderFault, Result , SmithError};use smith::error::{ProviderFault, Result , SmithError};15 - use smith :: http :: { HttpExchange, HttpExecutorRef, HttpHeader, HttpMethod} ; 16 + HttpBodyEnd , HttpBodyItem , HttpExchange, HttpExecutorRef, HttpHeader, HttpMethod, 16 18 use smith::message::{ContentBlock, Role};use smith::message::{ContentBlock, Role};17 19 use smith::provider::{ProviderRequest, RecordSink, StreamFn};use smith::provider::{ProviderRequest, RecordSink, StreamFn};18 20 use smith::tool::CancelHandle;use smith::tool::CancelHandle;19 - use std::collections::VecDeque;
20 21 use std::sync::Arc;use std::sync::Arc;416 417 let response = endpoint.executor.execute (exchange, cancel.clone ())? ; let response = endpoint.executor.execute (exchange, cancel.clone ())? ;417 418 if ! (200 .. 300 ).contains (& response.head.status) { if ! (200 .. 300 ).contains (& response.head.status) {418 419 let mut body = Vec ::new(); let mut body = Vec ::new();419 - for chunk in response.chunks {420 - body.extend_from_slice (& chunk.bytes); 420 + for item in response.body {422 + HttpBodyItem :: Chunk ( chunk ) => body.extend_from_slice (& chunk.bytes), 423 + HttpBodyItem::End(_ ) => break ,422 426 let message = String ::from_utf8_lossy(& body).into_owned (); let message = String ::from_utf8_lossy(& body).into_owned ();423 427 spool_record ( spool_record (432 436 return Err (SmithError::Provider { return Err (SmithError::Provider {433 - fault: match response.head.status {434 - 429 => ProviderFault::RateLimit {435 - retry_after_ms: None ,437 - 401 | 403 => ProviderFault::Authentication { message },438 - 400 | 404 => ProviderFault::Invalid {442 - 503 => ProviderFault::Overloaded { message },443 - _ => ProviderFault::Transient { message },437 + fault: status_fault (response.head.status, message),447 440 let mut decoder = make_decoder (endpoint.kind); let mut decoder = make_decoder (endpoint.kind);448 441 let mut received: u64 = 0 ; let mut received: u64 = 0 ;449 - let mut chunk_queue = VecDeque::new();442 + let outcome = |received: u64 , outcome: &str | {445 + "status" : response.head.status,446 + "response_bytes" : received,451 451 if cancel.is_cancelled () { if cancel.is_cancelled () {456 - "status" : response.head.status,457 - "response_bytes" : received,458 - "outcome" : "cancelled" ,452 + spool_record (& endpoint.records, outcome (received, "cancelled" ));461 453 return Err (SmithError::Cancelled); return Err (SmithError::Cancelled);463 - if chunk_queue.is_empty () {464 - match response.chunks .recv () {466 - received += u64 ::try_from(chunk.bytes.len ()).unwrap_or (u64 ::MAX );467 - chunk_queue.push_back (chunk.bytes);455 + let error = match response.body .recv () {456 + Ok (HttpBodyItem::Chunk(chunk)) => {457 + received += u64 ::try_from(chunk.bytes.len ()).unwrap_or (u64 ::MAX );458 + for event in decoder.push (& chunk.bytes)? {459 + if sender.send (Ok (event)).is_err () {472 - if let Some (bytes) = chunk_queue.pop_front () {473 - for event in decoder.push (& bytes)? {474 - if sender.send (Ok (event)).is_err () {465 + Ok (HttpBodyItem::End(HttpBodyEnd::Complete)) => break ,466 + Ok (HttpBodyItem::End(HttpBodyEnd::Cancelled)) => SmithError::Cancelled,467 + Ok (HttpBodyItem::End(HttpBodyEnd::Truncated { limit })) => SmithError::Provider {468 + fault: ProviderFault::Transient {469 + message: format! ("response body exceeded {limit} bytes" ),472 + Ok (HttpBodyItem::End(HttpBodyEnd::Failed { message })) => SmithError::Provider {473 + fault: ProviderFault::Transient { message },475 + Err (_ ) => SmithError::Provider {476 + fault: ProviderFault::Transient {477 + message: "body channel closed without an end" .to_string (),481 + spool_record (& endpoint.records, outcome (received, "failed" ));480 484 for event in decoder.finish ()? { for event in decoder.finish ()? {481 485 if sender.send (Ok (event)).is_err () { if sender.send (Ok (event)).is_err () {482 486 return Ok (()); return Ok (());489 - "status" : response.head.status,490 - "response_bytes" : received,491 - "outcome" : "completed" ,489 + spool_record (& endpoint.records, outcome (received, "completed" ));
494 + fn status_fault (status: u16 , message: String) -> ProviderFault {496 + 429 => ProviderFault::RateLimit {497 + retry_after_ms: None ,499 + 401 | 403 => ProviderFault::Authentication { message },500 + 400 | 404 => ProviderFault::Invalid {504 + 503 => ProviderFault::Overloaded { message },505 + _ => ProviderFault::Transient { message },497 509 #[cfg(test)]#[cfg(test)]498 510 mod tests {mod tests {499 511 use super ::* ; use super ::* ;smith-harness/src/http.rs Modified +31 / −12 text lines
6 6 use smith::error::{ProviderFault, Result , SmithError};use smith::error::{ProviderFault, Result , SmithError};7 - use smith :: http :: { HttpChunk, HttpExchange, HttpExecutor, HttpExecutorRef, HttpHead, HttpResponse } ; 8 + HttpBodyEnd , HttpBodyItem , HttpChunk, HttpExchange, HttpExecutor, HttpExecutorRef, HttpHead,8 11 use smith::tool::CancelHandle;use smith::tool::CancelHandle;9 12 use std::io::Read;use std::io::Read;10 13 use std::sync::Arc;use std::sync::Arc;171 + const BODY_CHANNEL_CHUNKS : usize = 16 ;172 180 fn stream_body (fn stream_body (173 181 head: HttpHead, head: HttpHead,174 182 mut body: impl Read + Send + 'static , mut body: impl Read + Send + 'static ,175 183 cancel: CancelHandle, cancel: CancelHandle,176 184 ) -> HttpResponse {) -> HttpResponse {177 - let (sender, receiver) = mpsc::channel();185 + let (sender, receiver) = mpsc::sync_channel(BODY_CHANNEL_CHUNKS );178 186 std::thread::spawn(move || { std::thread::spawn(move || {179 187 let mut buffer = [0 u8 ; 16 * 1024 ]; let mut buffer = [0 u8 ; 16 * 1024 ];180 188 let mut total: u64 = 0 ; let mut total: u64 = 0 ;182 190 let read = match body.read (&mut buffer) { let read = match body.read (&mut buffer) {183 - Ok (0 ) | Err (_ ) => return ,191 + Ok (0 ) => break HttpBodyEnd::Complete,193 + break HttpBodyEnd::Failed {194 + message: error.to_string (),184 197 Ok (read) => read, Ok (read) => read,
199 + if cancel.is_cancelled () {200 + break HttpBodyEnd::Cancelled;186 202 total = total.saturating_add (u64 ::try_from(read).unwrap_or (u64 ::MAX )); total = total.saturating_add (u64 ::try_from(read).unwrap_or (u64 ::MAX ));187 - if cancel . is_cancelled ( ) || total > MAX_BODY_BYTES {203 + if total > MAX_BODY_BYTES {204 + break HttpBodyEnd::Truncated {205 + limit: MAX_BODY_BYTES ,190 208 let chunk = HttpChunk { let chunk = HttpChunk {191 209 bytes: buffer[.. read].to_vec (), bytes: buffer[.. read].to_vec (),193 - if sender.send (chunk).is_err () {211 + if sender.send (HttpBodyItem :: Chunk ( chunk)) .is_err () {215 + let _ = sender.send (HttpBodyItem::End(end));198 217 HttpResponse { HttpResponse {smith-harness/tests/http_stream.rs Modified +48 / −17 text lines
4 - use smith :: http :: { HttpExchange, HttpExecutor, HttpMethod, HttpResponse} ; 5 + HttpBodyEnd , HttpBodyItem , HttpExchange, HttpExecutor, HttpMethod, HttpResponse, 5 7 use smith::tool::CancelHandle;use smith::tool::CancelHandle;6 8 use smith_harness::http::{MAX_BODY_BYTES , UreqHttpExecutor};use smith_harness::http::{MAX_BODY_BYTES , UreqHttpExecutor};7 9 use std::io::{Read, Write};use std::io::{Read, Write};44 46 let _ = socket.write_all (b "0\r\n\r\n" ); let _ = socket.write_all (b "0\r\n\r\n" );
51 + response: HttpResponse,53 + ) -> (Vec <(Duration, Vec <u8 >)>, Option <HttpBodyEnd>) {54 + let mut chunks = Vec ::new();55 + for item in response.body {57 + HttpBodyItem::Chunk(chunk) => chunks.push ((start.elapsed (), chunk.bytes)),58 + HttpBodyItem::End(end) => return (chunks, Some (end)),47 64 fn post (executor: & dyn HttpExecutor, port: u16 , cancel: CancelHandle) -> HttpResponse {fn post (executor: & dyn HttpExecutor, port: u16 , cancel: CancelHandle) -> HttpResponse {48 65 let exchange = HttpExchange { let exchange = HttpExchange {49 66 method: HttpMethod::Post, method: HttpMethod::Post,61 78 let start = Instant::now(); let start = Instant::now();62 79 let response = post (& executor, port, CancelHandle::new()); let response = post (& executor, port, CancelHandle::new());63 80 assert_eq! (response.head.status, 200 ); assert_eq! (response.head.status, 200 );64 - let arrivals: Vec <(Duration, Vec <u8 >)> = response67 - .map (|chunk| (start.elapsed (), chunk.bytes))81 + let (arrivals, end) = drain (response, start);82 + assert_eq! (end, Some (HttpBodyEnd::Complete));69 83 let body: Vec <u8 > = arrivals.iter ().flat_map (|(_, b)| b.clone ()).collect (); let body: Vec <u8 > = arrivals.iter ().flat_map (|(_, b)| b.clone ()).collect ();70 84 assert_eq! (body, EVENTS .concat ().as_bytes ()); assert_eq! (body, EVENTS .concat ().as_bytes ());71 85 let first = arrivals.first ().unwrap ().0 ; let first = arrivals.first ().unwrap ().0 ;83 97 let port = spawn_server (serve_events); let port = spawn_server (serve_events);84 98 let cancel = CancelHandle::new(); let cancel = CancelHandle::new();85 99 let response = post (& executor, port, cancel.clone ()); let response = post (& executor, port, cancel.clone ());86 - let first = response.chunks .recv ().unwrap ();87 - assert_eq! ( first . bytes, EVENTS [0 ].as_bytes ()); 100 + let first = response.body .recv ().unwrap ();103 + HttpBodyItem::Chunk(smith::http::HttpChunk {104 + bytes: EVENTS [0 ].as_bytes (). to_vec ( )88 107 cancel.cancel (); cancel.cancel ();89 108 let cancelled_at = Instant::now(); let cancelled_at = Instant::now();92 - let next = response.chunks .recv_timeout (EVENT_GAP * 2 );111 + let next = response.body .recv_timeout (EVENT_GAP * 2 );93 112 let stopped = cancelled_at.elapsed (); let stopped = cancelled_at.elapsed ();94 - assert_eq! ( next , Err (RecvTimeoutError::Disconnected)) ; 113 + assert_eq! (next, Ok (HttpBodyItem::End(HttpBodyEnd::Cancelled)));115 + response.body.recv_timeout (EVENT_GAP ),116 + Err (RecvTimeoutError::Disconnected)95 118 assert! (stopped < EVENT_GAP * 3 / 2 , "stopped after {stopped:?}" ); assert! (stopped < EVENT_GAP * 3 / 2 , "stopped after {stopped:?}" );111 134 let response = post (& executor, port, CancelHandle::new()); let response = post (& executor, port, CancelHandle::new());112 - let received: u64 = response115 - .map (|chunk| chunk.bytes.len () as u64 )135 + let (chunks, end) = drain (response, Instant::now());136 + let received: u64 = chunks.iter ().map (|(_, b)| b.len () as u64 ).sum ();139 + Some (HttpBodyEnd::Truncated {140 + limit: MAX_BODY_BYTES 117 143 assert! (received <= MAX_BODY_BYTES , "received {received}" ); assert! (received <= MAX_BODY_BYTES , "received {received}" );118 144 assert! (received > MAX_BODY_BYTES - 64 * 1024 , "received {received}" ); assert! (received > MAX_BODY_BYTES - 64 * 1024 , "received {received}" );135 161 let start = Instant::now(); let start = Instant::now();136 162 let response = post (& executor, port, CancelHandle::new()); let response = post (& executor, port, CancelHandle::new());137 - let body: Vec <u8 > = response . chunks.iter ().flat_map (|c | c . bytes ).collect ();163 + let (chunks, end) = drain (response, start);164 + let body: Vec <u8 > = chunks.into_iter ().flat_map (|( _ , b ) | b ).collect ();138 165 let ended = start.elapsed (); let ended = start.elapsed ();139 166 assert_eq! (body, b "okokokok" ); assert_eq! (body, b "okokokok" );
168 + matches! (end, Some (HttpBodyEnd::Failed { .. })),169 + "stalled body ended with {end:?}" 140 171 assert! (ended >= Duration::from_millis(600 ), "ended at {ended:?}" ); assert! (ended >= Duration::from_millis(600 ), "ended at {ended:?}" );141 172 assert! (ended < Duration::from_millis(1_000 ), "ended at {ended:?}" ); assert! (ended < Duration::from_millis(1_000 ), "ended at {ended:?}" );smith/src/http.rs Modified +35 / −4 text lines
63 63 pub bytes: Vec <u8 >, pub bytes: Vec <u8 >,67 + #[derive(Clone, Debug, PartialEq, Eq)]68 + pub enum HttpBodyEnd {86 + #[derive(Clone, Debug, PartialEq, Eq)]87 + pub enum HttpBodyItem {68 99 pub struct HttpResponse {pub struct HttpResponse {70 101 pub head: HttpHead, pub head: HttpHead,72 - pub chunks: Receiver<HttpChunk>,103 + pub body: Receiver<HttpBodyItem>,smith/src/provider.rs Modified +11 / −3 text lines
77 - pub type RecordSink = std::sync::mpsc::Sender <serde_json::Value>;77 + pub type RecordSink = std::sync::mpsc::SyncSender <serde_json::Value>;81 81 pub type RecordDrain = std::sync::mpsc::Receiver<serde_json::Value>;pub type RecordDrain = std::sync::mpsc::Receiver<serde_json::Value>;89 + pub const RECORD_CHANNEL_BOUND : usize = 64 ;84 92 #[must_use]#[must_use]85 93 pub fn record_channel () -> (RecordSink, RecordDrain) {pub fn record_channel () -> (RecordSink, RecordDrain) {86 - std::sync::mpsc::channel()94 + std::sync::mpsc::sync_channel(RECORD_CHANNEL_BOUND )