sui_indexer/store/
pg_indexer_store.rs

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
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
// Copyright (c) Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use std::collections::{BTreeMap, HashMap};
use std::io::Cursor;
use std::time::Duration;

use async_trait::async_trait;
use core::result::Result::Ok;
use csv::{ReaderBuilder, Writer};
use diesel::dsl::{max, min};
use diesel::ExpressionMethods;
use diesel::OptionalExtension;
use diesel::QueryDsl;
use diesel_async::scoped_futures::ScopedFutureExt;
use futures::future::Either;
use itertools::Itertools;
use object_store::path::Path;
use strum::IntoEnumIterator;
use sui_types::base_types::ObjectID;
use tap::TapFallible;
use tracing::{info, warn};

use sui_config::object_storage_config::{ObjectStoreConfig, ObjectStoreType};
use sui_protocol_config::ProtocolConfig;
use sui_storage::object_store::util::put;

use crate::config::UploadOptions;
use crate::database::ConnectionPool;
use crate::errors::{Context, IndexerError};
use crate::handlers::pruner::PrunableTable;
use crate::handlers::TransactionObjectChangesToCommit;
use crate::handlers::{CommitterWatermark, EpochToCommit};
use crate::metrics::IndexerMetrics;
use crate::models::checkpoints::StoredChainIdentifier;
use crate::models::checkpoints::StoredCheckpoint;
use crate::models::checkpoints::StoredCpTx;
use crate::models::display::StoredDisplay;
use crate::models::epoch::StoredEpochInfo;
use crate::models::epoch::{StoredFeatureFlag, StoredProtocolConfig};
use crate::models::events::StoredEvent;
use crate::models::obj_indices::StoredObjectVersion;
use crate::models::objects::{
    StoredDeletedObject, StoredFullHistoryObject, StoredHistoryObject, StoredObject,
    StoredObjectSnapshot,
};
use crate::models::packages::StoredPackage;
use crate::models::transactions::StoredTransaction;
use crate::models::watermarks::StoredWatermark;
use crate::schema::{
    chain_identifier, checkpoints, display, epochs, event_emit_module, event_emit_package,
    event_senders, event_struct_instantiation, event_struct_module, event_struct_name,
    event_struct_package, events, feature_flags, full_objects_history, objects, objects_history,
    objects_snapshot, objects_version, packages, protocol_configs, pruner_cp_watermark,
    raw_checkpoints, transactions, tx_affected_addresses, tx_affected_objects, tx_calls_fun,
    tx_calls_mod, tx_calls_pkg, tx_changed_objects, tx_digests, tx_input_objects, tx_kinds,
    watermarks,
};
use crate::store::{read_with_retry, transaction_with_retry};
use crate::types::{EventIndex, IndexedDeletedObject, IndexedObject};
use crate::types::{IndexedCheckpoint, IndexedEvent, IndexedPackage, IndexedTransaction, TxIndex};

use super::pg_partition_manager::{EpochPartitionData, PgPartitionManager};
use super::IndexerStore;

use crate::models::raw_checkpoints::StoredRawCheckpoint;
use diesel::upsert::excluded;
use sui_types::digests::{ChainIdentifier, CheckpointDigest};

#[macro_export]
macro_rules! chunk {
    ($data: expr, $size: expr) => {{
        $data
            .into_iter()
            .chunks($size)
            .into_iter()
            .map(|c| c.collect())
            .collect::<Vec<Vec<_>>>()
    }};
}

// In one DB transaction, the update could be chunked into
// a few statements, this is the amount of rows to update in one statement
// TODO: I think with the `per_db_tx` params, `PG_COMMIT_CHUNK_SIZE_INTRA_DB_TX`
// is now less relevant. We should do experiments and remove it if it's true.
const PG_COMMIT_CHUNK_SIZE_INTRA_DB_TX: usize = 1000;
// The amount of rows to update in one DB transaction
const PG_COMMIT_PARALLEL_CHUNK_SIZE: usize = 100;
// The amount of rows to update in one DB transaction, for objects particularly
// Having this number too high may cause many db deadlocks because of
// optimistic locking.
const PG_COMMIT_OBJECTS_PARALLEL_CHUNK_SIZE: usize = 500;
const PG_DB_COMMIT_SLEEP_DURATION: Duration = Duration::from_secs(3600);

#[derive(Clone)]
pub struct PgIndexerStoreConfig {
    pub parallel_chunk_size: usize,
    pub parallel_objects_chunk_size: usize,
    pub gcs_cred_path: Option<String>,
    pub gcs_display_bucket: Option<String>,
}

#[derive(Clone)]
pub struct PgIndexerStore {
    pool: ConnectionPool,
    metrics: IndexerMetrics,
    partition_manager: PgPartitionManager,
    config: PgIndexerStoreConfig,
}

impl PgIndexerStore {
    pub fn new(
        pool: ConnectionPool,
        upload_options: UploadOptions,
        metrics: IndexerMetrics,
    ) -> Self {
        let parallel_chunk_size = std::env::var("PG_COMMIT_PARALLEL_CHUNK_SIZE")
            .unwrap_or_else(|_e| PG_COMMIT_PARALLEL_CHUNK_SIZE.to_string())
            .parse::<usize>()
            .unwrap();
        let parallel_objects_chunk_size = std::env::var("PG_COMMIT_OBJECTS_PARALLEL_CHUNK_SIZE")
            .unwrap_or_else(|_e| PG_COMMIT_OBJECTS_PARALLEL_CHUNK_SIZE.to_string())
            .parse::<usize>()
            .unwrap();
        let partition_manager =
            PgPartitionManager::new(pool.clone()).expect("Failed to initialize partition manager");
        let config = PgIndexerStoreConfig {
            parallel_chunk_size,
            parallel_objects_chunk_size,
            gcs_cred_path: upload_options.gcs_cred_path,
            gcs_display_bucket: upload_options.gcs_display_bucket,
        };

        Self {
            pool,
            metrics,
            partition_manager,
            config,
        }
    }

    pub fn pool(&self) -> ConnectionPool {
        self.pool.clone()
    }

    /// Get the range of the protocol versions that need to be indexed.
    pub async fn get_protocol_version_index_range(&self) -> Result<(i64, i64), IndexerError> {
        use diesel_async::RunQueryDsl;

        let mut connection = self.pool.get().await?;
        // We start indexing from the next protocol version after the latest one stored in the db.
        let start = protocol_configs::table
            .select(max(protocol_configs::protocol_version))
            .first::<Option<i64>>(&mut connection)
            .await
            .map_err(Into::into)
            .context("Failed reading latest protocol version from PostgresDB")?
            .map_or(1, |v| v + 1);

        // We end indexing at the protocol version of the latest epoch stored in the db.
        let end = epochs::table
            .select(max(epochs::protocol_version))
            .first::<Option<i64>>(&mut connection)
            .await
            .map_err(Into::into)
            .context("Failed reading latest epoch protocol version from PostgresDB")?
            .unwrap_or(1);
        Ok((start, end))
    }

    async fn get_chain_identifier(&self) -> Result<Option<Vec<u8>>, IndexerError> {
        use diesel_async::RunQueryDsl;

        let mut connection = self.pool.get().await?;

        chain_identifier::table
            .select(chain_identifier::checkpoint_digest)
            .first::<Vec<u8>>(&mut connection)
            .await
            .optional()
            .map_err(Into::into)
            .context("Failed reading chain id from PostgresDB")
    }

    // `pub` is needed for wait_for_checkpoint in tests
    pub async fn get_latest_checkpoint_sequence_number(&self) -> Result<Option<u64>, IndexerError> {
        use diesel_async::RunQueryDsl;

        let mut connection = self.pool.get().await?;

        checkpoints::table
            .select(max(checkpoints::sequence_number))
            .first::<Option<i64>>(&mut connection)
            .await
            .map_err(Into::into)
            .map(|v| v.map(|v| v as u64))
            .context("Failed reading latest checkpoint sequence number from PostgresDB")
    }

    async fn get_available_checkpoint_range(&self) -> Result<(u64, u64), IndexerError> {
        use diesel_async::RunQueryDsl;

        let mut connection = self.pool.get().await?;

        checkpoints::table
            .select((
                min(checkpoints::sequence_number),
                max(checkpoints::sequence_number),
            ))
            .first::<(Option<i64>, Option<i64>)>(&mut connection)
            .await
            .map_err(Into::into)
            .map(|(min, max)| {
                (
                    min.unwrap_or_default() as u64,
                    max.unwrap_or_default() as u64,
                )
            })
            .context("Failed reading min and max checkpoint sequence numbers from PostgresDB")
    }

    async fn get_prunable_epoch_range(&self) -> Result<(u64, u64), IndexerError> {
        use diesel_async::RunQueryDsl;

        let mut connection = self.pool.get().await?;

        epochs::table
            .select((min(epochs::epoch), max(epochs::epoch)))
            .first::<(Option<i64>, Option<i64>)>(&mut connection)
            .await
            .map_err(Into::into)
            .map(|(min, max)| {
                (
                    min.unwrap_or_default() as u64,
                    max.unwrap_or_default() as u64,
                )
            })
            .context("Failed reading min and max epoch numbers from PostgresDB")
    }

    async fn get_min_prunable_checkpoint(&self) -> Result<u64, IndexerError> {
        use diesel_async::RunQueryDsl;

        let mut connection = self.pool.get().await?;

        pruner_cp_watermark::table
            .select(min(pruner_cp_watermark::checkpoint_sequence_number))
            .first::<Option<i64>>(&mut connection)
            .await
            .map_err(Into::into)
            .map(|v| v.unwrap_or_default() as u64)
            .context("Failed reading min prunable checkpoint sequence number from PostgresDB")
    }

    pub async fn get_checkpoint_range_for_epoch(
        &self,
        epoch: u64,
    ) -> Result<(u64, Option<u64>), IndexerError> {
        use diesel_async::RunQueryDsl;

        let mut connection = self.pool.get().await?;

        epochs::table
            .select((epochs::first_checkpoint_id, epochs::last_checkpoint_id))
            .filter(epochs::epoch.eq(epoch as i64))
            .first::<(i64, Option<i64>)>(&mut connection)
            .await
            .map_err(Into::into)
            .map(|(min, max)| (min as u64, max.map(|v| v as u64)))
            .context("Failed reading checkpoint range from PostgresDB")
    }

