nautilus-system 0.62.0

System orchestration for the Nautilus trading engine
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
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

//! Kernel construction, component ownership, and run-lifecycle orchestration.
//!
//! # Architecture
//!
//! [`NautilusKernel`] owns the shared clock, cache, portfolio, trader, order emulator, and data,
//! risk, and execution engines around an in-process message bus. These components use
//! `Rc<RefCell<_>>`, so the kernel is not a cross-thread synchronization boundary.
//!
//! # Lifecycle
//!
//! Construction initializes logging, optional persistence, message-bus handlers, and shutdown
//! routing. Normal startup starts the engines before initializing the trader. Live callers then
//! connect data clients, let instrument events populate the cache, connect execution clients, and
//! call [`NautilusKernel::start_trader`]. Event-store replay instead restores state and skips
//! engines, clients, trader startup, and live reconciliation.
//!
//! Shutdown is split so [`NautilusKernel::stop_trader`] can emit residual events before
//! [`NautilusKernel::finalize_stop`] saves state, stops engines, cancels timers, and seals the
//! event-store run. [`NautilusKernel::reset`] retains the assembled system for reuse, while
//! [`NautilusKernel::dispose`] releases its resources.

use std::{
    cell::{Cell, Ref, RefCell},
    fmt::Debug,
    rc::Rc,
    time::Duration,
};

use nautilus_common::{
    cache::{Cache, CacheConfig, database::CacheDatabaseAdapter},
    clients::{SocketReconnectLookup, SocketReconnectRequestOutcome},
    clock::Clock,
    component::Component,
    enums::{ComponentState, Environment},
    logging::{
        arm_shutdown_on_error, disarm_shutdown_on_error, headers, init_logging,
        logger::{LogGuard, LoggerConfig},
        try_drain_shutdown_on_error_trigger,
    },
    messages::system::{ReconnectSocket, ShutdownSystem},
    msgbus::{
        self, MessageBus, MessagingSwitchboard, ShareableMessageHandler, get_message_bus,
        set_message_bus,
    },
};
use nautilus_core::{UUID4, UnixNanos};
use nautilus_data::engine::DataEngine;
use nautilus_execution::{
    engine::ExecutionEngine,
    order_emulator::{adapter::OrderEmulatorAdapter, emulator::OrderEmulator},
};
use nautilus_model::identifiers::{ClientId, TraderId};
use nautilus_portfolio::portfolio::Portfolio;
use nautilus_risk::engine::RiskEngine;
use ustr::Ustr;

use crate::{
    builder::NautilusKernelBuilder,
    clock_factory::ClockFactory,
    config::NautilusKernelConfig,
    event_store::{EventStoreFactory, KernelEventStore, RegisteredComponents},
    trader::Trader,
};

/// Core Nautilus system kernel.
///
/// Orchestrates data and execution engines, cache, clock, and messaging across environments.
#[derive(Debug)]
pub struct NautilusKernel {
    /// The kernel name (for logging and identification).
    pub name: String,
    /// The unique instance identifier for this kernel.
    pub instance_id: UUID4,
    /// The machine identifier (hostname or similar).
    pub machine_id: String,
    /// The kernel configuration.
    pub config: Box<dyn NautilusKernelConfig>,
    /// The shared in-memory cache.
    pub cache: Rc<RefCell<Cache>>,
    /// The clock driving the kernel.
    pub clock: Rc<RefCell<dyn Clock>>,
    /// The portfolio manager.
    pub portfolio: Rc<RefCell<Portfolio>>,
    /// Guard for the logging subsystem (keeps logger thread alive).
    pub log_guard: LogGuard,
    /// The data engine instance.
    pub data_engine: Rc<RefCell<DataEngine>>,
    /// The risk engine instance.
    pub risk_engine: Rc<RefCell<RiskEngine>>,
    /// The execution engine instance.
    pub exec_engine: Rc<RefCell<ExecutionEngine>>,
    /// The order emulator for handling emulated orders.
    pub order_emulator: OrderEmulatorAdapter,
    /// The trader component (shared for [`Controller`](crate::controller::Controller) access).
    pub trader: Rc<RefCell<Trader>>,
    /// The UNIX timestamp (nanoseconds) when the kernel was created.
    pub ts_created: UnixNanos,
    /// The UNIX timestamp (nanoseconds) when the kernel was last started.
    pub ts_started: Option<UnixNanos>,
    /// The UNIX timestamp (nanoseconds) when the kernel was last shutdown.
    pub ts_shutdown: Option<UnixNanos>,
    shutdown_requested: Rc<Cell<bool>>,
    event_store: Option<Box<dyn KernelEventStore>>,
    event_store_replay: bool,
    state_save_armed: bool,
}

/// Optional construction-time dependencies for [`NautilusKernel`].
#[derive(Default)]
pub struct NautilusKernelDependencies {
    clock_factory: Option<ClockFactory>,
    cache_database: Option<Box<dyn CacheDatabaseAdapter>>,
    event_store_factory: Option<EventStoreFactory>,
}

impl Debug for NautilusKernelDependencies {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct(stringify!(NautilusKernelDependencies))
            .field("clock_factory", &self.clock_factory.is_some())
            .field("cache_database", &self.cache_database.is_some())
            .field("event_store_factory", &self.event_store_factory.is_some())
            .finish()
    }
}

impl NautilusKernelDependencies {
    /// Add a clock factory.
    #[must_use]
    pub fn with_clock_factory(mut self, clock_factory: Option<ClockFactory>) -> Self {
        self.clock_factory = clock_factory;
        self
    }

    /// Add a cache database adapter.
    #[must_use]
    pub fn with_cache_database(
        mut self,
        cache_database: Option<Box<dyn CacheDatabaseAdapter>>,
    ) -> Self {
        self.cache_database = cache_database;
        self
    }

    /// Add an event-store factory.
    #[must_use]
    pub fn with_event_store_factory(
        mut self,
        event_store_factory: Option<EventStoreFactory>,
    ) -> Self {
        self.event_store_factory = event_store_factory;
        self
    }
}

impl NautilusKernel {
    /// Create a new [`NautilusKernelBuilder`] for fluent configuration.
    #[must_use]
    pub const fn builder(
        name: String,
        trader_id: TraderId,
        environment: Environment,
    ) -> NautilusKernelBuilder {
        NautilusKernelBuilder::new(name, trader_id, environment)
    }

