ic-testkit 0.53.0

PocketIC-oriented test utilities for IC canister tests
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
use std::{
    collections::HashMap,
    fmt,
    time::{Duration, Instant},
};

use candid::Principal;
use pocket_ic::{CanisterLogRecord, CanisterStatusResult, PocketIc};

use super::{
    PocketIcCallFailure,
    transport::{self, capture_call},
};

/// Default maximum number of canister-log records retained in diagnostics.
pub const DEFAULT_CANISTER_LOG_RECORD_LIMIT: usize = 32;

/// Default maximum aggregate raw canister-log bytes retained in diagnostics.
pub const DEFAULT_CANISTER_LOG_BYTE_LIMIT: usize = 16 * 1024;

/// Explicit bounds applied when canister logs are converted to diagnostic text.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CanisterLogRenderLimits {
    /// Maximum retained records; zero retains none.
    pub record_limit: usize,
    /// Maximum retained raw-content bytes; zero retains none.
    pub byte_limit: usize,
}

impl Default for CanisterLogRenderLimits {
    fn default() -> Self {
        Self {
            record_limit: DEFAULT_CANISTER_LOG_RECORD_LIMIT,
            byte_limit: DEFAULT_CANISTER_LOG_BYTE_LIMIT,
        }
    }
}

/// Exact controller-aware inputs for one best-effort diagnostic collection.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CanisterDiagnosticsRequest {
    /// Canister to inspect.
    pub canister_id: Principal,
    /// Exact sender for the status request.
    pub status_sender: Principal,
    /// Exact sender for the log request.
    pub log_sender: Principal,
    /// Caller-selected log rendering bounds.
    pub log_limits: CanisterLogRenderLimits,
}

/// One caller-labeled exact diagnostic request in a collect-all batch.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LabeledCanisterDiagnosticsRequest {
    /// Caller label, checked for emptiness and uniqueness before collection.
    pub label: String,
    /// Exact controller-aware diagnostic inputs.
    pub request: CanisterDiagnosticsRequest,
}

/// Structural error that prevents a diagnostics batch from starting.
#[non_exhaustive]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CanisterDiagnosticsBatchContractError {
    /// An entry label was empty.
    EmptyLabel {
        /// Zero-based position of the invalid entry.
        index: usize,
    },
    /// Two entries used the same label.
    DuplicateLabel {
        /// Duplicated caller label.
        label: String,
        /// Position where the label first appeared.
        first_index: usize,
        /// Position where the label was repeated.
        duplicate_index: usize,
    },
}

/// One canister-log record retained as bounded lossy UTF-8 text.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CanisterDiagnosticLogRecord {
    index: u64,
    timestamp_nanos: u64,
    content: String,
    original_content_bytes: usize,
    omitted_content_bytes: usize,
}

impl CanisterDiagnosticLogRecord {
    /// Upstream record index.
    #[must_use]
    pub const fn index(&self) -> u64 {
        self.index
    }

    /// Upstream record timestamp in nanoseconds.
    #[must_use]
    pub const fn timestamp_nanos(&self) -> u64 {
        self.timestamp_nanos
    }

    /// Retained content converted with lossy UTF-8 decoding.
    #[must_use]
    pub fn content(&self) -> &str {
        &self.content
    }

    /// Original raw content length before bounding and conversion.
    #[must_use]
    pub const fn original_content_bytes(&self) -> usize {
        self.original_content_bytes
    }

    /// Raw content bytes omitted from this retained record.
    #[must_use]
    pub const fn omitted_content_bytes(&self) -> usize {
        self.omitted_content_bytes
    }

    /// Whether this record's content was truncated.
    #[must_use]
    pub const fn was_truncated(&self) -> bool {
        self.omitted_content_bytes != 0
    }
}

/// Successfully fetched canister logs after bounded text conversion.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CanisterDiagnosticLogs {
    records: Vec<CanisterDiagnosticLogRecord>,
    total_records: usize,
    total_content_bytes: usize,
    omitted_content_bytes: usize,
}