    pub async fn get_transaction_range_for_checkpoint(
        &self,
        checkpoint: u64,
    ) -> Result<(u64, u64), IndexerError> {
        use diesel_async::RunQueryDsl;

        let mut connection = self.pool.get().await?;

        pruner_cp_watermark::table
            .select((
                pruner_cp_watermark::min_tx_sequence_number,
                pruner_cp_watermark::max_tx_sequence_number,
            ))
            .filter(pruner_cp_watermark::checkpoint_sequence_number.eq(checkpoint as i64))
            .first::<(i64, i64)>(&mut connection)
            .await
            .map_err(Into::into)
            .map(|(min, max)| (min as u64, max as u64))
            .context("Failed reading transaction range from PostgresDB")
    }

    pub async fn get_latest_object_snapshot_checkpoint_sequence_number(
        &self,
    ) -> Result<Option<u64>, IndexerError> {
        use diesel_async::RunQueryDsl;

        let mut connection = self.pool.get().await?;

        objects_snapshot::table
            .select(max(objects_snapshot::checkpoint_sequence_number))
            .first::<Option<i64>>(&mut connection)
            .await
            .map_err(Into::into)
            .map(|v| v.map(|v| v as u64))
            .context(
                "Failed reading latest object snapshot checkpoint sequence number from PostgresDB",
            )
    }

    async fn persist_display_updates(
        &self,
        display_updates: Vec<StoredDisplay>,
    ) -> Result<(), IndexerError> {
        use diesel_async::RunQueryDsl;

        transaction_with_retry(&self.pool, PG_DB_COMMIT_SLEEP_DURATION, |conn| {
            async {
                diesel::insert_into(display::table)
                    .values(display_updates)
                    .on_conflict(display::object_type)
                    .do_update()
                    .set((
                        display::id.eq(excluded(display::id)),
                        display::version.eq(excluded(display::version)),
                        display::bcs.eq(excluded(display::bcs)),
                    ))
                    .execute(conn)
                    .await?;

                Ok::<(), IndexerError>(())
            }
            .scope_boxed()
        })
        .await?;

        Ok(())
    }

    async fn persist_object_mutation_chunk(
        &self,
        mutated_object_mutation_chunk: Vec<StoredObject>,
    ) -> Result<(), IndexerError> {
        use diesel_async::RunQueryDsl;

        let guard = self
            .metrics
            .checkpoint_db_commit_latency_objects_chunks
            .start_timer();
        transaction_with_retry(&self.pool, PG_DB_COMMIT_SLEEP_DURATION, |conn| {
            async {
                diesel::insert_into(objects::table)
                    .values(mutated_object_mutation_chunk.clone())
                    .on_conflict(objects::object_id)
                    .do_update()
                    .set((
                        objects::object_id.eq(excluded(objects::object_id)),
                        objects::object_version.eq(excluded(objects::object_version)),
                        objects::object_digest.eq(excluded(objects::object_digest)),
                        objects::owner_type.eq(excluded(objects::owner_type)),
                        objects::owner_id.eq(excluded(objects::owner_id)),
                        objects::object_type.eq(excluded(objects::object_type)),
                        objects::serialized_object.eq(excluded(objects::serialized_object)),
                        objects::coin_type.eq(excluded(objects::coin_type)),
                        objects::coin_balance.eq(excluded(objects::coin_balance)),
                        objects::df_kind.eq(excluded(objects::df_kind)),
                    ))
                    .execute(conn)
                    .await?;
                Ok::<(), IndexerError>(())
            }
            .scope_boxed()
        })
        .await
        .tap_ok(|_| {
            guard.stop_and_record();
        })
        .tap_err(|e| {
            tracing::error!("Failed to persist object mutations with error: {}", e);
        })
    }

    async fn persist_object_deletion_chunk(
        &self,
        deleted_objects_chunk: Vec<StoredDeletedObject>,
    ) -> Result<(), IndexerError> {
        use diesel_async::RunQueryDsl;
        let guard = self
            .metrics
            .checkpoint_db_commit_latency_objects_chunks
            .start_timer();
        transaction_with_retry(&self.pool, PG_DB_COMMIT_SLEEP_DURATION, |conn| {
            async {
                diesel::delete(
                    objects::table.filter(
                        objects::object_id.eq_any(
                            deleted_objects_chunk
                                .iter()
                                .map(|o| o.object_id.clone())
                                .collect::<Vec<_>>(),
                        ),
                    ),
                )
                .execute(conn)
                .await
                .map_err(IndexerError::from)
                .context("Failed to write object deletion to PostgresDB")?;

                Ok::<(), IndexerError>(())
            }
            .scope_boxed()
        })
        .await
        .tap_ok(|_| {
            guard.stop_and_record();
        })
        .tap_err(|e| {
            tracing::error!("Failed to persist object deletions with error: {}", e);
        })
    }

    async fn persist_object_snapshot_mutation_chunk(
        &self,
        objects_snapshot_mutations: Vec<StoredObjectSnapshot>,
    ) -> Result<(), IndexerError> {
        use diesel_async::RunQueryDsl;
        let guard = self
            .metrics
            .checkpoint_db_commit_latency_objects_snapshot_chunks
            .start_timer();
        transaction_with_retry(&self.pool, PG_DB_COMMIT_SLEEP_DURATION, |conn| {
            async {
                for mutation_chunk in
                    objects_snapshot_mutations.chunks(PG_COMMIT_CHUNK_SIZE_INTRA_DB_TX)
                {
                    diesel::insert_into(objects_snapshot::table)
                        .values(mutation_chunk)
                        .on_conflict(objects_snapshot::object_id)
                        .do_update()
                        .set((
                            objects_snapshot::object_version
                                .eq(excluded(objects_snapshot::object_version)),
                            objects_snapshot::object_status
                                .eq(excluded(objects_snapshot::object_status)),
                            objects_snapshot::object_digest
                                .eq(excluded(objects_snapshot::object_digest)),
                            objects_snapshot::owner_type.eq(excluded(objects_snapshot::owner_type)),
                            objects_snapshot::owner_id.eq(excluded(objects_snapshot::owner_id)),
                            objects_snapshot::object_type_package
                                .eq(excluded(objects_snapshot::object_type_package)),
                            objects_snapshot::object_type_module
                                .eq(excluded(objects_snapshot::object_type_module)),
                            objects_snapshot::object_type_name
                                .eq(excluded(objects_snapshot::object_type_name)),
                            objects_snapshot::object_type
                                .eq(excluded(objects_snapshot::object_type)),
                            objects_snapshot::serialized_object
                                .eq(excluded(objects_snapshot::serialized_object)),
                            objects_snapshot::coin_type.eq(excluded(objects_snapshot::coin_type)),
                            objects_snapshot::coin_balance
                                .eq(excluded(objects_snapshot::coin_balance)),
                            objects_snapshot::df_kind.eq(excluded(objects_snapshot::df_kind)),
                            objects_snapshot::checkpoint_sequence_number
                                .eq(excluded(objects_snapshot::checkpoint_sequence_number)),
                        ))
                        .execute(conn)
                        .await?;
                }
                Ok::<(), IndexerError>(())
            }
            .scope_boxed()
        })
        .await
        .tap_ok(|_| {
            guard.stop_and_record();
        })
        .tap_err(|e| {
            tracing::error!("Failed to persist object snapshot with error: {}", e);
        })
    }

    async fn persist_object_snapshot_deletion_chunk(
        &self,
        objects_snapshot_deletions: Vec<StoredObjectSnapshot>,
    ) -> Result<(), IndexerError> {
        use diesel_async::RunQueryDsl;
        let guard = self
            .metrics
            .checkpoint_db_commit_latency_objects_snapshot_chunks
            .start_timer();

        transaction_with_retry(&self.pool, PG_DB_COMMIT_SLEEP_DURATION, |conn| {
            async {
                for deletion_chunk in
                    objects_snapshot_deletions.chunks(PG_COMMIT_CHUNK_SIZE_INTRA_DB_TX)
                {
                    diesel::delete(
                        objects_snapshot::table.filter(
                            objects_snapshot::object_id.eq_any(
                                deletion_chunk
                                    .iter()
                                    .map(|o| o.object_id.clone())
                                    .collect::<Vec<_>>(),
                            ),
                        ),
                    )
                    .execute(conn)
                    .await
                    .map_err(IndexerError::from)
                    .context("Failed to write object deletion to PostgresDB")?;
                }
                Ok::<(), IndexerError>(())
            }
            .scope_boxed()
        })
        .await
        .tap_ok(|_| {
            let elapsed = guard.stop_and_record();
            info!(
                elapsed,
                "Deleted {} chunked object snapshots",
                objects_snapshot_deletions.len(),
            );
        })
        .tap_err(|e| {
            tracing::error!(
                "Failed to persist object snapshot deletions with error: {}",
                e
            );
        })
    }

    async fn persist_objects_history_chunk(
        &self,
        stored_objects_history: Vec<StoredHistoryObject>,
    ) -> Result<(), IndexerError> {
        use diesel_async::RunQueryDsl;
        let guard = self
            .metrics
            .checkpoint_db_commit_latency_objects_history_chunks
            .start_timer();
        transaction_with_retry(&self.pool, PG_DB_COMMIT_SLEEP_DURATION, |conn| {
            async {
                for stored_objects_history_chunk in
                    stored_objects_history.chunks(PG_COMMIT_CHUNK_SIZE_INTRA_DB_TX)
                {
                    let error_message = concat!(
                        "Failed to write to ",
                        stringify!((objects_history::table)),
                        " DB"
                    );
                    diesel::insert_into(objects_history::table)
                        .values(stored_objects_history_chunk)
                        .on_conflict_do_nothing()
                        .execute(conn)
                        .await
                        .map_err(IndexerError::from)
                        .context(error_message)?;
                }
                Ok::<(), IndexerError>(())
            }
            .scope_boxed()
        })
        .await
        .tap_ok(|_| {
            guard.stop_and_record();
        })
        .tap_err(|e| {
            tracing::error!("Failed to persist object history with error: {}", e);
        })
    }