    /// Create a new [`NautilusKernel`] instance.
    ///
    /// # Errors
    ///
    /// Returns an error if the kernel fails to initialize.
    pub fn new<T: NautilusKernelConfig + 'static>(name: String, config: T) -> anyhow::Result<Self> {
        Self::new_with(name, config, None, None)
    }

    /// Create a new [`NautilusKernel`] instance with an injected cache database adapter.
    ///
    /// The adapter is passed straight to [`Cache::new`] so the kernel can restore
    /// generic cache state (including snapshot blobs anchored by the event store) from
    /// the durable backing store on startup, without an external caller pre-seeding the
    /// in-memory cache.
    ///
    /// # Errors
    ///
    /// Returns an error if the kernel fails to initialize.
    pub fn new_with_cache_database<T: NautilusKernelConfig + 'static>(
        name: String,
        config: T,
        cache_database: Option<Box<dyn CacheDatabaseAdapter>>,
    ) -> anyhow::Result<Self> {
        Self::new_with(name, config, cache_database, None)
    }

    /// Create a new [`NautilusKernel`] instance with optional cache database and event store
    /// injections.
    ///
    /// The cache adapter is passed to [`Cache::new`]; the event-store factory is invoked
    /// with the kernel's clock so the resulting [`KernelEventStore`] implementation shares
    /// the same time source the kernel uses to stamp `RunStarted`/`RunEnded` and any
    /// drop-seal fallback timestamp.
    ///
    /// # Errors
    ///
    /// Returns an error if the kernel fails to initialize or the event-store factory fails.
    pub fn new_with<T: NautilusKernelConfig + 'static>(
        name: String,
        config: T,
        cache_database: Option<Box<dyn CacheDatabaseAdapter>>,
        event_store_factory: Option<EventStoreFactory>,
    ) -> anyhow::Result<Self> {
        Self::new_with_dependencies(
            name,
            config,
            NautilusKernelDependencies::default()
                .with_cache_database(cache_database)
                .with_event_store_factory(event_store_factory),
        )
    }

    /// Create a new [`NautilusKernel`] instance with construction-time dependencies.
    ///
    /// # Errors
    ///
    /// Returns an error if the kernel fails to initialize or an injected factory fails.
    pub fn new_with_dependencies<T: NautilusKernelConfig + 'static>(
        name: String,
        config: T,
        dependencies: NautilusKernelDependencies,
    ) -> anyhow::Result<Self> {
        let NautilusKernelDependencies {
            clock_factory,
            cache_database,
            event_store_factory,
        } = dependencies;
        let instance_id = config.instance_id().unwrap_or_default();
        let machine_id = Self::determine_machine_id()?;

        let logger_config = config.logging();
        let log_guard = Self::initialize_logging(config.trader_id(), instance_id, logger_config)?;
        headers::log_header(
            config.trader_id(),
            &machine_id,
            instance_id,
            Ustr::from(&name),
        );

        log::info!("Building system kernel");

        let clock_factory =
            clock_factory.unwrap_or_else(|| ClockFactory::for_environment(config.environment()));
        let clock = clock_factory.clock();
        let event_store = match event_store_factory {
            Some(factory) => Some(factory(instance_id, clock.clone())?),
            None => None,
        };
        let cache = Self::initialize_cache(config.cache(), cache_database);

        let msgbus = Rc::new(RefCell::new(MessageBus::new(
            config.trader_id(),
            instance_id,
            Some(name.clone()),
            None,
        )));
        set_message_bus(msgbus);

        if let Some(config) = config.msgbus()
            && let Some(filter) = config.types_filter
        {
            get_message_bus().borrow_mut().set_types_filter(filter);
        }

        let portfolio = Rc::new(RefCell::new(Portfolio::new(
            clock.clone(),
            cache.clone(),
            config.portfolio(),
        )));

        let risk_engine = RiskEngine::new(
            config.risk_engine().unwrap_or_default(),
            portfolio.borrow().clone_shallow(),
            clock.clone(),
            cache.clone(),
        );
        let risk_engine = Rc::new(RefCell::new(risk_engine));

        let exec_engine = ExecutionEngine::new(clock.clone(), cache.clone(), config.exec_engine());
        let exec_engine = Rc::new(RefCell::new(exec_engine));

        let order_emulator = OrderEmulatorAdapter::new(clock.clone(), cache.clone());

        let data_engine = DataEngine::new(clock.clone(), cache.clone(), config.data_engine());
        let data_engine = Rc::new(RefCell::new(data_engine));

        DataEngine::register_msgbus_handlers(&data_engine);
        RiskEngine::register_msgbus_handlers(&risk_engine);
        ExecutionEngine::register_msgbus_handlers(&exec_engine);
        OrderEmulator::register_msgbus_handlers(&order_emulator.emulator());

        let shutdown_requested = Rc::new(Cell::new(false));
        Self::register_shutdown_handler(config.trader_id(), shutdown_requested.clone());

        let trader = Rc::new(RefCell::new(Trader::new(
            config.trader_id(),
            instance_id,
            config.environment(),
            clock_factory,
            cache.clone(),
            portfolio.clone(),
        )));

        let ts_created = clock.borrow().timestamp_ns();

        Ok(Self {
            name,
            instance_id,
            machine_id,
            event_store,
            config: Box::new(config),
            cache,
            clock,
            portfolio,
            log_guard,
            data_engine,
            risk_engine,
            exec_engine,
            order_emulator,
            trader,
            ts_created,
            ts_started: None,
            ts_shutdown: None,
            shutdown_requested,
            event_store_replay: false,
            state_save_armed: false,
        })
    }

    fn register_shutdown_handler(trader_id: TraderId, shutdown_requested: Rc<Cell<bool>>) {
        let handler = ShareableMessageHandler::from_typed(move |cmd: &ShutdownSystem| {
            if cmd.trader_id != trader_id {
                log::warn!("Received {cmd} not for this trader {trader_id}, ignoring");
                return;
            }

            if shutdown_requested.get() {
                log::debug!("Shutdown already requested, ignoring {cmd}");
                return;
            }

            log::info!("Received {cmd}, requesting shutdown");
            shutdown_requested.set(true);
        });
        let topic = MessagingSwitchboard::shutdown_system_topic();
        msgbus::subscribe_any(topic.into(), handler, None);
    }

    fn determine_machine_id() -> anyhow::Result<String> {
        sysinfo::System::host_name().ok_or_else(|| anyhow::anyhow!("Failed to determine hostname"))
    }

    fn initialize_logging(
        trader_id: TraderId,
        instance_id: UUID4,
        config: LoggerConfig,
    ) -> anyhow::Result<LogGuard> {
        #[cfg(feature = "tracing-bridge")]
        let use_tracing = config.use_tracing;

        let file_config = config.file_config.clone().unwrap_or_default();
        let log_guard = match init_logging(trader_id, instance_id, config, file_config) {
            Ok(guard) => guard,
            Err(e) => {
                // Only recover from SetLoggerError (logger already registered).
                // This is common in tests where multiple kernels are created and
                // the log crate's global logger persists after LogGuard teardown.
                // Any other error (e.g. thread spawn failure) is propagated.
                if e.downcast_ref::<log::SetLoggerError>().is_some() {
                    if let Some(guard) = LogGuard::new() {
                        guard
                    } else {
                        return Err(e.context(
                            "A non-Nautilus logger is already registered; \
                             cannot initialize Nautilus logging",
                        ));
                    }
                } else {
                    return Err(e);
                }
            }
        };

        // Initialize tracing subscriber if enabled (idempotent)
        #[cfg(feature = "tracing-bridge")]
        if use_tracing && !nautilus_common::logging::bridge::tracing_is_initialized() {
            nautilus_common::logging::bridge::init_tracing()?;
        }

        Ok(log_guard)
    }

    fn initialize_cache(
        cache_config: Option<CacheConfig>,
        cache_database: Option<Box<dyn CacheDatabaseAdapter>>,
    ) -> Rc<RefCell<Cache>> {
        let cache_config = cache_config.unwrap_or_default();
        let cache = Cache::new(Some(cache_config), cache_database);

        Rc::new(RefCell::new(cache))
    }

    fn cancel_timers(&self) {
        self.clock.borrow_mut().cancel_timers();
    }

    #[must_use]
    pub fn generate_timestamp_ns(&self) -> UnixNanos {
        self.clock.borrow().timestamp_ns()
    }

    /// Routes a reconnect command to one registered socket endpoint.
    pub fn process_socket_reconnect(&self, command: ReconnectSocket) {
        let outcome = if command.trader_id == self.config.trader_id() {
            let data = self
                .data_engine
                .borrow()
                .socket_reconnect_lookup(&command.client_id, command.endpoint);
            let execution = self
                .exec_engine
                .borrow()
                .socket_reconnect_lookup(&command.client_id, command.endpoint);
            Self::request_socket_reconnect(data, execution)
        } else {
            SocketReconnectDispatchOutcome::InvalidTrader
        };

        if outcome == SocketReconnectDispatchOutcome::Accepted {
            log::info!(
                "Requested socket reconnect for client {}",
                command.client_id
            );
        } else {
            log::warn!(
                "Rejected socket reconnect request for client {}: {outcome:?}",
                command.client_id
            );
        }
    }

    fn request_socket_reconnect(
        data: SocketReconnectLookup,
        execution: SocketReconnectLookup,
    ) -> SocketReconnectDispatchOutcome {
        match (data, execution) {
            (SocketReconnectLookup::Handle(_), SocketReconnectLookup::Handle(_)) => {
                SocketReconnectDispatchOutcome::AmbiguousEndpoint
            }
            (SocketReconnectLookup::Handle(handle), _)
            | (_, SocketReconnectLookup::Handle(handle)) => match handle.request_reconnect() {
                SocketReconnectRequestOutcome::Accepted => SocketReconnectDispatchOutcome::Accepted,
                SocketReconnectRequestOutcome::AlreadyReconnecting => {
                    SocketReconnectDispatchOutcome::AlreadyReconnecting
                }
                SocketReconnectRequestOutcome::Disconnected => {
                    SocketReconnectDispatchOutcome::Disconnected
                }
                SocketReconnectRequestOutcome::Closed => SocketReconnectDispatchOutcome::Closed,
                SocketReconnectRequestOutcome::Unsupported => {
                    SocketReconnectDispatchOutcome::Unsupported
                }
            },
            (SocketReconnectLookup::EndpointNotFound, _)
            | (_, SocketReconnectLookup::EndpointNotFound) => {
                SocketReconnectDispatchOutcome::UnknownEndpoint
            }
            (SocketReconnectLookup::Unsupported, _) | (_, SocketReconnectLookup::Unsupported) => {
                SocketReconnectDispatchOutcome::Unsupported
            }
            (SocketReconnectLookup::ClientNotFound, SocketReconnectLookup::ClientNotFound) => {
                SocketReconnectDispatchOutcome::UnknownClient
            }
        }
    }

    /// Returns the kernel's environment context (Backtest, Sandbox, Live).
    #[must_use]
    pub fn environment(&self) -> Environment {
        self.config.environment()
    }

    /// Returns the kernel's name.
    #[must_use]
    pub const fn name(&self) -> &str {
        self.name.as_str()
    }

    /// Returns the kernel's trader ID.
    #[must_use]
    pub fn trader_id(&self) -> TraderId {
        self.config.trader_id()
    }

    /// Returns the kernel's machine ID.
    #[must_use]
    pub fn machine_id(&self) -> &str {
        &self.machine_id
    }

    /// Returns the kernel's instance ID.
    #[must_use]
    pub const fn instance_id(&self) -> UUID4 {
        self.instance_id
    }

    /// Returns the delay after stopping the node to await residual events before final shutdown.
    #[must_use]
    pub fn delay_post_stop(&self) -> Duration {
        self.config.delay_post_stop()
    }

    /// Returns the UNIX timestamp (ns) when the kernel was created.
    #[must_use]
    pub const fn ts_created(&self) -> UnixNanos {
        self.ts_created
    }

    /// Returns the UNIX timestamp (ns) when the kernel was last started.
    #[must_use]
    pub const fn ts_started(&self) -> Option<UnixNanos> {
        self.ts_started
    }

    /// Returns the UNIX timestamp (ns) when the kernel was last shutdown.
    #[must_use]
    pub const fn ts_shutdown(&self) -> Option<UnixNanos> {
        self.ts_shutdown
    }

    /// Returns `true` if shutdown has been requested.
    ///
    /// Drains pending shutdown-on-error logs before checking the kernel flag.
    #[must_use]
    pub fn is_shutdown_requested(&self) -> bool {
        self.drain_shutdown_on_error_trigger();
        self.shutdown_requested.get()
    }

    /// Clears the shutdown flag.
    ///
    /// Call this before starting a fresh run so a prior `ShutdownSystem`
    /// command does not abort it.
    pub fn reset_shutdown_flag(&self) {
        self.shutdown_requested.set(false);
    }

    /// Returns a shared handle to the shutdown flag for async runtimes
    /// that need to poll it outside the kernel's direct borrow.
    #[must_use]
    pub fn shutdown_flag(&self) -> Rc<Cell<bool>> {
        self.shutdown_requested.clone()
    }

    fn drain_shutdown_on_error_trigger(&self) {
        try_drain_shutdown_on_error_trigger(|trigger| {
            let command = ShutdownSystem::new(
                self.config.trader_id(),
                trigger.component,
                Some(format!(
                    "Error log received from {}: {}",
                    trigger.component, trigger.message
                )),
                UUID4::new(),
                trigger.timestamp,
                None,
            );

            msgbus::try_publish_any(
                MessagingSwitchboard::shutdown_system_topic(),
                command.as_any(),
            )
        });
    }

    /// Returns whether the kernel has been configured to load state.
    #[must_use]
    pub fn load_state(&self) -> bool {
        self.config.load_state()
    }

    /// Returns whether the kernel has been configured to save state.
    #[must_use]
    pub fn save_state(&self) -> bool {
        self.config.save_state()
    }

    /// Returns the kernel's clock.
    #[must_use]
    pub fn clock(&self) -> Rc<RefCell<dyn Clock>> {
        self.clock.clone()
    }

    /// Returns the kernel's cache.
    #[must_use]
    pub fn cache(&self) -> Rc<RefCell<Cache>> {
        self.cache.clone()
    }

    /// Returns the kernel's portfolio.
    #[must_use]
    pub fn portfolio(&self) -> Ref<'_, Portfolio> {
        self.portfolio.borrow()
    }

    /// Returns the kernel's data engine.
    #[must_use]
    pub fn data_engine(&self) -> Ref<'_, DataEngine> {
        self.data_engine.borrow()
    }

    /// Returns the kernel's risk engine.
    #[must_use]
    pub const fn risk_engine(&self) -> &Rc<RefCell<RiskEngine>> {
        &self.risk_engine
    }

    /// Returns the kernel's execution engine.
    #[must_use]
    pub const fn exec_engine(&self) -> &Rc<RefCell<ExecutionEngine>> {
        &self.exec_engine
    }

    /// Returns the kernel's trader (shared reference).
    #[must_use]
    pub fn trader(&self) -> &Rc<RefCell<Trader>> {
        &self.trader
    }

    /// Starts the Nautilus system kernel synchronously (for backtest use).
    pub fn start(&mut self) {
        arm_shutdown_on_error(self.config.shutdown_on_error());
        log::info!("Starting");

        self.event_store_replay = false;

        if let Some(event_store) = self.event_store.as_deref_mut() {
            self.exec_engine.borrow_mut().set_snapshot_anchorer(None);

            let components = Self::collect_registered_components(&self.trader);
            let environment = self.config.environment();
            let event_store_replay_configured = event_store.is_event_store_replay_configured();

            if event_store_replay_configured && !self.config.load_state() {
                log::error!("Event-store replay requires load_state=true");
                return;
            }

            if self.config.load_state()
                && let Err(e) =
                    event_store.restore_parent_cache(self.instance_id, &mut self.cache.borrow_mut())
            {
                log::error!("Failed to restore cache from event-store replay source: {e}");
                return;
            }

            if let Err(e) = event_store.open(self.instance_id, &components, environment) {
                log::error!("Failed to open event-store run: {e}");
                return;
            }

            let anchorer = event_store.snapshot_anchorer();
            self.exec_engine
                .borrow_mut()
                .set_snapshot_anchorer(anchorer);
            self.event_store_replay = event_store_replay_configured;
        }

        if self.event_store_replay {
            log::info!(
                "Event-store replay loaded; skipping engines, clients, trader startup, and live reconciliation",
            );
            self.ts_started = Some(self.clock.borrow().timestamp_ns());
            log::info!("Started");
            return;
        }

        self.start_engines();

        log::info!("Initializing trader");
        if let Err(e) = self.trader.borrow_mut().initialize() {
            log::error!("Error initializing trader: {e:?}");
            return;
        }

        // Execution and data clients are started by their engines via `start_engines` above

        self.ts_started = Some(self.clock.borrow().timestamp_ns());
        log::info!("Started");
    }

    fn collect_registered_components(trader: &Rc<RefCell<Trader>>) -> RegisteredComponents {
        let trader = trader.borrow();
        let mut components = RegisteredComponents::default();
        for actor_id in trader.actor_ids() {
            components
                .actors
                .insert(actor_id.to_string(), String::new());
        }

        for strategy_id in trader.strategy_ids() {
            components
                .strategies
                .insert(strategy_id.to_string(), String::new());
        }

        for algo_id in trader.exec_algorithm_ids() {
            components
                .algorithms
                .insert(algo_id.to_string(), String::new());
        }
        components
    }

    /// Starts the Nautilus system kernel asynchronously.
    #[expect(
        clippy::unused_async,
        reason = "keeps the public async kernel API shape stable"
    )]
    pub async fn start_async(&mut self) {
        self.start();
    }

    /// Starts the trader (strategies and actors).
    ///
    /// This should be called after clients are connected and instruments are cached.
    ///
    /// # Errors
    ///
    /// Returns an error if the trader or a registered component fails to start. A failed partial
    /// start is stopped immediately before the error is returned.
    pub fn start_trader(&mut self) -> anyhow::Result<()> {
        log::info!("Starting trader...");

        let load_state = self.config.load_state();
        let save_state = self.config.save_state();

        if (load_state || save_state) && !self.cache.borrow().has_backing() {
            log::warn!(
                "Cache has no database backing, load_state={load_state} and save_state={save_state} will have no effect"
            );
        }

        if load_state {
            Trader::load_state(&self.trader)
                .map_err(|e| anyhow::anyhow!("Failed to load actor and strategy state: {e:#}"))?;
        }

        self.state_save_armed = save_state;
        self.order_emulator.start();

        if let Err(start_err) = Trader::start_with_component_callbacks(&self.trader) {
            let stop_result = self.stop_trader_after_start_failure();
            self.order_emulator.stop();
            let save_result = self.save_trader_state();

            let mut errors = vec![format!("Failed to start trader: {start_err}")];
            if let Err(e) = stop_result {
                errors.push(format!("failed to stop partial trader start: {e}"));
            }

            if let Err(e) = save_result {
                errors.push(format!("failed to save partial trader state: {e}"));
            }
            anyhow::bail!("{}", errors.join("; "));
        }

        log::info!("Trader started");
        Ok(())
    }

    /// Stops the trader and its registered components.
    ///
    /// This method initiates a graceful shutdown of trading components (strategies, actors)
    /// which may trigger residual events such as order cancellations. The caller should
    /// continue processing events after calling this method to handle these residual events.
    pub fn stop_trader(&mut self) {
        disarm_shutdown_on_error();

        if !self.trader.borrow().is_running() {
            return;
        }

        log::info!("Stopping trader...");

        if let Err(e) = self.trader.borrow_mut().stop() {
            log::error!("Error stopping trader: {e}");
        }
    }

    /// Stops a partially started trader without deferring managed strategy shutdown.
    ///
    /// # Errors
    ///
    /// Returns an error if any active trader component cannot be stopped.
    pub fn stop_trader_after_start_failure(&mut self) -> anyhow::Result<()> {
        disarm_shutdown_on_error();

        if !matches!(
            self.trader.borrow().state(),
            ComponentState::Starting | ComponentState::Running
        ) {
            return Ok(());
        }

        log::info!("Stopping trader immediately...");
        self.trader.borrow_mut().stop_after_start_failure()
    }

    /// Finalizes the kernel shutdown after the grace period.
    ///
    /// This method should be called after the residual events grace period has elapsed
    /// and all remaining events have been processed. It disconnects clients and stops engines.
    ///
    /// # Errors
    ///
    /// Returns an error if actor or strategy state cannot be saved.
    #[allow(unknown_lints)]
    #[expect(
        clippy::unused_async,
        clippy::unused_async_trait_impl,
        reason = "keeps the public async kernel API shape stable"
    )]
    pub async fn finalize_stop(&mut self) -> anyhow::Result<()> {
        disarm_shutdown_on_error();

        // Execution and data clients are stopped by their engines via `stop_engines` below

        let save_result = self.save_trader_state();
        self.portfolio.borrow_mut().finalize_equity_curve();
        self.stop_engines();
        self.cancel_timers();

        let ts_shutdown = self.clock.borrow().timestamp_ns();

        if let Some(event_store) = self.event_store.as_deref_mut() {
            self.exec_engine.borrow_mut().set_snapshot_anchorer(None);
            event_store.seal(ts_shutdown);
        }
        self.ts_shutdown = Some(ts_shutdown);
        log::info!("Stopped");
        save_result
    }

    /// Saves actor and strategy state at most once for the current trader run.
    ///
    /// # Errors
    ///
    /// Returns an error if a component callback or cache persistence operation fails.
    pub fn save_trader_state(&mut self) -> anyhow::Result<()> {
        if !std::mem::take(&mut self.state_save_armed) {
            return Ok(());
        }

        Trader::save_state(&self.trader)
    }

    /// Returns the kernel-managed event-store integration, when one was injected.
    ///
    /// Callers wire an implementation through
    /// [`NautilusKernelBuilder::with_event_store`](crate::builder::NautilusKernelBuilder::with_event_store);
    /// without an injected adapter this returns `None`.
    #[must_use]
    pub fn event_store(&self) -> Option<&dyn KernelEventStore> {
        self.event_store.as_deref()
    }

    /// Returns whether the event-store integration is running an event-store replay start.
    #[must_use]
    pub fn is_event_store_replay(&self) -> bool {
        self.event_store_replay
    }

    /// Returns whether the event-store integration is configured for an event-store replay start.
    #[must_use]
    pub fn is_event_store_replay_configured(&self) -> bool {
        self.event_store
            .as_deref()
            .is_some_and(KernelEventStore::is_event_store_replay_configured)
    }

    /// Resets the Nautilus system kernel to its initial state.
    pub fn reset(&mut self) {
        disarm_shutdown_on_error();
        log::info!("Resetting");

        if let Err(e) = self.trader.borrow_mut().reset() {
            log::error!("Error resetting trader: {e:?}");
        }

        self.data_engine.borrow_mut().reset();
        self.exec_engine.borrow_mut().reset();
        self.risk_engine.borrow_mut().reset();
        self.order_emulator.reset();
        self.portfolio.borrow_mut().reset();

        self.ts_started = None;
        self.ts_shutdown = None;
        self.state_save_armed = false;

        log::info!("Reset");
    }

    /// Disposes of the Nautilus system kernel, releasing resources.
    pub fn dispose(&mut self) {
        disarm_shutdown_on_error();
        log::info!("Disposing");

        let trader_state = self.trader.borrow().state();
        match trader_state {
            ComponentState::Running => self.stop_trader(),
            ComponentState::Starting => {
                if let Err(e) = self.stop_trader_after_start_failure() {
                    log::error!("Error stopping partial trader start during disposal: {e:?}");
                }
            }
            _ => {}
        }

        if let Err(e) = self.save_trader_state() {
            log::error!("Error saving trader state during disposal: {e:?}");
        }

        {
            let mut trader = self.trader.borrow_mut();
            if trader.state() == ComponentState::PreInitialized
                && let Err(e) = trader.initialize()
            {
                log::error!("Error initializing trader for disposal: {e:?}");
            }

            if !trader.is_disposed()
                && let Err(e) = trader.dispose()
            {
                log::error!("Error disposing trader: {e:?}");
            }
        }

        self.stop_engines();
        self.portfolio.borrow_mut().reset();
        self.cancel_timers();

        // BacktestEngine::end() does not call finalize_stop, so dispose() seals the
        // run for non-streaming backtests. finalize_stop (live) consumes the session
        // first; this call is then a no-op. Callers that skip dispose entirely fall
        // back to the event-store implementation's Drop.
        if let Some(event_store) = self.event_store.as_deref_mut() {
            self.exec_engine.borrow_mut().set_snapshot_anchorer(None);
            let ts_dispose = self.clock.borrow().timestamp_ns();
            event_store.seal(ts_dispose);
        }

        self.data_engine.borrow_mut().dispose();
        self.exec_engine.borrow_mut().dispose();
        self.risk_engine.borrow_mut().dispose();
        self.order_emulator.dispose();
        self.cache.borrow_mut().dispose();
        get_message_bus().borrow_mut().dispose();

        log::info!("Disposed");
    }

    /// Starts all engine components.
    fn start_engines(&self) {
        self.data_engine.borrow_mut().start();
        self.exec_engine.borrow_mut().start();
        self.risk_engine.borrow_mut().start();
    }

    /// Stops all engine components.
    fn stop_engines(&self) {
        self.data_engine.borrow_mut().stop();
        self.exec_engine.borrow_mut().stop();
        self.risk_engine.borrow_mut().stop();
        self.order_emulator.stop();
    }

    /// Connects data engine clients.
    ///
    /// Data clients are connected first so that instruments are published
    /// and can be drained into the cache before execution clients connect.
    #[expect(clippy::await_holding_refcell_ref)] // Single-threaded runtime, intentional design
    pub async fn connect_data_clients(&mut self) {
        log::info!("Connecting data clients...");
        self.data_engine.borrow_mut().connect().await;
    }

    /// Connects execution engine clients.
    ///
    /// Must be called after data clients are connected and instrument events
    /// have been drained into the cache, so execution clients can load instruments.
    #[expect(clippy::await_holding_refcell_ref)] // Single-threaded runtime, intentional design
    pub async fn connect_exec_clients(&mut self) {
        log::info!("Connecting execution clients...");
        self.exec_engine.borrow_mut().connect().await;
    }

    /// Disconnects all engine clients.
    ///
    /// # Errors
    ///
    /// Returns an error if any client fails to disconnect.
    #[expect(clippy::await_holding_refcell_ref)] // Single-threaded runtime, intentional design
    pub async fn disconnect_clients(&mut self) -> anyhow::Result<()> {
        log::info!("Disconnecting clients...");
        let mut data_engine = self.data_engine.borrow_mut();
        let mut exec_engine = self.exec_engine.borrow_mut();
        let (data_result, exec_result) =
            futures::join!(data_engine.disconnect(), exec_engine.disconnect());

        match (data_result, exec_result) {
            (Ok(()), Ok(())) => Ok(()),
            (Err(data_err), Ok(())) => Err(data_err),
            (Ok(()), Err(exec_err)) => Err(exec_err),
            (Err(data_err), Err(exec_err)) => anyhow::bail!(
                "Failed to disconnect data clients: {data_err}; failed to disconnect execution \
                 clients: {exec_err}"
            ),
        }
    }

    /// Returns `true` if all engine clients are connected.
    #[must_use]
    pub fn check_engines_connected(&self) -> bool {
        self.data_engine.borrow().check_connected() && self.exec_engine.borrow().check_connected()
    }

    /// Returns `true` if all engine clients are disconnected.
    #[must_use]
    pub fn check_engines_disconnected(&self) -> bool {
        self.data_engine.borrow().check_disconnected()
            && self.exec_engine.borrow().check_disconnected()
    }

    /// Returns connection status for all data clients.
    #[must_use]
    pub fn data_client_connection_status(&self) -> Vec<(ClientId, bool)> {
        self.data_engine.borrow().client_connection_status()
    }

    /// Returns connection status for all execution clients.
    #[must_use]
    pub fn exec_client_connection_status(&self) -> Vec<(ClientId, bool)> {
        self.exec_engine.borrow().client_connection_status()
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum SocketReconnectDispatchOutcome {
    Accepted,
    AlreadyReconnecting,
    Disconnected,
    Closed,
    Unsupported,
    UnknownClient,
    UnknownEndpoint,
    AmbiguousEndpoint,
    InvalidTrader,
}

#[cfg(test)]
mod socket_reconnect_tests {
    use std::sync::{
        Arc,
        atomic::{AtomicBool, AtomicUsize, Ordering},
    };

    use nautilus_common::clients::{SocketReconnectHandle, SocketReconnectRegistry};
    use rstest::rstest;

    use super::*;

    fn stateful_handle(count: Arc<AtomicUsize>) -> SocketReconnectHandle {
        let reconnecting = AtomicBool::new(false);
        SocketReconnectHandle::new(move || {
            if reconnecting.swap(true, Ordering::SeqCst) {
                SocketReconnectRequestOutcome::AlreadyReconnecting
            } else {
                count.fetch_add(1, Ordering::SeqCst);
                SocketReconnectRequestOutcome::Accepted
            }
        })
    }

    #[rstest]
    fn endpoint_request_and_duplicate_leave_sibling_untouched() {
        let registry = SocketReconnectRegistry::default();
        let selected = Arc::new(AtomicUsize::new(0));
        let sibling = Arc::new(AtomicUsize::new(0));
        let _selected_registration = registry.register(
            Ustr::from("market-0"),
            stateful_handle(Arc::clone(&selected)),
        );
        let _sibling_registration = registry.register(
            Ustr::from("market-1"),
            stateful_handle(Arc::clone(&sibling)),
        );
        let selected_lookup = || {
            SocketReconnectLookup::Handle(
                registry
                    .get(Ustr::from("market-0"))
                    .expect("selected endpoint should be registered"),
            )
        };

        assert_eq!(
            NautilusKernel::request_socket_reconnect(
                selected_lookup(),
                SocketReconnectLookup::ClientNotFound,
            ),
            SocketReconnectDispatchOutcome::Accepted,
        );
        assert_eq!(
            NautilusKernel::request_socket_reconnect(
                selected_lookup(),
                SocketReconnectLookup::ClientNotFound,
            ),
            SocketReconnectDispatchOutcome::AlreadyReconnecting,
        );
        assert_eq!(selected.load(Ordering::SeqCst), 1);
        assert_eq!(sibling.load(Ordering::SeqCst), 0);
    }

    #[rstest]
    #[case(
        SocketReconnectLookup::ClientNotFound,
        SocketReconnectLookup::ClientNotFound,
        SocketReconnectDispatchOutcome::UnknownClient
    )]
    #[case(
        SocketReconnectLookup::Unsupported,
        SocketReconnectLookup::ClientNotFound,
        SocketReconnectDispatchOutcome::Unsupported
    )]
    #[case(
        SocketReconnectLookup::EndpointNotFound,
        SocketReconnectLookup::ClientNotFound,
        SocketReconnectDispatchOutcome::UnknownEndpoint
    )]
    fn rejected_lookup_does_not_invoke_an_endpoint(
        #[case] data: SocketReconnectLookup,
        #[case] execution: SocketReconnectLookup,
        #[case] expected: SocketReconnectDispatchOutcome,
    ) {
        assert_eq!(
            NautilusKernel::request_socket_reconnect(data, execution),
            expected,
        );
    }

    #[rstest]
    fn ambiguous_lookup_does_not_invoke_either_endpoint() {
        let data_count = Arc::new(AtomicUsize::new(0));
        let execution_count = Arc::new(AtomicUsize::new(0));

        assert_eq!(
            NautilusKernel::request_socket_reconnect(
                SocketReconnectLookup::Handle(stateful_handle(Arc::clone(&data_count))),
                SocketReconnectLookup::Handle(stateful_handle(Arc::clone(&execution_count))),
            ),
            SocketReconnectDispatchOutcome::AmbiguousEndpoint,
        );
        assert_eq!(data_count.load(Ordering::SeqCst), 0);
        assert_eq!(execution_count.load(Ordering::SeqCst), 0);
    }
}

