zebrad 7.2.0

The Zcash Foundation's independent, consensus-compatible implementation of a Zcash node
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
//! Integration with sentry.io for event reporting.

use std::{
    borrow::Cow,
    collections::BTreeMap,
    env,
    panic::PanicHookInfo,
    sync::{
        atomic::{AtomicU64, Ordering},
        Mutex, MutexGuard, PoisonError,
    },
    thread,
    time::{Duration, Instant, SystemTime},
};

use sentry::{
    integrations::{backtrace::current_stacktrace, tracing::EventFilter},
    protocol::{
        Context, Envelope, Event, Exception, Frame, Log, LogAttribute, Map, Mechanism,
        SessionAttributes, SessionStatus, SessionUpdate, Stacktrace, Value,
    },
    types::random_uuid,
    ClientInitGuard, ClientOptions, Hub, Scope,
};
use tracing::Level;
use zebra_chain::{
    block::Height,
    parameters::{Network, NetworkUpgrade},
};

use crate::{
    application::{build_version, ZebradApp},
    components::{
        metrics::{
            node_context::{self, ChainPosition},
            sentry_policy::{SentryPolicy, TRANSPORT_QUEUE_ENVELOPES},
        },
        sync::progress,
    },
};

mod metrics_adapter;

/// Sends a tip block delay to Sentry with the block's height, so that nodes can be compared block
/// by block.
///
/// The height isn't a label on the `zcash.chain.tip.block_delay_seconds` histogram, because
/// Prometheus would keep a series per height, so the metrics policy skips that histogram.
pub(crate) fn send_tip_block_delay(height: Height, seconds: f64) {
    tip_block_delay(node_context::network(), height, seconds).capture();
}

/// Returns a tip block delay with the block's height and, once the network is known, its network
/// upgrade.
///
/// The network upgrade comes from the block's own height, because the tip height that the node
/// context reports lags behind a new tip, which would put an activation block in the previous
/// upgrade.
fn tip_block_delay(
    network: Option<&Network>,
    height: Height,
    seconds: f64,
) -> sentry::metrics::DistributionMetric {
    let distribution =
        sentry::metrics::distribution("zcash.chain.tip.block_delay_seconds", seconds)
            .unit(sentry::protocol::Unit::Second)
            .attribute("chain.height", height.0);

    match network {
        Some(network) => distribution.attribute(
            "chain.network_upgrade",
            NetworkUpgrade::current(network, height).to_string(),
        ),
        None => distribution,
    }
}

/// Keeps the Sentry client open until [`end`] drops it.
///
/// `zebrad` exits with `process::exit`, which skips destructors, so the guard must be dropped
/// explicitly to end the release health session and flush queued events and logs.
static CLIENT_GUARD: Mutex<Option<ClientInitGuard>> = Mutex::new(None);

/// The release health session in progress.
///
/// Zebra tracks sessions itself instead of through the SDK. The SDK keeps a session per hub, and
/// a thread's hub keeps the session it copied when the thread first used Sentry, so a session
/// the SDK started later, such as a daily one, would miss errors reported on other threads.
static SESSION: Mutex<Option<SessionUpdate<'static>>> = Mutex::new(None);

/// Errors reported from any thread since the session in progress started.
static SESSION_ERRORS: AtomicU64 = AtomicU64::new(0);

/// How long one release health session lasts before it is ended and replaced.
///
/// Sentry drops session updates for sessions that started more than five days earlier, so a
/// longer session could never report how it ended.
const SESSION_ROTATION_INTERVAL: Duration = Duration::from_secs(24 * 60 * 60);

/// Environment and CI metadata attached to all Sentry events.
#[derive(Debug, Default)]
struct Metadata {
    environment: Option<String>,
    tags: BTreeMap<&'static str, String>,
    ci_context: BTreeMap<&'static str, String>,
}

impl Metadata {
    fn from_env() -> Self {
        Self::from_lookup(env_var)
    }

    fn from_lookup<F>(lookup: F) -> Self
    where
        F: Fn(&str) -> Option<String>,
    {
        let mut metadata = Self {
            environment: lookup_value(&lookup, "SENTRY_ENVIRONMENT"),
            ..Default::default()
        };

        insert_lookup_values(
            &lookup,
            &mut metadata.ci_context,
            &[
                ("GITHUB_RUN_ID", "run_id"),
                ("GITHUB_RUN_ATTEMPT", "run_attempt"),
                ("GITHUB_WORKFLOW", "workflow"),
                ("GITHUB_JOB", "job"),
            ],
        );

        insert_lookup_values(
            &lookup,
            &mut metadata.tags,
            &[
                ("GITHUB_EVENT_NAME", "deploy.trigger"),
                ("CI_PR_NUMBER", "pr.number"),
                ("CI_TEST_ID", "test.id"),
            ],
        );

        if let Some(git_ref) = slugged_git_ref(&lookup) {
            metadata.tags.insert("git.ref", git_ref);
        }

        let git_sha = lookup_value(&lookup, "GITHUB_SHA")
            .or_else(|| ZebradApp::git_commit().map(ToOwned::to_owned));
        if let Some(git_sha) = git_sha {
            metadata.tags.insert("git.sha", git_sha);
        }

        if lookup_value(&lookup, "GITHUB_ACTIONS").is_some_and(|v| v.eq_ignore_ascii_case("true")) {
            metadata
                .tags
                .insert("ci.provider", "github-actions".to_owned());
        }

        metadata
    }

    fn client_options(&self) -> ClientOptions {
        self.client_options_with_release(release_name())
    }

    fn client_options_with_release(&self, release: String) -> ClientOptions {
        let log_attributes = self.log_attributes();
        let network = self.tags.get("chain.network").cloned();
        let started_at = Instant::now();
        let options = ClientOptions::new()
            .release(release)
            // The Sentry metrics flush budget is a share of this queue.
            .transport_channel_capacity(TRANSPORT_QUEUE_ENVELOPES)
            .transport(metrics_adapter::transport_factory())
            // Suspect commits need in-app stack frames. Only ERROR events and panics are sent as
            // events, so capturing the stack stays off the common paths.
            .attach_stacktrace(true)
            .before_send(|mut event| {
                if event.level >= sentry::Level::Error {
                    SESSION_ERRORS.fetch_add(1, Ordering::Relaxed);
                }
                mark_zebra_frames_in_app(&mut event);
                add_chain_tags(&mut event, node_context::chain_position());
                Some(event)
            })
            .before_send_log(move |mut log| {
                merge_log_attributes(&mut log, &log_attributes);
                merge_log_attributes(
                    &mut log,
                    &chain_log_attributes(node_context::chain_position()),
                );
                Some(log)
            })
            .before_send_metric(move |mut metric| {
                add_metric_attributes(
                    &mut metric.attributes,
                    network.as_deref(),
                    node_context::chain_position(),
                    started_at.elapsed(),
                );
                Some(metric)
            });

        match &self.environment {
            Some(environment) => options.environment(environment.clone()),
            None => options,
        }
    }

