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
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
//! Transaction handle for Noxu DB.
//!
use crate::durability::{Durability, SyncPolicy};
use crate::environment::ActiveTxns;
use crate::error::{NoxuError, Result};
use crate::transaction_config::TransactionConfig;
use noxu_dbi::{
AckWaitErrorKind, DatabaseId, EnvironmentImpl, SharedReplicaAckCoordinator,
Trigger,
};
use noxu_log::LogManager;
use noxu_sync::Mutex as SyncMutex;
use noxu_txn::Txn;
use std::sync::{Arc, Mutex};
use std::time::Instant;
/// Transaction state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TransactionState {
/// Transaction is open and can be used for operations.
Open,
/// Transaction has been prepared (XA two-phase commit phase 1).
///
/// Locks are still held; the only valid transitions are
/// [`Transaction::resolved_commit_after_prepare`] and
/// [`Transaction::resolved_abort_after_prepare`]. Direct
/// `commit()` / `abort()` are protocol errors.
Prepared,
/// Transaction has been committed.
Committed,
/// Transaction has been aborted.
Aborted,
/// Transaction must be aborted (error occurred).
MustAbort,
}
/// A transaction handle.
///
///
///
/// Transaction handles are used to protect database operations.
/// A single Transaction may be used for operations on multiple databases
/// within the same environment.
///
/// Transaction handles are free-threaded; they may be used concurrently
/// by multiple threads. Once committed or aborted, the handle must not
/// be used for any further operations.
///
/// # Example
/// ```no_run
/// use noxu_db::{Environment, EnvironmentConfig};
/// use std::path::PathBuf;
///
/// let config = EnvironmentConfig::new(PathBuf::from("/tmp/mydb"))
/// .with_allow_create(true)
/// .with_transactional(true);
/// let env = Environment::open(config).unwrap();
/// let txn = env.begin_transaction(None).unwrap();
/// // ... do operations ...
/// txn.commit().unwrap();
/// ```
pub struct Transaction {
/// Transaction ID
id: u64,
/// Current state
state: Mutex<TransactionState>,
/// When this transaction was created
start_time: Instant,
/// Whether this is read-only
read_only: bool,
/// Optional caller-supplied transaction name (JE
/// `Transaction.setName(String)`).
///
/// The name is purely diagnostic: it is included in `Debug`
/// output and structured logs, and may be queried via
/// [`Transaction::get_name`].
/// (transaction-env F22 `setName/getName missing`).
name: Mutex<Option<String>>,
/// Durability override (None = use environment default)
durability: Option<Durability>,
/// Lock timeout in milliseconds (0 = use environment default)
lock_timeout_ms: Mutex<u64>,
/// Transaction timeout in milliseconds (0 = use environment default)
txn_timeout_ms: Mutex<u64>,
/// Write-ahead log manager (None when created outside of an Environment).
log_manager: Option<Arc<LogManager>>,
/// Internal transaction for lock management and write-set tracking.
///
/// When `Some`, write operations on cursors acquire per-record write locks
/// via this `Txn` and record abort before-images. On `abort()`, this `Txn`
/// releases all locks and collects `UndoRecord`s.
///
/// Relationship between `Transaction` (public) and `Txn` (internal)
/// in the: `Transaction.txnImpl` field.
inner_txn: Option<Arc<Mutex<Txn>>>,
/// Reference to the owning `EnvironmentImpl`.
///
/// Used by `abort()` to look up each modified database by ID and apply
/// undo records to the B-tree.
///
/// which is used by `Txn.undoLNs()` to call
/// `EnvironmentImpl.getDatabase(dbId).abort(undoLsn, locker)`.
env_impl: Option<Arc<SyncMutex<EnvironmentImpl>>>,
/// Shared registry of active transactions on the owning
/// `Environment`. When the transaction reaches a terminal state
/// (`commit`, `commit_with_durability`, or `abort`) we prune our
/// entry here so that `Environment::close()` can succeed.
///
/// Resolves F1 of the May 2026 API audit.
active_txns: Option<Arc<ActiveTxns>>,
/// Optional replica-ack coordinator (typically a
/// `noxu_rep::ReplicatedEnvironment`). When `Some`, a successful
/// `commit_with_durability` blocks until the configured
/// `ReplicaAckPolicy` is satisfied or the durability ack-timeout
/// elapses, in which case `NoxuError::InsufficientReplicas` is
/// returned. Closes finding F1 of
/// the 2026 review.
replica_coordinator: Option<SharedReplicaAckCoordinator>,
/// Per-commit timeout for replica acknowledgments. Default 5s; set
/// from the environment's `replica_ack_timeout_ms` (see
/// `EnvironmentConfig::replica_ack_timeout_ms`) when the
/// coordinator is installed.
replica_ack_timeout: std::time::Duration,
/// Callbacks to run when this transaction aborts.
///
/// C-4 / JE 1-I: used to undo transactional database registrations
/// when `open_database(Some(txn), ...)` is followed by `txn.abort()`.
/// Each callback is a `Box<dyn FnOnce() + Send>` so it can capture
/// shared state without requiring the caller to hold locks.
abort_callbacks: Mutex<Vec<Box<dyn FnOnce() + Send>>>,
/// Callbacks to run when this transaction commits.
///
/// C-4 / JE 1-I: used to finalise transactional database registrations
/// by moving the database name from `pending_names` to `name_map`.
commit_callbacks: Mutex<Vec<Box<dyn FnOnce() + Send>>>,
/// Databases modified under this transaction that carry user triggers,
/// keyed by database id so each is recorded at most once (DB-TRIG).
///
/// JE `Txn.triggerDbs` (a `Set<DatabaseImpl>`) populated by
/// `TriggerManager.runTriggers` -> `noteTriggerDb`. On `commit` / `abort`
/// every recorded database's triggers fire (`runCommitTriggers` /
/// `runAbortTriggers`), in registration order.
trigger_dbs: Mutex<Vec<(u64, Vec<Arc<dyn Trigger>>)>>,
}
impl Transaction {
/// Create a new unconnected transaction handle.
///
/// **Internal** — `pub(crate)` for the no-WAL / in-memory environment
/// path inside `Environment::begin_transaction`. Such a handle is not
/// wired to a WAL when constructed alone, so it is deliberately not part
/// of the public surface; downstream callers obtain a fully operational
/// handle via
/// [`Environment::begin_transaction`][crate::environment::Environment::begin_transaction].
///
/// # Arguments
/// * `id` - Unique transaction ID
/// * `config` - Transaction configuration
pub(crate) fn new(id: u64, config: TransactionConfig) -> Self {
observe_gauge_inc!("noxu_db_active_transactions");
Self {
id,
state: Mutex::new(TransactionState::Open),
start_time: Instant::now(),
read_only: config.read_only,
name: Mutex::new(None),
durability: Some(config.durability),
lock_timeout_ms: Mutex::new(config.lock_timeout_ms),
txn_timeout_ms: Mutex::new(config.txn_timeout_ms),
log_manager: None,
inner_txn: None,
env_impl: None,
active_txns: None,
replica_coordinator: None,
replica_ack_timeout: std::time::Duration::from_secs(5),
abort_callbacks: Mutex::new(Vec::new()),
commit_callbacks: Mutex::new(Vec::new()),
trigger_dbs: Mutex::new(Vec::new()),
}
}
/// Create a new transaction backed by a real WAL.
///
/// Called by `Environment::begin_transaction()` to wire the transaction to
/// the environment's log manager so that commit/abort write WAL entries.
///
/// **Internal** — `pub(crate)` for cross-module wiring within the
/// Noxu DB engine; not part of the public surface.
/// `LogManager` is not re-exported by `noxu-db`.
pub(crate) fn with_log_manager(
id: u64,
config: TransactionConfig,
log_manager: Arc<LogManager>,
) -> Self {
observe_gauge_inc!("noxu_db_active_transactions");
Self {
id,
state: Mutex::new(TransactionState::Open),
start_time: Instant::now(),
read_only: config.read_only,
name: Mutex::new(None),
durability: Some(config.durability),
lock_timeout_ms: Mutex::new(config.lock_timeout_ms),
txn_timeout_ms: Mutex::new(config.txn_timeout_ms),
log_manager: Some(log_manager),
inner_txn: None,
env_impl: None,
active_txns: None,
replica_coordinator: None,
replica_ack_timeout: std::time::Duration::from_secs(5),
abort_callbacks: Mutex::new(Vec::new()),
commit_callbacks: Mutex::new(Vec::new()),
trigger_dbs: Mutex::new(Vec::new()),
}
}
/// Wires the `EnvironmentImpl` so that `abort()` can apply undo records.
///
/// Called by `Environment::begin_transaction()` after constructing the
/// `Transaction`.
///
/// **Internal** — `EnvironmentImpl` is not re-exported by `noxu-db`.
pub(crate) fn with_env_impl(
mut self,
env_impl: Arc<SyncMutex<EnvironmentImpl>>,
) -> Self {
self.env_impl = Some(env_impl);
self
}
/// Sets the inner `Txn` for lock management and write-set tracking.
///
/// Called by `Environment::begin_transaction()` to wire the transaction to
/// the environment's `TxnManager` / `LockManager`.
///
/// **Internal** — `noxu_txn::Txn` is not re-exported by `noxu-db`.
pub(crate) fn with_inner_txn(mut self, txn: Arc<Mutex<Txn>>) -> Self {
self.inner_txn = Some(txn);
self
}
/// Removes the inner `Txn` from the environment's `TxnManager` (its
/// `all_txns` map and the lock manager's locker-label map) — the
/// counterpart to `TxnManager::begin_txn`, which the explicit-transaction
/// commit/abort paths previously never called (review F-5).
///
/// Without this, `TxnManager::all_txns` and the locker-label map grow
/// without bound for the process lifetime, `n_active_txns()` reports a
/// monotonically increasing (wrong) count, and `n_commits`/`n_aborts`
/// undercount. The inner `Txn`'s locker id (a separate id space from
/// `Transaction::id`) is the `all_txns` key, so we use it here.
///
/// Lock discipline: the inner-txn lock is read in a tight scope and
/// released before the (separate) environment lock is taken, and both
/// commit/abort paths have already released any env lock by this point.
fn unregister_inner_txn(&self, committed: bool) {
let Some(inner) = self.inner_txn.as_ref() else {
return;
};
let g = inner.lock().unwrap();
let inner_id = g.id_as_locker();
// TXN-2: mirror JE TxnManager.unRegisterTxn nActiveSerializable path.
// Read the isolation level before releasing the txn from the manager.
let was_serializable = g.is_serializable();
drop(g);
if let Some(env) = self.env_impl.as_ref() {
let guard = env.lock();
let tm = guard.get_txn_manager();
if committed {
tm.commit_txn(inner_id);
} else {
tm.abort_txn(inner_id);
}
// Decrement the serializable counter exactly once, after the
// all_txns entry is removed, so n_active_serializable ≤
// n_active at all times. Matches JE TxnManager.unRegisterTxn
// `nActiveSerializable.decrementAndGet()` ordering.
if was_serializable {
tm.unregister_serializable();
}
}
}
/// Wires the shared active-transactions registry so that `commit` /
/// `abort` can prune their own entry on completion.
///
/// Resolves F1 of the May 2026 API audit.
pub(crate) fn with_active_txns(
mut self,
registry: Arc<ActiveTxns>,
) -> Self {
self.active_txns = Some(registry);
self
}
/// Wires the replica-ack coordinator from the owning `Environment`.
///
/// When set, a successful `commit_with_durability` blocks until the
/// configured `ReplicaAckPolicy` is satisfied or `replica_ack_timeout`
/// elapses, in which case `NoxuError::InsufficientReplicas` is
/// returned.
///
/// Closes finding F1 of the 2026 review.
pub(crate) fn with_replica_coordinator(
mut self,
coord: SharedReplicaAckCoordinator,
ack_timeout: std::time::Duration,
) -> Self {
self.replica_coordinator = Some(coord);
self.replica_ack_timeout = ack_timeout;
self
}
/// Returns a clone of the `Arc<Mutex<Txn>>` inner transaction, if any.
///
/// Used by `Database::make_cursor_for_txn()` and the XA layer to wire a
/// cursor/branch to the same `Txn` so that write operations lock via the
/// transaction.
///
/// **Internal** — `#[doc(hidden)]` cross-crate wiring point.
/// `noxu_txn::Txn` is not re-exported by `noxu-db`, so the return type is
/// effectively un-nameable by downstream users; this is not part of the
/// stable surface.
#[doc(hidden)]
pub fn get_inner_txn(&self) -> Option<Arc<Mutex<Txn>>> {
self.inner_txn.clone()
}
/// Register a callback to run when this transaction aborts.
///
/// Used by `Environment::open_database()` to roll back a transactional
/// database creation if the owning transaction is aborted (C-4 / JE 1-I).
/// The callback is invoked from within `abort()`, after WAL writes but
/// before the outer state is marked `Aborted`.
pub fn register_abort_callback<F>(&self, f: F)
where
F: FnOnce() + Send + 'static,
{
self.abort_callbacks.lock().unwrap().push(Box::new(f));
}
/// Register a callback to run when this transaction commits.
///
/// Used by `Environment::open_database()` to finalise a transactional
/// database creation when the owning transaction commits (C-4 / JE 1-I).
/// The callback is invoked from within `commit_with_durability()`, after
/// the WAL entry is written and locks are released.
pub fn register_commit_callback<F>(&self, f: F)
where
F: FnOnce() + Send + 'static,
{
self.commit_callbacks.lock().unwrap().push(Box::new(f));
}
/// Record that a triggered database was modified under this transaction
/// (DB-TRIG).
///
/// Idempotent per database id: the first write to a given database under
/// this transaction records its triggers; subsequent writes are no-ops.
/// On `commit` / `abort` every recorded database's triggers fire in
/// registration order.
///
/// JE `Txn.noteTriggerDb` (a `Set<DatabaseImpl>` populated from
/// `TriggerManager.runTriggers`).
pub(crate) fn note_trigger_db(
&self,
db_id: u64,
triggers: &[Arc<dyn Trigger>],
) {
if triggers.is_empty() {
return;
}
let mut dbs = self.trigger_dbs.lock().unwrap();
if dbs.iter().any(|(id, _)| *id == db_id) {
return;
}
dbs.push((db_id, triggers.to_vec()));
}
/// Fire `TransactionTrigger.commit` for every recorded triggered database,
/// in registration order (DB-TRIG). JE
/// `TriggerManager.runCommitTriggers`.
fn run_commit_triggers(&self) {
let dbs = std::mem::take(&mut *self.trigger_dbs.lock().unwrap());
for (_db_id, triggers) in dbs {
for trigger in triggers {
trigger.commit(self.id);
}
}
}
/// Fire `TransactionTrigger.abort` for every recorded triggered database,
/// in registration order (DB-TRIG). JE
/// `TriggerManager.runAbortTriggers`.
fn run_abort_triggers(&self) {
let dbs = std::mem::take(&mut *self.trigger_dbs.lock().unwrap());
for (_db_id, triggers) in dbs {
for trigger in triggers {
trigger.abort(self.id);
}
}
}
/// Commit the transaction.
///
/// All operations performed under this transaction are made durable
/// and visible to other transactions.
///
/// # Errors
/// Returns an error if:
/// - The transaction is not in `Open` state.
/// - Writing the `TxnCommit` WAL entry fails (`EnvironmentFailure`
/// with reason `LogWrite`, propagated from `write_txn_end`).
/// - The inner-`Txn` commit fails after the WAL entry has been
/// fsynced (e.g. open cursors held against this transaction, or
/// inner-state inconsistency surfaced by `check_state`). When
/// this happens the transaction is still durably committed; the
/// error is propagated so the caller can react to the leak.
pub fn commit(&self) -> Result<()> {
observe_span!("txn_commit", txn_id = self.id);
let _obs_timer = observe_timer_start!();
observe_counter!("noxu_db_operations_total", "op" => "commit");
let durability = self.durability.unwrap_or(Durability::COMMIT_SYNC);
let result = self.commit_with_durability(durability);
observe_timer_record!(_obs_timer, "noxu_db_operation_duration_seconds", "op" => "commit");
result
}
/// Commit the transaction with specific durability.
///
/// # Arguments
/// * `durability` - Durability settings for this commit
///
/// # Errors
/// Returns an error if:
/// - The transaction is not in `Open` state.
/// - Writing the `TxnCommit` WAL entry fails (`EnvironmentFailure`
/// with reason `LogWrite`, propagated from `write_txn_end`).
/// - The inner-`Txn` commit fails after the WAL entry has been
/// fsynced (e.g. open cursors held against this transaction, or
/// inner-state inconsistency surfaced by `check_state`). When
/// this happens the transaction is still durably committed; the
/// error is propagated so the caller can react to the leak.
pub fn commit_with_durability(&self, durability: Durability) -> Result<()> {
self.check_open()?;
// Did this txn actually append any LN to the WAL? Computed once so
// the three write-path steps below (WAL frame, replica-ack wait,
// cleaner throttle) all short-circuit for a read-only-in-practice
// txn without re-locking the inner Txn.
let logged_data = self.has_logged_data();
// Write TxnCommit to the WAL before marking committed.
// Durability controls whether we fsync, flush, or just buffer.
//
// Gate on `has_logged_data()` (did this txn append any LN?), not the
// static `read_only` config flag. A default (write-capable) txn that
// only read logged nothing, so it needs no TxnCommit frame and —
// crucially — no commit fsync. JE: `Txn.commit` writes the commit
// entry only when `hasLoggedEntries()`. (read-commit-contention
// audit, 2026-07: gating on `read_only` forced every explicit read
// txn through the log-write latch + fsync group-commit at SYNC.)
if !self.read_only
&& logged_data
&& let Some(lm) = &self.log_manager
{
let (fsync, flush) = match durability.local_sync {
SyncPolicy::Sync => (true, true),
SyncPolicy::WriteNoSync => (false, true),
SyncPolicy::NoSync => (false, false),
};
self.write_txn_end(lm, true, fsync, flush)?;
}
// F1 (rep audit): wait for replica acknowledgments before returning
// success. This wait happens AFTER the local WAL is durable but
// BEFORE the inner txn releases its locks, mirroring BDB-JE
// `Txn.preLogCommitHook` / `commit(Durability)` ordering: the
// master is durable locally and replicas are notified, but the
// commit only "returns" once `replica_ack` is satisfied.
//
// If no coordinator is wired (non-replicated env) or the policy
// is `None`, the wait is skipped. Read-only commits never need
// replica acks. Captured failure is propagated at the end of
// the function after lock release so the caller observes a
// typed `NoxuError::InsufficientReplicas` rather than a state
// leak.
let ack_err: Option<NoxuError> = if !self.read_only
&& logged_data
&& durability.replica_ack
!= crate::durability::ReplicaAckPolicy::None
&& let Some(coord) = &self.replica_coordinator
{
match coord.await_replica_acks(
durability.replica_ack.as_kind(),
self.replica_ack_timeout,
) {
Ok(_received) => None,
Err(e) => match e.kind {
AckWaitErrorKind::NotMaster => {
Some(NoxuError::ReplicaWrite)
}
AckWaitErrorKind::Timeout | AckWaitErrorKind::Shutdown => {
Some(NoxuError::InsufficientReplicas {
required: e.needed,
available: e.received,
})
}
},
}
} else {
None
};
// Apply cleaner write-path backpressure: sleep briefly ONLY when the
// cleaner has fallen behind (a real backlog of files queued for
// cleaning), so writers slow to let cleaning catch up and the log does
// not grow unboundedly. When the cleaner is keeping up (the common
// case) this returns None and no sleep occurs. JE-faithful gating on
// the cleaner falling behind (EnvironmentImpl.checkDiskLimitViolation),
// NOT on a raw write rate.
// Extract the throttle Arc while holding the env lock, then
// drop the lock BEFORE sleeping to avoid blocking other threads.
if !self.read_only
&& logged_data
&& let Some(ref env) = self.env_impl
{
let throttle = env.lock().get_cleaner_throttle();
if let Some(delay) =
throttle.and_then(|t| t.should_throttle_writer())
{
std::thread::sleep(delay);
}
}
// Release per-record locks held by the inner Txn.
// The inner Txn has no log_manager so it won't write duplicate WAL records.
//
// At this point the commit is *durable* on disk: `write_txn_end`
// above has already fsynced the TxnCommit WAL entry, and recovery
// will replay this commit on the next environment open. The inner
// commit only releases `lock_manager` locks and flips the inner
// state Open → Committed; the data path mutations were applied to
// the in-memory tree at `db.put()` time.
//
// Possible failure modes for `inner.commit()`:
// * `has_open_cursors`: a user bug — a cursor on this transaction
// was not closed before `commit()`. The data is still
// durably committed; the cursor's lifetime contract is
// violated. Surfacing this lets the caller find the leak.
// * `check_state` (state != Open): the inner txn was flipped to
// `MustAbort` by the deadlock detector after our WAL fsync,
// or somehow advanced to `Committed`/`Aborted` already. Both
// indicate a state-machine inconsistency that needs to be
// visible.
//
// Either way, we mark the outer state `Committed` first because
// the durable record says so — returning early before that would
// leave the outer in `Open`, and a retried `commit()` would
// append a *second* `TxnCommit` record to the WAL. We then
// propagate the inner error so the caller can react.
//
// The inner Txn's `commit_with_durability` now drains all
// read and write locks on every error return path, so a
// failed inner.commit() no longer leaks lock-manager entries
// until environment close. See `Txn::commit_with_durability`
// and `Txn::release_all_locks` in noxu-txn for the
// implementation of this guarantee.
let inner_err = if let Some(inner) = &self.inner_txn {
match inner.lock().unwrap().commit() {
Ok(_) => None,
Err(e) => {
log::error!(
"Transaction::commit_with_durability: inner txn \
commit failed after WAL fsync (txn is durably \
committed; lock_manager locks may be leaked): {e}"
);
Some(e)
}
}
} else {
None
};
let mut state = self.state.lock().unwrap();
*state = TransactionState::Committed;
drop(state);
// C-4 / JE 1-I: run commit callbacks (transactional database
// registration finalisation).
let callbacks: Vec<Box<dyn FnOnce() + Send>> =
std::mem::take(&mut *self.commit_callbacks.lock().unwrap());
for cb in callbacks {
cb();
}
// DB-TRIG: fire TransactionTrigger.commit for every database modified
// under this transaction, in registration order. JE
// `TriggerManager.runCommitTriggers(txn)`.
self.run_commit_triggers();
// Prune our entry from the environment's active-txns registry so
// that `Environment::close()` can succeed (F1). Decrement the
// active-transactions gauge here (rather than in `commit()`) so
// that callers of `commit_with_durability` directly are also
// accounted for (resolves F9 as a side effect).
if let Some(registry) = &self.active_txns {
registry.mark_complete(self.id);
}
// F-5: counterpart to begin_txn — remove the inner Txn from
// TxnManager (all_txns + locker label) to avoid an unbounded leak.
self.unregister_inner_txn(true);
observe_gauge_dec!("noxu_db_active_transactions");
if let Some(e) = inner_err {
return Err(NoxuError::from(e));
}
// F1: surface any replica-ack failure last, after the local
// commit has fully released locks. The local commit is durable;
// returning this error tells the caller the durability policy
// was not satisfied so they can retry or rollback at the
// application layer.
if let Some(e) = ack_err {
return Err(e);
}
Ok(())
}
/// Abort the transaction.
///
/// All operations performed under this transaction are rolled back.
///
/// # Errors
/// Returns an error if:
/// - The transaction is already committed or aborted.
/// - Writing the `TxnAbort` WAL entry fails (`EnvironmentFailure`
/// with reason `LogWrite`, propagated from `write_txn_end`).
/// This path is taken only when the transaction is not read-only
/// and a `LogManager` is configured on the environment.
pub fn abort(&self) -> Result<()> {
observe_span!("txn_abort", txn_id = self.id);
observe_counter!("noxu_db_operations_total", "op" => "abort");
{
// Poison-safe: abort is reachable from Drop and a prior panic
// on this txn may have poisoned its own locks; recover and abort.
let state = self.state.lock().unwrap_or_else(|p| p.into_inner());
match *state {
TransactionState::Committed => {
return Err(NoxuError::OperationNotAllowed(
"Cannot abort a committed transaction".to_string(),
));
}
TransactionState::Aborted => {
return Err(NoxuError::OperationNotAllowed(
"Transaction already aborted".to_string(),
));
}
TransactionState::Open | TransactionState::MustAbort => {}
TransactionState::Prepared => {
return Err(NoxuError::OperationNotAllowed(
"Cannot abort a prepared transaction directly; \
use xa_rollback / resolved_abort_after_prepare"
.to_string(),
));
}
}
}
// Write TxnAbort to WAL before marking aborted (no fsync needed).
// Skipped when the txn logged nothing (read-only-in-practice): there
// is no undo chain for recovery to follow, so a TxnAbort frame is
// pointless. JE writes an abort entry only for txns with logged
// entries. (read-commit-contention audit, 2026-07.)
if !self.read_only
&& self.has_logged_data()
&& let Some(lm) = &self.log_manager
{
self.write_txn_end(lm, false, false, false)?;
}
// Apply undo records to the B-tree to restore before-images, then
// release write locks. The two steps must happen in this order: while
// write locks are still held, no reader can observe the in-flight value;
// once release_all_locks() is called, blocked readers unblock and must
// already see the restored before-image.
if let Some(inner) = &self.inner_txn {
// Phase 1: collect undo records without releasing write locks.
let mut undo_records = inner
.lock()
.unwrap_or_else(|p| p.into_inner())
.abort_collect_undo()
.unwrap_or_default();
// Apply undo in reverse-operation order (newest LSN first).
//
// The in-memory write-lock map is a HashMap (no order), so the
// raw `undo_records` order is non-deterministic. When the same
// key is touched multiple times in one txn (e.g. delete →
// re-insert in SR9465), the undo records carry conflicting
// intents:
// - DELETE undo (abort_data=orig) : restore the slot
// - INSERT undo (abort_known_deleted=t) : remove the slot
// Applying these in arbitrary order can leave the tree in either
// "correct" or "slot deleted" depending on iteration luck.
//
// The recovery path's backward log scan already applies undo
// newest-first; we mirror that here so the in-memory abort and
// crash-recovery undo are observationally identical. Sorting by
// `current_lsn` descending is sufficient because LSNs are
// monotonic per-WAL-write.
undo_records.sort_by_key(|r| std::cmp::Reverse(r.current_lsn));
// Phase 2: apply undo to the B-tree (write locks still held).
//
// H-1 (the 2026 review F-2.2): acquire env lock only for
// the fast database-handle lookup, then drop it immediately.
// This prevents the entire abort undo loop from serialising all
// concurrent readers/writers against the EnvironmentImpl mutex.
//
// Algorithm:
// a) Collect unique database IDs referenced by the undo set.
// b) For each ID, briefly lock env, clone the Arc<RwLock<DatabaseImpl>>,
// and immediately release the env lock.
// c) Apply all undo records without ever holding the env lock.
//
// Safety: the database Arcs are ref-counted; even if a concurrent
// `env.remove_database()` call drops the EnvironmentImpl's own Arc,
// our cloned Arc keeps the DatabaseImpl alive for the duration of
// the undo loop.
if let Some(env) = &self.env_impl {
// Step (a+b): collect database handles with minimal lock hold time.
use std::collections::HashMap;
let mut db_handles: HashMap<
i64,
// DST: matches `get_database_by_id`'s seam-typed return
// (`noxu_util::dst_sync_pl::RwLock` == `noxu_sync::RwLock`
// under the default cfg).
Arc<noxu_util::dst_sync_pl::RwLock<noxu_dbi::DatabaseImpl>>,
> = HashMap::new();
for undo in &undo_records {
let db_id_raw = undo.database_id as i64;
if db_handles.contains_key(&db_id_raw) {
continue;
}
// Brief env lock: lookup only.
let guard = env.lock();
if let Some(arc) =
guard.get_database_by_id(DatabaseId::new(db_id_raw))
{
db_handles.insert(db_id_raw, arc);
}
// env lock released here — drop(guard) implicit at end of block
}
// Step (c): apply undo records without holding env lock.
for undo in undo_records {
let Some(abort_key) = undo.abort_key else { continue };
let db_id_raw = undo.database_id as i64;
let Some(db_arc) = db_handles.get(&db_id_raw) else {
continue;
};
let db_guard = db_arc.read();
if let Some(tree) = db_guard.get_real_tree() {
if undo.abort_known_deleted {
if tree.delete(&abort_key) {
db_guard.decrement_entry_count();
}
} else if let Some(abort_data) = undo.abort_data {
let lsn = noxu_util::Lsn::from_u64(undo.abort_lsn);
if let Ok(is_new) =
tree.insert(abort_key, abort_data, lsn)
&& is_new
{
// Restoring a slot that the aborted txn had
// deleted: the in-memory delete already
// decremented the counter, so the restore
// must re-bump it.
db_guard.increment_entry_count();
}
}
}
}
}
// Phase 3: release write locks — blocked readers now unblock and
// see the restored before-image.
inner.lock().unwrap_or_else(|p| p.into_inner()).release_all_locks();
}
let mut state = self.state.lock().unwrap_or_else(|p| p.into_inner());
*state = TransactionState::Aborted;
drop(state);
// C-4 / JE 1-I: run abort callbacks (transactional database
// registration rollback).
let callbacks: Vec<Box<dyn FnOnce() + Send>> = std::mem::take(
&mut *self
.abort_callbacks
.lock()
.unwrap_or_else(|p| p.into_inner()),
);
for cb in callbacks {
cb();
}
// DB-TRIG: fire TransactionTrigger.abort for every database modified
// under this transaction, in registration order. The data-change
// undo above has already restored the before-images, so an abort
// trigger observes the rolled-back state. JE
// `TriggerManager.runAbortTriggers(txn)`.
self.run_abort_triggers();
// Prune our entry from the environment's active-txns registry so
// that `Environment::close()` can succeed (F1).
if let Some(registry) = &self.active_txns {
registry.mark_complete(self.id);
}
// F-5: counterpart to begin_txn — remove the inner Txn from
// TxnManager (all_txns + locker label) to avoid an unbounded leak.
self.unregister_inner_txn(false);
observe_gauge_dec!("noxu_db_active_transactions");
Ok(())
}
/// Prepares the transaction for the second phase of XA two-phase
/// commit.
///
/// Implements the crash-durable contract introduced in wave 3-2:
///
/// 1. Writes a `TxnPrepare` WAL frame containing the txn id, the
/// first / last LSN logged by this transaction, and the supplied
/// XID components (format_id, gtrid, bqual). The frame is
/// fsynced before this method returns, so a crash immediately
/// afterwards still allows recovery to resurrect the prepared
/// state.
/// 2. Marks the inner `Txn` as PREPARED — direct `commit()` and
/// `abort()` calls now return `OperationNotAllowed`; only
/// `resolved_commit_after_prepare` and
/// `resolved_abort_after_prepare` may finalise the transaction.
/// 3. Locks are RETAINED — prepared transactions hold every lock
/// until xa_commit / xa_rollback so concurrent readers cannot
/// observe in-flight state.
/// 4. The persistent prepared-log entry (the `noxu-xa::PreparedLog`
/// XID -> timestamp record) is the responsibility of the XA
/// layer and is written *after* this method returns. The WAL
/// `TxnPrepare` frame is the source of truth for crash
/// durability; the prepared-log database is a convenience for
/// operators inspecting in-doubt XIDs without scanning the WAL.
///
/// Returns `Ok(())` on success. Read-only transactions (no LN
/// frames written) still take a code path here so the inner Txn
/// flips to PREPARED, but no `TxnPrepare` frame is emitted — the
/// XA layer should take its `PrepareResult::ReadOnly` shortcut
/// rather than calling this method on read-only branches.
///
/// # Errors
/// * `OperationNotAllowed` if the transaction is not Open.
/// * `EnvironmentFailure { reason: LogWrite }` if the WAL write or
/// fsync fails.
pub fn prepare(
&self,
xid_format_id: i32,
xid_gtrid: &[u8],
xid_bqual: &[u8],
) -> Result<()> {
self.check_open()?;
// Capture first / last LSN from the inner Txn so the recovery
// code can chain them. For read-only branches both are
// NULL_LSN, in which case we skip writing the frame entirely
// (the prepared XID will appear in the persistent prepared-log
// database but recovery has nothing to do for it).
let (first_lsn, last_lsn) = match &self.inner_txn {
Some(inner) => {
let g = inner.lock().unwrap();
(g.first_lsn(), g.last_lsn())
}
None => {
(noxu_util::NULL_LSN.as_u64(), noxu_util::NULL_LSN.as_u64())
}
};
// Write the durable TxnPrepare frame. Skipped for read-only
// txns (no inner Txn or no LN frames) to avoid recording an
// empty prepare that recovery would have nothing to do with.
if !self.read_only
&& let Some(lm) = &self.log_manager
&& first_lsn != noxu_util::NULL_LSN.as_u64()
{
self.write_txn_prepare(
lm,
first_lsn,
last_lsn,
xid_format_id,
xid_gtrid,
xid_bqual,
)?;
}
// Flip the inner Txn into PREPARED state so direct
// `inner.commit()` / `inner.abort()` are protocol errors.
// The inner Txn has no `log_manager` of its own (the outer
// Transaction owns the only LM reference), so its `prepare`
// call is a pure flag-flip; it does not write a duplicate
// TxnPrepare frame.
if let Some(inner) = &self.inner_txn {
inner
.lock()
.unwrap()
.prepare(xid_format_id, xid_gtrid.to_vec(), xid_bqual.to_vec())
.map_err(NoxuError::from)?;
}
let mut state = self.state.lock().unwrap();
*state = TransactionState::Prepared;
Ok(())
}
/// Resolves a prepared transaction with a commit.
///
/// Used by the XA `xa_commit` path. Bypasses the
/// `TransactionState::Prepared` guard in `commit_with_durability`
/// because the prepare already established the commit decision.
///
/// Steps:
/// 1. Verifies the txn is Prepared.
/// 2. Writes a `TxnCommit` WAL frame (mirrors `commit()`).
/// 3. Releases the inner Txn's locks via `resolved_commit_after_prepare`.
/// 4. Transitions state to Committed and prunes from the active-txns
/// registry.
pub fn resolved_commit_after_prepare(&self) -> Result<()> {
{
let state = self.state.lock().unwrap();
if !matches!(*state, TransactionState::Prepared) {
return Err(NoxuError::OperationNotAllowed(format!(
"resolved_commit_after_prepare: expected Prepared, got {:?}",
*state
)));
}
}
// Write the TxnCommit frame.
//
// NOT gated on `has_logged_data()`: a prepared txn already wrote a
// durable TxnPrepare frame, so recovery WILL resurrect it unless we
// write the resolving TxnCommit. (The inner Txn's `prepare()`
// resets its `last_lsn`, so `has_logged_entries()` reads false here
// even though the txn did log data — the read-only fast path must
// never apply to a prepared branch.)
if !self.read_only
&& let Some(lm) = &self.log_manager
{
self.write_txn_end(lm, true /* is_commit */, true, true)?;
}
// Inner-side resolution: clear IS_PREPARED and run the standard
// commit path (which releases locks and flips inner state).
if let Some(inner) = &self.inner_txn {
inner
.lock()
.unwrap()
.resolved_commit_after_prepare()
.map_err(NoxuError::from)?;
}
let mut state = self.state.lock().unwrap();
*state = TransactionState::Committed;
drop(state);
// Run commit callbacks (e.g. transactional database registration).
let cbs: Vec<Box<dyn FnOnce() + Send>> =
std::mem::take(&mut *self.commit_callbacks.lock().unwrap());
for cb in cbs {
cb();
}
if let Some(registry) = &self.active_txns {
registry.mark_complete(self.id);
}
// F-5: counterpart to begin_txn — remove the inner Txn from
// TxnManager (all_txns + locker label) to avoid an unbounded leak.
self.unregister_inner_txn(true);
observe_gauge_dec!("noxu_db_active_transactions");
Ok(())
}
/// Resolves a prepared transaction with an abort.
pub fn resolved_abort_after_prepare(&self) -> Result<()> {
{
let state = self.state.lock().unwrap();
if !matches!(*state, TransactionState::Prepared) {
return Err(NoxuError::OperationNotAllowed(format!(
"resolved_abort_after_prepare: expected Prepared, got {:?}",
*state
)));
}
}
// Write the resolving TxnAbort frame. NOT gated on
// `has_logged_data()` for the same reason as the commit path above:
// a prepared txn wrote a durable TxnPrepare frame that recovery would
// otherwise resurrect, so the resolving frame must always be written.
if !self.read_only
&& let Some(lm) = &self.log_manager
{
self.write_txn_end(lm, false /* is_commit */, false, false)?;
}
// Apply undo records to the B-tree to restore before-images, then
// release write locks. Same 3-phase ordering as `Transaction::abort()`:
// collect undo → apply → release locks. See the matching comment
// in `Transaction::abort` for the rationale (no reader sees the
// in-flight value until the before-image is back in the tree).
if let Some(inner) = &self.inner_txn {
// First, clear the IS_PREPARED flag on the inner Txn so that
// `abort_collect_undo()` (which calls into `Txn::abort`) does
// not refuse with InvalidTransaction { state: PREPARED }.
// We do this via the inner's resolved-abort path, which
// performs `txn_flags &= !IS_PREPARED` and then runs `abort()`.
// Unfortunately that consumes the locks; we want the
// pre-release behaviour instead, so flip the flag manually
// and then run abort_collect_undo.
let mut undo_records = {
let mut g = inner.lock().unwrap();
// Undo the IS_PREPARED flag so abort_collect_undo doesn't
// refuse. Inner state is still Open at this point.
g.clear_prepared_flag();
g.abort_collect_undo().unwrap_or_default()
};
// See `abort()` above: undo must be applied newest-LSN first so
// that delete-then-reinsert sequences in the same txn are
// unwound in reverse-operation order, matching the recovery
// path's backward log scan.
undo_records.sort_by_key(|r| std::cmp::Reverse(r.current_lsn));
if let Some(env) = &self.env_impl {
let env_guard = env.lock();
for undo in undo_records {
let Some(abort_key) = undo.abort_key else { continue };
let db_id =
noxu_dbi::DatabaseId::new(undo.database_id as i64);
let Some(db_arc) = env_guard.get_database_by_id(db_id)
else {
continue;
};
let db_guard = db_arc.read();
if let Some(tree) = db_guard.get_real_tree() {
if undo.abort_known_deleted {
if tree.delete(&abort_key) {
db_guard.decrement_entry_count();
}
} else if let Some(abort_data) = undo.abort_data {
let lsn = noxu_util::Lsn::from_u64(undo.abort_lsn);
if let Ok(is_new) =
tree.insert(abort_key, abort_data, lsn)
&& is_new
{
db_guard.increment_entry_count();
}
}
}
}
}
inner.lock().unwrap().release_all_locks();
}
let mut state = self.state.lock().unwrap();
*state = TransactionState::Aborted;
drop(state);
// Run abort callbacks (e.g. transactional database registration rollback).
let cbs: Vec<Box<dyn FnOnce() + Send>> =
std::mem::take(&mut *self.abort_callbacks.lock().unwrap());
for cb in cbs {
cb();
}
if let Some(registry) = &self.active_txns {
registry.mark_complete(self.id);
}
// F-5: counterpart to begin_txn — remove the inner Txn from
// TxnManager (all_txns + locker label) to avoid an unbounded leak.
self.unregister_inner_txn(false);
observe_gauge_dec!("noxu_db_active_transactions");
Ok(())
}
/// Serializes a `TxnPrepareEntry` and writes it to the WAL with fsync.
fn write_txn_prepare(
&self,
lm: &LogManager,
first_lsn: u64,
last_lsn: u64,
xid_format_id: i32,
xid_gtrid: &[u8],
xid_bqual: &[u8],
) -> Result<()> {
use noxu_log::{LogEntryType, Provisional, entry::TxnPrepareEntry};
let timestamp_ms = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64;
let entry = TxnPrepareEntry::new(
self.id as i64,
timestamp_ms,
first_lsn,
last_lsn,
xid_format_id,
xid_gtrid.to_vec(),
xid_bqual.to_vec(),
)
.map_err(|e| {
NoxuError::environment_with_reason(
crate::error::EnvironmentFailureReason::LogWrite,
format!("prepare entry encode: {e}"),
)
})?;
let mut buf = Vec::with_capacity(entry.log_size());
entry.write_to_log(&mut buf);
// fsync=true, flush=true: prepare must be durable before
// returning so a subsequent crash sees the prepare frame.
lm.log(LogEntryType::TxnPrepare, &buf, Provisional::No, true, true)
.map(|_| ())
.map_err(|e| {
NoxuError::environment_with_reason(
crate::error::EnvironmentFailureReason::LogWrite,
e.to_string(),
)
})
}
/// Serializes a TxnCommit or TxnAbort entry and writes it to `lm`.
fn write_txn_end(
&self,
lm: &LogManager,
is_commit: bool,
fsync: bool,
flush: bool,
) -> Result<()> {
use bytes::BytesMut;
use noxu_log::{LogEntryType, Provisional, entry::TxnEndEntry};
use noxu_util::{lsn::NULL_LSN, vlsn::NULL_VLSN};
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64;
let entry = if is_commit {
TxnEndEntry::new_commit(
self.id as i64,
NULL_LSN,
timestamp,
0,
NULL_VLSN,
)
} else {
TxnEndEntry::new_abort(
self.id as i64,
NULL_LSN,
timestamp,
0,
NULL_VLSN,
)
};
let entry_type = if is_commit {
LogEntryType::TxnCommit
} else {
LogEntryType::TxnAbort
};
let mut buf = BytesMut::with_capacity(entry.log_size());
entry.write_to_log(&mut buf);
lm.log(entry_type, &buf, Provisional::No, flush, fsync)
.map(|_| ())
.map_err(|e| {
NoxuError::environment_with_reason(
crate::error::EnvironmentFailureReason::LogWrite,
e.to_string(),
)
})
}
/// Returns the transaction ID.
pub fn id(&self) -> u64 {
self.id
}
/// Set the human-readable name of this transaction.
///
/// Mirrors `Transaction.setName(String)`. The name is purely
/// diagnostic — it appears in `Debug` output, structured log
/// records, and lock-conflict reports.
/// (transaction-env F22).
pub fn set_name<S: Into<String>>(&self, name: S) {
*self.name.lock().unwrap() = Some(name.into());
}
/// Returns the caller-supplied transaction name, if any.
///
/// Mirrors `Transaction.getName()`.
pub fn name(&self) -> Option<String> {
self.name.lock().unwrap().clone()
}
/// Returns the number of locks currently held by this transaction.
///
/// Mirrors `Transaction.getLockStat()` / `Transaction.getNumWriteLocks() +
/// getNumReadLocks()` (the JE API exposes both counts; we return
/// the sum because the lock manager partitions reads / writes per
/// LSN rather than per record). Returns `0` for transactions that
/// have not acquired any locks (or for read-only transactions
/// running with read-uncommitted isolation, which skip lock
/// acquisition entirely).
/// (transaction-env F23 "lock-stat reporting missing").
pub fn lock_count(&self) -> usize {
match &self.inner_txn {
Some(txn) => {
let g = txn.lock().unwrap();
g.read_lock_count() + g.write_lock_count()
}
None => 0,
}
}
/// Returns `(read_lock_count, write_lock_count)` for this
/// transaction's lock set.
///
/// Mirrors JE's `Transaction.getNumReadLocks()` /
/// `getNumWriteLocks()` accessors. Returns `(0, 0)` for a
/// transaction that has not acquired any locks.
pub fn lock_counts(&self) -> (usize, usize) {
match &self.inner_txn {
Some(txn) => {
let g = txn.lock().unwrap();
(g.read_lock_count(), g.write_lock_count())
}
None => (0, 0),
}
}
/// Returns the current transaction state.
pub fn state(&self) -> TransactionState {
*self.state.lock().unwrap()
}
/// Check if the transaction is valid (in Open state).
pub fn is_valid(&self) -> bool {
matches!(self.state(), TransactionState::Open)
}
/// Set the lock timeout for this transaction.
///
/// # Arguments
/// * `timeout_ms` - Lock timeout in milliseconds (0 = use environment default)
pub fn set_lock_timeout(&self, timeout_ms: u64) {
*self.lock_timeout_ms.lock().unwrap() = timeout_ms;
}
/// Returns the lock timeout for this transaction.
pub fn lock_timeout(&self) -> u64 {
*self.lock_timeout_ms.lock().unwrap()
}
/// Set the transaction timeout.
///
/// # Arguments
/// * `timeout_ms` - Transaction timeout in milliseconds (0 = use environment default)
pub fn set_txn_timeout(&self, timeout_ms: u64) {
*self.txn_timeout_ms.lock().unwrap() = timeout_ms;
}
/// Returns the transaction timeout for this transaction.
pub fn txn_timeout(&self) -> u64 {
*self.txn_timeout_ms.lock().unwrap()
}
/// Returns the durability setting for this transaction.
pub fn durability(&self) -> Option<Durability> {
self.durability
}
/// Check if this is a read-only transaction.
pub fn is_read_only(&self) -> bool {
self.read_only
}
/// Returns `true` iff this transaction actually appended any data
/// (LN) log entries to the WAL.
///
/// This is the *dynamic* did-it-write signal, distinct from the static
/// [`Self::is_read_only`] config flag. A transaction created without
/// `with_read_only(true)` (the default) is write-*capable*, but if it
/// only performed reads it logged nothing and needs no `TxnCommit` /
/// `TxnAbort` frame — and, critically, no commit fsync.
///
/// JE: `Txn.commit()` writes a commit entry only for transactions that
/// have logged entries (`Txn.hasLoggedEntries()` /
/// `lastLoggedLsn != NULL_LSN`). A read-only-in-practice txn is a no-op
/// commit — no WAL write, no group-commit fsync barrier. Gating on the
/// static `read_only` flag instead (the pre-fix behaviour) forced every
/// explicit read txn through `write_txn_end` → `log` → `flush_sync` →
/// `fdatasync` at `SYNC`, serialising 100%-cache-hit readers on the
/// log-write latch + fsync group-commit condvar (read-commit-contention
/// audit, 2026-07).
fn has_logged_data(&self) -> bool {
match &self.inner_txn {
Some(inner) => inner
.lock()
.unwrap_or_else(|p| p.into_inner())
.has_logged_entries(),
// No inner Txn (env-less construction): it cannot have logged
// an LN through the engine, so there is nothing to commit
// durably.
None => false,
}
}
/// Get the elapsed time since transaction start.
pub fn elapsed(&self) -> std::time::Duration {
self.start_time.elapsed()
}
/// Check that the transaction is in Open state.
///
/// # Errors
/// Returns error if the transaction is not Open.
fn check_open(&self) -> Result<()> {
let state = self.state();
match state {
TransactionState::Open => Ok(()),
TransactionState::Prepared => Err(NoxuError::OperationNotAllowed(
"Transaction has been prepared; use xa_commit / xa_rollback"
.to_string(),
)),
TransactionState::Committed => Err(NoxuError::OperationNotAllowed(
"Transaction has been committed".to_string(),
)),
TransactionState::Aborted => Err(NoxuError::OperationNotAllowed(
"Transaction has been aborted".to_string(),
)),
TransactionState::MustAbort => Err(NoxuError::OperationNotAllowed(
"Transaction must be aborted due to previous error".to_string(),
)),
}
}
}
impl Drop for Transaction {
fn drop(&mut self) {
// Audit transaction-env F10 (Wave 2C-4): if the txn is still in
// a non-terminal state at drop time, perform an actual abort
// (release locks, apply undo, prune from active-txn registry,
// decrement gauge) instead of just logging a warning.
//
// Poison-safe: a panic elsewhere may have poisoned `state`. In Drop we
// MUST NOT unwrap() a poisoned lock — that would turn a recoverable
// poison into a double-panic and abort the whole process. Recover the
// guard with into_inner() and proceed with a best-effort abort.
let state =
*self.state.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
if matches!(state, TransactionState::Open | TransactionState::MustAbort)
{
log::warn!(
"Transaction {} dropped without commit or abort, \
implicitly aborting",
self.id
);
// Best-effort abort. Errors are swallowed because Drop
// cannot return Result; any failure (e.g., WAL write error)
// is still observable through the abort path's logging.
if let Err(e) = self.abort() {
log::error!(
"Transaction {} implicit abort on drop failed: {e}",
self.id,
);
}
} else if matches!(state, TransactionState::Prepared) {
// Prepared txns dropped without resolution simulate a crash
// — the durable TxnPrepare frame on disk is recovered on the
// next environment open, where xa_recover() will surface the
// XID for resolution. This is intentional and supports the
// crash-durable XA contract introduced in wave 3-2.
log::info!(
"Transaction {} dropped while prepared; XID will be \
surfaced via xa_recover() on next open",
self.id
);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_new_transaction() {
let config = TransactionConfig::default();
let txn = Transaction::new(1, config);
assert_eq!(txn.id(), 1);
assert_eq!(txn.state(), TransactionState::Open);
assert!(txn.is_valid());
assert!(!txn.is_read_only());
}
/// `set_name` / `get_name`
/// round-trip and survives commit (the JE shape stays valid until
/// the txn is dropped).
#[test]
fn test_set_name_get_name_round_trip() {
let config = TransactionConfig::default();
let txn = Transaction::new(1, config);
assert_eq!(txn.name(), None);
txn.set_name("workload-import");
assert_eq!(txn.name().as_deref(), Some("workload-import"));
// Setting again replaces.
txn.set_name("workload-import-2");
assert_eq!(txn.name().as_deref(), Some("workload-import-2"));
}
/// `lock_count` and
/// lock_counts return zero when there is no inner Txn (i.e., the
/// transaction is decorative — unit-test mode without an
/// EnvironmentImpl wired in).
#[test]
fn test_lock_counts_without_inner_txn_are_zero() {
let config = TransactionConfig::default();
let txn = Transaction::new(1, config);
assert_eq!(txn.lock_count(), 0);
assert_eq!(txn.lock_counts(), (0, 0));
}
#[test]
fn test_read_only_transaction() {
let config = TransactionConfig::default().with_read_only(true);
let txn = Transaction::new(2, config);
assert!(txn.is_read_only());
assert!(txn.is_valid());
}
#[test]
fn test_commit() {
let config = TransactionConfig::default();
let txn = Transaction::new(3, config);
assert!(txn.commit().is_ok());
assert_eq!(txn.state(), TransactionState::Committed);
assert!(!txn.is_valid());
}
#[test]
fn test_commit_twice_fails() {
let config = TransactionConfig::default();
let txn = Transaction::new(4, config);
assert!(txn.commit().is_ok());
let result = txn.commit();
assert!(result.is_err());
assert!(matches!(
result.unwrap_err(),
NoxuError::OperationNotAllowed(_)
));
}
#[test]
fn test_abort() {
let config = TransactionConfig::default();
let txn = Transaction::new(5, config);
assert!(txn.abort().is_ok());
assert_eq!(txn.state(), TransactionState::Aborted);
assert!(!txn.is_valid());
}
#[test]
fn test_abort_twice_fails() {
let config = TransactionConfig::default();
let txn = Transaction::new(6, config);
assert!(txn.abort().is_ok());
let result = txn.abort();
assert!(result.is_err());
}
#[test]
fn test_commit_after_abort_fails() {
let config = TransactionConfig::default();
let txn = Transaction::new(7, config);
assert!(txn.abort().is_ok());
let result = txn.commit();
assert!(result.is_err());
}
#[test]
fn test_abort_after_commit_fails() {
let config = TransactionConfig::default();
let txn = Transaction::new(8, config);
assert!(txn.commit().is_ok());
let result = txn.abort();
assert!(result.is_err());
}
#[test]
fn test_lock_timeout() {
let config = TransactionConfig::default();
let txn = Transaction::new(9, config);
assert_eq!(txn.lock_timeout(), 0);
txn.set_lock_timeout(5000);
assert_eq!(txn.lock_timeout(), 5000);
}
#[test]
fn test_txn_timeout() {
let config = TransactionConfig::default();
let txn = Transaction::new(10, config);
assert_eq!(txn.txn_timeout(), 0);
txn.set_txn_timeout(10000);
assert_eq!(txn.txn_timeout(), 10000);
}
#[test]
fn test_durability() {
let dur = Durability::COMMIT_SYNC;
let config = TransactionConfig::default().with_durability(dur);
let txn = Transaction::new(11, config);
assert_eq!(txn.durability(), Some(dur));
}
#[test]
fn test_elapsed_time() {
let config = TransactionConfig::default();
let txn = Transaction::new(12, config);
std::thread::sleep(std::time::Duration::from_millis(10));
let elapsed = txn.elapsed();
assert!(elapsed.as_millis() >= 10);
}
#[test]
fn test_commit_with_durability() {
let config = TransactionConfig::default();
let txn = Transaction::new(13, config);
let dur = Durability::COMMIT_NO_SYNC;
assert!(txn.commit_with_durability(dur).is_ok());
assert_eq!(txn.state(), TransactionState::Committed);
}
#[test]
fn test_must_abort_state() {
let config = TransactionConfig::default();
let txn = Transaction::new(14, config);
{
let mut state = txn.state.lock().unwrap();
*state = TransactionState::MustAbort;
}
assert_eq!(txn.state(), TransactionState::MustAbort);
assert!(!txn.is_valid());
// Can still abort a MustAbort transaction
assert!(txn.abort().is_ok());
assert_eq!(txn.state(), TransactionState::Aborted);
}
#[test]
fn test_must_abort_cannot_commit() {
let config = TransactionConfig::default();
let txn = Transaction::new(15, config);
{
let mut state = txn.state.lock().unwrap();
*state = TransactionState::MustAbort;
}
let result = txn.commit();
assert!(result.is_err());
assert!(matches!(
result.unwrap_err(),
NoxuError::OperationNotAllowed(_)
));
}
#[test]
fn test_state_transitions() {
let config = TransactionConfig::default();
// Open -> Committed
let txn1 = Transaction::new(16, config.clone());
assert_eq!(txn1.state(), TransactionState::Open);
txn1.commit().unwrap();
assert_eq!(txn1.state(), TransactionState::Committed);
// Open -> Aborted
let txn2 = Transaction::new(17, config);
assert_eq!(txn2.state(), TransactionState::Open);
txn2.abort().unwrap();
assert_eq!(txn2.state(), TransactionState::Aborted);
}
#[test]
fn test_transaction_id_uniqueness() {
let config = TransactionConfig::default();
let txn1 = Transaction::new(100, config.clone());
let txn2 = Transaction::new(101, config);
assert_ne!(txn1.id(), txn2.id());
}
// ── the terminal-state matrix ────────────────────────────────────────
//
// Every public operation routes through `check_open`, which admits only
// `Open`. The four rejecting states each carry a DIFFERENT message,
// because "you cannot do that" is useless to a caller who needs to know
// whether to retry (MustAbort -> abort and retry), resolve via XA
// (Prepared), or treat the work as already done (Committed). Previously
// only two of the twenty state/operation pairs were tested.
/// Force `txn` into `state` without going through a real transition, so
/// each terminal state can be probed independently.
fn forced(id: u64, state: TransactionState) -> Transaction {
let txn = Transaction::new(id, TransactionConfig::default());
*txn.state.lock().unwrap() = state;
txn
}
#[test]
fn every_terminal_state_rejects_commit_with_a_distinguishable_reason() {
let cases = [
(TransactionState::Prepared, "prepared"),
(TransactionState::Committed, "committed"),
(TransactionState::Aborted, "aborted"),
(TransactionState::MustAbort, "must be aborted"),
];
let mut messages = Vec::new();
for (i, (state, needle)) in cases.into_iter().enumerate() {
let txn = forced(900 + i as u64, state);
let err =
txn.commit().expect_err("a non-Open txn must refuse to commit");
let msg = err.to_string().to_lowercase();
assert!(
msg.contains(needle),
"the {state:?} rejection must say why (looking for \
{needle:?}); got: {msg}"
);
assert!(matches!(err, NoxuError::OperationNotAllowed(_)));
messages.push(msg);
}
// Every message must be distinct, or the caller cannot branch on it.
for i in 0..messages.len() {
for j in (i + 1)..messages.len() {
assert_ne!(
messages[i], messages[j],
"two states share a rejection message"
);
}
}
}
/// `commit()` and `commit_with_durability()` must agree on the state
/// guard -- the convenience wrapper must not bypass it.
#[test]
fn commit_with_durability_enforces_the_same_state_guard_as_commit() {
for (i, state) in [
TransactionState::Prepared,
TransactionState::Committed,
TransactionState::Aborted,
TransactionState::MustAbort,
]
.into_iter()
.enumerate()
{
let txn = forced(920 + i as u64, state);
assert!(
txn.commit_with_durability(Durability::COMMIT_NO_SYNC).is_err(),
"{state:?} must be refused by commit_with_durability too"
);
assert_eq!(
txn.state(),
state,
"a refused commit must not change the state"
);
}
}
/// A `Prepared` transaction may only be resolved through the XA pair.
/// Direct commit/abort are protocol errors, and -- the part that matters --
/// a refused call must leave the txn still Prepared and still resolvable,
/// not stranded holding locks in a state nothing can clear.
#[test]
fn a_prepared_transaction_is_only_resolvable_through_the_xa_pair() {
let txn = forced(940, TransactionState::Prepared);
assert!(txn.commit().is_err(), "direct commit is a protocol error");
assert!(txn.abort().is_err(), "direct abort is a protocol error");
assert_eq!(
txn.state(),
TransactionState::Prepared,
"a refused direct resolution must leave the txn resolvable"
);
txn.resolved_commit_after_prepare().unwrap();
assert_eq!(txn.state(), TransactionState::Committed);
}
#[test]
fn a_prepared_transaction_can_be_resolved_by_abort() {
let txn = forced(941, TransactionState::Prepared);
txn.resolved_abort_after_prepare().unwrap();
assert_eq!(txn.state(), TransactionState::Aborted);
}
/// The XA resolvers must refuse anything that is not Prepared, or a
/// never-prepared transaction could be committed through the XA path,
/// skipping the phase-1 durability the protocol depends on.
#[test]
fn the_xa_resolvers_refuse_a_transaction_that_was_never_prepared() {
for (i, state) in [
TransactionState::Open,
TransactionState::Committed,
TransactionState::Aborted,
TransactionState::MustAbort,
]
.into_iter()
.enumerate()
{
let a = forced(960 + i as u64, state);
let err = a
.resolved_commit_after_prepare()
.expect_err("resolving a non-Prepared txn must be refused");
assert!(
err.to_string().contains("Prepared"),
"the error must name the state it expected; got: {err}"
);
assert_eq!(a.state(), state, "a refusal must not change state");
let b = forced(980 + i as u64, state);
assert!(b.resolved_abort_after_prepare().is_err());
assert_eq!(b.state(), state);
}
}
/// `prepare` itself requires Open: preparing an already-resolved
/// transaction would fabricate an in-doubt branch that recovery would then
/// try to resolve.
#[test]
fn prepare_requires_an_open_transaction() {
for (i, state) in [
TransactionState::Prepared,
TransactionState::Committed,
TransactionState::Aborted,
TransactionState::MustAbort,
]
.into_iter()
.enumerate()
{
let txn = forced(1000 + i as u64, state);
assert!(
txn.prepare(1, b"gtrid", b"bqual").is_err(),
"{state:?} must not be preparable"
);
assert_eq!(txn.state(), state);
}
let open = forced(1010, TransactionState::Open);
open.prepare(1, b"gtrid", b"bqual").unwrap();
assert_eq!(open.state(), TransactionState::Prepared);
}
/// Abort is idempotent-ish in the useful direction: aborting an already
/// Aborted txn must be refused rather than double-releasing locks or
/// re-applying undo. But `MustAbort` MUST still be abortable -- that is
/// the entire purpose of the state.
#[test]
fn abort_refuses_resolved_states_but_must_abort_stays_abortable() {
let committed = forced(1020, TransactionState::Committed);
assert!(committed.abort().is_err());
assert_eq!(committed.state(), TransactionState::Committed);
let aborted = forced(1021, TransactionState::Aborted);
assert!(aborted.abort().is_err(), "double abort must be refused");
assert_eq!(aborted.state(), TransactionState::Aborted);
let must = forced(1022, TransactionState::MustAbort);
assert!(!must.is_valid());
must.abort().expect("MustAbort exists so it CAN be aborted");
assert_eq!(must.state(), TransactionState::Aborted);
}
/// `is_valid` means "can still be USED for work", which is `Open` alone.
/// Notably `Prepared` is NOT valid even though it still holds locks and is
/// still resolvable: after phase 1 the commit decision is fixed, so
/// accepting further reads or writes would let work slip in behind a
/// durability promise that has already been made. Callers gate on this, so
/// misclassifying any state would let work proceed on a txn that cannot
/// accept it.
#[test]
fn is_valid_means_open_and_nothing_else() {
assert!(forced(1040, TransactionState::Open).is_valid());
assert!(
!forced(1041, TransactionState::Prepared).is_valid(),
"a Prepared txn is resolvable but NOT usable: its commit decision \
is already fixed"
);
assert!(!forced(1042, TransactionState::Committed).is_valid());
assert!(!forced(1043, TransactionState::Aborted).is_valid());
assert!(!forced(1044, TransactionState::MustAbort).is_valid());
}
/// The timeout setters must round-trip independently. They are separate
/// knobs (a lock timeout is per-lock-wait, a txn timeout is for the whole
/// transaction) and conflating them would silently change semantics.
#[test]
fn the_two_timeouts_are_independent_knobs() {
let txn = Transaction::new(1060, TransactionConfig::default());
txn.set_lock_timeout(500);
txn.set_txn_timeout(9_000);
assert_eq!(txn.lock_timeout(), 500);
assert_eq!(txn.txn_timeout(), 9_000);
txn.set_lock_timeout(0);
assert_eq!(txn.lock_timeout(), 0, "0 means no lock timeout");
assert_eq!(
txn.txn_timeout(),
9_000,
"changing the lock timeout must not disturb the txn timeout"
);
}
/// Registered callbacks must fire on the matching resolution and NOT on
/// the other one -- a commit callback firing on abort would let an
/// application publish work that was rolled back.
#[test]
fn resolution_callbacks_fire_only_on_their_own_outcome() {
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
let commits = Arc::new(AtomicUsize::new(0));
let aborts = Arc::new(AtomicUsize::new(0));
let txn = Transaction::new(1080, TransactionConfig::default());
let c = Arc::clone(&commits);
txn.register_commit_callback(move || {
c.fetch_add(1, Ordering::SeqCst);
});
let a = Arc::clone(&aborts);
txn.register_abort_callback(move || {
a.fetch_add(1, Ordering::SeqCst);
});
txn.commit().unwrap();
assert_eq!(commits.load(Ordering::SeqCst), 1);
assert_eq!(
aborts.load(Ordering::SeqCst),
0,
"the abort callback must not fire on a commit"
);
let commits2 = Arc::new(AtomicUsize::new(0));
let aborts2 = Arc::new(AtomicUsize::new(0));
let txn2 = Transaction::new(1081, TransactionConfig::default());
let c2 = Arc::clone(&commits2);
txn2.register_commit_callback(move || {
c2.fetch_add(1, Ordering::SeqCst);
});
let a2 = Arc::clone(&aborts2);
txn2.register_abort_callback(move || {
a2.fetch_add(1, Ordering::SeqCst);
});
txn2.abort().unwrap();
assert_eq!(aborts2.load(Ordering::SeqCst), 1);
assert_eq!(
commits2.load(Ordering::SeqCst),
0,
"the commit callback must not fire on an abort -- that would let \
an application publish rolled-back work"
);
}
// ── env-wired transactions: the real commit / abort / undo paths ─────
//
// The tests above use `Transaction::new` directly, which produces a
// "decorative" transaction with no log manager, no inner Txn, and no
// environment. That reaches the state machine but NOT the three write-path
// steps in `commit_with_durability` (WAL frame, replica-ack wait, cleaner
// throttle) or the undo application in `abort`, all of which are gated on
// `!read_only && has_logged_data() && <subsystem present>`.
//
// These tests open a real environment so those paths actually run, and
// assert the behaviour that distinguishes them: WHETHER a WAL frame is
// written, and whether undo restores the correct before-image.
use crate::database_config::DatabaseConfig;
use crate::environment::Environment;
use crate::environment_config::EnvironmentConfig;
use tempfile::TempDir;
fn wired() -> (TempDir, Environment, crate::database::Database) {
let dir = TempDir::new().unwrap();
let env = Environment::open(
EnvironmentConfig::new(dir.path().to_path_buf())
.with_allow_create(true)
.with_transactional(true),
)
.unwrap();
let db = env
.open_database(
None,
"txn",
&DatabaseConfig::new()
.with_allow_create(true)
.with_transactional(true),
)
.unwrap();
(dir, env, db)
}
fn log_end(env: &Environment) -> u64 {
env.stats().unwrap().log.end_of_log
}
/// A transaction that only READ must not write a TxnCommit frame. This is
/// the read-commit-contention fix: the gate is `has_logged_data()`, not the
/// static `read_only` config flag, so a default write-capable txn that
/// happened only to read pays no log write and -- crucially -- no commit
/// fsync.
#[test]
fn a_txn_that_only_read_writes_no_commit_frame() {
let (_d, env, db) = wired();
db.put(b"k", b"v").unwrap();
let txn = env.begin_transaction(None).unwrap();
assert_eq!(db.get_in(&txn, b"k").unwrap().as_deref(), Some(&b"v"[..]));
let before = log_end(&env);
txn.commit().unwrap();
assert_eq!(
log_end(&env),
before,
"a read-only-in-practice txn must write no TxnCommit frame, and \
therefore take no commit fsync"
);
}
/// A transaction that WROTE must write a TxnCommit frame -- otherwise
/// recovery could not tell the write was committed and would undo it.
#[test]
fn a_txn_that_wrote_does_write_a_commit_frame() {
let (_d, env, db) = wired();
let txn = env.begin_transaction(None).unwrap();
db.put_in(&txn, b"k", b"v").unwrap();
let before = log_end(&env);
txn.commit().unwrap();
assert!(
log_end(&env) > before,
"a txn with logged data must write a TxnCommit frame, or recovery \
would undo the committed write"
);
assert_eq!(db.get(b"k").unwrap().as_deref(), Some(&b"v"[..]));
}
/// The same asymmetry on the abort side: a read-only-in-practice abort
/// writes no TxnAbort frame, because there is no undo chain for recovery to
/// follow.
#[test]
fn a_txn_that_only_read_writes_no_abort_frame() {
let (_d, env, db) = wired();
db.put(b"k", b"v").unwrap();
let txn = env.begin_transaction(None).unwrap();
let _ = db.get_in(&txn, b"k").unwrap();
let before = log_end(&env);
txn.abort().unwrap();
assert_eq!(
log_end(&env),
before,
"no logged data means no undo chain, so no TxnAbort frame"
);
}
/// Abort must restore the BEFORE-IMAGE of an updated record, not merely
/// drop the new value. This is the undo-application path
/// (`abort_data` / `abort_key`), and getting it wrong leaves the database
/// holding a value that was never committed.
#[test]
fn abort_restores_the_before_image_of_an_updated_record() {
let (_d, env, db) = wired();
db.put(b"k", b"original").unwrap();
let txn = env.begin_transaction(None).unwrap();
db.put_in(&txn, b"k", b"modified").unwrap();
assert_eq!(
db.get_in(&txn, b"k").unwrap().as_deref(),
Some(&b"modified"[..]),
"the txn must see its own write before resolving"
);
txn.abort().unwrap();
assert_eq!(
db.get(b"k").unwrap().as_deref(),
Some(&b"original"[..]),
"abort must restore the before-image, not leave the new value"
);
}
/// Abort of an INSERT must remove the record entirely -- there is no
/// before-image to restore, so the undo record carries
/// `abort_known_deleted` and the row must vanish.
#[test]
fn abort_removes_a_record_that_the_txn_inserted() {
let (_d, env, db) = wired();
let txn = env.begin_transaction(None).unwrap();
db.put_in(&txn, b"fresh", b"v").unwrap();
assert!(db.get_in(&txn, b"fresh").unwrap().is_some());
txn.abort().unwrap();
assert!(
db.get(b"fresh").unwrap().is_none(),
"an aborted insert must leave no record behind"
);
}
/// Abort of a DELETE must bring the record back. The three undo shapes
/// (update / insert / delete) are three distinct arms of the undo loop.
#[test]
fn abort_restores_a_record_that_the_txn_deleted() {
let (_d, env, db) = wired();
db.put(b"k", b"keepme").unwrap();
let txn = env.begin_transaction(None).unwrap();
assert!(db.delete_in(&txn, b"k").unwrap());
txn.abort().unwrap();
assert_eq!(
db.get(b"k").unwrap().as_deref(),
Some(&b"keepme"[..]),
"an aborted delete must restore the record"
);
}
/// Undo must span MULTIPLE keys and multiple databases-worth of records in
/// one abort. A loop that stopped after the first undo record would pass
/// every single-key test above.
#[test]
fn abort_undoes_every_record_the_txn_touched() {
let (_d, env, db) = wired();
for i in 0u8..5 {
db.put([i], b"orig").unwrap();
}
let txn = env.begin_transaction(None).unwrap();
for i in 0u8..5 {
db.put_in(&txn, [i], b"changed").unwrap();
}
db.put_in(&txn, b"new", b"inserted").unwrap();
txn.abort().unwrap();
for i in 0u8..5 {
assert_eq!(
db.get([i]).unwrap().as_deref(),
Some(&b"orig"[..]),
"key {i} was not undone -- the undo loop stopped early"
);
}
assert!(db.get(b"new").unwrap().is_none());
}
/// Commit must make the writes durable and visible outside the txn, and
/// must NOT be undone by a later abort of a different transaction.
#[test]
fn committed_writes_survive_a_later_unrelated_abort() {
let (_d, env, db) = wired();
let t1 = env.begin_transaction(None).unwrap();
db.put_in(&t1, b"committed", b"v1").unwrap();
t1.commit().unwrap();
let t2 = env.begin_transaction(None).unwrap();
db.put_in(&t2, b"rolledback", b"v2").unwrap();
t2.abort().unwrap();
assert_eq!(
db.get(b"committed").unwrap().as_deref(),
Some(&b"v1"[..]),
"an unrelated abort must not disturb committed data"
);
assert!(db.get(b"rolledback").unwrap().is_none());
}
/// `commit_with_durability` must honour the requested policy. NO_SYNC must
/// not fsync, SYNC must -- that is the entire point of the parameter, and
/// the fsync counter makes it observable.
#[test]
fn durability_controls_whether_the_commit_fsyncs() {
let (_d, env, db) = wired();
let before = env.stat_fsync_count();
let t = env.begin_transaction(None).unwrap();
db.put_in(&t, b"a", b"1").unwrap();
t.commit_with_durability(Durability::COMMIT_NO_SYNC).unwrap();
assert_eq!(
env.stat_fsync_count(),
before,
"COMMIT_NO_SYNC must not fsync"
);
let before = env.stat_fsync_count();
let t = env.begin_transaction(None).unwrap();
db.put_in(&t, b"b", b"2").unwrap();
t.commit_with_durability(Durability::COMMIT_SYNC).unwrap();
assert!(
env.stat_fsync_count() > before,
"COMMIT_SYNC must fsync, or the commit is not durable"
);
}
/// The active-transaction registry must be pruned on BOTH resolutions.
/// A leaked entry pins the txn's locks in the manager's view and would make
/// a later deadlock scan chase a transaction that no longer exists.
#[test]
fn both_resolutions_prune_the_active_transaction_registry() {
let (_d, env, db) = wired();
let baseline = env.stats().unwrap().txn.n_active;
let t = env.begin_transaction(None).unwrap();
db.put_in(&t, b"k", b"v").unwrap();
assert!(
env.stats().unwrap().txn.n_active > baseline,
"an open txn must be registered as active"
);
t.commit().unwrap();
assert_eq!(
env.stats().unwrap().txn.n_active,
baseline,
"a committed txn must be pruned from the active registry"
);
let t = env.begin_transaction(None).unwrap();
db.put_in(&t, b"k2", b"v").unwrap();
t.abort().unwrap();
assert_eq!(
env.stats().unwrap().txn.n_active,
baseline,
"an aborted txn must be pruned too"
);
}
/// Dropping a still-open transaction must ABORT it, not silently commit or
/// leak its locks. This is the F10 drop-abort path, and an early-return on
/// an error would leave the write visible.
#[test]
fn dropping_an_open_transaction_aborts_its_writes() {
let (_d, env, db) = wired();
db.put(b"k", b"original").unwrap();
{
let txn = env.begin_transaction(None).unwrap();
db.put_in(&txn, b"k", b"leaked").unwrap();
// No commit, no abort: just drop.
}
assert_eq!(
db.get(b"k").unwrap().as_deref(),
Some(&b"original"[..]),
"a dropped txn must abort, or its uncommitted write leaks"
);
}
/// A prepared transaction resolved through the XA commit path must make its
/// writes visible, and the prepare itself must write a durable frame so
/// recovery can find the in-doubt branch.
#[test]
fn a_prepared_txn_writes_a_durable_frame_and_commits_its_writes() {
let (_d, env, db) = wired();
let txn = env.begin_transaction(None).unwrap();
db.put_in(&txn, b"xa", b"v").unwrap();
let before = log_end(&env);
txn.prepare(1, b"gtrid", b"bqual").unwrap();
assert!(
log_end(&env) > before,
"prepare must write a durable TxnPrepare frame, or recovery \
cannot find the in-doubt branch"
);
assert_eq!(txn.state(), TransactionState::Prepared);
txn.resolved_commit_after_prepare().unwrap();
assert_eq!(txn.state(), TransactionState::Committed);
assert_eq!(db.get(b"xa").unwrap().as_deref(), Some(&b"v"[..]));
}
/// And resolved through the XA abort path, its writes must be undone --
/// prepare holds the locks but does not fix the outcome as commit.
#[test]
fn a_prepared_txn_resolved_by_abort_has_its_writes_undone() {
let (_d, env, db) = wired();
db.put(b"xa", b"original").unwrap();
let txn = env.begin_transaction(None).unwrap();
db.put_in(&txn, b"xa", b"modified").unwrap();
txn.prepare(1, b"gtrid", b"bqual").unwrap();
txn.resolved_abort_after_prepare().unwrap();
assert_eq!(
db.get(b"xa").unwrap().as_deref(),
Some(&b"original"[..]),
"an XA-aborted prepared txn must still undo its writes"
);
}
/// KNOWN GAP, pinned deliberately rather than asserted as correct.
///
/// `TransactionConfig::read_only` does NOT prevent writes today. The flag
/// is consumed only inside `Transaction`, where `!self.read_only` gates the
/// commit / abort / prepare WAL-frame paths. Nothing on the write path
/// consults it: `Database`'s write entry points check `check_writable`,
/// which reads the *DatabaseConfig*'s `read_only`, not the transaction's.
///
/// So a write on a read-only txn succeeds and lands in the tree, while the
/// flag suppresses the TxnCommit frame that would record it as committed.
/// JE rejects this at cursor-open time
/// (`LockerFactory.getWritableLocker`); Noxu does not.
///
/// This test asserts CURRENT behaviour so the gap is visible in the suite
/// instead of merely absent from it. Adding the missing guard is a breaking
/// change for any caller relying on today's permissiveness, so it belongs
/// in its own commit -- and it will make this test fail, which is the
/// point.
#[test]
fn read_only_transactions_do_not_yet_reject_writes() {
let (_d, env, db) = wired();
db.put(b"k", b"v").unwrap();
let cfg = TransactionConfig::default().with_read_only(true);
let txn = env.begin_transaction(Some(&cfg)).unwrap();
assert!(txn.is_read_only(), "the flag itself round-trips");
// Reads work, as they should.
assert_eq!(db.get_in(&txn, b"k").unwrap().as_deref(), Some(&b"v"[..]));
// And so does a WRITE, which is the gap.
assert!(
db.put_in(&txn, b"k", b"v2").is_ok(),
"documenting current behaviour: the read-only txn flag is not \
enforced on the write path"
);
// The commit writes no TxnCommit frame, because the same flag DOES gate
// that -- so the write is applied without a commit record.
let before = log_end(&env);
txn.commit().unwrap();
assert_eq!(
log_end(&env),
before,
"the read_only flag suppresses the commit frame even though the \
write was accepted"
);
}
}