laravel-rust-studio 0.1.1

See what a running Laravel for Rust application did: requests with their queries, errors with their source lines, mail, queued jobs, and durable workflows. For you in the browser, and for coding agents over MCP.
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
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
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
//! The telemetry store: bounded in-memory buffers, the cross-process journal that feeds them, the
//! diagnostics engine, and the live event bus behind the SSE stream.

use std::collections::{HashMap, HashSet, VecDeque};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use regex::Regex;
use serde_json::Value;
use tokio::sync::broadcast;
use tracing_subscriber::Registry;
use tracing_subscriber::registry::LookupSpan;

use crate::config::StudioConfig;
use crate::journal::{Journal, JournalEntry};
use crate::types::{
    BufferCounts, CacheRecord, DiagnosticIssue, DiagnosticsReport, ExceptionRecord, HttpClientRecord,
    JobActivityRecord, LatencyPoint, LogRecord, MailRecord, QueryBinding, QueryRecord, SpanCategory, SpanRecord,
    StudioEvent, TraceKind, TraceRecord, TraceSummary, WorkflowActivityRecord,
};

/// How many journal records are applied between trims while loading history.
const INGEST_CHUNK: usize = 1000;

/// What `laravel::db::listen` learned about a query, which its `db_query` span doesn't carry: the
/// SQL as sent, the bindings, and where the application built the query.
#[derive(Debug, Clone)]
pub(crate) struct DbSpanEnrichment {
    pub sql: String,
    pub connection: String,
    pub location: String,
    pub vendor: Option<String>,
    pub bindings: Vec<QueryBinding>,
    /// How long the database took, which the span can overstate: SQLx's SQLite worker thread
    /// holds the span a moment longer than the query runs.
    pub duration_ms: f64,
}

#[derive(Debug, Clone)]
struct ActiveSpan {
    trace_id: Option<String>,
    ignored: bool,
    is_db: bool,
    db_enrichment: Option<DbSpanEnrichment>,
}

/// The span that code outside the tracing layer, such as a query listener, is running in.
#[derive(Debug, Clone)]
pub(crate) struct SpanLink {
    /// The `db_query` span itself, when the code runs directly inside one.
    #[cfg_attr(
        not(feature = "database"),
        expect(dead_code, reason = "only the query listener reads it")
    )]
    pub db_span: Option<u64>,
    pub trace_id: Option<String>,
    /// Whether the work is Studio's own, or the framework's bookkeeping, and stays out of Studio.
    pub ignored: bool,
}

/// The process that captures telemetry, as traces name it.
#[derive(Debug, Clone)]
pub struct ProcessInfo {
    /// The console command the process runs, such as `serve` or `queue:work`.
    pub role: String,
    pub pid: u32,
}

impl ProcessInfo {
    /// Read the process's command from its arguments. A bare `cargo run` serves the application.
    #[must_use]
    pub fn detect() -> Self {
        let role = std::env::args()
            .skip(1)
            .find(|argument| !argument.starts_with('-'))
            .filter(|command| {
                command
                    .chars()
                    .all(|c| c.is_ascii_alphanumeric() || matches!(c, ':' | '-' | '_'))
            })
            .unwrap_or_else(|| "serve".to_owned());

        Self {
            role,
            pid: std::process::id(),
        }
    }
}

/// Which traces [`StudioStore::list_traces`] returns. The default is all of them.
#[derive(Debug, Clone, Copy, Default)]
pub struct TraceFilter<'a> {
    /// `request`, `job`, `workflow`, `command`, `schedule`, `tick`, or `background`.
    pub kind: Option<&'a str>,
    /// A response status, such as `404`, or a class of them, such as `5xx`.
    pub status: Option<&'a str>,
    /// Text in the trace's name, path, route, ID, or workflow run ID.
    pub search: Option<&'a str>,
    /// Only traces at least as long as `STUDIO_SLOW_REQUEST_MS`.
    pub slow: bool,
    /// Only traces that failed, or answered with a `4xx` or `5xx` status.
    pub errors: bool,
}

/// Which queries [`StudioStore::list_queries`] returns. The default is all of them.
#[derive(Debug, Clone, Copy, Default)]
pub struct QueryFilter<'a> {
    pub trace_id: Option<&'a str>,
    /// Only queries at least as long as `STUDIO_SLOW_QUERY_MS`.
    pub slow: bool,
    pub writes: bool,
    /// Only the reads that one trace ran more than once: N+1 queries.
    pub duplicates: bool,
    /// Leave out the queries a dependency's code built, such as the framework's own.
    pub app_only: bool,
    /// Text in the query's SQL, table, or source location.
    pub search: Option<&'a str>,
}

/// Shared, cheaply cloneable handle to everything Studio has captured.
#[derive(Clone)]
pub struct StudioStore {
    inner: Arc<Inner>,
}

struct Inner {
    config: StudioConfig,
    started_at: Instant,
    /// When the process started, on the clock its records are stamped by. A record from before
    /// then is one that an earlier run of the application left in the journal.
    started_at_ms: i64,
    process: ProcessInfo,
    /// The high bits of this process's record IDs, so IDs from different processes don't collide.
    id_tag: u64,
    next_sequence: AtomicU64,
    db_listener_active: AtomicBool,
    journal: Option<Journal>,

    // Newest first.
    traces: RwLock<VecDeque<TraceRecord>>,
    queries: RwLock<VecDeque<QueryRecord>>,
    logs: RwLock<VecDeque<LogRecord>>,
    exceptions: RwLock<VecDeque<ExceptionRecord>>,
    mails: RwLock<VecDeque<MailRecord>>,
    http_client: RwLock<VecDeque<HttpClientRecord>>,
    cache: RwLock<VecDeque<CacheRecord>>,
    workflow_activity: RwLock<VecDeque<WorkflowActivityRecord>>,
    job_activity: RwLock<VecDeque<JobActivityRecord>>,

    /// The spans that are open now, by their `tracing` ID.
    active_spans: RwLock<HashMap<u64, ActiveSpan>>,
    events: broadcast::Sender<StudioEvent>,
    /// Keeps the two events of one email from interleaving with another email's.
    mail_merge: Mutex<()>,
}

impl std::fmt::Debug for StudioStore {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("StudioStore")
            .field("process", &self.inner.process)
            .field("buffers", &self.buffer_counts())
            .finish_non_exhaustive()
    }
}

impl StudioStore {
    /// A store that keeps what it captures in memory only.
    #[must_use]
    pub fn new(config: StudioConfig) -> Self {
        Self::build(config, ProcessInfo::detect(), None)
    }

    /// A store that also shares what it captures with other processes through journal files in
    /// `dir`, and reads what they captured.
    #[must_use]
    pub fn with_journal(config: StudioConfig, dir: impl Into<PathBuf>) -> Self {
        let process = ProcessInfo::detect();
        let journal = Journal::new(
            dir.into(),
            &process.role,
            config.journal_max_mb.max(1) * 1024 * 1024,
            Duration::from_secs(config.journal_hours.max(1) * 60 * 60),
        );

        Self::build(config, process, Some(journal))
    }

    fn build(config: StudioConfig, process: ProcessInfo, journal: Option<Journal>) -> Self {
        let (events, _) = broadcast::channel(512);
        let id_tag = (uuid::Uuid::new_v4().as_u128() as u64) & 0xF_FFFF;

        Self {
            inner: Arc::new(Inner {
                config,
                started_at: Instant::now(),
                started_at_ms: now_ms(),
                process,
                id_tag,
                next_sequence: AtomicU64::new(1),
                db_listener_active: AtomicBool::new(false),
                journal,
                traces: RwLock::default(),
                queries: RwLock::default(),
                logs: RwLock::default(),
                exceptions: RwLock::default(),
                mails: RwLock::default(),
                http_client: RwLock::default(),
                cache: RwLock::default(),
                workflow_activity: RwLock::default(),
                job_activity: RwLock::default(),
                active_spans: RwLock::default(),
                events,
                mail_merge: Mutex::new(()),
            }),
        }
    }

    /// The configuration the store was created with.
    #[must_use]
    pub fn config(&self) -> &StudioConfig {
        &self.inner.config
    }

    /// The process that owns this store.
    #[must_use]
    pub fn process(&self) -> &ProcessInfo {
        &self.inner.process
    }

