saddle-observability 0.3.28

Saddle structured logging and trace correlation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
//! Original error content, streamed only into the existing diagnostic queue.
//! These records are privileged originals, not sanitized public error messages.
use super::*;
use std::{error::Error, fmt, io};

const PAYLOAD_BYTES: usize = 6144;

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum OriginalCaptureState {
    /// All exposed descriptions and the chain-end marker were accepted, not durable.
    CompleteEnqueued,
    OutputUnavailable,
    OutputRejected,
    FormattingFailed,
    CauseCycle,
    LegacyProjectionOnly,
}

#[derive(Serialize)]
struct Segment<'a> {
    schema_version: u8,
    event: &'static str,
    occurrence: DiagnosticOccurrence,
    sequence: u64,
    channel: &'static str,
    cause_depth: usize,
    payload: &'a str,
    state: &'static str,
}

trait OriginalOutput {
    fn submit(&self, segment: &Segment<'_>) -> DiagnosticSubmission;
}
impl OriginalOutput for EmergencyDiagnosticHandle {
    fn submit(&self, segment: &Segment<'_>) -> DiagnosticSubmission {
        self.submit_original_record(segment)
    }
}

struct Stream<'a, O: OriginalOutput> {
    output: &'a O,
    occurrence: DiagnosticOccurrence,
    sequence: u64,
    depth: usize,
    channel: &'static str,
    bytes: [u8; PAYLOAD_BYTES],
    len: usize,
    escaped: usize,
    failure: Option<OriginalCaptureState>,
    submission: DiagnosticSubmission,
}
impl<O: OriginalOutput> Stream<'_, O> {
    fn emit(&mut self, state: &'static str) -> fmt::Result {
        let payload = std::str::from_utf8(&self.bytes[..self.len]).map_err(|_| fmt::Error)?;
        let submission = self.output.submit(&Segment {
            schema_version: 1,
            event: "request_error_original",
            occurrence: self.occurrence,
            sequence: self.sequence,
            channel: self.channel,
            cause_depth: self.depth,
            payload,
            state,
        });
        if submission != DiagnosticSubmission::Enqueued {
            self.submission = submission;
            self.failure = Some(OriginalCaptureState::OutputRejected);
            return Err(fmt::Error);
        }
        self.sequence += 1;
        self.len = 0;
        self.escaped = 0;
        Ok(())
    }
    fn push(&mut self, text: &str) -> fmt::Result {
        if self.failure.is_some() {
            return Err(fmt::Error);
        }
        for c in text.chars() {
            let cost = match c {
                '"' | '\\' | '\n' | '\r' | '\t' | '\u{8}' | '\u{c}' => 2,
                '\u{0}'..='\u{1f}' => 6,
                _ => c.len_utf8(),
            };
            if self.escaped + cost > PAYLOAD_BYTES || self.len + c.len_utf8() > PAYLOAD_BYTES {
                self.emit("continuation")?;
            }
            let size = c.len_utf8();
            c.encode_utf8(&mut self.bytes[self.len..self.len + size]);
            self.len += size;
            self.escaped += cost;
        }
        Ok(())
    }
    fn json<T: Serialize>(&mut self, value: &T) -> fmt::Result {
        serde_json::to_writer(&mut *self, value).map_err(|_| fmt::Error)?;
        self.emit("field_end")
    }
    fn report_failure(&mut self, state: OriginalCaptureState) {
        // Preserve the already captured prefix; never mark it complete. If the
        // queue itself rejected, it may also reject this marker. Readback then
        // sees a missing terminal, which is necessarily incomplete.
        if self.failure == Some(OriginalCaptureState::OutputRejected) {
            return;
        }
        self.failure = Some(state);
        let marker = match state {
            OriginalCaptureState::FormattingFailed => "formatting_failed",
            OriginalCaptureState::CauseCycle => "cause_cycle",
            _ => "capture_failed",
        };
        let _ = self.emit(marker);
    }
}
impl<O: OriginalOutput> fmt::Write for Stream<'_, O> {
    fn write_str(&mut self, text: &str) -> fmt::Result {
        self.push(text)
    }
}
impl<O: OriginalOutput> io::Write for Stream<'_, O> {
    fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
        // serde_json writes UTF-8 str fragments and ASCII escapes; this adapter
        // rejects other binary writers rather than converting invalid bytes.
        let text = std::str::from_utf8(bytes).map_err(|_| io::ErrorKind::InvalidData)?;
        self.push(text).map_err(|_| io::ErrorKind::Other)?;
        Ok(bytes.len())
    }
    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