#[cfg(all(test, feature = "python"))]
mod tests {
    use nautilus_common::messages::system::ShutdownSystem;
    use nautilus_core::UUID4;
    use rstest::*;
    use ustr::Ustr;

    use super::*;
    use crate::builder::NautilusKernelBuilder;

    #[rstest]
    fn test_shutdown_system_sets_kernel_flag() {
        let kernel = NautilusKernelBuilder::default().build().unwrap();
        assert!(!kernel.is_shutdown_requested());

        let command = ShutdownSystem::new(
            kernel.trader_id(),
            Ustr::from("TestComponent"),
            Some("unit test".to_string()),
            UUID4::new(),
            kernel.generate_timestamp_ns(),
            None, // correlation_id
        );

        msgbus::publish_any(
            MessagingSwitchboard::shutdown_system_topic(),
            command.as_any(),
        );
        assert!(kernel.is_shutdown_requested());

        kernel.reset_shutdown_flag();
        assert!(!kernel.is_shutdown_requested());
    }

    #[rstest]
    fn test_shutdown_system_idempotent() {
        let kernel = NautilusKernelBuilder::default().build().unwrap();

        let make_cmd = || {
            ShutdownSystem::new(
                kernel.trader_id(),
                Ustr::from("TestComponent"),
                None,
                UUID4::new(),
                kernel.generate_timestamp_ns(),
                None, // correlation_id
            )
        };

        let topic = MessagingSwitchboard::shutdown_system_topic();
        msgbus::publish_any(topic, make_cmd().as_any());
        assert!(kernel.is_shutdown_requested());

        msgbus::publish_any(topic, make_cmd().as_any());
        assert!(kernel.is_shutdown_requested());

        kernel.reset_shutdown_flag();
        assert!(!kernel.is_shutdown_requested());

        msgbus::publish_any(topic, make_cmd().as_any());
        assert!(kernel.is_shutdown_requested());
    }