    /// Build the static CI/git attributes to attach to every outgoing [`Log`].
    ///
    /// `Scope::set_tag` only propagates to [`Event`]s, so Logs need their own
    /// enrichment path. CI context is namespaced under `ci.*` to mirror the
    /// grouping used for Event contexts.
    fn log_attributes(&self) -> Vec<(String, LogAttribute)> {
        let mut attrs = Vec::with_capacity(self.tags.len() + self.ci_context.len());
        for (key, value) in &self.tags {
            attrs.push(((*key).to_owned(), LogAttribute::from(value.clone())));
        }
        for (key, value) in &self.ci_context {
            attrs.push((format!("ci.{key}"), LogAttribute::from(value.clone())));
        }
        attrs
    }

    fn apply_to_scope(&self, scope: &mut Scope) {
        for (key, value) in &self.tags {
            scope.set_tag(key, value.as_str());
        }

        if !self.ci_context.is_empty() {
            scope.set_context("ci", Context::Other(context_map(&self.ci_context)));
        }
    }

    #[cfg(test)]
    fn environment(&self) -> Option<&str> {
        self.environment.as_deref()
    }
}

/// Starts the Sentry client and its release health sessions, which are replaced daily.
pub(crate) fn init(network: &Network) {
    let mut metadata = Metadata::from_env();
    metadata.tags.insert("chain.network", network.to_string());

    let guard = sentry::init(metadata.client_options());
    sentry::configure_scope(|scope| metadata.apply_to_scope(scope));

    let enabled = guard.is_enabled();
    *CLIENT_GUARD.lock().unwrap_or_else(PoisonError::into_inner) = Some(guard);

    // A disabled client has no sessions to rotate.
    if !enabled {
        return;
    }

    start_run_sessions();

    let rotation = thread::Builder::new()
        .name("sentry session rotation".to_owned())
        .spawn(|| loop {
            thread::sleep(SESSION_ROTATION_INTERVAL);
            rotate_session();
        });
    if let Err(error) = rotation {
        warn!(?error, "unable to start Sentry session rotation");
    }
}

/// Starts the first release health session of this run.
///
/// Every session of the run reports the same random ID as its distinct ID, so Sentry's crash-free
/// users rate is the share of runs without a crash.
fn start_run_sessions() {
    let Some(client) = Hub::current().client() else {
        return;
    };
    let options = client.options();
    let Some(release) = options.release.clone() else {
        return;
    };

    let attributes = SessionAttributes {
        release,
        environment: options.environment.clone(),
        ip_address: None,
        user_agent: None,
    };

    start_session(attributes, random_uuid().to_string());
}

/// Starts a release health session and reports that it started.
fn start_session(attributes: SessionAttributes<'static>, run_id: String) {
    let session = SessionUpdate {
        session_id: random_uuid(),
        distinct_id: Some(run_id),
        sequence: None,
        timestamp: None,
        started: SystemTime::now(),
        init: true,
        duration: None,
        status: SessionStatus::Ok,
        errors: 0,
        attributes,
    };

    send_session(session.clone());
    *lock_session() = Some(session);
}

/// Ends the session in progress with `status`, reports it, and returns it.
fn end_session(status: SessionStatus) -> Option<SessionUpdate<'static>> {
    let mut session = lock_session().take()?;

    session.init = false;
    session.status = status;
    session.errors = SESSION_ERRORS.swap(0, Ordering::Relaxed);
    session.timestamp = Some(SystemTime::now());
    session.duration = session
        .started
        .elapsed()
        .ok()
        .map(|duration| duration.as_secs_f64());

    send_session(session.clone());
    Some(session)
}

/// Ends the session in progress as exited and starts the next session of the same run.
fn rotate_session() {
    if let Some(ended) = end_session(SessionStatus::Exited) {
        let run_id = ended
            .distinct_id
            .expect("every session is started with the run ID");
        start_session(ended.attributes, run_id);
    }
}

fn send_session(session: SessionUpdate<'static>) {
    if let Some(client) = Hub::current().client() {
        let mut envelope = Envelope::new();
        envelope.add_item(session);
        client.send_envelope(envelope);
    }
}

fn lock_session() -> MutexGuard<'static, Option<SessionUpdate<'static>>> {
    SESSION.lock().unwrap_or_else(PoisonError::into_inner)
}

/// Ends the release health session with `status`, sends the metrics that are due without waiting
/// between envelopes, then closes the client.
///
/// The session update is queued before the metrics, so metrics can't take its place in the
/// transport queue.
///
/// Returns `false` if queued events, logs, and metrics could not be sent before the shutdown
/// timeout.
pub(crate) fn end(status: SessionStatus) -> bool {
    end_session(status);
    metrics_adapter::flush_at_exit();

    let guard = CLIENT_GUARD
        .lock()
        .unwrap_or_else(PoisonError::into_inner)
        .take();

    guard.is_none_or(|guard| guard.close(None))
}

/// Adds the chain position to `event`, keeping any tags the event already has.
fn add_chain_tags(event: &mut Event<'static>, chain_position: Option<ChainPosition>) {
    let Some(chain_position) = chain_position else {
        return;
    };

    event
        .tags
        .entry("chain.height".to_owned())
        .or_insert_with(|| chain_position.tip_height.0.to_string());
    event
        .tags
        .entry("chain.network_upgrade".to_owned())
        .or_insert_with(|| chain_position.network_upgrade.to_string());
}

/// Returns the chain position as log attributes, with the height as a number so that log
/// queries can aggregate it.
fn chain_log_attributes(chain_position: Option<ChainPosition>) -> Vec<(String, LogAttribute)> {
    let Some(chain_position) = chain_position else {
        return Vec::new();
    };

    vec![
        (
            "chain.height".to_owned(),
            LogAttribute::from(chain_position.tip_height.0),
        ),
        (
            "chain.network_upgrade".to_owned(),
            LogAttribute::from(chain_position.network_upgrade.to_string()),
        ),
    ]
}