#[derive(Serialize)]
struct Header<'a> {
    timestamp_unix_ms: u128,
    context: crate::AdmissionEventContext<'a>,
    stage: RootRequestEvent,
    facts: SourceDetail<'a>,
    outcome: RootOutcomeFacts,
    original_contract: &'static str,
    source_interface: &'static str,
}
enum RawSource<'a> {
    Error(&'a (dyn Error + 'static)),
    Description(&'a dyn fmt::Display, &'a dyn fmt::Debug),
}
#[derive(Serialize)]
struct IoFacts {
    kind: Kind,
    os_code: Option<i32>,
}
struct Kind(io::ErrorKind);
impl Serialize for Kind {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(&format_args!("{:?}", self.0))
    }
}

impl RootDiagnosticScope<'_> {
    /// Capture any standard error before lossy mapping. Unknown types need no
    /// registration. Caller location is first observation, not invented origin.
    #[track_caller]
    pub fn source_error(
        &self,
        error: &(dyn Error + 'static),
        source_stage: saddle_core::DiagnosticStage,
        stage: RootRequestEvent,
        axes: RootOutcomeFacts,
    ) -> RootRequestFailure {
        let code = DiagnosticCode::new("framework.error").expect("static code");
        let facts = BoundedDiagnostic::capture(
            DiagnosticCategory::UnexpectedError,
            saddle_core::CaptureSite::FirstObserved,
            saddle_core::BoundedDiagnosticCause::new(source_stage, code),
        );
        self.source_error_with_facts(error, facts, code, stage, axes)
    }

    /// Optional typed facts/classification supplement, never replace, original
    /// Display/source. Owns no raw error after returning. Cleanup may supply the
    /// existing primary occurrence in facts; this does not mint a second receipt.
    pub fn source_error_with_facts(
        &self,
        error: &(dyn Error + 'static),
        facts: BoundedDiagnostic,
        classification: DiagnosticCode,
        stage: RootRequestEvent,
        axes: RootOutcomeFacts,
    ) -> RootRequestFailure {
        self.original_record(
            RawSource::Error(error),
            SourceDetail::Bounded(&facts),
            classification,
            stage,
            axes,
        )
    }

    /// A panic/string payload may have Display but no Error::source interface.
    /// Preserve it without inventing a cause chain. The original facts/ID are
    /// consumed once; no second capture is required at the logger boundary.
    pub fn source_description<D: fmt::Display + fmt::Debug>(
        &self,
        description: &D,
        facts: BoundedDiagnostic,
        classification: DiagnosticCode,
        stage: RootRequestEvent,
        axes: RootOutcomeFacts,
    ) -> RootRequestFailure {
        self.original_record(
            RawSource::Description(description, description),
            SourceDetail::Bounded(&facts),
            classification,
            stage,
            axes,
        )
    }

    /// Compatibility for an already captured panic diagnostic plus its original
    /// payload. Preserves ID/primary/location/stack status, does not recapture.
    pub fn source_existing_description<D: fmt::Display + fmt::Debug>(
        &self,
        description: &D,
        diagnostic: Diagnostic,
        classification: DiagnosticCode,
        stage: RootRequestEvent,
        axes: RootOutcomeFacts,
    ) -> RootRequestFailure {
        self.original_record(
            RawSource::Description(description, description),
            SourceDetail::Existing(&diagnostic),
            classification,
            stage,
            axes,
        )
    }

    pub fn source_existing_error(
        &self,
        error: &(dyn Error + 'static),
        diagnostic: Diagnostic,
        classification: DiagnosticCode,
        stage: RootRequestEvent,
        axes: RootOutcomeFacts,
    ) -> RootRequestFailure {
        self.original_record(
            RawSource::Error(error),
            SourceDetail::Existing(&diagnostic),
            classification,
            stage,
            axes,
        )
    }

    fn original_record(
        &self,
        raw: RawSource<'_>,
        facts: SourceDetail<'_>,
        classification: DiagnosticCode,
        stage: RootRequestEvent,
        axes: RootOutcomeFacts,
    ) -> RootRequestFailure {
        let (occurrence, category) = match &facts {
            SourceDetail::Bounded(d) => (d.occurrence(), d.category()),
            SourceDetail::Existing(d) => (d.occurrence(), d.category()),
        };
        let source_interface = match raw {
            RawSource::Error(_) => "error_source",
            RawSource::Description(_, _) => "unavailable_description_debug_only",
        };
        let (submission, original_capture) = match self.output {
            None => (
                DiagnosticSubmission::OutputUnavailable,
                OriginalCaptureState::OutputUnavailable,
            ),
            Some(output) => capture(
                output,
                occurrence,
                raw,
                &Header {
                    timestamp_unix_ms: timestamp(),
                    context: crate::AdmissionEventContext::Rooted(self.view),
                    stage,
                    facts,
                    outcome: axes,
                    original_contract: "display-debug-source/v1",
                    source_interface,
                },
            ),
        };
        RootRequestFailure {
            source: self.view.clone(),
            occurrence,
            classification,
            source_submission: submission,
            category,
            outcome: axes,
            original_capture,
        }
    }
}

/// Output facts only: no request root, task authority or failure-retention permit.
#[must_use = "capture facts describe submission, not durable output or resource completion"]
pub struct UnrootedCaptureFacts {
    occurrence: DiagnosticOccurrence,
    submission: DiagnosticSubmission,
    original_capture: OriginalCaptureState,
}
impl UnrootedCaptureFacts {
    pub fn occurrence(&self) -> DiagnosticOccurrence {
        self.occurrence
    }
    pub fn submission(&self) -> DiagnosticSubmission {
        self.submission
    }
    pub fn original_capture(&self) -> OriginalCaptureState {
        self.original_capture
    }
}

/// For a failure before a root exists. Does not create identity or acquire storage.
/// Callers with a live view must use RootDiagnosticScope instead.
pub struct UnrootedDiagnosticScope<'a> {
    application: &'a saddle_core::ContextLabel,
    lifecycle: saddle_core::RequestViewPhase,
    output: Option<&'a EmergencyDiagnosticHandle>,
}
impl<'a> UnrootedDiagnosticScope<'a> {
    pub fn new(
        application: &'a saddle_core::ContextLabel,
        lifecycle: saddle_core::RequestViewPhase,
        output: Option<&'a EmergencyDiagnosticHandle>,
    ) -> Self {
        Self {
            application,
            lifecycle,
            output,
        }
    }
    #[track_caller]
    pub fn source_error(
        &self,
        error: &(dyn Error + 'static),
        source_stage: saddle_core::DiagnosticStage,
        stage: RootRequestEvent,
        axes: RootOutcomeFacts,
    ) -> UnrootedCaptureFacts {
        let facts = BoundedDiagnostic::capture(
            DiagnosticCategory::UnexpectedError,
            saddle_core::CaptureSite::FirstObserved,
            saddle_core::BoundedDiagnosticCause::new(
                source_stage,
                DiagnosticCode::new("framework.error").unwrap(),
            ),
        );
        self.original_record(RawSource::Error(error), &facts, stage, axes)
    }
    #[track_caller]
    pub fn source_description<D: fmt::Display + fmt::Debug>(
        &self,
        description: &D,
        source_stage: saddle_core::DiagnosticStage,
        stage: RootRequestEvent,
        axes: RootOutcomeFacts,
    ) -> UnrootedCaptureFacts {
        let facts = BoundedDiagnostic::capture(
            DiagnosticCategory::UnexpectedError,
            saddle_core::CaptureSite::FirstObserved,
            saddle_core::BoundedDiagnosticCause::new(
                source_stage,
                DiagnosticCode::new("framework.error").unwrap(),
            ),
        );
        self.original_record(
            RawSource::Description(description, description),
            &facts,
            stage,
            axes,
        )
    }
    fn original_record(
        &self,
        raw: RawSource<'_>,
        facts: &BoundedDiagnostic,
        stage: RootRequestEvent,
        axes: RootOutcomeFacts,
    ) -> UnrootedCaptureFacts {
        let occurrence = facts.occurrence();
        let source_interface = match raw {
            RawSource::Error(_) => "error_source",
            RawSource::Description(_, _) => "unavailable_description_debug_only",
        };
        let (submission, original_capture) = match self.output {
            None => (
                DiagnosticSubmission::OutputUnavailable,
                OriginalCaptureState::OutputUnavailable,
            ),
            Some(output) => capture(
                output,
                occurrence,
                raw,
                &Header {
                    timestamp_unix_ms: timestamp(),
                    context: crate::AdmissionEventContext::Unrooted {
                        application: self.application,
                        lifecycle: self.lifecycle,
                    },
                    stage,
                    facts: SourceDetail::Bounded(facts),
                    outcome: axes,
                    original_contract: "display-debug-source/v1",
                    source_interface,
                },
            ),
        };
        UnrootedCaptureFacts {
            occurrence,
            submission,
            original_capture,
        }
    }
}

// Brent's online cycle detector: constant borrowed state, no visited-node list
// and no limit on a finite acyclic chain. Error::source must expose a stable
// chain during this borrow; pathological mutating implementations are not
// converted into an invented finite chain.
struct CycleDetector<'a> {
    anchor: &'a (dyn Error + 'static),
    power: usize,
    distance: usize,
}
impl<'a> CycleDetector<'a> {
    fn new(anchor: &'a (dyn Error + 'static)) -> Self {
        Self {
            anchor,
            power: 1,
            distance: 0,
        }
    }
    fn repeats(&mut self, next: &'a (dyn Error + 'static)) -> bool {
        // Include trait metadata: distinct zero-sized errors may share a data
        // address. Duplicated vtables may delay detection until source traversal
        // revisits the same edge, but must not turn a finite chain into a cycle.
        if std::ptr::eq(self.anchor, next) {
            return true;
        }
        self.distance += 1;
        if self.distance == self.power {
            self.anchor = next;
            self.power = self.power.saturating_mul(2);
            self.distance = 0;
        }
        false
    }
}

