autumn-web 0.7.0

An opinionated, convention-over-configuration web framework for Rust
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
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
//! Replaying a capsule against a rebuilt application and judging the result.
//!
//! Everything the recorded request touched is served from the capsule — the
//! clock from [`ReplayClock`](crate::capsule::clock::ReplayClock), the database
//! from the stub server in `capsule::replay_db` — so the only remaining
//! variable is the code. [`execute`] rebuilds the recorded `http::Request`,
//! drives it through the router, and compares what came back with what the
//! capsule recorded.
//!
//! Three verdicts are possible:
//!
//! * [`Verdict::Reproduced`] — same outcome, no database divergence. The bug is
//!   still there (or the capsule records a fixed one and you are looking at a
//!   regression test).
//! * [`Verdict::Diverged`] — the replayed code asked the database something the
//!   recording never asked, *or* left part of the recording unasked. The tape
//!   cannot answer the first and the second is not a reproduction either, so
//!   the run is not a fair comparison: the code has changed underneath the
//!   capsule. A divergence wins over a matching status, because a status that
//!   matches by luck while the queries differ is not a reproduction.
//! * [`Verdict::Mismatch`] — the database tape lined up but the outcome did
//!   not. Usually what you want to see after a fix.
//!
//! This module deliberately holds no database types, so it compiles in a build
//! without the `db` feature; [`DivergenceLog`] is a plain shared buffer the
//! stub server writes into.

// Replay-time module (offline `autumn replay` runs, never the serving path);
// kept panic-averse with the same deny set, but deliberately outside the
// request-path panic-gate manifest — see CONTRIBUTING.md.
#![cfg_attr(
    not(test),
    deny(
        clippy::unwrap_used,
        clippy::expect_used,
        clippy::panic,
        clippy::unreachable,
        clippy::todo,
        clippy::unimplemented,
        clippy::indexing_slicing,
    )
)]

use std::any::Any;
use std::panic::AssertUnwindSafe;
use std::path::Path;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};

use axum::body::Body;
use axum::http::{HeaderName, HeaderValue, Method, Request, StatusCode, Uri, Version};
use base64::Engine as _;
use futures::FutureExt as _;
use serde::Serialize;
use tower::ServiceExt as _;

use crate::capsule::clock::ReplayClock;
use crate::capsule::schema::{
    Capsule, CapsuleBody, CapsuleOutcome, CapsuleRequest, ConnectionTape,
};

/// Process exit code for a faithful reproduction.
pub const EXIT_REPRODUCED: i32 = 0;
/// Process exit code for a divergent or mismatched replay.
pub const EXIT_DIVERGED: i32 = 1;
/// Process exit code for a capsule this build refuses to replay.
pub const EXIT_REFUSED: i32 = 2;

/// Largest response body read back for the verdict's error message.
const MAX_BODY_PEEK: usize = 64 * 1024;

/// Longest the verdict waits for a replayed response body to finish.
///
/// The request timeout is deliberately cleared in replay mode, and a route
/// whose failure was *fixed* may now stream a body that never ends (an SSE
/// endpoint, say) — without a deadline of its own the drain would hang and
/// `autumn replay` would never print a verdict. Judging a still-streaming
/// response after this long is sound: the status and error identity are in
/// the head, which has already arrived.
const BODY_DRAIN_DEADLINE: std::time::Duration = std::time::Duration::from_secs(10);

/// Drain up to [`MAX_BODY_PEEK`] of a replayed response body, giving up —
/// without failing the verdict — when it does not complete in time.
async fn drain_body(body: Body) {
    let _ = tokio::time::timeout(
        BODY_DRAIN_DEADLINE,
        axum::body::to_bytes(body, MAX_BODY_PEEK),
    )
    .await;
}

// ── Divergences ─────────────────────────────────────────────────────────────

/// Why the replayed database traffic did not line up with the tape.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum DivergenceKind {
    /// The tape held no exchange for the statement at all.
    UnrecordedQuery,
    /// The next recorded exchange carried different SQL.
    SqlMismatch,
    /// The SQL matched but an unmasked bind parameter did not.
    BindMismatch,
    /// The connection ran past the end of its recorded exchanges.
    TapeExhausted,
    /// A prepared statement was described that the tape holds no metadata for.
    UnknownStatement,
    /// The run finished with recorded exchanges left unasked on a connection.
    UnconsumedExchanges,
}

impl DivergenceKind {
    /// Short label used in the human summary.
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::UnrecordedQuery => "unrecorded query",
            Self::SqlMismatch => "sql mismatch",
            Self::BindMismatch => "bind mismatch",
            Self::TapeExhausted => "tape exhausted",
            Self::UnknownStatement => "unknown statement",
            Self::UnconsumedExchanges => "unconsumed exchanges",
        }
    }
}

/// One place where the replayed run asked for something the capsule cannot
/// answer.
#[derive(Debug, Clone, Serialize)]
pub struct Divergence {
    /// What went wrong.
    pub kind: DivergenceKind,
    /// Recorder-assigned id of the connection it happened on.
    pub connection: u64,
    /// Position in the connection's recorded exchange list.
    pub exchange_index: usize,
    /// SQL the tape expected next, when there was one.
    pub expected_sql: Option<String>,
    /// SQL the replayed code actually sent.
    pub actual_sql: String,
    /// Human-readable explanation, safe to print.
    pub detail: String,
}

/// How much of one recorded connection tape the replayed run actually asked
/// for.
///
/// A replay is only a reproduction if it *follows* the recording, and a
/// divergence log alone cannot see that: it only hears about statements the run
/// issued. A run that returns the recorded 500 without ever touching the
/// database issues nothing, so it would look flawless. The cursor lives here,
/// behind an atomic, because the stub server tasks are detached over a duplex
/// pipe — the driver has to be able to read their progress *after* the response
/// has resolved.
///
/// Only the ordered `exchanges` are tracked. The keyed buckets (`prologue`,
/// `statements`, `catalog`) are re-askable metadata rather than effects: a warm
/// recorded connection carries entries a cold replayed one may legitimately
/// never need.
#[derive(Debug)]
pub struct TapeProgress {
    connection: u64,
    /// SQL of every recorded exchange, in recorded order.
    exchanges: Vec<String>,
    consumed: AtomicUsize,
}