    /// Where the journal files live, or `None` when the journal is off.
    #[must_use]
    pub fn journal_dir(&self) -> Option<&Path> {
        self.inner.journal.as_ref().map(Journal::dir)
    }

    /// Seconds since this process started capturing.
    #[must_use]
    pub fn uptime_seconds(&self) -> u64 {
        self.inner.started_at.elapsed().as_secs()
    }

    /// Subscribe to records as they're captured, which the SSE stream forwards.
    #[must_use]
    pub fn subscribe(&self) -> broadcast::Receiver<StudioEvent> {
        self.inner.events.subscribe()
    }

    /// The next record ID: this process's tag above a counter. It stays below 2^53, so JavaScript
    /// reads it exactly.
    pub(crate) fn next_id(&self) -> u64 {
        let sequence = self.inner.next_sequence.fetch_add(1, Ordering::Relaxed) & 0xFFFF_FFFF;

        (self.inner.id_tag << 32) | sequence
    }

    #[cfg(feature = "database")]
    pub(crate) fn set_db_listener_active(&self, active: bool) {
        self.inner.db_listener_active.store(active, Ordering::Release);
    }

    pub(crate) fn db_listener_active(&self) -> bool {
        self.inner.db_listener_active.load(Ordering::Acquire)
    }

    // ---- Open spans ----

    pub(crate) fn register_active_span(&self, span_id: u64, trace_id: Option<String>, ignored: bool, is_db: bool) {
        if let Ok(mut spans) = self.inner.active_spans.write() {
            spans.insert(
                span_id,
                ActiveSpan {
                    trace_id,
                    ignored,
                    is_db,
                    db_enrichment: None,
                },
            );
        }
    }

    #[cfg(feature = "database")]
    pub(crate) fn attach_db_enrichment(&self, span_id: u64, enrichment: DbSpanEnrichment) {
        if let Ok(mut spans) = self.inner.active_spans.write()
            && let Some(span) = spans.get_mut(&span_id)
        {
            span.db_enrichment = Some(enrichment);
        }
    }

    /// Close a span and take what a query listener attached to it.
    pub(crate) fn unregister_active_span(&self, span_id: u64) -> Option<DbSpanEnrichment> {
        self.inner.active_spans.write().ok()?.remove(&span_id)?.db_enrichment
    }

    /// The captured span the calling code runs in. When the current span is one Studio doesn't
    /// capture, such as an application's own `trace_span!`, its closest captured ancestor counts.
    pub(crate) fn current_span_link(&self) -> Option<SpanLink> {
        let id = tracing::Span::current().id()?;
        let spans = self.inner.active_spans.read().ok()?;
        if let Some(span) = spans.get(&id.into_u64()) {
            return Some(SpanLink {
                db_span: span.is_db.then(|| id.into_u64()),
                trace_id: span.trace_id.clone(),
                ignored: span.ignored,
            });
        }

        tracing::dispatcher::get_default(|dispatch| {
            let registry = dispatch.downcast_ref::<Registry>()?;
            let mut ancestor = registry.span(&id)?.parent();
            while let Some(span) = ancestor {
                if let Some(active) = spans.get(&span.id().into_u64()) {
                    return Some(SpanLink {
                        db_span: None,
                        trace_id: active.trace_id.clone(),
                        ignored: active.ignored,
                    });
                }
                ancestor = span.parent();
            }

            None
        })
    }

    // ---- Recording ----

    fn emit(&self, event: StudioEvent) {
        let _ = self.inner.events.send(event);
    }

    /// Write a record this process captured to the journal, for the other processes to read.
    fn journaled(&self, entry: JournalEntry) -> JournalEntry {
        if let Some(journal) = &self.inner.journal {
            journal.append(&entry);
        }

        entry
    }

    /// Record a finished trace, after working out its query totals.
    pub fn record_trace(&self, mut trace: TraceRecord) {
        self.summarize_queries(&mut trace);
        trace.process.clone_from(&self.inner.process.role);
        trace.pid = self.inner.process.pid;

        self.apply(self.journaled(JournalEntry::Trace(Box::new(trace))), true, true);
    }

    fn summarize_queries(&self, trace: &mut TraceRecord) {
        let slow = self.inner.config.slow_query_ms as f64;
        let mut repeats: HashMap<String, usize> = HashMap::new();
        let (mut count, mut total_ms, mut slow_count) = (0usize, 0.0_f64, 0usize);
        // The write each span ran last, to tell a read that reads its row back...
        let mut written: HashMap<Option<u64>, Written> = HashMap::new();

        for span in trace.spans.iter_mut().filter(|span| span.category == SpanCategory::Db) {
            let Some(sql) = span.fields.get("db.query.text").and_then(Value::as_str) else {
                continue;
            };
            let normalized = normalize_sql(sql);
            if is_transaction_control(&normalized) {
                continue;
            }
            count += 1;
            total_ms += span.duration_ms;
            if span.duration_ms >= slow {
                slow_count += 1;
            }

            let reads = is_read(&normalized);
            let (_, table) = parse_sql_op_table(sql);
            let before = written.remove(&span.parent_id);
            span.read_back = reads && reads_back(before.as_ref(), table.as_deref(), span.location.as_deref());
            if !reads {
                written.insert(
                    span.parent_id,
                    Written {
                        table,
                        location: span.location.clone(),
                    },
                );
            }

            // A dependency's repeated reads, such as a workflow store's, aren't the application's to fix...
            if reads && span.vendor.is_none() && !span.read_back {
                *repeats.entry(normalized).or_insert(0) += 1;
            }
        }

        trace.query_count = count;
        trace.total_query_ms = round_ms(total_ms);
        trace.slow_query_count = slow_count;
        trace.duplicate_query_count = repeats.values().filter(|n| **n > 1).map(|n| n - 1).sum();
    }

    /// Record a SQL query.
    pub fn record_query(&self, mut query: QueryRecord) {
        query.is_slow = query.duration_ms >= self.inner.config.slow_query_ms as f64;
        query.read_back = !query.is_write && self.reads_back_its_trace(&query);

        self.apply(self.journaled(JournalEntry::Query(query)), true, true);
    }

    /// Whether the query before this one in its trace wrote the row this one reads back.
    fn reads_back_its_trace(&self, query: &QueryRecord) -> bool {
        let (Some(trace), Ok(queries)) = (&query.trace_id, self.inner.queries.read()) else {
            return false;
        };
        // The newest queries come first, and a trace's own queries are seldom far apart...
        let before = queries
            .iter()
            .take(64)
            .find(|other| other.trace_id.as_ref() == Some(trace) && !is_transaction_control(&other.normalized_sql));

        before.is_some_and(|before| {
            before.is_write
                && reads_back(
                    Some(&Written {
                        table: before.table.clone(),
                        location: before.location.clone(),
                    }),
                    query.table.as_deref(),
                    query.location.as_deref(),
                )
        })
    }

    /// Record a log line.
    pub fn record_log(&self, log: LogRecord) {
        self.apply(self.journaled(JournalEntry::Log(log)), true, true);
    }

    /// Record an error or a panic. The error handler tells Studio about each failure twice, once
    /// through its reporters and once through its log line, and the two are merged into one record.
    pub fn record_exception(&self, exception: ExceptionRecord) {
        self.apply(self.journaled(JournalEntry::Exception(exception)), true, true);
    }

    /// Record an email or a text message, merging it into what's already known of the same message.
    pub fn upsert_mail(&self, mail: MailRecord) {
        let _merging = self.inner.mail_merge.lock();
        let merged = self.merge_mail(mail);

        self.emit(StudioEvent::Mail(merged.clone()));
        self.journaled(JournalEntry::Mail(merged));
    }

    /// Record an outgoing HTTP request.
    pub fn record_http_client(&self, request: HttpClientRecord) {
        self.apply(self.journaled(JournalEntry::Http(request)), true, true);
    }

    /// Record a cache operation.
    pub fn record_cache(&self, operation: CacheRecord) {
        self.apply(self.journaled(JournalEntry::Cache(operation)), true, true);
    }

    /// Record that a workflow run advanced, completed, failed, or was cancelled.
    pub fn record_workflow_activity(&self, activity: WorkflowActivityRecord) {
        self.apply(self.journaled(JournalEntry::Workflow(activity)), true, true);
    }