    #[rstest]
    fn test_shutdown_system_ignores_other_trader() {
        let kernel = NautilusKernelBuilder::default().build().unwrap();

        let command = ShutdownSystem::new(
            TraderId::from("OTHER-TRADER"),
            Ustr::from("TestComponent"),
            None,
            UUID4::new(),
            kernel.generate_timestamp_ns(),
            None, // correlation_id
        );

        msgbus::publish_any(
            MessagingSwitchboard::shutdown_system_topic(),
            command.as_any(),
        );
        assert!(!kernel.is_shutdown_requested());
    }
}

#[cfg(test)]
mod lifecycle_tests {
    use futures::FutureExt;
    use indexmap::IndexMap;
    use nautilus_common::{
        actor::registry::get_actor_unchecked,
        cache::Cache,
        messages::data::{DataCommand, SubscribeCommand, UnsubscribeCommand},
        msgbus::stubs::{TypedIntoMessageSavingHandler, get_typed_into_message_saving_handler},
    };
    use nautilus_execution::engine::SnapshotAnchorer;
    use nautilus_model::{
        enums::{OrderSide, OrderStatus, OrderType, TriggerType},
        identifiers::{ActorId, ClientOrderId, StrategyId},
        instruments::{
            CryptoPerpetual, Instrument, InstrumentAny, stubs::crypto_perpetual_ethusdt,
        },
        orders::{Order, OrderAny, OrderTestBuilder},
        types::{Price, Quantity},
    };
    use nautilus_testkit::{
        cache::TestCacheDatabaseControl,
        components::{StateActor, StateStrategy},
    };
    use rstest::rstest;
    use ustr::Ustr;