impl TapeProgress {
    /// A cursor over `exchanges` (their SQL, in order) for connection
    /// `connection`.
    #[must_use]
    pub const fn new(connection: u64, exchanges: Vec<String>) -> Self {
        Self {
            connection,
            exchanges,
            consumed: AtomicUsize::new(0),
        }
    }

    /// The recorder-assigned id of the connection this tape came from.
    #[must_use]
    pub const fn connection(&self) -> u64 {
        self.connection
    }

    /// How many recorded exchanges the run has consumed so far — which is also
    /// the index of the next one the tape expects.
    #[must_use]
    pub fn consumed(&self) -> usize {
        self.consumed.load(Ordering::SeqCst)
    }

    /// Mark the exchange at the current position as served.
    pub fn advance(&self) {
        self.consumed.fetch_add(1, Ordering::SeqCst);
    }

    /// How many recorded exchanges were never asked for.
    #[must_use]
    pub fn unconsumed(&self) -> usize {
        self.exchanges.len().saturating_sub(self.consumed())
    }

    /// The divergence the leftovers amount to, if there are any.
    fn leftover_divergence(&self) -> Option<Divergence> {
        let consumed = self.consumed();
        let first = self.exchanges.get(consumed)?;
        let total = self.exchanges.len();
        let left = total.saturating_sub(consumed);
        Some(Divergence {
            kind: DivergenceKind::UnconsumedExchanges,
            connection: self.connection,
            exchange_index: consumed,
            expected_sql: Some(first.clone()),
            actual_sql: String::new(),
            detail: format!(
                "the capsule recorded {total} exchange(s) on connection {} but the replayed run \
                 asked for only {consumed}; {left} recorded statement(s) were never issued, the \
                 first being {first:?} — the replayed code reached its outcome without following \
                 the recorded database effects",
                self.connection
            ),
        })
    }
}

/// Everything a replay run learns about its database traffic.
///
/// Two halves: an append-only record of every divergence the run produced, and
/// the per-connection consumption cursors that catch the divergences *nobody
/// issues* — a recorded exchange the run never asked for.
///
/// The stub server writes into it from the connection tasks while the router
/// runs, so it is an `Arc`-shared mutex rather than a return value.
#[derive(Debug, Default)]
pub struct DivergenceLog {
    entries: Mutex<Vec<Divergence>>,
    tapes: Mutex<Vec<Arc<TapeProgress>>>,
}

impl DivergenceLog {
    /// An empty log.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Append a divergence.
    ///
    /// A poisoned lock is swallowed rather than propagated: a replay run that
    /// loses one divergence line is still worth finishing, and the connection
    /// task has nowhere to report to.
    pub fn record(&self, divergence: Divergence) {
        if let Ok(mut entries) = self.entries.lock() {
            entries.push(divergence);
        }
    }

    /// Register a recorded tape and hand back its consumption cursor.
    ///
    /// Every tape in a capsule must be registered — including ones no
    /// connection ever claims, because a pool that opens fewer connections than
    /// the recording did leaves those recordings unfollowed just as surely as a
    /// half-read one does.
    pub fn register_tape(&self, tape: &ConnectionTape) -> Arc<TapeProgress> {
        let progress = Arc::new(TapeProgress::new(
            tape.id,
            tape.exchanges
                .iter()
                .map(|exchange| exchange.sql.clone())
                .collect(),
        ));
        if let Ok(mut tapes) = self.tapes.lock() {
            tapes.push(Arc::clone(&progress));
        }
        progress
    }

    /// One divergence per registered tape that still holds unasked exchanges.
    ///
    /// Read by [`execute`] once the router has finished; the stub tasks advance
    /// their cursors before writing each recorded response, so everything the
    /// run consumed is already counted by the time its response resolves.
    #[must_use]
    pub fn unconsumed(&self) -> Vec<Divergence> {
        self.tapes
            .lock()
            .map(|tapes| {
                tapes
                    .iter()
                    .filter_map(|tape| tape.leftover_divergence())
                    .collect()
            })
            .unwrap_or_default()
    }

    /// `true` when no divergence has been *recorded*.
    ///
    /// This is about statements the run issued; leftover recorded exchanges are
    /// reported separately by [`unconsumed`](Self::unconsumed), which [`execute`]
    /// folds in before reaching a verdict.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.entries.lock().is_ok_and(|entries| entries.is_empty())
    }

    /// How many divergences were recorded.
    #[must_use]
    pub fn len(&self) -> usize {
        self.entries.lock().map_or(0, |entries| entries.len())
    }

    /// A snapshot of everything recorded so far.
    #[must_use]
    pub fn entries(&self) -> Vec<Divergence> {
        self.entries
            .lock()
            .map(|entries| entries.clone())
            .unwrap_or_default()
    }
}

// ── Verdict ─────────────────────────────────────────────────────────────────

/// The judgement a replay run reaches.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Verdict {
    /// Same outcome, no divergence.
    Reproduced,
    /// The replayed code left the tape.
    Diverged,
    /// The tape held, the outcome did not.
    Mismatch,
}

impl Verdict {
    /// Process exit code this verdict maps to.
    #[must_use]
    pub const fn exit_code(self) -> i32 {
        match self {
            Self::Reproduced => EXIT_REPRODUCED,
            Self::Diverged | Self::Mismatch => EXIT_DIVERGED,
        }
    }

    /// Lower-case label used in the JSON verdict and the human summary.
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::Reproduced => "reproduced",
            Self::Diverged => "diverged",
            Self::Mismatch => "mismatch",
        }
    }
}

/// Everything a replay run observed.
#[derive(Debug, Clone, Serialize)]
pub struct ReplayOutcome {
    /// The judgement.
    pub verdict: Verdict,
    /// What the capsule recorded.
    pub expected: CapsuleOutcome,
    /// What the replayed run produced.
    pub actual: CapsuleOutcome,
    /// Database divergences, in the order they happened.
    pub divergences: Vec<Divergence>,
    /// Non-fatal observations worth printing (clock over-reads, redaction
    /// limits, version drift).
    pub warnings: Vec<String>,
}

// ── Driver ──────────────────────────────────────────────────────────────────