    async fn persist_full_objects_history_chunk(
        &self,
        objects: Vec<StoredFullHistoryObject>,
    ) -> Result<(), IndexerError> {
        use diesel_async::RunQueryDsl;

        let guard = self
            .metrics
            .checkpoint_db_commit_latency_full_objects_history_chunks
            .start_timer();

        transaction_with_retry(&self.pool, PG_DB_COMMIT_SLEEP_DURATION, |conn| {
            async {
                for objects_chunk in objects.chunks(PG_COMMIT_CHUNK_SIZE_INTRA_DB_TX) {
                    diesel::insert_into(full_objects_history::table)
                        .values(objects_chunk)
                        .on_conflict_do_nothing()
                        .execute(conn)
                        .await
                        .map_err(IndexerError::from)
                        .context("Failed to write to full_objects_history table")?;
                }

                Ok(())
            }
            .scope_boxed()
        })
        .await
        .tap_ok(|_| {
            let elapsed = guard.stop_and_record();
            info!(
                elapsed,
                "Persisted {} chunked full objects history",
                objects.len(),
            );
        })
        .tap_err(|e| {
            tracing::error!("Failed to persist full object history with error: {}", e);
        })
    }

    async fn persist_objects_version_chunk(
        &self,
        object_versions: Vec<StoredObjectVersion>,
    ) -> Result<(), IndexerError> {
        use diesel_async::RunQueryDsl;

        let guard = self
            .metrics
            .checkpoint_db_commit_latency_objects_version_chunks
            .start_timer();

        transaction_with_retry(&self.pool, PG_DB_COMMIT_SLEEP_DURATION, |conn| {
            async {
                for object_version_chunk in object_versions.chunks(PG_COMMIT_CHUNK_SIZE_INTRA_DB_TX)
                {
                    diesel::insert_into(objects_version::table)
                        .values(object_version_chunk)
                        .on_conflict_do_nothing()
                        .execute(conn)
                        .await
                        .map_err(IndexerError::from)
                        .context("Failed to write to objects_version table")?;
                }
                Ok::<(), IndexerError>(())
            }
            .scope_boxed()
        })
        .await
        .tap_ok(|_| {
            let elapsed = guard.stop_and_record();
            info!(
                elapsed,
                "Persisted {} chunked object versions",
                object_versions.len(),
            );
        })
        .tap_err(|e| {
            tracing::error!("Failed to persist object versions with error: {}", e);
        })
    }

    async fn persist_raw_checkpoints_impl(
        &self,
        raw_checkpoints: &[StoredRawCheckpoint],
    ) -> Result<(), IndexerError> {
        use diesel_async::RunQueryDsl;

        transaction_with_retry(&self.pool, PG_DB_COMMIT_SLEEP_DURATION, |conn| {
            async {
                diesel::insert_into(raw_checkpoints::table)
                    .values(raw_checkpoints)
                    .on_conflict_do_nothing()
                    .execute(conn)
                    .await
                    .map_err(IndexerError::from)
                    .context("Failed to write to raw_checkpoints table")?;
                Ok::<(), IndexerError>(())
            }
            .scope_boxed()
        })
        .await
    }

    async fn persist_checkpoints(
        &self,
        checkpoints: Vec<IndexedCheckpoint>,
    ) -> Result<(), IndexerError> {
        use diesel_async::RunQueryDsl;

        let Some(first_checkpoint) = checkpoints.as_slice().first() else {
            return Ok(());
        };

        // If the first checkpoint has sequence number 0, we need to persist the digest as
        // chain identifier.
        if first_checkpoint.sequence_number == 0 {
            let checkpoint_digest = first_checkpoint.checkpoint_digest.into_inner().to_vec();
            self.persist_protocol_configs_and_feature_flags(checkpoint_digest.clone())
                .await?;
            self.persist_chain_identifier(checkpoint_digest).await?;
        }
        let guard = self
            .metrics
            .checkpoint_db_commit_latency_checkpoints
            .start_timer();

        let stored_cp_txs = checkpoints.iter().map(StoredCpTx::from).collect::<Vec<_>>();
        transaction_with_retry(&self.pool, PG_DB_COMMIT_SLEEP_DURATION, |conn| {
            async {
                for stored_cp_tx_chunk in stored_cp_txs.chunks(PG_COMMIT_CHUNK_SIZE_INTRA_DB_TX) {
                    diesel::insert_into(pruner_cp_watermark::table)
                        .values(stored_cp_tx_chunk)
                        .on_conflict_do_nothing()
                        .execute(conn)
                        .await
                        .map_err(IndexerError::from)
                        .context("Failed to write to pruner_cp_watermark table")?;
                }
                Ok::<(), IndexerError>(())
            }
            .scope_boxed()
        })
        .await
        .tap_ok(|_| {
            info!(
                "Persisted {} pruner_cp_watermark rows.",
                stored_cp_txs.len(),
            );
        })
        .tap_err(|e| {
            tracing::error!("Failed to persist pruner_cp_watermark with error: {}", e);
        })?;

        let stored_checkpoints = checkpoints
            .iter()
            .map(StoredCheckpoint::from)
            .collect::<Vec<_>>();
        transaction_with_retry(&self.pool, PG_DB_COMMIT_SLEEP_DURATION, |conn| {
            async {
                for stored_checkpoint_chunk in
                    stored_checkpoints.chunks(PG_COMMIT_CHUNK_SIZE_INTRA_DB_TX)
                {
                    diesel::insert_into(checkpoints::table)
                        .values(stored_checkpoint_chunk)
                        .on_conflict_do_nothing()
                        .execute(conn)
                        .await
                        .map_err(IndexerError::from)
                        .context("Failed to write to checkpoints table")?;
                    let time_now_ms = chrono::Utc::now().timestamp_millis();
                    for stored_checkpoint in stored_checkpoint_chunk {
                        self.metrics
                            .db_commit_lag_ms
                            .set(time_now_ms - stored_checkpoint.timestamp_ms);
                        self.metrics
                            .max_committed_checkpoint_sequence_number
                            .set(stored_checkpoint.sequence_number);
                        self.metrics
                            .committed_checkpoint_timestamp_ms
                            .set(stored_checkpoint.timestamp_ms);
                    }

                    for stored_checkpoint in stored_checkpoint_chunk {
                        info!(
                            "Indexer lag: \
                            persisted checkpoint {} with time now {} and checkpoint time {}",
                            stored_checkpoint.sequence_number,
                            time_now_ms,
                            stored_checkpoint.timestamp_ms
                        );
                    }
                }
                Ok::<(), IndexerError>(())
            }
            .scope_boxed()
        })
        .await
        .tap_ok(|_| {
            let elapsed = guard.stop_and_record();
            info!(
                elapsed,
                "Persisted {} checkpoints",
                stored_checkpoints.len()
            );
        })
        .tap_err(|e| {
            tracing::error!("Failed to persist checkpoints with error: {}", e);
        })
    }

    async fn persist_transactions_chunk(
        &self,
        transactions: Vec<IndexedTransaction>,
    ) -> Result<(), IndexerError> {
        use diesel_async::RunQueryDsl;
        let guard = self
            .metrics
            .checkpoint_db_commit_latency_transactions_chunks
            .start_timer();
        let transformation_guard = self
            .metrics
            .checkpoint_db_commit_latency_transactions_chunks_transformation
            .start_timer();
        let transactions = transactions
            .iter()
            .map(StoredTransaction::from)
            .collect::<Vec<_>>();
        drop(transformation_guard);

        transaction_with_retry(&self.pool, PG_DB_COMMIT_SLEEP_DURATION, |conn| {
            async {
                for transaction_chunk in transactions.chunks(PG_COMMIT_CHUNK_SIZE_INTRA_DB_TX) {
                    let error_message = concat!(
                        "Failed to write to ",
                        stringify!((transactions::table)),
                        " DB"
                    );
                    diesel::insert_into(transactions::table)
                        .values(transaction_chunk)
                        .on_conflict_do_nothing()
                        .execute(conn)
                        .await
                        .map_err(IndexerError::from)
                        .context(error_message)?;
                }
                Ok::<(), IndexerError>(())
            }
            .scope_boxed()
        })
        .await
        .tap_ok(|_| {
            let elapsed = guard.stop_and_record();
            info!(
                elapsed,
                "Persisted {} chunked transactions",
                transactions.len()
            );
        })
        .tap_err(|e| {
            tracing::error!("Failed to persist transactions with error: {}", e);
        })
    }

    async fn persist_events_chunk(&self, events: Vec<IndexedEvent>) -> Result<(), IndexerError> {
        use diesel_async::RunQueryDsl;
        let guard = self
            .metrics
            .checkpoint_db_commit_latency_events_chunks
            .start_timer();
        let len = events.len();
        let events = events
            .into_iter()
            .map(StoredEvent::from)
            .collect::<Vec<_>>();

        transaction_with_retry(&self.pool, PG_DB_COMMIT_SLEEP_DURATION, |conn| {
            async {
                for event_chunk in events.chunks(PG_COMMIT_CHUNK_SIZE_INTRA_DB_TX) {
                    let error_message =
                        concat!("Failed to write to ", stringify!((events::table)), " DB");
                    diesel::insert_into(events::table)
                        .values(event_chunk)
                        .on_conflict_do_nothing()
                        .execute(conn)
                        .await
                        .map_err(IndexerError::from)
                        .context(error_message)?;
                }
                Ok::<(), IndexerError>(())
            }
            .scope_boxed()
        })
        .await
        .tap_ok(|_| {
            let elapsed = guard.stop_and_record();
            info!(elapsed, "Persisted {} chunked events", len);
        })
        .tap_err(|e| {
            tracing::error!("Failed to persist events with error: {}", e);
        })
    }

    async fn persist_packages(&self, packages: Vec<IndexedPackage>) -> Result<(), IndexerError> {
        use diesel_async::RunQueryDsl;
        if packages.is_empty() {
            return Ok(());
        }
        let guard = self
            .metrics
            .checkpoint_db_commit_latency_packages
            .start_timer();
        let packages = packages
            .into_iter()
            .map(StoredPackage::from)
            .collect::<Vec<_>>();
        transaction_with_retry(&self.pool, PG_DB_COMMIT_SLEEP_DURATION, |conn| {
            async {
                for packages_chunk in packages.chunks(PG_COMMIT_CHUNK_SIZE_INTRA_DB_TX) {
                    diesel::insert_into(packages::table)
                        .values(packages_chunk)
                        .on_conflict(packages::package_id)
                        .do_update()
                        .set((
                            packages::package_id.eq(excluded(packages::package_id)),
                            packages::package_version.eq(excluded(packages::package_version)),
                            packages::move_package.eq(excluded(packages::move_package)),
                            packages::checkpoint_sequence_number
                                .eq(excluded(packages::checkpoint_sequence_number)),
                        ))
                        .execute(conn)
                        .await?;
                }
                Ok::<(), IndexerError>(())
            }
            .scope_boxed()
        })
        .await
        .tap_ok(|_| {
            let elapsed = guard.stop_and_record();
            info!(elapsed, "Persisted {} packages", packages.len());
        })
        .tap_err(|e| {
            tracing::error!("Failed to persist packages with error: {}", e);
        })
    }

