1use std::collections::{BTreeMap, VecDeque};
22use std::io::{self, Write};
23use std::path::{Path, PathBuf};
24use std::sync::{
25 atomic::{AtomicBool, Ordering},
26 Arc, Mutex,
27};
28use std::time::{SystemTime, UNIX_EPOCH};
29
30use tokio::io::AsyncReadExt;
31
32pub const DEFAULT_MAX_LINE_BYTES: usize = 2048;
39
40pub const DEFAULT_MAX_LINES: usize = 200;
42
43pub const DEFAULT_MAX_BYTES: usize = 64 * 1024;
49
50#[derive(Debug, Clone, PartialEq, Eq)]
58pub enum CaptureState {
59 Captured,
61 Incomplete { reason: String },
66 NotCaptured { reason: String },
68}
69
70#[derive(Debug, Clone, PartialEq, Eq)]
77pub enum TailEntry {
78 Line {
79 text: String,
80 truncated: bool,
82 at_ms: Option<u64>,
86 },
87 ProcessStart,
90}
91
92impl TailEntry {
93 fn cost(&self) -> usize {
94 match self {
95 Self::Line { text, .. } => text.len(),
96 Self::ProcessStart => 0,
97 }
98 }
99}
100
101#[derive(Debug, Clone, PartialEq, Eq)]
106enum Slot {
107 Line {
108 text: String,
109 truncated: bool,
110 at_ms: Option<u64>,
111 },
112 ProcessStart {
113 generation: u64,
114 },
115}
116
117impl Slot {
118 fn cost(&self) -> usize {
119 match self {
120 Self::Line { text, .. } => text.len(),
121 Self::ProcessStart { .. } => 0,
122 }
123 }
124}
125
126#[derive(Debug, Clone, PartialEq, Eq)]
128enum PumpPhase {
129 Attached,
131 Retired,
134 Late { reason: String },
137}
138
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140pub struct StderrTailConfig {
141 max_lines: usize,
142 max_bytes: usize,
143 max_line_bytes: usize,
144}
145
146impl StderrTailConfig {
147 pub const fn new(max_lines: usize, max_bytes: usize, max_line_bytes: usize) -> Self {
150 Self {
151 max_lines,
152 max_bytes,
153 max_line_bytes: if max_line_bytes > max_bytes {
154 max_bytes
155 } else {
156 max_line_bytes
157 },
158 }
159 }
160}
161
162impl Default for StderrTailConfig {
163 fn default() -> Self {
164 Self::new(DEFAULT_MAX_LINES, DEFAULT_MAX_BYTES, DEFAULT_MAX_LINE_BYTES)
165 }
166}
167
168#[derive(Debug, Clone, PartialEq, Eq)]
170pub struct StderrTailSnapshot {
171 pub capture: CaptureState,
172 pub entries: Vec<TailEntry>,
173 pub dropped_lines: u64,
180}
181
182impl StderrTailSnapshot {
183 pub fn not_captured(reason: impl Into<String>) -> Self {
185 Self {
186 capture: CaptureState::NotCaptured {
187 reason: reason.into(),
188 },
189 entries: Vec::new(),
190 dropped_lines: 0,
191 }
192 }
193}
194
195#[derive(Debug)]
208pub struct StderrRing {
209 config: StderrTailConfig,
210 entries: VecDeque<Slot>,
211 lines: usize,
215 bytes: usize,
216 dropped_lines: u64,
217 capture: CaptureState,
218 incomplete: BTreeMap<u64, String>,
221 generation: u64,
223 pumps: BTreeMap<u64, PumpPhase>,
225 evicted_through: u64,
229}
230
231impl StderrRing {
232 pub fn new(config: StderrTailConfig) -> Self {
233 Self {
234 config,
235 entries: VecDeque::new(),
236 lines: 0,
237 bytes: 0,
238 dropped_lines: 0,
239 capture: CaptureState::NotCaptured {
242 reason: "stderr reader has not started".to_string(),
243 },
244 generation: 0,
245 pumps: BTreeMap::new(),
246 incomplete: BTreeMap::new(),
247 evicted_through: 0,
248 }
249 }
250
251 pub fn generation(&self) -> u64 {
253 self.generation
254 }
255
256 pub fn mark_captured(&mut self) {
257 if matches!(self.capture, CaptureState::NotCaptured { .. }) {
258 self.capture = CaptureState::Captured;
259 }
260 }
261
262 pub fn mark_incomplete(&mut self, reason: impl Into<String>) {
263 self.mark_captured();
264 self.mark_incomplete_from(self.generation, reason);
265 }
266
267 pub(crate) fn mark_incomplete_from(&mut self, generation: u64, reason: impl Into<String>) {
268 let oldest_retained = match self.entries.front() {
269 Some(Slot::ProcessStart { generation }) => *generation,
270 Some(Slot::Line { .. }) => self.evicted_through,
271 None => self.generation,
272 };
273 if generation >= oldest_retained {
274 self.incomplete.insert(generation, reason.into());
275 }
276 }
277
278 pub fn mark_not_captured(&mut self, reason: impl Into<String>) {
279 self.capture = CaptureState::NotCaptured {
280 reason: reason.into(),
281 };
282 }
283
284 pub fn push_process_start(&mut self) -> u64 {
296 self.generation += 1;
297 let generation = self.generation;
298 if let Some(Slot::ProcessStart {
304 generation: previous,
305 }) = self.entries.back()
306 {
307 if self.pumps.range(*previous..).next().is_none() {
308 self.entries.pop_back();
309 }
310 }
311 self.push_entry(Slot::ProcessStart { generation });
312 generation
313 }
314
315 pub(crate) fn begin_process(&mut self) -> u64 {
318 let generation = self.push_process_start();
319 self.pumps.insert(generation, PumpPhase::Attached);
320 generation
321 }
322
323 pub(crate) fn retire_pump(&mut self, generation: u64) {
326 if let Some(phase @ PumpPhase::Attached) = self.pumps.get_mut(&generation) {
327 *phase = PumpPhase::Retired;
328 }
329 }
330
331 pub(crate) fn mark_pump_late(&mut self, generation: u64, reason: impl Into<String>) {
336 if let Some(phase) = self.pumps.get_mut(&generation) {
337 *phase = PumpPhase::Late {
338 reason: reason.into(),
339 };
340 }
341 }
342
343 pub(crate) fn finish_pump(&mut self, generation: u64) {
346 self.pumps.remove(&generation);
347 }
348
349 pub fn push_line(&mut self, line: &str) {
356 self.push_line_from(self.generation, line);
357 }
358
359 pub(crate) fn push_line_from(&mut self, generation: u64, line: &str) {
361 self.admit_line(generation, line, None);
362 }
363
364 pub(crate) fn push_line_from_at(&mut self, generation: u64, line: &str, at_ms: u64) {
367 self.admit_line(generation, line, Some(at_ms));
368 }
369
370 fn admit_line(&mut self, generation: u64, line: &str, at_ms: Option<u64>) {
375 let (text, truncated) = truncate_line(line, self.config.max_line_bytes);
376 let slot = Slot::Line {
377 text,
378 truncated,
379 at_ms,
380 };
381 let retired = matches!(
382 self.pumps.get(&generation),
383 Some(PumpPhase::Retired | PumpPhase::Late { .. })
384 );
385 if !retired || generation >= self.generation {
386 self.push_entry(slot);
387 return;
388 }
389 if self.evicted_through > generation {
390 self.dropped_lines += 1;
393 return;
394 }
395 let index = self.entries.iter().position(
396 |slot| matches!(slot, Slot::ProcessStart { generation: start } if *start > generation),
397 );
398 match index {
399 Some(index) => self.insert_entry(index, slot),
400 None => self.push_entry(slot),
401 }
402 }
403
404 fn push_entry(&mut self, entry: Slot) {
405 self.insert_entry(self.entries.len(), entry);
406 }
407
408 fn insert_entry(&mut self, index: usize, entry: Slot) {
409 self.bytes += entry.cost();
410 if matches!(entry, Slot::Line { .. }) {
411 self.lines += 1;
412 }
413 self.entries.insert(index, entry);
414 self.evict_to_fit();
415 }
416
417 fn evict_to_fit(&mut self) {
418 while self.lines > self.config.max_lines
419 || (self.bytes > self.config.max_bytes && self.entries.len() > 1)
420 {
421 let Some(evicted) = self.entries.pop_front() else {
422 break;
423 };
424 self.bytes -= evicted.cost();
425 match evicted {
426 Slot::Line { .. } => {
427 self.lines -= 1;
428 self.dropped_lines += 1;
429 }
430 Slot::ProcessStart { generation } => {
431 self.evicted_through = self.evicted_through.max(generation);
432 }
433 }
434 }
435 let oldest_retained = match self.entries.front() {
436 Some(Slot::ProcessStart { generation }) => *generation,
437 Some(Slot::Line { .. }) => self.evicted_through,
438 None => self.generation,
439 };
440 self.incomplete
441 .retain(|generation, _| *generation >= oldest_retained);
442 }
443
444 pub fn snapshot(
448 &self,
449 max_lines: Option<usize>,
450 max_bytes: Option<usize>,
451 ) -> StderrTailSnapshot {
452 let line_limit = max_lines.unwrap_or(self.config.max_lines);
453 let byte_limit = max_bytes.unwrap_or(self.config.max_bytes);
454
455 let mut visible: Vec<TailEntry> = Vec::with_capacity(self.entries.len());
459 let mut output_before = self.dropped_lines > 0;
460 for slot in &self.entries {
461 match slot {
462 Slot::Line {
463 text,
464 truncated,
465 at_ms,
466 } => {
467 visible.push(TailEntry::Line {
468 text: text.clone(),
469 truncated: *truncated,
470 at_ms: *at_ms,
471 });
472 output_before = true;
473 }
474 Slot::ProcessStart { .. } => {
475 if output_before && !matches!(visible.last(), Some(TailEntry::ProcessStart)) {
476 visible.push(TailEntry::ProcessStart);
477 }
478 }
479 }
480 }
481
482 let mut taken: Vec<TailEntry> = Vec::new();
483 let mut bytes = 0usize;
484 let mut lines = 0usize;
485 for entry in visible.iter().rev() {
488 match entry {
489 TailEntry::Line { .. } => {
490 if lines >= line_limit {
491 break;
492 }
493 let cost = entry.cost();
494 if lines > 0 && bytes + cost > byte_limit {
495 break;
496 }
497 bytes += cost;
498 lines += 1;
499 taken.push(entry.clone());
500 }
501 TailEntry::ProcessStart if lines > 0 => taken.push(entry.clone()),
502 TailEntry::ProcessStart => {}
503 }
504 }
505 taken.reverse();
506
507 let withheld = self.lines.saturating_sub(lines);
508
509 let late = self.pumps.values().find_map(|phase| match phase {
515 PumpPhase::Late { reason } => Some(reason),
516 _ => None,
517 });
518 let incomplete = self.incomplete.values().next().or(late);
519 let capture = match (&self.capture, incomplete) {
520 (CaptureState::Captured, Some(reason)) => CaptureState::Incomplete {
521 reason: reason.clone(),
522 },
523 (capture, _) => capture.clone(),
524 };
525
526 StderrTailSnapshot {
527 capture,
528 entries: taken,
529 dropped_lines: self.dropped_lines + withheld as u64,
534 }
535 }
536}
537
538const MAX_PENDING_LINE_BYTES: usize = 1024 * 1024;
547
548pub async fn pump_stderr<R>(source: R, ring: Arc<Mutex<StderrRing>>)
551where
552 R: AsyncReadExt + Unpin,
553{
554 pump_stderr_into(source, ring, &mut StderrSink).await
555}
556
557#[derive(Clone)]
564pub(crate) enum ChildOutputSink {
565 File {
566 sink: Arc<Mutex<cortexkit_log::LineSink>>,
567 path: Arc<PathBuf>,
568 failure_reported: Arc<AtomicBool>,
569 },
570 Stderr,
571}
572
573impl ChildOutputSink {
574 pub(crate) fn open(path: &Path, retention: cortexkit_log::Retention) -> io::Result<Self> {
575 Ok(Self::File {
576 sink: Arc::new(Mutex::new(cortexkit_log::LineSink::open(path, retention)?)),
577 path: Arc::new(path.to_path_buf()),
578 failure_reported: Arc::new(AtomicBool::new(false)),
579 })
580 }
581}
582
583pub trait OutputSink {
586 fn write_line(&mut self, line: &[u8]);
587
588 fn stamps_lines(&self) -> bool {
597 false
598 }
599}
600
601struct StderrSink;
602
603impl OutputSink for StderrSink {
604 fn write_line(&mut self, line: &[u8]) {
605 let stderr = std::io::stderr();
606 let mut handle = stderr.lock();
607 let _ = handle.write_all(line);
608 }
609}
610
611impl OutputSink for ChildOutputSink {
612 fn write_line(&mut self, line: &[u8]) {
613 match self {
614 Self::File {
615 sink,
616 path,
617 failure_reported,
618 } => {
619 let result = sink
620 .lock()
621 .unwrap_or_else(|poisoned| poisoned.into_inner())
622 .write_line(line);
623 if let Err(error) = result {
624 if !failure_reported.swap(true, Ordering::Relaxed) {
625 tracing::warn!(
626 path = %path.display(),
627 error = %error,
628 "child output capture write failed; later failures are suppressed"
629 );
630 }
631 }
632 }
633 Self::Stderr => StderrSink.write_line(line),
634 }
635 }
636
637 fn stamps_lines(&self) -> bool {
644 matches!(self, Self::File { .. })
645 }
646}
647
648#[cfg(test)]
652pub(crate) async fn pump_stderr_to<R, S>(
653 source: R,
654 ring: Arc<Mutex<StderrRing>>,
655 generation: u64,
656 mut sink: S,
657) where
658 R: AsyncReadExt + Unpin,
659 S: OutputSink,
660{
661 pump_lines_into(source, Some((&ring, generation)), &mut sink, "stderr").await;
662}
663
664#[cfg(test)]
665pub(crate) async fn pump_stdout_to<R>(source: R, mut sink: ChildOutputSink)
666where
667 R: AsyncReadExt + Unpin,
668{
669 pump_lines_into(source, None, &mut sink, "stdout").await;
670}
671
672async fn pump_stderr_into<R, S>(source: R, ring: Arc<Mutex<StderrRing>>, sink: &mut S)
675where
676 R: AsyncReadExt + Unpin,
677 S: OutputSink,
678{
679 let generation = lock_ring(&ring).generation();
680 pump_lines_into(source, Some((&ring, generation)), sink, "stderr").await;
681}
682
683async fn pump_lines_into<R, S>(
684 mut source: R,
685 ring: Option<(&Arc<Mutex<StderrRing>>, u64)>,
686 sink: &mut S,
687 stream_name: &str,
688) where
689 R: AsyncReadExt + Unpin,
690 S: OutputSink,
691{
692 if let Some((ring, _)) = ring {
693 lock_ring(ring).mark_captured();
694 }
695
696 let mut framer = LineFramer::default();
697 let mut chunk = [0u8; 8192];
698 loop {
699 let read = match source.read(&mut chunk).await {
700 Ok(0) => break,
701 Ok(n) => n,
702 Err(error) => {
703 if let Some((ring, generation)) = ring {
704 let mut ring = lock_ring(ring);
705 ring.mark_incomplete_from(
706 generation,
707 format!("{stream_name} read failed: {error}"),
708 );
709 ring.finish_pump(generation);
710 } else {
711 tracing::warn!(stream = stream_name, error = %error, "child output capture read failed");
712 }
713 return;
714 }
715 };
716 framer.push(&chunk[..read], |raw, terminated| {
717 emit_line(ring, sink, raw, terminated)
718 });
719 }
720
721 framer.finish(|raw, terminated| emit_line(ring, sink, raw, terminated));
722 if let Some((ring, generation)) = ring {
723 lock_ring(ring).finish_pump(generation);
724 }
725}
726
727#[derive(Default)]
728pub(crate) struct LineFramer {
729 pending: Vec<u8>,
731}
732
733impl LineFramer {
734 pub(crate) fn push(&mut self, chunk: &[u8], mut emit: impl FnMut(&[u8], bool)) {
735 let pending = &mut self.pending;
736 let mut scanned_upto = pending.len();
737 pending.extend_from_slice(chunk);
738 let mut cursor = 0;
739 while let Some(relative) = find_newline(&pending[scanned_upto..]) {
740 let newline = scanned_upto + relative;
741 emit(&pending[cursor..newline], true);
742 cursor = newline + 1;
743 scanned_upto = cursor;
744 }
745 pending.drain(..cursor);
746 if pending.len() >= MAX_PENDING_LINE_BYTES {
747 emit(&std::mem::take(pending), false);
748 }
749 }
750
751 pub(crate) fn finish(self, mut emit: impl FnMut(&[u8], bool)) {
752 if !self.pending.is_empty() {
753 emit(&self.pending, false);
754 }
755 }
756}
757
758#[cfg(test)]
766thread_local! {
767 static SCANNED_BYTES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
768}
769
770#[cfg(test)]
771fn take_scanned_bytes() -> usize {
772 SCANNED_BYTES.with(|scanned| scanned.replace(0))
773}
774
775fn find_newline(haystack: &[u8]) -> Option<usize> {
778 let found = memchr::memchr(b'\n', haystack);
779 #[cfg(test)]
780 SCANNED_BYTES.with(|scanned| {
781 scanned.set(scanned.get() + found.map(|index| index + 1).unwrap_or(haystack.len()));
782 });
783 found
784}
785
786fn emit_line<S: OutputSink>(
787 ring: Option<(&Arc<Mutex<StderrRing>>, u64)>,
788 sink: &mut S,
789 raw: &[u8],
790 terminated: bool,
791) {
792 write_captured_line(ring, sink, raw, terminated, unix_ms(SystemTime::now()));
798}
799
800pub(crate) fn write_captured_line<S: OutputSink>(
801 ring: Option<(&Arc<Mutex<StderrRing>>, u64)>,
802 sink: &mut S,
803 raw: &[u8],
804 terminated: bool,
805 at_ms: u64,
806) {
807 if let Some((ring, generation)) = ring {
808 lock_ring(ring).push_line_from_at(generation, &String::from_utf8_lossy(raw), at_ms);
809 }
810
811 let stamp = sink.stamps_lines().then(|| format_capture_stamp(at_ms));
814 if stamp.is_none() && !terminated {
815 sink.write_line(raw);
816 return;
817 }
818 let mut framed = Vec::with_capacity(CAPTURE_STAMP_PREFIX_LEN + raw.len() + 1);
819 if let Some(stamp) = stamp {
820 framed.extend_from_slice(stamp.as_bytes());
821 framed.push(b' ');
822 }
823 framed.extend_from_slice(raw);
824 if terminated {
825 framed.push(b'\n');
826 }
827 sink.write_line(&framed);
828}
829
830pub(crate) fn unix_ms(at: SystemTime) -> u64 {
831 at.duration_since(UNIX_EPOCH)
834 .map(|since| u64::try_from(since.as_millis()).unwrap_or(u64::MAX))
835 .unwrap_or(0)
836}
837
838pub const CAPTURE_STAMP_LEN: usize = 24;
840
841pub const CAPTURE_STAMP_PREFIX_LEN: usize = CAPTURE_STAMP_LEN + 1;
843
844pub fn format_capture_stamp(at_ms: u64) -> String {
849 let seconds = at_ms / 1000;
850 let millis = at_ms % 1000;
851 let days = seconds / 86_400;
852 let of_day = seconds % 86_400;
853 let (year, month, day) = civil_from_days(days);
854 format!(
855 "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{millis:03}Z",
856 of_day / 3600,
857 (of_day % 3600) / 60,
858 of_day % 60,
859 )
860}
861
862pub fn split_capture_stamp(line: &str) -> Option<(u64, &str)> {
869 let bytes = line.as_bytes();
870 if bytes.len() < CAPTURE_STAMP_PREFIX_LEN || bytes[CAPTURE_STAMP_LEN] != b' ' {
871 return None;
872 }
873 let stamp = &bytes[..CAPTURE_STAMP_LEN];
874 for (index, expected) in [
875 (4, b'-'),
876 (7, b'-'),
877 (10, b'T'),
878 (13, b':'),
879 (16, b':'),
880 (19, b'.'),
881 (23, b'Z'),
882 ] {
883 if stamp[index] != expected {
884 return None;
885 }
886 }
887 let number = |from: usize, to: usize| -> Option<u64> {
888 let digits = &stamp[from..to];
889 if !digits.iter().all(u8::is_ascii_digit) {
890 return None;
891 }
892 Some(
893 digits
894 .iter()
895 .fold(0u64, |total, digit| total * 10 + u64::from(digit - b'0')),
896 )
897 };
898 let year = number(0, 4)?;
899 let month = number(5, 7)?;
900 let day = number(8, 10)?;
901 let hour = number(11, 13)?;
902 let minute = number(14, 16)?;
903 let second = number(17, 19)?;
904 let millis = number(20, 23)?;
905 if year < 1970
906 || !(1..=12).contains(&month)
907 || day == 0
908 || day > days_in_month(year, month)
909 || hour > 23
910 || minute > 59
911 || second > 59
912 {
913 return None;
914 }
915 let days = days_from_civil(year, month, day);
916 let seconds = days * 86_400 + hour * 3600 + minute * 60 + second;
917 Some((seconds * 1000 + millis, &line[CAPTURE_STAMP_PREFIX_LEN..]))
919}
920
921fn days_in_month(year: u64, month: u64) -> u64 {
922 match month {
923 2 if year.is_multiple_of(4) && (!year.is_multiple_of(100) || year.is_multiple_of(400)) => {
924 29
925 }
926 2 => 28,
927 4 | 6 | 9 | 11 => 30,
928 _ => 31,
929 }
930}
931
932fn civil_from_days(days: u64) -> (u64, u64, u64) {
936 let z = days + 719_468;
937 let era = z / 146_097;
938 let doe = z - era * 146_097;
939 let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
940 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
941 let mp = (5 * doy + 2) / 153;
942 let day = doy - (153 * mp + 2) / 5 + 1;
943 let month = if mp < 10 { mp + 3 } else { mp - 9 };
944 let year = yoe + era * 400 + u64::from(month <= 2);
945 (year, month, day)
946}
947
948fn days_from_civil(year: u64, month: u64, day: u64) -> u64 {
949 let year = if month <= 2 { year - 1 } else { year };
950 let era = year / 400;
951 let yoe = year - era * 400;
952 let shifted_month = if month > 2 { month - 3 } else { month + 9 };
953 let doy = (153 * shifted_month + 2) / 5 + day - 1;
954 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
955 era * 146_097 + doe - 719_468
956}
957
958#[cfg(test)]
962pub(crate) fn untimed(entries: Vec<TailEntry>) -> Vec<TailEntry> {
963 entries
964 .into_iter()
965 .map(|entry| match entry {
966 TailEntry::Line {
967 text, truncated, ..
968 } => TailEntry::Line {
969 text,
970 truncated,
971 at_ms: None,
972 },
973 TailEntry::ProcessStart => TailEntry::ProcessStart,
974 })
975 .collect()
976}
977
978fn lock_ring(ring: &Arc<Mutex<StderrRing>>) -> std::sync::MutexGuard<'_, StderrRing> {
979 ring.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
980}
981
982fn truncate_line(line: &str, max_bytes: usize) -> (String, bool) {
988 if line.len() <= max_bytes {
989 return (line.to_string(), false);
990 }
991 let mut end = max_bytes;
992 while end > 0 && !line.is_char_boundary(end) {
993 end -= 1;
994 }
995 (line[..end].to_string(), true)
996}
997
998#[cfg(test)]
999mod tests {
1000 use std::{
1001 io,
1002 pin::Pin,
1003 task::{Context, Poll},
1004 };
1005
1006 use super::*;
1007 use tokio::io::{AsyncRead, ReadBuf};
1008
1009 fn ring(max_lines: usize, max_bytes: usize, max_line_bytes: usize) -> StderrRing {
1010 StderrRing::new(StderrTailConfig::new(max_lines, max_bytes, max_line_bytes))
1011 }
1012
1013 fn lines(snapshot: &StderrTailSnapshot) -> Vec<String> {
1014 snapshot
1015 .entries
1016 .iter()
1017 .filter_map(|entry| match entry {
1018 TailEntry::Line { text, .. } => Some(text.clone()),
1019 TailEntry::ProcessStart => None,
1020 })
1021 .collect()
1022 }
1023
1024 #[test]
1025 fn a_fresh_ring_reports_not_captured_rather_than_empty() {
1026 let ring = ring(10, 1024, 128);
1029 let snapshot = ring.snapshot(None, None);
1030 assert!(matches!(snapshot.capture, CaptureState::NotCaptured { .. }));
1031 assert!(snapshot.entries.is_empty());
1032 }
1033
1034 #[test]
1035 fn read_failure_does_not_taint_generations_after_its_section_is_evicted() {
1036 let mut ring = StderrRing::new(StderrTailConfig {
1037 max_lines: 1,
1038 ..Default::default()
1039 });
1040 ring.begin_process();
1041 ring.mark_captured();
1042 ring.push_line("old output");
1043 ring.mark_incomplete("read failed");
1044 assert!(matches!(
1045 ring.snapshot(None, None).capture,
1046 CaptureState::Incomplete { .. }
1047 ));
1048 ring.begin_process();
1049 ring.mark_captured();
1050 ring.push_line("new output");
1051 assert_eq!(ring.snapshot(None, None).capture, CaptureState::Captured);
1052 }
1053
1054 #[test]
1055 fn a_captured_module_that_printed_nothing_is_distinguishable_from_an_uncaptured_one() {
1056 let mut captured = ring(10, 1024, 128);
1057 captured.mark_captured();
1058 let uncaptured = ring(10, 1024, 128);
1059
1060 let captured = captured.snapshot(None, None);
1061 let uncaptured = uncaptured.snapshot(None, None);
1062
1063 assert!(captured.entries.is_empty());
1066 assert!(uncaptured.entries.is_empty());
1067 assert_eq!(captured.capture, CaptureState::Captured);
1068 assert!(matches!(
1069 uncaptured.capture,
1070 CaptureState::NotCaptured { .. }
1071 ));
1072 }
1073
1074 #[test]
1075 fn the_line_cap_evicts_oldest_first_and_counts_what_it_dropped() {
1076 let mut ring = ring(3, 10_000, 128);
1077 ring.mark_captured();
1078 for i in 0..6 {
1079 ring.push_line(&format!("line{i}"));
1080 }
1081 let snapshot = ring.snapshot(None, None);
1082 assert_eq!(lines(&snapshot), vec!["line3", "line4", "line5"]);
1083 assert_eq!(snapshot.dropped_lines, 3);
1086 }
1087
1088 #[test]
1089 fn the_byte_cap_binds_before_the_line_cap_when_lines_are_large() {
1090 let mut ring = ring(100, 30, 128);
1092 ring.mark_captured();
1093 for i in 0..10 {
1094 ring.push_line(&format!("{i}--------")); }
1096 let snapshot = ring.snapshot(None, None);
1097 assert!(
1098 snapshot.entries.len() < 10,
1099 "byte cap did not bind: {} entries retained",
1100 snapshot.entries.len()
1101 );
1102 let retained: usize = lines(&snapshot).iter().map(String::len).sum();
1103 assert!(
1104 retained <= 30,
1105 "retained {retained} bytes over a 30 byte cap"
1106 );
1107 assert!(snapshot.dropped_lines > 0);
1108 }
1109
1110 #[test]
1111 fn one_enormous_line_is_truncated_rather_than_evicting_the_tail() {
1112 let mut ring = ring(10, 10_000, 64);
1115 ring.mark_captured();
1116 ring.push_line("context line that must survive");
1117 ring.push_line(&"x".repeat(40_000));
1118
1119 let snapshot = ring.snapshot(None, None);
1120 let kept = &snapshot.entries;
1121 assert!(matches!(
1122 &kept[0],
1123 TailEntry::Line { text, truncated: false, .. }
1124 if text == "context line that must survive"
1125 ));
1126 let TailEntry::Line {
1127 text, truncated, ..
1128 } = &kept[1]
1129 else {
1130 panic!("expected a truncated line");
1131 };
1132 assert_eq!(text, &"x".repeat(64));
1133 assert!(*truncated);
1134 }
1135
1136 #[test]
1137 fn truncation_is_visible_so_a_cut_line_is_not_mistaken_for_a_short_one() {
1138 let mut ring = ring(10, 10_000, 16);
1139 ring.mark_captured();
1140 ring.push_line("0123456789abcdefghij");
1141 ring.push_line("short");
1142
1143 let snapshot = ring.snapshot(None, None);
1144 let TailEntry::Line { truncated, .. } = &snapshot.entries[0] else {
1145 panic!("expected a line");
1146 };
1147 assert!(truncated);
1148 let TailEntry::Line { truncated, .. } = &snapshot.entries[1] else {
1149 panic!("expected a line");
1150 };
1151 assert!(!truncated, "a short line must not be reported as truncated");
1152 }
1153
1154 #[test]
1155 fn truncation_cuts_on_a_char_boundary_rather_than_splitting_utf8() {
1156 let mut ring = ring(10, 10_000, 5);
1159 ring.mark_captured();
1160 ring.push_line("aa€€€€");
1161 let snapshot = ring.snapshot(None, None);
1162 let TailEntry::Line {
1163 text, truncated, ..
1164 } = &snapshot.entries[0]
1165 else {
1166 panic!("expected a line");
1167 };
1168 assert!(truncated);
1169 assert!(text.starts_with("aa"));
1170 }
1171
1172 #[test]
1173 fn a_restart_boundary_keeps_generations_distinguishable() {
1174 let mut ring = ring(10, 10_000, 128);
1175 ring.mark_captured();
1176 ring.push_line("before the crash");
1177 ring.push_process_start();
1178 ring.push_line("after the respawn");
1179
1180 let snapshot = ring.snapshot(None, None);
1181 assert_eq!(
1182 snapshot.entries,
1183 vec![
1184 TailEntry::Line {
1185 text: "before the crash".to_string(),
1186 truncated: false,
1187 at_ms: None,
1188 },
1189 TailEntry::ProcessStart,
1190 TailEntry::Line {
1191 text: "after the respawn".to_string(),
1192 truncated: false,
1193 at_ms: None,
1194 },
1195 ]
1196 );
1197 }
1198
1199 #[test]
1200 fn the_ring_survives_respawn_because_the_cause_is_written_before_the_exit() {
1201 let mut ring = ring(10, 10_000, 128);
1204 ring.mark_captured();
1205 ring.push_line("Error: storage section missing");
1206 ring.push_process_start();
1207
1208 let snapshot = ring.snapshot(None, None);
1209 assert!(lines(&snapshot).contains(&"Error: storage section missing".to_string()));
1210 }
1211
1212 #[test]
1213 fn a_caller_limit_returns_the_newest_lines_not_the_oldest() {
1214 let mut ring = ring(100, 100_000, 128);
1215 ring.mark_captured();
1216 for i in 0..10 {
1217 ring.push_line(&format!("line{i}"));
1218 }
1219 let snapshot = ring.snapshot(Some(3), None);
1220 assert_eq!(lines(&snapshot), vec!["line7", "line8", "line9"]);
1221 }
1222
1223 #[test]
1224 fn a_caller_line_limit_keeps_the_boundary_before_the_selected_line() {
1225 let mut ring = ring(100, 100_000, 128);
1226 ring.mark_captured();
1227 ring.push_line("before restart");
1228 ring.push_process_start();
1229 ring.push_line("after restart");
1230
1231 let snapshot = ring.snapshot(Some(1), None);
1232 assert_eq!(
1233 snapshot.entries,
1234 vec![
1235 TailEntry::ProcessStart,
1236 TailEntry::Line {
1237 text: "after restart".to_string(),
1238 truncated: false,
1239 at_ms: None,
1240 },
1241 ]
1242 );
1243 }
1244
1245 #[test]
1246 fn a_caller_line_limit_omits_a_trailing_boundary_after_the_selected_line() {
1247 let mut ring = ring(100, 100_000, 128);
1248 ring.mark_captured();
1249 ring.push_line("before restart");
1250 ring.push_process_start();
1251
1252 let snapshot = ring.snapshot(Some(1), None);
1253 assert_eq!(
1254 snapshot.entries,
1255 vec![TailEntry::Line {
1256 text: "before restart".to_string(),
1257 truncated: false,
1258 at_ms: None,
1259 }]
1260 );
1261 }
1262
1263 #[test]
1264 fn a_caller_limit_reports_what_it_withheld_rather_than_looking_complete() {
1265 let mut ring = ring(100, 100_000, 128);
1266 ring.mark_captured();
1267 for i in 0..10 {
1268 ring.push_line(&format!("line{i}"));
1269 }
1270 assert_eq!(ring.snapshot(Some(3), None).dropped_lines, 7);
1273 assert_eq!(ring.snapshot(None, None).dropped_lines, 0);
1274 }
1275
1276 #[test]
1277 fn a_caller_limit_cannot_widen_the_rings_own_caps() {
1278 let mut ring = ring(2, 10_000, 128);
1279 ring.mark_captured();
1280 for i in 0..5 {
1281 ring.push_line(&format!("line{i}"));
1282 }
1283 let snapshot = ring.snapshot(Some(1000), Some(1_000_000));
1284 assert_eq!(lines(&snapshot).len(), 2);
1285 }
1286
1287 fn shared(max_lines: usize, max_bytes: usize, max_line_bytes: usize) -> Arc<Mutex<StderrRing>> {
1288 Arc::new(Mutex::new(ring(max_lines, max_bytes, max_line_bytes)))
1289 }
1290
1291 #[derive(Default)]
1294 struct RecordingSink {
1295 writes: Vec<Vec<u8>>,
1296 }
1297
1298 impl OutputSink for RecordingSink {
1299 fn write_line(&mut self, line: &[u8]) {
1300 self.writes.push(line.to_vec());
1301 }
1302 }
1303
1304 struct ChunkedReader {
1307 chunks: VecDeque<Vec<u8>>,
1308 }
1309
1310 impl AsyncRead for ChunkedReader {
1311 fn poll_read(
1312 mut self: Pin<&mut Self>,
1313 _cx: &mut Context<'_>,
1314 buf: &mut ReadBuf<'_>,
1315 ) -> Poll<io::Result<()>> {
1316 match self.chunks.pop_front() {
1317 None => Poll::Ready(Ok(())),
1318 Some(chunk) => {
1319 buf.put_slice(&chunk);
1320 Poll::Ready(Ok(()))
1321 }
1322 }
1323 }
1324 }
1325
1326 struct FailingReader {
1327 bytes: Vec<u8>,
1328 emitted: bool,
1329 }
1330
1331 impl AsyncRead for FailingReader {
1332 fn poll_read(
1333 mut self: Pin<&mut Self>,
1334 _cx: &mut Context<'_>,
1335 buf: &mut ReadBuf<'_>,
1336 ) -> Poll<io::Result<()>> {
1337 if self.emitted {
1338 return Poll::Ready(Err(io::Error::other("reader failed")));
1339 }
1340 self.emitted = true;
1341 buf.put_slice(&self.bytes);
1342 Poll::Ready(Ok(()))
1343 }
1344 }
1345
1346 #[tokio::test]
1347 async fn the_pump_splits_on_newlines_and_keeps_a_trailing_fragment() {
1348 let ring = shared(10, 10_000, 128);
1349 let source = std::io::Cursor::new(b"one\ntwo\nthree".to_vec());
1352 let mut sink = RecordingSink::default();
1353 pump_stderr_into(source, Arc::clone(&ring), &mut sink).await;
1354
1355 let snapshot = lock_ring(&ring).snapshot(None, None);
1356 assert_eq!(lines(&snapshot), vec!["one", "two", "three"]);
1357 assert_eq!(snapshot.capture, CaptureState::Captured);
1358 assert_eq!(
1359 sink.writes,
1360 vec![b"one\n".to_vec(), b"two\n".to_vec(), b"three".to_vec()]
1361 );
1362 }
1363
1364 #[tokio::test]
1365 async fn a_read_failure_keeps_prior_lines_and_marks_the_capture_incomplete() {
1366 let ring = shared(10, 10_000, 128);
1367 let source = FailingReader {
1368 bytes: b"crash cause\n".to_vec(),
1369 emitted: false,
1370 };
1371 let mut sink = RecordingSink::default();
1372 pump_stderr_into(source, Arc::clone(&ring), &mut sink).await;
1373
1374 let snapshot = lock_ring(&ring).snapshot(None, None);
1375 assert_eq!(lines(&snapshot), vec!["crash cause"]);
1376 assert!(matches!(
1377 snapshot.capture,
1378 CaptureState::Incomplete { ref reason } if reason.contains("reader failed")
1379 ));
1380 assert_eq!(sink.writes, vec![b"crash cause\n".to_vec()]);
1381 }
1382
1383 #[tokio::test]
1384 async fn every_captured_line_is_also_forwarded() {
1385 let ring = shared(10, 10_000, 128);
1389 let source = std::io::Cursor::new(b"alpha\nbeta\n".to_vec());
1390 let mut sink = RecordingSink::default();
1391 pump_stderr_into(source, Arc::clone(&ring), &mut sink).await;
1392
1393 assert_eq!(sink.writes, vec![b"alpha\n".to_vec(), b"beta\n".to_vec()]);
1394 }
1395
1396 #[tokio::test]
1397 async fn each_forwarded_line_is_exactly_one_write() {
1398 let ring = shared(10, 10_000, 128);
1403 let source = std::io::Cursor::new(b"first\nsecond\nthird\n".to_vec());
1404 let mut sink = RecordingSink::default();
1405 pump_stderr_into(source, Arc::clone(&ring), &mut sink).await;
1406
1407 assert_eq!(sink.writes.len(), 3);
1408 for write in &sink.writes {
1409 assert_eq!(
1410 write.iter().filter(|byte| **byte == b'\n').count(),
1411 1,
1412 "a write carried something other than exactly one complete line"
1413 );
1414 assert_eq!(*write.last().unwrap(), b'\n');
1415 }
1416 }
1417
1418 #[test]
1419 fn the_first_process_start_is_not_recorded_because_it_divides_nothing() {
1420 let mut ring = ring(10, 10_000, 128);
1423 ring.push_process_start();
1424 assert!(ring.snapshot(None, None).entries.is_empty());
1425
1426 ring.push_line("first process said this");
1427 ring.push_process_start();
1428 assert!(
1429 matches!(ring.entries.back(), Some(Slot::ProcessStart { .. })),
1430 "a boundary with output before it must be recorded"
1431 );
1432 ring.push_line("second process said this");
1433 assert_eq!(
1434 ring.snapshot(None, None).entries,
1435 vec![
1436 TailEntry::Line {
1437 text: "first process said this".to_string(),
1438 truncated: false,
1439 at_ms: None,
1440 },
1441 TailEntry::ProcessStart,
1442 TailEntry::Line {
1443 text: "second process said this".to_string(),
1444 truncated: false,
1445 at_ms: None,
1446 },
1447 ],
1448 "only the boundary with output before it may be shown"
1449 );
1450 }
1451
1452 #[test]
1453 fn a_process_start_is_recorded_when_only_dropped_lines_precede_it() {
1454 let mut ring = ring(1, 10_000, 128);
1458 ring.push_line("evicted");
1459 ring.push_line("also evicted");
1460 ring.entries.clear();
1464 ring.lines = 0;
1465 ring.bytes = 0;
1466 ring.push_process_start();
1467 ring.push_line("survivor");
1468 assert_eq!(
1469 ring.snapshot(None, None).entries,
1470 vec![
1471 TailEntry::ProcessStart,
1472 TailEntry::Line {
1473 text: "survivor".to_string(),
1474 truncated: false,
1475 at_ms: None,
1476 },
1477 ]
1478 );
1479 }
1480
1481 fn line(text: &str) -> TailEntry {
1482 TailEntry::Line {
1483 text: text.to_string(),
1484 truncated: false,
1485 at_ms: None,
1486 }
1487 }
1488
1489 #[test]
1490 fn a_late_line_from_a_retired_process_lands_in_that_processs_section() {
1491 let mut ring = ring(10, 10_000, 128);
1495 ring.mark_captured();
1496 let old = ring.begin_process();
1497 ring.push_line_from(old, "old: booting");
1498 ring.retire_pump(old);
1499 let new = ring.begin_process();
1500 ring.push_line_from(new, "new: booting");
1501 ring.push_line_from(old, "old: config error");
1502
1503 assert_eq!(
1504 ring.snapshot(None, None).entries,
1505 vec![
1506 line("old: booting"),
1507 line("old: config error"),
1508 TailEntry::ProcessStart,
1509 line("new: booting"),
1510 ]
1511 );
1512 }
1513
1514 #[test]
1515 fn a_line_from_a_process_that_was_not_retired_is_appended_as_it_arrives() {
1516 let mut ring = ring(10, 10_000, 128);
1519 ring.mark_captured();
1520 let incumbent = ring.begin_process();
1521 ring.push_line_from(incumbent, "incumbent: before");
1522 let candidate = ring.begin_process();
1523 ring.push_line_from(candidate, "candidate: booting");
1524 ring.push_line_from(incumbent, "incumbent: still serving");
1525
1526 assert_eq!(
1527 ring.snapshot(None, None).entries,
1528 vec![
1529 line("incumbent: before"),
1530 TailEntry::ProcessStart,
1531 line("candidate: booting"),
1532 line("incumbent: still serving"),
1533 ]
1534 );
1535 }
1536
1537 #[test]
1538 fn a_late_line_keeps_its_section_when_the_process_had_printed_nothing_before() {
1539 let mut ring = ring(10, 10_000, 128);
1543 ring.mark_captured();
1544 let first = ring.begin_process();
1545 ring.push_line_from(first, "first: done");
1546 ring.finish_pump(first);
1547 let old = ring.begin_process();
1548 ring.retire_pump(old);
1549 let new = ring.begin_process();
1550 ring.push_line_from(new, "new: booting");
1551 ring.push_line_from(old, "old: config error");
1552
1553 assert_eq!(
1554 ring.snapshot(None, None).entries,
1555 vec![
1556 line("first: done"),
1557 TailEntry::ProcessStart,
1558 line("old: config error"),
1559 TailEntry::ProcessStart,
1560 line("new: booting"),
1561 ]
1562 );
1563 }
1564
1565 #[test]
1566 fn a_late_line_whose_section_was_evicted_counts_as_dropped() {
1567 let mut ring = ring(2, 10_000, 128);
1568 ring.mark_captured();
1569 let old = ring.begin_process();
1570 ring.push_line_from(old, "old");
1571 ring.retire_pump(old);
1572 let new = ring.begin_process();
1573 for text in ["new 1", "new 2", "new 3"] {
1574 ring.push_line_from(new, text);
1575 }
1576 ring.push_line_from(old, "old, late");
1579
1580 let snapshot = ring.snapshot(None, None);
1581 assert_eq!(snapshot.entries, vec![line("new 2"), line("new 3")]);
1582 assert_eq!(snapshot.dropped_lines, 3);
1583 }
1584
1585 #[test]
1586 fn a_late_reader_reads_incomplete_until_its_pipe_reaches_eof() {
1587 let mut ring = ring(10, 10_000, 128);
1588 ring.mark_captured();
1589 let old = ring.begin_process();
1590 ring.retire_pump(old);
1591 ring.mark_pump_late(old, "still open");
1592 ring.begin_process();
1593 assert_eq!(
1594 ring.snapshot(None, None).capture,
1595 CaptureState::Incomplete {
1596 reason: "still open".to_string()
1597 }
1598 );
1599
1600 ring.finish_pump(old);
1601 assert_eq!(ring.snapshot(None, None).capture, CaptureState::Captured);
1602 }
1603
1604 #[test]
1605 fn silent_restarts_do_not_grow_the_ring() {
1606 let mut ring = ring(10, 10_000, 128);
1607 ring.mark_captured();
1608 ring.push_line("once");
1609 for _ in 0..100 {
1610 let generation = ring.begin_process();
1611 ring.finish_pump(generation);
1612 }
1613 assert_eq!(ring.entries.len(), 2);
1614 }
1615
1616 #[tokio::test]
1617 async fn the_pump_marks_captured_even_when_the_module_writes_nothing() {
1618 let ring = shared(10, 10_000, 128);
1621 let source = std::io::Cursor::new(Vec::new());
1622 let mut sink = RecordingSink::default();
1623 pump_stderr_into(source, Arc::clone(&ring), &mut sink).await;
1624
1625 let snapshot = lock_ring(&ring).snapshot(None, None);
1626 assert!(snapshot.entries.is_empty());
1627 assert_eq!(snapshot.capture, CaptureState::Captured);
1628 assert!(sink.writes.is_empty());
1629 }
1630
1631 #[tokio::test]
1632 async fn a_line_with_no_newline_cannot_grow_the_reader_without_bound() {
1633 let ring = shared(10, 10_000_000, 4 * 1024 * 1024);
1636 let source = std::io::Cursor::new(vec![b'x'; MAX_PENDING_LINE_BYTES + 4096]);
1637 let mut sink = RecordingSink::default();
1638 pump_stderr_into(source, Arc::clone(&ring), &mut sink).await;
1639
1640 let snapshot = lock_ring(&ring).snapshot(None, None);
1641 assert_eq!(
1642 lines(&snapshot).len(),
1643 2,
1644 "expected a forced flush at the ceiling plus the remainder"
1645 );
1646 assert_eq!(
1647 sink.writes,
1648 vec![vec![b'x'; MAX_PENDING_LINE_BYTES], vec![b'x'; 4096],],
1649 "forced flushes and EOF fragments must not invent delimiters"
1650 );
1651 }
1652
1653 #[tokio::test]
1654 async fn boundaries_truncation_and_framing_do_not_depend_on_chunk_splits() {
1655 let ring = shared(100, 100_000, 8);
1659 let source = ChunkedReader {
1660 chunks: vec![
1661 b"fir".to_vec(),
1662 b"st\nsec".to_vec(),
1663 b"ond\ncarry\r".to_vec(),
1664 b"\nover\n".to_vec(),
1665 b"12345678\n".to_vec(),
1666 b"1234567".to_vec(),
1667 b"89\n".to_vec(),
1668 b"tail".to_vec(),
1669 ]
1670 .into_iter()
1671 .collect(),
1672 };
1673 let mut sink = RecordingSink::default();
1674 pump_stderr_into(source, Arc::clone(&ring), &mut sink).await;
1675
1676 let snapshot = lock_ring(&ring).snapshot(None, None);
1677 assert_eq!(snapshot.capture, CaptureState::Captured);
1678 assert_eq!(
1679 untimed(snapshot.entries),
1680 vec![
1681 TailEntry::Line {
1682 text: "first".to_string(),
1683 truncated: false,
1684 at_ms: None,
1685 },
1686 TailEntry::Line {
1687 text: "second".to_string(),
1688 truncated: false,
1689 at_ms: None,
1690 },
1691 TailEntry::Line {
1693 text: "carry\r".to_string(),
1694 truncated: false,
1695 at_ms: None,
1696 },
1697 TailEntry::Line {
1698 text: "over".to_string(),
1699 truncated: false,
1700 at_ms: None,
1701 },
1702 TailEntry::Line {
1704 text: "12345678".to_string(),
1705 truncated: false,
1706 at_ms: None,
1707 },
1708 TailEntry::Line {
1710 text: "12345678".to_string(),
1711 truncated: true,
1712 at_ms: None,
1713 },
1714 TailEntry::Line {
1715 text: "tail".to_string(),
1716 truncated: false,
1717 at_ms: None,
1718 },
1719 ]
1720 );
1721 assert_eq!(
1722 sink.writes,
1723 vec![
1724 b"first\n".to_vec(),
1725 b"second\n".to_vec(),
1726 b"carry\r\n".to_vec(),
1727 b"over\n".to_vec(),
1728 b"12345678\n".to_vec(),
1729 b"123456789\n".to_vec(),
1730 b"tail".to_vec(),
1731 ]
1732 );
1733 }
1734
1735 #[tokio::test]
1736 async fn a_line_with_no_newline_is_not_rescanned_from_byte_zero_on_every_chunk() {
1737 let input = vec![b'x'; MAX_PENDING_LINE_BYTES + 4096];
1743 let ring = shared(10, 10_000_000, 4 * 1024 * 1024);
1744 let source = std::io::Cursor::new(input.clone());
1745 let mut sink = RecordingSink::default();
1746
1747 take_scanned_bytes();
1748 pump_stderr_into(source, Arc::clone(&ring), &mut sink).await;
1749 let scanned = take_scanned_bytes();
1750
1751 assert!(
1752 scanned <= 2 * input.len(),
1753 "newline searches examined {scanned} bytes for {} bytes of input; \
1754 each chunk must search only newly arrived bytes",
1755 input.len()
1756 );
1757 }
1758
1759 fn now_ms() -> u64 {
1760 unix_ms(SystemTime::now())
1761 }
1762
1763 #[tokio::test]
1764 async fn a_captured_line_carries_the_time_the_reader_framed_it() {
1765 let ring = shared(10, 10_000, 128);
1769 let before = now_ms();
1770 let source = std::io::Cursor::new(b"first\nsecond".to_vec());
1771 pump_stderr_into(source, Arc::clone(&ring), &mut RecordingSink::default()).await;
1772 let after = now_ms();
1773
1774 let entries = lock_ring(&ring).snapshot(None, None).entries;
1775 assert_eq!(entries.len(), 2);
1776 for entry in entries {
1777 let TailEntry::Line { text, at_ms, .. } = entry else {
1778 panic!("expected only lines, got {entry:?}");
1779 };
1780 let at_ms = at_ms.unwrap_or_else(|| panic!("line {text:?} has no capture time"));
1781 assert!(
1782 (before..=after).contains(&at_ms),
1783 "line {text:?} stamped {at_ms}, outside the pump's run {before}..={after}"
1784 );
1785 }
1786 }
1787
1788 async fn capture_through_file_sink(chunks: Vec<Vec<u8>>) -> (String, u64, u64) {
1790 let temp = cortexkit_test_support::ScratchDir::new("stderr-capture-stamp");
1791 let path = temp.path().join("stamped.stderr.log");
1792 let sink = ChildOutputSink::open(&path, cortexkit_log::Retention::default()).unwrap();
1793 let ring = shared(10, 10_000, 128);
1794 let generation = lock_ring(&ring).begin_process();
1795 let before = now_ms();
1796 pump_stderr_to(
1797 ChunkedReader {
1798 chunks: chunks.into_iter().collect(),
1799 },
1800 ring,
1801 generation,
1802 sink,
1803 )
1804 .await;
1805 let after = now_ms();
1806 (std::fs::read_to_string(&path).unwrap(), before, after)
1807 }
1808
1809 fn assert_stamp_shape(line: &str) {
1813 let bytes = line.as_bytes();
1814 assert!(bytes.len() > 25, "line too short for a stamp: {line:?}");
1815 for (index, byte) in bytes[..25].iter().enumerate() {
1816 let expected_separator = match index {
1817 4 | 7 => Some(b'-'),
1818 10 => Some(b'T'),
1819 13 | 16 => Some(b':'),
1820 19 => Some(b'.'),
1821 23 => Some(b'Z'),
1822 24 => Some(b' '),
1823 _ => None,
1824 };
1825 match expected_separator {
1826 Some(separator) => assert_eq!(*byte, separator, "byte {index} of {line:?}"),
1827 None => assert!(byte.is_ascii_digit(), "byte {index} of {line:?}"),
1828 }
1829 }
1830 }
1831
1832 #[tokio::test]
1833 async fn the_capture_file_stamps_each_line_and_keeps_the_module_bytes_verbatim() {
1834 let module_lines = [
1838 "plain line",
1839 "2020-01-01T00:00:00.000Z INFO mymod: own stamp",
1840 ];
1841 let input = format!("{}\n{}\n", module_lines[0], module_lines[1]);
1842 let (contents, before, after) = capture_through_file_sink(vec![input.into_bytes()]).await;
1843
1844 assert!(contents.ends_with('\n'));
1845 let lines: Vec<&str> = contents.lines().collect();
1846 assert_eq!(lines.len(), 2, "capture file: {contents:?}");
1847 for (line, module_line) in lines.iter().zip(module_lines) {
1848 assert_stamp_shape(line);
1849 assert_eq!(&line[25..], module_line, "module bytes changed");
1850 let (at_ms, rest) = split_capture_stamp(line).unwrap();
1851 assert_eq!(rest, module_line);
1852 assert!(
1854 (before..=after).contains(&at_ms),
1855 "stamped {at_ms}, outside the pump's run {before}..={after}"
1856 );
1857 }
1858 }
1859
1860 #[tokio::test]
1861 async fn a_line_split_across_several_writes_is_stamped_once() {
1862 let (contents, _, _) = capture_through_file_sink(vec![
1866 b"par".to_vec(),
1867 b"tial li".to_vec(),
1868 b"ne\nwhole\n".to_vec(),
1869 ])
1870 .await;
1871
1872 let lines: Vec<&str> = contents.lines().collect();
1873 assert_eq!(lines.len(), 2, "capture file: {contents:?}");
1874 for (line, module_line) in lines.iter().zip(["partial line", "whole"]) {
1875 assert_stamp_shape(line);
1876 assert_eq!(&line[25..], module_line, "capture file: {contents:?}");
1877 }
1878 }
1879
1880 #[tokio::test]
1881 async fn a_line_flushed_at_the_ceiling_is_stamped_only_at_the_start_of_each_file_line() {
1882 let mut long = vec![b'x'; MAX_PENDING_LINE_BYTES + 100];
1887 long.push(b'\n');
1888 let chunks = long.chunks(8192).map(<[u8]>::to_vec).collect();
1890 let (contents, _, _) = capture_through_file_sink(chunks).await;
1891
1892 let lines: Vec<&str> = contents.lines().collect();
1893 assert_eq!(lines.len(), 2, "expected the flushed piece and the rest");
1894 for line in &lines {
1895 assert_stamp_shape(line);
1896 assert!(
1897 line[25..].bytes().all(|byte| byte == b'x'),
1898 "a stamp landed inside module bytes"
1899 );
1900 }
1901 let module_bytes: usize = lines.iter().map(|line| line.len() - 25).sum();
1902 assert_eq!(module_bytes, MAX_PENDING_LINE_BYTES + 100);
1903 }
1904
1905 #[test]
1906 fn the_capture_stamp_is_the_daemon_log_timestamp_form() {
1907 for (at_ms, text) in [
1908 (0, "1970-01-01T00:00:00.000Z"),
1909 (951_868_799_999, "2000-02-29T23:59:59.999Z"),
1910 (1_789_801_440_685, "2026-09-19T07:04:00.685Z"),
1911 (4_107_542_400_001, "2100-03-01T00:00:00.001Z"),
1912 ] {
1913 let stamp = format_capture_stamp(at_ms);
1914 assert_eq!(stamp, text);
1915 assert_eq!(stamp.len(), CAPTURE_STAMP_LEN);
1916 let daemon_line = format!("{stamp} INFO subc: probe");
1919 let parsed = cortexkit_log::parse_line(&daemon_line).unwrap();
1920 assert_eq!(
1921 parsed.timestamp,
1922 UNIX_EPOCH + std::time::Duration::from_millis(at_ms)
1923 );
1924 assert_eq!(
1925 split_capture_stamp(&format!("{stamp} body")),
1926 Some((at_ms, "body"))
1927 );
1928 }
1929 }
1930
1931 #[test]
1932 fn a_line_without_a_well_formed_stamp_has_no_capture_time() {
1933 for line in [
1934 "",
1935 "plain module output",
1936 "2026-09-19T07:04:00.685Z",
1937 "2026-09-19T07:04:00.685Zbody",
1938 "2026-09-19T07:04:00.685z body",
1939 "2026-09-19 07:04:00.685Z body",
1940 "2026-09-19T07:04:00Z body",
1941 "2026-02-30T07:04:00.685Z body",
1942 "2026-13-19T07:04:00.685Z body",
1943 "2026-09-19T24:04:00.685Z body",
1944 "2026-09-19T07:04:00.6a5Z body",
1945 "1969-12-31T23:59:59.999Z body",
1946 ] {
1947 assert_eq!(split_capture_stamp(line), None, "{line:?}");
1948 }
1949 }
1950
1951 #[test]
1952 fn a_byte_limit_smaller_than_one_line_still_returns_that_line() {
1953 let mut ring = ring(10, 10_000, 128);
1956 ring.mark_captured();
1957 ring.push_line("a line considerably longer than the request limit");
1958 let snapshot = ring.snapshot(None, Some(4));
1959 assert_eq!(snapshot.entries.len(), 1);
1960 }
1961
1962 #[test]
1963 fn an_incoherent_config_clamps_the_line_cap_and_keeps_its_restart_boundary() {
1964 let config = StderrTailConfig::new(2, 10, 100);
1965 assert_eq!(config.max_line_bytes, config.max_bytes);
1966 let mut ring = StderrRing::new(config);
1967 ring.mark_captured();
1968 ring.push_line("old");
1969 ring.push_process_start();
1970 ring.push_line("new process line longer than the ring byte cap");
1971
1972 assert_eq!(
1973 ring.snapshot(None, None).entries,
1974 vec![
1975 TailEntry::ProcessStart,
1976 TailEntry::Line {
1977 text: "new proces".to_string(),
1978 truncated: true,
1979 at_ms: None,
1980 },
1981 ]
1982 );
1983 }
1984}