/// Adds the network, the network upgrade at the tip, whether the node is near the tip, and the
/// process uptime to a metric's attributes, keeping any the metric already has.
///
/// Unlike events and logs, metrics don't get the tip height, because a block timing value is often
/// for a block above the tip.
fn add_metric_attributes(
    attributes: &mut Map<Cow<'static, str>, LogAttribute>,
    network: Option<&str>,
    chain_position: Option<ChainPosition>,
    uptime: Duration,
) {
    if let Some(network) = network {
        attributes
            .entry("chain.network".into())
            .or_insert_with(|| network.to_owned().into());
    }
    if let Some(chain_position) = chain_position {
        attributes
            .entry("chain.network_upgrade".into())
            .or_insert_with(|| chain_position.network_upgrade.to_string().into());
        attributes
            .entry("chain.near_tip".into())
            .or_insert_with(|| chain_position.near_tip.into());
    }
    attributes
        .entry("process.uptime_seconds".into())
        .or_insert_with(|| uptime.as_secs().into());
}

/// Returns the Sentry tracing layer, or `None` if [`init`] has not bound an enabled client.
///
/// Must be called after [`init`].
pub(crate) fn tracing_layer<S>() -> Option<impl tracing_subscriber::Layer<S>>
where
    S: tracing::Subscriber + for<'span> tracing_subscriber::registry::LookupSpan<'span>,
{
    is_client_enabled().then(|| {
        sentry::integrations::tracing::layer()
            // Zebra doesn't send Sentry traces, so a Sentry span would never be sent, and building
            // one costs work on every poll of an instrumented future, such as each peer message.
            .span_filter(|_| false)
            .event_filter(|metadata| match *metadata.level() {
                Level::ERROR => EventFilter::Event | EventFilter::Log,
                Level::WARN => EventFilter::Log | EventFilter::Breadcrumb,
                // Sync progress is logged once a minute, so sending it gives Sentry each node's
                // height and network upgrade over time without the volume of all INFO logs.
                Level::INFO if metadata.target() == progress::LOG_TARGET => {
                    EventFilter::Log | EventFilter::Breadcrumb
                }
                Level::INFO => EventFilter::Breadcrumb,
                _ => EventFilter::Ignore,
            })
    })
}

/// Returns the recorder that sends every metric to Sentry, starting the thread that flushes it on
/// the first call. Returns `None` if [`init`] has not bound an enabled client, or if that thread
/// can't start.
///
/// Must be called after the tracing subscriber is installed, so a failure to start the thread is
/// logged.
pub(crate) fn metrics_recorder() -> Option<&'static SentryPolicy> {
    if !is_client_enabled() {
        return None;
    }

    metrics_adapter::start()
}

fn is_client_enabled() -> bool {
    Hub::current()
        .client()
        .is_some_and(|client| client.is_enabled())
}

/// Builds the Sentry event for a panic.
///
/// Like Sentry's panic integration, the panic message becomes the issue title and the current
/// stack trace locates and groups it. Zebra's panic report is attached for its diagnostic
/// metadata.
pub(crate) fn panic_event_from(
    panic_info: &PanicHookInfo<'_>,
    panic_report: impl ToString,
) -> Event<'static> {
    let exception = Exception {
        ty: "panic".into(),
        mechanism: Some(Mechanism {
            ty: "panic".into(),
            handled: Some(false),
            ..Default::default()
        }),
        value: Some(
            panic_info
                .payload_as_str()
                .unwrap_or("Box<dyn Any>")
                .to_owned(),
        ),
        stacktrace: current_stacktrace().map(without_panic_handling_frames),
        ..Default::default()
    };

    let mut panic_context = Map::new();
    panic_context.insert("report".to_owned(), panic_report.to_string().into());
    if let Some(location) = panic_info.location() {
        panic_context.insert("location".to_owned(), location.to_string().into());
    }

    let mut event = Event {
        exception: vec![exception].into(),
        level: sentry::Level::Fatal,
        ..Default::default()
    };
    event
        .contexts
        .insert("panic".to_owned(), Context::Other(panic_context));

    event
}

/// Removes the frames that handle the panic: the standard library's panic machinery and the
/// panic hook that builds the event.
///
/// Sentry names an issue after its newest in-app frame, and the hook's frames are in-app, so
/// without this every panic would point at the hook instead of the code that panicked.
fn without_panic_handling_frames(mut stacktrace: Stacktrace) -> Stacktrace {
    let starts_panic = |frame: &Frame| {
        frame.function.as_deref().is_some_and(|function| {
            function.starts_with("std::panicking::") || function.ends_with("rust_begin_unwind")
        })
    };
    let is_runtime = |frame: &Frame| {
        frame.function.as_deref().is_some_and(|function| {
            function.starts_with("std::")
                || function.starts_with("core::")
                || function.ends_with("rust_begin_unwind")
        })
    };

    // Frames are ordered from oldest to newest.
    if let Some(mut first_panic_frame) = stacktrace.frames.iter().rposition(starts_panic) {
        while first_panic_frame > 0 && is_runtime(&stacktrace.frames[first_panic_frame - 1]) {
            first_panic_frame -= 1;
        }
        stacktrace.frames.truncate(first_panic_frame);
    }

    stacktrace
}

/// Marks the stack frames from Zebra's crates as in-app, and every other frame as not in-app.
///
/// The SDK classifies frames by function name, but release builds keep only line tables, so
/// inlined frames lose their module path. When no frame matches, the SDK marks every frame
/// in-app. Zebra's frames keep their source file, so Zebra classifies frames by path instead, and
/// frames without one are not in-app.
fn mark_zebra_frames_in_app(event: &mut Event<'static>) {
    let exception_stacktraces = event
        .exception
        .values
        .iter_mut()
        .filter_map(|exception| exception.stacktrace.as_mut());
    let thread_stacktraces = event
        .threads
        .values
        .iter_mut()
        .filter_map(|thread| thread.stacktrace.as_mut());

    for stacktrace in exception_stacktraces
        .chain(thread_stacktraces)
        .chain(event.stacktrace.as_mut())
    {
        for frame in &mut stacktrace.frames {
            frame.in_app = Some(frame.abs_path.as_deref().is_some_and(is_zebra_source));
        }
    }
}