    async fn persist_event_indices_chunk(
        &self,
        indices: Vec<EventIndex>,
    ) -> Result<(), IndexerError> {
        use diesel_async::RunQueryDsl;

        let guard = self
            .metrics
            .checkpoint_db_commit_latency_event_indices_chunks
            .start_timer();
        let len = indices.len();
        let (
            event_emit_packages,
            event_emit_modules,
            event_senders,
            event_struct_packages,
            event_struct_modules,
            event_struct_names,
            event_struct_instantiations,
        ) = indices.into_iter().map(|i| i.split()).fold(
            (
                Vec::new(),
                Vec::new(),
                Vec::new(),
                Vec::new(),
                Vec::new(),
                Vec::new(),
                Vec::new(),
            ),
            |(
                mut event_emit_packages,
                mut event_emit_modules,
                mut event_senders,
                mut event_struct_packages,
                mut event_struct_modules,
                mut event_struct_names,
                mut event_struct_instantiations,
            ),
             index| {
                event_emit_packages.push(index.0);
                event_emit_modules.push(index.1);
                event_senders.push(index.2);
                event_struct_packages.push(index.3);
                event_struct_modules.push(index.4);
                event_struct_names.push(index.5);
                event_struct_instantiations.push(index.6);
                (
                    event_emit_packages,
                    event_emit_modules,
                    event_senders,
                    event_struct_packages,
                    event_struct_modules,
                    event_struct_names,
                    event_struct_instantiations,
                )
            },
        );

        transaction_with_retry(&self.pool, PG_DB_COMMIT_SLEEP_DURATION, |conn| {
            async {
                for event_emit_packages_chunk in
                    event_emit_packages.chunks(PG_COMMIT_CHUNK_SIZE_INTRA_DB_TX)
                {
                    diesel::insert_into(event_emit_package::table)
                        .values(event_emit_packages_chunk)
                        .on_conflict_do_nothing()
                        .execute(conn)
                        .await?;
                }

                for event_emit_modules_chunk in
                    event_emit_modules.chunks(PG_COMMIT_CHUNK_SIZE_INTRA_DB_TX)
                {
                    diesel::insert_into(event_emit_module::table)
                        .values(event_emit_modules_chunk)
                        .on_conflict_do_nothing()
                        .execute(conn)
                        .await?;
                }

                for event_senders_chunk in event_senders.chunks(PG_COMMIT_CHUNK_SIZE_INTRA_DB_TX) {
                    diesel::insert_into(event_senders::table)
                        .values(event_senders_chunk)
                        .on_conflict_do_nothing()
                        .execute(conn)
                        .await?;
                }

                for event_struct_packages_chunk in
                    event_struct_packages.chunks(PG_COMMIT_CHUNK_SIZE_INTRA_DB_TX)
                {
                    diesel::insert_into(event_struct_package::table)
                        .values(event_struct_packages_chunk)
                        .on_conflict_do_nothing()
                        .execute(conn)
                        .await?;
                }

                for event_struct_modules_chunk in
                    event_struct_modules.chunks(PG_COMMIT_CHUNK_SIZE_INTRA_DB_TX)
                {
                    diesel::insert_into(event_struct_module::table)
                        .values(event_struct_modules_chunk)
                        .on_conflict_do_nothing()
                        .execute(conn)
                        .await?;
                }

                for event_struct_names_chunk in
                    event_struct_names.chunks(PG_COMMIT_CHUNK_SIZE_INTRA_DB_TX)
                {
                    diesel::insert_into(event_struct_name::table)
                        .values(event_struct_names_chunk)
                        .on_conflict_do_nothing()
                        .execute(conn)
                        .await?;
                }

                for event_struct_instantiations_chunk in
                    event_struct_instantiations.chunks(PG_COMMIT_CHUNK_SIZE_INTRA_DB_TX)
                {
                    diesel::insert_into(event_struct_instantiation::table)
                        .values(event_struct_instantiations_chunk)
                        .on_conflict_do_nothing()
                        .execute(conn)
                        .await?;
                }
                Ok(())
            }
            .scope_boxed()
        })
        .await?;

        let elapsed = guard.stop_and_record();
        info!(elapsed, "Persisted {} chunked event indices", len);
        Ok(())
    }

    async fn persist_tx_indices_chunk(&self, indices: Vec<TxIndex>) -> Result<(), IndexerError> {
        use diesel_async::RunQueryDsl;

        let guard = self
            .metrics
            .checkpoint_db_commit_latency_tx_indices_chunks
            .start_timer();
        let len = indices.len();
        let (
            affected_addresses,
            affected_objects,
            input_objects,
            changed_objects,
            pkgs,
            mods,
            funs,
            digests,
            kinds,
        ) = indices.into_iter().map(|i| i.split()).fold(
            (
                Vec::new(),
                Vec::new(),
                Vec::new(),
                Vec::new(),
                Vec::new(),
                Vec::new(),
                Vec::new(),
                Vec::new(),
                Vec::new(),
            ),
            |(
                mut tx_affected_addresses,
                mut tx_affected_objects,
                mut tx_input_objects,
                mut tx_changed_objects,
                mut tx_pkgs,
                mut tx_mods,
                mut tx_funs,
                mut tx_digests,
                mut tx_kinds,
            ),
             index| {
                tx_affected_addresses.extend(index.0);
                tx_affected_objects.extend(index.1);
                tx_input_objects.extend(index.2);
                tx_changed_objects.extend(index.3);
                tx_pkgs.extend(index.4);
                tx_mods.extend(index.5);
                tx_funs.extend(index.6);
                tx_digests.extend(index.7);
                tx_kinds.extend(index.8);
                (
                    tx_affected_addresses,
                    tx_affected_objects,
                    tx_input_objects,
                    tx_changed_objects,
                    tx_pkgs,
                    tx_mods,
                    tx_funs,
                    tx_digests,
                    tx_kinds,
                )
            },
        );

        transaction_with_retry(&self.pool, PG_DB_COMMIT_SLEEP_DURATION, |conn| {
            async {
                for affected_addresses_chunk in
                    affected_addresses.chunks(PG_COMMIT_CHUNK_SIZE_INTRA_DB_TX)
                {
                    diesel::insert_into(tx_affected_addresses::table)
                        .values(affected_addresses_chunk)
                        .on_conflict_do_nothing()
                        .execute(conn)
                        .await?;
                }

                for affected_objects_chunk in
                    affected_objects.chunks(PG_COMMIT_CHUNK_SIZE_INTRA_DB_TX)
                {
                    diesel::insert_into(tx_affected_objects::table)
                        .values(affected_objects_chunk)
                        .on_conflict_do_nothing()
                        .execute(conn)
                        .await?;
                }

                for input_objects_chunk in input_objects.chunks(PG_COMMIT_CHUNK_SIZE_INTRA_DB_TX) {
                    diesel::insert_into(tx_input_objects::table)
                        .values(input_objects_chunk)
                        .on_conflict_do_nothing()
                        .execute(conn)
                        .await?;
                }

                for changed_objects_chunk in
                    changed_objects.chunks(PG_COMMIT_CHUNK_SIZE_INTRA_DB_TX)
                {
                    diesel::insert_into(tx_changed_objects::table)
                        .values(changed_objects_chunk)
                        .on_conflict_do_nothing()
                        .execute(conn)
                        .await?;
                }

                for pkgs_chunk in pkgs.chunks(PG_COMMIT_CHUNK_SIZE_INTRA_DB_TX) {
                    diesel::insert_into(tx_calls_pkg::table)
                        .values(pkgs_chunk)
                        .on_conflict_do_nothing()
                        .execute(conn)
                        .await?;
                }

                for mods_chunk in mods.chunks(PG_COMMIT_CHUNK_SIZE_INTRA_DB_TX) {
                    diesel::insert_into(tx_calls_mod::table)
                        .values(mods_chunk)
                        .on_conflict_do_nothing()
                        .execute(conn)
                        .await?;
                }

                for funs_chunk in funs.chunks(PG_COMMIT_CHUNK_SIZE_INTRA_DB_TX) {
                    diesel::insert_into(tx_calls_fun::table)
                        .values(funs_chunk)
                        .on_conflict_do_nothing()
                        .execute(conn)
                        .await?;
                }

                for digests_chunk in digests.chunks(PG_COMMIT_CHUNK_SIZE_INTRA_DB_TX) {
                    diesel::insert_into(tx_digests::table)
                        .values(digests_chunk)
                        .on_conflict_do_nothing()
                        .execute(conn)
                        .await?;
                }

                for kinds_chunk in kinds.chunks(PG_COMMIT_CHUNK_SIZE_INTRA_DB_TX) {
                    diesel::insert_into(tx_kinds::table)
                        .values(kinds_chunk)
                        .on_conflict_do_nothing()
                        .execute(conn)
                        .await?;
                }

                Ok(())
            }
            .scope_boxed()
        })
        .await?;

        let elapsed = guard.stop_and_record();
        info!(elapsed, "Persisted {} chunked tx_indices", len);
        Ok(())
    }