impl CanisterDiagnosticLogs {
    /// Retained records in upstream order.
    #[must_use]
    pub fn records(&self) -> &[CanisterDiagnosticLogRecord] {
        &self.records
    }

    /// Total number of records returned by PocketIC before bounding.
    #[must_use]
    pub const fn total_records(&self) -> usize {
        self.total_records
    }

    /// Total raw content bytes returned by PocketIC before bounding.
    #[must_use]
    pub const fn total_content_bytes(&self) -> usize {
        self.total_content_bytes
    }

    /// Number of whole records omitted by the configured bounds.
    #[must_use]
    pub const fn omitted_records(&self) -> usize {
        self.total_records - self.records.len()
    }

    /// Aggregate raw content bytes omitted across retained and omitted records.
    #[must_use]
    pub const fn omitted_content_bytes(&self) -> usize {
        self.omitted_content_bytes
    }

    /// Whether either whole records or record content were truncated.
    #[must_use]
    pub const fn was_truncated(&self) -> bool {
        self.omitted_records() != 0 || self.omitted_content_bytes != 0
    }
}

impl fmt::Display for CanisterDiagnosticLogs {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.records.is_empty() {
            if self.total_records == 0 {
                formatter.write_str("<empty>")?;
            } else {
                formatter.write_str("<no retained records>")?;
            }
        } else {
            for (position, record) in self.records.iter().enumerate() {
                if position != 0 {
                    formatter.write_str(", ")?;
                }
                write!(
                    formatter,
                    "[{}@{}]={:?}",
                    record.index, record.timestamp_nanos, record.content
                )?;
                if record.was_truncated() {
                    write!(
                        formatter,
                        " (truncated {} bytes)",
                        record.omitted_content_bytes
                    )?;
                }
            }
        }
        if self.was_truncated() {
            write!(
                formatter,
                "; truncated omitted_records={} omitted_content_bytes={}",
                self.omitted_records(),
                self.omitted_content_bytes
            )?;
        }
        Ok(())
    }
}

/// Independent status and log outcomes for one diagnostic collection.
#[derive(Debug)]
pub struct CanisterDiagnosticsReport {
    /// Exact request used for this report.
    pub request: CanisterDiagnosticsRequest,
    /// Status result, independent of log retrieval.
    pub status: Result<CanisterStatusResult, PocketIcCallFailure>,
    /// Log result, independent of status retrieval.
    pub logs: Result<CanisterDiagnosticLogs, PocketIcCallFailure>,
}

impl CanisterDiagnosticsReport {
    /// Whether both status and log collection succeeded.
    #[must_use]
    pub const fn is_success(&self) -> bool {
        self.status.is_ok() && self.logs.is_ok()
    }
}

/// One ordered labeled entry in a collect-all diagnostics batch.
#[derive(Debug)]
pub struct CanisterDiagnosticsBatchEntry {
    /// Caller-supplied label.
    pub label: String,
    /// Structured status and log outcomes for this entry.
    pub report: CanisterDiagnosticsReport,
    /// Complete wall-clock time for this target's diagnostic collection.
    pub entry_elapsed: Duration,
}

impl CanisterDiagnosticsBatchEntry {
    /// Whether both status and log collection succeeded for this entry.
    #[must_use]
    pub const fn is_success(&self) -> bool {
        self.report.is_success()
    }
}

/// Ordered entries from a sequential collect-all diagnostics batch.
#[derive(Debug, Default)]
pub struct CanisterDiagnosticsBatchReport {
    /// Entries in the supplied request order.
    pub entries: Vec<CanisterDiagnosticsBatchEntry>,
    /// Complete wall-clock time for the sequential collect-all batch.
    pub total: Duration,
}

impl CanisterDiagnosticsBatchReport {
    /// Entries with at least one failed status or log operation.
    pub fn failures(&self) -> impl Iterator<Item = &CanisterDiagnosticsBatchEntry> {
        self.entries.iter().filter(|entry| !entry.is_success())
    }

    /// Whether every entry collected both status and logs successfully.
    #[must_use]
    pub fn is_success(&self) -> bool {
        self.entries
            .iter()
            .all(CanisterDiagnosticsBatchEntry::is_success)
    }
}