    use super::*;
    use crate::{
        builder::NautilusKernelBuilder,
        event_store::{KernelEventStore, RegisteredComponents},
    };

    #[derive(Debug)]
    struct RecordingEventStore {
        control: TestCacheDatabaseControl,
        opened: bool,
    }

    impl KernelEventStore for RecordingEventStore {
        fn restore_parent_cache(
            &mut self,
            _instance_id: UUID4,
            _cache: &mut Cache,
        ) -> anyhow::Result<()> {
            self.control.record("event_store.restore");
            Ok(())
        }

        fn open(
            &mut self,
            _instance_id: UUID4,
            _components: &RegisteredComponents,
            _environment: Environment,
        ) -> anyhow::Result<()> {
            self.control.record("event_store.open");
            self.opened = true;
            Ok(())
        }

        fn snapshot_anchorer(&self) -> Option<SnapshotAnchorer> {
            None
        }

        fn seal(&mut self, _ts_init: UnixNanos) {
            if self.opened {
                self.control.record("event_store.seal");
                self.opened = false;
            }
        }

        fn run_id(&self) -> Option<&str> {
            None
        }

        fn parent_run_id(&self) -> Option<&str> {
            None
        }

        fn is_halted(&self) -> bool {
            false
        }
    }

    fn state(key: &str, value: &[u8]) -> IndexMap<String, Vec<u8>> {
        IndexMap::from([(key.to_string(), value.to_vec())])
    }