    async fn persist_epoch(&self, epoch: EpochToCommit) -> Result<(), IndexerError> {
        use diesel_async::RunQueryDsl;
        let guard = self
            .metrics
            .checkpoint_db_commit_latency_epoch
            .start_timer();
        let epoch_id = epoch.new_epoch.epoch;

        transaction_with_retry(&self.pool, PG_DB_COMMIT_SLEEP_DURATION, |conn| {
            async {
                if let Some(last_epoch) = &epoch.last_epoch {
                    let last_epoch_id = last_epoch.epoch;

                    info!(last_epoch_id, "Persisting epoch end data.");
                    diesel::update(epochs::table.filter(epochs::epoch.eq(last_epoch_id)))
                        .set(last_epoch)
                        .execute(conn)
                        .await?;
                }

                let epoch_id = epoch.new_epoch.epoch;
                info!(epoch_id, "Persisting epoch beginning info");
                let error_message =
                    concat!("Failed to write to ", stringify!((epochs::table)), " DB");
                diesel::insert_into(epochs::table)
                    .values(epoch.new_epoch)
                    .on_conflict_do_nothing()
                    .execute(conn)
                    .await
                    .map_err(IndexerError::from)
                    .context(error_message)?;
                Ok::<(), IndexerError>(())
            }
            .scope_boxed()
        })
        .await
        .tap_ok(|_| {
            let elapsed = guard.stop_and_record();
            info!(elapsed, epoch_id, "Persisted epoch beginning info");
        })
        .tap_err(|e| {
            tracing::error!("Failed to persist epoch with error: {}", e);
        })
    }

    async fn advance_epoch(&self, epoch_to_commit: EpochToCommit) -> Result<(), IndexerError> {
        use diesel_async::RunQueryDsl;

        let mut connection = self.pool.get().await?;

        let last_epoch_id = epoch_to_commit.last_epoch.as_ref().map(|e| e.epoch);
        // partition_0 has been created, so no need to advance it.
        if let Some(last_epoch_id) = last_epoch_id {
            let last_db_epoch: Option<StoredEpochInfo> = epochs::table
                .filter(epochs::epoch.eq(last_epoch_id))
                .first::<StoredEpochInfo>(&mut connection)
                .await
                .optional()
                .map_err(Into::into)
                .context("Failed to read last epoch from PostgresDB")?;
            if let Some(last_epoch) = last_db_epoch {
                let epoch_partition_data =
                    EpochPartitionData::compose_data(epoch_to_commit, last_epoch);
                let table_partitions = self.partition_manager.get_table_partitions().await?;
                for (table, (_, last_partition)) in table_partitions {
                    // Only advance epoch partition for epoch partitioned tables.
                    if !self
                        .partition_manager
                        .get_strategy(&table)
                        .is_epoch_partitioned()
                    {
                        continue;
                    }
                    let guard = self.metrics.advance_epoch_latency.start_timer();
                    self.partition_manager
                        .advance_epoch(table.clone(), last_partition, &epoch_partition_data)
                        .await?;
                    let elapsed = guard.stop_and_record();
                    info!(
                        elapsed,
                        "Advanced epoch partition {} for table {}",
                        last_partition,
                        table.clone()
                    );
                }
            } else {
                tracing::error!("Last epoch: {} from PostgresDB is None.", last_epoch_id);
            }
        }

        Ok(())
    }

    async fn prune_checkpoints_table(&self, cp: u64) -> Result<(), IndexerError> {
        use diesel_async::RunQueryDsl;
        transaction_with_retry(&self.pool, PG_DB_COMMIT_SLEEP_DURATION, |conn| {
            async {
                diesel::delete(
                    checkpoints::table.filter(checkpoints::sequence_number.eq(cp as i64)),
                )
                .execute(conn)
                .await
                .map_err(IndexerError::from)
                .context("Failed to prune checkpoints table")?;

                Ok::<(), IndexerError>(())
            }
            .scope_boxed()
        })
        .await
    }

    async fn prune_event_indices_table(
        &self,
        min_tx: u64,
        max_tx: u64,
    ) -> Result<(), IndexerError> {
        use diesel_async::RunQueryDsl;

        let (min_tx, max_tx) = (min_tx as i64, max_tx as i64);
        transaction_with_retry(&self.pool, PG_DB_COMMIT_SLEEP_DURATION, |conn| {
            async {
                diesel::delete(
                    event_emit_module::table
                        .filter(event_emit_module::tx_sequence_number.between(min_tx, max_tx)),
                )
                .execute(conn)
                .await?;

                diesel::delete(
                    event_emit_package::table
                        .filter(event_emit_package::tx_sequence_number.between(min_tx, max_tx)),
                )
                .execute(conn)
                .await?;

                diesel::delete(
                    event_senders::table
                        .filter(event_senders::tx_sequence_number.between(min_tx, max_tx)),
                )
                .execute(conn)
                .await?;

                diesel::delete(event_struct_instantiation::table.filter(
                    event_struct_instantiation::tx_sequence_number.between(min_tx, max_tx),
                ))
                .execute(conn)
                .await?;

                diesel::delete(
                    event_struct_module::table
                        .filter(event_struct_module::tx_sequence_number.between(min_tx, max_tx)),
                )
                .execute(conn)
                .await?;

                diesel::delete(
                    event_struct_name::table
                        .filter(event_struct_name::tx_sequence_number.between(min_tx, max_tx)),
                )
                .execute(conn)
                .await?;

                diesel::delete(
                    event_struct_package::table
                        .filter(event_struct_package::tx_sequence_number.between(min_tx, max_tx)),
                )
                .execute(conn)
                .await?;

                Ok(())
            }
            .scope_boxed()
        })
        .await
    }

    async fn prune_tx_indices_table(&self, min_tx: u64, max_tx: u64) -> Result<(), IndexerError> {
        use diesel_async::RunQueryDsl;

        let (min_tx, max_tx) = (min_tx as i64, max_tx as i64);
        transaction_with_retry(&self.pool, PG_DB_COMMIT_SLEEP_DURATION, |conn| {
            async {
                diesel::delete(
                    tx_affected_addresses::table
                        .filter(tx_affected_addresses::tx_sequence_number.between(min_tx, max_tx)),
                )
                .execute(conn)
                .await?;

                diesel::delete(
                    tx_affected_objects::table
                        .filter(tx_affected_objects::tx_sequence_number.between(min_tx, max_tx)),
                )
                .execute(conn)
                .await?;

                diesel::delete(
                    tx_input_objects::table
                        .filter(tx_input_objects::tx_sequence_number.between(min_tx, max_tx)),
                )
                .execute(conn)
                .await?;

                diesel::delete(
                    tx_changed_objects::table
                        .filter(tx_changed_objects::tx_sequence_number.between(min_tx, max_tx)),
                )
                .execute(conn)
                .await?;

                diesel::delete(
                    tx_calls_pkg::table
                        .filter(tx_calls_pkg::tx_sequence_number.between(min_tx, max_tx)),
                )
                .execute(conn)
                .await?;

                diesel::delete(
                    tx_calls_mod::table
                        .filter(tx_calls_mod::tx_sequence_number.between(min_tx, max_tx)),
                )
                .execute(conn)
                .await?;

                diesel::delete(
                    tx_calls_fun::table
                        .filter(tx_calls_fun::tx_sequence_number.between(min_tx, max_tx)),
                )
                .execute(conn)
                .await?;

                diesel::delete(
                    tx_digests::table
                        .filter(tx_digests::tx_sequence_number.between(min_tx, max_tx)),
                )
                .execute(conn)
                .await?;

                Ok(())
            }
            .scope_boxed()
        })
        .await
    }

    async fn prune_cp_tx_table(&self, cp: u64) -> Result<(), IndexerError> {
        use diesel_async::RunQueryDsl;

        transaction_with_retry(&self.pool, PG_DB_COMMIT_SLEEP_DURATION, |conn| {
            async {
                diesel::delete(
                    pruner_cp_watermark::table
                        .filter(pruner_cp_watermark::checkpoint_sequence_number.eq(cp as i64)),
                )
                .execute(conn)
                .await
                .map_err(IndexerError::from)
                .context("Failed to prune pruner_cp_watermark table")?;
                Ok(())
            }
            .scope_boxed()
        })
        .await
    }

    async fn get_network_total_transactions_by_end_of_epoch(
        &self,
        epoch: u64,
    ) -> Result<Option<u64>, IndexerError> {
        use diesel_async::RunQueryDsl;

        let mut connection = self.pool.get().await?;

        // TODO: (wlmyng) update to read from epochs::network_total_transactions

        Ok(Some(
            checkpoints::table
                .filter(checkpoints::epoch.eq(epoch as i64))
                .select(checkpoints::network_total_transactions)
                .order_by(checkpoints::sequence_number.desc())
                .first::<i64>(&mut connection)
                .await
                .map_err(Into::into)
                .context("Failed to get network total transactions in epoch")
                .map(|v| v as u64)?,
        ))
    }

    async fn update_watermarks_upper_bound<E: IntoEnumIterator>(
        &self,
        watermark: CommitterWatermark,
    ) -> Result<(), IndexerError>
    where
        E::Iterator: Iterator<Item: AsRef<str>>,
    {
        use diesel_async::RunQueryDsl;

        let guard = self
            .metrics
            .checkpoint_db_commit_latency_watermarks
            .start_timer();

        transaction_with_retry(&self.pool, PG_DB_COMMIT_SLEEP_DURATION, |conn| {
            let upper_bound_updates = E::iter()
                .map(|table| StoredWatermark::from_upper_bound_update(table.as_ref(), watermark))
                .collect::<Vec<_>>();
            async {
                diesel::insert_into(watermarks::table)
                    .values(upper_bound_updates)
                    .on_conflict(watermarks::pipeline)
                    .do_update()
                    .set((
                        watermarks::epoch_hi_inclusive.eq(excluded(watermarks::epoch_hi_inclusive)),
                        watermarks::checkpoint_hi_inclusive
                            .eq(excluded(watermarks::checkpoint_hi_inclusive)),
                        watermarks::tx_hi.eq(excluded(watermarks::tx_hi)),
                    ))
                    .execute(conn)
                    .await
                    .map_err(IndexerError::from)
                    .context("Failed to update watermarks upper bound")?;

                Ok::<(), IndexerError>(())
            }
            .scope_boxed()
        })
        .await
        .tap_ok(|_| {
            let elapsed = guard.stop_and_record();
            info!(elapsed, "Persisted watermarks");
        })
        .tap_err(|e| {
            tracing::error!("Failed to persist watermarks with error: {}", e);
        })
    }

    async fn map_epochs_to_cp_tx(
        &self,
        epochs: &[u64],
    ) -> Result<HashMap<u64, (u64, u64)>, IndexerError> {
        use diesel_async::RunQueryDsl;

        let mut connection = self.pool.get().await?;

        let results: Vec<(i64, i64, Option<i64>)> = epochs::table
            .filter(epochs::epoch.eq_any(epochs.iter().map(|&e| e as i64)))
            .select((
                epochs::epoch,
                epochs::first_checkpoint_id,
                epochs::first_tx_sequence_number,
            ))
            .load::<(i64, i64, Option<i64>)>(&mut connection)
            .await
            .map_err(Into::into)
            .context("Failed to fetch first checkpoint and tx seq num for epochs")?;

        Ok(results
            .into_iter()
            .map(|(epoch, checkpoint, tx)| {
                (
                    epoch as u64,
                    (checkpoint as u64, tx.unwrap_or_default() as u64),
                )
            })
            .collect())
    }