impl fmt::Display for CanisterDiagnosticsBatchReport {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "diagnostics={} total={:?}",
            self.entries.len(),
            self.total
        )?;
        for entry in &self.entries {
            write!(
                formatter,
                "; label={:?} elapsed={:?} {}",
                entry.label, entry.entry_elapsed, entry.report
            )?;
        }
        Ok(())
    }
}

impl fmt::Display for CanisterDiagnosticsReport {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "canister={} status_sender={} status=",
            self.request.canister_id, self.request.status_sender
        )?;
        match &self.status {
            Ok(status) => write!(
                formatter,
                "ok(state={:?} version={} controllers={} module_hash_bytes={} memory_bytes={} cycles={})",
                status.status,
                status.version,
                status.settings.controllers.len(),
                status.module_hash.as_ref().map_or(0, Vec::len),
                status.memory_size,
                status.cycles,
            ),
            Err(failure) => write!(formatter, "<{failure}>"),
        }?;
        write!(formatter, " log_sender={} logs=", self.request.log_sender)?;
        match &self.logs {
            Err(failure) => write!(formatter, "<{failure}>")?,
            Ok(logs) => write!(formatter, "{logs}")?,
        }
        Ok(())
    }
}

/// Reusable structured PocketIC failure diagnostics.
pub trait PocketIcDiagnosticsExt {
    /// Collect status and bounded logs using the request's exact senders.
    ///
    /// Both calls are attempted independently. PocketIC transport panics are
    /// captured so diagnostics can remain subordinate to the original failure.
    fn collect_canister_diagnostics(
        &self,
        request: CanisterDiagnosticsRequest,
    ) -> CanisterDiagnosticsReport;

    /// Collect every labeled request sequentially in its supplied order.
    ///
    /// Every target is attempted even when an earlier entry fails or panics.
    /// Each entry preserves its exact request and independent status/log
    /// outcomes; no anonymous retry or fallback is performed.
    fn collect_canister_diagnostics_batch(
        &self,
        requests: &[LabeledCanisterDiagnosticsRequest],
    ) -> Result<CanisterDiagnosticsBatchReport, CanisterDiagnosticsBatchContractError> {
        validate_diagnostics_batch_labels(requests)?;
        let started = Instant::now();
        let entries = requests
            .iter()
            .map(|labeled| {
                let entry_started = Instant::now();
                let request = labeled.request;
                let report =
                    transport::capture_operation(|| self.collect_canister_diagnostics(request))
                        .unwrap_or_else(|source| CanisterDiagnosticsReport {
                            request,
                            status: Err(PocketIcCallFailure::Operation(source.clone())),
                            logs: Err(PocketIcCallFailure::Operation(source)),
                        });
                CanisterDiagnosticsBatchEntry {
                    label: labeled.label.clone(),
                    report,
                    entry_elapsed: entry_started.elapsed(),
                }
            })
            .collect();
        Ok(CanisterDiagnosticsBatchReport {
            entries,
            total: started.elapsed(),
        })
    }
}

fn validate_diagnostics_batch_labels(
    requests: &[LabeledCanisterDiagnosticsRequest],
) -> Result<(), CanisterDiagnosticsBatchContractError> {
    let mut seen = HashMap::new();
    for (index, request) in requests.iter().enumerate() {
        let label = request.label.as_str();
        if label.is_empty() {
            return Err(CanisterDiagnosticsBatchContractError::EmptyLabel { index });
        }
        if let Some(first_index) = seen.insert(label, index) {
            return Err(CanisterDiagnosticsBatchContractError::DuplicateLabel {
                label: label.to_owned(),
                first_index,
                duplicate_index: index,
            });
        }
    }
    Ok(())
}

impl fmt::Display for CanisterDiagnosticsBatchContractError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyLabel { index } => {
                write!(
                    formatter,
                    "diagnostics batch label at index {index} is empty"
                )
            }
            Self::DuplicateLabel {
                label,
                first_index,
                duplicate_index,
            } => write!(
                formatter,
                "diagnostics batch label {label:?} at index {duplicate_index} duplicates index {first_index}",
            ),
        }
    }
}