    /// Record one attempt of a queued job.
    pub fn record_job_activity(&self, activity: JobActivityRecord) {
        self.apply(self.journaled(JournalEntry::Job(activity)), true, true);
    }

    /// Put a record in its buffer. `broadcast` tells the SSE stream about it, and `trim` drops the
    /// buffer's oldest records over its limit, which loading history does itself, in one pass.
    fn apply(&self, entry: JournalEntry, broadcast: bool, trim: bool) {
        let config = &self.inner.config;
        let limit = |max: usize| if trim { max.max(1) } else { usize::MAX };

        match entry {
            JournalEntry::Trace(trace) => {
                if broadcast {
                    self.emit(StudioEvent::Trace(TraceSummary::from(&*trace)));
                }
                push(&self.inner.traces, *trace, limit(config.max_traces));
            }
            JournalEntry::Query(query) => {
                if broadcast {
                    self.emit(StudioEvent::Query(query.clone()));
                }
                push(&self.inner.queries, query, limit(config.max_queries));
            }
            JournalEntry::Log(log) => {
                if broadcast {
                    self.emit(StudioEvent::Log(log.clone()));
                }
                push(&self.inner.logs, log, limit(config.max_logs));
            }
            JournalEntry::Exception(exception) => {
                if let Some(recorded) = self.merge_exception(exception, limit(config.max_exceptions))
                    && broadcast
                {
                    self.emit(StudioEvent::Exception(recorded));
                }
            }
            JournalEntry::Mail(mail) => {
                let merged = self.merge_mail(mail);
                if broadcast {
                    self.emit(StudioEvent::Mail(merged));
                }
            }
            JournalEntry::Http(request) => push(&self.inner.http_client, request, limit(config.max_http_client)),
            JournalEntry::Cache(operation) => push(&self.inner.cache, operation, limit(config.max_cache)),
            JournalEntry::Workflow(activity) => {
                if let Ok(mut activities) = self.inner.workflow_activity.write() {
                    // A run's last advance closes just after the run says how it ended, and mustn't
                    // take that ending back...
                    let ended = activities.iter().any(|known| {
                        known.run_id == activity.run_id
                            && matches!(known.status.as_str(), "completed" | "failed" | "cancelled")
                            && activity.updated_at_ms - known.updated_at_ms < 5_000
                    });
                    if ended && activity.status == "advanced" {
                        return;
                    }
                    activities.retain(|known| known.run_id != activity.run_id);
                    activities.push_front(activity.clone());
                    activities.truncate(limit(200));
                }
                if broadcast {
                    self.emit(StudioEvent::Workflow(activity));
                }
            }
            JournalEntry::Job(activity) => {
                let merged = self.merge_job_activity(activity, limit(500));
                if broadcast {
                    self.emit(StudioEvent::Job(merged));
                }
            }
        }
    }

    /// A job's last failed attempt is told twice, by `JobProcessed` with how long it took, and by
    /// `JobFailed` with why it failed. The two become one record.
    fn merge_job_activity(&self, incoming: JobActivityRecord, max: usize) -> JobActivityRecord {
        let Ok(mut activities) = self.inner.job_activity.write() else {
            return incoming;
        };
        let same = activities
            .iter_mut()
            .take(32)
            .find(|known| known.job_id == incoming.job_id && known.attempt == incoming.attempt);

        if let Some(known) = same {
            if incoming.error.is_some() {
                known.error = incoming.error;
            } else {
                known.outcome = incoming.outcome;
                known.duration_ms = incoming.duration_ms;
            }
            return known.clone();
        }

        activities.push_front(incoming.clone());
        activities.truncate(max);

        incoming
    }

    /// Add an exception, or fill in the record of the same failure. Returns the record when it's new.
    fn merge_exception(&self, incoming: ExceptionRecord, max: usize) -> Option<ExceptionRecord> {
        let mut exceptions = self.inner.exceptions.write().ok()?;
        let same = exceptions.iter_mut().take(8).find(|known| {
            known.message == incoming.message
                && (known.timestamp_ms - incoming.timestamp_ms).abs() < 500
                && (known.trace_id == incoming.trace_id || known.trace_id.is_none() || incoming.trace_id.is_none())
        });

        if let Some(known) = same {
            if incoming.causes.len() > known.causes.len() {
                known.causes = incoming.causes;
            }
            if known.context.is_empty() {
                known.context = incoming.context;
            }
            if known.error_type == "Error" {
                known.error_type = incoming.error_type;
            }
            known.location = known.location.take().or(incoming.location);
            known.trace_id = known.trace_id.take().or(incoming.trace_id);
            known.method = known.method.take().or(incoming.method);
            known.path = known.path.take().or(incoming.path);
            known.route = known.route.take().or(incoming.route);
            return None;
        }

        exceptions.push_front(incoming.clone());
        exceptions.truncate(max);

        Some(incoming)
    }

    /// The log mailer describes one email in two events and a span, and this joins them by the
    /// message's ID.
    fn merge_mail(&self, incoming: MailRecord) -> MailRecord {
        let Ok(mut mails) = self.inner.mails.write() else {
            return incoming;
        };
        let known = mails
            .iter_mut()
            .find(|mail| !incoming.message_id.is_empty() && mail.message_id == incoming.message_id);

        let Some(mail) = known else {
            let mut mail = incoming;
            extract_links_and_codes(&mut mail);
            mails.push_front(mail.clone());
            mails.truncate(self.inner.config.max_mails.max(1));
            return mail;
        };

        // The log mailer names itself `log`, while the span knows the mailer's configured name...
        if incoming.mailer.as_deref().is_some_and(|mailer| mailer != "log") || mail.mailer.is_none() {
            mail.mailer = incoming.mailer.or(mail.mailer.take());
        }
        mail.transport = mail.transport.take().or(incoming.transport);
        mail.from = mail.from.take().or(incoming.from);
        if incoming.to.as_deref().is_some_and(|to| !to.ends_with("recipient(s)")) || mail.to.is_none() {
            mail.to = incoming.to.or(mail.to.take());
        }
        mail.cc = mail.cc.take().or(incoming.cc);
        mail.bcc = mail.bcc.take().or(incoming.bcc);
        mail.subject = mail.subject.take().or(incoming.subject);
        mail.text = mail.text.take().or(incoming.text);
        mail.html = mail.html.take().or(incoming.html);
        mail.trace_id = mail.trace_id.take().or(incoming.trace_id);
        mail.attachments = mail.attachments.max(incoming.attachments);
        if incoming.is_error {
            mail.is_error = true;
            mail.error = mail.error.take().or(incoming.error);
        }
        extract_links_and_codes(mail);

        mail.clone()
    }

    // ---- The journal ----

    /// Read what other processes captured since the last call, and return how many records came in.
    /// The first call also loads what earlier runs left behind. Calls closer together than a fifth
    /// of a second do nothing, so every Studio request may call this.
    pub fn sync(&self) -> usize {
        let Some(journal) = &self.inner.journal else {
            return 0;
        };
        let batch = journal.read_new(false);
        if batch.entries.is_empty() {
            return 0;
        }

        let count = batch.entries.len();
        for (index, entry) in batch.entries.into_iter().enumerate() {
            self.apply(entry, !batch.initial, false);
            if (index + 1) % INGEST_CHUNK == 0 {
                self.sort_and_trim();
            }
        }
        self.sort_and_trim();

        count
    }

    /// Order every buffer newest first, since another process's records arrive late, and drop what's
    /// over each buffer's limit.
    fn sort_and_trim(&self) {
        let config = &self.inner.config;

        sort_and_trim(&self.inner.traces, config.max_traces, |trace| trace.finished_at_ms);
        sort_and_trim(&self.inner.queries, config.max_queries, |query| query.started_at_ms);
        sort_and_trim(&self.inner.logs, config.max_logs, |log| log.timestamp_ms);
        sort_and_trim(&self.inner.exceptions, config.max_exceptions, |exception| {
            exception.timestamp_ms
        });
        sort_and_trim(&self.inner.mails, config.max_mails, |mail| mail.timestamp_ms);
        sort_and_trim(&self.inner.http_client, config.max_http_client, |request| {
            request.timestamp_ms
        });
        sort_and_trim(&self.inner.cache, config.max_cache, |operation| operation.timestamp_ms);
        sort_and_trim(&self.inner.workflow_activity, 200, |activity| activity.updated_at_ms);
        sort_and_trim(&self.inner.job_activity, 500, |activity| activity.timestamp_ms);
    }