/// Replay `capsule` against `router` and judge the result.
///
/// `divergences` must be the same log the replay database pool was built with
/// (see `capsule::replay_db::pool_from_capsule`) — it is read *after* the
/// router has finished, so every query the handler made is already in it, and
/// so are the consumption cursors of every registered tape. Both halves count:
/// a statement the tape cannot answer is a divergence, and so is a recorded
/// exchange the run never asked for, because reaching the recorded outcome
/// without the recorded database traffic is not a reproduction.
/// `clock` is the [`ReplayClock`] installed on the rebuilt state, when there is
/// one; it is only read for the over-read warning.
///
/// The router is driven inside `catch_unwind`, so a handler that panics without
/// a panic-catching middleware is *compared* against a recorded panic rather
/// than aborting the replay process.
pub async fn execute(
    router: axum::Router,
    capsule: &Capsule,
    divergences: Arc<DivergenceLog>,
    clock: Option<&ReplayClock>,
) -> ReplayOutcome {
    let mut warnings = Vec::new();
    version_warnings(capsule, &mut warnings);

    let actual = match rebuild_request(&capsule.request, &mut warnings) {
        Ok(request) => drive(router, request).await,
        Err(reason) => {
            warnings.push(format!(
                "the recorded request could not be rebuilt: {reason}"
            ));
            CapsuleOutcome::Status {
                code: 0,
                message: reason,
                problem_type: None,
            }
        }
    };

    if let Some(clock) = clock {
        let over_reads = clock.over_reads();
        if over_reads > 0 {
            warnings.push(format!(
                "the replayed handler read the clock {over_reads} more time(s) than the recording \
                 did; the last recorded reading was repeated, so times after that point are not \
                 faithful"
            ));
        }
        let unconsumed = clock.unconsumed();
        if unconsumed > 0 {
            warnings.push(format!(
                "the replayed handler read the clock {unconsumed} fewer time(s) than the recording \
                 did — a time-dependent branch the recording took was not exercised, so treat a \
                 reproduced verdict with care"
            ));
        }
    }

    redaction_warning(capsule, &actual, &mut warnings);

    // Statements the run issued that the tape could not answer, then recorded
    // statements the run never issued at all.
    let mut entries = divergences.entries();
    entries.extend(divergences.unconsumed());
    let verdict = if entries.is_empty() {
        if outcomes_match(&capsule.outcome, &actual) {
            Verdict::Reproduced
        } else {
            Verdict::Mismatch
        }
    } else {
        Verdict::Diverged
    };

    ReplayOutcome {
        verdict,
        expected: capsule.outcome.clone(),
        actual,
        divergences: entries,
        warnings,
    }
}

/// Drive one rebuilt request through the router, capturing an escaping panic.
///
/// The call runs inside [`crate::capsule::clock::with_replay_request_scope`],
/// which is what entitles it — and only it — to consume the capsule's
/// recorded clock readings. Reads from anywhere else during the replay
/// (boot, or tasks the handler spawns) are served non-consuming, mirroring
/// the capture side, where only scope-carrying reads were recorded.
async fn drive(router: axum::Router, request: Request<Body>) -> CapsuleOutcome {
    let call = crate::capsule::clock::with_replay_request_scope(router.oneshot(request));
    match AssertUnwindSafe(call).catch_unwind().await {
        Ok(Ok(response)) => outcome_from_response(response).await,
        // `Router`'s error type is `Infallible`, but the service contract still
        // has an error arm; treat it as a zero-status failure rather than
        // unwrapping.
        Ok(Err(error)) => CapsuleOutcome::Status {
            code: 0,
            message: format!("the router failed to answer: {error}"),
            problem_type: None,
        },
        Err(payload) => CapsuleOutcome::Panic {
            status: StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
            payload: format_panic_payload(payload.as_ref()),
            backtrace: None,
        },
    }
}

/// Describe the response the way the capture path describes it, so the two are
/// directly comparable: message and problem type come from the
/// `AutumnErrorInfo` the error pipeline stashes in the extensions, exactly as
/// `reporting::report_response` reads them.
async fn outcome_from_response(response: axum::response::Response) -> CapsuleOutcome {
    let status = response.status();
    // A panic the reporting layer caught and converted into a sanitized 500
    // still carries its identity in the extensions; describe it as the panic
    // it was, so it is compared against a recorded panic by payload rather
    // than letting any same-status response pass for it.
    if let Some(caught) = response.extensions().get::<crate::reporting::CaughtPanic>() {
        let payload = caught.payload.clone();
        drain_body(response.into_body()).await;
        return CapsuleOutcome::Panic {
            status: status.as_u16(),
            payload,
            backtrace: None,
        };
    }
    let info = response
        .extensions()
        .get::<crate::middleware::exception_filter::AutumnErrorInfo>();
    let (message, problem_type) = info.map_or_else(
        || {
            (
                status
                    .canonical_reason()
                    .unwrap_or("server error")
                    .to_owned(),
                None,
            )
        },
        |info| (info.message.clone(), info.problem_type.map(str::to_owned)),
    );
    // Draining the body keeps a streaming handler from being judged before it
    // has actually produced anything — but only up to a deadline, so a body
    // that never ends cannot hang the verdict.
    drain_body(response.into_body()).await;
    CapsuleOutcome::Status {
        code: status.as_u16(),
        message,
        problem_type,
    }
}

/// Same downcast ladder `reporting::format_panic_payload` uses.
fn format_panic_payload(payload: &(dyn Any + Send)) -> String {
    payload
        .downcast_ref::<&str>()
        .map(|text| (*text).to_owned())
        .or_else(|| payload.downcast_ref::<String>().cloned())
        .unwrap_or_else(|| "handler panicked".to_owned())
}