    fn finalize(kernel: &mut NautilusKernel) -> anyhow::Result<()> {
        kernel
            .finalize_stop()
            .now_or_never()
            .expect("kernel finalization must not yield")
    }

    fn add_state_components(
        kernel: &NautilusKernel,
        control: &TestCacheDatabaseControl,
        actor: StateActor,
        strategy: StateStrategy,
    ) {
        kernel.trader.borrow_mut().add_actor(actor).unwrap();
        kernel.trader.borrow_mut().add_strategy(strategy).unwrap();
        control.record("components.registered");
    }

    fn create_stop_market_order(instrument: &CryptoPerpetual, client_order_id: &str) -> OrderAny {
        OrderTestBuilder::new(OrderType::StopMarket)
            .instrument_id(instrument.id())
            .client_order_id(ClientOrderId::from(client_order_id))
            .side(OrderSide::Buy)
            .trigger_price(Price::from("5100.00"))
            .quantity(Quantity::from(1))
            .emulation_trigger(TriggerType::BidAsk)
            .build()
    }

    fn register_data_command_handler(id: &str) -> TypedIntoMessageSavingHandler<DataCommand> {
        let (handler, saving_handler) =
            get_typed_into_message_saving_handler::<DataCommand>(Some(Ustr::from(id)));
        msgbus::register_data_command_endpoint(
            MessagingSwitchboard::data_engine_queue_execute(),
            handler,
        );
        saving_handler
    }