/// Returns whether `path` is a source file in one of Zebra's crates.
///
/// A crate's sources are in `<crate directory>/src/`. The directory is the crate name in a
/// checkout, such as `/zebra/zebrad/src/` in the Docker images, and the crate name and version
/// in the Cargo registry, such as `zebra-chain-14.0.0/src/`.
fn is_zebra_source(path: &str) -> bool {
    let is_zebra_crate = |dir: &str| {
        dir == "zebrad"
            || ["zebrad-", "zebra-", "tower-batch-control", "tower-fallback"]
                .iter()
                .any(|prefix| dir.starts_with(prefix))
    };

    let dirs = || path.split(['/', '\\']);

    dirs()
        .zip(dirs().skip(1))
        .any(|(dir, next)| next == "src" && is_zebra_crate(dir))
}

/// Merge `attrs` into `log.attributes`, letting existing keys win.
///
/// Tracing event fields are already present on the [`Log`] when the
/// `before_send_log` hook fires, so we must not overwrite them; this keeps
/// our CI/git metadata as a fallback that enriches (but never masks) the
/// log's own attributes.
fn merge_log_attributes(log: &mut Log, attrs: &[(String, LogAttribute)]) {
    for (key, value) in attrs {
        log.attributes
            .entry(key.clone())
            .or_insert_with(|| value.clone());
    }
}

fn env_var(key: &str) -> Option<String> {
    env::var(key).ok()
}

fn lookup_value<F>(lookup: &F, key: &str) -> Option<String>
where
    F: Fn(&str) -> Option<String>,
{
    let value = lookup(key)?;
    let value = value.trim();

    (!value.is_empty()).then(|| value.to_owned())
}

