From 6553dfda4a933faef9c3ef0dd1ef5ef382408281 Mon Sep 17 00:00:00 2001 From: Guilhem Lemouel Date: Thu, 26 Nov 2026 00:33:51 -0800 Subject: [PATCH] fix: bound S3 file previews and keep text cut at a character boundary Co-Authored-By: Claude Opus 5.5 --- .../src/ai_session_tools/storage.rs | 139 ++++++++++++++---- 1 file changed, 112 insertions(+), 27 deletions(-) diff --git a/backend/windmill-api/src/ai_session_tools/storage.rs b/backend/windmill-api/src/ai_session_tools/storage.rs index 393e5501a8..feb46a5d3d 100644 --- a/backend/windmill-api/src/ai_session_tools/storage.rs +++ b/backend/windmill-api/src/ai_session_tools/storage.rs @@ -37,7 +37,8 @@ const DEFAULT_MAX_KEYS: u64 = 100; const MAX_KEYS: u64 = 500; /// Bytes of a text file handed to the model, under the MCP runner's result limit. const PREVIEW_BYTES: u64 = 32 * 1024; -const PARQUET_PREVIEW_ROWS: &str = "50"; +const PARQUET_PREVIEW_ROWS: usize = 50; +const MAX_CELL_CHARS: usize = 1000; /// `None` for the primary storage, however it was named. fn storage_arg(args: &Value) -> Option<&str> { @@ -163,45 +164,57 @@ async fn read_s3_file(ctx: &Ctx<'_>, args: &Value) -> ToolResult { out.insert("last_modified".into(), meta["last_modified"].clone()); if key.to_lowercase().ends_with(".parquet") { - let rows = ctx + let preview = ctx .get(&with_query( ctx.ws(&format!( "job_helpers/load_parquet_preview/{}", path_enc(key) )), - &[("limit", Some(PARQUET_PREVIEW_ROWS)), ("storage", storage)], - )) - .await?; - for field in ["columns", "column_types", "rows"] { - out.insert(field.into(), rows[field].clone()); - } - out.insert( - "note".into(), - format!("At most the first {PARQUET_PREVIEW_ROWS} rows.").into(), - ); - } else { - let length = size.min(PREVIEW_BYTES).to_string(); - let preview = ctx - .get(&with_query( - ctx.ws("job_helpers/load_file_preview"), &[ - ("file_key", Some(key)), + ("limit", Some(&PARQUET_PREVIEW_ROWS.to_string())), ("storage", storage), - ("file_size_in_bytes", Some(&size.to_string())), - ("read_bytes_from", Some("0")), - ("read_bytes_length", Some(&length)), ], )) .await?; + let returned = array(preview.get("rows")); + let (rows, cut_cells) = bounded_rows(returned); + out.insert("columns".into(), preview["columns"].clone()); + out.insert("column_types".into(), preview["column_types"].clone()); + let mut notes = vec![]; + if rows.len() < returned.len() || returned.len() == PARQUET_PREVIEW_ROWS { + notes.push(format!("The first {} rows only.", rows.len())); + } + if cut_cells { + notes.push(format!( + "Text cells longer than {MAX_CELL_CHARS} characters are cut." + )); + } + out.insert("rows".into(), rows.into()); + if !notes.is_empty() { + out.insert("note".into(), notes.join(" ").into()); + } + } else { + let mut length = size.min(PREVIEW_BYTES); + let mut preview = text_preview(ctx, key, storage, size, length).await?; + // The endpoint decodes text strictly, so a cut inside a multi-byte character fails + // the whole preview; a UTF-8 character ends within the 3 bytes before it. + while preview["msg"] + .as_str() + .is_some_and(|m| m.ends_with("File encoding is not supported")) + && length < size + && length + 3 > size.min(PREVIEW_BYTES) + { + length -= 1; + preview = text_preview(ctx, key, storage, size, length).await?; + } match preview["content"].as_str() { Some(content) => { + // A CSV preview is the endpoint's parsed rows, whatever length was asked. + let shown = cut_utf8(content, PREVIEW_BYTES as usize); out.insert("content_type".into(), preview["content_type"].clone()); - out.insert("preview".into(), content.into()); - if size > PREVIEW_BYTES { - out.insert( - "note".into(), - format!("Only the first {PREVIEW_BYTES} bytes.").into(), - ); + out.insert("preview".into(), shown.into()); + if shown.len() < content.len() || length < size { + out.insert("note".into(), "Only the start of the file.".into()); } } None => { @@ -212,6 +225,64 @@ async fn read_s3_file(ctx: &Ctx<'_>, args: &Value) -> ToolResult { Ok(pretty(&Value::Object(out))) } +async fn text_preview( + ctx: &Ctx<'_>, + key: &str, + storage: Option<&str>, + size: u64, + length: u64, +) -> Result { + ctx.get(&with_query( + ctx.ws("job_helpers/load_file_preview"), + &[ + ("file_key", Some(key)), + ("storage", storage), + ("file_size_in_bytes", Some(&size.to_string())), + ("read_bytes_from", Some("0")), + ("read_bytes_length", Some(&length.to_string())), + ], + )) + .await +} + +fn cut_utf8(text: &str, max_bytes: usize) -> &str { + if text.len() <= max_bytes { + return text; + } + let mut end = max_bytes; + while !text.is_char_boundary(end) { + end -= 1; + } + &text[..end] +} + +/// Parquet rows within the preview budget, with long text cells cut; also whether a cell was. +fn bounded_rows(rows: &[Value]) -> (Vec, bool) { + let mut kept = vec![]; + let mut cut_cells = false; + // the array's brackets, then each row and its separator + let mut bytes = 2; + for row in rows { + let mut row = row.clone(); + if let Value::Object(cells) = &mut row { + for cell in cells.values_mut() { + if let Value::String(s) = cell { + if let Some((end, _)) = s.char_indices().nth(MAX_CELL_CHARS) { + s.truncate(end); + cut_cells = true; + } + } + } + } + bytes += row.to_string().len() + 1; + if bytes > PREVIEW_BYTES as usize && !kept.is_empty() { + break; + } + kept.push(row); + } + (kept, cut_cells) +} + fn in_storage(storage: Option<&str>) -> String { storage .map(|s| format!(" in storage `{s}`")) @@ -276,4 +347,18 @@ mod tests { assert_eq!(folder_prefix(Some("/charts")), "charts/"); assert_eq!(folder_prefix(Some("/")), ""); } + + /// The endpoints return whole rows whatever size was asked, so the tool must bound them. + #[test] + fn previews_stay_within_the_byte_budget() { + let long = "é".repeat(PREVIEW_BYTES as usize); + let cut = cut_utf8(&long, PREVIEW_BYTES as usize + 1); + assert_eq!(cut.len(), PREVIEW_BYTES as usize); + + let rows: Vec = (0..50).map(|i| json!({ "id": i, "text": long })).collect(); + let (kept, cut_cells) = bounded_rows(&rows); + assert!(cut_cells); + assert!(kept.len() < rows.len()); + assert!(Value::from(kept).to_string().len() <= PREVIEW_BYTES as usize); + } }