    /// Forget everything captured, in this process's memory and in every process's journal. The
    /// application's own tables, such as its workflow runs and failed jobs, aren't touched.
    pub fn clear(&self) {
        clear(&self.inner.traces);
        clear(&self.inner.queries);
        clear(&self.inner.logs);
        clear(&self.inner.exceptions);
        clear(&self.inner.mails);
        clear(&self.inner.http_client);
        clear(&self.inner.cache);
        clear(&self.inner.workflow_activity);
        clear(&self.inner.job_activity);
        if let Some(journal) = &self.inner.journal {
            journal.clear();
        }

        self.emit(StudioEvent::Cleared);
    }

    // ---- Reading ----

    #[must_use]
    pub fn buffer_counts(&self) -> BufferCounts {
        BufferCounts {
            traces: len(&self.inner.traces),
            queries: len(&self.inner.queries),
            logs: len(&self.inner.logs),
            exceptions: len(&self.inner.exceptions),
            mails: len(&self.inner.mails),
            http_client: len(&self.inner.http_client),
            cache: len(&self.inner.cache),
        }
    }

    /// The traces that match a filter, newest first.
    #[must_use]
    pub fn list_traces(&self, filter: &TraceFilter<'_>, limit: usize) -> Vec<TraceSummary> {
        let slow_ms = self.inner.config.slow_request_ms as f64;
        let search = filter.search.map(str::to_ascii_lowercase);
        let Ok(traces) = self.inner.traces.read() else {
            return Vec::new();
        };

        traces
            .iter()
            .filter(|trace| filter.kind.is_none_or(|kind| trace.kind.as_str() == kind))
            .filter(|trace| match filter.status {
                Some("2xx") => trace.status_code.is_some_and(|code| (200..300).contains(&code)),
                Some("3xx") => trace.status_code.is_some_and(|code| (300..400).contains(&code)),
                Some("4xx") => trace.status_code.is_some_and(|code| (400..500).contains(&code)),
                Some("5xx") => trace.status_code.is_some_and(|code| code >= 500),
                Some(code) => code.parse::<u16>().is_ok_and(|code| trace.status_code == Some(code)),
                None => true,
            })
            .filter(|trace| !filter.slow || trace.response_ms() >= slow_ms)
            .filter(|trace| !filter.errors || trace.is_error || trace.status_code.is_some_and(|code| code >= 400))
            .filter(|trace| {
                search.as_ref().is_none_or(|needle| {
                    let has = |text: &str| text.to_ascii_lowercase().contains(needle);
                    has(&trace.name)
                        || has(&trace.id)
                        || trace.path.as_deref().is_some_and(has)
                        || trace.route.as_deref().is_some_and(has)
                        || trace.workflow_run_id.as_deref().is_some_and(has)
                })
            })
            .take(limit)
            .map(TraceSummary::from)
            .collect()
    }

    #[must_use]
    pub fn get_trace(&self, id: &str) -> Option<TraceRecord> {
        self.inner
            .traces
            .read()
            .ok()?
            .iter()
            .find(|trace| trace.id == id)
            .cloned()
    }

    /// The newest trace of an HTTP request.
    #[must_use]
    pub fn latest_request_trace(&self) -> Option<TraceRecord> {
        self.inner
            .traces
            .read()
            .ok()?
            .iter()
            .find(|trace| trace.kind == TraceKind::Request)
            .cloned()
    }

    /// The queries that match a filter, newest first.
    #[must_use]
    pub fn list_queries(&self, filter: &QueryFilter<'_>, limit: usize) -> Vec<QueryRecord> {
        let search = filter.search.map(str::to_ascii_lowercase);
        let Ok(queries) = self.inner.queries.read() else {
            return Vec::new();
        };

        let mut repeats: HashMap<(&str, &str), usize> = HashMap::new();
        if filter.duplicates {
            for query in queries.iter().filter(|query| is_repeatable(query)) {
                if let Some(trace) = &query.trace_id {
                    *repeats.entry((trace, &query.normalized_sql)).or_insert(0) += 1;
                }
            }
        }

        queries
            .iter()
            .filter(|query| filter.trace_id.is_none_or(|id| query.trace_id.as_deref() == Some(id)))
            .filter(|query| !filter.slow || query.is_slow)
            .filter(|query| !filter.writes || query.is_write)
            .filter(|query| !filter.app_only || query.vendor.is_none())
            .filter(|query| {
                !filter.duplicates
                    || query.trace_id.as_deref().is_some_and(|trace| {
                        is_repeatable(query)
                            && repeats
                                .get(&(trace, query.normalized_sql.as_str()))
                                .copied()
                                .unwrap_or(0)
                                > 1
                    })
            })
            .filter(|query| {
                search.as_ref().is_none_or(|needle| {
                    let has = |text: &str| text.to_ascii_lowercase().contains(needle);
                    has(&query.sql)
                        || query.table.as_deref().is_some_and(has)
                        || query.location.as_deref().is_some_and(has)
                })
            })
            .take(limit)
            .cloned()
            .collect()
    }

    #[must_use]
    pub fn list_logs(
        &self,
        trace_id: Option<&str>,
        level: Option<&str>,
        search: Option<&str>,
        limit: usize,
    ) -> Vec<LogRecord> {
        let search = search.map(str::to_ascii_lowercase);
        let Ok(logs) = self.inner.logs.read() else {
            return Vec::new();
        };

        logs.iter()
            .filter(|log| trace_id.is_none_or(|id| log.trace_id.as_deref() == Some(id)))
            .filter(|log| level.is_none_or(|level| log.level.eq_ignore_ascii_case(level)))
            .filter(|log| {
                search.as_ref().is_none_or(|needle| {
                    log.message.to_ascii_lowercase().contains(needle)
                        || log.target.to_ascii_lowercase().contains(needle)
                })
            })
            .take(limit)
            .cloned()
            .collect()
    }

    #[must_use]
    pub fn list_exceptions(&self, search: Option<&str>, limit: usize) -> Vec<ExceptionRecord> {
        let search = search.map(str::to_ascii_lowercase);
        let Ok(exceptions) = self.inner.exceptions.read() else {
            return Vec::new();
        };

        exceptions
            .iter()
            .filter(|exception| {
                search.as_ref().is_none_or(|needle| {
                    let has = |text: &str| text.to_ascii_lowercase().contains(needle);
                    has(&exception.message)
                        || has(&exception.error_type)
                        || exception.location.as_deref().is_some_and(has)
                        || exception.trace_id.as_deref().is_some_and(has)
                })
            })
            .take(limit)
            .cloned()
            .collect()
    }

    #[must_use]
    pub fn latest_exception(&self) -> Option<ExceptionRecord> {
        self.inner.exceptions.read().ok()?.front().cloned()
    }

    #[must_use]
    pub fn get_exception(&self, id: u64) -> Option<ExceptionRecord> {
        self.inner
            .exceptions
            .read()
            .ok()?
            .iter()
            .find(|exception| exception.id == id)
            .cloned()
    }

    /// Emails and text messages, newest first. `kind` is `mail` or `sms`.
    #[must_use]
    pub fn list_mails(&self, kind: Option<&str>, search: Option<&str>, limit: usize) -> Vec<MailRecord> {
        let search = search.map(str::to_ascii_lowercase);
        let Ok(mails) = self.inner.mails.read() else {
            return Vec::new();
        };

        mails
            .iter()
            .filter(|mail| kind.is_none_or(|kind| mail.kind == kind))
            .filter(|mail| {
                search.as_ref().is_none_or(|needle| {
                    let has = |text: &String| text.to_ascii_lowercase().contains(needle);
                    mail.subject.as_ref().is_some_and(has)
                        || mail.to.as_ref().is_some_and(has)
                        || mail.text.as_ref().is_some_and(has)
                })
            })
            .take(limit)
            .cloned()
            .collect()
    }

    #[must_use]
    pub fn latest_mail(&self) -> Option<MailRecord> {
        self.inner.mails.read().ok()?.front().cloned()
    }

    #[must_use]
    pub fn get_mail(&self, id: u64) -> Option<MailRecord> {
        self.inner.mails.read().ok()?.iter().find(|mail| mail.id == id).cloned()
    }

