| 1 | use std::collections::VecDeque; |
| 2 | use std::io::{self, Read, Seek, SeekFrom, Write}; |
| 3 | use std::path::{Path, PathBuf}; |
| 4 | use std::sync::{Arc, Mutex}; |
| 5 | |
| 6 | use encoding_rs::{CoderResult, Decoder, UTF_8}; |
| 7 | |
| 8 | const BOUNDED_OUTPUT_MAX_LINES: usize = 400; |
| 9 | const BOUNDED_OUTPUT_MAX_BYTES: usize = 16 * 1024; |
| 10 | const BOUNDED_OUTPUT_RETAIN_BYTES: usize = BOUNDED_OUTPUT_MAX_BYTES + 4; |
| 11 | |
| 12 | #[derive(Debug, Clone)] |
| 13 | pub(super) struct SessionArtifactSpec { |
| 14 | pub(super) session_id: String, |
| 15 | pub(super) artifact_id: String, |
| 16 | } |
| 17 | |
| 18 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 19 | pub(super) struct PersistedShellArtifact { |
| 20 | pub(super) artifact_id: String, |
| 21 | pub(super) session_id: String, |
| 22 | pub(super) absolute_path: PathBuf, |
| 23 | pub(super) relative_path: PathBuf, |
| 24 | pub(super) byte_size: u64, |
| 25 | pub(super) complete: bool, |
| 26 | pub(super) digest: String, |
| 27 | } |
| 28 | |
| 29 | pub(super) fn persist_shell_output_artifact( |
| 30 | session_id: &str, |
| 31 | origin_tool_call_id: Option<&str>, |
| 32 | fallback_key: &str, |
| 33 | raw_bytes: &[u8], |
| 34 | ) -> io::Result<PersistedShellArtifact> { |
| 35 | if !codewhale_runtime::artifacts::is_valid_session_id(session_id) { |
| 36 | return Err(io::Error::new( |
| 37 | io::ErrorKind::InvalidInput, |
| 38 | "session artifact storage is unavailable without a valid session id", |
| 39 | )); |
| 40 | } |
| 41 | let raw_id = origin_tool_call_id |
| 42 | .map(str::trim) |
| 43 | .filter(|id| !id.is_empty()) |
| 44 | .unwrap_or(fallback_key); |
| 45 | let artifact_id = codewhale_runtime::artifacts::artifact_id_for_tool_call(raw_id); |
| 46 | persist_shell_bytes_with_spec( |
| 47 | &SessionArtifactSpec { |
| 48 | session_id: session_id.to_string(), |
| 49 | artifact_id, |
| 50 | }, |
| 51 | raw_bytes, |
| 52 | ) |
| 53 | } |
| 54 | |
| 55 | fn persist_shell_bytes_with_spec( |
| 56 | spec: &SessionArtifactSpec, |
| 57 | raw_bytes: &[u8], |
| 58 | ) -> io::Result<PersistedShellArtifact> { |
| 59 | let (absolute_path, relative_path) = |
| 60 | codewhale_runtime::artifacts::write_session_artifact_immutable( |
| 61 | &spec.session_id, |
| 62 | &spec.artifact_id, |
| 63 | raw_bytes, |
| 64 | )?; |
| 65 | let digest = codewhale_runtime::hashing::sha256_hex(raw_bytes); |
| 66 | Ok(PersistedShellArtifact { |
| 67 | artifact_id: spec.artifact_id.clone(), |
| 68 | session_id: spec.session_id.clone(), |
| 69 | complete: true, |
| 70 | absolute_path, |
| 71 | relative_path, |
| 72 | byte_size: raw_bytes.len().try_into().unwrap_or(u64::MAX), |
| 73 | digest, |
| 74 | }) |
| 75 | } |
| 76 | |
| 77 | #[derive(Debug)] |
| 78 | pub(super) struct BoundedOutputSnapshot { |
| 79 | pub(super) content: String, |
| 80 | pub(super) total_bytes: usize, |
| 81 | pub(super) retained_bytes: usize, |
| 82 | pub(super) truncated: bool, |
| 83 | pub(super) persisted_artifact: Option<PersistedShellArtifact>, |
| 84 | } |
| 85 | |
| 86 | pub(super) struct BoundedOutputAccumulator { |
| 87 | tail: VecDeque<u8>, |
| 88 | tail_newlines: usize, |
| 89 | total_bytes: usize, |
| 90 | total_newlines: usize, |
| 91 | current_line_bytes: usize, |
| 92 | last_line_bytes: usize, |
| 93 | front_clipped: bool, |
| 94 | last_byte: Option<u8>, |
| 95 | decoder: Decoder, |
| 96 | stream_finished: bool, |
| 97 | stream_error: Option<String>, |
| 98 | temp: Option<tempfile::NamedTempFile>, |
| 99 | session_artifact: Option<SessionArtifactSpec>, |
| 100 | persisted_artifact: Option<PersistedShellArtifact>, |
| 101 | spill_unavailable: Option<String>, |
| 102 | } |
| 103 | |
| 104 | impl BoundedOutputAccumulator { |
| 105 | pub(super) fn new_in( |
| 106 | spill_dir: Option<&Path>, |
| 107 | session_artifact: Option<SessionArtifactSpec>, |
| 108 | ) -> Self { |
| 109 | let mut builder = tempfile::Builder::new(); |
| 110 | builder.prefix("codewhale-bash-"); |
| 111 | let temp = match spill_dir { |
| 112 | Some(dir) => builder.tempfile_in(dir), |
| 113 | None => builder.tempfile(), |
| 114 | }; |
| 115 | let (temp, spill_unavailable) = match temp { |
| 116 | Ok(temp) => (Some(temp), None), |
| 117 | Err(error) => { |
| 118 | tracing::warn!( |
| 119 | error = %error, |
| 120 | "shell output spill file unavailable; continuing with the in-memory tail only" |
| 121 | ); |
| 122 | (None, Some(spill_unavailable_reason(&error))) |
| 123 | } |
| 124 | }; |
| 125 | Self { |
| 126 | tail: VecDeque::with_capacity(BOUNDED_OUTPUT_RETAIN_BYTES), |
| 127 | tail_newlines: 0, |
| 128 | total_bytes: 0, |
| 129 | total_newlines: 0, |
| 130 | current_line_bytes: 0, |
| 131 | last_line_bytes: 0, |
| 132 | front_clipped: false, |
| 133 | last_byte: None, |
| 134 | decoder: UTF_8.new_decoder_without_bom_handling(), |
| 135 | stream_finished: false, |
| 136 | stream_error: None, |
| 137 | temp, |
| 138 | session_artifact, |
| 139 | persisted_artifact: None, |
| 140 | spill_unavailable, |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | /// Why the complete output is not being persisted, if it is not. |
| 145 | #[cfg(test)] |
| 146 | pub(super) fn spill_unavailable(&self) -> Option<&str> { |
| 147 | self.spill_unavailable.as_deref() |
| 148 | } |
| 149 | |
| 150 | fn decode(&mut self, bytes: &[u8], last: bool) -> String { |
| 151 | let capacity = self |
| 152 | .decoder |
| 153 | .max_utf8_buffer_length(bytes.len()) |
| 154 | .unwrap_or(bytes.len().saturating_mul(3).saturating_add(3)); |
| 155 | let mut decoded = String::with_capacity(capacity); |
| 156 | let mut offset = 0; |
| 157 | loop { |
| 158 | let (result, read, _) = |
| 159 | self.decoder |
| 160 | .decode_to_string(&bytes[offset..], &mut decoded, last); |
| 161 | offset += read; |
| 162 | if result == CoderResult::InputEmpty { |
| 163 | return decoded; |
| 164 | } |
| 165 | decoded.reserve(capacity.max(4)); |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | pub(super) fn append(&mut self, raw: &[u8]) -> io::Result<()> { |
| 170 | if self.stream_finished { |
| 171 | return Err(io::Error::other( |
| 172 | "shell output arrived after the stream closed", |
| 173 | )); |
| 174 | } |
| 175 | if let Some(temp) = self.temp.as_mut() { |
| 176 | temp.write_all(raw)?; |
| 177 | } |
| 178 | let decoded = self.decode(raw, false); |
| 179 | self.append_decoded(decoded.as_bytes()); |
| 180 | Ok(()) |
| 181 | } |
| 182 | |
| 183 | pub(super) fn finish(&mut self) -> io::Result<()> { |
| 184 | if !self.stream_finished { |
| 185 | let decoded = self.decode(&[], true); |
| 186 | self.append_decoded(decoded.as_bytes()); |
| 187 | if let Some(temp) = self.temp.as_mut() { |
| 188 | temp.flush()?; |
| 189 | } |
| 190 | self.stream_finished = true; |
| 191 | } |
| 192 | Ok(()) |
| 193 | } |
| 194 | |
| 195 | pub(super) fn record_error(&mut self, error: &io::Error) { |
| 196 | self.stream_error = Some(error.to_string()); |
| 197 | } |
| 198 | |
| 199 | fn append_decoded(&mut self, bytes: &[u8]) { |
| 200 | self.total_bytes = self.total_bytes.saturating_add(bytes.len()); |
| 201 | for &byte in bytes { |
| 202 | self.tail.push_back(byte); |
| 203 | if byte == b'\n' { |
| 204 | self.tail_newlines += 1; |
| 205 | self.total_newlines += 1; |
| 206 | self.last_line_bytes = self.current_line_bytes; |
| 207 | self.current_line_bytes = 0; |
| 208 | } else { |
| 209 | self.current_line_bytes += 1; |
| 210 | } |
| 211 | self.last_byte = Some(byte); |
| 212 | } |
| 213 | while self.tail.len() > BOUNDED_OUTPUT_RETAIN_BYTES { |
| 214 | self.pop_front(); |
| 215 | self.front_clipped = true; |
| 216 | } |
| 217 | while self.tail_lines() > BOUNDED_OUTPUT_MAX_LINES { |
| 218 | while let Some(byte) = self.tail.pop_front() { |
| 219 | if byte == b'\n' { |
| 220 | self.tail_newlines -= 1; |
| 221 | break; |
| 222 | } |
| 223 | } |
| 224 | self.front_clipped = false; |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | fn pop_front(&mut self) { |
| 229 | if self.tail.pop_front() == Some(b'\n') { |
| 230 | self.tail_newlines -= 1; |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | fn tail_lines(&self) -> usize { |
| 235 | self.tail_newlines + usize::from(self.tail.back().is_some_and(|byte| *byte != b'\n')) |
| 236 | } |
| 237 | |
| 238 | fn total_lines(&self) -> usize { |
| 239 | self.total_newlines + usize::from(self.last_byte.is_some_and(|byte| byte != b'\n')) |
| 240 | } |
| 241 | |
| 242 | fn selected(&self) -> (Vec<u8>, bool) { |
| 243 | let mut bytes = self.tail.iter().copied().collect::<Vec<_>>(); |
| 244 | let recent_line_bytes = if self.last_byte == Some(b'\n') { |
| 245 | self.last_line_bytes |
| 246 | } else { |
| 247 | self.current_line_bytes |
| 248 | }; |
| 249 | let partial_line = recent_line_bytes > BOUNDED_OUTPUT_MAX_BYTES; |
| 250 | if partial_line { |
| 251 | if bytes.last() == Some(&b'\n') { |
| 252 | bytes.pop(); |
| 253 | } |
| 254 | let floor = bytes.len().saturating_sub(BOUNDED_OUTPUT_MAX_BYTES); |
| 255 | let start = (floor..bytes.len()) |
| 256 | .find(|index| std::str::from_utf8(&bytes[*index..]).is_ok()) |
| 257 | .unwrap_or(bytes.len()); |
| 258 | bytes.drain(..start); |
| 259 | } else if self.front_clipped |
| 260 | && let Some(newline) = bytes.iter().position(|byte| *byte == b'\n') |
| 261 | { |
| 262 | bytes.drain(..=newline); |
| 263 | } |
| 264 | (bytes, partial_line) |
| 265 | } |
| 266 | |
| 267 | fn format_size(bytes: usize) -> String { |
| 268 | if bytes < 1024 { |
| 269 | format!("{bytes}B") |
| 270 | } else if bytes < 1024 * 1024 { |
| 271 | format!("{:.1}KB", bytes as f64 / 1024.0) |
| 272 | } else { |
| 273 | format!("{:.1}MB", bytes as f64 / (1024.0 * 1024.0)) |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | pub(super) fn total_bytes(&self) -> usize { |
| 278 | self.total_bytes |
| 279 | } |
| 280 | |
| 281 | /// Decoded output appended after `cursor` (a previous `total_bytes`), for |
| 282 | /// incremental readers such as `wait`. The second value counts bytes of |
| 283 | /// that range the memory bound already discarded; the complete output is |
| 284 | /// still in the spill file. |
| 285 | pub(super) fn delta_since(&self, cursor: usize) -> io::Result<(String, usize)> { |
| 286 | if let Some(error) = self.stream_error.as_ref() { |
| 287 | return Err(io::Error::other(error.clone())); |
| 288 | } |
| 289 | let new_bytes = self.total_bytes.saturating_sub(cursor); |
| 290 | let available = new_bytes.min(self.tail.len()); |
| 291 | let mut bytes = self |
| 292 | .tail |
| 293 | .range(self.tail.len() - available..) |
| 294 | .copied() |
| 295 | .collect::<Vec<_>>(); |
| 296 | // A cursor is always a character boundary; a clipped tail's front may |
| 297 | // not be, so drop any continuation bytes it starts with. |
| 298 | let partial = bytes |
| 299 | .iter() |
| 300 | .take_while(|byte| (**byte & 0xC0) == 0x80) |
| 301 | .count(); |
| 302 | bytes.drain(..partial); |
| 303 | let omitted = new_bytes - available + partial; |
| 304 | Ok((String::from_utf8_lossy(&bytes).into_owned(), omitted)) |
| 305 | } |
| 306 | |
| 307 | fn persist_temp_to_session_artifact(&mut self) -> io::Result<()> { |
| 308 | let Some(temp) = self.temp.as_mut() else { |
| 309 | return Ok(()); |
| 310 | }; |
| 311 | let Some(spec) = self.session_artifact.as_ref() else { |
| 312 | self.spill_unavailable = |
| 313 | Some("session artifact storage is unavailable without an active session".into()); |
| 314 | return Err(io::Error::other(self.spill_unavailable.clone().unwrap())); |
| 315 | }; |
| 316 | temp.flush()?; |
| 317 | temp.as_file_mut().seek(SeekFrom::Start(0))?; |
| 318 | let result = codewhale_runtime::artifacts::write_session_artifact_immutable_from_reader( |
| 319 | &spec.session_id, |
| 320 | &spec.artifact_id, |
| 321 | temp.as_file_mut(), |
| 322 | ); |
| 323 | match result { |
| 324 | Ok((absolute_path, relative_path, byte_size, digest)) => { |
| 325 | self.persisted_artifact = Some(PersistedShellArtifact { |
| 326 | artifact_id: spec.artifact_id.clone(), |
| 327 | session_id: spec.session_id.clone(), |
| 328 | complete: true, |
| 329 | absolute_path, |
| 330 | relative_path, |
| 331 | byte_size, |
| 332 | digest, |
| 333 | }); |
| 334 | self.spill_unavailable = None; |
| 335 | self.temp.take(); |
| 336 | Ok(()) |
| 337 | } |
| 338 | Err(error) => { |
| 339 | self.spill_unavailable = Some(spill_unavailable_reason(&error)); |
| 340 | Err(error) |
| 341 | } |
| 342 | } |
| 343 | } |
| 344 | |
| 345 | pub(super) fn retained_raw_bytes(&self) -> Option<(Vec<u8>, usize)> { |
| 346 | let mut file = if let Some(artifact) = self.persisted_artifact.as_ref() { |
| 347 | codewhale_runtime::artifacts::open_session_relative( |
| 348 | &artifact.session_id, |
| 349 | &artifact.relative_path, |
| 350 | false, |
| 351 | ) |
| 352 | .ok()? |
| 353 | .open_file() |
| 354 | .ok()? |
| 355 | } else { |
| 356 | self.temp.as_ref()?.reopen().ok()? |
| 357 | }; |
| 358 | let size = file.metadata().ok()?.len(); |
| 359 | let omitted = size.saturating_sub(BOUNDED_OUTPUT_MAX_BYTES as u64); |
| 360 | file.seek(SeekFrom::Start(omitted)).ok()?; |
| 361 | let mut bytes = Vec::new(); |
| 362 | file.take(BOUNDED_OUTPUT_MAX_BYTES as u64) |
| 363 | .read_to_end(&mut bytes) |
| 364 | .ok()?; |
| 365 | Some((bytes, usize::try_from(omitted).unwrap_or(usize::MAX))) |
| 366 | } |
| 367 | |
| 368 | pub(super) fn release_temp(&mut self) { |
| 369 | if self.persisted_artifact.is_some() || self.selected().0.len() == self.total_bytes { |
| 370 | self.temp.take(); |
| 371 | } |
| 372 | } |
| 373 | |
| 374 | pub(super) fn persisted_artifact(&self) -> Option<PersistedShellArtifact> { |
| 375 | self.persisted_artifact.clone() |
| 376 | } |
| 377 | |
| 378 | pub(super) fn omitted_notice(&mut self, omitted: usize) -> String { |
| 379 | if self.stream_finished && self.persisted_artifact.is_none() && self.temp.is_some() { |
| 380 | let _ = self.persist_temp_to_session_artifact(); |
| 381 | } |
| 382 | match ( |
| 383 | self.persisted_artifact.as_ref(), |
| 384 | self.spill_unavailable.as_deref(), |
| 385 | ) { |
| 386 | (Some(artifact), _) => format!( |
| 387 | "[{omitted} bytes of earlier output not retained in memory. Full output saved as artifact {}; {}]\n", |
| 388 | artifact.artifact_id, |
| 389 | crate::tools::truncate::spillover_recovery_instruction(Some(&artifact.artifact_id)), |
| 390 | ), |
| 391 | (None, Some(reason)) => format!( |
| 392 | "[{omitted} bytes of earlier output not retained in memory. Full output was not persisted: {reason}]\n" |
| 393 | ), |
| 394 | (None, None) if self.temp.is_some() && self.session_artifact.is_some() => format!( |
| 395 | "[{omitted} bytes of earlier output not retained in memory; full output will be saved as a session artifact when the command finishes]\n" |
| 396 | ), |
| 397 | (None, None) => { |
| 398 | format!("[{omitted} bytes of earlier output not retained in memory]\n") |
| 399 | } |
| 400 | } |
| 401 | } |
| 402 | |
| 403 | pub(super) fn snapshot(&mut self, finalize: bool) -> io::Result<BoundedOutputSnapshot> { |
| 404 | if let Some(error) = self.stream_error.as_ref() { |
| 405 | return Err(io::Error::other(error.clone())); |
| 406 | } |
| 407 | let (selected, partial_line) = self.selected(); |
| 408 | let retained_bytes = selected.len(); |
| 409 | let truncated = retained_bytes < self.total_bytes; |
| 410 | let total_lines = self.total_lines(); |
| 411 | let kept_lines = selected.iter().filter(|byte| **byte == b'\n').count() |
| 412 | + usize::from(selected.last().is_some_and(|byte| *byte != b'\n')); |
| 413 | let mut content = String::from_utf8(selected).expect("stream decoder emits valid UTF-8"); |
| 414 | |
| 415 | if finalize |
| 416 | && truncated |
| 417 | && self.stream_finished |
| 418 | && self.persisted_artifact.is_none() |
| 419 | && self.temp.is_some() |
| 420 | && self.session_artifact.is_some() |
| 421 | { |
| 422 | self.persist_temp_to_session_artifact()?; |
| 423 | } |
| 424 | if truncated && finalize && self.persisted_artifact.is_none() { |
| 425 | let reason = self.spill_unavailable.as_deref().unwrap_or( |
| 426 | if self.session_artifact.is_none() { |
| 427 | "session artifact storage is unavailable without an active session" |
| 428 | } else { |
| 429 | "the output stream did not close cleanly, so the full output artifact was not saved" |
| 430 | }, |
| 431 | ); |
| 432 | content.push_str(&format!( |
| 433 | "\n\n[Showing the last {} of {} lines ({} limit). Full output was not persisted: {reason}]", |
| 434 | Self::format_size(retained_bytes), |
| 435 | total_lines, |
| 436 | Self::format_size(BOUNDED_OUTPUT_MAX_BYTES), |
| 437 | )); |
| 438 | } else if truncated |
| 439 | && finalize |
| 440 | && let Some(artifact) = self.persisted_artifact.as_ref() |
| 441 | { |
| 442 | let recovery = |
| 443 | crate::tools::truncate::spillover_recovery_instruction(Some(&artifact.artifact_id)); |
| 444 | if partial_line { |
| 445 | content.push_str(&format!( |
| 446 | "\n\n[Showing last {} of line {} (line is {}). Full output saved as artifact {}; {recovery}]", |
| 447 | Self::format_size(retained_bytes), |
| 448 | total_lines, |
| 449 | Self::format_size(self.current_line_bytes), |
| 450 | artifact.artifact_id, |
| 451 | )); |
| 452 | } else { |
| 453 | let start = total_lines.saturating_sub(kept_lines) + 1; |
| 454 | let limit = if self.front_clipped { |
| 455 | format!(" ({} limit)", Self::format_size(BOUNDED_OUTPUT_MAX_BYTES)) |
| 456 | } else { |
| 457 | String::new() |
| 458 | }; |
| 459 | content.push_str(&format!( |
| 460 | "\n\n[Showing lines {start}-{total_lines} of {total_lines}{limit}. Full output saved as artifact {}; {recovery}]", |
| 461 | artifact.artifact_id, |
| 462 | )); |
| 463 | } |
| 464 | } |
| 465 | Ok(BoundedOutputSnapshot { |
| 466 | content, |
| 467 | total_bytes: self.total_bytes, |
| 468 | retained_bytes, |
| 469 | truncated, |
| 470 | persisted_artifact: self.persisted_artifact.clone(), |
| 471 | }) |
| 472 | } |
| 473 | |
| 474 | #[cfg(test)] |
| 475 | pub(super) fn retained_memory_bytes(&self) -> usize { |
| 476 | self.tail.len() |
| 477 | } |
| 478 | } |
| 479 | |
| 480 | /// Human-readable, actionable reason for a failed spill-file creation. |
| 481 | pub(super) fn spill_unavailable_reason(error: &io::Error) -> String { |
| 482 | match resource_exhaustion_hint(error) { |
| 483 | Some(hint) => format!("{error} ({hint})"), |
| 484 | None => error.to_string(), |
| 485 | } |
| 486 | } |
| 487 | |
| 488 | /// When an I/O error looks like host resource exhaustion, name the likely |
| 489 | /// cause and the remedy. Returns `None` for ordinary errors. |
| 490 | pub(super) fn resource_exhaustion_hint(error: &io::Error) -> Option<&'static str> { |
| 491 | use io::ErrorKind; |
| 492 | match error.kind() { |
| 493 | ErrorKind::StorageFull | ErrorKind::QuotaExceeded => { |
| 494 | return Some("the disk holding the temp dir is full; free space and retry"); |
| 495 | } |
| 496 | ErrorKind::OutOfMemory => { |
| 497 | return Some("the host is out of memory; close heavy processes and retry"); |
| 498 | } |
| 499 | _ => {} |
| 500 | } |
| 501 | let code = error.raw_os_error()?; |
| 502 | // ENOSPC / EDQUOT / EMFILE / ENFILE / ENOMEM / EAGAIN — the codes fork(2), |
| 503 | // pipe(2), and open(2) return when the machine is thrashing. |
| 504 | #[cfg(unix)] |
| 505 | { |
| 506 | if code == libc::ENOSPC || code == libc::EDQUOT { |
| 507 | return Some("the disk holding the temp dir is full; free space and retry"); |
| 508 | } |
| 509 | if code == libc::EMFILE || code == libc::ENFILE { |
| 510 | return Some( |
| 511 | "the process or host has run out of file descriptors; close background jobs or raise `ulimit -n` and retry", |
| 512 | ); |
| 513 | } |
| 514 | if code == libc::ENOMEM { |
| 515 | return Some("the host is out of memory; close heavy processes and retry"); |
| 516 | } |
| 517 | if code == libc::EAGAIN { |
| 518 | return Some( |
| 519 | "the host refused to create a process, thread, or pipe (resource limit reached); close heavy processes and retry", |
| 520 | ); |
| 521 | } |
| 522 | } |
| 523 | #[cfg(windows)] |
| 524 | { |
| 525 | // ERROR_DISK_FULL, ERROR_HANDLE_DISK_FULL, ERROR_NOT_ENOUGH_MEMORY, ERROR_TOO_MANY_OPEN_FILES |
| 526 | if code == 112 || code == 39 { |
| 527 | return Some("the disk holding the temp dir is full; free space and retry"); |
| 528 | } |
| 529 | if code == 8 { |
| 530 | return Some("the host is out of memory; close heavy processes and retry"); |
| 531 | } |
| 532 | if code == 4 { |
| 533 | return Some( |
| 534 | "the process has run out of file handles; close background jobs and retry", |
| 535 | ); |
| 536 | } |
| 537 | } |
| 538 | let _ = code; |
| 539 | None |
| 540 | } |
| 541 | |
| 542 | /// Hard in-flight ceiling for one raw shell stream held in memory (#5472). |
| 543 | /// Past this the oldest bytes are dropped — counted, never silently lost — so |
| 544 | /// one chatty command (`cargo build -v`, `git log -p`) cannot grow the process |
| 545 | /// by its entire output. Deliberately far above every consumer of these bytes: |
| 546 | /// the 30 KB tool-result truncation (`shell_output::MAX_OUTPUT_SIZE`), the |
| 547 | /// 1,200-char job-panel tail and the 1 KiB completion tail all fit with three |
| 548 | /// orders of magnitude to spare. The only surface a clip can reach is the |
| 549 | /// durable completion artifact, which records the omission explicitly. |
| 550 | pub(super) const RAW_STREAM_MAX_BYTES: usize = 16 * 1024 * 1024; |
| 551 | |
| 552 | /// Extra headroom before a front-drop, so the O(len) compaction runs once per |
| 553 | /// `cap / 4` bytes appended instead of once per chunk. |
| 554 | const RAW_STREAM_DROP_SLACK: usize = RAW_STREAM_MAX_BYTES / 4; |
| 555 | |
| 556 | /// Tail retained once a job's output has been *delivered* — the foreground |
| 557 | /// result is already the tool result, or the completion evidence is already |
| 558 | /// written to its session artifact. Everything past this is dead weight for |
| 559 | /// the up-to-1 h the finished record stays listed (#5472 finding 1). |
| 560 | pub(super) const RAW_STREAM_SETTLED_TAIL_BYTES: usize = 64 * 1024; |
| 561 | |
| 562 | /// One raw (undecoded) shell stream retained in memory for a live job. |
| 563 | /// |
| 564 | /// Bounded two independent ways, which is the whole point of the type: |
| 565 | /// `append` enforces `cap` while the command runs, and `release_to_tail` |
| 566 | /// collapses the buffer the moment its bytes have been delivered. Both record |
| 567 | /// how many leading bytes were discarded so `total_len` — and therefore every |
| 568 | /// `stdout_len` / `byte_length` the model and the artifact see — stays honest. |
| 569 | pub(super) struct RawOutputBuffer { |
| 570 | data: Vec<u8>, |
| 571 | dropped: usize, |
| 572 | cap: usize, |
| 573 | abandoned: bool, |
| 574 | spool_on_clip: bool, |
| 575 | spool: Option<tempfile::NamedTempFile>, |
| 576 | final_artifact: Option<PersistedShellArtifact>, |
| 577 | } |
| 578 | |
| 579 | impl RawOutputBuffer { |
| 580 | pub(super) fn new() -> Self { |
| 581 | Self::with_cap(RAW_STREAM_MAX_BYTES) |
| 582 | } |
| 583 | |
| 584 | pub(super) fn with_cap(cap: usize) -> Self { |
| 585 | Self { |
| 586 | data: Vec::new(), |
| 587 | dropped: 0, |
| 588 | cap: cap.max(1), |
| 589 | abandoned: false, |
| 590 | spool_on_clip: false, |
| 591 | spool: None, |
| 592 | final_artifact: None, |
| 593 | } |
| 594 | } |
| 595 | |
| 596 | /// Append, returning `false` once nobody will ever read this stream again. |
| 597 | /// |
| 598 | /// The reader thread uses that as its exit condition, which is the only way |
| 599 | /// out when a descendant has escaped the process group and holds the pipe |
| 600 | /// write-end open: `read()` will never see EOF, so without this the thread |
| 601 | /// runs — and retains its buffer — for the life of the process (#5472 |
| 602 | /// finding 2). |
| 603 | pub(super) fn append(&mut self, bytes: &[u8]) -> bool { |
| 604 | if self.abandoned { |
| 605 | // Keep the total honest even though the bytes are discarded. |
| 606 | self.dropped = self.dropped.saturating_add(bytes.len()); |
| 607 | return false; |
| 608 | } |
| 609 | if self.spool_on_clip { |
| 610 | let clipped = self.data.len().saturating_add(bytes.len()) |
| 611 | > self.cap.saturating_add(RAW_STREAM_DROP_SLACK.min(self.cap)); |
| 612 | let write = if let Some(file) = self.spool.as_mut() { |
| 613 | file.write_all(bytes) |
| 614 | } else if clipped && self.dropped == 0 { |
| 615 | tempfile::NamedTempFile::new().and_then(|mut file| { |
| 616 | file.write_all(&self.data)?; |
| 617 | file.write_all(bytes)?; |
| 618 | self.spool = Some(file); |
| 619 | Ok(()) |
| 620 | }) |
| 621 | } else { |
| 622 | Ok(()) |
| 623 | }; |
| 624 | if let Err(error) = write { |
| 625 | tracing::warn!(%error, "raw shell spill unavailable"); |
| 626 | self.spool.take(); |
| 627 | self.spool_on_clip = false; |
| 628 | } |
| 629 | } |
| 630 | self.data.extend_from_slice(bytes); |
| 631 | if self.data.len() > self.cap.saturating_add(RAW_STREAM_DROP_SLACK.min(self.cap)) { |
| 632 | self.drop_front_to(self.cap); |
| 633 | } |
| 634 | true |
| 635 | } |
| 636 | |
| 637 | pub(super) fn for_job(cap: usize, spool_on_clip: bool) -> SharedRawOutput { |
| 638 | Arc::new(Mutex::new(Self { |
| 639 | spool_on_clip, |
| 640 | ..Self::with_cap(cap) |
| 641 | })) |
| 642 | } |
| 643 | |
| 644 | pub(super) fn mark_read_error(&mut self) { |
| 645 | self.abandoned = true; |
| 646 | } |
| 647 | |
| 648 | pub(super) fn capture_complete(&self) -> bool { |
| 649 | !self.abandoned && (self.dropped == 0 || self.spool.is_some()) |
| 650 | } |
| 651 | |
| 652 | fn copy_complete(&self, writer: &mut impl Write) -> io::Result<()> { |
| 653 | if self.abandoned { |
| 654 | return Err(io::Error::other("the output reader ended before EOF")); |
| 655 | } |
| 656 | if let Some(file) = self.spool.as_ref() { |
| 657 | let copied = io::copy(&mut file.reopen()?, writer)?; |
| 658 | if copied != self.total_len() as u64 { |
| 659 | return Err(io::Error::other("raw shell spill is incomplete")); |
| 660 | } |
| 661 | } else if self.dropped == 0 { |
| 662 | writer.write_all(&self.data)?; |
| 663 | } else { |
| 664 | return Err(io::Error::other( |
| 665 | "raw shell output was dropped before publication", |
| 666 | )); |
| 667 | } |
| 668 | Ok(()) |
| 669 | } |
| 670 | |
| 671 | pub(super) fn artifact(&self) -> Option<PersistedShellArtifact> { |
| 672 | self.final_artifact.clone() |
| 673 | } |
| 674 | |
| 675 | pub(super) fn publish_complete( |
| 676 | &mut self, |
| 677 | stderr: Option<&Self>, |
| 678 | session: &str, |
| 679 | key: &str, |
| 680 | ) -> io::Result<PersistedShellArtifact> { |
| 681 | let mut file = tempfile::tempfile()?; |
| 682 | self.copy_complete(&mut file)?; |
| 683 | if let Some(stderr) = stderr.filter(|raw| raw.total_len() > 0) { |
| 684 | if self.total_len() != 0 { |
| 685 | file.write_all(b"\n\n")?; |
| 686 | } |
| 687 | file.write_all(b"STDERR:\n")?; |
| 688 | stderr.copy_complete(&mut file)?; |
| 689 | } |
| 690 | file.rewind()?; |
| 691 | let artifact_id = codewhale_runtime::artifacts::artifact_id_for_tool_call(key); |
| 692 | let (absolute_path, relative_path, byte_size, digest) = |
| 693 | codewhale_runtime::artifacts::write_session_artifact_immutable_from_reader( |
| 694 | session, |
| 695 | &artifact_id, |
| 696 | &mut file, |
| 697 | )?; |
| 698 | let artifact = PersistedShellArtifact { |
| 699 | artifact_id, |
| 700 | complete: true, |
| 701 | session_id: session.to_owned(), |
| 702 | absolute_path, |
| 703 | relative_path, |
| 704 | byte_size, |
| 705 | digest, |
| 706 | }; |
| 707 | self.final_artifact = Some(artifact.clone()); |
| 708 | Ok(artifact) |
| 709 | } |
| 710 | |
| 711 | /// Give up on this stream: release everything held and stop accepting more. |
| 712 | /// |
| 713 | /// Called when the bounded reader join times out. The shell is already |
| 714 | /// terminal and its result already delivered, so nothing can consume these |
| 715 | /// bytes; holding them until the writer eventually closes is pure residency. |
| 716 | pub(super) fn abandon(&mut self) { |
| 717 | self.abandoned = true; |
| 718 | self.spool.take(); |
| 719 | self.dropped = self.dropped.saturating_add(self.data.len()); |
| 720 | self.data = Vec::new(); |
| 721 | } |
| 722 | |
| 723 | /// Total bytes this stream has produced, including bytes no longer held. |
| 724 | pub(super) fn total_len(&self) -> usize { |
| 725 | self.dropped.saturating_add(self.data.len()) |
| 726 | } |
| 727 | |
| 728 | /// Leading bytes discarded by the in-flight cap or by `release_to_tail`. |
| 729 | pub(super) fn dropped(&self) -> usize { |
| 730 | self.dropped |
| 731 | } |
| 732 | |
| 733 | pub(super) fn retained(&self) -> &[u8] { |
| 734 | &self.data |
| 735 | } |
| 736 | |
| 737 | /// Collapse to at most `keep` trailing bytes and give the allocation back. |
| 738 | /// Called once a job is terminal *and* its output has been delivered. |
| 739 | pub(super) fn release_to_tail(&mut self, keep: usize) { |
| 740 | self.spool.take(); |
| 741 | if self.data.len() <= keep { |
| 742 | return; |
| 743 | } |
| 744 | self.drop_front_to(keep); |
| 745 | self.data.shrink_to_fit(); |
| 746 | } |
| 747 | |
| 748 | fn drop_front_to(&mut self, keep: usize) { |
| 749 | let mut start = self.data.len().saturating_sub(keep); |
| 750 | // Snap forward off a UTF-8 continuation byte so the retained slice |
| 751 | // never begins mid-character (the leading-U+FFFD bug guarded against |
| 752 | // in `tail_from_buffer`). |
| 753 | while start < self.data.len() && (self.data[start] & 0xC0) == 0x80 { |
| 754 | start += 1; |
| 755 | } |
| 756 | self.data.drain(..start); |
| 757 | self.dropped = self.dropped.saturating_add(start); |
| 758 | } |
| 759 | } |
| 760 | |
| 761 | impl Default for RawOutputBuffer { |
| 762 | fn default() -> Self { |
| 763 | Self::new() |
| 764 | } |
| 765 | } |
| 766 | |
| 767 | pub(super) type SharedRawOutput = Arc<Mutex<RawOutputBuffer>>; |
| 768 | |
| 769 | #[cfg(any(test, feature = "test-support"))] |
| 770 | pub(super) fn new_shared_raw_output() -> SharedRawOutput { |
| 771 | Arc::new(Mutex::new(RawOutputBuffer::new())) |
| 772 | } |
| 773 | |
| 774 | pub(super) fn take_delta_from_buffer( |
| 775 | buffer: &SharedRawOutput, |
| 776 | cursor: &mut usize, |
| 777 | ) -> (Vec<u8>, usize) { |
| 778 | let guard = buffer.lock().unwrap_or_else(|e| e.into_inner()); |
| 779 | let total = guard.total_len(); |
| 780 | // The cursor is an absolute offset into the stream. Bytes the bound already |
| 781 | // discarded can never be delivered as a delta, so skip forward over them |
| 782 | // rather than re-sending the retained tail as if it were new. |
| 783 | let start_abs = (*cursor).max(guard.dropped()).min(total); |
| 784 | let start = start_abs - guard.dropped(); |
| 785 | let retained = guard.retained(); |
| 786 | // Clone only the unread portion (the delta), not the entire accumulated buffer. |
| 787 | // Long-running processes can produce megabytes of output; cloning the full |
| 788 | // buffer on every poll held the ShellManager mutex for O(total_bytes) time. |
| 789 | let unread = &retained[start..]; |
| 790 | // A poll can land mid-character: the caller decodes this delta as UTF-8, so |
| 791 | // handing back a truncated multibyte sequence renders it as replacement |
| 792 | // glyphs and corrupts the next delta's leading byte too (the streaming-client |
| 793 | // bug from #1675, in the shell preview path). Leave an incomplete trailing |
| 794 | // sequence in the buffer for the next poll. Bytes that are genuinely invalid |
| 795 | // rather than merely unfinished still pass through, so binary output cannot |
| 796 | // stall the cursor, and the final result is read from the whole buffer. |
| 797 | let consumed = match std::str::from_utf8(unread) { |
| 798 | Ok(_) => unread.len(), |
| 799 | Err(error) if error.error_len().is_none() => error.valid_up_to(), |
| 800 | Err(_) => unread.len(), |
| 801 | }; |
| 802 | let delta = unread[..consumed].to_vec(); |
| 803 | *cursor = start_abs + consumed; |
| 804 | (delta, total) |
| 805 | } |
| 806 | |
| 807 | /// Read only the tail of a byte buffer and return (total_len, tail_string). |
| 808 | /// |
| 809 | /// Avoids cloning the full buffer when only a trailing excerpt is needed |
| 810 | /// (e.g. for the job-panel display). `max_tail_chars` is in Unicode scalar |
| 811 | /// values; we read at most `max_tail_chars * 4` bytes from the end to account |
| 812 | /// for multi-byte UTF-8 sequences. |
| 813 | pub(super) fn tail_from_buffer(buffer: &SharedRawOutput, max_tail_chars: usize) -> (usize, String) { |
| 814 | let guard = buffer.lock().unwrap_or_else(|e| e.into_inner()); |
| 815 | // The reported length is the stream's total, not what is still held: a |
| 816 | // released or clipped buffer must not make the model believe the command |
| 817 | // printed less than it did. |
| 818 | let total = guard.total_len(); |
| 819 | let retained = guard.retained(); |
| 820 | let retained_len = retained.len(); |
| 821 | // Over-estimate byte count (4 bytes per char worst case for UTF-8). |
| 822 | let mut tail_start = retained_len.saturating_sub(max_tail_chars.saturating_mul(4)); |
| 823 | // Snap forward to the next valid UTF-8 codepoint boundary so we don't |
| 824 | // pass a slice beginning with continuation bytes (0x80-0xBF) to |
| 825 | // from_utf8_lossy, which would emit a leading U+FFFD replacement char. |
| 826 | while tail_start < retained_len && (retained[tail_start] & 0xC0) == 0x80 { |
| 827 | tail_start += 1; |
| 828 | } |
| 829 | let tail_str = String::from_utf8_lossy(&retained[tail_start..]).into_owned(); |
| 830 | (total, tail_text(&tail_str, max_tail_chars)) |
| 831 | } |
| 832 | |
| 833 | pub(super) fn tail_text(text: &str, max_chars: usize) -> String { |
| 834 | if text.chars().count() <= max_chars { |
| 835 | return text.to_string(); |
| 836 | } |
| 837 | let tail = text |
| 838 | .chars() |
| 839 | .rev() |
| 840 | .take(max_chars) |
| 841 | .collect::<Vec<_>>() |
| 842 | .into_iter() |
| 843 | .rev() |
| 844 | .collect::<String>(); |
| 845 | format!("...{tail}") |
| 846 | } |
| 847 | |
| 848 | #[cfg(test)] |
| 849 | mod tests { |
| 850 | use super::{ |
| 851 | BOUNDED_OUTPUT_MAX_BYTES, BOUNDED_OUTPUT_MAX_LINES, BOUNDED_OUTPUT_RETAIN_BYTES, |
| 852 | BoundedOutputAccumulator, RAW_STREAM_MAX_BYTES, RawOutputBuffer, SessionArtifactSpec, |
| 853 | SharedRawOutput, tail_from_buffer, take_delta_from_buffer, |
| 854 | }; |
| 855 | use std::path::PathBuf; |
| 856 | use std::sync::{Arc, Mutex}; |
| 857 | |
| 858 | struct TestArtifactRootGuard { |
| 859 | _lock: std::sync::MutexGuard<'static, ()>, |
| 860 | previous: Option<PathBuf>, |
| 861 | _dir: tempfile::TempDir, |
| 862 | } |
| 863 | |
| 864 | impl TestArtifactRootGuard { |
| 865 | fn new() -> Self { |
| 866 | let lock = codewhale_runtime::artifacts::TEST_ARTIFACT_SESSIONS_GUARD |
| 867 | .lock() |
| 868 | .unwrap_or_else(|error| error.into_inner()); |
| 869 | let dir = tempfile::tempdir().expect("tempdir"); |
| 870 | let previous = codewhale_runtime::artifacts::set_test_artifact_sessions_root(Some( |
| 871 | dir.path().join("sessions"), |
| 872 | )); |
| 873 | Self { |
| 874 | _lock: lock, |
| 875 | previous, |
| 876 | _dir: dir, |
| 877 | } |
| 878 | } |
| 879 | } |
| 880 | |
| 881 | impl Drop for TestArtifactRootGuard { |
| 882 | fn drop(&mut self) { |
| 883 | codewhale_runtime::artifacts::set_test_artifact_sessions_root(self.previous.take()); |
| 884 | } |
| 885 | } |
| 886 | |
| 887 | fn test_artifact_spec(name: &str) -> SessionArtifactSpec { |
| 888 | SessionArtifactSpec { |
| 889 | session_id: "session-test".to_string(), |
| 890 | artifact_id: codewhale_runtime::artifacts::artifact_id_for_tool_call(name), |
| 891 | } |
| 892 | } |
| 893 | |
| 894 | fn raw(bytes: &[u8]) -> SharedRawOutput { |
| 895 | let mut buffer = RawOutputBuffer::new(); |
| 896 | buffer.append(bytes); |
| 897 | Arc::new(Mutex::new(buffer)) |
| 898 | } |
| 899 | |
| 900 | fn append(buffer: &SharedRawOutput, bytes: &[u8]) { |
| 901 | buffer.lock().unwrap().append(bytes); |
| 902 | } |
| 903 | |
| 904 | #[test] |
| 905 | fn delta_holds_back_an_incomplete_trailing_utf8_sequence() { |
| 906 | // "宽" is three bytes; deliver two of them, then the rest. |
| 907 | let wide = "宽".as_bytes(); |
| 908 | let buffer = raw(b"ok "); |
| 909 | append(&buffer, &wide[..2]); |
| 910 | let mut cursor = 0usize; |
| 911 | |
| 912 | let (delta, total) = take_delta_from_buffer(&buffer, &mut cursor); |
| 913 | assert_eq!( |
| 914 | String::from_utf8(delta).expect("delta must be whole characters"), |
| 915 | "ok " |
| 916 | ); |
| 917 | assert_eq!(total, 5, "total still reports every buffered byte"); |
| 918 | assert_eq!(cursor, 3, "the split character stays unread"); |
| 919 | |
| 920 | append(&buffer, &wide[2..]); |
| 921 | let (delta, _) = take_delta_from_buffer(&buffer, &mut cursor); |
| 922 | assert_eq!( |
| 923 | String::from_utf8(delta).expect("delta must be whole characters"), |
| 924 | "宽" |
| 925 | ); |
| 926 | } |
| 927 | |
| 928 | #[test] |
| 929 | fn delta_does_not_stall_on_genuinely_invalid_bytes() { |
| 930 | // A lone 0xFF is never a valid start byte: passing it through keeps |
| 931 | // binary output flowing instead of parking the cursor forever. |
| 932 | let buffer = raw(&[b'a', 0xFF, b'b']); |
| 933 | let mut cursor = 0usize; |
| 934 | let (delta, total) = take_delta_from_buffer(&buffer, &mut cursor); |
| 935 | assert_eq!(delta, vec![b'a', 0xFF, b'b']); |
| 936 | assert_eq!(cursor, total); |
| 937 | } |
| 938 | |
| 939 | // === #5472: in-memory retention bounds for the raw `Bash` streams === |
| 940 | |
| 941 | #[test] |
| 942 | fn raw_buffer_caps_in_flight_bytes_and_keeps_the_total_honest() { |
| 943 | let mut buffer = RawOutputBuffer::with_cap(1_024); |
| 944 | // 4 MiB through a 1 KiB cap: the analogue of `cargo build -v` through |
| 945 | // the 16 MiB production ceiling. |
| 946 | for _ in 0..1_024 { |
| 947 | buffer.append(&[b'x'; 4_096]); |
| 948 | } |
| 949 | let produced = 1_024 * 4_096; |
| 950 | assert_eq!( |
| 951 | buffer.total_len(), |
| 952 | produced, |
| 953 | "the stream's length must survive the bound" |
| 954 | ); |
| 955 | assert_eq!(buffer.dropped(), produced - buffer.retained().len()); |
| 956 | assert!( |
| 957 | buffer.retained().len() <= 1_024 + 1_024 / 4, |
| 958 | "retained {} exceeded cap + slack", |
| 959 | buffer.retained().len() |
| 960 | ); |
| 961 | } |
| 962 | |
| 963 | #[test] |
| 964 | fn raw_buffer_release_collapses_to_a_tail_and_reports_the_omission() { |
| 965 | let mut buffer = RawOutputBuffer::new(); |
| 966 | buffer.append(&[b'y'; 200_000]); |
| 967 | assert_eq!(buffer.dropped(), 0, "200 KB is under the in-flight ceiling"); |
| 968 | |
| 969 | buffer.release_to_tail(1_000); |
| 970 | assert_eq!(buffer.retained().len(), 1_000); |
| 971 | assert_eq!(buffer.dropped(), 199_000); |
| 972 | assert_eq!( |
| 973 | buffer.total_len(), |
| 974 | 200_000, |
| 975 | "releasing memory must not rewrite how much the command printed" |
| 976 | ); |
| 977 | } |
| 978 | |
| 979 | #[test] |
| 980 | fn raw_buffer_never_retains_a_split_character() { |
| 981 | let mut buffer = RawOutputBuffer::with_cap(8); |
| 982 | // Each "宽" is 3 bytes, so a byte-exact tail would land mid-character. |
| 983 | for _ in 0..64 { |
| 984 | buffer.append("宽".as_bytes()); |
| 985 | } |
| 986 | assert!( |
| 987 | std::str::from_utf8(buffer.retained()).is_ok(), |
| 988 | "front-drop must snap off continuation bytes" |
| 989 | ); |
| 990 | |
| 991 | let mut released = RawOutputBuffer::new(); |
| 992 | for _ in 0..64 { |
| 993 | released.append("宽".as_bytes()); |
| 994 | } |
| 995 | released.release_to_tail(10); |
| 996 | assert!(std::str::from_utf8(released.retained()).is_ok()); |
| 997 | } |
| 998 | |
| 999 | #[test] |
| 1000 | fn delta_skips_bytes_the_bound_already_discarded() { |
| 1001 | // A consumer that stops reading while output keeps arriving must be |
| 1002 | // moved forward, not handed the retained tail as if it were new bytes. |
| 1003 | let buffer = Arc::new(Mutex::new(RawOutputBuffer::with_cap(16))); |
| 1004 | append(&buffer, b"first-chunk-that-will-be-dropped-entirely"); |
| 1005 | let mut cursor = 0usize; |
| 1006 | let (delta, total) = take_delta_from_buffer(&buffer, &mut cursor); |
| 1007 | let dropped = buffer.lock().unwrap().dropped(); |
| 1008 | assert!(dropped > 0, "the cap must have clipped the front"); |
| 1009 | assert_eq!(cursor, total, "cursor lands at the stream's true position"); |
| 1010 | assert_eq!( |
| 1011 | delta.len(), |
| 1012 | total - dropped, |
| 1013 | "only bytes still held can be delivered" |
| 1014 | ); |
| 1015 | |
| 1016 | append(&buffer, b"tail"); |
| 1017 | let (delta, _) = take_delta_from_buffer(&buffer, &mut cursor); |
| 1018 | assert_eq!( |
| 1019 | delta, |
| 1020 | b"tail".to_vec(), |
| 1021 | "subsequent deltas continue from the corrected cursor" |
| 1022 | ); |
| 1023 | } |
| 1024 | |
| 1025 | #[test] |
| 1026 | fn tail_reports_the_stream_total_not_the_retained_length() { |
| 1027 | let buffer = Arc::new(Mutex::new(RawOutputBuffer::new())); |
| 1028 | append(&buffer, b"abcdefghij"); |
| 1029 | buffer.lock().unwrap().release_to_tail(4); |
| 1030 | let (total, tail) = tail_from_buffer(&buffer, 100); |
| 1031 | assert_eq!(total, 10, "stdout_len must not shrink when memory is freed"); |
| 1032 | assert_eq!(tail, "ghij"); |
| 1033 | } |
| 1034 | |
| 1035 | #[test] |
| 1036 | fn abandoning_a_stream_releases_it_and_stops_the_reader() { |
| 1037 | let mut buffer = RawOutputBuffer::new(); |
| 1038 | assert!(buffer.append(&[b'a'; 5_000]), "a live stream keeps reading"); |
| 1039 | buffer.abandon(); |
| 1040 | |
| 1041 | assert_eq!(buffer.retained().len(), 0, "held bytes are released"); |
| 1042 | assert_eq!( |
| 1043 | buffer.total_len(), |
| 1044 | 5_000, |
| 1045 | "the stream's length survives the release" |
| 1046 | ); |
| 1047 | assert!( |
| 1048 | !buffer.append(&[b'b'; 100]), |
| 1049 | "an abandoned stream tells the reader thread to exit" |
| 1050 | ); |
| 1051 | assert_eq!(buffer.retained().len(), 0, "and retains nothing further"); |
| 1052 | assert_eq!( |
| 1053 | buffer.total_len(), |
| 1054 | 5_100, |
| 1055 | "bytes that arrive after the give-up are still counted, not hidden" |
| 1056 | ); |
| 1057 | } |
| 1058 | |
| 1059 | #[test] |
| 1060 | fn raw_stream_ceiling_clears_every_downstream_bound() { |
| 1061 | // The clip must be unreachable by the model-visible surfaces: the 30 KB |
| 1062 | // result truncation, the 1,200-char job tail, the 1 KiB completion tail. |
| 1063 | const { assert!(RAW_STREAM_MAX_BYTES > 30_000 * 100) }; |
| 1064 | const { assert!(super::RAW_STREAM_SETTLED_TAIL_BYTES > 30_000) }; |
| 1065 | } |
| 1066 | |
| 1067 | #[test] |
| 1068 | fn bounded_output_keeps_last_two_thousand_complete_lines() { |
| 1069 | let _root = TestArtifactRootGuard::new(); |
| 1070 | let source = (0..=BOUNDED_OUTPUT_MAX_LINES) |
| 1071 | .map(|index| format!("line-{index}")) |
| 1072 | .collect::<Vec<_>>() |
| 1073 | .join("\n"); |
| 1074 | let mut output = |
| 1075 | BoundedOutputAccumulator::new_in(None, Some(test_artifact_spec("lines-2001"))); |
| 1076 | output.append(source.as_bytes()).expect("append"); |
| 1077 | output.finish().expect("finish"); |
| 1078 | let snapshot = output.snapshot(true).expect("snapshot"); |
| 1079 | assert!(snapshot.truncated); |
| 1080 | assert!(snapshot.content.starts_with("line-1\n")); |
| 1081 | assert!(snapshot.content.contains("Showing lines 2-401 of 401")); |
| 1082 | assert!(snapshot.content.contains("retrieve_tool_result")); |
| 1083 | assert!(!snapshot.content.contains("codewhale-bash-")); |
| 1084 | let artifact = snapshot.persisted_artifact.expect("session artifact"); |
| 1085 | assert_eq!(artifact.artifact_id, "art_lines-2001"); |
| 1086 | assert_eq!( |
| 1087 | std::fs::read(&artifact.absolute_path).expect("read artifact"), |
| 1088 | source.as_bytes() |
| 1089 | ); |
| 1090 | } |
| 1091 | |
| 1092 | #[test] |
| 1093 | fn bounded_output_streams_raw_full_output_and_bounds_decoded_tail() { |
| 1094 | let _root = TestArtifactRootGuard::new(); |
| 1095 | let raw = vec![0xFF; 2 * 1024 * 1024]; |
| 1096 | let mut output = |
| 1097 | BoundedOutputAccumulator::new_in(None, Some(test_artifact_spec("raw-2mb"))); |
| 1098 | let scratch_path = output |
| 1099 | .temp |
| 1100 | .as_ref() |
| 1101 | .expect("scratch temp") |
| 1102 | .path() |
| 1103 | .to_path_buf(); |
| 1104 | for chunk in raw.chunks(4_096) { |
| 1105 | output.append(chunk).expect("append"); |
| 1106 | assert!(output.retained_memory_bytes() <= BOUNDED_OUTPUT_MAX_BYTES + 4); |
| 1107 | } |
| 1108 | output.finish().expect("finish"); |
| 1109 | let snapshot = output.snapshot(true).expect("snapshot"); |
| 1110 | assert!(snapshot.truncated); |
| 1111 | assert!(snapshot.retained_bytes <= BOUNDED_OUTPUT_MAX_BYTES); |
| 1112 | assert!(snapshot.content.contains('\u{FFFD}')); |
| 1113 | assert!(!scratch_path.exists()); |
| 1114 | let artifact = snapshot.persisted_artifact.expect("session artifact"); |
| 1115 | assert_eq!( |
| 1116 | std::fs::read(&artifact.absolute_path).expect("read full output"), |
| 1117 | raw |
| 1118 | ); |
| 1119 | } |
| 1120 | |
| 1121 | #[test] |
| 1122 | fn bounded_output_delta_since_returns_only_new_bytes() { |
| 1123 | let mut output = BoundedOutputAccumulator::new_in(None, None); |
| 1124 | output.append(b"first\n").expect("append"); |
| 1125 | let cursor = output.total_bytes(); |
| 1126 | assert_eq!(output.delta_since(0).expect("delta").0, "first\n"); |
| 1127 | output.append(b"second\n").expect("append"); |
| 1128 | assert_eq!( |
| 1129 | output.delta_since(cursor).expect("delta"), |
| 1130 | ("second\n".to_string(), 0) |
| 1131 | ); |
| 1132 | assert_eq!( |
| 1133 | output.delta_since(output.total_bytes()).expect("delta"), |
| 1134 | (String::new(), 0) |
| 1135 | ); |
| 1136 | |
| 1137 | let mut output = BoundedOutputAccumulator::new_in(None, None); |
| 1138 | output.append(b"a").expect("append"); |
| 1139 | output |
| 1140 | .append("é".repeat(BOUNDED_OUTPUT_MAX_BYTES).as_bytes()) |
| 1141 | .expect("append"); |
| 1142 | let total = output.total_bytes(); |
| 1143 | let (delta, omitted) = output.delta_since(0).expect("delta"); |
| 1144 | assert!(!delta.contains('\u{FFFD}')); |
| 1145 | assert_eq!(delta.len() + omitted, total); |
| 1146 | assert!(delta.len() <= BOUNDED_OUTPUT_RETAIN_BYTES); |
| 1147 | } |
| 1148 | |
| 1149 | #[test] |
| 1150 | fn bounded_output_omitted_notice_names_session_artifact_not_temp_path() { |
| 1151 | let _root = TestArtifactRootGuard::new(); |
| 1152 | let mut output = |
| 1153 | BoundedOutputAccumulator::new_in(None, Some(test_artifact_spec("omitted-delta"))); |
| 1154 | let notice = output.omitted_notice(42); |
| 1155 | assert!(notice.starts_with("[42 bytes"), "{notice}"); |
| 1156 | assert!(notice.contains("session artifact"), "{notice}"); |
| 1157 | assert!(!notice.contains("codewhale-bash-"), "{notice}"); |
| 1158 | |
| 1159 | output.append(b"payload").expect("append"); |
| 1160 | output.finish().expect("finish"); |
| 1161 | let finished_notice = output.omitted_notice(42); |
| 1162 | assert!( |
| 1163 | finished_notice.contains("art_omitted-delta"), |
| 1164 | "{finished_notice}" |
| 1165 | ); |
| 1166 | assert!( |
| 1167 | finished_notice.contains("retrieve_tool_result"), |
| 1168 | "{finished_notice}" |
| 1169 | ); |
| 1170 | assert!( |
| 1171 | !finished_notice.contains("codewhale-bash-"), |
| 1172 | "{finished_notice}" |
| 1173 | ); |
| 1174 | |
| 1175 | let missing = tempfile::tempdir().expect("tempdir").path().join("gone"); |
| 1176 | let mut unspilled = |
| 1177 | BoundedOutputAccumulator::new_in(Some(&missing), Some(test_artifact_spec("unspilled"))); |
| 1178 | let notice = unspilled.omitted_notice(7); |
| 1179 | assert!(notice.contains("not persisted"), "{notice}"); |
| 1180 | } |
| 1181 | |
| 1182 | #[test] |
| 1183 | fn bounded_output_huge_terminal_line_matches_upstream_notice() { |
| 1184 | let _root = TestArtifactRootGuard::new(); |
| 1185 | let mut source = vec![b'x'; BOUNDED_OUTPUT_MAX_BYTES + 1_024]; |
| 1186 | source.push(b'\n'); |
| 1187 | let mut output = |
| 1188 | BoundedOutputAccumulator::new_in(None, Some(test_artifact_spec("huge-line"))); |
| 1189 | output.append(&source).expect("append"); |
| 1190 | output.finish().expect("finish"); |
| 1191 | let snapshot = output.snapshot(true).expect("snapshot"); |
| 1192 | assert!(snapshot.content.contains("Showing last 16.0KB of line 1")); |
| 1193 | assert!(snapshot.content.contains("line is 0B")); |
| 1194 | assert!(snapshot.content.contains("art_huge-line")); |
| 1195 | assert!(snapshot.content.contains("retrieve_tool_result")); |
| 1196 | assert!(!snapshot.content.contains("codewhale-bash-")); |
| 1197 | let artifact = snapshot.persisted_artifact.expect("session artifact"); |
| 1198 | assert_eq!( |
| 1199 | std::fs::read(&artifact.absolute_path).expect("read artifact"), |
| 1200 | source |
| 1201 | ); |
| 1202 | } |
| 1203 | |
| 1204 | #[test] |
| 1205 | fn unclosed_stream_overflow_returns_tail_instead_of_error() { |
| 1206 | let _root = TestArtifactRootGuard::new(); |
| 1207 | let source = (0..=BOUNDED_OUTPUT_MAX_LINES) |
| 1208 | .map(|index| format!("line-{index}")) |
| 1209 | .collect::<Vec<_>>() |
| 1210 | .join("\n"); |
| 1211 | let mut output = |
| 1212 | BoundedOutputAccumulator::new_in(None, Some(test_artifact_spec("unclosed"))); |
| 1213 | output.append(source.as_bytes()).expect("append"); |
| 1214 | let snapshot = output |
| 1215 | .snapshot(true) |
| 1216 | .expect("unclosed stream still yields output"); |
| 1217 | assert!(snapshot.truncated); |
| 1218 | assert!(snapshot.persisted_artifact.is_none()); |
| 1219 | assert!( |
| 1220 | snapshot.content.contains("Full output was not persisted"), |
| 1221 | "{}", |
| 1222 | snapshot.content |
| 1223 | ); |
| 1224 | } |
| 1225 | |
| 1226 | #[test] |
| 1227 | fn spill_failure_is_soft_and_names_the_reason() { |
| 1228 | let missing = |
| 1229 | std::env::temp_dir().join(format!("codewhale-missing-spill-{}", std::process::id())); |
| 1230 | let mut output = |
| 1231 | BoundedOutputAccumulator::new_in(Some(&missing), Some(test_artifact_spec("missing-1"))); |
| 1232 | let reason = output.spill_unavailable().expect("spill unavailable"); |
| 1233 | assert!(!reason.is_empty(), "reason must name the io error"); |
| 1234 | |
| 1235 | output.append(b"ok\n").expect("append works without spill"); |
| 1236 | output.finish().expect("finish works without spill"); |
| 1237 | let short = output.snapshot(true).expect("snapshot"); |
| 1238 | assert_eq!(short.content, "ok\n"); |
| 1239 | assert!(!short.truncated); |
| 1240 | assert!(short.persisted_artifact.is_none()); |
| 1241 | |
| 1242 | let source = (0..=BOUNDED_OUTPUT_MAX_LINES) |
| 1243 | .map(|index| format!("line-{index}")) |
| 1244 | .collect::<Vec<_>>() |
| 1245 | .join("\n"); |
| 1246 | let mut output = |
| 1247 | BoundedOutputAccumulator::new_in(Some(&missing), Some(test_artifact_spec("missing-2"))); |
| 1248 | output.append(source.as_bytes()).expect("append"); |
| 1249 | output.finish().expect("finish"); |
| 1250 | let snapshot = output.snapshot(true).expect("snapshot"); |
| 1251 | assert!(snapshot.truncated); |
| 1252 | assert!(snapshot.content.starts_with("line-1\n")); |
| 1253 | assert!( |
| 1254 | snapshot.content.contains("Full output was not persisted:"), |
| 1255 | "{}", |
| 1256 | snapshot.content |
| 1257 | ); |
| 1258 | assert!(!snapshot.content.contains("Full output: ")); |
| 1259 | assert!(snapshot.persisted_artifact.is_none()); |
| 1260 | } |
| 1261 | |
| 1262 | #[test] |
| 1263 | fn resource_exhaustion_hint_names_disk_descriptors_and_memory() { |
| 1264 | use std::io::{Error, ErrorKind}; |
| 1265 | assert!( |
| 1266 | super::resource_exhaustion_hint(&Error::from(ErrorKind::StorageFull)) |
| 1267 | .expect("storage full") |
| 1268 | .contains("disk") |
| 1269 | ); |
| 1270 | assert!( |
| 1271 | super::resource_exhaustion_hint(&Error::from(ErrorKind::OutOfMemory)) |
| 1272 | .expect("oom") |
| 1273 | .contains("memory") |
| 1274 | ); |
| 1275 | #[cfg(unix)] |
| 1276 | { |
| 1277 | assert!( |
| 1278 | super::resource_exhaustion_hint(&Error::from_raw_os_error(libc::ENOSPC)) |
| 1279 | .expect("enospc") |
| 1280 | .contains("disk") |
| 1281 | ); |
| 1282 | assert!( |
| 1283 | super::resource_exhaustion_hint(&Error::from_raw_os_error(libc::EMFILE)) |
| 1284 | .expect("emfile") |
| 1285 | .contains("file descriptors") |
| 1286 | ); |
| 1287 | assert!( |
| 1288 | super::resource_exhaustion_hint(&Error::from_raw_os_error(libc::EAGAIN)) |
| 1289 | .expect("eagain") |
| 1290 | .contains("retry") |
| 1291 | ); |
| 1292 | } |
| 1293 | assert!(super::resource_exhaustion_hint(&Error::from(ErrorKind::NotFound)).is_none()); |
| 1294 | assert!( |
| 1295 | super::resource_exhaustion_hint(&Error::from(ErrorKind::PermissionDenied)).is_none() |
| 1296 | ); |
| 1297 | } |
| 1298 | } |
| 1299 |