fn insert_lookup_values<F>(
    lookup: &F,
    target: &mut BTreeMap<&'static str, String>,
    mappings: &[(&str, &'static str)],
) where
    F: Fn(&str) -> Option<String>,
{
    for (env_key, target_key) in mappings {
        if let Some(value) = lookup_value(lookup, env_key) {
            target.insert(*target_key, value);
        }
    }
}

fn slugged_git_ref<F>(lookup: &F) -> Option<String>
where
    F: Fn(&str) -> Option<String>,
{
    [
        "GITHUB_REF_POINT_SLUG_URL",
        "GITHUB_HEAD_REF_SLUG_URL",
        "GITHUB_REF_NAME_SLUG_URL",
    ]
    .into_iter()
    .find_map(|key| lookup_value(lookup, key))
}

fn context_map(values: &BTreeMap<&'static str, String>) -> Map<String, Value> {
    values
        .iter()
        .map(|(key, value)| (key.to_string(), Value::String(value.clone())))
        .collect()
}

fn release_name() -> String {
    release_name_from(&env_var)
}

fn release_name_from<F>(lookup: &F) -> String
where
    F: Fn(&str) -> Option<String>,
{
    lookup_value(lookup, "SENTRY_RELEASE").unwrap_or_else(|| build_version().to_string())
}

#[cfg(test)]
mod tests {
    use std::{
        collections::{BTreeMap, HashMap},
        panic,
        sync::{Arc, Mutex},
        time::{Duration, SystemTime},
    };

    use sentry::{
        protocol::{
            Context, EnvelopeItem, Event, Frame, ItemContainer, Log, LogAttribute, LogLevel, Map,
            Metric, MetricType, SessionStatus, Stacktrace, Unit, Value,
        },
        test::{with_captured_envelopes_options, with_captured_events_options},
        Client, ClientOptions, Hub, Scope,
    };
    use tracing_subscriber::{layer::SubscriberExt, Registry};
    use zebra_chain::{
        block::Height,
        parameters::{Network, NetworkUpgrade},
    };

    use crate::{
        application::build_version,
        components::metrics::sentry_policy::{SentryPolicy, TRANSPORT_QUEUE_ENVELOPES},
    };

    use super::{
        add_chain_tags, add_metric_attributes, chain_log_attributes, end_session, is_zebra_source,
        merge_log_attributes, metrics_adapter, panic_event_from, release_name_from, rotate_session,
        start_run_sessions, tracing_layer, without_panic_handling_frames, ChainPosition, Metadata,
    };

    /// Returns the metrics that Sentry receives while `send` runs with a client built from
    /// `metadata`.
    fn sent_metrics(metadata: &Metadata, send: impl FnOnce()) -> Vec<Metric> {
        with_captured_envelopes_options(
            send,
            metadata.client_options_with_release("zebrad@test".to_string()),
        )
        .iter()
        .flat_map(|envelope| envelope.items())
        .filter_map(|item| match item {
            EnvelopeItem::ItemContainer(ItemContainer::Metrics(metrics)) => Some(metrics),
            _ => None,
        })
        .flatten()
        .cloned()
        .collect()
    }

    fn metric_attribute<'a>(metric: &'a Metric, key: &str) -> Option<&'a Value> {
        metric.attributes.get(key).map(|attribute| &attribute.0)
    }

    fn tracing_layer_installed_with(client: Option<Client>) -> bool {
        let hub = Hub::new(client.map(Arc::new), Arc::new(Scope::default()));
        Hub::run(Arc::new(hub), || tracing_layer::<Registry>().is_some())
    }

    #[test]
    fn tracing_layer_requires_a_client() {
        assert!(!tracing_layer_installed_with(None));
    }

    #[test]
    fn tracing_layer_requires_an_enabled_client() {
        let disabled = Client::from(ClientOptions::default());

        assert!(!tracing_layer_installed_with(Some(disabled)));
    }

    #[test]
    fn tracing_layer_is_installed_with_an_enabled_client() {
        let enabled = Client::from(sentry::apply_defaults(
            ClientOptions::new().dsn("https://public@example.com/1"),
        ));

        assert!(tracing_layer_installed_with(Some(enabled)));
    }

    #[test]
    fn tracing_layer_creates_no_sentry_spans() {
        let enabled = Client::from(sentry::apply_defaults(
            ClientOptions::new().dsn("https://public@example.com/1"),
        ));
        let hub = Hub::new(Some(Arc::new(enabled)), Arc::new(Scope::default()));

        Hub::run(Arc::new(hub), || {
            let layer = tracing_layer().expect("an enabled client installs the layer");
            let subscriber = Registry::default().with(layer);

            tracing::subscriber::with_default(subscriber, || {
                let _span = tracing::info_span!("work").entered();

                assert!(Hub::current()
                    .configure_scope(|scope| scope.get_span())
                    .is_none());
            });
        });
    }

    #[test]
    fn metadata_ignores_empty_values() {
        let env = HashMap::from([
            ("SENTRY_ENVIRONMENT", "".to_string()),
            ("CI_TEST_ID", "   ".to_string()),
        ]);
        let metadata = Metadata::from_lookup(|key| env.get(key).cloned());

        assert_eq!(metadata.environment(), None);
        assert_eq!(metadata.tags.get("test.id"), None);
        assert!(metadata.ci_context.is_empty());
    }

    #[test]
    fn metadata_reads_expected_tags_and_ci_context() {
        let env = HashMap::from([
            ("SENTRY_ENVIRONMENT", "stage".to_string()),
            ("GITHUB_ACTIONS", "true".to_string()),
            ("GITHUB_EVENT_NAME", "push".to_string()),
            ("GITHUB_REF_POINT_SLUG_URL", "main".to_string()),
            ("GITHUB_SHA", "deadbeef".to_string()),
            ("GITHUB_RUN_ID", "42".to_string()),
            ("GITHUB_RUN_ATTEMPT", "2".to_string()),
            ("GITHUB_WORKFLOW", "CI".to_string()),
            ("GITHUB_JOB", "deploy".to_string()),
            ("CI_TEST_ID", "sync-full-mainnet".to_string()),
        ]);
        let metadata = Metadata::from_lookup(|key| env.get(key).cloned());

        assert_eq!(metadata.environment(), Some("stage"));
        assert_eq!(
            metadata.tags.get("deploy.trigger").map(String::as_str),
            Some("push"),
        );
        assert_eq!(
            metadata.tags.get("git.ref").map(String::as_str),
            Some("main"),
        );
        assert_eq!(
            metadata.tags.get("git.sha").map(String::as_str),
            Some("deadbeef"),
        );
        assert_eq!(
            metadata.tags.get("ci.provider").map(String::as_str),
            Some("github-actions"),
        );
        assert_eq!(
            metadata.tags.get("test.id").map(String::as_str),
            Some("sync-full-mainnet"),
        );
        assert_eq!(
            metadata.ci_context.get("run_id").map(String::as_str),
            Some("42"),
        );
        assert_eq!(
            metadata.ci_context.get("run_attempt").map(String::as_str),
            Some("2"),
        );
        assert_eq!(
            metadata.ci_context.get("workflow").map(String::as_str),
            Some("CI"),
        );
        assert_eq!(
            metadata.ci_context.get("job").map(String::as_str),
            Some("deploy"),
        );
    }

    #[test]
    fn metadata_reads_pull_request_number_from_ci_input() {
        let env = HashMap::from([
            ("GITHUB_ACTIONS", "true".to_string()),
            ("GITHUB_REF_POINT_SLUG_URL", "fix-sentry-tags".to_string()),
            ("CI_PR_NUMBER", "84".to_string()),
        ]);
        let metadata = Metadata::from_lookup(|key| env.get(key).cloned());

        assert_eq!(
            metadata.tags.get("git.ref").map(String::as_str),
            Some("fix-sentry-tags"),
        );
        assert_eq!(
            metadata.tags.get("pr.number").map(String::as_str),
            Some("84"),
        );
    }

    #[test]
    fn metadata_prefers_slugged_git_ref_when_available() {
        let env = HashMap::from([
            (
                "GITHUB_REF_POINT_SLUG_URL",
                "feature-use-sentry".to_string(),
            ),
            (
                "GITHUB_HEAD_REF_SLUG_URL",
                "feature-use-plus-sentry".to_string(),
            ),
            ("GITHUB_REF_NAME_SLUG_URL", "84-merge".to_string()),
        ]);
        let metadata = Metadata::from_lookup(|key| env.get(key).cloned());

        assert_eq!(
            metadata.tags.get("git.ref").map(String::as_str),
            Some("feature-use-sentry"),
        );
    }

    #[test]
    fn metadata_ignores_missing_slugged_git_ref() {
        let env = HashMap::from([
            ("GITHUB_ACTIONS", "true".to_string()),
            ("GITHUB_EVENT_NAME", "push".to_string()),
        ]);
        let metadata = Metadata::from_lookup(|key| env.get(key).cloned());

        assert_eq!(metadata.tags.get("git.ref"), None);
    }

    #[test]
    fn release_name_prefers_sentry_release_override() {
        let env = HashMap::from([("SENTRY_RELEASE", "zebrad@4.4.0-rc.1".to_string())]);

        let release = release_name_from(&|key| env.get(key).cloned());

        assert_eq!(release, "zebrad@4.4.0-rc.1");
    }

    #[test]
    fn release_name_defaults_to_build_version() {
        let env: HashMap<&str, String> = HashMap::new();

        let release = release_name_from(&|key| env.get(key).cloned());

        assert_eq!(release, build_version().to_string());
    }

    #[test]
    fn client_options_leave_sessions_to_zebra_and_roundtrip_environment() {
        let env = HashMap::from([("SENTRY_ENVIRONMENT", "stage".to_string())]);
        let metadata = Metadata::from_lookup(|key| env.get(key).cloned());

        let options = metadata.client_options_with_release("zebrad@test".to_string());

        assert!(!options.auto_session_tracking);
        assert_eq!(options.environment.as_deref(), Some("stage"));
        assert_eq!(options.release.as_deref(), Some("zebrad@test"));
        assert_eq!(
            options.transport_channel_capacity.map(usize::from),
            Some(TRANSPORT_QUEUE_ENVELOPES),
            "the metrics flush budget leaves room in this queue",
        );
        assert!(
            options.transport.is_some(),
            "metrics flushes check the transport the client sends through",
        );
    }

    #[test]
    fn client_options_omits_environment_when_unset() {
        let metadata = Metadata::from_lookup(|_: &str| -> Option<String> { None });

        let options = metadata.client_options_with_release("zebrad@test".to_string());

        assert!(options.environment.is_none());
    }

    #[test]
    fn log_attributes_include_tags_and_ci_context() {
        let env = HashMap::from([
            ("GITHUB_ACTIONS", "true".to_string()),
            ("GITHUB_EVENT_NAME", "push".to_string()),
            ("GITHUB_SHA", "deadbeef".to_string()),
            ("GITHUB_REF_POINT_SLUG_URL", "main".to_string()),
            ("GITHUB_RUN_ID", "42".to_string()),
            ("GITHUB_RUN_ATTEMPT", "2".to_string()),
            ("GITHUB_WORKFLOW", "CI".to_string()),
            ("GITHUB_JOB", "deploy".to_string()),
            ("CI_TEST_ID", "sync-full-mainnet".to_string()),
            ("CI_PR_NUMBER", "84".to_string()),
        ]);
        let metadata = Metadata::from_lookup(|key| env.get(key).cloned());

        let attrs: BTreeMap<String, LogAttribute> = metadata.log_attributes().into_iter().collect();

        let expect = |key: &str, value: &str| {
            assert_eq!(
                attrs.get(key).and_then(|attr| attr.0.as_str()),
                Some(value),
                "missing or wrong log attribute {key}",
            );
        };

        expect("test.id", "sync-full-mainnet");
        expect("git.sha", "deadbeef");
        expect("git.ref", "main");
        expect("ci.provider", "github-actions");
        expect("pr.number", "84");
        expect("deploy.trigger", "push");
        expect("ci.run_id", "42");
        expect("ci.run_attempt", "2");
        expect("ci.workflow", "CI");
        expect("ci.job", "deploy");
    }

    #[test]
    fn merge_log_attributes_preserves_existing() {
        let mut log = Log {
            level: LogLevel::Info,
            body: "test".to_string(),
            trace_id: None,
            timestamp: SystemTime::UNIX_EPOCH,
            severity_number: None,
            attributes: BTreeMap::new(),
        };

        log.attributes.insert(
            "git.sha".to_string(),
            LogAttribute::from("event-sha".to_string()),
        );

        let attrs = vec![
            (
                "git.sha".to_string(),
                LogAttribute::from("metadata-sha".to_string()),
            ),
            (
                "ci.run_id".to_string(),
                LogAttribute::from("42".to_string()),
            ),
        ];

        merge_log_attributes(&mut log, &attrs);

        assert_eq!(
            log.attributes
                .get("git.sha")
                .and_then(|attr| attr.0.as_str()),
            Some("event-sha"),
            "pre-existing attribute must not be overwritten",
        );
        assert_eq!(
            log.attributes
                .get("ci.run_id")
                .and_then(|attr| attr.0.as_str()),
            Some("42"),
            "new attribute must be inserted",
        );
    }

    /// Returns the chain position at `tip_height` on Mainnet.
    fn chain_position(tip_height: u32, near_tip: bool) -> ChainPosition {
        let tip_height = Height(tip_height);
        ChainPosition {
            tip_height,
            network_upgrade: NetworkUpgrade::current(&Network::Mainnet, tip_height),
            near_tip,
        }
    }

    #[test]
    fn chain_tags_keep_existing_event_tags() {
        let mut event = Event::default();
        event
            .tags
            .insert("chain.height".to_owned(), "event-height".to_owned());

        add_chain_tags(&mut event, Some(chain_position(3_543_405, true)));

        assert_eq!(
            event.tags.get("chain.height").map(String::as_str),
            Some("event-height"),
        );
        assert_eq!(
            event.tags.get("chain.network_upgrade").map(String::as_str),
            Some("Nu7"),
        );
    }

    #[test]
    fn chain_tags_are_omitted_before_the_tip_is_known() {
        let mut event = Event::default();

        add_chain_tags(&mut event, None);

        assert!(event.tags.is_empty());
        assert!(chain_log_attributes(None).is_empty());
    }

    #[test]
    fn chain_log_attributes_report_height_as_a_number() {
        let attrs: BTreeMap<String, LogAttribute> =
            chain_log_attributes(Some(chain_position(3_543_405, true)))
                .into_iter()
                .collect();

        assert_eq!(
            attrs.get("chain.height").and_then(|attr| attr.0.as_u64()),
            Some(3_543_405),
        );
        assert_eq!(
            attrs
                .get("chain.network_upgrade")
                .and_then(|attr| attr.0.as_str()),
            Some("Nu7"),
        );
    }

    #[test]
    fn tip_block_delays_are_sent_with_their_block_height() {
        let metadata = Metadata::from_lookup(|_: &str| -> Option<String> { None });

        // The Mainnet NU7 activation block, which the tip height read by other metrics often
        // hasn't reached yet.
        let height = Height(3_543_405);

        let metrics = sent_metrics(&metadata, || {
            super::tip_block_delay(Some(&Network::Mainnet), height, 2.0).capture();
        });

        let [metric] = metrics.as_slice() else {
            panic!("expected one tip block delay, got {metrics:?}");
        };
        assert_eq!(metric.name, "zcash.chain.tip.block_delay_seconds");
        assert_eq!(metric.r#type, MetricType::Distribution);
        assert_eq!(metric.value, 2.0);
        assert_eq!(metric.unit, Some(Unit::Second));
        assert_eq!(
            metric_attribute(metric, "chain.height").and_then(Value::as_u64),
            Some(3_543_405),
        );
        assert_eq!(
            metric_attribute(metric, "chain.network_upgrade").and_then(Value::as_str),
            Some("Nu7"),
        );
    }

    #[test]
    fn metrics_are_sent_with_their_unit_and_labels() {
        let mut metadata = Metadata::from_lookup(|_: &str| -> Option<String> { None });
        metadata.tags.insert("chain.network", "Mainnet".to_owned());
        let policy = SentryPolicy::default();

        metrics::with_local_recorder(&policy, || {
            crate::components::metrics::describe_all();

            metrics::histogram!("sync.stage.duration_seconds", "stage" => "obtain_tips")
                .record(2.0);
            // Sent directly with its block height, so the policy skips it.
            metrics::histogram!(
                "zcash.chain.tip.block_delay_seconds",
                "chain.network_upgrade" => "Nu7",
            )
            .record(2.0);
            metrics::counter!("sync.block.error.count", "kind" => "not_found").increment(3);
            metrics::gauge!("zebra.state.rocksdb.total_disk_size_bytes").set(1024.0);
        });
        let metrics = sent_metrics(&metadata, || policy.flush(metrics_adapter::send));

        let sent = |name: &str| {
            metrics
                .iter()
                .find(|metric| metric.name == name)
                .unwrap_or_else(|| panic!("{name} is sent: {metrics:?}"))
        };

        let stage = sent("sync.stage.duration_seconds");
        assert_eq!(stage.r#type, MetricType::Distribution);
        assert_eq!(stage.value, 2.0);
        assert_eq!(stage.unit, Some(Unit::Second));
        assert_eq!(
            metric_attribute(stage, "stage").and_then(Value::as_str),
            Some("obtain_tips"),
        );
        assert_eq!(
            metric_attribute(stage, "chain.network").and_then(Value::as_str),
            Some("Mainnet"),
        );
        assert!(
            metrics
                .iter()
                .all(|metric| metric.name != "zcash.chain.tip.block_delay_seconds"),
            "the policy doesn't send the tip block delay a second time",
        );

        let errors = sent("sync.block.error.count");
        assert_eq!(errors.r#type, MetricType::Counter);
        assert_eq!(errors.value, 3.0);
        assert_eq!(
            metric_attribute(errors, "kind").and_then(Value::as_str),
            Some("not_found"),
        );

        let disk_size = sent("zebra.state.rocksdb.total_disk_size_bytes");
        assert_eq!(disk_size.r#type, MetricType::Gauge);
        assert_eq!(disk_size.value, 1024.0);
        assert_eq!(disk_size.unit, Some(Unit::Byte));
    }

    #[test]
    fn metric_attributes_are_added_once_known_and_keep_existing_ones() {
        let mut attributes = Map::new();
        add_metric_attributes(&mut attributes, None, None, Duration::ZERO);
        assert_eq!(
            attributes.keys().collect::<Vec<_>>(),
            ["process.uptime_seconds"],
        );

        let mut attributes = Map::new();
        attributes.insert("chain.network_upgrade".into(), "metric-upgrade".into());
        add_metric_attributes(
            &mut attributes,
            Some("Mainnet"),
            Some(chain_position(3_543_405, true)),
            Duration::from_millis(90_500),
        );
        let attribute = |key: &str| attributes.get(key).map(|attr| &attr.0);

        assert_eq!(
            attribute("chain.network").and_then(|value| value.as_str()),
            Some("Mainnet"),
        );
        assert_eq!(
            attribute("chain.network_upgrade").and_then(|value| value.as_str()),
            Some("metric-upgrade"),
        );
        assert_eq!(
            attribute("process.uptime_seconds").and_then(|value| value.as_u64()),
            Some(90),
        );
    }

    #[test]
    fn metrics_say_whether_the_node_was_near_the_tip() {
        for near_tip in [false, true] {
            let mut attributes = Map::new();
            add_metric_attributes(
                &mut attributes,
                None,
                Some(chain_position(3_000_000, near_tip)),
                Duration::ZERO,
            );

            assert_eq!(
                attributes
                    .get("chain.near_tip")
                    .and_then(|attr| attr.0.as_bool()),
                Some(near_tip),
            );
        }
    }

    #[test]
    fn memory_metrics_are_sent_with_their_units() {
        let metadata = Metadata::from_lookup(|_: &str| -> Option<String> { None });

        let policy = metrics_adapter::start().expect("the test can start the flush thread");

        let metrics = sent_metrics(&metadata, || {
            metrics::with_local_recorder(policy, || {
                crate::components::metrics::describe_all();
                metrics::gauge!("state.memory.index.entries").set(2_000_000.0);
                metrics::gauge!("state.memory.backup.restore.duration_seconds").set(25.0);
                metrics::counter!("state.memory.fork.evicted.count").increment(2);
                // Recorded directly, so its unit is checked on every platform.
                metrics::gauge!("process.memory.rss_fraction").set(0.5);
                crate::components::metrics::record();
            });

            super::end(SessionStatus::Crashed);
        });

        let mut metrics: Vec<_> = metrics
            .iter()
            .map(|metric| (metric.name.to_string(), metric.r#type, metric.unit.clone()))
            .collect();
        metrics.sort_by(|a, b| a.0.cmp(&b.0));

        let mut expected = vec![
            (
                "state.memory.backup.restore.duration_seconds".to_string(),
                MetricType::Gauge,
                Some(Unit::Second),
            ),
            (
                "state.memory.fork.evicted.count".to_string(),
                MetricType::Counter,
                None,
            ),
            (
                "state.memory.index.entries".to_string(),
                MetricType::Gauge,
                None,
            ),
            (
                "process.memory.rss_fraction".to_string(),
                MetricType::Gauge,
                Some(Unit::Ratio),
            ),
        ];
        if cfg!(target_os = "linux") {
            expected.push((
                "process.memory.rss_bytes".to_string(),
                MetricType::Gauge,
                Some(Unit::Byte),
            ));
        }
        expected.sort_by(|a, b| a.0.cmp(&b.0));
        assert_eq!(metrics, expected);
    }

    #[test]
    fn counts_since_the_last_flush_are_sent_at_shutdown() {
        let metadata = Metadata::from_lookup(|_: &str| -> Option<String> { None });

        let policy = metrics_adapter::start().expect("the test can start the flush thread");

        let metrics = sent_metrics(&metadata, || {
            metrics::with_local_recorder(policy, || {
                metrics::counter!("sync.restart.count", "reason" => "sync_step_timeout")
                    .increment(1);
            });

            super::end(SessionStatus::Crashed);
        });

        let [metric] = metrics.as_slice() else {
            panic!("expected the restart count, got {metrics:?}");
        };

        assert_eq!(metric.name, "sync.restart.count");
        assert_eq!(metric.value, 1.0);
    }

    #[test]
    fn errors_from_any_hub_count_toward_the_session_in_progress() {
        let metadata = Metadata::from_lookup(|_: &str| -> Option<String> { None });

        let envelopes = with_captured_envelopes_options(
            || {
                start_run_sessions();
                // Hubs on other threads are copied once, before any later session starts.
                let earlier_hub = Hub::new_from_top(Hub::current());

                rotate_session();
                earlier_hub.capture_event(Event {
                    level: sentry::Level::Error,
                    ..Default::default()
                });
                end_session(SessionStatus::Crashed);
            },
            metadata.client_options_with_release("zebrad@test".to_string()),
        );

        let sessions: Vec<_> = envelopes
            .iter()
            .flat_map(|envelope| envelope.items())
            .filter_map(|item| match item {
                EnvelopeItem::SessionUpdate(session) => Some(session),
                _ => None,
            })
            .collect();

        let summary: Vec<_> = sessions
            .iter()
            .map(|session| (session.init, session.status, session.errors))
            .collect();
        assert_eq!(
            summary,
            [
                (true, SessionStatus::Ok, 0),
                (false, SessionStatus::Exited, 0),
                (true, SessionStatus::Ok, 0),
                (false, SessionStatus::Crashed, 1),
            ],
        );
        assert_eq!(sessions[0].session_id, sessions[1].session_id);
        assert_eq!(sessions[2].session_id, sessions[3].session_id);
        assert_ne!(sessions[0].session_id, sessions[2].session_id);
        assert!(
            sessions.iter().all(|session| session.distinct_id.is_some()
                && session.distinct_id == sessions[0].distinct_id),
            "every session of a run reports the run ID",
        );
    }

    #[test]
    fn panic_events_use_the_panic_message_and_stack() {
        static EVENT: Mutex<Option<Event<'static>>> = Mutex::new(None);

        let previous_hook = panic::take_hook();
        panic::set_hook(Box::new(|panic_info| {
            *EVENT.lock().expect("only this hook locks it") =
                Some(panic_event_from(panic_info, "full panic report"));
        }));
        let result = panic::catch_unwind(|| panic!("listener failed"));
        panic::set_hook(previous_hook);
        assert!(result.is_err());

        let event = EVENT
            .lock()
            .expect("the hook has returned")
            .take()
            .expect("the hook captured the panic");
        let exception = &event.exception.values[0];

        assert_eq!(exception.value.as_deref(), Some("listener failed"));
        assert_eq!(
            exception.mechanism.as_ref().and_then(|m| m.handled),
            Some(false)
        );
        // Optimized builds can inline the panicking closure and shorten function names, so check
        // that no frame that handles the panic remains, rather than naming the newest frame. Older
        // frames, such as the test's own `catch_unwind`, are expected to remain.
        let frames = &exception
            .stacktrace
            .as_ref()
            .expect("panic events carry a stack trace")
            .frames;
        let panic_handling = [
            "current_stacktrace",
            "panic_event_from",
            "rust_begin_unwind",
            "begin_panic_handler",
            "rust_panic_with_hook",
            "panic_with_hook",
            "panic_fmt",
        ];
        assert!(!frames.is_empty(), "the stack keeps the code that panicked");
        for function in frames.iter().filter_map(|frame| frame.function.as_deref()) {
            assert!(
                !panic_handling.iter().any(|name| function.contains(name)),
                "the stack ends at the code that panicked, without the panic handling: {function}",
            );
        }

        let Some(Context::Other(panic_context)) = event.contexts.get("panic") else {
            panic!("panic events carry the panic report");
        };
        assert_eq!(
            panic_context
                .get("report")
                .and_then(|report| report.as_str()),
            Some("full panic report"),
        );
        assert!(panic_context
            .get("location")
            .and_then(|location| location.as_str())
            .is_some_and(|location| location.contains("sentry.rs")));
    }

    #[test]
    fn panic_stacks_end_at_the_code_that_panicked() {
        let frame = |function: &str| Frame {
            function: Some(function.to_owned()),
            ..Default::default()
        };
        // Oldest first, as Sentry orders frames.
        let stacktrace = Stacktrace {
            frames: vec![
                frame("std::rt::lang_start"),
                frame("std::panicking::catch_unwind"),
                frame("zebrad::components::start"),
                frame("zebra_network::open_listener"),
                frame("core::panicking::panic_fmt"),
                frame("__rustc::rust_begin_unwind"),
                frame("std::panicking::panic_with_hook"),
                frame("zebrad::application::panic_hook"),
                frame("zebrad::sentry::panic_event_from"),
            ],
            ..Default::default()
        };

        let functions: Vec<_> = without_panic_handling_frames(stacktrace)
            .frames
            .into_iter()
            .filter_map(|frame| frame.function)
            .collect();

        assert_eq!(
            functions,
            [
                "std::rt::lang_start",
                "std::panicking::catch_unwind",
                "zebrad::components::start",
                "zebra_network::open_listener",
            ],
        );
    }

    /// Returns the frames Sentry uses for suspect commits: the exception stack traces, or the
    /// current thread's stack trace when no exception has one.
    fn suspect_commit_stacktrace<'a>(event: &'a Event<'static>) -> Option<&'a Stacktrace> {
        event
            .exception
            .iter()
            .find_map(|exception| exception.stacktrace.as_ref())
            .or_else(|| {
                event
                    .threads
                    .iter()
                    .find(|thread| thread.current)
                    .and_then(|thread| thread.stacktrace.as_ref())
            })
    }

    #[test]
    fn error_events_carry_in_app_frames_for_suspect_commits() {
        let metadata = Metadata::default();

        let events = with_captured_events_options(
            || {
                let layer = tracing_layer().expect("the test client is enabled");
                let subscriber = Registry::default().with(layer);

                tracing::subscriber::with_default(subscriber, || {
                    tracing::error!("block commit failed");

                    let error = std::io::Error::other("disk full");
                    tracing::error!(
                        error = &error as &dyn std::error::Error,
                        "block commit failed"
                    );
                });
            },
            // `sentry::init` adds the default integrations, which capture and classify stacks.
            sentry::apply_defaults(metadata.client_options_with_release("zebrad@test".to_string())),
        );

        assert_eq!(events.len(), 2, "both ERROR events are sent: {events:?}");

        for event in &events {
            let frames = &suspect_commit_stacktrace(event)
                .expect("ERROR events carry a stack trace")
                .frames;
            let in_app_frames: Vec<_> = frames
                .iter()
                .filter(|frame| frame.in_app == Some(true))
                .collect();

            assert!(
                in_app_frames.iter().any(|frame| frame
                    .abs_path
                    .as_deref()
                    .is_some_and(|path| path.ends_with("zebrad/src/sentry.rs"))),
                "the code that logged the error is an in-app frame with its source path: {frames:?}",
            );
            assert!(
                in_app_frames.iter().all(|frame| frame
                    .abs_path
                    .as_deref()
                    .is_some_and(|path| path.contains("zebrad/src/"))),
                "dependency frames are not in-app: {in_app_frames:?}",
            );
        }
    }

    #[test]
    fn zebra_sources_are_recognized_in_checkouts_and_the_registry() {
        for zebra_path in [
            "/zebra/zebrad/src/components/sync.rs",
            "/home/user/zebra/zebra-network/src/peer_set/initialize.rs",
            "/root/.cargo/registry/src/index.crates.io-0000/zebra-chain-14.0.0/src/block.rs",
            "/zebra/tower-batch-control/src/service.rs",
        ] {
            assert!(is_zebra_source(zebra_path), "{zebra_path} is Zebra's");
        }

        for other_path in [
            "/root/.cargo/registry/src/index.crates.io-0000/tokio-1.47.0/src/runtime/task.rs",
            "/rustc/f8297e351a40c1439a467bbbb6879088047f50b3/library/std/src/panicking.rs",
            "/zebra/zebrad/build.rs",
        ] {
            assert!(!is_zebra_source(other_path), "{other_path} is not Zebra's");
        }
    }
}