    #[rstest]
    fn test_state_persistence_orders_restore_load_start_stop_save_seal_and_dispose() {
        let actor_id = ActorId::from("STATE-ACTOR");
        let strategy_id = StrategyId::from("STATE-STRATEGY-001");
        let actor_load = state("actor-loaded", b"actor-load-value");
        let strategy_load = state("strategy-loaded", b"strategy-load-value");
        let actor_save = state("actor-saved", b"actor-save-value");
        let strategy_save = state("strategy-saved", b"strategy-save-value");
        let (database, control) = TestCacheDatabaseControl::create();
        control.set_actor_state(actor_id, &actor_load);
        control.set_strategy_state(strategy_id, &strategy_load);

        let event_store_control = control.clone();
        let mut kernel = NautilusKernelBuilder::default()
            .with_cache_database(Box::new(database))
            .with_event_store(move |_instance_id, _clock| {
                Ok(Box::new(RecordingEventStore {
                    control: event_store_control,
                    opened: false,
                }))
            })
            .build()
            .unwrap();

        let actor = StateActor::new(actor_id, control.clone(), actor_save.clone());
        let strategy = StateStrategy::new(strategy_id, control.clone(), strategy_save.clone());
        add_state_components(&kernel, &control, actor, strategy);

        kernel.start();
        kernel.start_trader().unwrap();

        let actor_state = get_actor_unchecked::<StateActor>(&actor_id.inner())
            .state_load()
            .cloned();
        let strategy_state = get_actor_unchecked::<StateStrategy>(&strategy_id.inner())
            .state_load()
            .cloned();
        assert_eq!(actor_state, Some(actor_load));
        assert_eq!(strategy_state, Some(strategy_load));

        kernel.stop_trader();
        kernel.stop_trader();
        finalize(&mut kernel).unwrap();
        finalize(&mut kernel).unwrap();
        kernel.dispose();

        assert_eq!(
            control.events(),
            vec![
                "components.registered",
                "event_store.restore",
                "event_store.open",
                "actor.load:STATE-ACTOR",
                "actor.on_load",
                "strategy.load:STATE-STRATEGY-001",
                "strategy.on_load",
                "actor.on_start",
                "strategy.on_start",
                "actor.on_stop",
                "strategy.on_stop",
                "actor.on_save",
                "actor.update:STATE-ACTOR",
                "strategy.on_save",
                "strategy.update:STATE-STRATEGY-001",
                "event_store.seal",
                "database.close",
            ]
        );
        assert_eq!(control.actor_state(&actor_id), Some(actor_save));
        assert_eq!(control.strategy_state(&strategy_id), Some(strategy_save));
    }

    #[rstest]
    fn test_state_persistence_skips_callbacks_without_cache_backing() {
        let actor_id = ActorId::from("NO-BACKING-ACTOR");
        let strategy_id = StrategyId::from("NO-BACKING-STRATEGY-001");
        let control = TestCacheDatabaseControl::default();
        let mut kernel = NautilusKernelBuilder::default().build().unwrap();
        let actor = StateActor::new(actor_id, control.clone(), state("actor", b"save"));
        let strategy = StateStrategy::new(strategy_id, control.clone(), state("strategy", b"save"));
        add_state_components(&kernel, &control, actor, strategy);

        kernel.start();
        kernel.start_trader().unwrap();
        kernel.stop_trader();
        finalize(&mut kernel).unwrap();
        kernel.dispose();

        assert_eq!(
            control.events(),
            vec![
                "components.registered",
                "actor.on_start",
                "strategy.on_start",
                "actor.on_stop",
                "strategy.on_stop",
            ]
        );
    }

    #[rstest]
    fn test_state_persistence_skips_empty_load_and_persists_empty_save() {
        let actor_id = ActorId::from("EMPTY-STATE-ACTOR");
        let strategy_id = StrategyId::from("EMPTY-STATE-STRATEGY-001");
        let (database, control) = TestCacheDatabaseControl::create();
        let mut kernel = NautilusKernelBuilder::default()
            .with_cache_database(Box::new(database))
            .build()
            .unwrap();
        let actor = StateActor::new(actor_id, control.clone(), IndexMap::new());
        let strategy = StateStrategy::new(strategy_id, control.clone(), IndexMap::new());
        add_state_components(&kernel, &control, actor, strategy);

        kernel.start();
        kernel.start_trader().unwrap();
        kernel.stop_trader();
        finalize(&mut kernel).unwrap();

        assert_eq!(
            control.events(),
            vec![
                "components.registered",
                "actor.load:EMPTY-STATE-ACTOR",
                "strategy.load:EMPTY-STATE-STRATEGY-001",
                "actor.on_start",
                "strategy.on_start",
                "actor.on_stop",
                "strategy.on_stop",
                "actor.on_save",
                "actor.update:EMPTY-STATE-ACTOR",
                "strategy.on_save",
                "strategy.update:EMPTY-STATE-STRATEGY-001",
            ]
        );
        assert_eq!(control.actor_state(&actor_id), Some(IndexMap::new()));
        assert_eq!(control.strategy_state(&strategy_id), Some(IndexMap::new()));
        kernel.dispose();
    }

    #[rstest]
    fn test_state_save_reports_all_callback_errors_and_continues_shutdown() {
        let actor_id = ActorId::from("FAIL-SAVE-ACTOR");
        let strategy_id = StrategyId::from("FAIL-SAVE-STRATEGY-001");
        let (database, control) = TestCacheDatabaseControl::create();
        let event_store_control = control.clone();
        let mut kernel = NautilusKernelBuilder::default()
            .with_cache_database(Box::new(database))
            .with_event_store(move |_instance_id, _clock| {
                Ok(Box::new(RecordingEventStore {
                    control: event_store_control,
                    opened: false,
                }))
            })
            .build()
            .unwrap();
        let actor = StateActor::new(actor_id, control.clone(), IndexMap::new()).with_fail_save();
        let strategy =
            StateStrategy::new(strategy_id, control.clone(), IndexMap::new()).with_fail_save();
        add_state_components(&kernel, &control, actor, strategy);

        kernel.start();
        kernel.start_trader().unwrap();
        kernel.stop_trader();
        let expected_shutdown = kernel.clock.borrow().timestamp_ns();
        let error = finalize(&mut kernel).unwrap_err();
        kernel.dispose();

        assert_eq!(
            error.to_string(),
            "Failed to save component state: actor FAIL-SAVE-ACTOR callback: test actor on_save \
             failure; strategy FAIL-SAVE-STRATEGY-001 callback: test strategy on_save failure"
        );
        assert_eq!(kernel.ts_shutdown, Some(expected_shutdown));
        assert_eq!(
            control.events(),
            vec![
                "components.registered",
                "event_store.restore",
                "event_store.open",
                "actor.load:FAIL-SAVE-ACTOR",
                "strategy.load:FAIL-SAVE-STRATEGY-001",
                "actor.on_start",
                "strategy.on_start",
                "actor.on_stop",
                "strategy.on_stop",
                "actor.on_save",
                "strategy.on_save",
                "event_store.seal",
                "database.close",
            ]
        );
    }

    #[rstest]
    fn test_state_load_callback_failure_prevents_start_and_save() {
        let actor_id = ActorId::from("FAIL-LOAD-ACTOR");
        let strategy_id = StrategyId::from("FAIL-LOAD-STRATEGY-001");
        let (database, control) = TestCacheDatabaseControl::create();
        control.set_actor_state(actor_id, &state("actor", b"load"));
        control.set_strategy_state(strategy_id, &state("strategy", b"load"));
        let mut kernel = NautilusKernelBuilder::default()
            .with_cache_database(Box::new(database))
            .build()
            .unwrap();
        let actor = StateActor::new(actor_id, control.clone(), IndexMap::new()).with_fail_load();
        let strategy = StateStrategy::new(strategy_id, control.clone(), IndexMap::new());
        add_state_components(&kernel, &control, actor, strategy);

        kernel.start();
        let error = kernel.start_trader().unwrap_err();
        kernel.dispose();

        assert_eq!(
            error.to_string(),
            "Failed to load actor and strategy state: Failed to restore actor FAIL-LOAD-ACTOR \
             state: test actor on_load failure"
        );
        assert_eq!(
            control.events(),
            vec![
                "components.registered",
                "actor.load:FAIL-LOAD-ACTOR",
                "actor.on_load",
                "database.close",
            ]
        );
    }