impl std::error::Error for CanisterDiagnosticsBatchContractError {}

impl PocketIcDiagnosticsExt for PocketIc {
    fn collect_canister_diagnostics(
        &self,
        request: CanisterDiagnosticsRequest,
    ) -> CanisterDiagnosticsReport {
        let status =
            capture_call(|| self.canister_status(request.canister_id, Some(request.status_sender)));
        let logs =
            capture_call(|| self.fetch_canister_logs(request.canister_id, request.log_sender))
                .map(|records| render_log_records(records, request.log_limits));

        CanisterDiagnosticsReport {
            request,
            status,
            logs,
        }
    }
}

fn render_log_records(
    records: Vec<CanisterLogRecord>,
    limits: CanisterLogRenderLimits,
) -> CanisterDiagnosticLogs {
    let total_records = records.len();
    let mut total_content_bytes = 0usize;
    let mut rendered = Vec::with_capacity(total_records.min(limits.record_limit));
    let mut retained_bytes = 0usize;
    let mut omitted_content_bytes = 0usize;

    for record in records {
        total_content_bytes = total_content_bytes.saturating_add(record.content.len());
        if rendered.len() == limits.record_limit || retained_bytes == limits.byte_limit {
            omitted_content_bytes = omitted_content_bytes.saturating_add(record.content.len());
            continue;
        }

        let available = limits.byte_limit.saturating_sub(retained_bytes);
        let retained = record.content.len().min(available);
        let omitted = record.content.len().saturating_sub(retained);
        let content = String::from_utf8_lossy(&record.content[..retained]).into_owned();
        retained_bytes = retained_bytes.saturating_add(retained);
        omitted_content_bytes = omitted_content_bytes.saturating_add(omitted);
        rendered.push(CanisterDiagnosticLogRecord {
            index: record.idx,
            timestamp_nanos: record.timestamp_nanos,
            content,
            original_content_bytes: record.content.len(),
            omitted_content_bytes: omitted,
        });
    }

    CanisterDiagnosticLogs {
        records: rendered,
        total_records,
        total_content_bytes,
        omitted_content_bytes,
    }
}

#[cfg(test)]
mod tests {
    use std::cell::Cell;

    use candid::Principal;
    use pocket_ic::CanisterLogRecord;

    use super::{
        CanisterDiagnosticsBatchContractError, CanisterDiagnosticsReport,
        CanisterDiagnosticsRequest, CanisterLogRenderLimits, LabeledCanisterDiagnosticsRequest,
        PocketIcCallFailure, PocketIcDiagnosticsExt, capture_call, render_log_records,
    };

    #[test]
    fn diagnostic_transport_classification_survives_context_and_io_wrapping() {
        const REFUSED: &str = "HTTP failure: reqwest::Error { kind: Request, url: \"http://127.0.0.1:1234/instances/0/read/get_time\", source: ConnectError(\"tcp connect error\", Os { code: 111, kind: ConnectionRefused, message: \"Connection refused\" }) }";
        const RESET: &str = "HTTP failure: reqwest::Error { kind: Request, url: \"http://127.0.0.1:49238/instances/0/read/get_time\", source: hyper_util::client::legacy::Error(SendRequest, hyper::Error(Io, Os { code: 54, kind: ConnectionReset, message: \"Connection reset by peer\" })) }";
        for message in [REFUSED, RESET, "application worker channel closed"] {
            let error = capture_call::<()>(|| panic!("{message}"))
                .expect_err("diagnostic operation should capture the panic");
            let expected = message != "application worker channel closed";
            let PocketIcCallFailure::Operation(source) = &error else {
                panic!("expected the original operation error");
            };
            assert_eq!(source.message(), message);
            assert_eq!(source.is_transport(), expected);
            let chained = std::error::Error::source(&error)
                .and_then(|cause| cause.downcast_ref::<super::super::PocketIcOperationError>())
                .expect("diagnostic error exposes its original typed cause");
            assert_eq!(chained, source);
            assert_eq!(
                super::super::is_dead_pocket_ic_transport_error(&error),
                expected,
            );
            let wrapped = std::io::Error::other(error);
            assert_eq!(
                super::super::is_dead_pocket_ic_transport_error(&wrapped),
                expected,
            );
        }
    }