    #[must_use]
    pub fn list_http_client(&self, trace_id: Option<&str>, limit: usize) -> Vec<HttpClientRecord> {
        newest(&self.inner.http_client, limit, |request| {
            trace_id.is_none_or(|id| request.trace_id.as_deref() == Some(id))
        })
    }

    #[must_use]
    pub fn list_cache(&self, trace_id: Option<&str>, limit: usize) -> Vec<CacheRecord> {
        newest(&self.inner.cache, limit, |operation| {
            trace_id.is_none_or(|id| operation.trace_id.as_deref() == Some(id))
        })
    }

    #[must_use]
    pub fn list_workflow_activity(&self, limit: usize) -> Vec<WorkflowActivityRecord> {
        newest(&self.inner.workflow_activity, limit, |_| true)
    }

    #[must_use]
    pub fn list_job_activity(&self, limit: usize) -> Vec<JobActivityRecord> {
        newest(&self.inner.job_activity, limit, |_| true)
    }

    /// Totals over what the buffers hold now.
    #[must_use]
    pub fn compute_metrics(&self) -> StoreMetrics {
        let mut metrics = StoreMetrics::default();

        if let Ok(traces) = self.inner.traces.read() {
            let mut durations = Vec::new();
            for trace in traces.iter().filter(|trace| trace.kind == TraceKind::Request) {
                let failed = trace.is_error || trace.status_code.is_some_and(|code| code >= 500);
                metrics.total_requests += 1;
                metrics.total_errors += u64::from(failed);
                durations.push(trace.response_ms());
                if metrics.latency_series.len() < 60 {
                    metrics.latency_series.push(LatencyPoint {
                        trace_id: trace.id.clone(),
                        timestamp_ms: trace.started_at_ms,
                        duration_ms: trace.response_ms(),
                        status_code: trace.status_code,
                        label: trace.name.clone(),
                        is_error: failed,
                    });
                }
            }
            metrics.latency_series.reverse();
            metrics.duplicate_query_traces = traces.iter().filter(|trace| trace.duplicate_query_count > 0).count();

            if !durations.is_empty() {
                metrics.avg_request_ms = round_ms(durations.iter().sum::<f64>() / durations.len() as f64);
                durations.sort_by(f64::total_cmp);
                let rank = (durations.len() as f64 * 0.95).ceil() as usize;
                metrics.p95_request_ms = round_ms(durations[rank.clamp(1, durations.len()) - 1]);
                metrics.error_rate_pct = percent(metrics.total_errors, metrics.total_requests);
            }
        }

        if let Ok(queries) = self.inner.queries.read() {
            metrics.total_queries = queries.len() as u64;
            metrics.slow_queries = queries.iter().filter(|query| query.is_slow).count() as u64;
        }

        if let Ok(cache) = self.inner.cache.read() {
            let hits = cache.iter().filter(|operation| operation.hit == Some(true)).count() as u64;
            let misses = cache.iter().filter(|operation| operation.hit == Some(false)).count() as u64;
            if hits + misses > 0 {
                metrics.cache_hit_rate_pct = Some(percent(hits, hits + misses));
            }
        }

        metrics
    }

    /// Look through what was captured for problems worth a developer's or an agent's attention:
    /// errors, N+1 queries, slow queries, slow requests, and failed outgoing requests.
    #[must_use]
    pub fn diagnose_telemetry(&self) -> Vec<DiagnosticIssue> {
        self.diagnose_telemetry_since(i64::MIN)
    }

    /// The same, looking only at what was captured at `since_ms` or later.
    ///
    /// Each problem says when it was last seen. One that this run of the application has shown is
    /// described by what this run captured, and comes before the ones that only earlier runs left.
    #[must_use]
    pub fn diagnose_telemetry_since(&self, since_ms: i64) -> Vec<DiagnosticIssue> {
        let mut issues = Vec::new();
        let mount = self.inner.config.mount_path();

        self.diagnose_exceptions(&mount, since_ms, &mut issues);
        self.diagnose_queries(&mount, since_ms, &mut issues);
        self.diagnose_requests(&mount, since_ms, &mut issues);
        self.diagnose_http_client(since_ms, &mut issues);

        issues
    }

    /// Count problems into a report. `observed` are the problems found in what was captured, and
    /// those last seen before this process started are set apart: a change to the code restarts
    /// the application, so the code that runs now hasn't shown them. `standing` are the problems
    /// that hold until something is done about them, as a failed job does, whenever they began.
    #[must_use]
    pub fn report(&self, observed: Vec<DiagnosticIssue>, standing: Vec<DiagnosticIssue>) -> DiagnosticsReport {
        let started_at_ms = self.inner.started_at_ms;
        let (mut before_restart, mut issues): (Vec<_>, Vec<_>) = observed
            .into_iter()
            .partition(|issue| issue.last_seen_ms.is_some_and(|seen| seen < started_at_ms));
        issues.extend(standing);
        sort_by_severity(&mut before_restart);

        let traces_since_start = self.inner.traces.read().map_or(0, |traces| {
            traces
                .iter()
                .filter(|trace| is_serving(trace.kind) && trace.finished_at_ms >= started_at_ms)
                .count()
        });

        DiagnosticsReport {
            before_restart,
            started_at_ms,
            traces_since_start,
            ..finalize_diagnostics(issues)
        }
    }

    /// Whether a record stamped `at_ms` was captured since this process started. What came before,
    /// an earlier run of the application left, and the code may have changed since.
    fn is_of_this_run(&self, at_ms: i64) -> bool {
        at_ms >= self.inner.started_at_ms
    }

    fn diagnose_exceptions(&self, mount: &str, since_ms: i64, issues: &mut Vec<DiagnosticIssue>) {
        let Ok(exceptions) = self.inner.exceptions.read() else {
            return;
        };
        let latest = || {
            exceptions
                .iter()
                .take(100)
                .filter(|exception| exception.timestamp_ms >= since_ms)
        };
        // An error counts the times this run raised it, or the times earlier runs did when this
        // one hasn't...
        let mut counts: HashMap<(&str, bool), usize> = HashMap::new();
        for exception in latest() {
            let run = self.is_of_this_run(exception.timestamp_ms);
            *counts.entry((exception.message.as_str(), run)).or_insert(0) += 1;
        }

        let mut seen = HashSet::new();
        for exception in latest() {
            if !seen.insert(exception.message.as_str()) {
                continue;
            }
            let run = self.is_of_this_run(exception.timestamp_ms);
            let count = counts[&(exception.message.as_str(), run)];
            let times = if count > 1 {
                format!(" ({count}×)")
            } else {
                String::new()
            };
            let mut detail = Vec::new();
            if !exception.causes.is_empty() {
                detail.push(format!("Caused by: {}.", exception.causes.join(" → ")));
            }
            if let (Some(method), Some(path)) = (&exception.method, &exception.path) {
                detail.push(format!("Raised during {method} {path}."));
            }
            let detail = if detail.is_empty() {
                exception.message.clone()
            } else {
                detail.join(" ")
            };

            issues.push(DiagnosticIssue {
                severity: "critical".to_owned(),
                category: "exception".to_owned(),
                title: format!(
                    "{}{times}: {}",
                    short_type(&exception.error_type),
                    truncate(&exception.message, 110)
                ),
                detail,
                location: exception.location.clone(),
                trace_id: exception.trace_id.clone(),
                resource_id: Some(exception.id.to_string()),
                hint: "Read the code at the location, and what the application did before it failed.".to_owned(),
                next: exception
                    .trace_id
                    .as_ref()
                    .map(|trace| format!("GET {mount}/api/traces/{trace}")),
                last_seen_ms: Some(exception.timestamp_ms),
            });
            if issues.len() >= 8 {
                break;
            }
        }
    }