    async fn update_watermarks_lower_bound(
        &self,
        watermarks: Vec<(PrunableTable, u64)>,
    ) -> Result<(), IndexerError> {
        use diesel_async::RunQueryDsl;

        let epochs: Vec<u64> = watermarks.iter().map(|(_table, epoch)| *epoch).collect();
        let epoch_mapping = self.map_epochs_to_cp_tx(&epochs).await?;
        let lookups: Result<Vec<StoredWatermark>, IndexerError> = watermarks
            .into_iter()
            .map(|(table, epoch)| {
                let (checkpoint, tx) = epoch_mapping.get(&epoch).ok_or_else(|| {
                    IndexerError::PersistentStorageDataCorruptionError(format!(
                        "Epoch {} not found in epoch mapping",
                        epoch
                    ))
                })?;

                Ok(StoredWatermark::from_lower_bound_update(
                    table.as_ref(),
                    epoch,
                    table.select_reader_lo(*checkpoint, *tx),
                ))
            })
            .collect();
        let lower_bound_updates = lookups?;

        let guard = self
            .metrics
            .checkpoint_db_commit_latency_watermarks
            .start_timer();

        transaction_with_retry(&self.pool, PG_DB_COMMIT_SLEEP_DURATION, |conn| {
            async {
                use diesel::dsl::sql;
                use diesel::query_dsl::methods::FilterDsl;

                diesel::insert_into(watermarks::table)
                    .values(lower_bound_updates)
                    .on_conflict(watermarks::pipeline)
                    .do_update()
                    .set((
                        watermarks::reader_lo.eq(excluded(watermarks::reader_lo)),
                        watermarks::epoch_lo.eq(excluded(watermarks::epoch_lo)),
                        watermarks::timestamp_ms.eq(sql::<diesel::sql_types::BigInt>(
                            "(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000)::bigint",
                        )),
                    ))
                    .filter(excluded(watermarks::reader_lo).gt(watermarks::reader_lo))
                    .filter(excluded(watermarks::epoch_lo).gt(watermarks::epoch_lo))
                    .filter(
                        diesel::dsl::sql::<diesel::sql_types::BigInt>(
                            "(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000)::bigint",
                        )
                        .gt(watermarks::timestamp_ms),
                    )
                    .execute(conn)
                    .await?;

                Ok::<(), IndexerError>(())
            }
            .scope_boxed()
        })
        .await
        .tap_ok(|_| {
            let elapsed = guard.stop_and_record();
            info!(elapsed, "Persisted watermarks");
        })
        .tap_err(|e| {
            tracing::error!("Failed to persist watermarks with error: {}", e);
        })
    }

    async fn get_watermarks(&self) -> Result<(Vec<StoredWatermark>, i64), IndexerError> {
        use diesel_async::RunQueryDsl;

        // read_only transaction, otherwise this will block and get blocked by write transactions to
        // the same table.
        read_with_retry(&self.pool, PG_DB_COMMIT_SLEEP_DURATION, |conn| {
            async {
                let stored = watermarks::table
                    .load::<StoredWatermark>(conn)
                    .await
                    .map_err(Into::into)
                    .context("Failed reading watermarks from PostgresDB")?;

                let timestamp = diesel::select(diesel::dsl::sql::<diesel::sql_types::BigInt>(
                    "(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000)::bigint",
                ))
                .get_result(conn)
                .await
                .map_err(Into::into)
                .context("Failed reading current timestamp from PostgresDB")?;

                Ok((stored, timestamp))
            }
            .scope_boxed()
        })
        .await
    }
}

#[async_trait]
impl IndexerStore for PgIndexerStore {
    async fn get_latest_checkpoint_sequence_number(&self) -> Result<Option<u64>, IndexerError> {
        self.get_latest_checkpoint_sequence_number().await
    }

    async fn get_available_epoch_range(&self) -> Result<(u64, u64), IndexerError> {
        self.get_prunable_epoch_range().await
    }

    async fn get_available_checkpoint_range(&self) -> Result<(u64, u64), IndexerError> {
        self.get_available_checkpoint_range().await
    }

    async fn get_chain_identifier(&self) -> Result<Option<Vec<u8>>, IndexerError> {
        self.get_chain_identifier().await
    }

    async fn get_latest_object_snapshot_checkpoint_sequence_number(
        &self,
    ) -> Result<Option<u64>, IndexerError> {
        self.get_latest_object_snapshot_checkpoint_sequence_number()
            .await
    }

    async fn persist_objects(
        &self,
        object_changes: Vec<TransactionObjectChangesToCommit>,
    ) -> Result<(), IndexerError> {
        if object_changes.is_empty() {
            return Ok(());
        }
        let guard = self
            .metrics
            .checkpoint_db_commit_latency_objects
            .start_timer();
        let (indexed_mutations, indexed_deletions) = retain_latest_indexed_objects(object_changes);
        let object_mutations = indexed_mutations
            .into_iter()
            .map(StoredObject::from)
            .collect::<Vec<_>>();
        let object_deletions = indexed_deletions
            .into_iter()
            .map(StoredDeletedObject::from)
            .collect::<Vec<_>>();
        let mutation_len = object_mutations.len();
        let deletion_len = object_deletions.len();

        let object_mutation_chunks =
            chunk!(object_mutations, self.config.parallel_objects_chunk_size);
        let object_deletion_chunks =
            chunk!(object_deletions, self.config.parallel_objects_chunk_size);
        let mutation_futures = object_mutation_chunks
            .into_iter()
            .map(|c| self.persist_object_mutation_chunk(c))
            .map(Either::Left);
        let deletion_futures = object_deletion_chunks
            .into_iter()
            .map(|c| self.persist_object_deletion_chunk(c))
            .map(Either::Right);
        let all_futures = mutation_futures.chain(deletion_futures).collect::<Vec<_>>();

        futures::future::join_all(all_futures)
            .await
            .into_iter()
            .collect::<Result<Vec<_>, _>>()
            .map_err(|e| {
                IndexerError::PostgresWriteError(format!(
                    "Failed to persist all object mutation or deletion chunks: {:?}",
                    e
                ))
            })?;
        let elapsed = guard.stop_and_record();
        info!(
            elapsed,
            "Persisted {} objects mutations and {} deletions", mutation_len, deletion_len
        );
        Ok(())
    }

    async fn persist_objects_snapshot(
        &self,
        object_changes: Vec<TransactionObjectChangesToCommit>,
    ) -> Result<(), IndexerError> {
        if object_changes.is_empty() {
            return Ok(());
        }
        let guard = self
            .metrics
            .checkpoint_db_commit_latency_objects_snapshot
            .start_timer();
        let (indexed_mutations, indexed_deletions) = retain_latest_indexed_objects(object_changes);
        let object_snapshot_mutations: Vec<StoredObjectSnapshot> = indexed_mutations
            .into_iter()
            .map(StoredObjectSnapshot::from)
            .collect();
        let object_snapshot_deletions: Vec<StoredObjectSnapshot> = indexed_deletions
            .into_iter()
            .map(StoredObjectSnapshot::from)
            .collect();
        let mutation_len = object_snapshot_mutations.len();
        let deletion_len = object_snapshot_deletions.len();
        let object_snapshot_mutation_chunks = chunk!(
            object_snapshot_mutations,
            self.config.parallel_objects_chunk_size
        );
        let object_snapshot_deletion_chunks = chunk!(
            object_snapshot_deletions,
            self.config.parallel_objects_chunk_size
        );
        let mutation_futures = object_snapshot_mutation_chunks
            .into_iter()
            .map(|c| self.persist_object_snapshot_mutation_chunk(c))
            .map(Either::Left)
            .collect::<Vec<_>>();
        let deletion_futures = object_snapshot_deletion_chunks
            .into_iter()
            .map(|c| self.persist_object_snapshot_deletion_chunk(c))
            .map(Either::Right)
            .collect::<Vec<_>>();
        let all_futures = mutation_futures
            .into_iter()
            .chain(deletion_futures)
            .collect::<Vec<_>>();
        futures::future::join_all(all_futures)
            .await
            .into_iter()
            .collect::<Result<Vec<_>, _>>()
            .map_err(|e| {
                IndexerError::PostgresWriteError(format!(
                    "Failed to persist object snapshot mutation or deletion chunks: {:?}",
                    e
                ))
            })
            .tap_ok(|_| {
                let elapsed = guard.stop_and_record();
                info!(
                    elapsed,
                    "Persisted {} objects snapshot mutations and {} deletions",
                    mutation_len,
                    deletion_len
                );
            })
            .tap_err(|e| {
                tracing::error!(
                    "Failed to persist object snapshot mutation or deletion chunks: {:?}",
                    e
                )
            })?;
        Ok(())
    }

    async fn persist_object_history(
        &self,
        object_changes: Vec<TransactionObjectChangesToCommit>,
    ) -> Result<(), IndexerError> {
        let skip_history = std::env::var("SKIP_OBJECT_HISTORY")
            .map(|val| val.eq_ignore_ascii_case("true"))
            .unwrap_or(false);
        if skip_history {
            info!("skipping object history");
            return Ok(());
        }

        if object_changes.is_empty() {
            return Ok(());
        }
        let objects = make_objects_history_to_commit(object_changes);
        let guard = self
            .metrics
            .checkpoint_db_commit_latency_objects_history
            .start_timer();

        let len = objects.len();
        let chunks = chunk!(objects, self.config.parallel_objects_chunk_size);
        let futures = chunks
            .into_iter()
            .map(|c| self.persist_objects_history_chunk(c))
            .collect::<Vec<_>>();

        futures::future::join_all(futures)
            .await
            .into_iter()
            .collect::<Result<Vec<_>, _>>()
            .map_err(|e| {
                IndexerError::PostgresWriteError(format!(
                    "Failed to persist all objects history chunks: {:?}",
                    e
                ))
            })?;
        let elapsed = guard.stop_and_record();
        info!(elapsed, "Persisted {} objects history", len);
        Ok(())
    }