/// Rebuild the recorded request.
fn rebuild_request(
    recorded: &CapsuleRequest,
    warnings: &mut Vec<String>,
) -> Result<Request<Body>, String> {
    let method = Method::from_bytes(recorded.method.as_bytes())
        .map_err(|error| format!("method {:?} is not valid: {error}", recorded.method))?;
    let uri: Uri = recorded
        .uri
        .parse()
        .map_err(|error| format!("uri {:?} is not valid: {error}", recorded.uri))?;

    let body = match &recorded.body {
        CapsuleBody::Absent => Body::empty(),
        CapsuleBody::Text(text) => Body::from(text.clone()),
        CapsuleBody::Base64(encoded) => {
            let bytes = base64::engine::general_purpose::STANDARD
                .decode(encoded.as_bytes())
                .map_err(|error| format!("the recorded body is not valid base64: {error}"))?;
            Body::from(bytes)
        }
        CapsuleBody::Skipped { declared_len } => {
            warnings.push(format!(
                "the recorded body was larger than the capture cap ({}) and was never read, so \
                 the replayed request is sent with an empty body",
                declared_len.map_or_else(
                    || "length unknown".to_owned(),
                    |len| format!(
                        "{len} \
                     bytes declared"
                    )
                )
            ));
            Body::empty()
        }
    };

    let mut builder = Request::builder()
        .method(method)
        .uri(uri)
        .version(parse_version(&recorded.http_version));
    // Restore client identity: the recorded *resolved* identity is
    // pre-inserted whole, and `TrustedProxiesLayer` honors a pre-existing
    // `ResolvedClientIdentity` rather than re-resolving — re-running trust
    // evaluation against a synthetic peer would (correctly) distrust the
    // recorded forwarded headers and settle on a different host and scheme
    // than the failing request saw. `ConnectInfo` is anchored too, for
    // anything reading the peer directly.
    if recorded.client_addr.is_some()
        || recorded.client_host.is_some()
        || recorded.client_scheme.is_some()
    {
        builder = builder.extension(crate::security::ResolvedClientIdentity {
            addr: recorded.client_addr,
            host: recorded.client_host.clone(),
            scheme: recorded.client_scheme.clone(),
        });
    }
    // The raw peer socket outranks a synthesized one: middleware and
    // handlers that inspect the peer directly (address *and* port) see what
    // the recording server saw. Capsules that predate `peer_addr` fall back
    // to anchoring the resolved client address with a zero port.
    if let Some(peer) = recorded.peer_addr {
        builder = builder.extension(axum::extract::ConnectInfo(peer));
    } else if let Some(addr) = recorded.client_addr {
        builder = builder.extension(axum::extract::ConnectInfo(std::net::SocketAddr::new(
            addr, 0,
        )));
    }
    for (name, value) in &recorded.headers {
        let Ok(name) = HeaderName::from_bytes(name.as_bytes()) else {
            warnings.push(format!("dropped unparseable recorded header name {name:?}"));
            continue;
        };
        let Ok(value) = HeaderValue::from_str(value) else {
            warnings.push(format!(
                "dropped unparseable recorded header value for {name}"
            ));
            continue;
        };
        builder = builder.header(name, value);
    }
    // Non-UTF-8 header values travel base64-encoded so the JSON stays
    // diffable; restore the exact bytes — a placeholder here would hand the
    // handler different metadata than production saw.
    for (name, encoded) in &recorded.binary_headers {
        let Ok(name) = HeaderName::from_bytes(name.as_bytes()) else {
            warnings.push(format!("dropped unparseable recorded header name {name:?}"));
            continue;
        };
        let value = base64::engine::general_purpose::STANDARD
            .decode(encoded)
            .ok()
            .and_then(|bytes| HeaderValue::from_bytes(&bytes).ok());
        let Some(value) = value else {
            warnings.push(format!(
                "dropped undecodable recorded binary header value for {name}"
            ));
            continue;
        };
        builder = builder.header(name, value);
    }
    builder
        .body(body)
        .map_err(|error| format!("the rebuilt request is not valid: {error}"))
}

/// `http::Version` as `redact` formats it (`{:?}`), back into a `Version`.
fn parse_version(text: &str) -> Version {
    match text {
        "HTTP/0.9" => Version::HTTP_09,
        "HTTP/1.0" => Version::HTTP_10,
        "HTTP/2.0" => Version::HTTP_2,
        "HTTP/3.0" => Version::HTTP_3,
        _ => Version::HTTP_11,
    }
}

/// Whether the replayed outcome counts as the recorded one.
///
/// Two failures are the same failure when they have the same *identity*, not
/// merely the same status: a 500 whose message and problem type differ is a
/// different bug, and reporting it as a reproduction is exactly the wrong
/// answer for a tool whose job is telling you whether the bug is still there.
/// So a status outcome compares code, problem type **and** message. The
/// comparison is fair because both sides went through the same redaction: the
/// replayed request carries the capsule's `[FILTERED]` literals, so a message
/// that echoes request content echoes the same masked content.
///
/// A recorded panic compares by whole payload when the replayed panic also
/// escaped, and never across variants: a panic-catching middleware keeps the
/// panic's identity (`CaughtPanic`), so a cross-variant pair means the
/// failure *kind* changed.
fn outcomes_match(expected: &CapsuleOutcome, actual: &CapsuleOutcome) -> bool {
    match (expected, actual) {
        (
            CapsuleOutcome::Status {
                code: expected_code,
                message: expected_message,
                problem_type: expected_type,
            },
            CapsuleOutcome::Status {
                code: actual_code,
                message: actual_message,
                problem_type: actual_type,
            },
        ) => {
            expected_code == actual_code
                && expected_type == actual_type
                && expected_message == actual_message
        }
        (
            CapsuleOutcome::Panic {
                payload: expected, ..
            },
            CapsuleOutcome::Panic {
                payload: actual, ..
            },
        ) => panic_payloads_match(expected, actual),
        // A caught panic keeps its identity through the reporting layer (the
        // `CaughtPanic` response extension), so both sides of a genuinely
        // reproduced panic present as `Panic` above. A cross-variant pair
        // therefore means the failure *kind* changed — a fixed panic replaced
        // by an ordinary error, or the reverse — and a shared status code is
        // not a reproduction.
        (CapsuleOutcome::Panic { .. }, CapsuleOutcome::Status { .. })
        | (CapsuleOutcome::Status { .. }, CapsuleOutcome::Panic { .. }) => false,
    }
}

/// Whether two panic payloads describe the same panic.
fn panic_payloads_match(expected: &str, actual: &str) -> bool {
    // Whole-payload equality, deliberately: persistence never truncates a
    // panic payload (redaction only substitutes masked secrets, and the
    // replayed handler panics with the same `[FILTERED]` literals its request
    // carries), so a substring rule would let `database timeout while writing
    // the audit log` pass for a recorded `database timeout` — a different
    // panic wearing the old one's prefix.
    expected == actual
}