    fn diagnose_queries(&self, mount: &str, since_ms: i64, issues: &mut Vec<DiagnosticIssue>) {
        let Ok(queries) = self.inner.queries.read() else {
            return;
        };
        let latest = || {
            queries
                .iter()
                .take(1000)
                .filter(|query| query.started_at_ms >= since_ms)
        };

        // A command such as `migrate` repeats queries by design, so only the work an application
        // does for its users is looked at: its requests, jobs, and workflows...
        let serving: HashSet<String> = self.inner.traces.read().map_or_else(
            |_| HashSet::new(),
            |traces| {
                traces
                    .iter()
                    .filter(|trace| is_serving(trace.kind))
                    .map(|trace| trace.id.clone())
                    .collect()
            },
        );

        // The same read, many times in one trace...
        let mut groups: HashMap<(&str, &str), Vec<&QueryRecord>> = HashMap::new();
        for query in latest() {
            if let Some(trace) = &query.trace_id
                && is_repeatable(query)
                && serving.contains(trace)
            {
                groups.entry((trace, &query.normalized_sql)).or_default().push(query);
            }
        }
        // One issue for each place in the code, however many requests went through it...
        type Place<'a> = (&'a str, Option<&'a str>);
        struct Repeated<'a> {
            trace: &'a str,
            queries: Vec<&'a QueryRecord>,
            last_seen_ms: i64,
        }
        let latest_of =
            |group: &[&QueryRecord]| group.iter().map(|query| query.started_at_ms).max().unwrap_or(i64::MIN);
        let mut worst: HashMap<Place<'_>, Repeated<'_>> = HashMap::new();
        for ((trace, sql), group) in groups {
            if group.len() < 3 {
                continue;
            }
            let location = group.iter().find_map(|query| query.location.as_deref());
            let known = worst.entry((sql, location)).or_insert(Repeated {
                trace,
                queries: Vec::new(),
                last_seen_ms: i64::MIN,
            });
            known.last_seen_ms = known.last_seen_ms.max(latest_of(&group));
            // A trace of this run before one of an earlier run, then the trace that repeated it
            // most, and of those, the latest...
            let rank = |group: &[&QueryRecord]| {
                let latest = latest_of(group);
                (self.is_of_this_run(latest), group.len(), latest)
            };
            if rank(&group) > rank(&known.queries) {
                known.trace = trace;
                known.queries = group;
            }
        }
        let mut repeated: Vec<_> = worst.into_iter().collect();
        repeated.sort_by(|a, b| {
            self.is_of_this_run(b.1.last_seen_ms)
                .cmp(&self.is_of_this_run(a.1.last_seen_ms))
                .then(b.1.queries.len().cmp(&a.1.queries.len()))
                .then(a.0.cmp(&b.0))
        });

        for ((sql, location), repeated) in repeated.into_iter().take(5) {
            let (trace, group) = (repeated.trace, repeated.queries);
            let total_ms: f64 = group.iter().map(|query| query.duration_ms).sum();
            issues.push(DiagnosticIssue {
                severity: "warning".to_owned(),
                category: "n_plus_one".to_owned(),
                title: format!("N+1 query: the same SELECT ran {}× in one trace ({total_ms:.1}ms)", group.len()),
                detail: truncate(sql, 240),
                location: location.map(str::to_owned),
                trace_id: Some(trace.to_owned()),
                resource_id: None,
                hint: "Load the rows in one query: eager load the relationship with `.with(...)`, count with `with_count`, or filter with `is_in(...)`.".to_owned(),
                next: Some(format!("GET {mount}/api/traces/{trace}")),
                last_seen_ms: Some(repeated.last_seen_ms),
            });
        }

        // The slowest queries, one for each statement, and this run's before an earlier run's...
        let mut slow: Vec<&QueryRecord> = latest().filter(|query| query.is_slow).collect();
        let mut last_seen: HashMap<&str, i64> = HashMap::new();
        for query in &slow {
            let seen = last_seen
                .entry(query.normalized_sql.as_str())
                .or_insert(query.started_at_ms);
            *seen = (*seen).max(query.started_at_ms);
        }
        slow.sort_by(|a, b| {
            self.is_of_this_run(b.started_at_ms)
                .cmp(&self.is_of_this_run(a.started_at_ms))
                .then(b.duration_ms.total_cmp(&a.duration_ms))
        });
        let mut seen = HashSet::new();
        for query in slow {
            if !seen.insert(query.normalized_sql.as_str()) {
                continue;
            }
            issues.push(DiagnosticIssue {
                severity: "warning".to_owned(),
                category: "slow_query".to_owned(),
                title: format!(
                    "Slow query: {:.1}ms (over {}ms)",
                    query.duration_ms, self.inner.config.slow_query_ms
                ),
                detail: truncate(&query.sql, 240),
                location: query.location.clone(),
                trace_id: query.trace_id.clone(),
                resource_id: Some(query.id.to_string()),
                hint: "Add an index for the filtered and ordered columns, select fewer columns, or paginate."
                    .to_owned(),
                next: query
                    .trace_id
                    .as_ref()
                    .map(|trace| format!("GET {mount}/api/traces/{trace}")),
                last_seen_ms: last_seen.get(query.normalized_sql.as_str()).copied(),
            });
            if seen.len() >= 4 {
                break;
            }
        }
    }

    fn diagnose_requests(&self, mount: &str, since_ms: i64, issues: &mut Vec<DiagnosticIssue>) {
        let Ok(traces) = self.inner.traces.read() else {
            return;
        };
        let slow_ms = self.inner.config.slow_request_ms as f64;
        let mut seen = HashSet::new();

        for trace in traces.iter().filter(|trace| {
            trace.kind == TraceKind::Request
                && trace.response_ms() >= slow_ms
                && !trace.is_error
                && trace.started_at_ms >= since_ms
        }) {
            if !seen.insert(trace.name.as_str()) {
                continue;
            }
            issues.push(DiagnosticIssue {
                severity: "warning".to_owned(),
                category: "slow_request".to_owned(),
                title: format!("Slow request: {} took {:.1}ms", trace.name, trace.response_ms()),
                detail: format!(
                    "{} took {:.1}ms, and {} made. The response was {}.",
                    counted(trace.query_count, "query", "queries"),
                    trace.total_query_ms,
                    counted(
                        trace.http_client_count,
                        "outgoing HTTP request was",
                        "outgoing HTTP requests were"
                    ),
                    trace
                        .status_code
                        .map_or_else(|| "unknown".to_owned(), |code| code.to_string())
                ),
                location: None,
                trace_id: Some(trace.id.clone()),
                resource_id: Some(trace.id.clone()),
                hint: "See which of its spans took the time.".to_owned(),
                next: Some(format!("GET {mount}/api/traces/{}", trace.id)),
                last_seen_ms: Some(trace.started_at_ms),
            });
            if seen.len() >= 3 {
                break;
            }
        }
    }

    fn diagnose_http_client(&self, since_ms: i64, issues: &mut Vec<DiagnosticIssue>) {
        let Ok(requests) = self.inner.http_client.read() else {
            return;
        };
        let mut seen = HashSet::new();

        for request in requests
            .iter()
            .filter(|request| request.is_error && request.timestamp_ms >= since_ms)
        {
            if !seen.insert((request.method.as_str(), request.url.as_str())) {
                continue;
            }
            let outcome = request
                .status
                .map_or_else(|| "no response".to_owned(), |status| format!("HTTP {status}"));
            issues.push(DiagnosticIssue {
                severity: "warning".to_owned(),
                category: "http_client_error".to_owned(),
                title: format!(
                    "Outgoing request failed: {} {} ({outcome})",
                    request.method,
                    truncate(&request.url, 90)
                ),
                detail: request.error.clone().unwrap_or(outcome),
                location: None,
                trace_id: request.trace_id.clone(),
                resource_id: Some(request.id.to_string()),
                hint: "Check the URL, the credentials, and whether the other service is up.".to_owned(),
                next: None,
                last_seen_ms: Some(request.timestamp_ms),
            });
            if seen.len() >= 3 {
                break;
            }
        }
    }
}

/// Totals over what the store's buffers hold.
#[derive(Debug, Clone, Default)]
pub struct StoreMetrics {
    pub total_requests: u64,
    pub total_errors: u64,
    pub error_rate_pct: f64,
    pub avg_request_ms: f64,
    pub p95_request_ms: f64,
    pub total_queries: u64,
    pub slow_queries: u64,
    pub duplicate_query_traces: usize,
    pub cache_hit_rate_pct: Option<f64>,
    pub latency_series: Vec<LatencyPoint>,
}