fn capture<O: OriginalOutput>(
    output: &O,
    occurrence: DiagnosticOccurrence,
    raw: RawSource<'_>,
    header: &impl Serialize,
) -> (DiagnosticSubmission, OriginalCaptureState) {
    let mut stream = Stream {
        output,
        occurrence,
        sequence: 0,
        depth: 0,
        channel: "context",
        bytes: [0; PAYLOAD_BYTES],
        len: 0,
        escaped: 0,
        failure: None,
        submission: DiagnosticSubmission::Enqueued,
    };
    let result = (|| -> fmt::Result {
        stream.json(header)?;
        let error = match raw {
            RawSource::Error(error) => error,
            RawSource::Description(description, debug) => {
                stream.channel = "description";
                if fmt::write(&mut stream, format_args!("{description}")).is_err() {
                    let state = stream
                        .failure
                        .unwrap_or(OriginalCaptureState::FormattingFailed);
                    stream.report_failure(state);
                    return Err(fmt::Error);
                }
                stream.emit("field_end")?;
                stream.channel = "debug";
                if fmt::write(&mut stream, format_args!("{debug:?}")).is_err() {
                    let state = stream
                        .failure
                        .unwrap_or(OriginalCaptureState::FormattingFailed);
                    stream.report_failure(state);
                    return Err(fmt::Error);
                }
                stream.emit("field_end")?;
                stream.depth = 1;
                stream.channel = "terminal";
                return stream.emit("description_complete_source_unavailable");
            }
        };
        let mut cycle = CycleDetector::new(error);
        let mut next = Some(error);
        while let Some(current) = next {
            stream.channel = "description";
            if fmt::write(&mut stream, format_args!("{current}")).is_err() {
                let failure = stream
                    .failure
                    .unwrap_or(OriginalCaptureState::FormattingFailed);
                stream.report_failure(failure);
                return Err(fmt::Error);
            }
            stream.emit("field_end")?;
            stream.channel = "debug";
            if fmt::write(&mut stream, format_args!("{current:?}")).is_err() {
                let state = stream
                    .failure
                    .unwrap_or(OriginalCaptureState::FormattingFailed);
                stream.report_failure(state);
                return Err(fmt::Error);
            }
            stream.emit("field_end")?;
            if let Some(io) = current.downcast_ref::<io::Error>() {
                stream.channel = "io_facts";
                stream.json(&IoFacts {
                    kind: Kind(io.kind()),
                    os_code: io.raw_os_error(),
                })?;
            }
            next = current.source();
            stream.depth += 1;
            if next.is_some_and(|next| cycle.repeats(next)) {
                stream.channel = "description";
                stream.report_failure(OriginalCaptureState::CauseCycle);
                return Err(fmt::Error);
            }
        }
        stream.channel = "terminal";
        stream.emit("exposed_chain_complete")
    })();
    if result.is_ok() {
        (stream.submission, OriginalCaptureState::CompleteEnqueued)
    } else {
        let state = stream
            .failure
            .unwrap_or(OriginalCaptureState::FormattingFailed);
        if stream.submission == DiagnosticSubmission::Enqueued {
            (DiagnosticSubmission::EncodingFailed, state)
        } else {
            (stream.submission, state)
        }
    }
}

