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
use bytes::Bytes;
use parking_lot::{Mutex, RwLock};
use std::collections::HashSet;
use std::sync::Arc;
use uuid::Uuid;
use crate::batch::{WriteBatch, WriteBatchIterator};
use crate::bytes_range::{ByteRangeBounds, BytesRange};
use crate::config::{MergeOptions, PutOptions, ReadOptions, ScanOptions, WriteOptions};
use crate::db::DbInner;
use crate::db::WriteHandle;
use crate::db_iter::{DbIterator, DbIteratorRangeTracker};
use crate::error::SlateDBError;
use crate::iter::IterationOrder;
use crate::reader::ScanContext;
use crate::transaction_manager::{IsolationLevel, TransactionManager};
use crate::types::KeyValue;
use crate::{DbReadOps, DbTransactionOps};
/// A database transaction that provides atomic read-write operations with
/// configurable isolation levels. This is the main interface for transactional
/// operations in SlateDB.
///
/// # Examples
///
/// Basic transaction usage:
/// ```rust
/// # async fn run() -> Result<(), slatedb::Error> {
/// # use std::sync::Arc;
/// # use slatedb::object_store::memory::InMemory;
/// use slatedb::{Db, IsolationLevel};
///
/// # let object_store = Arc::new(InMemory::new());
/// # let db = Db::open("path/to/db", object_store).await?;
/// let txn = db.begin(IsolationLevel::Snapshot).await?;
///
/// // Read operations
/// let value = txn.get(b"key").await?;
///
/// // Write operations
/// txn.put(b"key", b"value")?;
/// txn.delete(b"key")?;
///
/// // Commit the transaction
/// txn.commit().await?;
/// # Ok(())
/// # };
/// ```
pub struct DbTransaction {
/// Transaction ID generated by the transaction manager
txn_id: Uuid,
/// Sequence number when the transaction started
started_seq: u64,
/// Reference to the transaction manager
txn_manager: Arc<TransactionManager>,
/// The write batch of the transaction, which contains the uncommitted writes.
/// Users can read data from the write batch during the transaction, thus providing
/// an MVCC view of the database.
///
/// DbTransaction is not intended for concurrent use; we use `RwLock` (not `RefCell`) for
/// interior mutability to preserve `Sync` in async contexts. `RefCell` is `!Sync` and would
/// make `DbTransaction` `!Sync`, which is incompatible with async code using the `DbReadOps`
/// trait.
write_batch: RwLock<WriteBatch>,
/// Reference to the database
db_inner: Arc<DbInner>,
/// Isolation level for this transaction
isolation_level: IsolationLevel,
/// Range trackers for scanned ranges (used for SSI conflict detection)
range_trackers: Mutex<Vec<DbIteratorRangeTracker>>,
/// Keys that should be excluded from write conflict detection when committing.
untracked_write_keys: RwLock<HashSet<Bytes>>,
}
impl DbTransaction {
#[allow(unused)]
pub(crate) fn new(
db_inner: Arc<DbInner>,
txn_manager: Arc<TransactionManager>,
isolation_level: IsolationLevel,
) -> Self {
let (txn_id, seq) = txn_manager.new_transaction();
Self {
txn_id,
started_seq: seq,
txn_manager,
write_batch: RwLock::new(WriteBatch::new()),
db_inner,
isolation_level,
range_trackers: Mutex::new(Vec::new()),
untracked_write_keys: RwLock::new(HashSet::new()),
}
}
/// Get a value from the transaction with default read options.
/// This operation will track the read for conflict detection in SSI mode.
///
/// ## Arguments
/// - `key`: the key to get
///
/// ## Returns
/// - `Result<Option<Bytes>, SlateDBError>`: the value if it exists, None otherwise
pub async fn get<K: AsRef<[u8]> + Send>(&self, key: K) -> Result<Option<Bytes>, crate::Error> {
self.get_with_options(key, &ReadOptions::default()).await
}
/// Get a value from the transaction with custom read options.
/// This operation will track the read for conflict detection in SSI mode.
///
/// ## Arguments
/// - `key`: the key to get
/// - `options`: the read options to use
///
/// ## Returns
/// - `Result<Option<Bytes>, SlateDBError>`: the value if it exists, None otherwise
pub async fn get_with_options<K: AsRef<[u8]> + Send>(
&self,
key: K,
options: &ReadOptions,
) -> Result<Option<Bytes>, crate::Error> {
self.get_key_value_with_options(key, options)
.await
.map(|kv_opt| kv_opt.map(|kv| kv.value))
}
/// Get a key-value pair from the transaction with default read options.
pub async fn get_key_value<K: AsRef<[u8]> + Send>(
&self,
key: K,
) -> Result<Option<KeyValue>, crate::Error> {
self.get_key_value_with_options(key, &ReadOptions::default())
.await
}
/// Get a key-value pair from the transaction with custom read options.
pub async fn get_key_value_with_options<K: AsRef<[u8]> + Send>(
&self,
key: K,
options: &ReadOptions,
) -> Result<Option<KeyValue>, crate::Error> {
self.db_inner.check_closed()?;
// Track read key for SSI conflict detection if needed
if self.isolation_level == IsolationLevel::SerializableSnapshot {
let key_bytes = Bytes::copy_from_slice(key.as_ref());
let mut read_keys = HashSet::new();
read_keys.insert(key_bytes);
self.txn_manager.track_read_keys(&self.txn_id, read_keys);
}
let db_state = self.db_inner.state.read().view();
// Build the write batch iterator synchronously while holding the read
// guard, avoiding a clone of the full batch. The iterator materializes
// only the entries overlapping the read range (a single key for a
// point get), so this is O(log N) instead of O(N).
let key_slice = key.as_ref();
let range = BytesRange::from_slice(key_slice..=key_slice);
let write_batch_iter = {
let guard = self.write_batch.read();
Some(WriteBatchIterator::new(
&guard,
range,
IterationOrder::Ascending,
u64::MAX,
None,
None,
))
};
let kv = self
.db_inner
.reader
.get_key_value_with_options(
key,
options,
&db_state,
write_batch_iter,
Some(self.started_seq),
)
.await
.map_err(crate::Error::from)?;
Ok(kv)
}
/// Scan a range of keys using the default scan options.
/// This operation will track the read range for conflict detection in SSI mode.
///
/// ## Arguments
/// - `range`: the range of keys to scan
///
/// ## Returns
/// - `Result<DbIterator, SlateDBError>`: An iterator with the results of the scan
pub async fn scan<T>(&self, range: T) -> Result<DbIterator, crate::Error>
where
T: ByteRangeBounds + Send,
{
self.scan_with_options(range, &ScanOptions::default()).await
}
/// Scan a range of keys with the provided options.
/// This operation will track the read range for conflict detection in SSI mode.
///
/// ## Arguments
/// - `range`: the range of keys to scan
/// - `options`: the scan options to use
///
/// ## Returns
/// - `Result<DbIterator, SlateDBError>`: An iterator with the results of the scan
pub async fn scan_with_options<T>(
&self,
range: T,
options: &ScanOptions,
) -> Result<DbIterator, crate::Error>
where
T: ByteRangeBounds + Send,
{
// TODO: this range conversion logic can be extract to an util
let start = range.start_bound().map(Bytes::copy_from_slice);
let end = range.end_bound().map(Bytes::copy_from_slice);
let range = BytesRange::from((start, end));
self.scan_inner(range, options, None).await
}
/// Scan keys that share the provided prefix, restricted to `subrange`,
/// using the default scan options.
/// This operation will track the read range for conflict detection in SSI mode.
///
/// The subrange bounds are key *suffixes* interpreted relative to the
/// prefix: a bound `s` selects the full key `prefix ++ s`. Pass `..` to
/// scan the prefix's entire keyspace.
///
/// ## Arguments
/// - `prefix`: the key prefix to scan
/// - `subrange`: the range of key suffixes (relative to `prefix`) to
/// scan; `..` scans all keys with the prefix
///
/// ## Returns
/// - `Result<DbIterator, SlateDBError>`: An iterator with the results of the scan
pub async fn scan_prefix<P, T>(
&self,
prefix: P,
subrange: T,
) -> Result<DbIterator, crate::Error>
where
P: AsRef<[u8]> + Send,
T: ByteRangeBounds + Send,
{
self.scan_prefix_with_options(prefix, subrange, &ScanOptions::default())
.await
}
/// Scan keys that share the provided prefix, restricted to `subrange`,
/// with custom options. See [`Self::scan_prefix`] for the subrange
/// semantics.
/// This operation will track the read range for conflict detection in SSI mode.
///
/// ## Arguments
/// - `prefix`: the key prefix to scan
/// - `subrange`: the range of key suffixes (relative to `prefix`) to
/// scan; `..` scans all keys with the prefix
/// - `options`: the scan options to use
///
/// ## Returns
/// - `Result<DbIterator, SlateDBError>`: An iterator with the results of the scan
pub async fn scan_prefix_with_options<P, T>(
&self,
prefix: P,
subrange: T,
options: &ScanOptions,
) -> Result<DbIterator, crate::Error>
where
P: AsRef<[u8]> + Send,
T: ByteRangeBounds + Send,
{
let prefix = Bytes::copy_from_slice(prefix.as_ref());
let range = BytesRange::from_prefix_and_subrange(prefix.as_ref(), subrange);
self.scan_inner(range, options, Some(prefix)).await
}
async fn scan_inner(
&self,
range: BytesRange,
options: &ScanOptions,
prefix: Option<Bytes>,
) -> Result<DbIterator, crate::Error> {
// Under SSI, register the *requested* scan range with the transaction
// so that any concurrent write inside it is detected as an
// rw-anti-dependency at commit time — including writes to portions of
// the range that the iterator never yielded (empty scans, partial
// scans, scans whose tombstones were skipped). See
// `DbIteratorRangeTracker` for the rationale.
if self.isolation_level == IsolationLevel::SerializableSnapshot {
let tracker = DbIteratorRangeTracker::new(range.clone());
self.range_trackers.lock().push(tracker);
}
self.db_inner.check_closed()?;
let db_state = self.db_inner.state.read().view();
// Build the write batch iterator synchronously while holding the read
// guard, avoiding a clone of the full batch. The iterator materializes
// only the entries in the scan range.
let write_batch_iter = {
let guard = self.write_batch.read();
Some(WriteBatchIterator::new(
&guard,
range.clone(),
options.order,
u64::MAX,
None,
None,
))
};
self.db_inner
.reader
.scan_with_options(
range,
options,
ScanContext {
db_state: &db_state,
write_batch_iter,
max_seq: Some(self.started_seq),
prefix,
},
)
.await
.map_err(Into::into)
}
/// Put a key-value pair into the transaction.
/// The write will be buffered in the transaction's write batch until commit.
///
/// ## Arguments
/// - `key`: the key to write
/// - `value`: the value to write
///
/// ## Errors
/// - It's not really possible to have error here, since the write operation is
/// buffered in the write batch.
pub fn put<K, V>(&self, key: K, value: V) -> Result<(), crate::Error>
where
K: AsRef<[u8]>,
V: AsRef<[u8]>,
{
self.put_with_options(key, value, &PutOptions::default())
}
/// Put a key-value pair into the transaction with custom options.
/// The write will be buffered in the transaction's write batch until commit.
///
/// ## Arguments
/// - `key`: the key to write
/// - `value`: the value to write
/// - `options`: the put options to use
///
/// ## Errors
/// - It's not really possible to have error here, since the write operation is
/// buffered in the write batch.
pub fn put_with_options<K, V>(
&self,
key: K,
value: V,
options: &PutOptions,
) -> Result<(), crate::Error>
where
K: AsRef<[u8]>,
V: AsRef<[u8]>,
{
self.write_batch
.write()
.put_with_options(key, value, options);
Ok(())
}
/// Mark keys as read for conflict detection.
///
/// This method explicitly tracks read operations for conflict detection. When keys are
/// marked as read, the transaction will detect conflicts if another transaction modifies
/// any of those keys after this transaction started, regardless of the isolation level.
///
/// This allows for selective read-write conflict detection even in Snapshot Isolation mode,
/// where reads are not automatically tracked (unlike `get()` which only tracks reads in SSI
/// mode).
///
/// ## Arguments
/// - `keys`: an iterator of keys to mark as read
///
/// ## Examples
/// ```rust
/// # async fn example() -> Result<(), slatedb::Error> {
/// # use std::sync::Arc;
/// # use slatedb::object_store::memory::InMemory;
/// use slatedb::{Db, IsolationLevel};
///
/// # let object_store = Arc::new(InMemory::new());
/// # let db = Db::open("test_path", object_store).await?;
/// let txn = db.begin(IsolationLevel::Snapshot).await?;
/// txn.mark_read([b"key1", b"key2", b"key3"])?;
/// # Ok(())
/// # }
/// ```
pub fn mark_read<K, I>(&self, keys: I) -> Result<(), crate::Error>
where
K: AsRef<[u8]>,
I: IntoIterator<Item = K>,
{
// Always track reads when explicitly marked, regardless of isolation level.
// The current conflict checking logic always checks the read_keys set
// even in SI mode. The only difference between SI and SSI is whether
// the read keys are tracked in the read set or not.
let read_keys = keys.into_iter().map(|k| Bytes::copy_from_slice(k.as_ref()));
self.txn_manager.track_read_keys(&self.txn_id, read_keys);
Ok(())
}
/// Mark written keys as untracked for conflict detection.
///
/// Keys marked with this method are still written atomically with the rest of the
/// transaction, but are excluded from transaction conflict detection on commit for
/// both this transaction and other transactions.
///
/// This means:
/// - If another transaction reads a key written with an `unmark_write` by this transaction, that key
/// will not cause a read-write conflict.
/// - If another transaction writes a key written with an `unmark_write` by this transaction, that key
/// will not cause a write-write conflict.
///
/// You may call `unmark_write` either before or after writing a key in the transaction.
/// Once a key is unmarked, it cannot be marked again within the same transaction and
/// remains unmarked for the duration of this transaction, even if `put`, `merge`, or
/// `delete` is called on the same key later in the transaction.
///
/// ## Arguments
/// - `keys`: an iterator of keys to exclude from write conflict tracking
///
/// ## Examples
/// ```rust
/// # async fn example() -> Result<(), slatedb::Error> {
/// # use std::sync::Arc;
/// # use slatedb::object_store::memory::InMemory;
/// use slatedb::{Db, IsolationLevel};
///
/// # let object_store = Arc::new(InMemory::new());
/// # let db = Db::open("test_path", object_store).await?;
/// let txn = db.begin(IsolationLevel::Snapshot).await?;
/// txn.put(b"counter", b"1")?;
/// txn.unmark_write([b"counter"])?;
/// txn.put(b"counter", b"2")?;
/// txn.commit().await?;
/// # Ok(())
/// # }
/// ```
pub fn unmark_write<K, I>(&self, keys: I) -> Result<(), crate::Error>
where
K: AsRef<[u8]>,
I: IntoIterator<Item = K>,
{
let mut untracked_keys = self.untracked_write_keys.write();
untracked_keys.extend(keys.into_iter().map(|k| Bytes::copy_from_slice(k.as_ref())));
Ok(())
}
/// Merge a key-value pair into the transaction.
///
/// ## Errors
/// - `Error`: if no merge operator is configured for the database.
pub fn merge<K, V>(&self, key: K, value: V) -> Result<(), crate::Error>
where
K: AsRef<[u8]>,
V: AsRef<[u8]>,
{
self.merge_with_options(key, value, &MergeOptions::default())
}
/// Merge a key-value pair into the transaction with custom options.
///
/// ## Errors
/// - `Error`: if no merge operator is configured for the database.
pub fn merge_with_options<K, V>(
&self,
key: K,
value: V,
options: &MergeOptions,
) -> Result<(), crate::Error>
where
K: AsRef<[u8]>,
V: AsRef<[u8]>,
{
if self.db_inner.flush_merge_operator.is_none() {
return Err(SlateDBError::MergeOperatorMissing.into());
}
self.write_batch
.write()
.merge_with_options(key, value, options);
Ok(())
}
/// Delete a key from the transaction.
/// The delete will be buffered in the transaction's write batch until commit.
///
/// ## Arguments
/// - `key`: the key to delete
///
/// ## Errors
/// - It's not really possible to have error here, since the delete operation is
/// buffered in the write batch.
pub fn delete<K: AsRef<[u8]>>(&self, key: K) -> Result<(), crate::Error> {
self.write_batch.write().delete(key);
Ok(())
}
/// Commit the transaction by applying all buffered operations to the database.
///
/// This method finalizes the transaction by writing all pending puts, deletes, and other
/// operations from the write batch to persistent storage. The actual conflict detection
/// (including read-write and write-write conflicts) is deferred to the task that processes
/// the WriteBatch, which ensures the atomicity of transactions.
///
/// If the transaction's write batch is empty, this operation is a no-op and returns `Ok(())`
/// immediately without any database interaction. Since it's impossible to have read-write
/// conflict, neither write-write conflict for an empty write batch.
///
/// ## Returns
/// - `Ok(Some(WriteHandle))` if the commit is successful and there are writes in the batch.
/// - `Ok(None)` if the commit is successful but the write batch is empty (no-op).
///
/// ## Errors
/// - Returns `Error` if the commit operation fails, which could be due to:
/// - Database I/O errors
/// - Concurrency conflicts detected during WriteBatch processing
pub async fn commit(self) -> Result<Option<WriteHandle>, crate::Error> {
self.commit_with_options(&WriteOptions::default()).await
}
/// Commit the transaction with custom write options.
///
/// This method behaves the same as [`DbTransaction::commit`], but allows callers
/// to specify custom [`WriteOptions`], such as `await_durable`.
///
/// ## Arguments
/// - `options`: the write options to use for the commit
///
/// ## Returns
/// - `Ok(Some(WriteHandle))` if the commit is successful and there are writes in the batch.
/// - `Ok(None)` if the commit is successful but the write batch is empty (no-op).
///
/// ## Errors
/// - Returns `Error` if the commit operation fails, which could be due to:
/// - Database I/O errors
/// - Concurrency conflicts detected during WriteBatch processing
pub async fn commit_with_options(
self,
options: &WriteOptions,
) -> Result<Option<WriteHandle>, crate::Error> {
// Take the write_batch for submission to the database.
let write_batch = self.write_batch.read().clone();
// Materialize the SSI read-range dependencies the transaction
// accumulated during scans. Each tracker carries the requested scan
// range; the conflict check in `TransactionManager` will then catch
// any committed write whose key falls inside it.
if self.isolation_level == IsolationLevel::SerializableSnapshot {
for tracker in self.range_trackers.lock().iter() {
self.txn_manager
.track_read_range(&self.txn_id, tracker.get_range());
}
}
// If the WriteBatch is empty, it's a no-op or read-only batch.
if write_batch.is_empty() {
// Check for read conflicts before returning Ok(None).
if self.txn_manager.check_has_conflict(&self.txn_id) {
return Err(SlateDBError::TransactionConflict.into());
}
return Ok(None);
}
// Track only write keys that were not explicitly unmarked.
let tracked_write_keys = {
let untracked_write_keys = self.untracked_write_keys.read();
write_batch
.keys()
.into_iter()
.filter(|key| !untracked_write_keys.contains(key))
.collect()
};
self.txn_manager
.track_write_keys(&self.txn_id, &tracked_write_keys);
// Submit the WriteBatch to the database for processing. The batch is sent to a
// dedicated background task (in batch_write.rs) that processes all WriteBatches
// sequentially, ensuring no concurrent writes. Both conflict checking & persisting
// are handled there.
let db_inner = Arc::clone(&self.db_inner);
db_inner
.write_with_options(write_batch, options, Some(self))
.await
.map(Some)
.map_err(Into::into)
}
/// Rollback the transaction by discarding all buffered operations.
/// This is automatically called when the transaction is dropped.
pub fn rollback(self) {
// do nothing, trigger the Drop of the transaction
}
/// Get the sequence number this transaction was started at. This is equivalent to
/// the snapshot sequence number for this transaction, which determines data visibility
/// for reads in this transaction.
pub fn seqnum(&self) -> u64 {
self.started_seq
}
/// Get the transaction ID. This is a unique identifier for this transaction, generated
/// by the transaction manager.
pub fn id(&self) -> Uuid {
self.txn_id
}
}
#[async_trait::async_trait]
impl DbReadOps for DbTransaction {
async fn get_with_options<K: AsRef<[u8]> + Send>(
&self,
key: K,
options: &ReadOptions,
) -> Result<Option<Bytes>, crate::Error> {
DbTransaction::get_with_options(self, key, options).await
}
async fn get_key_value_with_options<K: AsRef<[u8]> + Send>(
&self,
key: K,
options: &ReadOptions,
) -> Result<Option<KeyValue>, crate::Error> {
DbTransaction::get_key_value_with_options(self, key, options).await
}
async fn scan_with_options<T>(
&self,
range: T,
options: &ScanOptions,
) -> Result<DbIterator, crate::Error>
where
T: ByteRangeBounds + Send,
{
DbTransaction::scan_with_options(self, range, options).await
}
async fn scan_prefix_with_options<P, T>(
&self,
prefix: P,
subrange: T,
options: &ScanOptions,
) -> Result<DbIterator, crate::Error>
where
P: AsRef<[u8]> + Send,
T: ByteRangeBounds + Send,
{
DbTransaction::scan_prefix_with_options(self, prefix, subrange, options).await
}
}
#[async_trait::async_trait]
impl DbTransactionOps for DbTransaction {
fn put_with_options<K, V>(
&self,
key: K,
value: V,
options: &PutOptions,
) -> Result<(), crate::Error>
where
K: AsRef<[u8]>,
V: AsRef<[u8]>,
{
DbTransaction::put_with_options(self, key, value, options)
}
fn delete<K: AsRef<[u8]>>(&self, key: K) -> Result<(), crate::Error> {
DbTransaction::delete(self, key)
}
fn merge_with_options<K, V>(
&self,
key: K,
value: V,
options: &MergeOptions,
) -> Result<(), crate::Error>
where
K: AsRef<[u8]>,
V: AsRef<[u8]>,
{
DbTransaction::merge_with_options(self, key, value, options)
}
fn mark_read<K, I>(&self, keys: I) -> Result<(), crate::Error>
where
K: AsRef<[u8]>,
I: IntoIterator<Item = K>,
{
DbTransaction::mark_read(self, keys)
}
fn unmark_write<K, I>(&self, keys: I) -> Result<(), crate::Error>
where
K: AsRef<[u8]>,
I: IntoIterator<Item = K>,
{
DbTransaction::unmark_write(self, keys)
}
fn seqnum(&self) -> u64 {
DbTransaction::seqnum(self)
}
fn id(&self) -> Uuid {
DbTransaction::id(self)
}
async fn commit_with_options(
self,
options: &WriteOptions,
) -> Result<Option<WriteHandle>, crate::Error>
where
Self: Sized + Send,
{
DbTransaction::commit_with_options(self, options).await
}
fn rollback(self)
where
Self: Sized,
{
DbTransaction::rollback(self)
}
}
/// Unregister from transaction manager when dropped.
/// If the transaction hasn't been committed, it's considered rolled back.
impl Drop for DbTransaction {
fn drop(&mut self) {
self.txn_manager.drop_txn(&self.txn_id);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::MetricLevel;
use crate::merge_operator::{MergeOperator, MergeOperatorError};
use crate::object_store::memory::InMemory;
use rstest::rstest;
use std::sync::Arc;
struct CounterMergeOperator;
impl MergeOperator for CounterMergeOperator {
fn merge(
&self,
_key: &Bytes,
existing_value: Option<Bytes>,
value: Bytes,
) -> Result<Bytes, MergeOperatorError> {
let existing = existing_value
.map(|v| u64::from_le_bytes(v.as_ref().try_into().unwrap()))
.unwrap_or(0);
let operand = u64::from_le_bytes(value.as_ref().try_into().unwrap());
Ok(Bytes::copy_from_slice(&(existing + operand).to_le_bytes()))
}
fn merge_batch(
&self,
_key: &Bytes,
existing_value: Option<Bytes>,
operands: &[Bytes],
) -> Result<Bytes, MergeOperatorError> {
let mut total = existing_value
.map(|v| u64::from_le_bytes(v.as_ref().try_into().unwrap()))
.unwrap_or(0);
for operand in operands {
total += u64::from_le_bytes(operand.as_ref().try_into().unwrap());
}
Ok(Bytes::copy_from_slice(&total.to_le_bytes()))
}
}
#[tokio::test]
async fn test_txn_basic_visibility() {
// Setup database with initial data
let object_store: Arc<dyn object_store::ObjectStore> = Arc::new(InMemory::new());
let db = crate::Db::open("test_db", object_store).await.unwrap();
// Put initial data
db.put(b"k1", b"v1").await.unwrap();
// Begin transaction
let txn = db.begin(IsolationLevel::Snapshot).await.unwrap();
// Put data from others
db.put(b"k2", b"v2").await.unwrap();
// Read within transaction - should see the initial data
let value = txn.get(b"k1").await.unwrap();
assert_eq!(value, Some(Bytes::from_static(b"v1")));
// Commit transaction
txn.commit().await.unwrap();
}
#[tokio::test]
async fn test_txn_write_visibility_in_txn() {
// Setup database with initial data
let object_store: Arc<dyn object_store::ObjectStore> = Arc::new(InMemory::new());
let db = crate::Db::open("test_db", object_store).await.unwrap();
// Put initial data
db.put(b"k1", b"v1").await.unwrap();
// Begin transaction
let txn = db
.begin(IsolationLevel::SerializableSnapshot)
.await
.unwrap();
// Write within transaction
txn.put(b"k1", b"v2").unwrap();
// Read within transaction - should see the updated value in the transaction
let value = txn.get(b"k1").await.unwrap();
assert_eq!(value, Some(Bytes::from_static(b"v2")));
// Commit transaction
txn.commit().await.unwrap();
}
#[tokio::test]
async fn test_txn_si_commit_conflict() {
// Setup database with initial data
let object_store: Arc<dyn object_store::ObjectStore> = Arc::new(InMemory::new());
let db = crate::Db::open("test_db", object_store).await.unwrap();
// Put initial data
db.put(b"k1", b"v1").await.unwrap();
// Begin first transaction
let txn1 = db.begin(IsolationLevel::Snapshot).await.unwrap();
txn1.put(b"k1", b"v2").unwrap();
// Begin second transaction
let txn2 = db.begin(IsolationLevel::Snapshot).await.unwrap();
txn2.put(b"k1", b"v3").unwrap();
// Commit first transaction - should succeed
txn1.commit().await.unwrap();
// Commit second transaction - should fail due to conflict
let result = txn2.commit().await;
assert!(result.is_err());
}
#[tokio::test]
async fn test_txn_si_commit_conflict_with_db_writes() {
// Setup database with initial data
let object_store: Arc<dyn object_store::ObjectStore> = Arc::new(InMemory::new());
let db = crate::Db::open("test_db", object_store).await.unwrap();
// Put initial data
db.put(b"k1", b"v1").await.unwrap();
// Begin first transaction
let txn1 = db.begin(IsolationLevel::Snapshot).await.unwrap();
txn1.put(b"k1", b"v2").unwrap();
// DB put on the same key
db.put(b"k1", b"v3").await.unwrap();
// Commit transaction - should conflict
let result = txn1.commit().await;
assert!(result.is_err());
}
#[tokio::test]
async fn test_txn_ssi_commit_conflict() {
// Setup database with initial data
let object_store: Arc<dyn object_store::ObjectStore> = Arc::new(InMemory::new());
let db = crate::Db::open("test_db", object_store).await.unwrap();
// Put initial data
db.put(b"k1", b"v1").await.unwrap();
db.put(b"k2", b"v2.1").await.unwrap();
// Begin first transaction
let txn1 = db
.begin(IsolationLevel::SerializableSnapshot)
.await
.unwrap();
txn1.put(b"k1", b"v2").unwrap();
txn1.put(b"k2", b"v2.2").unwrap();
// Begin second transaction
let txn2 = db
.begin(IsolationLevel::SerializableSnapshot)
.await
.unwrap();
let val2 = txn2.get(b"k2").await.unwrap();
assert_eq!(val2, Some(Bytes::from_static(b"v2.1")));
txn2.put(b"k3", b"v3").unwrap();
// Commit first transaction - should succeed
txn1.commit().await.unwrap();
// Commit second transaction - should fail due to conflict for reading k2
let result = txn2.commit().await;
assert!(result.is_err());
}
#[tokio::test]
async fn test_txn_ssi_commit_conflit_with_ranges() {
// Setup database with initial data
let object_store: Arc<dyn object_store::ObjectStore> = Arc::new(InMemory::new());
let db = crate::Db::open("test_db", object_store).await.unwrap();
// Put initial data
db.put(b"k1", b"v1").await.unwrap();
db.put(b"k2", b"v2.1").await.unwrap();
db.put(b"k3", b"v3").await.unwrap();
// Begin first transaction
let txn1 = db
.begin(IsolationLevel::SerializableSnapshot)
.await
.unwrap();
// Begin second transaction
let txn2 = db
.begin(IsolationLevel::SerializableSnapshot)
.await
.unwrap();
// Transaction 2 scans k2..k3
{
let mut iter = txn2.scan(&b"k2"[..]..=&b"k3"[..]).await.unwrap();
while let Some(_kv) = iter.next().await.unwrap() {
// Just iterate through the range to track it
}
}
// Transaction 1 writes within the range that transaction 2 scanned
txn1.put(b"k2", b"v2.2").unwrap();
txn1.commit().await.unwrap();
// Transaction 2 tries to write something
txn2.put(b"k4", b"v4").unwrap();
// Commit second transaction - should fail due to phantom conflict
// because it read a range that was modified by transaction 1
let result = txn2.commit().await;
assert!(result.is_err());
}
/// Two SSI transactions each scan a disjoint range that is empty at the
/// snapshot, then each writes a key inside the *other* transaction's
/// scanned range. Under a correct SSI implementation exactly one of the
/// two must abort: the requested-but-empty scan ranges create
/// rw-anti-dependencies in both directions, and no serial order is
/// consistent with both reads. Regression: previously the range tracker
/// only recorded yielded keys, so an empty scan registered no range and
/// both txns committed (write skew).
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_txn_ssi_write_skew_via_empty_scans() {
let object_store: Arc<dyn object_store::ObjectStore> = Arc::new(InMemory::new());
let db = crate::Db::open("test_db", object_store).await.unwrap();
// Seed a key well outside both scan ranges so neither scan sees it.
db.put(b"~outside_both_ranges", b"v").await.unwrap();
db.flush().await.unwrap();
let txn1 = db
.begin(IsolationLevel::SerializableSnapshot)
.await
.unwrap();
let txn2 = db
.begin(IsolationLevel::SerializableSnapshot)
.await
.unwrap();
// T1 scans [a..m); empty.
{
let mut iter = txn1.scan(&b"a"[..]..&b"m"[..]).await.unwrap();
assert!(iter.next().await.unwrap().is_none(), "[a..m) is empty");
}
// T2 scans [n..z); empty.
{
let mut iter = txn2.scan(&b"n"[..]..&b"z"[..]).await.unwrap();
assert!(iter.next().await.unwrap().is_none(), "[n..z) is empty");
}
// Each writes into the other's scan range.
txn1.put(b"x_from_t1", b"v1").unwrap();
txn2.put(b"b_from_t2", b"v2").unwrap();
let r1 = txn1.commit().await;
let r2 = txn2.commit().await;
// Exactly one of the two must be rejected as a TransactionConflict.
assert!(
r1.is_ok() ^ r2.is_ok(),
"expected exactly one commit to abort, got r1={r1:?}, r2={r2:?}",
);
}
/// A scan over a wide range that yields a single key in the middle still
/// observes the entire requested range, so a concurrent write into the
/// unobserved portion is a phantom. Regression: previously the tracker
/// only recorded `[yielded_first, yielded_last]`, so a write outside that
/// bounding box but inside the requested range was missed.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_txn_ssi_phantom_outside_yielded_bbox() {
let object_store: Arc<dyn object_store::ObjectStore> = Arc::new(InMemory::new());
let db = crate::Db::open("test_db", object_store).await.unwrap();
db.put(b"k_mid", b"seed").await.unwrap();
db.flush().await.unwrap();
let txn1 = db
.begin(IsolationLevel::SerializableSnapshot)
.await
.unwrap();
// Scan [k_aaa..k_zzz); only k_mid is in range, so the yielded bbox
// collapses to (k_mid, k_mid) under the old tracker.
{
let mut iter = txn1.scan(&b"k_aaa"[..]..&b"k_zzz"[..]).await.unwrap();
let kv = iter.next().await.unwrap().expect("k_mid present");
assert_eq!(kv.key.as_ref(), b"k_mid");
assert!(iter.next().await.unwrap().is_none(), "only k_mid in range");
}
// Concurrent non-txn writer inserts a key inside T1's requested range
// but outside the yielded bbox.
db.put(b"k_aaa_inserted", b"phantom").await.unwrap();
// T1 makes a write so commit triggers SSI conflict checks.
txn1.put(b"t1_marker", b"x").unwrap();
assert!(txn1.commit().await.is_err());
}
/// A tombstone that sits inside a scan's requested range causes
/// `DbIterator::next_entry` to skip the key, so the caller sees an
/// "absent" observation. A concurrent resurrect of that key is therefore
/// a phantom. Regression: the old tracker only saw yielded keys, so
/// tombstone-only ranges registered no read dependency at all.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_txn_ssi_tombstone_resurrection_in_scan_range() {
let object_store: Arc<dyn object_store::ObjectStore> = Arc::new(InMemory::new());
let db = crate::Db::open("test_db", object_store).await.unwrap();
db.put(b"k_deleted", b"v_orig").await.unwrap();
db.flush().await.unwrap();
db.delete(b"k_deleted").await.unwrap();
db.flush().await.unwrap();
let txn1 = db
.begin(IsolationLevel::SerializableSnapshot)
.await
.unwrap();
{
let mut iter = txn1.scan(&b"k_a"[..]..&b"k_z"[..]).await.unwrap();
assert!(
iter.next().await.unwrap().is_none(),
"tombstone in range should make scan appear empty to caller",
);
}
// Concurrent (non-txn) writer resurrects the exact key T1 observed
// as absent.
db.put(b"k_deleted", b"resurrected").await.unwrap();
txn1.put(b"t1_marker", b"x").unwrap();
assert!(txn1.commit().await.is_err());
}
/// `scan_prefix` shares the same range-tracking machinery as `scan`, so
/// the empty-prefix-scan blind spot is the same anomaly: a "first
/// writer" gate based on an empty prefix scan must abort when another
/// writer races in. Regression: previously an empty prefix scan tracked
/// no range and both writers committed.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_txn_ssi_empty_scan_prefix_detects_concurrent_insert() {
let object_store: Arc<dyn object_store::ObjectStore> = Arc::new(InMemory::new());
let db = crate::Db::open("test_db", object_store).await.unwrap();
db.put(b"sentinel", b"x").await.unwrap();
db.flush().await.unwrap();
let txn1 = db
.begin(IsolationLevel::SerializableSnapshot)
.await
.unwrap();
{
let mut iter = txn1.scan_prefix(b"users/", ..).await.unwrap();
assert!(iter.next().await.unwrap().is_none(), "no users yet");
}
// Concurrent writer races T1 and creates the first user.
db.put(b"users/alice", b"first").await.unwrap();
txn1.put(b"users/bob", b"second").unwrap();
assert!(txn1.commit().await.is_err());
}
/// A `scan_prefix` with a bounded subrange must register exactly the
/// composed range for SSI conflict detection: a concurrent write inside
/// the subrange aborts the transaction even if never yielded, while a
/// write under the same prefix but outside the subrange does not.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_txn_ssi_scan_prefix_subrange_tracks_composed_range() {
let object_store: Arc<dyn object_store::ObjectStore> = Arc::new(InMemory::new());
let db = crate::Db::open("test_db", object_store).await.unwrap();
db.put(b"users/m_mallory", b"v").await.unwrap();
db.flush().await.unwrap();
// A write under the prefix but before the subrange start is not a
// conflict: the tracked range starts at users/m, not users/.
let txn1 = db
.begin(IsolationLevel::SerializableSnapshot)
.await
.unwrap();
{
let mut iter = txn1
.scan_prefix(b"users/", b"m".as_slice()..)
.await
.unwrap();
let kv = iter.next().await.unwrap().expect("mallory in subrange");
assert_eq!(kv.key.as_ref(), b"users/m_mallory");
assert!(iter.next().await.unwrap().is_none());
}
db.put(b"users/alice", b"outside subrange").await.unwrap();
txn1.put(b"t1_marker", b"x").unwrap();
txn1.commit()
.await
.expect("write under prefix but outside subrange must not conflict");
// A write inside the subrange is a phantom even though the scan never
// yielded it.
let txn2 = db
.begin(IsolationLevel::SerializableSnapshot)
.await
.unwrap();
{
let mut iter = txn2
.scan_prefix(b"users/", b"m".as_slice()..)
.await
.unwrap();
let kv = iter.next().await.unwrap().expect("mallory in subrange");
assert_eq!(kv.key.as_ref(), b"users/m_mallory");
assert!(iter.next().await.unwrap().is_none());
}
db.put(b"users/zach", b"inside subrange").await.unwrap();
txn2.put(b"t2_marker", b"x").unwrap();
assert!(
txn2.commit().await.is_err(),
"write inside the subrange must abort the transaction"
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_txn_commit_await_durable_false() {
use crate::config::{DurabilityLevel::*, ReadOptions, WriteOptions};
use fail_parallel::FailPointRegistry;
// Setup database with failpoints to pause durable writes
let fp_registry = Arc::new(FailPointRegistry::new());
let object_store: Arc<dyn object_store::ObjectStore> = Arc::new(InMemory::new());
let db = crate::Db::builder("/tmp/test_txn_commit_await_durable_false", object_store)
.with_fp_registry(fp_registry.clone())
.build()
.await
.unwrap();
// Pause durable writes to object storage
fail_parallel::cfg(fp_registry.clone(), "write-wal-sst-io-error", "pause").unwrap();
// Begin a transaction and write a key
let txn = db.begin(IsolationLevel::Snapshot).await.unwrap();
txn.put(b"k", b"v").unwrap();
// Commit without waiting for durability
txn.commit_with_options(&WriteOptions {
await_durable: false,
..Default::default()
})
.await
.unwrap();
// Memory (in-memory) read should see the value
let val = db
.get_with_options(b"k", &ReadOptions::new().with_durability_filter(Memory))
.await
.unwrap();
assert_eq!(val, Some(Bytes::from_static(b"v")));
// Remote (durable) read should not see the value yet
let val = db
.get_with_options(b"k", &ReadOptions::new().with_durability_filter(Remote))
.await
.unwrap();
assert_eq!(val, None);
// Clean up
fail_parallel::cfg(fp_registry.clone(), "write-wal-sst-io-error", "off").unwrap();
db.close().await.unwrap();
}
// Transaction test structures for table-driven tests
#[derive(Debug, Clone)]
struct TransactionTestCase {
name: &'static str,
isolation_level: IsolationLevel,
initial_data: Vec<(Bytes, Bytes)>,
operations: Vec<TransactionTestOp>,
expected_results: Vec<TransactionTestOpResult>,
}
#[derive(Debug, Clone)]
#[allow(dead_code)]
enum TransactionTestOp {
TxnGet(Bytes),
TxnScan(Bytes, Bytes),
TxnPut(Bytes, Bytes),
TxnDelete(Bytes),
TxnMarkRead(Bytes),
TxnCommit,
TxnRollback,
DbPut(Bytes, Bytes),
DbGet(Bytes),
}
#[derive(Debug, Clone, PartialEq)]
enum TransactionTestOpResult {
Got(Option<Bytes>),
Scanned(Vec<Bytes>),
Empty,
Conflicted,
Invalid,
}
async fn execute_transaction_test_ops(
db: crate::Db,
operations: Vec<TransactionTestOp>,
initial_data: Vec<(Bytes, Bytes)>,
isolation_level: IsolationLevel,
) -> Vec<TransactionTestOpResult> {
// Setup initial data
for (key, value) in initial_data {
db.put(key, value).await.unwrap();
}
let mut txn_opt = Some(db.begin(isolation_level).await.unwrap());
let mut results = Vec::new();
for operation in operations.iter() {
let result = match (txn_opt.as_mut(), operation) {
// Transaction operations with active transaction
(Some(txn), TransactionTestOp::TxnGet(key)) => {
let val = txn.get(key).await.unwrap();
TransactionTestOpResult::Got(val)
}
(Some(txn), TransactionTestOp::TxnScan(start, end)) => {
let mut iter = txn.scan(&start[..]..=&end[..]).await.unwrap();
let mut scanned_keys = Vec::new();
while let Some(kv) = iter.next().await.unwrap() {
scanned_keys.push(kv.key);
}
TransactionTestOpResult::Scanned(scanned_keys)
}
(Some(txn), TransactionTestOp::TxnPut(key, value)) => {
txn.put(key, value).unwrap();
TransactionTestOpResult::Empty
}
(Some(txn), TransactionTestOp::TxnDelete(key)) => {
txn.delete(key).unwrap();
TransactionTestOpResult::Empty
}
(Some(txn), TransactionTestOp::TxnMarkRead(key)) => {
txn.mark_read([key]).unwrap();
TransactionTestOpResult::Empty
}
(Some(_txn), TransactionTestOp::TxnCommit) => {
let txn = txn_opt.take().unwrap();
match txn.commit().await {
Ok(_) => TransactionTestOpResult::Empty,
Err(_) => TransactionTestOpResult::Conflicted,
}
}
(Some(_txn), TransactionTestOp::TxnRollback) => {
let txn = txn_opt.take().unwrap();
txn.rollback();
TransactionTestOpResult::Empty
}
// Database operations
(_, TransactionTestOp::DbPut(key, value)) => {
db.put(key, value).await.unwrap();
TransactionTestOpResult::Empty
}
(_, TransactionTestOp::DbGet(key)) => {
let val = db.get(key).await.unwrap();
TransactionTestOpResult::Got(val)
}
// Invalid operations (transaction operations without active transaction)
(None, TransactionTestOp::TxnGet(_))
| (None, TransactionTestOp::TxnScan(_, _))
| (None, TransactionTestOp::TxnPut(_, _))
| (None, TransactionTestOp::TxnDelete(_))
| (None, TransactionTestOp::TxnMarkRead(_))
| (None, TransactionTestOp::TxnCommit)
| (None, TransactionTestOp::TxnRollback) => TransactionTestOpResult::Invalid,
};
results.push(result);
}
results
}
// Table-driven tests using rstest
#[rstest]
#[case::ssi_basic_visibility(
TransactionTestCase {
name: "ssi_basic_visibility",
isolation_level: IsolationLevel::SerializableSnapshot,
initial_data: vec![(Bytes::from("k1"), Bytes::from("v1"))],
operations: vec![
TransactionTestOp::TxnGet(Bytes::from("k1")),
TransactionTestOp::TxnCommit,
],
expected_results: vec![
TransactionTestOpResult::Got(Some(Bytes::from("v1"))),
TransactionTestOpResult::Empty,
]
}
)]
#[case::ssi_write_visibility_in_txn(
TransactionTestCase {
name: "ssi_write_visibility_in_txn",
isolation_level: IsolationLevel::SerializableSnapshot,
initial_data: vec![(Bytes::from("k1"), Bytes::from("v1"))],
operations: vec![
TransactionTestOp::TxnPut(Bytes::from("k1"), Bytes::from("v2")),
TransactionTestOp::TxnGet(Bytes::from("k1")),
TransactionTestOp::TxnCommit,
],
expected_results: vec![
TransactionTestOpResult::Empty,
TransactionTestOpResult::Got(Some(Bytes::from("v2"))),
TransactionTestOpResult::Empty,
]
}
)]
#[case::ssi_delete_visibility_in_txn(
TransactionTestCase {
name: "ssi_delete_visibility_in_txn",
isolation_level: IsolationLevel::SerializableSnapshot,
initial_data: vec![(Bytes::from("k1"), Bytes::from("v1"))],
operations: vec![
TransactionTestOp::TxnDelete(Bytes::from("k1")),
TransactionTestOp::TxnGet(Bytes::from("k1")),
TransactionTestOp::TxnCommit,
],
expected_results: vec![
TransactionTestOpResult::Empty,
TransactionTestOpResult::Got(None),
TransactionTestOpResult::Empty,
]
}
)]
#[case::ssi_rollback_visibility(
TransactionTestCase {
name: "ssi_rollback_visibility",
isolation_level: IsolationLevel::SerializableSnapshot,
initial_data: vec![(Bytes::from("k1"), Bytes::from("v1"))],
operations: vec![
TransactionTestOp::TxnPut(Bytes::from("k1"), Bytes::from("v2")),
TransactionTestOp::TxnRollback,
TransactionTestOp::DbGet(Bytes::from("k1")),
],
expected_results: vec![
TransactionTestOpResult::Empty,
TransactionTestOpResult::Empty,
TransactionTestOpResult::Got(Some(Bytes::from("v1"))),
]
}
)]
#[case::si_concurrent_read_snapshot(
TransactionTestCase {
name: "si_concurrent_read_snapshot",
isolation_level: IsolationLevel::Snapshot,
initial_data: vec![(Bytes::from("k1"), Bytes::from("v1"))],
operations: vec![
TransactionTestOp::DbPut(Bytes::from("k1"), Bytes::from("v2")),
TransactionTestOp::TxnGet(Bytes::from("k1")),
TransactionTestOp::TxnCommit,
],
expected_results: vec![
TransactionTestOpResult::Empty,
TransactionTestOpResult::Got(Some(Bytes::from("v1"))),
TransactionTestOpResult::Empty,
]
}
)]
#[case::ssi_write_write_conflict(
TransactionTestCase {
name: "ssi_write_write_conflict",
isolation_level: IsolationLevel::SerializableSnapshot,
initial_data: vec![(Bytes::from("k1"), Bytes::from("v1"))],
operations: vec![
TransactionTestOp::TxnPut(Bytes::from("k1"), Bytes::from("v2")),
TransactionTestOp::DbPut(Bytes::from("k1"), Bytes::from("v3")),
TransactionTestOp::TxnCommit,
],
expected_results: vec![
TransactionTestOpResult::Empty,
TransactionTestOpResult::Empty,
TransactionTestOpResult::Conflicted,
]
}
)]
#[case::ssi_read_write_conflict(
TransactionTestCase {
name: "ssi_read_write_conflict",
isolation_level: IsolationLevel::SerializableSnapshot,
initial_data: vec![(Bytes::from("k1"), Bytes::from("v1"))],
operations: vec![
TransactionTestOp::TxnGet(Bytes::from("k1")),
TransactionTestOp::DbPut(Bytes::from("k1"), Bytes::from("v1")),
TransactionTestOp::TxnPut(Bytes::from("k2"), Bytes::from("v2.1")),
TransactionTestOp::TxnCommit,
],
expected_results: vec![
TransactionTestOpResult::Got(Some(Bytes::from("v1"))),
TransactionTestOpResult::Empty,
TransactionTestOpResult::Empty,
TransactionTestOpResult::Conflicted,
]
}
)]
#[case::si_read_write_no_conflict(
TransactionTestCase {
name: "si_read_write_no_conflict",
isolation_level: IsolationLevel::Snapshot,
initial_data: vec![(Bytes::from("k1"), Bytes::from("v1"))],
operations: vec![
TransactionTestOp::TxnGet(Bytes::from("k1")),
TransactionTestOp::DbPut(Bytes::from("k1"), Bytes::from("v2")),
TransactionTestOp::TxnCommit,
],
expected_results: vec![
TransactionTestOpResult::Got(Some(Bytes::from("v1"))),
TransactionTestOpResult::Empty,
TransactionTestOpResult::Empty,
]
}
)]
#[case::ssi_write_read_conflict(
TransactionTestCase {
name: "ssi_write_read_conflict",
isolation_level: IsolationLevel::SerializableSnapshot,
initial_data: vec![(Bytes::from("k1"), Bytes::from("v1"))],
operations: vec![
TransactionTestOp::DbPut(Bytes::from("k1"), Bytes::from("v2")),
TransactionTestOp::TxnGet(Bytes::from("k1")),
TransactionTestOp::TxnPut(Bytes::from("k3"), Bytes::from("v3")),
TransactionTestOp::TxnCommit,
],
expected_results: vec![
TransactionTestOpResult::Empty,
TransactionTestOpResult::Got(Some(Bytes::from("v1"))),
TransactionTestOpResult::Empty,
TransactionTestOpResult::Conflicted,
]
}
)]
#[case::si_write_read_no_conflict(
TransactionTestCase {
name: "si_write_read_no_conflict",
isolation_level: IsolationLevel::Snapshot,
initial_data: vec![(Bytes::from("k1"), Bytes::from("v1"))],
operations: vec![
TransactionTestOp::DbPut(Bytes::from("k1"), Bytes::from("v2")),
TransactionTestOp::TxnGet(Bytes::from("k1")),
TransactionTestOp::TxnCommit,
],
expected_results: vec![
TransactionTestOpResult::Empty,
TransactionTestOpResult::Got(Some(Bytes::from("v1"))),
TransactionTestOpResult::Empty,
]
}
)]
#[case::ssi_range_write_conflict(
TransactionTestCase {
name: "ssi_range_write_conflict",
isolation_level: IsolationLevel::SerializableSnapshot,
initial_data: vec![
(Bytes::from("k1"), Bytes::from("v1")),
(Bytes::from("k2"), Bytes::from("v2")),
(Bytes::from("k3"), Bytes::from("v3")),
(Bytes::from("k4"), Bytes::from("v4")),
(Bytes::from("k5"), Bytes::from("v5"))
],
operations: vec![
TransactionTestOp::TxnScan(Bytes::from("k1"), Bytes::from("k5")),
TransactionTestOp::DbPut(Bytes::from("k3"), Bytes::from("v3_new")),
TransactionTestOp::TxnPut(Bytes::from("k100"), Bytes::from("v100")),
TransactionTestOp::TxnCommit,
],
expected_results: vec![
TransactionTestOpResult::Scanned(vec![Bytes::from("k1"), Bytes::from("k2"), Bytes::from("k3"), Bytes::from("k4"), Bytes::from("k5")]),
TransactionTestOpResult::Empty,
TransactionTestOpResult::Empty,
TransactionTestOpResult::Conflicted,
]
}
)]
#[case::si_range_write_no_conflict(
TransactionTestCase {
name: "si_range_write_no_conflict",
isolation_level: IsolationLevel::Snapshot,
initial_data: vec![
(Bytes::from("k1"), Bytes::from("v1")),
(Bytes::from("k2"), Bytes::from("v2")),
(Bytes::from("k3"), Bytes::from("v3")),
(Bytes::from("k4"), Bytes::from("v4")),
(Bytes::from("k5"), Bytes::from("v5"))
],
operations: vec![
TransactionTestOp::TxnScan(Bytes::from("k1"), Bytes::from("k5")),
TransactionTestOp::DbPut(Bytes::from("k3"), Bytes::from("v3_new")),
TransactionTestOp::TxnPut(Bytes::from("k100"), Bytes::from("v100")),
TransactionTestOp::TxnCommit,
],
expected_results: vec![
TransactionTestOpResult::Scanned(vec![Bytes::from("k1"), Bytes::from("k2"), Bytes::from("k3"), Bytes::from("k4"), Bytes::from("k5")]),
TransactionTestOpResult::Empty,
TransactionTestOpResult::Empty,
TransactionTestOpResult::Empty,
]
}
)]
#[case::ssi_mark_read_conflict(
TransactionTestCase {
name: "ssi_mark_read_conflict",
isolation_level: IsolationLevel::SerializableSnapshot,
initial_data: vec![(Bytes::from("k1"), Bytes::from("v1"))],
operations: vec![
TransactionTestOp::TxnMarkRead(Bytes::from("k1")),
TransactionTestOp::DbPut(Bytes::from("k1"), Bytes::from("v2")),
TransactionTestOp::TxnPut(Bytes::from("k2"), Bytes::from("v2")),
TransactionTestOp::TxnCommit,
],
expected_results: vec![
TransactionTestOpResult::Empty,
TransactionTestOpResult::Empty,
TransactionTestOpResult::Empty,
TransactionTestOpResult::Conflicted,
]
}
)]
#[case::ssi_mark_read_multiple_keys_conflict(
TransactionTestCase {
name: "ssi_mark_read_multiple_keys_conflict",
isolation_level: IsolationLevel::SerializableSnapshot,
initial_data: vec![
(Bytes::from("k1"), Bytes::from("v1")),
(Bytes::from("k2"), Bytes::from("v2")),
(Bytes::from("k3"), Bytes::from("v3"))
],
operations: vec![
TransactionTestOp::TxnMarkRead(Bytes::from("k1")),
TransactionTestOp::TxnMarkRead(Bytes::from("k2")),
TransactionTestOp::DbPut(Bytes::from("k2"), Bytes::from("v2_new")),
TransactionTestOp::TxnPut(Bytes::from("k4"), Bytes::from("v4")),
TransactionTestOp::TxnCommit,
],
expected_results: vec![
TransactionTestOpResult::Empty,
TransactionTestOpResult::Empty,
TransactionTestOpResult::Empty,
TransactionTestOpResult::Empty,
TransactionTestOpResult::Conflicted,
]
}
)]
#[case::ssi_mark_read_no_conflict_on_different_key(
TransactionTestCase {
name: "ssi_mark_read_no_conflict_on_different_key",
isolation_level: IsolationLevel::SerializableSnapshot,
initial_data: vec![
(Bytes::from("k1"), Bytes::from("v1")),
(Bytes::from("k2"), Bytes::from("v2"))
],
operations: vec![
TransactionTestOp::TxnMarkRead(Bytes::from("k1")),
TransactionTestOp::DbPut(Bytes::from("k2"), Bytes::from("v2_new")),
TransactionTestOp::TxnPut(Bytes::from("k3"), Bytes::from("v3")),
TransactionTestOp::TxnCommit,
],
expected_results: vec![
TransactionTestOpResult::Empty,
TransactionTestOpResult::Empty,
TransactionTestOpResult::Empty,
TransactionTestOpResult::Empty,
]
}
)]
#[case::ssi_mark_read_conflict_without_write(
TransactionTestCase {
name: "ssi_mark_read_conflict_without_write",
isolation_level: IsolationLevel::SerializableSnapshot,
initial_data: vec![(Bytes::from("k1"), Bytes::from("v1"))],
operations: vec![
TransactionTestOp::TxnMarkRead(Bytes::from("k1")),
TransactionTestOp::DbPut(Bytes::from("k1"), Bytes::from("v2")),
TransactionTestOp::TxnCommit,
],
expected_results: vec![
TransactionTestOpResult::Empty,
TransactionTestOpResult::Empty,
TransactionTestOpResult::Conflicted,
]
}
)]
#[case::ssi_get_conflict_without_write(
TransactionTestCase {
name: "ssi_get_conflict_without_write",
isolation_level: IsolationLevel::SerializableSnapshot,
initial_data: vec![(Bytes::from("k1"), Bytes::from("v1"))],
operations: vec![
TransactionTestOp::TxnGet(Bytes::from("k1")),
TransactionTestOp::DbPut(Bytes::from("k1"), Bytes::from("v2")),
TransactionTestOp::TxnCommit,
],
expected_results: vec![
TransactionTestOpResult::Got(Some(Bytes::from("v1"))),
TransactionTestOpResult::Empty,
TransactionTestOpResult::Conflicted,
]
}
)]
#[case::ssi_scan_conflict_without_write(
TransactionTestCase {
name: "ssi_scan_conflict_without_write",
isolation_level: IsolationLevel::SerializableSnapshot,
initial_data: vec![
(Bytes::from("k1"), Bytes::from("v1")),
(Bytes::from("k2"), Bytes::from("v2")),
(Bytes::from("k3"), Bytes::from("v3")),
],
operations: vec![
TransactionTestOp::TxnScan(Bytes::from("k1"), Bytes::from("k3")),
TransactionTestOp::DbPut(Bytes::from("k2"), Bytes::from("v2_new")),
TransactionTestOp::TxnCommit,
],
expected_results: vec![
TransactionTestOpResult::Scanned(vec![
Bytes::from("k1"),
Bytes::from("k2"),
Bytes::from("k3"),
]),
TransactionTestOpResult::Empty,
TransactionTestOpResult::Conflicted,
]
}
)]
#[case::si_mark_read_conflict(
TransactionTestCase {
name: "si_mark_read_conflict",
isolation_level: IsolationLevel::Snapshot,
initial_data: vec![(Bytes::from("k1"), Bytes::from("v1"))],
operations: vec![
TransactionTestOp::TxnMarkRead(Bytes::from("k1")),
TransactionTestOp::DbPut(Bytes::from("k1"), Bytes::from("v2")),
TransactionTestOp::TxnPut(Bytes::from("k2"), Bytes::from("v2")),
TransactionTestOp::TxnCommit,
],
expected_results: vec![
TransactionTestOpResult::Empty,
TransactionTestOpResult::Empty,
TransactionTestOpResult::Empty,
TransactionTestOpResult::Conflicted,
]
}
)]
#[case::si_mark_read_write_write_conflict(
TransactionTestCase {
name: "si_mark_read_write_write_conflict",
isolation_level: IsolationLevel::Snapshot,
initial_data: vec![(Bytes::from("k1"), Bytes::from("v1"))],
operations: vec![
TransactionTestOp::TxnMarkRead(Bytes::from("k1")),
TransactionTestOp::TxnPut(Bytes::from("k2"), Bytes::from("v2")),
TransactionTestOp::DbPut(Bytes::from("k2"), Bytes::from("v2_db")),
TransactionTestOp::TxnCommit,
],
expected_results: vec![
TransactionTestOpResult::Empty,
TransactionTestOpResult::Empty,
TransactionTestOpResult::Empty,
TransactionTestOpResult::Conflicted,
]
}
)]
#[tokio::test]
async fn test_txn_table_driven(#[case] test_case: TransactionTestCase) {
let object_store: Arc<dyn object_store::ObjectStore> = Arc::new(InMemory::new());
let db = crate::Db::open(test_case.name, object_store).await.unwrap();
let initial_data_bytes: Vec<(Bytes, Bytes)> = test_case.initial_data.clone();
let results = execute_transaction_test_ops(
db,
test_case.operations,
initial_data_bytes,
test_case.isolation_level,
)
.await;
for (i, (result, expected)) in results
.iter()
.zip(test_case.expected_results.iter())
.enumerate()
{
assert_eq!(
result, expected,
"Test '{}' failed at operation {}: expected {:?}, got {:?}",
test_case.name, i, expected, result
);
}
}
#[tokio::test]
async fn test_txn_scan_sees_concurrent_put_in_same_txn() {
// Setup database with initial data
let object_store: Arc<dyn object_store::ObjectStore> = Arc::new(InMemory::new());
let db = crate::Db::open("test_db", object_store).await.unwrap();
// Put initial data: k1 and k3
db.put(b"k1", b"v1").await.unwrap();
db.put(b"k3", b"v3").await.unwrap();
// Begin transaction
let txn = db.begin(IsolationLevel::Snapshot).await.unwrap();
// Test 1: Scan created before put should NOT see the new key or updated value for an existing key
{
// Start a scan from k1 to k3 (inclusive)
let mut iter = txn.scan(&b"k1"[..]..=&b"k3"[..]).await.unwrap();
// Put k2 in the transaction (after scan has started)
txn.put(b"k2", b"v2").unwrap();
// Update k3 within the transaction after the scan has started
txn.put(b"k3", b"v3_updated").unwrap();
// Iterate through the results
let mut results = Vec::new();
while let Some(kv) = iter.next().await.unwrap() {
results.push((kv.key.clone(), kv.value.clone()));
}
// The iterator should see k1 and k3 (the snapshot at scan time)
// It should NOT see k2 because the scan was created before k2 was put
assert_eq!(results.len(), 2);
assert_eq!(results[0].0, Bytes::from_static(b"k1"));
assert_eq!(results[0].1, Bytes::from_static(b"v1"));
assert_eq!(results[1].0, Bytes::from_static(b"k3"));
assert_eq!(results[1].1, Bytes::from_static(b"v3"));
} // iter is dropped here
// Test 2: A new scan after the put should see k2
{
let mut iter2 = txn.scan(&b"k1"[..]..=&b"k3"[..]).await.unwrap();
let mut results2 = Vec::new();
while let Some(kv) = iter2.next().await.unwrap() {
results2.push((kv.key.clone(), kv.value.clone()));
}
// This new scan should see all three keys and the updated value for k3
assert_eq!(results2.len(), 3);
assert_eq!(results2[0].0, Bytes::from_static(b"k1"));
assert_eq!(results2[1].0, Bytes::from_static(b"k2"));
assert_eq!(results2[1].1, Bytes::from_static(b"v2"));
assert_eq!(results2[2].0, Bytes::from_static(b"k3"));
assert_eq!(results2[2].1, Bytes::from_static(b"v3_updated"));
} // iter2 is dropped here
// Commit the transaction
txn.commit().await.unwrap();
// Verify k2 is now in the database
let value = db.get(b"k2").await.unwrap();
assert_eq!(value, Some(Bytes::from_static(b"v2")));
}
#[tokio::test]
async fn test_mark_read_equivalent_to_get_in_ssi() {
// This test verifies that mark_read() behaves the same as get() in terms of conflict detection in SSI mode.
// Setup database with initial data
let object_store: Arc<dyn object_store::ObjectStore> = Arc::new(InMemory::new());
let db = crate::Db::open("test_mark_read_equivalent", object_store)
.await
.unwrap();
db.put(b"k1", b"v1").await.unwrap();
// Test 1: Transaction using mark_read() should conflict
let txn1 = db
.begin(IsolationLevel::SerializableSnapshot)
.await
.unwrap();
txn1.mark_read([b"k1"]).unwrap();
// Another transaction modifies k1
db.put(b"k1", b"v2").await.unwrap();
// Transaction 1 tries to write and commit
txn1.put(b"k2", b"v2").unwrap();
let result1 = txn1.commit().await;
assert!(
result1.is_err(),
"Transaction with mark_read() should conflict"
);
// Reset the database state
db.put(b"k1", b"v1").await.unwrap();
// Test 2: Transaction using get() should also conflict (same behavior)
let txn2 = db
.begin(IsolationLevel::SerializableSnapshot)
.await
.unwrap();
let _ = txn2.get(b"k1").await.unwrap();
// Another transaction modifies k1
db.put(b"k1", b"v2_again").await.unwrap();
// Transaction 2 tries to write and commit
txn2.put(b"k3", b"v3").unwrap();
let result2 = txn2.commit().await;
assert!(result2.is_err(), "Transaction with get() should conflict");
// Both should have the same behavior: conflict detection
}
#[tokio::test]
async fn test_mark_read_multiple_keys_at_once() {
// This test verifies that mark_read() can track multiple keys in one call
let object_store: Arc<dyn object_store::ObjectStore> = Arc::new(InMemory::new());
let db = crate::Db::open("test_mark_read_multiple", object_store)
.await
.unwrap();
db.put(b"k1", b"v1").await.unwrap();
db.put(b"k2", b"v2").await.unwrap();
db.put(b"k3", b"v3").await.unwrap();
let txn = db
.begin(IsolationLevel::SerializableSnapshot)
.await
.unwrap();
// Mark multiple keys at once
txn.mark_read([b"k1", b"k2", b"k3"]).unwrap();
// Another transaction modifies one of the marked keys
db.put(b"k2", b"v2_modified").await.unwrap();
// Transaction tries to commit with a write
txn.put(b"k4", b"v4").unwrap();
let result = txn.commit().await;
assert!(
result.is_err(),
"Transaction should conflict because k2 was modified"
);
}
#[tokio::test]
async fn test_unmark_write_ignores_write_write_conflicts() {
let object_store: Arc<dyn object_store::ObjectStore> = Arc::new(InMemory::new());
let db = crate::Db::open("test_unmark_write_ww", object_store)
.await
.unwrap();
db.put(b"k1", b"v1").await.unwrap();
let txn = db.begin(IsolationLevel::Snapshot).await.unwrap();
txn.put(b"k1", b"v2").unwrap();
txn.unmark_write([b"k1"]).unwrap();
db.put(b"k1", b"v3").await.unwrap();
let result = txn.commit().await;
assert!(
result.is_ok(),
"Transaction should not conflict for untracked write key"
);
let value = db.get(b"k1").await.unwrap();
assert_eq!(value, Some(Bytes::from_static(b"v2")));
}
#[tokio::test]
async fn test_unmark_write_only_excludes_selected_keys() {
let object_store: Arc<dyn object_store::ObjectStore> = Arc::new(InMemory::new());
let db = crate::Db::open("test_unmark_write_partial", object_store)
.await
.unwrap();
db.put(b"k1", b"v1").await.unwrap();
db.put(b"k2", b"v2").await.unwrap();
let txn = db.begin(IsolationLevel::Snapshot).await.unwrap();
txn.put(b"k1", b"v1_txn").unwrap();
txn.put(b"k2", b"v2_txn").unwrap();
txn.unmark_write([b"k1"]).unwrap();
db.put(b"k2", b"v2_db").await.unwrap();
let result = txn.commit().await;
assert!(
result.is_err(),
"Transaction should still conflict on tracked key k2"
);
}
#[tokio::test]
async fn test_unmark_write_avoids_read_write_conflicts_for_others() {
let object_store: Arc<dyn object_store::ObjectStore> = Arc::new(InMemory::new());
let db = crate::Db::open("test_unmark_write_rw", object_store)
.await
.unwrap();
db.put(b"k1", b"v1").await.unwrap();
let reader_txn = db
.begin(IsolationLevel::SerializableSnapshot)
.await
.unwrap();
let _ = reader_txn.get(b"k1").await.unwrap();
let writer_txn = db.begin(IsolationLevel::Snapshot).await.unwrap();
writer_txn.put(b"k1", b"v2").unwrap();
writer_txn.unmark_write([b"k1"]).unwrap();
writer_txn.commit().await.unwrap();
reader_txn.put(b"k2", b"v2").unwrap();
let result = reader_txn.commit().await;
assert!(
result.is_ok(),
"Reader transaction should not conflict with untracked write key"
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_unmark_write_merge_counter_aggregates_under_high_concurrency() {
const CONCURRENT_TXNS: usize = 32;
const ROUNDS: usize = 20;
const MERGE_INCREMENT: [u8; 8] = 1u64.to_le_bytes();
const EXPECTED: u64 = (CONCURRENT_TXNS * ROUNDS) as u64;
let object_store: Arc<dyn object_store::ObjectStore> = Arc::new(InMemory::new());
let db = crate::Db::builder("test_unmark_write_merge_counter", object_store)
.with_merge_operator(Arc::new(CounterMergeOperator))
.build()
.await
.unwrap();
for _ in 0..ROUNDS {
let barrier = Arc::new(tokio::sync::Barrier::new(CONCURRENT_TXNS));
let mut handles = Vec::with_capacity(CONCURRENT_TXNS);
for _ in 0..CONCURRENT_TXNS {
let db = db.clone();
let barrier = barrier.clone();
handles.push(tokio::spawn(async move {
barrier.wait().await;
let txn = db
.begin(IsolationLevel::SerializableSnapshot)
.await
.unwrap();
txn.merge(b"counter", MERGE_INCREMENT).unwrap();
txn.unmark_write([b"counter"]).unwrap();
txn.commit().await.unwrap();
}));
}
for handle in handles {
handle.await.unwrap();
}
}
let value = db.get(b"counter").await.unwrap().unwrap();
let total = u64::from_le_bytes(value.as_ref().try_into().unwrap());
assert_eq!(total, EXPECTED);
}
#[tokio::test]
async fn test_txn_merge_requires_merge_operator() {
let object_store: Arc<dyn object_store::ObjectStore> = Arc::new(InMemory::new());
let db = crate::Db::open("test_txn_merge_requires_merge_operator", object_store)
.await
.unwrap();
let txn = db.begin(IsolationLevel::Snapshot).await.unwrap();
let err = txn
.merge_with_options(b"counter", 1u64.to_le_bytes(), &MergeOptions::default())
.unwrap_err();
assert_eq!(err.kind(), crate::ErrorKind::Invalid);
txn.commit().await.unwrap();
assert_eq!(db.get(b"counter").await.unwrap(), None);
}
#[tokio::test]
async fn test_txn_commit_rejects_same_key_merge_different_ttls() {
let object_store: Arc<dyn object_store::ObjectStore> = Arc::new(InMemory::new());
let db = crate::Db::builder(
"test_txn_commit_rejects_same_key_merge_different_ttls",
object_store,
)
.with_settings(test_db_options(0, 1024, None))
.with_merge_operator(Arc::new(CounterMergeOperator))
.build()
.await
.unwrap();
let txn = db.begin(IsolationLevel::Snapshot).await.unwrap();
txn.merge_with_options(
b"counter",
1u64.to_le_bytes(),
&MergeOptions {
ttl: crate::config::Ttl::ExpireAfter(3600),
},
)
.unwrap();
txn.merge_with_options(
b"counter",
2u64.to_le_bytes(),
&MergeOptions {
ttl: crate::config::Ttl::ExpireAfter(7200),
},
)
.unwrap();
let err = txn.commit().await.unwrap_err();
assert_eq!(err.kind(), crate::ErrorKind::Invalid);
assert!(
err.to_string()
.contains("only one merge TTL per-key allowed"),
"unexpected error: {err}"
);
assert_eq!(db.get(b"counter").await.unwrap(), None);
db.close().await.unwrap();
}
fn test_db_options(
min_filter_keys: u32,
l0_sst_size_bytes: usize,
compactor_options: Option<crate::config::CompactorOptions>,
) -> crate::config::Settings {
crate::config::Settings {
flush_interval: None,
#[cfg(feature = "wal_disable")]
wal_enabled: true,
manifest_poll_interval: std::time::Duration::from_secs(3600),
manifest_update_timeout: std::time::Duration::from_secs(300),
max_unflushed_bytes: 134_217_728,
l0_max_ssts: 8,
l0_max_ssts_per_key: 8,
l0_flush_parallelism: 1,
min_filter_keys,
l0_sst_size_bytes,
max_wal_flushes_before_l0_flush: 4096,
compactor_options,
compression_codec: None,
object_store_cache_options: crate::config::ObjectStoreCacheOptions::default(),
garbage_collector_options: None,
metric_level: MetricLevel::default(),
default_ttl: None,
block_format: None,
}
}
#[tokio::test]
async fn test_txn_commit_returns_write_handle() {
use slatedb_common::clock::MockSystemClock;
let object_store: Arc<dyn object_store::ObjectStore> = Arc::new(InMemory::new());
let path = "/tmp/test_txn_commit_returns_write_handle";
let clock = Arc::new(MockSystemClock::new());
let db = crate::Db::builder(path, object_store)
.with_settings(test_db_options(0, 1024, None))
.with_system_clock(clock.clone())
.build()
.await
.unwrap();
// Basic put
clock.set(100);
let txn = db.begin(IsolationLevel::Snapshot).await.unwrap();
txn.put(b"key1", b"value1").unwrap();
let handle = txn
.commit_with_options(&WriteOptions {
await_durable: false,
..Default::default()
})
.await
.unwrap()
.unwrap();
assert_eq!(handle.seqnum(), 1);
assert_eq!(handle.create_ts(), 100);
// Put with options (TTL)
clock.set(200);
let txn = db.begin(IsolationLevel::Snapshot).await.unwrap();
let put_opts = PutOptions {
ttl: crate::config::Ttl::ExpireAfter(1000),
};
txn.put_with_options(b"key2", b"value2", &put_opts).unwrap();
let handle = txn
.commit_with_options(&WriteOptions {
await_durable: false,
..Default::default()
})
.await
.unwrap()
.unwrap();
assert_eq!(handle.seqnum(), 2);
assert_eq!(handle.create_ts(), 200);
// Delete
clock.set(300);
let txn = db.begin(IsolationLevel::Snapshot).await.unwrap();
txn.delete(b"key1").unwrap();
let handle = txn
.commit_with_options(&WriteOptions {
await_durable: false,
..Default::default()
})
.await
.unwrap()
.unwrap();
assert_eq!(handle.seqnum(), 3);
assert_eq!(handle.create_ts(), 300);
}
#[tokio::test]
async fn test_txn_commit_with_options_empty_batch_returns_none() {
let object_store: Arc<dyn object_store::ObjectStore> = Arc::new(InMemory::new());
let db = crate::Db::open("test_txn_commit_with_options_empty_batch", object_store)
.await
.unwrap();
let txn = db.begin(IsolationLevel::Snapshot).await.unwrap();
let result = txn
.commit_with_options(&WriteOptions {
await_durable: false,
..Default::default()
})
.await
.unwrap();
assert!(result.is_none());
}
}