/// Order issues by severity and count them into a report, with none of them set apart as from
/// before a restart. [`StudioStore::report`] makes the report of a running application.
#[must_use]
pub fn finalize_diagnostics(mut issues: Vec<DiagnosticIssue>) -> DiagnosticsReport {
    sort_by_severity(&mut issues);
    let critical_count = issues.iter().filter(|issue| issue.severity == "critical").count();
    let warning_count = issues.iter().filter(|issue| issue.severity == "warning").count();
    let status = match (critical_count, warning_count) {
        (0, 0) => "healthy",
        (0, _) => "degraded",
        _ => "critical",
    };

    DiagnosticsReport {
        status: status.to_owned(),
        generated_at_ms: now_ms(),
        issue_count: issues.len(),
        critical_count,
        warning_count,
        issues,
        before_restart: Vec::new(),
        started_at_ms: 0,
        traces_since_start: 0,
    }
}

fn sort_by_severity(issues: &mut [DiagnosticIssue]) {
    issues.sort_by_key(|issue| match issue.severity.as_str() {
        "critical" => 0,
        "warning" => 1,
        _ => 2,
    });
}

/// Whether a trace of this kind is work the application does for its users: a request, a queued
/// job, or a workflow advance. A console command or a tick isn't.
const fn is_serving(kind: TraceKind) -> bool {
    matches!(kind, TraceKind::Request | TraceKind::Job | TraceKind::Workflow)
}

fn push<T>(buffer: &RwLock<VecDeque<T>>, item: T, max: usize) {
    if let Ok(mut buffer) = buffer.write() {
        buffer.push_front(item);
        buffer.truncate(max);
    }
}

fn clear<T>(buffer: &RwLock<VecDeque<T>>) {
    if let Ok(mut buffer) = buffer.write() {
        buffer.clear();
    }
}

fn len<T>(buffer: &RwLock<VecDeque<T>>) -> usize {
    buffer.read().map(|buffer| buffer.len()).unwrap_or(0)
}

fn newest<T: Clone>(buffer: &RwLock<VecDeque<T>>, limit: usize, keep: impl Fn(&T) -> bool) -> Vec<T> {
    buffer
        .read()
        .map(|buffer| buffer.iter().filter(|item| keep(item)).take(limit).cloned().collect())
        .unwrap_or_default()
}

fn sort_and_trim<T>(buffer: &RwLock<VecDeque<T>>, max: usize, timestamp: impl Fn(&T) -> i64) {
    if let Ok(mut buffer) = buffer.write() {
        buffer
            .make_contiguous()
            .sort_by_key(|item| std::cmp::Reverse(timestamp(item)));
        buffer.truncate(max.max(1));
    }
}

fn percent(part: u64, whole: u64) -> f64 {
    if whole == 0 {
        return 0.0;
    }

    (part as f64 / whole as f64 * 1000.0).round() / 10.0
}

/// The time now, in milliseconds since the Unix epoch.
#[must_use]
pub fn now_ms() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|elapsed| elapsed.as_millis() as i64)
        .unwrap_or(0)
}

/// A time as the application's tables hold it, such as `2026-12-02T10:00:00Z`, in milliseconds
/// since the Unix epoch.
pub(crate) fn timestamp_ms(time: &str) -> Option<i64> {
    time.parse::<jiff::Timestamp>()
        .ok()
        .map(jiff::Timestamp::as_millisecond)
}

/// Round milliseconds to two decimal places.
#[must_use]
pub fn round_ms(ms: f64) -> f64 {
    (ms * 100.0).round() / 100.0
}

/// A statement with its literals and placeholders written as `?`, so queries that differ only in
/// their values compare equal.
#[must_use]
pub fn normalize_sql(sql: &str) -> String {
    use std::sync::OnceLock;
    static PATTERNS: OnceLock<[Regex; 5]> = OnceLock::new();

    let [strings, placeholders, numbers, lists, whitespace] = PATTERNS.get_or_init(|| {
        [
            r"'(?:''|[^'])*'",
            r"\$\d+",
            r"\b\d+(?:\.\d+)?\b",
            r"(?i)\bin\s*\(\s*\?(?:\s*,\s*\?)*\s*\)",
            r"\s+",
        ]
        .map(|pattern| Regex::new(pattern).expect("the pattern is valid"))
    });

    let sql = strings.replace_all(sql, "?");
    let sql = placeholders.replace_all(&sql, "?");
    let sql = numbers.replace_all(&sql, "?");
    let sql = lists.replace_all(&sql, "in (?)");

    whitespace.replace_all(sql.trim(), " ").into_owned()
}

fn first_word(sql: &str) -> String {
    sql.trim_start_matches(['(', ' '])
        .split(|c: char| !c.is_ascii_alphabetic())
        .next()
        .unwrap_or_default()
        .to_ascii_uppercase()
}

/// Whether a statement only begins, ends, or configures a transaction or connection.
fn is_transaction_control(sql: &str) -> bool {
    matches!(
        first_word(sql).as_str(),
        "BEGIN" | "COMMIT" | "ROLLBACK" | "START" | "SAVEPOINT" | "RELEASE" | "PRAGMA" | "SET"
    )
}

/// Whether running the query again and again in one trace is an N+1 problem: it reads, and the
/// application's own code built it.
fn is_repeatable(query: &QueryRecord) -> bool {
    query.vendor.is_none() && !query.read_back && is_read(&query.normalized_sql)
}

/// The table a write changed, and the line of code that built the write.
struct Written {
    table: Option<String>,
    location: Option<String>,
}

/// Whether a read of `table`, built at `location`, reads back what the write before it wrote: the
/// same line of code built both, for the same table. Creating a model on MySQL runs such a pair,
/// an `INSERT` and a `SELECT` of the new row, because MySQL has no `RETURNING`.
fn reads_back(before: Option<&Written>, table: Option<&str>, location: Option<&str>) -> bool {
    before.is_some_and(|written| {
        table.is_some()
            && written.table.as_deref() == table
            && location.is_some()
            && written.location.as_deref() == location
    })
}

/// A source location as Studio shows it, and the dependency it's in, if any. Cargo builds
/// dependencies from its own directories, whose long paths are cut down to the crate, as
/// `laravel-rust-workflow-0.1.3/src/workflow/store/database.rs:146:57`.
#[must_use]
pub fn clean_location(location: &str) -> (String, Option<String>) {
    use std::sync::OnceLock;
    static WORKING_DIRECTORY: OnceLock<Option<String>> = OnceLock::new();

    let location = location.replace('\\', "/");
    for marker in ["/registry/src/", "/git/checkouts/"] {
        let Some((_, rest)) = location.split_once(marker) else {
            continue;
        };
        // Skip the registry's or the checkout's own directory...
        let rest = rest.split_once('/').map_or(rest, |(_, rest)| rest);
        let package = rest.split('/').next().unwrap_or_default();
        let name = match package.rsplit_once('-') {
            Some((name, version)) if version.starts_with(|c: char| c.is_ascii_digit()) => name,
            _ => package,
        };

        return (rest.to_owned(), Some(name.to_owned()));
    }

    // Code that a macro includes by its full path, such as a migration, says where it is in full.
    // The application runs from its own directory, which the path is shown from...
    let directory = WORKING_DIRECTORY.get_or_init(|| {
        let directory = std::env::current_dir().ok()?;
        Some(format!(
            "{}/",
            directory.to_string_lossy().replace('\\', "/").trim_end_matches('/')
        ))
    });
    if let Some(relative) = directory
        .as_deref()
        .and_then(|directory| location.strip_prefix(directory))
    {
        return (relative.to_owned(), None);
    }

    (location, None)
}

/// Whether a location that [`clean_location`] cut down is in a dependency: it starts with a
/// package's directory, as `laravel-rust-workflow-0.1.3/src/workflow/run.rs:631:64` does.
#[must_use]
pub fn is_dependency_location(location: &str) -> bool {
    use std::sync::OnceLock;
    static PACKAGE: OnceLock<Regex> = OnceLock::new();

    PACKAGE
        .get_or_init(|| Regex::new(r"^[A-Za-z0-9_-]+-\d+\.\d+\.\d+[^/]*/").expect("the pattern is valid"))
        .is_match(location)
}

/// Whether a statement reads rows. Only reads count as N+1 queries: a loop of inserts is a loop.
fn is_read(sql: &str) -> bool {
    match first_word(sql).as_str() {
        "SELECT" => true,
        "WITH" => {
            let sql = sql.to_ascii_lowercase();
            !["insert ", "update ", "delete "]
                .iter()
                .any(|write| sql.contains(write))
        }
        _ => false,
    }
}