/// Source scratch only; the borrowed error owns its own storage. Neither is queued.
pub fn original_capture_layout() -> (std::alloc::Layout, std::alloc::Layout, usize) {
    (
        std::alloc::Layout::new::<Stream<'static, EmergencyDiagnosticHandle>>(),
        std::alloc::Layout::new::<CycleDetector<'static>>(),
        PAYLOAD_BYTES,
    )
}

#[cfg(test)]
mod content_tests {
    use super::*;
    use std::cell::RefCell;

    struct Node {
        text: String,
        next: Option<Box<Node>>,
    }
    impl fmt::Display for Node {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str(&self.text)
        }
    }
    impl fmt::Debug for Node {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str(&self.text)
        }
    }
    impl Error for Node {
        fn source(&self) -> Option<&(dyn Error + 'static)> {
            self.next.as_deref().map(|v| v as &dyn Error)
        }
    }
    struct Readback<'a> {
        expected: &'a [String],
        // sequence, per-field offset, completed Display/Debug fields, terminal
        state: RefCell<(u64, usize, usize, bool)>,
    }
    impl OriginalOutput for Readback<'_> {
        fn submit(&self, segment: &Segment<'_>) -> DiagnosticSubmission {
            // Exercise real JSON escaping and decoding but not output capacity:
            // a full queue is a different contract from content truncation.
            let encoded = serde_json::to_vec(segment).unwrap();
            assert!(encoded.len() < 8192);
            let row: serde_json::Value = serde_json::from_slice(&encoded).unwrap();
            let mut s = self.state.borrow_mut();
            assert_eq!(row["sequence"].as_u64().unwrap(), s.0);
            s.0 += 1;
            if matches!(segment.channel, "description" | "debug") {
                let expected = &self.expected[segment.cause_depth];
                let payload = row["payload"].as_str().unwrap();
                assert_eq!(payload, &expected[s.1..s.1 + payload.len()]);
                s.1 += payload.len();
                if segment.state == "field_end" {
                    assert_eq!(s.1, expected.len(), "original tail missing");
                    s.1 = 0;
                    s.2 += 1;
                }
            }
            if segment.channel == "terminal" {
                assert_eq!(segment.state, "exposed_chain_complete");
                assert_eq!(segment.cause_depth, self.expected.len());
                assert_eq!(s.2, self.expected.len() * 2);
                s.3 = true;
            }
            DiagnosticSubmission::Enqueued
        }
    }
    fn assert_content(expected: Vec<String>) -> u64 {
        assert_content_context(expected, false)
    }
    fn assert_content_context(expected: Vec<String>, unrooted: bool) -> u64 {
        let mut head = None;
        for text in expected.iter().rev() {
            head = Some(Box::new(Node {
                text: text.clone(),
                next: head,
            }));
        }
        let publisher = saddle_core::RequestRootPublisher::create(
            saddle_core::ContextLabel::checked("content-test").unwrap(),
            saddle_core::ContextFact::NotEstablished,
        )
        .unwrap();
        let view = publisher
            .reference()
            .view(saddle_core::RequestLocalFacts::new(
                saddle_core::RequestViewPhase::Reading,
            ));
        let diagnostic = BoundedDiagnostic::capture(
            DiagnosticCategory::UnexpectedError,
            saddle_core::CaptureSite::FirstObserved,
            saddle_core::BoundedDiagnosticCause::new(
                saddle_core::DiagnosticStage::RequestDecode,
                DiagnosticCode::new("content.original").unwrap(),
            ),
        );
        let output = Readback {
            expected: &expected,
            state: RefCell::new((0, 0, 0, false)),
        };
        let application = saddle_core::ContextLabel::checked("content-test").unwrap();
        let result = capture(
            &output,
            diagnostic.occurrence(),
            RawSource::Error(head.as_deref().unwrap()),
            &Header {
                timestamp_unix_ms: 0,
                context: if unrooted {
                    crate::AdmissionEventContext::Unrooted {
                        application: &application,
                        lifecycle: saddle_core::RequestViewPhase::Reading,
                    }
                } else {
                    crate::AdmissionEventContext::Rooted(&view)
                },
                stage: RootRequestEvent::Ingress,
                facts: SourceDetail::Bounded(&diagnostic),
                outcome: RootOutcomeFacts::default(),
                original_contract: "display-debug-source/v1",
                source_interface: "error_source",
            },
        );
        assert_eq!(
            result,
            (
                DiagnosticSubmission::Enqueued,
                OriginalCaptureState::CompleteEnqueued
            )
        );
        assert!(output.state.borrow().3);
        output.state.into_inner().0
    }
    #[test]
    fn rooted_and_unrooted_share_lossless_long_content() {
        let expected = vec![
            format!("HEAD-中文\n\"{}\"-TAIL", "原文".repeat(2200)),
            "nested-cause\n完整".into(),
        ];
        let rooted = assert_content_context(expected.clone(), false);
        let unrooted = assert_content_context(expected, true);
        assert_eq!(rooted, unrooted);
    }
    #[test]
    fn finite_chain_beyond_old_256_keeps_every_cause() {
        let segments = assert_content(
            (0..300)
                .map(|n| format!("unknown-{n}-原文\n\"tail\""))
                .collect(),
        );
        assert!(segments > 600);
        println!("content readback: 300 original causes and Debug fields complete");
    }
    #[test]
    fn cycle_detector_handles_prefix_and_nontrivial_cycle() {
        let nodes: Vec<Node> = (0..4)
            .map(|n| Node {
                text: n.to_string(),
                next: None,
            })
            .collect();
        let mut cycle = CycleDetector::new(&nodes[0]);
        // A -> B -> C -> D -> B; no equal text or depth-limit heuristic.
        for node in [&nodes[1], &nodes[2], &nodes[3]] {
            assert!(!cycle.repeats(node));
        }
        let found = (0..32).any(|step| cycle.repeats(&nodes[1 + step % 3]));
        assert!(found);
    }
    #[test]
    fn finite_text_beyond_old_4096_segments_keeps_tail() {
        let text = format!("{}END-原文", "x".repeat(6144 * 4097));
        let segments = assert_content(vec![text]);
        assert!(segments > 8194);
        println!("content readback: {segments} segments, complete Display/Debug tails");
    }
}