/// The one-line explanation for a verdict whose status lined up but whose
/// failure identity did not, so a reader is not left comparing two `500`s.
fn identity_mismatch_note(expected: &CapsuleOutcome, actual: &CapsuleOutcome) -> Option<String> {
    let (
        CapsuleOutcome::Status {
            code: expected_code,
            message: expected_message,
            problem_type: expected_type,
        },
        CapsuleOutcome::Status {
            code: actual_code,
            message: actual_message,
            problem_type: actual_type,
        },
    ) = (expected, actual)
    else {
        return None;
    };
    if expected_code != actual_code {
        return None;
    }
    if expected_type != actual_type {
        return Some(format!(
            "the status matched ({expected_code}) but the failure identity did not: the capsule \
             recorded problem type {expected_type:?} and the replay produced {actual_type:?}"
        ));
    }
    (expected_message != actual_message).then(|| {
        format!(
            "the status matched ({expected_code}) but the failure identity did not: the capsule \
             recorded {expected_message:?} and the replay produced {actual_message:?} — same \
             status, different failure"
        )
    })
}

/// Warn when the capsule came from a different build (F23, soft half).
fn version_warnings(capsule: &Capsule, warnings: &mut Vec<String>) {
    let running = env!("CARGO_PKG_VERSION");
    if capsule.autumn_version != running {
        warnings.push(format!(
            "the capsule was recorded by autumn-web {} but this build is {running}; a difference \
             in framework behaviour will show up as a mismatch that is not your application's",
            capsule.autumn_version
        ));
    }
    if capsule.truncated {
        warnings.push(
            "the capsule is truncated: recording stopped before it was complete — its notes \
             say why"
                .to_owned(),
        );
    }
}

/// F16: an authenticated route replayed without its credentials answers 401/403
/// where the recording answered 5xx. Say so, rather than leaving the operator
/// to work out why a reproduction failed.
fn redaction_warning(capsule: &Capsule, actual: &CapsuleOutcome, warnings: &mut Vec<String>) {
    let CapsuleOutcome::Status { code: actual, .. } = actual else {
        return;
    };
    if *actual != 401 && *actual != 403 {
        return;
    }
    let recorded_server_error = match &capsule.outcome {
        CapsuleOutcome::Status { code, .. } => (500..600).contains(code),
        CapsuleOutcome::Panic { .. } => true,
    };
    if !recorded_server_error {
        return;
    }
    let credential_redacted = capsule.request.redacted_keys.iter().any(|key| {
        let key = key.to_ascii_lowercase();
        key.starts_with("header:authorization")
            || key.starts_with("header:cookie")
            || key.starts_with("header:proxy-authorization")
    });
    if !credential_redacted {
        return;
    }
    warnings.push(format!(
        "the replay answered {actual} where the recording answered a server error, and the \
         capsule's credentials were masked by redaction (`{}`): authenticated routes are not \
         faithfully replayable from a capsule — re-record against an unauthenticated route, or \
         accept that the replay stops at the auth layer",
        capsule.request.redacted_keys.join("`, `")
    ));
}

// ── Refusal and reporting ───────────────────────────────────────────────────

/// Reason this build refuses to replay `capsule`, if any.
///
/// A refusal is not a verdict: nothing was run, so the caller should
/// [`print_refusal`] and exit [`EXIT_REFUSED`] rather than reporting a
/// mismatch. A format-version mismatch is refused earlier still, by
/// [`Capsule::from_json`](crate::capsule::schema::Capsule::from_json).
#[must_use]
pub fn refusal_reason(capsule: &Capsule) -> Option<String> {
    if capsule.truncated {
        return Some(
            "the capsule is truncated — recording stopped before it was complete (a size cap, \
             an unrecordable connection, or a streaming response body), so a replay would \
             report divergences that never happened. The capsule's notes say exactly why; for \
             a size cap, raise `[failure_capture] max_capsule_bytes` and re-record."
                .to_owned(),
        );
    }
    if let CapsuleBody::Skipped { declared_len } = &capsule.request.body {
        // Replaying with an empty body would drive the handler with input the
        // failing request never had. The handler then rejects it, the verdict
        // reads `mismatch` — which the guide tells operators means "the bug is
        // gone" — and a live bug is quietly marked fixed. Missing input is a
        // refusal, not a verdict.
        let size = declared_len.map_or_else(
            || "its size was never declared".to_owned(),
            |len| format!("it declared {len} byte(s)"),
        );
        return Some(format!(
            "the capsule's request body was not recorded ({size}) — it was over \
             `[failure_capture] max_body_bytes`, or it declared a structure redaction could not \
             parse and mask. Replaying would send an empty body, so a handler that reads the \
             body would be judged on input the failing request never had. The capsule's notes \
             say which case this was; raise `max_body_bytes` and re-record if it was the cap."
        ));
    }
    None
}

/// Exit code for a capsule this build refuses to replay.
#[must_use]
pub const fn refusal_exit_code() -> i32 {
    EXIT_REFUSED
}

/// Print a refusal — machine-readable on stdout, human-readable on stderr —
/// and return the process exit code ([`EXIT_REFUSED`]).
#[must_use]
pub fn print_refusal(reason: &str, capsule_path: &Path) -> i32 {
    let document = serde_json::json!({
        "verdict": "refused",
        "capsule": capsule_path.display().to_string(),
        "reason": reason,
    });
    println!("{document}");
    eprintln!("REFUSED  {}", capsule_path.display());
    eprintln!("  {}", printable(reason));
    EXIT_REFUSED
}

/// Strip C0 control characters from a string that came out of a capsule before
/// it is written to a terminal.
///
/// Capsule text is production request data: an error message, a panic payload
/// or a SQL string can carry whatever a client sent, including ANSI escape
/// sequences that would repaint the operator's terminal, hide the rest of the
/// verdict, or forge a line of output. Newlines and tabs are kept — they are
/// ordinary in a SQL statement — and everything else in the C0 range, escape
/// included, becomes a visible placeholder. The JSON document on stdout is
/// untouched: it is data, and a consumer needs it verbatim.
fn printable(text: &str) -> String {
    if !text
        .chars()
        .any(|c| c.is_control() && c != '\n' && c != '\t')
    {
        return text.to_owned();
    }
    text.chars()
        .map(|c| {
            if c.is_control() && c != '\n' && c != '\t' {
                '\u{fffd}'
            } else {
                c
            }
        })
        .collect()
}