/// Find the links and the sign-in codes in an email or a text message, which is usually what a
/// developer, or an agent driving the application, opened the message for.
pub(crate) fn extract_links_and_codes(mail: &mut MailRecord) {
    use std::sync::OnceLock;
    static URL: OnceLock<Regex> = OnceLock::new();
    static CODE: OnceLock<Regex> = OnceLock::new();

    let url = URL.get_or_init(|| Regex::new(r#"https?://[^\s<>"'`\])]+"#).expect("the pattern is valid"));
    let code = CODE.get_or_init(|| {
        Regex::new(r"(?i)\b(?:code|otp|pin|passcode|password|token)\b[^0-9\n]{0,24}?\b(\d{4,8})\b")
            .expect("the pattern is valid")
    });

    let mut urls: Vec<String> = Vec::new();
    for body in [mail.text.as_deref(), mail.html.as_deref()].into_iter().flatten() {
        for found in url.find_iter(body) {
            let found = found
                .as_str()
                .trim_end_matches(['.', ',', ';', ':', '!', '?'])
                .replace("&amp;", "&");
            if !urls.contains(&found) {
                urls.push(found);
            }
        }
    }

    let mut codes: Vec<String> = Vec::new();
    for body in [mail.subject.as_deref(), mail.text.as_deref()].into_iter().flatten() {
        for found in code.captures_iter(body) {
            let found = found[1].to_owned();
            if !codes.contains(&found) {
                codes.push(found);
            }
        }
    }

    mail.extracted_urls = urls;
    mail.extracted_codes = codes;
}

/// A count with its noun: `1 query`, or `3 queries`.
#[must_use]
pub(crate) fn counted<N>(count: N, one: &str, many: &str) -> String
where
    N: Copy + std::fmt::Display + TryInto<u64>,
{
    let noun = if count.try_into().is_ok_and(|count| count == 1) {
        one
    } else {
        many
    };

    format!("{count} {noun}")
}

/// At most `max` characters of `text`, with an ellipsis when it was cut.
#[must_use]
pub fn truncate(text: &str, max: usize) -> String {
    let mut characters = text.chars();
    let kept: String = characters.by_ref().take(max).collect();
    if characters.next().is_some() {
        format!("{kept}…")
    } else {
        kept
    }
}

/// The last segment of a type's path, as `app::handlers::InvoiceRenderFailed` is `InvoiceRenderFailed`.
#[must_use]
pub fn short_type(path: &str) -> &str {
    path.rsplit("::").next().unwrap_or(path)
}

/// The statement's kind and the first table it names, as `("SELECT", "users")`.
#[must_use]
pub fn parse_sql_op_table(sql: &str) -> (Option<String>, Option<String>) {
    use std::sync::OnceLock;
    static TABLE: OnceLock<Regex> = OnceLock::new();

    let operation = Some(first_word(sql)).filter(|word| !word.is_empty());
    let table = TABLE
        .get_or_init(|| {
            Regex::new(r#"(?i)\b(?:from|into|update|join|table)\s+[`"\[]?([a-z0-9_.]+)"#).expect("the pattern is valid")
        })
        .captures(sql)
        .map(|found| found[1].to_owned());

    (operation, table)
}

/// Order a trace's spans by when they started.
pub(crate) fn sort_spans(spans: &mut [SpanRecord]) {
    spans.sort_by(|a, b| {
        a.start_offset_ms
            .total_cmp(&b.start_offset_ms)
            .then_with(|| a.id.cmp(&b.id))
    });
}

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

    #[test]
    fn only_one_takes_the_singular() {
        assert_eq!(counted(1_u64, "query", "queries"), "1 query");
        assert_eq!(counted(0_usize, "query", "queries"), "0 queries");
        assert_eq!(counted(3_i64, "run is", "runs are"), "3 runs are");
    }

    #[test]
    fn queries_that_differ_only_in_their_values_normalize_alike() {
        let one = normalize_sql("select * from `users` where `id` = 1 and name = 'Taylor' limit 1");
        let two = normalize_sql("select * from `users`  where `id` = 42 and name = 'O''Brien' limit 1");
        assert_eq!(one, two);

        let list = normalize_sql("select * from posts where id in (?, ?, ?)");
        assert_eq!(list, normalize_sql("select * from posts where id IN ($1,$2)"));
    }

    #[test]
    fn a_read_of_the_row_its_own_line_wrote_is_a_read_back() {
        let written = Written {
            table: Some("users".to_owned()),
            location: Some("src/seed.rs:29:28".to_owned()),
        };

        assert!(reads_back(Some(&written), Some("users"), Some("src/seed.rs:29:28")));
        // Another line's read of the table is a query of its own...
        assert!(!reads_back(Some(&written), Some("users"), Some("src/seed.rs:31:9")));
        assert!(!reads_back(Some(&written), Some("posts"), Some("src/seed.rs:29:28")));
        assert!(!reads_back(None, Some("users"), Some("src/seed.rs:29:28")));
        // Without a line to compare, as when no query listener ran, nothing is known...
        let unplaced = Written {
            table: Some("users".to_owned()),
            location: None,
        };
        assert!(!reads_back(Some(&unplaced), Some("users"), None));
    }

    #[test]
    fn only_reads_count_as_repeated_queries() {
        assert!(is_read("select * from users"));
        assert!(is_read("WITH recent AS (SELECT 1) SELECT * FROM recent"));
        assert!(!is_read("insert into users (name) values (?)"));
        assert!(!is_read(
            "with moved as (delete from a returning *) select * from moved"
        ));
        assert!(is_transaction_control("BEGIN"));
        assert!(is_transaction_control("SAVEPOINT laravel_1"));
        assert!(!is_transaction_control("select 1"));
    }

    #[test]
    fn a_dependencys_location_is_cut_down_to_its_crate() {
        let (location, vendor) = clean_location(
            "/Users/taylor/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/laravel-rust-workflow-0.1.3/src/workflow/store/database.rs:146:57",
        );
        assert_eq!(
            location,
            "laravel-rust-workflow-0.1.3/src/workflow/store/database.rs:146:57"
        );
        assert_eq!(vendor.as_deref(), Some("laravel-rust-workflow"));

        assert!(is_dependency_location(&location));

        let (location, vendor) = clean_location("src/http/handlers/posts.rs:12:5");
        assert_eq!((location.as_str(), vendor), ("src/http/handlers/posts.rs:12:5", None));
        assert!(!is_dependency_location(&location));
    }

    #[test]
    fn statements_name_their_operation_and_table() {
        let (operation, table) = parse_sql_op_table("select `users`.* from `users` where `users`.`id` = ?");
        assert_eq!(
            (operation.as_deref(), table.as_deref()),
            (Some("SELECT"), Some("users"))
        );

        let (operation, table) = parse_sql_op_table("insert into \"posts\" (title) values (?)");
        assert_eq!(
            (operation.as_deref(), table.as_deref()),
            (Some("INSERT"), Some("posts"))
        );

        let (operation, table) = parse_sql_op_table("BEGIN");
        assert_eq!((operation.as_deref(), table), (Some("BEGIN"), None));
    }

    #[test]
    fn links_and_codes_are_found_in_messages() {
        let mut mail = MailRecord {
            id: 1,
            message_id: "m1".into(),
            trace_id: None,
            kind: "mail".into(),
            mailer: None,
            transport: None,
            from: None,
            to: None,
            cc: None,
            bcc: None,
            subject: Some("Your code".into()),
            text: Some("Verify: https://app.test/verify/5?signature=abc&expires=9.\nYour verification code: 482913\nOrder 2026 shipped.".into()),
            html: Some("<a href=\"https://app.test/verify/5?signature=abc&amp;expires=9\">Verify</a>".into()),
            attachments: 0,
            extracted_urls: Vec::new(),
            extracted_codes: Vec::new(),
            timestamp_ms: 0,
            is_error: false,
            error: None,
        };
        extract_links_and_codes(&mut mail);

        assert_eq!(
            mail.extracted_urls,
            ["https://app.test/verify/5?signature=abc&expires=9"]
        );
        assert_eq!(mail.extracted_codes, ["482913"]);
    }
}