repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

feat(http): body streams end with an explicit outcome; record and body channels bounded

18f87e35507f24e2cee5f70565ac260d6844cf7c

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (6)

+190 / −88 text lines

Diff layout

.system/specs/SMH-SPEC-SPEC0001-smith-specification/index.md

Modified

+4 / −3 text lines

103103Every exchange is bounded and observable:
105105- 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,
107107- 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,
110110- 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,
111112- non-2xx statuses are delivered as responses, never as transport errors.
113114### Model capabilities

smith-ai/src/transport.rs

Modified

+61 / −49 text lines

1212use crate::openai::OpenAiDecoder;
1313use futures::StreamExt;
1414use smith::error::{ProviderFault, Result, SmithError};
15use smith::http::{HttpExchange, HttpExecutorRef, HttpHeader, HttpMethod};
15use smith::http::{
16 HttpBodyEnd, HttpBodyItem, HttpExchange, HttpExecutorRef, HttpHeader, HttpMethod,
17};
1618use smith::message::{ContentBlock, Role};
1719use smith::provider::{ProviderRequest, RecordSink, StreamFn};
1820use smith::tool::CancelHandle;
19use std::collections::VecDeque;
2021use std::sync::Arc;
2223/// Where provider effect records go until the agent drains them into the
416417 let response = endpoint.executor.execute(exchange, cancel.clone())?;
417418 if !(200..300).contains(&response.head.status) {
418419 let mut body = Vec::new();
419 for chunk in response.chunks {
420 body.extend_from_slice(&chunk.bytes);
420 for item in response.body {
421 match item {
422 HttpBodyItem::Chunk(chunk) => body.extend_from_slice(&chunk.bytes),
423 HttpBodyItem::End(_) => break,
424 }
421425 }
422426 let message = String::from_utf8_lossy(&body).into_owned();
423427 spool_record(
430434 }),
431435 );
432436 return Err(SmithError::Provider {
433 fault: match response.head.status {
434 429 => ProviderFault::RateLimit {
435 retry_after_ms: None,
436 },
437 401 | 403 => ProviderFault::Authentication { message },
438 400 | 404 => ProviderFault::Invalid {
439 field: None,
440 message,
441 },
442 503 => ProviderFault::Overloaded { message },
443 _ => ProviderFault::Transient { message },
444 },
437 fault: status_fault(response.head.status, message),
445438 });
446439 }
447440 let mut decoder = make_decoder(endpoint.kind);
448441 let mut received: u64 = 0;
449 let mut chunk_queue = VecDeque::new();
442 let outcome = |received: u64, outcome: &str| {
443 serde_json::json!({
444 "phase": "outcome",
445 "status": response.head.status,
446 "response_bytes": received,
447 "outcome": outcome,
448 })
449 };
450450 loop {
451451 if cancel.is_cancelled() {
452 spool_record(
453 &endpoint.records,
454 serde_json::json!({
455 "phase": "outcome",
456 "status": response.head.status,
457 "response_bytes": received,
458 "outcome": "cancelled",
459 }),
460 );
452 spool_record(&endpoint.records, outcome(received, "cancelled"));
461453 return Err(SmithError::Cancelled);
462454 }
463 if chunk_queue.is_empty() {
464 match response.chunks.recv() {
465 Ok(chunk) => {
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() {
460 return Ok(());
461 }
468462 }
469 Err(_) => break,
463 continue;
470464 }
471 }
472 if let Some(bytes) = chunk_queue.pop_front() {
473 for event in decoder.push(&bytes)? {
474 if sender.send(Ok(event)).is_err() {
475 return Ok(());
476 }
477 }
478 }
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"),
470 },
471 },
472 Ok(HttpBodyItem::End(HttpBodyEnd::Failed { message })) => SmithError::Provider {
473 fault: ProviderFault::Transient { message },
474 },
475 Err(_) => SmithError::Provider {
476 fault: ProviderFault::Transient {
477 message: "body channel closed without an end".to_string(),
478 },
479 },
480 };
481 spool_record(&endpoint.records, outcome(received, "failed"));
482 return Err(error);
479483 }
480484 for event in decoder.finish()? {
481485 if sender.send(Ok(event)).is_err() {
482486 return Ok(());
483487 }
484488 }
485 spool_record(
486 &endpoint.records,
487 serde_json::json!({
488 "phase": "outcome",
489 "status": response.head.status,
490 "response_bytes": received,
491 "outcome": "completed",
492 }),
493 );
489 spool_record(&endpoint.records, outcome(received, "completed"));
494490 Ok(())
493/// The provider fault a non-2xx status maps to.
494fn status_fault(status: u16, message: String) -> ProviderFault {
495 match status {
496 429 => ProviderFault::RateLimit {
497 retry_after_ms: None,
498 },
499 401 | 403 => ProviderFault::Authentication { message },
500 400 | 404 => ProviderFault::Invalid {
501 field: None,
502 message,
503 },
504 503 => ProviderFault::Overloaded { message },
505 _ => ProviderFault::Transient { message },
506 }
507}
497509#[cfg(test)]
498510mod tests {
499511 use super::*;

smith-harness/src/http.rs

Modified

+31 / −12 text lines

44//! effects later; every call is bounded, cancellable, and recordable.
66use smith::error::{ProviderFault, Result, SmithError};
7use smith::http::{HttpChunk, HttpExchange, HttpExecutor, HttpExecutorRef, HttpHead, HttpResponse};
7use smith::http::{
8 HttpBodyEnd, HttpBodyItem, HttpChunk, HttpExchange, HttpExecutor, HttpExecutorRef, HttpHead,
9 HttpResponse,
10};
811use smith::tool::CancelHandle;
912use std::io::Read;
1013use std::sync::Arc;
164167 Ok(())
167/// Pump `body` into ordered chunks on a reader thread.
170/// Body chunks in flight before the reader thread blocks on the consumer.
171const BODY_CHANNEL_CHUNKS: usize = 16;
173/// Pump `body` into ordered items on a reader thread.
168174///
169/// The channel closes at end of body, on read error, past
170/// [`MAX_BODY_BYTES`], or once `cancel` fires; no chunk read after
175/// The body ends with [`HttpBodyEnd::Complete`] at end of body,
176/// [`HttpBodyEnd::Failed`] on a read error or gap timeout,
177/// [`HttpBodyEnd::Truncated`] past [`MAX_BODY_BYTES`], or
178/// [`HttpBodyEnd::Cancelled`] once `cancel` fires; no chunk read after
171179/// cancellation is delivered.
172180fn stream_body(
173181 head: HttpHead,
174182 mut body: impl Read + Send + 'static,
175183 cancel: CancelHandle,
176184) -> HttpResponse {
177 let (sender, receiver) = mpsc::channel();
185 let (sender, receiver) = mpsc::sync_channel(BODY_CHANNEL_CHUNKS);
178186 std::thread::spawn(move || {
179187 let mut buffer = [0u8; 16 * 1024];
180188 let mut total: u64 = 0;
181 loop {
189 let end = loop {
182190 let read = match body.read(&mut buffer) {
183 Ok(0) | Err(_) => return,
191 Ok(0) => break HttpBodyEnd::Complete,
192 Err(error) => {
193 break HttpBodyEnd::Failed {
194 message: error.to_string(),
195 };
196 }
184197 Ok(read) => read,
185198 };
199 if cancel.is_cancelled() {
200 break HttpBodyEnd::Cancelled;
201 }
186202 total = total.saturating_add(u64::try_from(read).unwrap_or(u64::MAX));
187 if cancel.is_cancelled() || total > MAX_BODY_BYTES {
188 return;
203 if total > MAX_BODY_BYTES {
204 break HttpBodyEnd::Truncated {
205 limit: MAX_BODY_BYTES,
206 };
189207 }
190208 let chunk = HttpChunk {
191209 bytes: buffer[..read].to_vec(),
192210 };
193 if sender.send(chunk).is_err() {
211 if sender.send(HttpBodyItem::Chunk(chunk)).is_err() {
194212 return;
195213 }
196 }
214 };
215 let _ = sender.send(HttpBodyItem::End(end));
197216 });
198217 HttpResponse {
199218 head,
200 chunks: receiver,
219 body: receiver,
201220 }

smith-harness/tests/http_stream.rs

Modified

+48 / −17 text lines

11//! Streaming, cancellation, size-bound, and timeout semantics of the HTTP
22//! engine against a real loopback socket (`SMH-SPEC-SPEC0001`, network transport).
4use smith::http::{HttpExchange, HttpExecutor, HttpMethod, HttpResponse};
4use smith::http::{
5 HttpBodyEnd, HttpBodyItem, HttpExchange, HttpExecutor, HttpMethod, HttpResponse,
6};
57use smith::tool::CancelHandle;
68use smith_harness::http::{MAX_BODY_BYTES, UreqHttpExecutor};
79use std::io::{Read, Write};
4446 let _ = socket.write_all(b"0\r\n\r\n");
49/// Every chunk with its arrival time, then how the body ended.
50fn drain(
51 response: HttpResponse,
52 start: Instant,
53) -> (Vec<(Duration, Vec<u8>)>, Option<HttpBodyEnd>) {
54 let mut chunks = Vec::new();
55 for item in response.body {
56 match item {
57 HttpBodyItem::Chunk(chunk) => chunks.push((start.elapsed(), chunk.bytes)),
58 HttpBodyItem::End(end) => return (chunks, Some(end)),
59 }
60 }
61 (chunks, None)
62}
4764fn post(executor: &dyn HttpExecutor, port: u16, cancel: CancelHandle) -> HttpResponse {
4865 let exchange = HttpExchange {
4966 method: HttpMethod::Post,
6178 let start = Instant::now();
6279 let response = post(&executor, port, CancelHandle::new());
6380 assert_eq!(response.head.status, 200);
64 let arrivals: Vec<(Duration, Vec<u8>)> = response
65 .chunks
66 .iter()
67 .map(|chunk| (start.elapsed(), chunk.bytes))
68 .collect();
81 let (arrivals, end) = drain(response, start);
82 assert_eq!(end, Some(HttpBodyEnd::Complete));
6983 let body: Vec<u8> = arrivals.iter().flat_map(|(_, b)| b.clone()).collect();
7084 assert_eq!(body, EVENTS.concat().as_bytes());
7185 let first = arrivals.first().unwrap().0;
8397 let port = spawn_server(serve_events);
8498 let cancel = CancelHandle::new();
8599 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();
101 assert_eq!(
102 first,
103 HttpBodyItem::Chunk(smith::http::HttpChunk {
104 bytes: EVENTS[0].as_bytes().to_vec()
105 })
106 );
88107 cancel.cancel();
89108 let cancelled_at = Instant::now();
90 // The reader delivers nothing read after cancellation and exits
109 // The reader delivers nothing read after cancellation and ends the body
91110 // once its in-flight read returns: within one event gap.
92 let next = response.chunks.recv_timeout(EVENT_GAP * 2);
111 let next = response.body.recv_timeout(EVENT_GAP * 2);
93112 let stopped = cancelled_at.elapsed();
94 assert_eq!(next, Err(RecvTimeoutError::Disconnected));
113 assert_eq!(next, Ok(HttpBodyItem::End(HttpBodyEnd::Cancelled)));
114 assert_eq!(
115 response.body.recv_timeout(EVENT_GAP),
116 Err(RecvTimeoutError::Disconnected)
117 );
95118 assert!(stopped < EVENT_GAP * 3 / 2, "stopped after {stopped:?}");
109132 }
110133 });
111134 let response = post(&executor, port, CancelHandle::new());
112 let received: u64 = response
113 .chunks
114 .iter()
115 .map(|chunk| chunk.bytes.len() as u64)
116 .sum();
135 let (chunks, end) = drain(response, Instant::now());
136 let received: u64 = chunks.iter().map(|(_, b)| b.len() as u64).sum();
137 assert_eq!(
138 end,
139 Some(HttpBodyEnd::Truncated {
140 limit: MAX_BODY_BYTES
141 })
142 );
117143 assert!(received <= MAX_BODY_BYTES, "received {received}");
118144 assert!(received > MAX_BODY_BYTES - 64 * 1024, "received {received}");
134160 });
135161 let start = Instant::now();
136162 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();
138165 let ended = start.elapsed();
139166 assert_eq!(body, b"okokokok");
167 assert!(
168 matches!(end, Some(HttpBodyEnd::Failed { .. })),
169 "stalled body ended with {end:?}"
170 );
140171 assert!(ended >= Duration::from_millis(600), "ended at {ended:?}");
141172 assert!(ended < Duration::from_millis(1_000), "ended at {ended:?}");

smith/src/http.rs

Modified

+35 / −4 text lines

6363 pub bytes: Vec<u8>,
66/// A streaming HTTP response: head first, chunks in order, end of channel
67/// means the body is complete.
66/// Why a body stream ended; every body ends with exactly one of these.
67#[derive(Clone, Debug, PartialEq, Eq)]
68pub enum HttpBodyEnd {
69 /// The server finished the body.
70 Complete,
71 /// The body exceeded `limit` bytes and was cut off.
72 Truncated {
73 /// The bound that was exceeded.
74 limit: u64,
75 },
76 /// Cancellation was observed between chunks.
77 Cancelled,
78 /// The transport failed mid-body: read error or chunk-gap timeout.
79 Failed {
80 /// Engine diagnostic.
81 message: String,
82 },
83}
85/// One item of a streaming body.
86#[derive(Clone, Debug, PartialEq, Eq)]
87pub enum HttpBodyItem {
88 /// Bytes in order.
89 Chunk(HttpChunk),
90 /// Terminal item; nothing follows.
91 End(HttpBodyEnd),
92}
94/// A streaming HTTP response: head first, then ordered body items.
95///
96/// The body ends with [`HttpBodyItem::End`]; a channel that closes without
97/// an end item is an engine failure and consumers treat it as
98/// [`HttpBodyEnd::Failed`].
6899pub struct HttpResponse {
69100 /// Response head.
70101 pub head: HttpHead,
71 /// Ordered body chunks; the channel closes at end of body.
72 pub chunks: Receiver<HttpChunk>,
102 /// Ordered body items over a bounded channel.
103 pub body: Receiver<HttpBodyItem>,
75106/// Executes [`HttpExchange`]s.

smith/src/provider.rs

Modified

+11 / −3 text lines

7575/// Transport side of the provider effect record channel: redacted records
7676/// go in as they happen.
77pub type RecordSink = std::sync::mpsc::Sender<serde_json::Value>;
77pub type RecordSink = std::sync::mpsc::SyncSender<serde_json::Value>;
7979/// Session side of the provider effect record channel: the agent drains it
8080/// after every provider round.
8181pub type RecordDrain = std::sync::mpsc::Receiver<serde_json::Value>;
83/// A fresh record channel.
83/// Records one round may leave in the channel before the agent drains it.
84///
85/// Invariant: an exchange records at most two entries (intent, outcome), a
86/// round makes at most a handful of exchanges across failover attempts, and
87/// the agent drains after every round; the bound is never reached, so a
88/// sender never blocks.
89pub const RECORD_CHANNEL_BOUND: usize = 64;
91/// A fresh bounded record channel.
8492#[must_use]
8593pub fn record_channel() -> (RecordSink, RecordDrain) {
86 std::sync::mpsc::channel()
94 std::sync::mpsc::sync_channel(RECORD_CHANNEL_BOUND)
8997/// Build a [`StreamFn`] from a callable that produces the stream.