/// Original database source outside a request; never manufactures a trace or
/// request account. `maintenance` distinguishes a tracked sweep from unscoped
/// startup/cleanup where request association is unavailable.
#[doc(hidden)]
pub fn database_background_error(
    output: Option<&EmergencyDiagnosticHandle>,
    datasource: u64,
    connection: Option<u64>,
    sweep: u64,
    phase: &'static str,
    maintenance: bool,
    error: &(dyn Error + 'static),
    facts: BoundedDiagnostic,
) -> UnrootedCaptureFacts {
    #[derive(Serialize)]
    struct Context {
        schema_version: u8,
        datasource: u64,
        connection: ContextFact<u64>,
        maintenance_sweep: u64,
        maintenance_phase: &'static str,
        request: ContextFact<()>,
        trace_id: ContextFact<()>,
        application: ContextFact<()>,
    }
    #[derive(Serialize)]
    struct BackgroundHeader<'a> {
        timestamp_unix_ms: u128,
        context: Context,
        stage: &'static str,
        facts: &'a BoundedDiagnostic,
        original_contract: &'static str,
        source_interface: &'static str,
    }
    let occurrence = facts.occurrence();
    let missing = if maintenance { ContextFact::NotApplicable } else { ContextFact::Unavailable };
    let header = BackgroundHeader {
        timestamp_unix_ms: timestamp(),
        context: Context { schema_version: 2, datasource,
            connection: connection.map(ContextFact::Present).unwrap_or(ContextFact::NotEstablished),
            maintenance_sweep: sweep, maintenance_phase: phase,
            request: missing, trace_id: missing, application: ContextFact::Unavailable },
        stage: if maintenance { "database_maintenance" } else { "database_connection" }, facts: &facts,
        original_contract: "display-debug-source/v1", source_interface: "error_source",
    };
    let (submission, original_capture) = match output {
        Some(output) => capture(output, occurrence, RawSource::Error(error), &header),
        None => (DiagnosticSubmission::OutputUnavailable, OriginalCaptureState::OutputUnavailable),
    };
    UnrootedCaptureFacts { occurrence, submission, original_capture }
}