    #[rstest]
    fn test_state_save_reports_all_persistence_errors() {
        let actor_id = ActorId::from("FAIL-UPDATE-ACTOR");
        let strategy_id = StrategyId::from("FAIL-UPDATE-STRATEGY-001");
        let (database, control) = TestCacheDatabaseControl::create();
        control.set_fail_update_actor(true);
        control.set_fail_update_strategy(true);
        let mut kernel = NautilusKernelBuilder::default()
            .with_cache_database(Box::new(database))
            .build()
            .unwrap();
        let actor = StateActor::new(actor_id, control.clone(), state("actor", b"save"));
        let strategy = StateStrategy::new(strategy_id, control.clone(), state("strategy", b"save"));
        add_state_components(&kernel, &control, actor, strategy);

        kernel.start();
        kernel.start_trader().unwrap();
        kernel.stop_trader();
        let error = finalize(&mut kernel).unwrap_err();
        kernel.dispose();

        assert_eq!(
            error.to_string(),
            "Failed to save component state: actor FAIL-UPDATE-ACTOR persistence: test actor \
             update failure; strategy FAIL-UPDATE-STRATEGY-001 persistence: test strategy update \
             failure"
        );
        assert_eq!(
            control.events(),
            vec![
                "components.registered",
                "actor.load:FAIL-UPDATE-ACTOR",
                "strategy.load:FAIL-UPDATE-STRATEGY-001",
                "actor.on_start",
                "strategy.on_start",
                "actor.on_stop",
                "strategy.on_stop",
                "actor.on_save",
                "actor.update:FAIL-UPDATE-ACTOR",
                "strategy.on_save",
                "strategy.update:FAIL-UPDATE-STRATEGY-001",
                "database.close",
            ]
        );
    }

    #[rstest]
    fn test_partial_startup_stops_and_saves_once() {
        let actor_id = ActorId::from("PARTIAL-ACTOR");
        let strategy_id = StrategyId::from("PARTIAL-STRATEGY-001");
        let (database, control) = TestCacheDatabaseControl::create();
        let mut kernel = NautilusKernelBuilder::default()
            .with_cache_database(Box::new(database))
            .build()
            .unwrap();
        let actor = StateActor::new(actor_id, control.clone(), state("actor", b"partial"));
        let strategy =
            StateStrategy::new(strategy_id, control.clone(), state("strategy", b"partial"))
                .with_fail_start();
        add_state_components(&kernel, &control, actor, strategy);

        kernel.start();
        let error = kernel.start_trader().unwrap_err();
        kernel.dispose();

        assert_eq!(
            error.to_string(),
            "Failed to start trader: test strategy on_start failure"
        );
        assert_eq!(
            control.events(),
            vec![
                "components.registered",
                "actor.load:PARTIAL-ACTOR",
                "strategy.load:PARTIAL-STRATEGY-001",
                "actor.on_start",
                "strategy.on_start",
                "actor.on_stop",
                "strategy.on_stop",
                "actor.on_save",
                "actor.update:PARTIAL-ACTOR",
                "strategy.on_save",
                "strategy.update:PARTIAL-STRATEGY-001",
                "database.close",
            ]
        );
        assert_eq!(
            control.actor_state(&actor_id),
            Some(state("actor", b"partial"))
        );
        assert_eq!(
            control.strategy_state(&strategy_id),
            Some(state("strategy", b"partial"))
        );
    }

    #[rstest]
    fn test_forced_dispose_stops_and_saves_once() {
        let actor_id = ActorId::from("FORCED-ACTOR");
        let strategy_id = StrategyId::from("FORCED-STRATEGY-001");
        let (database, control) = TestCacheDatabaseControl::create();
        let mut kernel = NautilusKernelBuilder::default()
            .with_cache_database(Box::new(database))
            .build()
            .unwrap();
        let actor = StateActor::new(actor_id, control.clone(), state("actor", b"forced"));
        let strategy =
            StateStrategy::new(strategy_id, control.clone(), state("strategy", b"forced"));
        add_state_components(&kernel, &control, actor, strategy);

        kernel.start();
        kernel.start_trader().unwrap();
        kernel.dispose();

        assert_eq!(
            control.events(),
            vec![
                "components.registered",
                "actor.load:FORCED-ACTOR",
                "strategy.load:FORCED-STRATEGY-001",
                "actor.on_start",
                "strategy.on_start",
                "actor.on_stop",
                "strategy.on_stop",
                "actor.on_save",
                "actor.update:FORCED-ACTOR",
                "strategy.on_save",
                "strategy.update:FORCED-STRATEGY-001",
                "database.close",
            ]
        );
    }

    #[rstest]
    fn test_start_trader_starts_order_emulator_for_cached_emulated_orders() {
        let mut kernel = NautilusKernelBuilder::default().build().unwrap();
        let data_commands = register_data_command_handler("DataEngine.queue_execute.kernel_start");
        let instrument = crypto_perpetual_ethusdt();
        let instrument_id = instrument.id();
        let first_order = create_stop_market_order(&instrument, "O-KERNEL-001");
        let second_order = create_stop_market_order(&instrument, "O-KERNEL-002");
        let first_client_order_id = first_order.client_order_id();
        let second_client_order_id = second_order.client_order_id();
        kernel
            .cache
            .borrow_mut()
            .add_instrument(InstrumentAny::CryptoPerpetual(instrument))
            .unwrap();
        kernel
            .cache
            .borrow_mut()
            .add_order(first_order, None, None, false)
            .unwrap();
        kernel
            .cache
            .borrow_mut()
            .add_order(second_order, None, None, false)
            .unwrap();

        kernel.start();
        assert!(
            kernel
                .order_emulator
                .get_emulator()
                .get_matching_core(&instrument_id)
                .is_none()
        );
        kernel.start_trader().unwrap();

        let commands = data_commands.get_messages();
        let cache = kernel.cache.borrow();
        let first_status = cache.order(&first_client_order_id).unwrap().status();
        let second_status = cache.order(&second_client_order_id).unwrap().status();
        drop(cache);
        let emulator = kernel.order_emulator.get_emulator();
        assert!(emulator.get_matching_core(&instrument_id).is_some());
        assert_eq!(emulator.subscribed_quotes(), vec![instrument_id]);
        assert_eq!(first_status, OrderStatus::Emulated);
        assert_eq!(second_status, OrderStatus::Emulated);
        assert!(commands.iter().any(|command| matches!(
            command,
            DataCommand::Subscribe(SubscribeCommand::Quotes(command))
                if command.instrument_id == instrument_id
        )));

        data_commands.clear();
        drop(emulator);
        kernel.stop_trader();
        kernel.dispose();

        let commands = data_commands.get_messages();
        let emulator = kernel.order_emulator.get_emulator();
        assert!(emulator.subscribed_quotes().is_empty());
        assert!(emulator.get_matching_core(&instrument_id).is_none());
        assert!(commands.iter().any(|command| matches!(
            command,
            DataCommand::Unsubscribe(UnsubscribeCommand::Quotes(command))
                if command.instrument_id == instrument_id
        )));
    }

    #[rstest]
    fn test_reset_resets_order_emulator_state() {
        let mut kernel = NautilusKernelBuilder::default().build().unwrap();
        let data_commands = register_data_command_handler("DataEngine.queue_execute.kernel_reset");
        let instrument = crypto_perpetual_ethusdt();
        let instrument_id = instrument.id();
        let order = create_stop_market_order(&instrument, "O-KERNEL-RESET-001");
        kernel
            .cache
            .borrow_mut()
            .add_instrument(InstrumentAny::CryptoPerpetual(instrument))
            .unwrap();
        kernel
            .cache
            .borrow_mut()
            .add_order(order, None, None, false)
            .unwrap();

        kernel.start();
        kernel.start_trader().unwrap();
        assert!(
            kernel
                .order_emulator
                .get_emulator()
                .get_matching_core(&instrument_id)
                .is_some()
        );
        kernel.stop_trader();
        data_commands.clear();

        kernel.reset();

        let commands = data_commands.get_messages();
        let emulator = kernel.order_emulator.get_emulator();
        assert!(emulator.subscribed_quotes().is_empty());
        assert!(emulator.get_matching_core(&instrument_id).is_none());
        assert!(commands.iter().any(|command| matches!(
            command,
            DataCommand::Unsubscribe(UnsubscribeCommand::Quotes(command))
                if command.instrument_id == instrument_id
        )));

        drop(emulator);
        kernel.dispose();
    }
}