Skip to main content

subc_daemon/
stderr_tail.rs

1//! Bounded per-module stderr capture.
2//!
3//! # Why this exists
4//!
5//! `last_exit_code` survives a respawn because the supervisor holds it in memory.
6//! Stderr had no such path: it went to the daemon's inherited fd, and from there
7//! to whatever rotates or evicts it. On the box this was written for, that window
8//! was about three hours; on another it was bounded by a log file reaching 908 MB
9//! with one module accounting for 98% of it. Two hosts, two mechanisms, the same
10//! outcome -- the text explaining a crash is gone by the time anyone asks.
11//!
12//! So this keeps the last few lines where `last_exit` already lives: in supervisor
13//! memory, immune to whatever happens to the log.
14//!
15//! # What it is not
16//!
17//! Not a log. The ring is deliberately small and lossy, and callers are expected
18//! to know they are reading a tail rather than a history. The daemon log keeps
19//! doing its job; this exists because that job has a time limit.
20
21use 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
32/// Longest single line admitted to the ring before truncation.
33///
34/// A module emitting a 40 MB backtrace on one line satisfies any line-count cap
35/// while evicting everything else -- the pathological emitter wins twice, once by
36/// filling the ring and once by being unreadable itself. Truncating on the way in
37/// costs that emitter one line instead of the whole tail.
38pub const DEFAULT_MAX_LINE_BYTES: usize = 2048;
39
40/// Lines retained per module.
41pub const DEFAULT_MAX_LINES: usize = 200;
42
43/// Total bytes retained per module, across all lines.
44///
45/// Both this and [`DEFAULT_MAX_LINES`] apply; whichever binds first wins. A line
46/// cap alone is satisfied by 200 lines of 2 KB, which is not a budget worth
47/// holding for fifteen modules.
48pub const DEFAULT_MAX_BYTES: usize = 64 * 1024;
49
50/// Whether a module's stderr is being captured, and if not, why not.
51///
52/// Typed rather than nullable so `NotCaptured` has to be handled rather than
53/// defaulted past. An empty tail and an uncaptured one send an operator in
54/// opposite directions -- one says the module printed nothing before dying, the
55/// other says nobody was listening -- and rendering them alike is the defect this
56/// module exists to fix, reproduced one layer up.
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub enum CaptureState {
59    /// A reader is attached, or was attached and reached clean EOF.
60    Captured,
61    /// Retained entries are valid, but capture ended before clean EOF, or the
62    /// pipe of a process the supervisor has already moved on from has not
63    /// reached EOF yet. The second kind clears when that pipe does reach EOF,
64    /// because from then on nothing that process wrote is missing.
65    Incomplete { reason: String },
66    /// No reader was attached. The tail says nothing about what the module wrote.
67    NotCaptured { reason: String },
68}
69
70/// One retained entry.
71///
72/// Boundaries are in-band rather than a separate field because their position
73/// relative to the lines is the whole point: "these three lines came from the
74/// process that died, those came from its replacement" is unanswerable from a
75/// count.
76#[derive(Debug, Clone, PartialEq, Eq)]
77pub enum TailEntry {
78    Line {
79        text: String,
80        /// This line was cut at the per-line cap.
81        truncated: bool,
82        /// Wall-clock Unix milliseconds at which the reader framed this line,
83        /// the same instant stamped on its capture-file line. `None` for a line
84        /// admitted without one (see [`StderrRing::push_line`]).
85        at_ms: Option<u64>,
86    },
87    /// The supervisor spawned a new process for this module. Lines after this
88    /// entry come from the new one.
89    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/// One stored entry. Unlike [`TailEntry`], a boundary remembers which process
102/// generation it starts, so a line that arrives late from an older process can
103/// be put back in that process's section instead of after its successor's
104/// boundary.
105#[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/// Where the stderr reader of one process generation stands.
127#[derive(Debug, Clone, PartialEq, Eq)]
128enum PumpPhase {
129    /// The process is the supervisor's current concern; its lines go at the end.
130    Attached,
131    /// The supervisor has moved on from the process, but its pipe is still open.
132    /// Lines it still delivers belong in its own section.
133    Retired,
134    /// Retired, and the pipe was still open when the supervisor stopped waiting
135    /// for it. Reported as `Incomplete` until the pipe reaches EOF.
136    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    /// Keeps every retained line within the ring's total byte budget.
148    /// Clamp rather than reject so diagnostics degrade without blocking supervisor startup.
149    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/// A module's retained stderr, oldest first.
169#[derive(Debug, Clone, PartialEq, Eq)]
170pub struct StderrTailSnapshot {
171    pub capture: CaptureState,
172    pub entries: Vec<TailEntry>,
173    /// Lines evicted since the module was first supervised.
174    ///
175    /// Non-zero means the tail starts mid-stream. That is the ring working as
176    /// intended, but a reader diagnosing a crash needs to know the first retained
177    /// line is not the first line the module wrote -- otherwise an absent cause
178    /// reads as a module that never explained itself.
179    pub dropped_lines: u64,
180}
181
182impl StderrTailSnapshot {
183    /// The uncaptured case, for a module whose stderr was never piped.
184    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/// Bounded ring of a single module's stderr lines.
196///
197/// Survives respawn deliberately. The stderr explaining an exit is written
198/// *before* that exit, so clearing on restart would discard the lines exactly
199/// when they become the thing being asked for. [`TailEntry::ProcessStart`] keeps
200/// the generations distinguishable instead.
201///
202/// A process's stderr reader can outlive the supervisor's interest in it: the
203/// reader may not have been scheduled yet when the process exited, or a
204/// descendant may still hold the pipe open. Lines such a reader delivers after
205/// the next process started are placed before that next process's boundary, so
206/// the section a line appears in always names the process that wrote it.
207#[derive(Debug)]
208pub struct StderrRing {
209    config: StderrTailConfig,
210    entries: VecDeque<Slot>,
211    // Count of `TailEntry::Line` entries, kept running because eviction checks
212    // it on every push and recounting would walk the whole ring under the
213    // mutex each time.
214    lines: usize,
215    bytes: usize,
216    dropped_lines: u64,
217    capture: CaptureState,
218    /// Read failures belong to retained process sections, not every later
219    /// process that reuses this ring. Eviction removes their missing-data claim.
220    incomplete: BTreeMap<u64, String>,
221    /// Generation of the newest process boundary; 0 before the first.
222    generation: u64,
223    /// Readers that have not reached EOF yet, by the generation they read for.
224    pumps: BTreeMap<u64, PumpPhase>,
225    /// Highest generation whose boundary was evicted from the front. A late line
226    /// from an older generation belongs in front of that boundary, which is
227    /// evicted territory, so it is counted as dropped rather than stored.
228    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            // Until a reader attaches, the honest answer is that nothing is
240            // listening -- not that the module has been quiet.
241            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    /// Generation of the newest process boundary.
252    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    /// Record that a new process was spawned for this module, returning the
285    /// generation number its lines are attributed to.
286    ///
287    /// A boundary separates output on either side of it, so one with nothing
288    /// before it separates nothing: on the FIRST spawn it would make a module
289    /// that printed nothing render as a marker rather than as empty, and the
290    /// caller then has to decide whether a one-marker tail counts as silence.
291    /// The boundary is still stored, because a late line from an older process
292    /// needs it to find its section, but [`Self::snapshot`] shows it only once
293    /// there is output before it to divide, which keeps "captured and empty"
294    /// literally empty.
295    pub fn push_process_start(&mut self) -> u64 {
296        self.generation += 1;
297        let generation = self.generation;
298        // Two boundaries in a row mean the process between them has written
299        // nothing retained. The earlier one can go only if no reader from its
300        // generation onward is still open: such a reader may yet deliver a line
301        // that belongs between the two. Without this a module that restarts
302        // silently would grow the ring by one boundary per restart forever.
303        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    /// [`Self::push_process_start`] for a process whose stderr reader is
316    /// attached: the reader is tracked until it calls [`Self::finish_pump`].
317    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    /// The supervisor has moved on from this generation's process. Its reader
324    /// keeps running, and any line it still delivers is kept in its own section.
325    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    /// The supervisor stopped waiting for this generation's reader before its
332    /// pipe reached EOF. The capture reads as `Incomplete` with `reason` until
333    /// the reader finishes. A reader that already finished is left alone: it
334    /// got everything.
335    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    /// This generation's reader has stopped: at EOF, or on a read error that
344    /// has already been recorded with [`Self::mark_incomplete`].
345    pub(crate) fn finish_pump(&mut self, generation: u64) {
346        self.pumps.remove(&generation);
347    }
348
349    /// Admit one complete line, truncating it if it exceeds the per-line cap.
350    ///
351    /// `line` must not contain a trailing newline; the reader strips it so the
352    /// stored text and the byte accounting agree. The line carries no capture
353    /// time: only the pipe reader knows when a line arrived, and it records
354    /// that through `Self::push_line_from_at`.
355    pub fn push_line(&mut self, line: &str) {
356        self.push_line_from(self.generation, line);
357    }
358
359    /// [`Self::push_line`] for a line read from `generation`'s pipe.
360    pub(crate) fn push_line_from(&mut self, generation: u64, line: &str) {
361        self.admit_line(generation, line, None);
362    }
363
364    /// [`Self::push_line_from`] for a line the reader framed at `at_ms`
365    /// (wall-clock Unix milliseconds).
366    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    /// A line from a retired process that arrives after a newer process started
371    /// goes in front of the first boundary newer than its own generation. Lines
372    /// from a process the supervisor has not retired (the incumbent during a
373    /// swap's overlap) go at the end, as they arrive.
374    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            // The section this line belongs to has been evicted, so the line is
391            // older than everything retained.
392            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    /// The most recent entries, oldest first, bounded by the caller's limits.
445    ///
446    /// `max_lines`/`max_bytes` narrow the ring's own caps; they cannot widen them.
447    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        // The stored boundaries, reduced to the ones worth showing: a boundary
456        // with no output before it (retained or evicted) divides nothing, and
457        // two in a row say no more than one.
458        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        // Walk backwards: a tail is anchored at the newest end, so a caller
486        // asking for 20 lines wants the last 20, not the first 20.
487        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        // A retired process whose pipe the supervisor stopped waiting for may
510        // still be writing; until its reader reaches EOF the tail cannot claim
511        // to hold everything. A permanent state (a read failure, no pipe at
512        // all) is the more specific fact and is reported as is. A read failure
513        // no longer taints the tail after the affected section is evicted.
514        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            // Lines the ring evicted plus lines this request's own limits held
530            // back. Both mean the same thing to the reader -- the text above is
531            // not the beginning -- and separating them would invite treating a
532            // narrow request as evidence of a quiet module.
533            dropped_lines: self.dropped_lines + withheld as u64,
534        }
535    }
536}
537
538/// Reassembly buffer ceiling for a line with no newline in sight.
539///
540/// The ring truncates what it stores, but the READER has to hold the bytes until
541/// it finds a delimiter. A module emitting a gigabyte with no newline would grow
542/// this buffer without bound and take the daemon down with it -- a module fault
543/// escalating into a fleet fault, which is exactly what supervision exists to
544/// prevent. At this ceiling the pending bytes are flushed as a line and
545/// reassembly restarts.
546const MAX_PENDING_LINE_BYTES: usize = 1024 * 1024;
547
548/// Read a child's stderr to EOF, retaining the bounded crash tail and forwarding
549/// every complete line to the selected capture sink.
550pub 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/// Shared destination for a child's stdout and stderr pumps.
558///
559/// The file keeps the historical `.stderr.log` name even though it carries both
560/// streams; the stable name is part of the operator contract. Both pumps share
561/// one mutex, and cortexkit-log writes each framed line in one call, so partial
562/// lines from the two pipes cannot interleave.
563#[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
583/// Where forwarded complete lines go. It exists so tests can observe framing
584/// and so production can serialize the two child pipes through one file sink.
585pub trait OutputSink {
586    fn write_line(&mut self, line: &[u8]);
587
588    /// Whether each write should begin with its capture time (see
589    /// [`format_capture_stamp`]).
590    ///
591    /// Only a sink that ends every write with a newline may say yes: then each
592    /// write is a whole line of its own, and a stamp at the front of the write
593    /// is at the front of a line. A sink that passes an unterminated piece
594    /// through as-is would have the next piece continue the same line, and a
595    /// stamp there would land in the middle of it.
596    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    // The capture file is read long after it was written, often next to the
638    // daemon's own log, whose lines carry a time. `LineSink::write_line`
639    // appends a newline to any write that lacks one, so every write here is a
640    // whole line and may carry the stamp. The daemon's inherited stderr gets
641    // the module's bytes unchanged: an unterminated piece is continued there by
642    // the next one, and whatever collects that stream stamps it itself.
643    fn stamps_lines(&self) -> bool {
644        matches!(self, Self::File { .. })
645    }
646}
647
648/// Read one process generation's stderr to EOF. `generation` is the value
649/// [`StderrRing::begin_process`] returned for that process; it decides which
650/// section of the ring a line lands in if the reader outlives the process.
651#[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
672/// Read stderr for whichever process generation is newest when the reader
673/// starts.
674async 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    // Everything retained from the previous chunk has already been scanned.
730    pending: Vec<u8>,
731}
732
733impl LineFramer {
734    #[cfg(unix)]
735    pub(crate) fn from_tail(pending: Vec<u8>) -> Self {
736        Self { pending }
737    }
738
739    #[cfg(unix)]
740    pub(crate) fn tail(&self) -> &[u8] {
741        &self.pending
742    }
743
744    pub(crate) fn push(&mut self, chunk: &[u8], mut emit: impl FnMut(&[u8], bool)) {
745        let pending = &mut self.pending;
746        let mut scanned_upto = pending.len();
747        pending.extend_from_slice(chunk);
748        let mut cursor = 0;
749        while let Some(relative) = find_newline(&pending[scanned_upto..]) {
750            let newline = scanned_upto + relative;
751            emit(&pending[cursor..newline], true);
752            cursor = newline + 1;
753            scanned_upto = cursor;
754        }
755        pending.drain(..cursor);
756        if pending.len() >= MAX_PENDING_LINE_BYTES {
757            emit(&std::mem::take(pending), false);
758        }
759    }
760
761    pub(crate) fn finish(self, mut emit: impl FnMut(&[u8], bool)) {
762        if !self.pending.is_empty() {
763            emit(&self.pending, false);
764        }
765    }
766}
767
768// Bytes examined by newline searches, summed across a pump. Tests use this to
769// assert the reader does not rescan bytes it already knows contain no newline.
770// Per thread, not process-wide: other tests pump concurrently on their own
771// threads, and a shared counter picked up their searches too, failing the
772// bound by a few bytes under a parallel run. `#[tokio::test]` runs its body
773// and every future it awaits on one thread, so a pump's searches land on the
774// test's own counter.
775#[cfg(test)]
776thread_local! {
777    static SCANNED_BYTES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
778}
779
780#[cfg(test)]
781fn take_scanned_bytes() -> usize {
782    SCANNED_BYTES.with(|scanned| scanned.replace(0))
783}
784
785/// Locate the next newline in `haystack`, counting the bytes examined so a
786/// test can observe how much of the pending buffer each search walks.
787fn find_newline(haystack: &[u8]) -> Option<usize> {
788    let found = memchr::memchr(b'\n', haystack);
789    #[cfg(test)]
790    SCANNED_BYTES.with(|scanned| {
791        scanned.set(scanned.get() + found.map(|index| index + 1).unwrap_or(haystack.len()));
792    });
793    found
794}
795
796fn emit_line<S: OutputSink>(
797    ring: Option<(&Arc<Mutex<StderrRing>>, u64)>,
798    sink: &mut S,
799    raw: &[u8],
800    terminated: bool,
801) {
802    // One instant for both destinations, taken here because this is where the
803    // line is complete. The module's bytes do not say when the line arrived,
804    // so the time is stored beside it: as `at_ms` in the ring and as the stamp
805    // in the file. A time assigned later, when either is read, would look
806    // recorded while being off by however long the line sat there.
807    write_captured_line(ring, sink, raw, terminated, unix_ms(SystemTime::now()));
808}
809
810pub(crate) fn write_captured_line<S: OutputSink>(
811    ring: Option<(&Arc<Mutex<StderrRing>>, u64)>,
812    sink: &mut S,
813    raw: &[u8],
814    terminated: bool,
815    at_ms: u64,
816) {
817    if let Some((ring, generation)) = ring {
818        lock_ring(ring).push_line_from_at(generation, &String::from_utf8_lossy(raw), at_ms);
819    }
820
821    // Framed and written in ONE call, stamp included. Two writes would let the
822    // other pipe land between the pieces.
823    let stamp = sink.stamps_lines().then(|| format_capture_stamp(at_ms));
824    if stamp.is_none() && !terminated {
825        sink.write_line(raw);
826        return;
827    }
828    let mut framed = Vec::with_capacity(CAPTURE_STAMP_PREFIX_LEN + raw.len() + 1);
829    if let Some(stamp) = stamp {
830        framed.extend_from_slice(stamp.as_bytes());
831        framed.push(b' ');
832    }
833    framed.extend_from_slice(raw);
834    if terminated {
835        framed.push(b'\n');
836    }
837    sink.write_line(&framed);
838}
839
840pub(crate) fn unix_ms(at: SystemTime) -> u64 {
841    // A clock set before 1970 is already wrong about every time it reports;
842    // saturating keeps the stamp well-formed rather than failing the write.
843    at.duration_since(UNIX_EPOCH)
844        .map(|since| u64::try_from(since.as_millis()).unwrap_or(u64::MAX))
845        .unwrap_or(0)
846}
847
848/// Length of a capture stamp, `2026-09-19T07:04:00.685Z`.
849pub const CAPTURE_STAMP_LEN: usize = 24;
850
851/// Length of the prefix on a capture-file line: the stamp and one space.
852pub const CAPTURE_STAMP_PREFIX_LEN: usize = CAPTURE_STAMP_LEN + 1;
853
854/// `at_ms` (Unix milliseconds) as RFC 3339 UTC with milliseconds and `Z`,
855/// the form the daemon's own log lines begin with, so one parser reads the
856/// time of a line in either file. Always [`CAPTURE_STAMP_LEN`] bytes for any
857/// time before the year 10000.
858pub fn format_capture_stamp(at_ms: u64) -> String {
859    let seconds = at_ms / 1000;
860    let millis = at_ms % 1000;
861    let days = seconds / 86_400;
862    let of_day = seconds % 86_400;
863    let (year, month, day) = civil_from_days(days);
864    format!(
865        "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{millis:03}Z",
866        of_day / 3600,
867        (of_day % 3600) / 60,
868        of_day % 60,
869    )
870}
871
872/// Split a capture-file line into the time its stamp records (Unix
873/// milliseconds) and the module's bytes after the stamp's space.
874///
875/// `None` when the line does not begin with a well-formed stamp and one space:
876/// a line written before capture lines were stamped has no recorded time, and
877/// the caller must leave it undated rather than guess one.
878pub fn split_capture_stamp(line: &str) -> Option<(u64, &str)> {
879    let bytes = line.as_bytes();
880    if bytes.len() < CAPTURE_STAMP_PREFIX_LEN || bytes[CAPTURE_STAMP_LEN] != b' ' {
881        return None;
882    }
883    let stamp = &bytes[..CAPTURE_STAMP_LEN];
884    for (index, expected) in [
885        (4, b'-'),
886        (7, b'-'),
887        (10, b'T'),
888        (13, b':'),
889        (16, b':'),
890        (19, b'.'),
891        (23, b'Z'),
892    ] {
893        if stamp[index] != expected {
894            return None;
895        }
896    }
897    let number = |from: usize, to: usize| -> Option<u64> {
898        let digits = &stamp[from..to];
899        if !digits.iter().all(u8::is_ascii_digit) {
900            return None;
901        }
902        Some(
903            digits
904                .iter()
905                .fold(0u64, |total, digit| total * 10 + u64::from(digit - b'0')),
906        )
907    };
908    let year = number(0, 4)?;
909    let month = number(5, 7)?;
910    let day = number(8, 10)?;
911    let hour = number(11, 13)?;
912    let minute = number(14, 16)?;
913    let second = number(17, 19)?;
914    let millis = number(20, 23)?;
915    if year < 1970
916        || !(1..=12).contains(&month)
917        || day == 0
918        || day > days_in_month(year, month)
919        || hour > 23
920        || minute > 59
921        || second > 59
922    {
923        return None;
924    }
925    let days = days_from_civil(year, month, day);
926    let seconds = days * 86_400 + hour * 3600 + minute * 60 + second;
927    // Index 25 follows an ASCII space, so it is a char boundary.
928    Some((seconds * 1000 + millis, &line[CAPTURE_STAMP_PREFIX_LEN..]))
929}
930
931fn days_in_month(year: u64, month: u64) -> u64 {
932    match month {
933        2 if year.is_multiple_of(4) && (!year.is_multiple_of(100) || year.is_multiple_of(400)) => {
934            29
935        }
936        2 => 28,
937        4 | 6 | 9 | 11 => 30,
938        _ => 31,
939    }
940}
941
942// Days since 1970-01-01 to a proleptic Gregorian date and back, after Howard
943// Hinnant's `civil_from_days`/`days_from_civil`, restricted to dates from 1970
944// on so the arithmetic stays unsigned.
945fn civil_from_days(days: u64) -> (u64, u64, u64) {
946    let z = days + 719_468;
947    let era = z / 146_097;
948    let doe = z - era * 146_097;
949    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
950    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
951    let mp = (5 * doy + 2) / 153;
952    let day = doy - (153 * mp + 2) / 5 + 1;
953    let month = if mp < 10 { mp + 3 } else { mp - 9 };
954    let year = yoe + era * 400 + u64::from(month <= 2);
955    (year, month, day)
956}
957
958fn days_from_civil(year: u64, month: u64, day: u64) -> u64 {
959    let year = if month <= 2 { year - 1 } else { year };
960    let era = year / 400;
961    let yoe = year - era * 400;
962    let shifted_month = if month > 2 { month - 3 } else { month + 9 };
963    let doy = (153 * shifted_month + 2) / 5 + day - 1;
964    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
965    era * 146_097 + doe - 719_468
966}
967
968/// `entries` with every capture time removed, for tests that compare what a
969/// pump stored against expected text: the times are whatever the clock read,
970/// and the tests that check them do so on their own.
971#[cfg(test)]
972pub(crate) fn untimed(entries: Vec<TailEntry>) -> Vec<TailEntry> {
973    entries
974        .into_iter()
975        .map(|entry| match entry {
976            TailEntry::Line {
977                text, truncated, ..
978            } => TailEntry::Line {
979                text,
980                truncated,
981                at_ms: None,
982            },
983            TailEntry::ProcessStart => TailEntry::ProcessStart,
984        })
985        .collect()
986}
987
988fn lock_ring(ring: &Arc<Mutex<StderrRing>>) -> std::sync::MutexGuard<'_, StderrRing> {
989    ring.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
990}
991
992/// Cut `line` to at most `max_bytes`, reporting whether it was shortened.
993///
994/// Cuts on a char boundary: slicing a multi-byte sequence would produce invalid
995/// UTF-8, and a panic while capturing a crash message is the worst possible time
996/// to discover that.
997fn truncate_line(line: &str, max_bytes: usize) -> (String, bool) {
998    if line.len() <= max_bytes {
999        return (line.to_string(), false);
1000    }
1001    let mut end = max_bytes;
1002    while end > 0 && !line.is_char_boundary(end) {
1003        end -= 1;
1004    }
1005    (line[..end].to_string(), true)
1006}
1007
1008#[cfg(test)]
1009mod tests {
1010    use std::{
1011        io,
1012        pin::Pin,
1013        task::{Context, Poll},
1014    };
1015
1016    use super::*;
1017    use tokio::io::{AsyncRead, ReadBuf};
1018
1019    fn ring(max_lines: usize, max_bytes: usize, max_line_bytes: usize) -> StderrRing {
1020        StderrRing::new(StderrTailConfig::new(max_lines, max_bytes, max_line_bytes))
1021    }
1022
1023    fn lines(snapshot: &StderrTailSnapshot) -> Vec<String> {
1024        snapshot
1025            .entries
1026            .iter()
1027            .filter_map(|entry| match entry {
1028                TailEntry::Line { text, .. } => Some(text.clone()),
1029                TailEntry::ProcessStart => None,
1030            })
1031            .collect()
1032    }
1033
1034    #[test]
1035    fn a_fresh_ring_reports_not_captured_rather_than_empty() {
1036        // The distinction this whole module exists for: "nobody was listening"
1037        // must not render as "the module said nothing".
1038        let ring = ring(10, 1024, 128);
1039        let snapshot = ring.snapshot(None, None);
1040        assert!(matches!(snapshot.capture, CaptureState::NotCaptured { .. }));
1041        assert!(snapshot.entries.is_empty());
1042    }
1043
1044    #[test]
1045    fn read_failure_does_not_taint_generations_after_its_section_is_evicted() {
1046        let mut ring = StderrRing::new(StderrTailConfig {
1047            max_lines: 1,
1048            ..Default::default()
1049        });
1050        ring.begin_process();
1051        ring.mark_captured();
1052        ring.push_line("old output");
1053        ring.mark_incomplete("read failed");
1054        assert!(matches!(
1055            ring.snapshot(None, None).capture,
1056            CaptureState::Incomplete { .. }
1057        ));
1058        ring.begin_process();
1059        ring.mark_captured();
1060        ring.push_line("new output");
1061        assert_eq!(ring.snapshot(None, None).capture, CaptureState::Captured);
1062    }
1063
1064    #[test]
1065    fn a_captured_module_that_printed_nothing_is_distinguishable_from_an_uncaptured_one() {
1066        let mut captured = ring(10, 1024, 128);
1067        captured.mark_captured();
1068        let uncaptured = ring(10, 1024, 128);
1069
1070        let captured = captured.snapshot(None, None);
1071        let uncaptured = uncaptured.snapshot(None, None);
1072
1073        // Both are empty. Only the capture state separates them, which is the
1074        // point -- an assertion on emptiness alone would pass either way.
1075        assert!(captured.entries.is_empty());
1076        assert!(uncaptured.entries.is_empty());
1077        assert_eq!(captured.capture, CaptureState::Captured);
1078        assert!(matches!(
1079            uncaptured.capture,
1080            CaptureState::NotCaptured { .. }
1081        ));
1082    }
1083
1084    #[test]
1085    fn the_line_cap_evicts_oldest_first_and_counts_what_it_dropped() {
1086        let mut ring = ring(3, 10_000, 128);
1087        ring.mark_captured();
1088        for i in 0..6 {
1089            ring.push_line(&format!("line{i}"));
1090        }
1091        let snapshot = ring.snapshot(None, None);
1092        assert_eq!(lines(&snapshot), vec!["line3", "line4", "line5"]);
1093        // Without this the tail silently becomes "the last lines that happened
1094        // to survive" and reads as complete.
1095        assert_eq!(snapshot.dropped_lines, 3);
1096    }
1097
1098    #[test]
1099    fn the_byte_cap_binds_before_the_line_cap_when_lines_are_large() {
1100        // 100 lines allowed, but only ~30 bytes of them.
1101        let mut ring = ring(100, 30, 128);
1102        ring.mark_captured();
1103        for i in 0..10 {
1104            ring.push_line(&format!("{i}--------")); // 9 bytes each
1105        }
1106        let snapshot = ring.snapshot(None, None);
1107        assert!(
1108            snapshot.entries.len() < 10,
1109            "byte cap did not bind: {} entries retained",
1110            snapshot.entries.len()
1111        );
1112        let retained: usize = lines(&snapshot).iter().map(String::len).sum();
1113        assert!(
1114            retained <= 30,
1115            "retained {retained} bytes over a 30 byte cap"
1116        );
1117        assert!(snapshot.dropped_lines > 0);
1118    }
1119
1120    #[test]
1121    fn one_enormous_line_is_truncated_rather_than_evicting_the_tail() {
1122        // The pathological-emitter case: without per-line truncation this single
1123        // line would evict every other line AND be unreadable itself.
1124        let mut ring = ring(10, 10_000, 64);
1125        ring.mark_captured();
1126        ring.push_line("context line that must survive");
1127        ring.push_line(&"x".repeat(40_000));
1128
1129        let snapshot = ring.snapshot(None, None);
1130        let kept = &snapshot.entries;
1131        assert!(matches!(
1132            &kept[0],
1133            TailEntry::Line { text, truncated: false, .. }
1134                if text == "context line that must survive"
1135        ));
1136        let TailEntry::Line {
1137            text, truncated, ..
1138        } = &kept[1]
1139        else {
1140            panic!("expected a truncated line");
1141        };
1142        assert_eq!(text, &"x".repeat(64));
1143        assert!(*truncated);
1144    }
1145
1146    #[test]
1147    fn truncation_is_visible_so_a_cut_line_is_not_mistaken_for_a_short_one() {
1148        let mut ring = ring(10, 10_000, 16);
1149        ring.mark_captured();
1150        ring.push_line("0123456789abcdefghij");
1151        ring.push_line("short");
1152
1153        let snapshot = ring.snapshot(None, None);
1154        let TailEntry::Line { truncated, .. } = &snapshot.entries[0] else {
1155            panic!("expected a line");
1156        };
1157        assert!(truncated);
1158        let TailEntry::Line { truncated, .. } = &snapshot.entries[1] else {
1159            panic!("expected a line");
1160        };
1161        assert!(!truncated, "a short line must not be reported as truncated");
1162    }
1163
1164    #[test]
1165    fn truncation_cuts_on_a_char_boundary_rather_than_splitting_utf8() {
1166        // A panic message with non-ASCII in it is not exotic, and slicing mid
1167        // sequence would panic while capturing a crash.
1168        let mut ring = ring(10, 10_000, 5);
1169        ring.mark_captured();
1170        ring.push_line("aa€€€€");
1171        let snapshot = ring.snapshot(None, None);
1172        let TailEntry::Line {
1173            text, truncated, ..
1174        } = &snapshot.entries[0]
1175        else {
1176            panic!("expected a line");
1177        };
1178        assert!(truncated);
1179        assert!(text.starts_with("aa"));
1180    }
1181
1182    #[test]
1183    fn a_restart_boundary_keeps_generations_distinguishable() {
1184        let mut ring = ring(10, 10_000, 128);
1185        ring.mark_captured();
1186        ring.push_line("before the crash");
1187        ring.push_process_start();
1188        ring.push_line("after the respawn");
1189
1190        let snapshot = ring.snapshot(None, None);
1191        assert_eq!(
1192            snapshot.entries,
1193            vec![
1194                TailEntry::Line {
1195                    text: "before the crash".to_string(),
1196                    truncated: false,
1197                    at_ms: None,
1198                },
1199                TailEntry::ProcessStart,
1200                TailEntry::Line {
1201                    text: "after the respawn".to_string(),
1202                    truncated: false,
1203                    at_ms: None,
1204                },
1205            ]
1206        );
1207    }
1208
1209    #[test]
1210    fn the_ring_survives_respawn_because_the_cause_is_written_before_the_exit() {
1211        // Clearing on restart would discard the lines at the exact moment they
1212        // become the thing being asked for.
1213        let mut ring = ring(10, 10_000, 128);
1214        ring.mark_captured();
1215        ring.push_line("Error: storage section missing");
1216        ring.push_process_start();
1217
1218        let snapshot = ring.snapshot(None, None);
1219        assert!(lines(&snapshot).contains(&"Error: storage section missing".to_string()));
1220    }
1221
1222    #[test]
1223    fn a_caller_limit_returns_the_newest_lines_not_the_oldest() {
1224        let mut ring = ring(100, 100_000, 128);
1225        ring.mark_captured();
1226        for i in 0..10 {
1227            ring.push_line(&format!("line{i}"));
1228        }
1229        let snapshot = ring.snapshot(Some(3), None);
1230        assert_eq!(lines(&snapshot), vec!["line7", "line8", "line9"]);
1231    }
1232
1233    #[test]
1234    fn a_caller_line_limit_keeps_the_boundary_before_the_selected_line() {
1235        let mut ring = ring(100, 100_000, 128);
1236        ring.mark_captured();
1237        ring.push_line("before restart");
1238        ring.push_process_start();
1239        ring.push_line("after restart");
1240
1241        let snapshot = ring.snapshot(Some(1), None);
1242        assert_eq!(
1243            snapshot.entries,
1244            vec![
1245                TailEntry::ProcessStart,
1246                TailEntry::Line {
1247                    text: "after restart".to_string(),
1248                    truncated: false,
1249                    at_ms: None,
1250                },
1251            ]
1252        );
1253    }
1254
1255    #[test]
1256    fn a_caller_line_limit_omits_a_trailing_boundary_after_the_selected_line() {
1257        let mut ring = ring(100, 100_000, 128);
1258        ring.mark_captured();
1259        ring.push_line("before restart");
1260        ring.push_process_start();
1261
1262        let snapshot = ring.snapshot(Some(1), None);
1263        assert_eq!(
1264            snapshot.entries,
1265            vec![TailEntry::Line {
1266                text: "before restart".to_string(),
1267                truncated: false,
1268                at_ms: None,
1269            }]
1270        );
1271    }
1272
1273    #[test]
1274    fn a_caller_limit_reports_what_it_withheld_rather_than_looking_complete() {
1275        let mut ring = ring(100, 100_000, 128);
1276        ring.mark_captured();
1277        for i in 0..10 {
1278            ring.push_line(&format!("line{i}"));
1279        }
1280        // Nothing was evicted; the narrowing is the caller's own. It still has to
1281        // be reported, or a 3-line request reads as a module that wrote 3 lines.
1282        assert_eq!(ring.snapshot(Some(3), None).dropped_lines, 7);
1283        assert_eq!(ring.snapshot(None, None).dropped_lines, 0);
1284    }
1285
1286    #[test]
1287    fn a_caller_limit_cannot_widen_the_rings_own_caps() {
1288        let mut ring = ring(2, 10_000, 128);
1289        ring.mark_captured();
1290        for i in 0..5 {
1291            ring.push_line(&format!("line{i}"));
1292        }
1293        let snapshot = ring.snapshot(Some(1000), Some(1_000_000));
1294        assert_eq!(lines(&snapshot).len(), 2);
1295    }
1296
1297    fn shared(max_lines: usize, max_bytes: usize, max_line_bytes: usize) -> Arc<Mutex<StderrRing>> {
1298        Arc::new(Mutex::new(ring(max_lines, max_bytes, max_line_bytes)))
1299    }
1300
1301    /// Records each forwarded write separately, so a test can tell one write of
1302    /// `b"abc\n"` from two writes of `b"abc"` and `b"\n"`.
1303    #[derive(Default)]
1304    struct RecordingSink {
1305        writes: Vec<Vec<u8>>,
1306    }
1307
1308    impl OutputSink for RecordingSink {
1309        fn write_line(&mut self, line: &[u8]) {
1310            self.writes.push(line.to_vec());
1311        }
1312    }
1313
1314    /// Yields predetermined chunks, one per read, so a test controls exactly
1315    /// where the byte stream is split.
1316    struct ChunkedReader {
1317        chunks: VecDeque<Vec<u8>>,
1318    }
1319
1320    impl AsyncRead for ChunkedReader {
1321        fn poll_read(
1322            mut self: Pin<&mut Self>,
1323            _cx: &mut Context<'_>,
1324            buf: &mut ReadBuf<'_>,
1325        ) -> Poll<io::Result<()>> {
1326            match self.chunks.pop_front() {
1327                None => Poll::Ready(Ok(())),
1328                Some(chunk) => {
1329                    buf.put_slice(&chunk);
1330                    Poll::Ready(Ok(()))
1331                }
1332            }
1333        }
1334    }
1335
1336    struct FailingReader {
1337        bytes: Vec<u8>,
1338        emitted: bool,
1339    }
1340
1341    impl AsyncRead for FailingReader {
1342        fn poll_read(
1343            mut self: Pin<&mut Self>,
1344            _cx: &mut Context<'_>,
1345            buf: &mut ReadBuf<'_>,
1346        ) -> Poll<io::Result<()>> {
1347            if self.emitted {
1348                return Poll::Ready(Err(io::Error::other("reader failed")));
1349            }
1350            self.emitted = true;
1351            buf.put_slice(&self.bytes);
1352            Poll::Ready(Ok(()))
1353        }
1354    }
1355
1356    #[tokio::test]
1357    async fn the_pump_splits_on_newlines_and_keeps_a_trailing_fragment() {
1358        let ring = shared(10, 10_000, 128);
1359        // No trailing newline on the last line: a crashing process routinely dies
1360        // mid-line, and that fragment is often the message worth reading.
1361        let source = std::io::Cursor::new(b"one\ntwo\nthree".to_vec());
1362        let mut sink = RecordingSink::default();
1363        pump_stderr_into(source, Arc::clone(&ring), &mut sink).await;
1364
1365        let snapshot = lock_ring(&ring).snapshot(None, None);
1366        assert_eq!(lines(&snapshot), vec!["one", "two", "three"]);
1367        assert_eq!(snapshot.capture, CaptureState::Captured);
1368        assert_eq!(
1369            sink.writes,
1370            vec![b"one\n".to_vec(), b"two\n".to_vec(), b"three".to_vec()]
1371        );
1372    }
1373
1374    #[tokio::test]
1375    async fn a_read_failure_keeps_prior_lines_and_marks_the_capture_incomplete() {
1376        let ring = shared(10, 10_000, 128);
1377        let source = FailingReader {
1378            bytes: b"crash cause\n".to_vec(),
1379            emitted: false,
1380        };
1381        let mut sink = RecordingSink::default();
1382        pump_stderr_into(source, Arc::clone(&ring), &mut sink).await;
1383
1384        let snapshot = lock_ring(&ring).snapshot(None, None);
1385        assert_eq!(lines(&snapshot), vec!["crash cause"]);
1386        assert!(matches!(
1387            snapshot.capture,
1388            CaptureState::Incomplete { ref reason } if reason.contains("reader failed")
1389        ));
1390        assert_eq!(sink.writes, vec![b"crash cause\n".to_vec()]);
1391    }
1392
1393    #[tokio::test]
1394    async fn every_captured_line_is_also_forwarded() {
1395        // Forwarding is not optional. The daemon log is overwhelmingly module
1396        // output; a tap that captured without forwarding would leave it nearly
1397        // empty and every existing reader would report clean on nothing.
1398        let ring = shared(10, 10_000, 128);
1399        let source = std::io::Cursor::new(b"alpha\nbeta\n".to_vec());
1400        let mut sink = RecordingSink::default();
1401        pump_stderr_into(source, Arc::clone(&ring), &mut sink).await;
1402
1403        assert_eq!(sink.writes, vec![b"alpha\n".to_vec(), b"beta\n".to_vec()]);
1404    }
1405
1406    #[tokio::test]
1407    async fn each_forwarded_line_is_exactly_one_write() {
1408        // Inheriting the fd gave line atomicity for free. Reading a pipe and
1409        // re-emitting can split a line that used to be atomic, so the framing
1410        // must be one syscall per complete line -- asserted as one write per
1411        // line, not merely as correct bytes.
1412        let ring = shared(10, 10_000, 128);
1413        let source = std::io::Cursor::new(b"first\nsecond\nthird\n".to_vec());
1414        let mut sink = RecordingSink::default();
1415        pump_stderr_into(source, Arc::clone(&ring), &mut sink).await;
1416
1417        assert_eq!(sink.writes.len(), 3);
1418        for write in &sink.writes {
1419            assert_eq!(
1420                write.iter().filter(|byte| **byte == b'\n').count(),
1421                1,
1422                "a write carried something other than exactly one complete line"
1423            );
1424            assert_eq!(*write.last().unwrap(), b'\n');
1425        }
1426    }
1427
1428    #[test]
1429    fn the_first_process_start_is_not_recorded_because_it_divides_nothing() {
1430        // Otherwise a module that printed nothing renders as a lone boundary
1431        // marker, and every caller has to decide whether that counts as silence.
1432        let mut ring = ring(10, 10_000, 128);
1433        ring.push_process_start();
1434        assert!(ring.snapshot(None, None).entries.is_empty());
1435
1436        ring.push_line("first process said this");
1437        ring.push_process_start();
1438        assert!(
1439            matches!(ring.entries.back(), Some(Slot::ProcessStart { .. })),
1440            "a boundary with output before it must be recorded"
1441        );
1442        ring.push_line("second process said this");
1443        assert_eq!(
1444            ring.snapshot(None, None).entries,
1445            vec![
1446                TailEntry::Line {
1447                    text: "first process said this".to_string(),
1448                    truncated: false,
1449                    at_ms: None,
1450                },
1451                TailEntry::ProcessStart,
1452                TailEntry::Line {
1453                    text: "second process said this".to_string(),
1454                    truncated: false,
1455                    at_ms: None,
1456                },
1457            ],
1458            "only the boundary with output before it may be shown"
1459        );
1460    }
1461
1462    #[test]
1463    fn a_process_start_is_recorded_when_only_dropped_lines_precede_it() {
1464        // The ring can be non-empty in the sense that matters -- lines were
1465        // written and evicted -- while `entries` is empty. Suppressing the
1466        // boundary there would attribute surviving output to the wrong process.
1467        let mut ring = ring(1, 10_000, 128);
1468        ring.push_line("evicted");
1469        ring.push_line("also evicted");
1470        // Emptying `entries` by hand must also zero the running totals kept
1471        // beside it, or the ring holds counts for lines it no longer has and
1472        // any later eviction decision is made against the stale numbers.
1473        ring.entries.clear();
1474        ring.lines = 0;
1475        ring.bytes = 0;
1476        ring.push_process_start();
1477        ring.push_line("survivor");
1478        assert_eq!(
1479            ring.snapshot(None, None).entries,
1480            vec![
1481                TailEntry::ProcessStart,
1482                TailEntry::Line {
1483                    text: "survivor".to_string(),
1484                    truncated: false,
1485                    at_ms: None,
1486                },
1487            ]
1488        );
1489    }
1490
1491    fn line(text: &str) -> TailEntry {
1492        TailEntry::Line {
1493            text: text.to_string(),
1494            truncated: false,
1495            at_ms: None,
1496        }
1497    }
1498
1499    #[test]
1500    fn a_late_line_from_a_retired_process_lands_in_that_processs_section() {
1501        // The reader of a process that already exited may deliver its last
1502        // lines after the next process started. Appending them would put the
1503        // crash's own explanation under its successor's boundary.
1504        let mut ring = ring(10, 10_000, 128);
1505        ring.mark_captured();
1506        let old = ring.begin_process();
1507        ring.push_line_from(old, "old: booting");
1508        ring.retire_pump(old);
1509        let new = ring.begin_process();
1510        ring.push_line_from(new, "new: booting");
1511        ring.push_line_from(old, "old: config error");
1512
1513        assert_eq!(
1514            ring.snapshot(None, None).entries,
1515            vec![
1516                line("old: booting"),
1517                line("old: config error"),
1518                TailEntry::ProcessStart,
1519                line("new: booting"),
1520            ]
1521        );
1522    }
1523
1524    #[test]
1525    fn a_line_from_a_process_that_was_not_retired_is_appended_as_it_arrives() {
1526        // A swap runs the incumbent alongside its candidate; until the
1527        // supervisor retires it, the incumbent is live and its lines are news.
1528        let mut ring = ring(10, 10_000, 128);
1529        ring.mark_captured();
1530        let incumbent = ring.begin_process();
1531        ring.push_line_from(incumbent, "incumbent: before");
1532        let candidate = ring.begin_process();
1533        ring.push_line_from(candidate, "candidate: booting");
1534        ring.push_line_from(incumbent, "incumbent: still serving");
1535
1536        assert_eq!(
1537            ring.snapshot(None, None).entries,
1538            vec![
1539                line("incumbent: before"),
1540                TailEntry::ProcessStart,
1541                line("candidate: booting"),
1542                line("incumbent: still serving"),
1543            ]
1544        );
1545    }
1546
1547    #[test]
1548    fn a_late_line_keeps_its_section_when_the_process_had_printed_nothing_before() {
1549        // A process whose reader had delivered nothing when its successor
1550        // started has a boundary with nothing after it. Dropping that boundary
1551        // as redundant would file the late line under the process before.
1552        let mut ring = ring(10, 10_000, 128);
1553        ring.mark_captured();
1554        let first = ring.begin_process();
1555        ring.push_line_from(first, "first: done");
1556        ring.finish_pump(first);
1557        let old = ring.begin_process();
1558        ring.retire_pump(old);
1559        let new = ring.begin_process();
1560        ring.push_line_from(new, "new: booting");
1561        ring.push_line_from(old, "old: config error");
1562
1563        assert_eq!(
1564            ring.snapshot(None, None).entries,
1565            vec![
1566                line("first: done"),
1567                TailEntry::ProcessStart,
1568                line("old: config error"),
1569                TailEntry::ProcessStart,
1570                line("new: booting"),
1571            ]
1572        );
1573    }
1574
1575    #[test]
1576    fn a_late_line_whose_section_was_evicted_counts_as_dropped() {
1577        let mut ring = ring(2, 10_000, 128);
1578        ring.mark_captured();
1579        let old = ring.begin_process();
1580        ring.push_line_from(old, "old");
1581        ring.retire_pump(old);
1582        let new = ring.begin_process();
1583        for text in ["new 1", "new 2", "new 3"] {
1584            ring.push_line_from(new, text);
1585        }
1586        // The old section and the boundary after it are gone; the late line
1587        // belongs in front of everything retained.
1588        ring.push_line_from(old, "old, late");
1589
1590        let snapshot = ring.snapshot(None, None);
1591        assert_eq!(snapshot.entries, vec![line("new 2"), line("new 3")]);
1592        assert_eq!(snapshot.dropped_lines, 3);
1593    }
1594
1595    #[test]
1596    fn a_late_reader_reads_incomplete_until_its_pipe_reaches_eof() {
1597        let mut ring = ring(10, 10_000, 128);
1598        ring.mark_captured();
1599        let old = ring.begin_process();
1600        ring.retire_pump(old);
1601        ring.mark_pump_late(old, "still open");
1602        ring.begin_process();
1603        assert_eq!(
1604            ring.snapshot(None, None).capture,
1605            CaptureState::Incomplete {
1606                reason: "still open".to_string()
1607            }
1608        );
1609
1610        ring.finish_pump(old);
1611        assert_eq!(ring.snapshot(None, None).capture, CaptureState::Captured);
1612    }
1613
1614    #[test]
1615    fn silent_restarts_do_not_grow_the_ring() {
1616        let mut ring = ring(10, 10_000, 128);
1617        ring.mark_captured();
1618        ring.push_line("once");
1619        for _ in 0..100 {
1620            let generation = ring.begin_process();
1621            ring.finish_pump(generation);
1622        }
1623        assert_eq!(ring.entries.len(), 2);
1624    }
1625
1626    #[tokio::test]
1627    async fn the_pump_marks_captured_even_when_the_module_writes_nothing() {
1628        // Clean EOF with no output is a module that was quiet, not one nobody
1629        // listened to -- and the two must not render alike.
1630        let ring = shared(10, 10_000, 128);
1631        let source = std::io::Cursor::new(Vec::new());
1632        let mut sink = RecordingSink::default();
1633        pump_stderr_into(source, Arc::clone(&ring), &mut sink).await;
1634
1635        let snapshot = lock_ring(&ring).snapshot(None, None);
1636        assert!(snapshot.entries.is_empty());
1637        assert_eq!(snapshot.capture, CaptureState::Captured);
1638        assert!(sink.writes.is_empty());
1639    }
1640
1641    #[tokio::test]
1642    async fn a_line_with_no_newline_cannot_grow_the_reader_without_bound() {
1643        // A module fault must not become a daemon fault: without the pending
1644        // ceiling this buffer grows to whatever the module writes.
1645        let ring = shared(10, 10_000_000, 4 * 1024 * 1024);
1646        let source = std::io::Cursor::new(vec![b'x'; MAX_PENDING_LINE_BYTES + 4096]);
1647        let mut sink = RecordingSink::default();
1648        pump_stderr_into(source, Arc::clone(&ring), &mut sink).await;
1649
1650        let snapshot = lock_ring(&ring).snapshot(None, None);
1651        assert_eq!(
1652            lines(&snapshot).len(),
1653            2,
1654            "expected a forced flush at the ceiling plus the remainder"
1655        );
1656        assert_eq!(
1657            sink.writes,
1658            vec![vec![b'x'; MAX_PENDING_LINE_BYTES], vec![b'x'; 4096],],
1659            "forced flushes and EOF fragments must not invent delimiters"
1660        );
1661    }
1662
1663    #[tokio::test]
1664    async fn boundaries_truncation_and_framing_do_not_depend_on_chunk_splits() {
1665        // The same stream split at hostile boundaries -- mid-line, between a CR
1666        // and its LF, and a line sitting exactly on the per-line cap -- must
1667        // produce the same ring entries and forwarded bytes as any other split.
1668        let ring = shared(100, 100_000, 8);
1669        let source = ChunkedReader {
1670            chunks: vec![
1671                b"fir".to_vec(),
1672                b"st\nsec".to_vec(),
1673                b"ond\ncarry\r".to_vec(),
1674                b"\nover\n".to_vec(),
1675                b"12345678\n".to_vec(),
1676                b"1234567".to_vec(),
1677                b"89\n".to_vec(),
1678                b"tail".to_vec(),
1679            ]
1680            .into_iter()
1681            .collect(),
1682        };
1683        let mut sink = RecordingSink::default();
1684        pump_stderr_into(source, Arc::clone(&ring), &mut sink).await;
1685
1686        let snapshot = lock_ring(&ring).snapshot(None, None);
1687        assert_eq!(snapshot.capture, CaptureState::Captured);
1688        assert_eq!(
1689            untimed(snapshot.entries),
1690            vec![
1691                TailEntry::Line {
1692                    text: "first".to_string(),
1693                    truncated: false,
1694                    at_ms: None,
1695                },
1696                TailEntry::Line {
1697                    text: "second".to_string(),
1698                    truncated: false,
1699                    at_ms: None,
1700                },
1701                // The pump delimits on '\n' alone; a CR belongs to the line body.
1702                TailEntry::Line {
1703                    text: "carry\r".to_string(),
1704                    truncated: false,
1705                    at_ms: None,
1706                },
1707                TailEntry::Line {
1708                    text: "over".to_string(),
1709                    truncated: false,
1710                    at_ms: None,
1711                },
1712                // Exactly at the per-line cap: kept whole.
1713                TailEntry::Line {
1714                    text: "12345678".to_string(),
1715                    truncated: false,
1716                    at_ms: None,
1717                },
1718                // One byte past the cap: cut, and marked as cut.
1719                TailEntry::Line {
1720                    text: "12345678".to_string(),
1721                    truncated: true,
1722                    at_ms: None,
1723                },
1724                TailEntry::Line {
1725                    text: "tail".to_string(),
1726                    truncated: false,
1727                    at_ms: None,
1728                },
1729            ]
1730        );
1731        assert_eq!(
1732            sink.writes,
1733            vec![
1734                b"first\n".to_vec(),
1735                b"second\n".to_vec(),
1736                b"carry\r\n".to_vec(),
1737                b"over\n".to_vec(),
1738                b"12345678\n".to_vec(),
1739                b"123456789\n".to_vec(),
1740                b"tail".to_vec(),
1741            ]
1742        );
1743    }
1744
1745    #[tokio::test]
1746    async fn a_line_with_no_newline_is_not_rescanned_from_byte_zero_on_every_chunk() {
1747        // One 1 MiB line arrives in 8192-byte reads. Searching the whole
1748        // pending buffer for a newline on every chunk scans each byte once per
1749        // chunk that arrived after it -- about 64 MiB examined per MiB of
1750        // output. Searching only the bytes that arrived since the last search
1751        // scans each byte once.
1752        let input = vec![b'x'; MAX_PENDING_LINE_BYTES + 4096];
1753        let ring = shared(10, 10_000_000, 4 * 1024 * 1024);
1754        let source = std::io::Cursor::new(input.clone());
1755        let mut sink = RecordingSink::default();
1756
1757        take_scanned_bytes();
1758        pump_stderr_into(source, Arc::clone(&ring), &mut sink).await;
1759        let scanned = take_scanned_bytes();
1760
1761        assert!(
1762            scanned <= 2 * input.len(),
1763            "newline searches examined {scanned} bytes for {} bytes of input; \
1764             each chunk must search only newly arrived bytes",
1765            input.len()
1766        );
1767    }
1768
1769    fn now_ms() -> u64 {
1770        unix_ms(SystemTime::now())
1771    }
1772
1773    #[tokio::test]
1774    async fn a_captured_line_carries_the_time_the_reader_framed_it() {
1775        // The ring is read after the fact (`ck module stderr`), and without a
1776        // time a reader cannot tell a crash's last words from a line written
1777        // hours before it.
1778        let ring = shared(10, 10_000, 128);
1779        let before = now_ms();
1780        let source = std::io::Cursor::new(b"first\nsecond".to_vec());
1781        pump_stderr_into(source, Arc::clone(&ring), &mut RecordingSink::default()).await;
1782        let after = now_ms();
1783
1784        let entries = lock_ring(&ring).snapshot(None, None).entries;
1785        assert_eq!(entries.len(), 2);
1786        for entry in entries {
1787            let TailEntry::Line { text, at_ms, .. } = entry else {
1788                panic!("expected only lines, got {entry:?}");
1789            };
1790            let at_ms = at_ms.unwrap_or_else(|| panic!("line {text:?} has no capture time"));
1791            assert!(
1792                (before..=after).contains(&at_ms),
1793                "line {text:?} stamped {at_ms}, outside the pump's run {before}..={after}"
1794            );
1795        }
1796    }
1797
1798    /// Reads a capture file written through the production sink.
1799    async fn capture_through_file_sink(chunks: Vec<Vec<u8>>) -> (String, u64, u64) {
1800        let temp = cortexkit_test_support::ScratchDir::new("stderr-capture-stamp");
1801        let path = temp.path().join("stamped.stderr.log");
1802        let sink = ChildOutputSink::open(&path, cortexkit_log::Retention::default()).unwrap();
1803        let ring = shared(10, 10_000, 128);
1804        let generation = lock_ring(&ring).begin_process();
1805        let before = now_ms();
1806        pump_stderr_to(
1807            ChunkedReader {
1808                chunks: chunks.into_iter().collect(),
1809            },
1810            ring,
1811            generation,
1812            sink,
1813        )
1814        .await;
1815        let after = now_ms();
1816        (std::fs::read_to_string(&path).unwrap(), before, after)
1817    }
1818
1819    /// Checks the prefix's shape by position, independently of
1820    /// [`split_capture_stamp`], so a parser that accepted a malformed stamp
1821    /// could not vouch for the writer that produced it.
1822    fn assert_stamp_shape(line: &str) {
1823        let bytes = line.as_bytes();
1824        assert!(bytes.len() > 25, "line too short for a stamp: {line:?}");
1825        for (index, byte) in bytes[..25].iter().enumerate() {
1826            let expected_separator = match index {
1827                4 | 7 => Some(b'-'),
1828                10 => Some(b'T'),
1829                13 | 16 => Some(b':'),
1830                19 => Some(b'.'),
1831                23 => Some(b'Z'),
1832                24 => Some(b' '),
1833                _ => None,
1834            };
1835            match expected_separator {
1836                Some(separator) => assert_eq!(*byte, separator, "byte {index} of {line:?}"),
1837                None => assert!(byte.is_ascii_digit(), "byte {index} of {line:?}"),
1838            }
1839        }
1840    }
1841
1842    #[tokio::test]
1843    async fn the_capture_file_stamps_each_line_and_keeps_the_module_bytes_verbatim() {
1844        // The second line begins with a stamp of its own (a module that logs
1845        // in the fleet format to stderr). Its bytes must survive untouched:
1846        // the capture stamp goes in front, nothing is parsed or replaced.
1847        let module_lines = [
1848            "plain line",
1849            "2020-01-01T00:00:00.000Z INFO  mymod: own stamp",
1850        ];
1851        let input = format!("{}\n{}\n", module_lines[0], module_lines[1]);
1852        let (contents, before, after) = capture_through_file_sink(vec![input.into_bytes()]).await;
1853
1854        assert!(contents.ends_with('\n'));
1855        let lines: Vec<&str> = contents.lines().collect();
1856        assert_eq!(lines.len(), 2, "capture file: {contents:?}");
1857        for (line, module_line) in lines.iter().zip(module_lines) {
1858            assert_stamp_shape(line);
1859            assert_eq!(&line[25..], module_line, "module bytes changed");
1860            let (at_ms, rest) = split_capture_stamp(line).unwrap();
1861            assert_eq!(rest, module_line);
1862            // Millisecond stamps round the pump's own bounds down.
1863            assert!(
1864                (before..=after).contains(&at_ms),
1865                "stamped {at_ms}, outside the pump's run {before}..={after}"
1866            );
1867        }
1868    }
1869
1870    #[tokio::test]
1871    async fn a_line_split_across_several_writes_is_stamped_once() {
1872        // A module that writes one line in pieces, and a pipe that delivers it
1873        // in pieces, must still produce one stamp at the front of the line and
1874        // none in its middle.
1875        let (contents, _, _) = capture_through_file_sink(vec![
1876            b"par".to_vec(),
1877            b"tial li".to_vec(),
1878            b"ne\nwhole\n".to_vec(),
1879        ])
1880        .await;
1881
1882        let lines: Vec<&str> = contents.lines().collect();
1883        assert_eq!(lines.len(), 2, "capture file: {contents:?}");
1884        for (line, module_line) in lines.iter().zip(["partial line", "whole"]) {
1885            assert_stamp_shape(line);
1886            assert_eq!(&line[25..], module_line, "capture file: {contents:?}");
1887        }
1888    }
1889
1890    #[tokio::test]
1891    async fn a_line_flushed_at_the_ceiling_is_stamped_only_at_the_start_of_each_file_line() {
1892        // Past the reassembly ceiling the pending bytes go out without their
1893        // newline. The file sink ends every write with one, so the rest of
1894        // the line starts a new file line, and that is where its stamp goes;
1895        // a stamp anywhere else would sit in the middle of module bytes.
1896        let mut long = vec![b'x'; MAX_PENDING_LINE_BYTES + 100];
1897        long.push(b'\n');
1898        // The reader's buffer holds 8 KiB, so feed it reads no larger than that.
1899        let chunks = long.chunks(8192).map(<[u8]>::to_vec).collect();
1900        let (contents, _, _) = capture_through_file_sink(chunks).await;
1901
1902        let lines: Vec<&str> = contents.lines().collect();
1903        assert_eq!(lines.len(), 2, "expected the flushed piece and the rest");
1904        for line in &lines {
1905            assert_stamp_shape(line);
1906            assert!(
1907                line[25..].bytes().all(|byte| byte == b'x'),
1908                "a stamp landed inside module bytes"
1909            );
1910        }
1911        let module_bytes: usize = lines.iter().map(|line| line.len() - 25).sum();
1912        assert_eq!(module_bytes, MAX_PENDING_LINE_BYTES + 100);
1913    }
1914
1915    #[test]
1916    fn the_capture_stamp_is_the_daemon_log_timestamp_form() {
1917        for (at_ms, text) in [
1918            (0, "1970-01-01T00:00:00.000Z"),
1919            (951_868_799_999, "2000-02-29T23:59:59.999Z"),
1920            (1_789_801_440_685, "2026-09-19T07:04:00.685Z"),
1921            (4_107_542_400_001, "2100-03-01T00:00:00.001Z"),
1922        ] {
1923            let stamp = format_capture_stamp(at_ms);
1924            assert_eq!(stamp, text);
1925            assert_eq!(stamp.len(), CAPTURE_STAMP_LEN);
1926            // The daemon's own log parser reads the same instant from it, so
1927            // one parser serves both files.
1928            let daemon_line = format!("{stamp} INFO  subc: probe");
1929            let parsed = cortexkit_log::parse_line(&daemon_line).unwrap();
1930            assert_eq!(
1931                parsed.timestamp,
1932                UNIX_EPOCH + std::time::Duration::from_millis(at_ms)
1933            );
1934            assert_eq!(
1935                split_capture_stamp(&format!("{stamp} body")),
1936                Some((at_ms, "body"))
1937            );
1938        }
1939    }
1940
1941    #[test]
1942    fn a_line_without_a_well_formed_stamp_has_no_capture_time() {
1943        for line in [
1944            "",
1945            "plain module output",
1946            "2026-09-19T07:04:00.685Z",
1947            "2026-09-19T07:04:00.685Zbody",
1948            "2026-09-19T07:04:00.685z body",
1949            "2026-09-19 07:04:00.685Z body",
1950            "2026-09-19T07:04:00Z body",
1951            "2026-02-30T07:04:00.685Z body",
1952            "2026-13-19T07:04:00.685Z body",
1953            "2026-09-19T24:04:00.685Z body",
1954            "2026-09-19T07:04:00.6a5Z body",
1955            "1969-12-31T23:59:59.999Z body",
1956        ] {
1957            assert_eq!(split_capture_stamp(line), None, "{line:?}");
1958        }
1959    }
1960
1961    #[test]
1962    fn a_byte_limit_smaller_than_one_line_still_returns_that_line() {
1963        // Returning nothing would be indistinguishable from a quiet module, which
1964        // is the failure this module exists to prevent.
1965        let mut ring = ring(10, 10_000, 128);
1966        ring.mark_captured();
1967        ring.push_line("a line considerably longer than the request limit");
1968        let snapshot = ring.snapshot(None, Some(4));
1969        assert_eq!(snapshot.entries.len(), 1);
1970    }
1971
1972    #[test]
1973    fn an_incoherent_config_clamps_the_line_cap_and_keeps_its_restart_boundary() {
1974        let config = StderrTailConfig::new(2, 10, 100);
1975        assert_eq!(config.max_line_bytes, config.max_bytes);
1976        let mut ring = StderrRing::new(config);
1977        ring.mark_captured();
1978        ring.push_line("old");
1979        ring.push_process_start();
1980        ring.push_line("new process line longer than the ring byte cap");
1981
1982        assert_eq!(
1983            ring.snapshot(None, None).entries,
1984            vec![
1985                TailEntry::ProcessStart,
1986                TailEntry::Line {
1987                    text: "new proces".to_string(),
1988                    truncated: true,
1989                    at_ms: None,
1990                },
1991            ]
1992        );
1993    }
1994}