/// Print a replay verdict — JSON on stdout, a human summary on stderr — and
/// return the process exit code.
///
/// Exit codes: `0` reproduced, `1` diverged or mismatched, `2` refused (see
/// [`print_refusal`]).
#[must_use]
pub fn print_verdict(outcome: &ReplayOutcome, capsule_path: &Path) -> i32 {
    let document = serde_json::json!({
        "verdict": outcome.verdict.label(),
        "capsule": capsule_path.display().to_string(),
        "expected": outcome.expected,
        "actual": outcome.actual,
        "divergences": outcome.divergences,
        "warnings": outcome.warnings,
    });
    println!("{document}");

    eprintln!(
        "{}  {}",
        outcome.verdict.label().to_uppercase(),
        capsule_path.display()
    );
    eprintln!(
        "  expected: {}",
        printable(&describe_outcome(&outcome.expected))
    );
    eprintln!(
        "  actual:   {}",
        printable(&describe_outcome(&outcome.actual))
    );
    if outcome.verdict == Verdict::Mismatch
        && let Some(note) = identity_mismatch_note(&outcome.expected, &outcome.actual)
    {
        eprintln!("  {}", printable(&note));
    }
    if !outcome.divergences.is_empty() {
        eprintln!("  database divergences ({}):", outcome.divergences.len());
        for divergence in &outcome.divergences {
            eprintln!(
                "    [{}] connection {} exchange {}: {}",
                divergence.kind.label(),
                divergence.connection,
                divergence.exchange_index,
                printable(&divergence.detail)
            );
        }
    }
    for warning in &outcome.warnings {
        eprintln!("  warning: {}", printable(warning));
    }
    outcome.verdict.exit_code()
}