    struct PanickingThenReporting {
        calls: Cell<usize>,
    }

    impl PocketIcDiagnosticsExt for PanickingThenReporting {
        fn collect_canister_diagnostics(
            &self,
            request: CanisterDiagnosticsRequest,
        ) -> CanisterDiagnosticsReport {
            let call = self.calls.get();
            self.calls.set(call + 1);
            assert_ne!(call, 0, "synthetic first-entry diagnostic panic");
            CanisterDiagnosticsReport {
                request,
                status: Err(PocketIcCallFailure::Operation(
                    super::super::PocketIcOperationError::new("synthetic status failure"),
                )),
                logs: Err(PocketIcCallFailure::Operation(
                    super::super::PocketIcOperationError::new("synthetic log failure"),
                )),
            }
        }
    }

    #[test]
    fn labeled_batch_retains_order_and_continues_after_entry_panic() {
        let collector = PanickingThenReporting {
            calls: Cell::new(0),
        };
        let first = CanisterDiagnosticsRequest {
            canister_id: Principal::from_slice(&[1]),
            status_sender: Principal::from_slice(&[2]),
            log_sender: Principal::from_slice(&[3]),
            log_limits: CanisterLogRenderLimits::default(),
        };
        let second = CanisterDiagnosticsRequest {
            canister_id: Principal::from_slice(&[4]),
            status_sender: Principal::from_slice(&[5]),
            log_sender: Principal::from_slice(&[6]),
            log_limits: CanisterLogRenderLimits::default(),
        };
        let report = collector
            .collect_canister_diagnostics_batch(&[
                LabeledCanisterDiagnosticsRequest {
                    label: "root".into(),
                    request: first,
                },
                LabeledCanisterDiagnosticsRequest {
                    label: "worker".into(),
                    request: second,
                },
            ])
            .expect("valid labeled diagnostics batch");

        assert_eq!(collector.calls.get(), 2);
        assert_eq!(report.entries.len(), 2);
        assert_eq!(report.entries[0].label, "root");
        assert_eq!(report.entries[0].report.request, first);
        assert_eq!(report.entries[1].label, "worker");
        assert_eq!(report.entries[1].report.request, second);
        assert!(
            report
                .entries
                .iter()
                .all(|entry| entry.entry_elapsed <= report.total)
        );
        assert_eq!(report.failures().count(), 2);
        assert!(!report.is_success());
        let compact = report.to_string();
        assert!(compact.contains("label=\"root\""));
        assert!(compact.contains("label=\"worker\""));
        assert!(compact.contains("synthetic first-entry diagnostic panic"));
    }

    #[test]
    fn diagnostic_batch_rejects_invalid_labels_before_collection() {
        let collector = PanickingThenReporting {
            calls: Cell::new(0),
        };
        let request = CanisterDiagnosticsRequest {
            canister_id: Principal::from_slice(&[1]),
            status_sender: Principal::from_slice(&[2]),
            log_sender: Principal::from_slice(&[3]),
            log_limits: CanisterLogRenderLimits::default(),
        };
        let empty = collector
            .collect_canister_diagnostics_batch(&[LabeledCanisterDiagnosticsRequest {
                label: String::new(),
                request,
            }])
            .expect_err("empty label must reject diagnostics batch");
        assert_eq!(
            empty,
            CanisterDiagnosticsBatchContractError::EmptyLabel { index: 0 }
        );
        assert_eq!(collector.calls.get(), 0);

        let duplicate = collector
            .collect_canister_diagnostics_batch(&[
                LabeledCanisterDiagnosticsRequest {
                    label: "same".into(),
                    request,
                },
                LabeledCanisterDiagnosticsRequest {
                    label: "same".into(),
                    request,
                },
            ])
            .expect_err("duplicate labels must reject diagnostics batch");
        assert_eq!(
            duplicate,
            CanisterDiagnosticsBatchContractError::DuplicateLabel {
                label: "same".to_owned(),
                first_index: 0,
                duplicate_index: 1,
            }
        );
        assert_eq!(collector.calls.get(), 0);
    }