    // TODO: There are quite some shared boiler-plate code in all functions.
    // We should clean them up eventually.
    async fn persist_full_objects_history(
        &self,
        object_changes: Vec<TransactionObjectChangesToCommit>,
    ) -> Result<(), IndexerError> {
        let skip_history = std::env::var("SKIP_OBJECT_HISTORY")
            .map(|val| val.eq_ignore_ascii_case("true"))
            .unwrap_or(false);
        if skip_history {
            info!("skipping object history");
            return Ok(());
        }

        if object_changes.is_empty() {
            return Ok(());
        }
        let objects: Vec<StoredFullHistoryObject> = object_changes
            .into_iter()
            .flat_map(|c| {
                let TransactionObjectChangesToCommit {
                    changed_objects,
                    deleted_objects,
                } = c;
                changed_objects
                    .into_iter()
                    .map(|o| o.into())
                    .chain(deleted_objects.into_iter().map(|o| o.into()))
            })
            .collect();
        let guard = self
            .metrics
            .checkpoint_db_commit_latency_full_objects_history
            .start_timer();

        let len = objects.len();
        let chunks = chunk!(objects, self.config.parallel_objects_chunk_size);
        let futures = chunks
            .into_iter()
            .map(|c| self.persist_full_objects_history_chunk(c))
            .collect::<Vec<_>>();

        futures::future::join_all(futures)
            .await
            .into_iter()
            .collect::<Result<Vec<_>, _>>()
            .map_err(|e| {
                IndexerError::PostgresWriteError(format!(
                    "Failed to persist all full objects history chunks: {:?}",
                    e
                ))
            })?;
        let elapsed = guard.stop_and_record();
        info!(elapsed, "Persisted {} full objects history", len);
        Ok(())
    }

    async fn persist_objects_version(
        &self,
        object_versions: Vec<StoredObjectVersion>,
    ) -> Result<(), IndexerError> {
        if object_versions.is_empty() {
            return Ok(());
        }

        let guard = self
            .metrics
            .checkpoint_db_commit_latency_objects_version
            .start_timer();

        let len = object_versions.len();
        let chunks = chunk!(object_versions, self.config.parallel_objects_chunk_size);
        let futures = chunks
            .into_iter()
            .map(|c| self.persist_objects_version_chunk(c))
            .collect::<Vec<_>>();

        futures::future::join_all(futures)
            .await
            .into_iter()
            .collect::<Result<Vec<_>, _>>()
            .map_err(|e| {
                IndexerError::PostgresWriteError(format!(
                    "Failed to persist all objects version chunks: {:?}",
                    e
                ))
            })?;

        let elapsed = guard.stop_and_record();
        info!(elapsed, "Persisted {} object versions", len);
        Ok(())
    }

    async fn persist_checkpoints(
        &self,
        checkpoints: Vec<IndexedCheckpoint>,
    ) -> Result<(), IndexerError> {
        self.persist_checkpoints(checkpoints).await
    }

    async fn persist_transactions(
        &self,
        transactions: Vec<IndexedTransaction>,
    ) -> Result<(), IndexerError> {
        let guard = self
            .metrics
            .checkpoint_db_commit_latency_transactions
            .start_timer();
        let len = transactions.len();

        let chunks = chunk!(transactions, self.config.parallel_chunk_size);
        let futures = chunks
            .into_iter()
            .map(|c| self.persist_transactions_chunk(c))
            .collect::<Vec<_>>();

        futures::future::join_all(futures)
            .await
            .into_iter()
            .collect::<Result<Vec<_>, _>>()
            .map_err(|e| {
                IndexerError::PostgresWriteError(format!(
                    "Failed to persist all transactions chunks: {:?}",
                    e
                ))
            })?;
        let elapsed = guard.stop_and_record();
        info!(elapsed, "Persisted {} transactions", len);
        Ok(())
    }

    async fn persist_events(&self, events: Vec<IndexedEvent>) -> Result<(), IndexerError> {
        if events.is_empty() {
            return Ok(());
        }
        let len = events.len();
        let guard = self
            .metrics
            .checkpoint_db_commit_latency_events
            .start_timer();
        let chunks = chunk!(events, self.config.parallel_chunk_size);
        let futures = chunks
            .into_iter()
            .map(|c| self.persist_events_chunk(c))
            .collect::<Vec<_>>();

        futures::future::join_all(futures)
            .await
            .into_iter()
            .collect::<Result<Vec<_>, _>>()
            .map_err(|e| {
                IndexerError::PostgresWriteError(format!(
                    "Failed to persist all events chunks: {:?}",
                    e
                ))
            })?;
        let elapsed = guard.stop_and_record();
        info!(elapsed, "Persisted {} events", len);
        Ok(())
    }

    async fn persist_displays(
        &self,
        display_updates: BTreeMap<String, StoredDisplay>,
    ) -> Result<(), IndexerError> {
        if display_updates.is_empty() {
            return Ok(());
        }
        self.persist_display_updates(display_updates.values().cloned().collect::<Vec<_>>())
            .await
    }

    async fn persist_packages(&self, packages: Vec<IndexedPackage>) -> Result<(), IndexerError> {
        if packages.is_empty() {
            return Ok(());
        }
        self.persist_packages(packages).await
    }

    async fn persist_event_indices(&self, indices: Vec<EventIndex>) -> Result<(), IndexerError> {
        if indices.is_empty() {
            return Ok(());
        }
        let len = indices.len();
        let guard = self
            .metrics
            .checkpoint_db_commit_latency_event_indices
            .start_timer();
        let chunks = chunk!(indices, self.config.parallel_chunk_size);

        let futures = chunks
            .into_iter()
            .map(|chunk| self.persist_event_indices_chunk(chunk))
            .collect::<Vec<_>>();
        futures::future::join_all(futures)
            .await
            .into_iter()
            .collect::<Result<Vec<_>, _>>()
            .map_err(|e| {
                IndexerError::PostgresWriteError(format!(
                    "Failed to persist all event_indices chunks: {:?}",
                    e
                ))
            })
            .tap_ok(|_| {
                let elapsed = guard.stop_and_record();
                info!(elapsed, "Persisted {} event_indices chunks", len);
            })
            .tap_err(|e| tracing::error!("Failed to persist all event_indices chunks: {:?}", e))?;
        Ok(())
    }

    async fn persist_tx_indices(&self, indices: Vec<TxIndex>) -> Result<(), IndexerError> {
        if indices.is_empty() {
            return Ok(());
        }
        let len = indices.len();
        let guard = self
            .metrics
            .checkpoint_db_commit_latency_tx_indices
            .start_timer();
        let chunks = chunk!(indices, self.config.parallel_chunk_size);

        let futures = chunks
            .into_iter()
            .map(|chunk| self.persist_tx_indices_chunk(chunk))
            .collect::<Vec<_>>();
        futures::future::join_all(futures)
            .await
            .into_iter()
            .collect::<Result<Vec<_>, _>>()
            .map_err(|e| {
                IndexerError::PostgresWriteError(format!(
                    "Failed to persist all tx_indices chunks: {:?}",
                    e
                ))
            })
            .tap_ok(|_| {
                let elapsed = guard.stop_and_record();
                info!(elapsed, "Persisted {} tx_indices chunks", len);
            })
            .tap_err(|e| tracing::error!("Failed to persist all tx_indices chunks: {:?}", e))?;
        Ok(())
    }

    async fn persist_epoch(&self, epoch: EpochToCommit) -> Result<(), IndexerError> {
        self.persist_epoch(epoch).await
    }

    async fn advance_epoch(&self, epoch: EpochToCommit) -> Result<(), IndexerError> {
        self.advance_epoch(epoch).await
    }

    async fn prune_epoch(&self, epoch: u64) -> Result<(), IndexerError> {
        let (mut min_cp, max_cp) = match self.get_checkpoint_range_for_epoch(epoch).await? {
            (min_cp, Some(max_cp)) => Ok((min_cp, max_cp)),
            _ => Err(IndexerError::PostgresReadError(format!(
                "Failed to get checkpoint range for epoch {}",
                epoch
            ))),
        }?;

        // NOTE: for disaster recovery, min_cp is the min cp of the current epoch, which is likely
        // partially pruned already. min_prunable_cp is the min cp to be pruned.
        // By std::cmp::max, we will resume the pruning process from the next checkpoint, instead of
        // the first cp of the current epoch.
        let min_prunable_cp = self.get_min_prunable_checkpoint().await?;
        min_cp = std::cmp::max(min_cp, min_prunable_cp);
        for cp in min_cp..=max_cp {
            // NOTE: the order of pruning tables is crucial:
            // 1. prune tx_* tables;
            // 2. prune event_* tables;
            // 3. then prune pruner_cp_watermark table, which is the checkpoint pruning watermark table and also tx seq source
            // of a checkpoint to prune tx_* tables;
            // 4. lastly prune checkpoints table, because wait_for_graphql_checkpoint_pruned
            // uses this table as the pruning watermark table.
            info!(
                "Pruning checkpoint {} of epoch {} (min_prunable_cp: {})",
                cp, epoch, min_prunable_cp
            );

            let (min_tx, max_tx) = self.get_transaction_range_for_checkpoint(cp).await?;
            self.prune_tx_indices_table(min_tx, max_tx).await?;
            info!(
                "Pruned transactions for checkpoint {} from tx {} to tx {}",
                cp, min_tx, max_tx
            );
            self.prune_event_indices_table(min_tx, max_tx).await?;
            info!(
                "Pruned events of transactions for checkpoint {} from tx {} to tx {}",
                cp, min_tx, max_tx
            );
            self.metrics.last_pruned_transaction.set(max_tx as i64);

            self.prune_cp_tx_table(cp).await?;
            // NOTE: prune checkpoints table last b/c wait_for_graphql_checkpoint_pruned
            // uses this table as the watermark table.
            self.prune_checkpoints_table(cp).await?;

            info!("Pruned checkpoint {} of epoch {}", cp, epoch);
            self.metrics.last_pruned_checkpoint.set(cp as i64);
        }

        Ok(())
    }