/// One-line human rendering of an outcome.
fn describe_outcome(outcome: &CapsuleOutcome) -> String {
    match outcome {
        CapsuleOutcome::Status {
            code,
            message,
            problem_type,
        } => problem_type.as_ref().map_or_else(
            || format!("{code} {message}"),
            |problem_type| format!("{code} {message} ({problem_type})"),
        ),
        CapsuleOutcome::Panic {
            status, payload, ..
        } => format!("{status} panic: {payload}"),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn status(code: u16) -> CapsuleOutcome {
        CapsuleOutcome::Status {
            code,
            message: "boom".to_owned(),
            problem_type: None,
        }
    }

    fn panic_outcome(payload: &str) -> CapsuleOutcome {
        CapsuleOutcome::Panic {
            status: 500,
            payload: payload.to_owned(),
            backtrace: None,
        }
    }

    fn fixture(outcome: CapsuleOutcome) -> Capsule {
        Capsule {
            format_version: crate::capsule::schema::CAPSULE_FORMAT_VERSION,
            id: "fixture".to_owned(),
            captured_at: chrono::Utc::now(),
            autumn_version: env!("CARGO_PKG_VERSION").to_owned(),
            app: crate::capsule::schema::AppInfo::default(),
            request: CapsuleRequest {
                method: "GET".to_owned(),
                uri: "/orders".to_owned(),
                route: None,
                http_version: "HTTP/1.1".to_owned(),
                headers: Vec::new(),
                binary_headers: Vec::new(),
                body: CapsuleBody::Absent,
                redacted_keys: Vec::new(),
                peer_addr: None,
                client_addr: None,
                client_host: None,
                client_scheme: None,
            },
            outcome,
            clock: Vec::new(),
            clock_monotonic_us: Vec::new(),
            db: None,
            db_roles: Vec::new(),
            truncated: false,
            notes: Vec::new(),
        }
    }

    #[test]
    fn a_recorded_client_addr_is_restored_as_the_replayed_peer() {
        let mut recorded = crate::capsule::schema::test_support::request("GET", "/whoami");
        recorded.client_addr = Some(std::net::IpAddr::from([203, 0, 113, 9]));
        let mut warnings = Vec::new();
        let request = rebuild_request(&recorded, &mut warnings).expect("request rebuilds");
        let peer = request
            .extensions()
            .get::<axum::extract::ConnectInfo<std::net::SocketAddr>>()
            .expect("the recorded client address must anchor the replayed peer");
        assert_eq!(peer.0.ip(), std::net::IpAddr::from([203, 0, 113, 9]));
        let identity = request
            .extensions()
            .get::<crate::security::ResolvedClientIdentity>()
            .expect("the full resolved identity must be restored");
        assert_eq!(
            identity.addr,
            Some(std::net::IpAddr::from([203, 0, 113, 9]))
        );

        let anonymous = crate::capsule::schema::test_support::request("GET", "/whoami");
        let request = rebuild_request(&anonymous, &mut warnings).expect("request rebuilds");
        assert!(
            request
                .extensions()
                .get::<axum::extract::ConnectInfo<std::net::SocketAddr>>()
                .is_none(),
            "no recorded address, no synthetic peer"
        );
    }

    #[test]
    fn verdict_exit_codes_are_zero_one_two() {
        assert_eq!(Verdict::Reproduced.exit_code(), 0);
        assert_eq!(Verdict::Diverged.exit_code(), 1);
        assert_eq!(Verdict::Mismatch.exit_code(), 1);
        assert_eq!(refusal_exit_code(), 2);
    }

    #[test]
    fn same_status_reproduces_and_different_status_mismatches() {
        assert!(outcomes_match(&status(500), &status(500)));
        assert!(!outcomes_match(&status(500), &status(503)));
    }

    #[test]
    fn a_caught_panic_matches_the_recorded_panic_status() {
        // A replayed panic keeps its identity through the reporting layer via
        // the `CaughtPanic` extension, so a genuine reproduction presents as
        // Panic↔Panic; a bare status — any status — is a different failure.
        assert!(!outcomes_match(&panic_outcome("boom"), &status(500)));
        assert!(!outcomes_match(&panic_outcome("boom"), &status(503)));
        assert!(outcomes_match(
            &panic_outcome("boom"),
            &panic_outcome("boom")
        ));
        // Both sides format a payload the same way (a `&str`/`String`
        // downcast, no location suffix), so a superstring is a *different*
        // panic, not a tolerance case.
        assert!(!outcomes_match(
            &panic_outcome("boom"),
            &panic_outcome("boom at src/lib.rs:1")
        ));
        assert!(!outcomes_match(
            &panic_outcome("boom"),
            &panic_outcome("something else")
        ));
    }

    /// A failure's identity is more than its status code. Two different 500s
    /// are two different bugs, and calling the second one a reproduction of the
    /// first is the wrong answer from a tool whose whole job is telling you
    /// whether the bug is still there.
    #[test]
    fn a_matching_status_with_a_different_failure_is_a_mismatch() {
        let recorded = CapsuleOutcome::Status {
            code: 500,
            message: "order 42 has no shipping address".to_owned(),
            problem_type: Some("https://errors.example/db".to_owned()),
        };
        assert!(outcomes_match(&recorded, &recorded.clone()));

        let other_message = CapsuleOutcome::Status {
            code: 500,
            message: "connection pool exhausted".to_owned(),
            problem_type: Some("https://errors.example/db".to_owned()),
        };
        assert!(
            !outcomes_match(&recorded, &other_message),
            "a different failure with the same status is not a reproduction"
        );
        assert!(
            identity_mismatch_note(&recorded, &other_message)
                .is_some_and(|note| note.contains("failure identity")),
            "the verdict must explain that the status matched but the failure did not"
        );

        let other_type = CapsuleOutcome::Status {
            code: 500,
            message: "order 42 has no shipping address".to_owned(),
            problem_type: Some("https://errors.example/other".to_owned()),
        };
        assert!(!outcomes_match(&recorded, &other_type));
        assert!(identity_mismatch_note(&recorded, &other_type).is_some());

        // A genuinely different status is reported as such, not as an identity
        // difference.
        assert!(identity_mismatch_note(&recorded, &status(503)).is_none());
    }

    /// Panic payloads compare by whole-payload equality: persistence never
    /// truncates one, so a new panic that merely *contains* the recorded
    /// message — `database timeout while writing the audit log` for a
    /// recorded `database timeout` — is a different panic, not a
    /// reproduction.
    #[test]
    fn panic_payloads_compare_by_equality() {
        assert!(!outcomes_match(
            &panic_outcome(""),
            &panic_outcome("something else entirely")
        ));
        assert!(outcomes_match(&panic_outcome(""), &panic_outcome("")));
        assert!(!outcomes_match(
            &panic_outcome("handler panicked"),
            &panic_outcome("index out of bounds")
        ));
        assert!(outcomes_match(
            &panic_outcome("handler panicked"),
            &panic_outcome("handler panicked")
        ));
        assert!(
            !outcomes_match(
                &panic_outcome("database timeout"),
                &panic_outcome("database timeout while writing the audit log")
            ),
            "a superstring is a different panic wearing the old one's prefix"
        );
    }

    /// Capsule text is production request data. Printing it to a terminal
    /// verbatim would let a recorded ANSI escape repaint the operator's screen
    /// or forge a line of the verdict.
    #[test]
    fn control_characters_are_stripped_from_printed_capsule_text() {
        let scrubbed = printable("boom\u{1b}[2J\u{1b}[1;1HREPRODUCED  clean\u{7}");
        assert!(
            !scrubbed.contains('\u{1b}') && !scrubbed.contains('\u{7}'),
            "escape sequences must not reach the terminal, got {scrubbed:?}"
        );
        assert!(scrubbed.starts_with("boom"), "the text itself is kept");
        assert_eq!(
            printable("SELECT 1\n\tFROM t"),
            "SELECT 1\n\tFROM t",
            "newlines and tabs are ordinary in SQL and must survive"
        );
    }

    #[test]
    fn a_truncated_capsule_is_refused() {
        let mut capsule = fixture(status(500));
        assert!(refusal_reason(&capsule).is_none());
        capsule.truncated = true;
        let reason = refusal_reason(&capsule).expect("truncated capsules are refused");
        assert!(reason.contains("truncated"));
    }

    /// A body the capture never recorded is missing *input*, not a difference
    /// in behaviour. Replaying it empty and reporting `mismatch` would read as
    /// "the bug is gone" when nothing of the kind was established.
    #[test]
    fn a_capsule_whose_body_was_never_recorded_is_refused() {
        let mut capsule = fixture(status(500));
        assert!(refusal_reason(&capsule).is_none());

        capsule.request.body = CapsuleBody::Skipped {
            declared_len: Some(2_000_000),
        };
        let reason =
            refusal_reason(&capsule).expect("a capsule with an unrecorded body is refused");
        assert!(
            reason.contains("2000000"),
            "the refusal must say how big the body was: {reason}"
        );
        assert!(
            reason.contains("max_body_bytes"),
            "the refusal must point at the knob that caused it: {reason}"
        );

        // A skipped body with no declared length is refused just the same.
        capsule.request.body = CapsuleBody::Skipped { declared_len: None };
        assert!(refusal_reason(&capsule).is_some());

        // A body that was recorded, or genuinely absent, still replays.
        capsule.request.body = CapsuleBody::Text("{}".to_owned());
        assert!(refusal_reason(&capsule).is_none());
        capsule.request.body = CapsuleBody::Absent;
        assert!(refusal_reason(&capsule).is_none());
    }

    #[test]
    fn redaction_is_named_when_a_recorded_server_error_replays_as_401() {
        let mut capsule = fixture(status(500));
        capsule.request.redacted_keys = vec!["header:authorization".to_owned()];
        let mut warnings = Vec::new();
        redaction_warning(&capsule, &status(401), &mut warnings);
        assert_eq!(warnings.len(), 1, "expected one warning, got {warnings:?}");
        assert!(warnings.iter().any(|w| w.contains("authenticated routes")));

        // No credential was masked: nothing to blame redaction for.
        let capsule = fixture(status(500));
        let mut warnings = Vec::new();
        redaction_warning(&capsule, &status(401), &mut warnings);
        assert!(warnings.is_empty(), "unexpected warning: {warnings:?}");

        // The recording itself was a 401: not a redaction artefact.
        let mut capsule = fixture(status(401));
        capsule.request.redacted_keys = vec!["header:authorization".to_owned()];
        let mut warnings = Vec::new();
        redaction_warning(&capsule, &status(401), &mut warnings);
        assert!(warnings.is_empty(), "unexpected warning: {warnings:?}");
    }

    #[test]
    fn the_recorded_request_is_rebuilt_verbatim() {
        let mut capsule = fixture(status(500));
        capsule.request.method = "POST".to_owned();
        capsule.request.uri = "/orders?page=2".to_owned();
        capsule.request.headers = vec![("content-type".to_owned(), "application/json".to_owned())];
        capsule.request.body = CapsuleBody::Text("{\"a\":1}".to_owned());

        let mut warnings = Vec::new();
        let request = rebuild_request(&capsule.request, &mut warnings).expect("request rebuilds");
        assert_eq!(request.method(), Method::POST);
        assert_eq!(
            request.uri().path_and_query().map(ToString::to_string),
            Some("/orders?page=2".to_owned())
        );
        assert_eq!(
            request
                .headers()
                .get("content-type")
                .and_then(|v| v.to_str().ok()),
            Some("application/json")
        );
        assert!(warnings.is_empty(), "unexpected warnings: {warnings:?}");
    }

    #[test]
    fn a_skipped_body_warns_instead_of_pretending() {
        let mut capsule = fixture(status(500));
        capsule.request.body = CapsuleBody::Skipped {
            declared_len: Some(9_000_000),
        };
        let mut warnings = Vec::new();
        rebuild_request(&capsule.request, &mut warnings).expect("request rebuilds");
        assert!(
            warnings.iter().any(|w| w.contains("empty body")),
            "expected a skipped-body warning, got {warnings:?}"
        );
    }

    #[test]
    fn the_divergence_log_collects_across_clones() {
        let log = Arc::new(DivergenceLog::new());
        assert!(log.is_empty());
        Arc::clone(&log).record(Divergence {
            kind: DivergenceKind::UnrecordedQuery,
            connection: 3,
            exchange_index: 0,
            expected_sql: None,
            actual_sql: "SELECT 1".to_owned(),
            detail: "nothing recorded".to_owned(),
        });
        assert_eq!(log.len(), 1);
        assert!(!log.is_empty());
        assert_eq!(
            log.entries().first().map(|entry| entry.actual_sql.clone()),
            Some("SELECT 1".to_owned())
        );
    }

    fn tape(id: u64, sqls: &[&str]) -> ConnectionTape {
        ConnectionTape {
            role: crate::capsule::schema::TAPE_ROLE_PRIMARY.to_owned(),
            id,
            prologue: Vec::new(),
            statements: Vec::new(),
            catalog: Vec::new(),
            exchanges: sqls
                .iter()
                .map(|sql| crate::capsule::schema::Exchange {
                    protocol: crate::capsule::schema::ExchangeProtocol::Extended,
                    sql: (*sql).to_owned(),
                    binds: Vec::new(),
                    response: Vec::new(),
                    row_count: 0,
                    error: None,
                })
                .collect(),
        }
    }

    #[test]
    fn a_fully_consumed_tape_leaves_no_divergence() {
        let log = DivergenceLog::new();
        let progress = log.register_tape(&tape(1, &["SELECT 1", "SELECT 2"]));
        progress.advance();
        progress.advance();
        assert_eq!(progress.unconsumed(), 0);
        assert!(log.unconsumed().is_empty());
    }

    #[test]
    fn leftover_exchanges_name_the_connection_count_and_first_statement() {
        let log = DivergenceLog::new();
        let progress = log.register_tape(&tape(4, &["SELECT 1", "SELECT 2", "SELECT 3"]));
        progress.advance();

        let divergences = log.unconsumed();
        let [divergence] = divergences.as_slice() else {
            panic!("expected exactly one divergence, got {divergences:?}");
        };
        assert_eq!(divergence.kind, DivergenceKind::UnconsumedExchanges);
        assert_eq!(divergence.connection, 4);
        assert_eq!(divergence.exchange_index, 1);
        assert_eq!(divergence.expected_sql.as_deref(), Some("SELECT 2"));
        assert!(
            divergence.detail.contains('2') && divergence.detail.contains("SELECT 2"),
            "the detail must give the count and the first unissued statement, got {:?}",
            divergence.detail
        );
    }

    #[test]
    fn a_tape_no_connection_ever_claimed_is_wholly_unconsumed() {
        let log = DivergenceLog::new();
        let _progress = log.register_tape(&tape(9, &["SELECT 1"]));
        let divergences = log.unconsumed();
        assert_eq!(divergences.len(), 1);
        assert_eq!(
            divergences.first().map(|entry| entry.exchange_index),
            Some(0),
            "nothing was consumed, so the report starts at the first exchange"
        );
    }

    #[test]
    fn an_empty_tape_is_never_a_divergence() {
        let log = DivergenceLog::new();
        let _progress = log.register_tape(&tape(2, &[]));
        assert!(log.unconsumed().is_empty());
    }

    #[tokio::test]
    async fn a_capsule_without_a_database_reproduces_unaffected() {
        let router = axum::Router::new().route("/orders", axum::routing::get(|| async { "ok" }));
        // The recorded outcome is the one this router produces, message and
        // all: a reproduction means the same failure, not merely the same
        // status code.
        let mut capsule = fixture(CapsuleOutcome::Status {
            code: 200,
            message: "OK".to_owned(),
            problem_type: None,
        });
        capsule.db = None;
        let outcome = execute(router, &capsule, Arc::new(DivergenceLog::new()), None).await;
        assert_eq!(outcome.verdict, Verdict::Reproduced, "{outcome:?}");
        assert!(outcome.divergences.is_empty(), "{outcome:?}");
    }

    #[tokio::test]
    async fn unconsumed_exchanges_turn_a_matching_outcome_into_a_divergence() {
        let router = axum::Router::new().route("/orders", axum::routing::get(|| async { "ok" }));
        let capsule = fixture(status(200));
        let log = Arc::new(DivergenceLog::new());
        // Registered but never served: the run reaches the recorded outcome
        // without following the recorded effects.
        let _progress = log.register_tape(&tape(1, &["SELECT 1"]));

        let outcome = execute(router, &capsule, Arc::clone(&log), None).await;
        assert_eq!(outcome.verdict, Verdict::Diverged, "{outcome:?}");
        assert_eq!(
            outcome.divergences.first().map(|entry| entry.kind),
            Some(DivergenceKind::UnconsumedExchanges),
            "{outcome:?}"
        );
    }

    #[tokio::test]
    async fn a_panicking_router_is_captured_not_propagated() {
        async fn boom() -> &'static str {
            panic!("kaboom in handler")
        }
        let router = axum::Router::new().route("/boom", axum::routing::get(boom));
        let mut capsule = fixture(panic_outcome("kaboom in handler"));
        capsule.request.uri = "/boom".to_owned();
        let outcome = execute(router, &capsule, Arc::new(DivergenceLog::new()), None).await;
        assert_eq!(outcome.verdict, Verdict::Reproduced, "{outcome:?}");
    }
}