    #[test]
    fn log_rendering_is_bounded_lossy_utf8_and_reports_truncation() {
        let logs = render_log_records(
            vec![
                CanisterLogRecord {
                    idx: 7,
                    timestamp_nanos: 11,
                    content: vec![b'f', 0x80, b'o'],
                },
                CanisterLogRecord {
                    idx: 8,
                    timestamp_nanos: 12,
                    content: b"bar".to_vec(),
                },
            ],
            CanisterLogRenderLimits {
                record_limit: 1,
                byte_limit: 2,
            },
        );

        assert_eq!(logs.total_records(), 2);
        assert_eq!(logs.total_content_bytes(), 6);
        assert_eq!(logs.omitted_records(), 1);
        assert_eq!(logs.omitted_content_bytes(), 4);
        assert!(logs.was_truncated());
        assert_eq!(logs.records().len(), 1);
        assert_eq!(logs.records()[0].content(), "f�");
        assert_eq!(logs.records()[0].original_content_bytes(), 3);
        assert_eq!(logs.records()[0].omitted_content_bytes(), 1);
        assert!(logs.records()[0].was_truncated());
        let rendered = logs.to_string();
        assert!(rendered.contains("f�"));
        assert!(rendered.contains("truncated omitted_records=1 omitted_content_bytes=4"));
    }

    #[test]
    fn zero_log_bounds_retain_only_aggregate_truncation() {
        for (record_limit, byte_limit) in [(0, 0), (0, 16), (16, 0)] {
            let logs = render_log_records(
                vec![CanisterLogRecord {
                    idx: 1,
                    timestamp_nanos: 2,
                    content: b"hello".to_vec(),
                }],
                CanisterLogRenderLimits {
                    record_limit,
                    byte_limit,
                },
            );

            assert_eq!(logs.records(), []);
            assert_eq!(logs.total_records(), 1);
            assert_eq!(logs.total_content_bytes(), 5);
            assert_eq!(logs.omitted_records(), 1);
            assert_eq!(logs.omitted_content_bytes(), 5);
            assert!(logs.was_truncated());
            assert_eq!(
                logs.to_string(),
                "<no retained records>; truncated omitted_records=1 omitted_content_bytes=5"
            );
        }
    }

    #[test]
    fn logs_within_bounds_preserve_empty_records_and_raw_byte_totals() {
        let limits = CanisterLogRenderLimits {
            record_limit: 3,
            byte_limit: 3,
        };
        let empty = render_log_records(vec![], limits);
        assert_eq!(empty.total_records(), 0);
        assert_eq!(empty.total_content_bytes(), 0);
        assert_eq!(empty.omitted_records(), 0);
        assert_eq!(empty.omitted_content_bytes(), 0);
        assert!(!empty.was_truncated());
        assert_eq!(empty.to_string(), "<empty>");

        let logs = render_log_records(
            vec![
                CanisterLogRecord {
                    idx: 1,
                    timestamp_nanos: 2,
                    content: vec![],
                },
                CanisterLogRecord {
                    idx: 3,
                    timestamp_nanos: 4,
                    content: vec![0x80, b'a'],
                },
                CanisterLogRecord {
                    idx: 5,
                    timestamp_nanos: 6,
                    content: vec![],
                },
            ],
            limits,
        );
        assert_eq!(logs.total_records(), 3);
        assert_eq!(logs.records().len(), 3);
        assert_eq!(logs.total_content_bytes(), 2);
        assert_eq!(logs.records()[0].content(), "");
        assert_eq!(logs.records()[1].content(), "�a");
        assert_eq!(logs.records()[2].content(), "");
        assert_eq!(logs.omitted_records(), 0);
        assert_eq!(logs.omitted_content_bytes(), 0);
        assert!(!logs.was_truncated());
    }
}