    async fn upload_display(&self, epoch_number: u64) -> Result<(), IndexerError> {
        use diesel_async::RunQueryDsl;
        let mut connection = self.pool.get().await?;
        let mut buffer = Cursor::new(Vec::new());
        {
            let mut writer = Writer::from_writer(&mut buffer);
            let displays = display::table
                .load::<StoredDisplay>(&mut connection)
                .await
                .map_err(Into::into)
                .context("Failed to get display from database")?;
            info!("Read {} displays", displays.len());
            writer
                .write_record(["object_type", "id", "version", "bcs"])
                .map_err(|_| {
                    IndexerError::GcsError("Failed to write display to csv".to_string())
                })?;
            for display in displays {
                writer
                    .write_record(&[
                        display.object_type,
                        hex::encode(display.id),
                        display.version.to_string(),
                        hex::encode(display.bcs),
                    ])
                    .map_err(|_| IndexerError::GcsError("Failed to write to csv".to_string()))?;
            }
            writer
                .flush()
                .map_err(|_| IndexerError::GcsError("Failed to flush csv".to_string()))?;
        }

        if let (Some(cred_path), Some(bucket)) = (
            self.config.gcs_cred_path.clone(),
            self.config.gcs_display_bucket.clone(),
        ) {
            let remote_store_config = ObjectStoreConfig {
                object_store: Some(ObjectStoreType::GCS),
                bucket: Some(bucket),
                google_service_account: Some(cred_path),
                object_store_connection_limit: 200,
                no_sign_request: false,
                ..Default::default()
            };
            let remote_store = remote_store_config.make().map_err(|e| {
                IndexerError::GcsError(format!("Failed to make GCS remote store: {}", e))
            })?;
            let path = Path::from(format!("display_{}.csv", epoch_number).as_str());
            put(&remote_store, &path, buffer.into_inner().into())
                .await
                .map_err(|e| IndexerError::GcsError(format!("Failed to put to GCS: {}", e)))?;
        } else {
            warn!("Either GCS cred path or bucket is not set, skipping display upload.");
        }
        Ok(())
    }

    async fn restore_display(&self, bytes: bytes::Bytes) -> Result<(), IndexerError> {
        let cursor = Cursor::new(bytes);
        let mut csv_reader = ReaderBuilder::new().has_headers(true).from_reader(cursor);
        let displays = csv_reader
            .deserialize()
            .collect::<Result<Vec<StoredDisplay>, csv::Error>>()
            .map_err(|e| {
                IndexerError::GcsError(format!("Failed to deserialize display records: {}", e))
            })?;
        self.persist_display_updates(displays).await
    }

    async fn get_network_total_transactions_by_end_of_epoch(
        &self,
        epoch: u64,
    ) -> Result<Option<u64>, IndexerError> {
        self.get_network_total_transactions_by_end_of_epoch(epoch)
            .await
    }

    /// Persist protocol configs and feature flags until the protocol version for the latest epoch
    /// we have stored in the db, inclusive.
    async fn persist_protocol_configs_and_feature_flags(
        &self,
        chain_id: Vec<u8>,
    ) -> Result<(), IndexerError> {
        use diesel_async::RunQueryDsl;

        let chain_id = ChainIdentifier::from(
            CheckpointDigest::try_from(chain_id).expect("Unable to convert chain id"),
        );

        let mut all_configs = vec![];
        let mut all_flags = vec![];

        let (start_version, end_version) = self.get_protocol_version_index_range().await?;
        info!(
            "Persisting protocol configs with start_version: {}, end_version: {}",
            start_version, end_version
        );

        // Gather all protocol configs and feature flags for all versions between start and end.
        for version in start_version..=end_version {
            let protocol_configs = ProtocolConfig::get_for_version_if_supported(
                (version as u64).into(),
                chain_id.chain(),
            )
            .ok_or(IndexerError::GenericError(format!(
                "Unable to fetch protocol version {} and chain {:?}",
                version,
                chain_id.chain()
            )))?;
            let configs_vec = protocol_configs
                .attr_map()
                .into_iter()
                .map(|(k, v)| StoredProtocolConfig {
                    protocol_version: version,
                    config_name: k,
                    config_value: v.map(|v| v.to_string()),
                })
                .collect::<Vec<_>>();
            all_configs.extend(configs_vec);

            let feature_flags = protocol_configs
                .feature_map()
                .into_iter()
                .map(|(k, v)| StoredFeatureFlag {
                    protocol_version: version,
                    flag_name: k,
                    flag_value: v,
                })
                .collect::<Vec<_>>();
            all_flags.extend(feature_flags);
        }

        // Now insert all of them into the db.
        // TODO: right now the size of these updates is manageable but later we may consider batching.
        transaction_with_retry(&self.pool, PG_DB_COMMIT_SLEEP_DURATION, |conn| {
            async {
                for config_chunk in all_configs.chunks(PG_COMMIT_CHUNK_SIZE_INTRA_DB_TX) {
                    diesel::insert_into(protocol_configs::table)
                        .values(config_chunk)
                        .on_conflict_do_nothing()
                        .execute(conn)
                        .await
                        .map_err(IndexerError::from)
                        .context("Failed to write to protocol_configs table")?;
                }

                diesel::insert_into(feature_flags::table)
                    .values(all_flags.clone())
                    .on_conflict_do_nothing()
                    .execute(conn)
                    .await
                    .map_err(IndexerError::from)
                    .context("Failed to write to feature_flags table")?;
                Ok::<(), IndexerError>(())
            }
            .scope_boxed()
        })
        .await?;
        Ok(())
    }

    async fn persist_chain_identifier(
        &self,
        checkpoint_digest: Vec<u8>,
    ) -> Result<(), IndexerError> {
        use diesel_async::RunQueryDsl;

        transaction_with_retry(&self.pool, PG_DB_COMMIT_SLEEP_DURATION, |conn| {
            async {
                diesel::insert_into(chain_identifier::table)
                    .values(StoredChainIdentifier { checkpoint_digest })
                    .on_conflict_do_nothing()
                    .execute(conn)
                    .await
                    .map_err(IndexerError::from)
                    .context("failed to write to chain_identifier table")?;
                Ok::<(), IndexerError>(())
            }
            .scope_boxed()
        })
        .await?;
        Ok(())
    }

    async fn persist_raw_checkpoints(
        &self,
        checkpoints: Vec<StoredRawCheckpoint>,
    ) -> Result<(), IndexerError> {
        self.persist_raw_checkpoints_impl(&checkpoints).await
    }

    async fn update_watermarks_upper_bound<E: IntoEnumIterator>(
        &self,
        watermark: CommitterWatermark,
    ) -> Result<(), IndexerError>
    where
        E::Iterator: Iterator<Item: AsRef<str>>,
    {
        self.update_watermarks_upper_bound::<E>(watermark).await
    }

    async fn update_watermarks_lower_bound(
        &self,
        watermarks: Vec<(PrunableTable, u64)>,
    ) -> Result<(), IndexerError> {
        self.update_watermarks_lower_bound(watermarks).await
    }

    async fn get_watermarks(&self) -> Result<(Vec<StoredWatermark>, i64), IndexerError> {
        self.get_watermarks().await
    }
}

fn make_objects_history_to_commit(
    tx_object_changes: Vec<TransactionObjectChangesToCommit>,
) -> Vec<StoredHistoryObject> {
    let deleted_objects: Vec<StoredHistoryObject> = tx_object_changes
        .clone()
        .into_iter()
        .flat_map(|changes| changes.deleted_objects)
        .map(|o| o.into())
        .collect();
    let mutated_objects: Vec<StoredHistoryObject> = tx_object_changes
        .into_iter()
        .flat_map(|changes| changes.changed_objects)
        .map(|o| o.into())
        .collect();
    deleted_objects.into_iter().chain(mutated_objects).collect()
}

// Partition object changes into deletions and mutations,
// within partition of mutations or deletions, retain the latest with highest version;
// For overlappings of mutations and deletions, only keep one with higher version.
// This is necessary b/c after this step, DB commit will be done in parallel and not in order.
fn retain_latest_indexed_objects(
    tx_object_changes: Vec<TransactionObjectChangesToCommit>,
) -> (Vec<IndexedObject>, Vec<IndexedDeletedObject>) {
    // Only the last deleted / mutated object will be in the map,
    // b/c tx_object_changes are in order and versions always increment,
    let (mutations, deletions) = tx_object_changes
        .into_iter()
        .flat_map(|change| {
            change
                .changed_objects
                .into_iter()
                .map(Either::Left)
                .chain(
                    change
                        .deleted_objects
                        .into_iter()
                        .map(Either::Right),
                )
        })
        .fold(
            (HashMap::<ObjectID, IndexedObject>::new(), HashMap::<ObjectID, IndexedDeletedObject>::new()),
            |(mut mutations, mut deletions), either_change| {
                match either_change {
                    // Remove mutation / deletion with a following deletion / mutation,
                    // b/c following deletion / mutation always has a higher version.
                    // Technically, assertions below are not required, double check just in case.
                    Either::Left(mutation) => {
                        let id = mutation.object.id();
                        let mutation_version = mutation.object.version();
                        if let Some(existing) = deletions.remove(&id) {
                            assert!(
                                existing.object_version < mutation_version.value(),
                                "Mutation version ({:?}) should be greater than existing deletion version ({:?}) for object {:?}",
                                mutation_version,
                                existing.object_version,
                                id
                            );
                        }
                        if let Some(existing) = mutations.insert(id, mutation) {
                            assert!(
                                existing.object.version() < mutation_version,
                                "Mutation version ({:?}) should be greater than existing mutation version ({:?}) for object {:?}",
                                mutation_version,
                                existing.object.version(),
                                id
                            );
                        }
                    }
                    Either::Right(deletion) => {
                        let id = deletion.object_id;
                        let deletion_version = deletion.object_version;
                        if let Some(existing) = mutations.remove(&id) {
                            assert!(
                                existing.object.version().value() < deletion_version,
                                "Deletion version ({:?}) should be greater than existing mutation version ({:?}) for object {:?}",
                                deletion_version,
                                existing.object.version(),
                                id
                            );
                        }
                        if let Some(existing) = deletions.insert(id, deletion) {
                            assert!(
                                existing.object_version < deletion_version,
                                "Deletion version ({:?}) should be greater than existing deletion version ({:?}) for object {:?}",
                                deletion_version,
                                existing.object_version,
                                id
                            );
                        }
                    }
                }
                (mutations, deletions)
            },
        );
    (
        mutations.into_values().collect(),
        deletions.into_values().collect(),
    )
}