summaryrefslogtreecommitdiff
path: root/source/Felix/Store.hs
blob: bf84f6e0e74d7ca39d0e4c949c1220fb15e65131 (plain)
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
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE NoImplicitPrelude #-}

-- | Coordinator-owned access to the disposable SQLite store.
module Felix.Store
    ( Store
    , StoreSelection(..)
    , StorePlan
    , StorePath
    , storePathFilePath
    , storeRollbackJournalPath
    , StorePlanningError(..)
    , renderStorePlanningError
    , planStore
    , StoreLease
    , storeLeasePath
    , withStoreLease
    , StoreLifecycleError(..)
    , renderStoreLifecycleError
    , withOpenStore
    , StoreStartup(..)
    , StoreCompatibility(..)
    , currentStoreCompatibility
    , StoreIncompatibility(..)
    , renderStoreIncompatibility
    , StoreOpenError(..)
    , renderStoreOpenError
    , StoreRelation(..)
    , StoreFailure(..)
    , renderStoreFailure
    , openStore
    , closeStore
    , loadProofValidation
    , loadDeclarationValidation
    , loadParsedArtifact
    , writeParsedArtifact
    , CachedModuleInstallation
    , cachedInstallationSyntax
    , cachedInstallationSemantic
    , cachedInstallationObjects
    , cachedInstallationPropositions
    , cachedInstallationFinalPrefix
    , loadCachedModuleInstallation
    , writePendingModulePrefix
    , writeSealedModule
    , StoreMemo
    , newStoreMemo
    , StoreMemoVisits(..)
    , storeMemoVisits
    , StoreCoordinator
    , newStoreCoordinator
    , withStoreCoordinator
    ) where

import Base
import Checking.Core
import Checking.Declaration qualified as Declaration
import Checking.Identity
import Checking.Materialization qualified as Materialization
import Checking.Semantic
import Felix.Cache.Codec
import Felix.Module (ModuleName)
import Felix.Parsed.Identity qualified as Parsed
import Felix.Parsed.Payload qualified as ParsedPayload
import Syntax.Interface qualified as Syntax

import Control.Concurrent.MVar
    ( MVar
    , newMVar
    , withMVar
    )
import Control.Exception qualified as Exception
import Control.Monad (foldM, unless)
import Control.Monad.Except qualified as Except
import Data.Bifunctor (first)
import Data.ByteString (ByteString)
import Data.Int (Int64)
import Data.Map.Strict qualified as Map
import Data.Set qualified as Set
import Data.Text qualified as Text
import Data.Word (Word32)
import Data.IORef qualified as IORef
import Database.SQLite.Simple qualified as SQLite
import Database.SQLite.Simple.Types (Only(..), Query(..))
import System.Directory qualified as Directory
import System.FilePath.Posix qualified as Posix
import System.IO.Temp qualified as Temp


data Store = Store
    !FilePath
    !TheoryId
    !SQLite.Connection

-- | The single invocation-local gateway for a store connection and its
-- ordinary 'IORef'-backed validation memo.  Module checkers may run in
-- parallel, but every SQLite and memo operation remains coordinator-owned.
newtype StoreCoordinator = StoreCoordinator (MVar ())

newStoreCoordinator :: IO StoreCoordinator
newStoreCoordinator = StoreCoordinator <$> newMVar ()

withStoreCoordinator :: StoreCoordinator -> IO value -> IO value
withStoreCoordinator (StoreCoordinator ownership) action =
    withMVar ownership (const action)

-- | A completely validated, inert cached module.  Runtime authority is
-- minted only after this value is adopted by 'Checking.Module'.
data CachedModuleInstallation = CachedModuleInstallation
    !Syntax.ModuleSyntaxInterface
    !SemanticInterface
    ![AssertedObject]
    ![CheckedPropositionContent]
    !PrefixContextId

cachedInstallationSyntax
    :: CachedModuleInstallation
    -> Syntax.ModuleSyntaxInterface
cachedInstallationSyntax
        (CachedModuleInstallation syntax _semantic
            _objects _propositions _prefix) =
    syntax

cachedInstallationSemantic
    :: CachedModuleInstallation
    -> SemanticInterface
cachedInstallationSemantic
        (CachedModuleInstallation _syntax semantic
            _objects _propositions _prefix) =
    semantic

cachedInstallationObjects
    :: CachedModuleInstallation
    -> [AssertedObject]
cachedInstallationObjects
        (CachedModuleInstallation _syntax _semantic
            objects _propositions _prefix) =
    objects

cachedInstallationPropositions
    :: CachedModuleInstallation
    -> [CheckedPropositionContent]
cachedInstallationPropositions
        (CachedModuleInstallation _syntax _semantic
            _objects propositions _prefix) =
    propositions

cachedInstallationFinalPrefix
    :: CachedModuleInstallation
    -> PrefixContextId
cachedInstallationFinalPrefix
        (CachedModuleInstallation _syntax _semantic
            _objects _propositions prefix) =
    prefix

-- | Invocation-local decoded row memo.  It never changes a persistent row
-- and is discarded with the coordinator invocation.  Its ordinary IORefs are
-- coordinator-confined: operations on one memo must remain sequential or be
-- serialized by that coordinator.
data StoreMemo = StoreMemo
    { memoArtifactRows :: !(IORef.IORef
        (Map ModuleArtifactId
            (Either StoreFailure (Maybe ModuleArtifactResult))))
    , memoSyntaxRows :: !(IORef.IORef
        (Map Syntax.SyntaxInterfaceId
            (Either StoreFailure (Maybe Syntax.ModuleSyntaxInterface))))
    , memoSemanticRows :: !(IORef.IORef
        (Map SemanticInterfaceId
            (Either StoreFailure (Maybe SemanticInterface))))
    , memoObjectRows :: !(IORef.IORef
        (Map ObjectId (Either StoreFailure (Maybe AssertedObject))))
    , memoPropositionRows :: !(IORef.IORef
        (Map PropositionId
            (Either StoreFailure (Maybe (CanonicalTerm ObjectId)))))
    , memoValidatedSyntax :: !(IORef.IORef (Set Syntax.SyntaxInterfaceId))
    , memoValidatedSemantic :: !(IORef.IORef (Set SemanticInterfaceId))
    , memoCheckedObjects :: !(IORef.IORef CheckedObjectClosure)
    , memoValidatedPropositions :: !(IORef.IORef
        (Map PropositionId CheckedPropositionContent))
    , memoValidatedArtifacts :: !(IORef.IORef (Set ModuleArtifactId))
    , memoSyntaxValidationVisits :: !(IORef.IORef Int)
    , memoSemanticValidationVisits :: !(IORef.IORef Int)
    , memoObjectValidationVisits :: !(IORef.IORef Int)
    , memoPropositionValidationVisits :: !(IORef.IORef Int)
    , memoArtifactValidationVisits :: !(IORef.IORef Int)
    }

-- Root-scoped validation carries one flat inventory through a deterministic
-- visited fold.  Immutable rows and their validation results are memoized
-- above, but complete transitive inventories are not retained per interface.
data SemanticInventory = SemanticInventory
    !(Set SemanticFactOccurrenceFingerprint)
    !(Map SemanticName SemanticFactOccurrenceFingerprint)
    !(Map SemanticGlobalKey SemanticGlobalTarget)

data StoreMemoVisits = StoreMemoVisits
    { storeArtifactRowsDecoded :: !Int
    , storeSyntaxRowsDecoded :: !Int
    , storeSyntaxRowsValidated :: !Int
    , storeSemanticRowsDecoded :: !Int
    , storeSemanticRowsValidated :: !Int
    , storeObjectRowsDecoded :: !Int
    , storeObjectRowsValidated :: !Int
    , storePropositionRowsDecoded :: !Int
    , storePropositionRowsValidated :: !Int
    , storeArtifactsValidated :: !Int
    }
    deriving stock (Show, Eq)

newStoreMemo :: Store -> IO StoreMemo
newStoreMemo (Store _path theory _connection) = do
    emptyClosure <-
        case validateObjectClosure theory [] of
            Right closure -> pure closure
            Left _ -> impossible "empty store object closure is invalid"
    artifactRows <- IORef.newIORef Map.empty
    syntaxRows <- IORef.newIORef Map.empty
    semanticRows <- IORef.newIORef Map.empty
    objectRows <- IORef.newIORef Map.empty
    propositionRows <- IORef.newIORef Map.empty
    validatedSyntax <- IORef.newIORef Set.empty
    validatedSemantic <- IORef.newIORef Set.empty
    checkedObjects <- IORef.newIORef emptyClosure
    validatedPropositions <- IORef.newIORef Map.empty
    validatedArtifacts <- IORef.newIORef Set.empty
    syntaxVisits <- IORef.newIORef 0
    semanticVisits <- IORef.newIORef 0
    objectVisits <- IORef.newIORef 0
    propositionVisits <- IORef.newIORef 0
    artifactVisits <- IORef.newIORef 0
    pure
        StoreMemo
            { memoArtifactRows = artifactRows
            , memoSyntaxRows = syntaxRows
            , memoSemanticRows = semanticRows
            , memoObjectRows = objectRows
            , memoPropositionRows = propositionRows
            , memoValidatedSyntax = validatedSyntax
            , memoValidatedSemantic = validatedSemantic
            , memoCheckedObjects = checkedObjects
            , memoValidatedPropositions = validatedPropositions
            , memoValidatedArtifacts = validatedArtifacts
            , memoSyntaxValidationVisits = syntaxVisits
            , memoSemanticValidationVisits = semanticVisits
            , memoObjectValidationVisits = objectVisits
            , memoPropositionValidationVisits = propositionVisits
            , memoArtifactValidationVisits = artifactVisits
            }

storeMemoVisits :: StoreMemo -> IO StoreMemoVisits
storeMemoVisits memo = do
    artifactRows <- IORef.readIORef (memoArtifactRows memo)
    syntaxRows <- IORef.readIORef (memoSyntaxRows memo)
    semanticRows <- IORef.readIORef (memoSemanticRows memo)
    objectRows <- IORef.readIORef (memoObjectRows memo)
    propositionRows <- IORef.readIORef (memoPropositionRows memo)
    syntaxVisits <- IORef.readIORef (memoSyntaxValidationVisits memo)
    semanticVisits <- IORef.readIORef (memoSemanticValidationVisits memo)
    objectVisits <- IORef.readIORef (memoObjectValidationVisits memo)
    propositionVisits <-
        IORef.readIORef (memoPropositionValidationVisits memo)
    artifactVisits <- IORef.readIORef (memoArtifactValidationVisits memo)
    pure
        StoreMemoVisits
            { storeArtifactRowsDecoded = Map.size artifactRows
            , storeSyntaxRowsDecoded = Map.size syntaxRows
            , storeSyntaxRowsValidated = syntaxVisits
            , storeSemanticRowsDecoded = Map.size semanticRows
            , storeSemanticRowsValidated = semanticVisits
            , storeObjectRowsDecoded = Map.size objectRows
            , storeObjectRowsValidated = objectVisits
            , storePropositionRowsDecoded = Map.size propositionRows
            , storePropositionRowsValidated =
                propositionVisits
            , storeArtifactsValidated = artifactVisits
            }

data StoreSelection
    = DefaultStore
    | ExplicitStore !FilePath
    | FreshTemporaryStore
    deriving stock (Show, Eq)

data StorePlan
    = DefaultStorePlan !StorePath
    | ExplicitStorePlan !StorePath
    | FreshStorePlan
    deriving stock (Show, Eq)

newtype StorePath = StorePath FilePath
    deriving stock (Show, Eq, Ord)

storePathFilePath :: StorePath -> FilePath
storePathFilePath (StorePath path) =
    path

storeRollbackJournalPath :: StorePath -> FilePath
storeRollbackJournalPath storePath =
    storePathFilePath storePath <> "-journal"

data StorePlanningError
    = StorePathResolutionFailed !FilePath !Text
    | ExplicitStoreParentMissing !FilePath
    | ExplicitStoreParentNotDirectory !FilePath
    deriving stock (Show, Eq)

renderStorePlanningError :: StorePlanningError -> Text
renderStorePlanningError = \case
    StorePathResolutionFailed path reason ->
        "could not resolve store path " <> quotePath path <> ": " <> reason
    ExplicitStoreParentMissing parent ->
        "the parent of --store does not exist: " <> quotePath parent
    ExplicitStoreParentNotDirectory parent ->
        "the parent of --store is not a directory: " <> quotePath parent

data StoreLease = StoreLease
    !StorePlan
    !StorePath

storeLeasePath :: StoreLease -> StorePath
storeLeasePath (StoreLease _plan path) =
    path

data StoreLifecycleError
    = StoreParentCreationFailed !FilePath !Text
    | StoreLifecycleOpenFailed !StoreOpenError
    | StoreCloseFailed !StoreFailure
    deriving stock (Show, Eq)

renderStoreLifecycleError :: StoreLifecycleError -> Text
renderStoreLifecycleError = \case
    StoreParentCreationFailed parent reason ->
        "could not create default store directory " <> quotePath parent
            <> ": " <> reason
    StoreLifecycleOpenFailed failure ->
        renderStoreOpenError failure
    StoreCloseFailed failure ->
        "could not close the selected store: " <> renderStoreFailure failure

data StoreStartup
    = InitializedNewStore
    | OpenedCurrentStore
    deriving stock (Show, Eq)


planStore
    :: StoreSelection
    -> IO (Either StorePlanningError StorePlan)
planStore = \case
    DefaultStore -> do
        resolved <- trySynchronous do
            cacheDirectory <-
                Directory.getXdgDirectory
                    Directory.XdgCache
                    "felix"
            normalizeAbsolutePath
                (cacheDirectory Posix.</> "store.sqlite")
        pure
            (case resolved of
                Left failure ->
                    Left
                        (StorePathResolutionFailed
                            "felix/store.sqlite"
                            (exceptionText failure))
                Right path ->
                    Right
                        (DefaultStorePlan
                            (StorePath path)))
    ExplicitStore requested -> do
        resolved <- trySynchronous
            (normalizeAbsolutePath requested)
        case resolved of
            Left failure ->
                pure
                    (Left
                        (StorePathResolutionFailed
                            requested
                            (exceptionText failure)))
            Right path -> do
                let parent = Posix.takeDirectory path
                inspected <- trySynchronous do
                    exists <- Directory.doesPathExist parent
                    directory <- Directory.doesDirectoryExist parent
                    pure (exists, directory)
                pure
                    (case inspected of
                        Left failure ->
                            Left
                                (StorePathResolutionFailed
                                    parent
                                    (exceptionText failure))
                        Right (False, _isDirectory) ->
                            Left
                                (ExplicitStoreParentMissing parent)
                        Right (True, False) ->
                            Left
                                (ExplicitStoreParentNotDirectory parent)
                        Right (True, True) ->
                            Right
                                (ExplicitStorePlan
                                    (StorePath path)))
    FreshTemporaryStore ->
        pure (Right FreshStorePlan)

withStoreLease
    :: StorePlan
    -> (StoreLease -> IO value)
    -> IO value
withStoreLease plan action =
    case plan of
        DefaultStorePlan path ->
            action (StoreLease plan path)
        ExplicitStorePlan path ->
            action (StoreLease plan path)
        FreshStorePlan ->
            Temp.withSystemTempDirectory
                "felix-store"
                \directory -> do
                    path <- normalizeAbsolutePath
                        (directory Posix.</> "store.sqlite")
                    action
                        (StoreLease
                            plan
                            (StorePath path))

withOpenStore
    :: StoreLease
    -> TheoryId
    -> (StoreStartup -> Store -> IO value)
    -> IO (Either StoreLifecycleError value)
withOpenStore
        (StoreLease plan path@(StorePath filePath))
        theory
        action = do
    prepared <- prepareStoreParent plan path
    case prepared of
        Left failure ->
            pure (Left failure)
        Right () ->
            Exception.mask \restore -> do
                opened <- restore (openStore filePath theory)
                case opened of
                    Left failure ->
                        pure
                            (Left
                                (StoreLifecycleOpenFailed failure))
                    Right (startup, store) -> do
                        result <- Exception.try
                            (restore (action startup store))
                        closed <- trySynchronous
                            (closeStore store)
                        case result of
                            Left failure ->
                                Exception.throwIO
                                    (failure
                                        :: Exception.SomeException)
                            Right value ->
                                pure
                                    (case closed of
                                        Left failure ->
                                            Left
                                                (StoreCloseFailed
                                                    (operationFailure
                                                        "close store"
                                                        failure))
                                        Right () ->
                                            Right value)

prepareStoreParent
    :: StorePlan
    -> StorePath
    -> IO (Either StoreLifecycleError ())
prepareStoreParent plan (StorePath path) =
    case plan of
        DefaultStorePlan _ -> do
            let parent = Posix.takeDirectory path
            created <- trySynchronous
                (Directory.createDirectoryIfMissing
                    True
                    parent)
            pure
                (case created of
                    Left failure ->
                        Left
                            (StoreParentCreationFailed
                                parent
                                (exceptionText failure))
                    Right () ->
                        Right ())
        ExplicitStorePlan _ ->
            pure (Right ())
        FreshStorePlan ->
            pure (Right ())

normalizeAbsolutePath :: FilePath -> IO FilePath
normalizeAbsolutePath path =
    Posix.normalise <$> Directory.makeAbsolute path

data StoreCompatibility = StoreCompatibility
    !CacheEpoch
    !TheoryId
    deriving stock (Show, Eq)

currentStoreCompatibility :: TheoryId -> StoreCompatibility
currentStoreCompatibility =
    StoreCompatibility currentCacheEpoch

data StoreIncompatibility
    = StoreCompatibilityMissing
    | StoreCompatibilityMalformed !Text
    | StoreCompatibilityMismatch
        !StoreCompatibility
        !StoreCompatibility
    deriving stock (Show, Eq)

renderStoreIncompatibility :: StoreIncompatibility -> Text
renderStoreIncompatibility = \case
    StoreCompatibilityMissing ->
        "compatibility metadata is missing"
    StoreCompatibilityMalformed reason ->
        "compatibility metadata is malformed: " <> reason
    StoreCompatibilityMismatch expected actual ->
        "compatibility differs: expected " <> renderCompatibility expected
            <> ", found " <> renderCompatibility actual

renderCompatibility :: StoreCompatibility -> Text
renderCompatibility (StoreCompatibility epoch theory) =
    "cache epoch " <> Text.pack (show (cacheEpochValue epoch))
        <> " and theory " <> Text.pack (show theory)

data StoreOpenError
    = IncompatibleStore !StoreIncompatibility
    | FatalStoreStartup !StoreFailure
    deriving stock (Show, Eq)

renderStoreOpenError :: StoreOpenError -> Text
renderStoreOpenError = \case
    IncompatibleStore incompatibility ->
        renderStoreIncompatibility incompatibility
    FatalStoreStartup failure ->
        renderStoreFailure failure

data StoreRelation
    = CanonicalObjects
    | CanonicalPropositions
    | ProofValidations
    | DeclarationValidations
    | SyntaxInterfaces
    | SemanticInterfaces
    | ModuleArtifacts
    | ParsedArtifacts
    deriving stock (Show, Eq, Ord)

data StoreFailure
    = StoreOperationFailed !Text !Text
    | StoreSchemaIntegrityFailure !Text
    | StoreConfigurationFailure !Text
    | StoreRowPayloadMismatch
        !StoreRelation
        !ByteString
    | StoreRowDecodeFailure
        !StoreRelation
        !ByteString
        !CacheDecodeError
    | StoreObjectValidationFailure !ObjectValidationError
    | StorePropositionValidationFailure !PropositionValidationError
    | StoreValidationRecordKeyMismatch !StoreRelation
    | StoreInterfaceIdMismatch !StoreRelation
    | StoreSyntaxInterfaceValidationFailure
        !Syntax.SyntaxInterfaceError
    | StoreSemanticInterfaceValidationFailure
        !SemanticInterfaceError
    | StoreModuleArtifactIdMismatch
    | StoreParsedArtifactIdMismatch
    | StoreModuleArtifactColumnsMismatch
    | StoreModuleArtifactSyntaxMismatch
        !Syntax.SyntaxInterfaceId !Syntax.SyntaxInterfaceId
    | StoreModuleArtifactOwnerMismatch !ModuleName !ModuleName
    | StoreModuleArtifactDirectMismatch
        ![SemanticInterfaceId] ![SemanticInterfaceId]
    | StoreModuleArtifactTheoryMismatch !TheoryId !TheoryId
    | StoreModulePrefixFailure !PrefixContextError
    | StoreModulePrefixMismatch
    | StoreImportedOccurrenceValidationFailure
        !Materialization.MaterializationError
    | StoreSemanticAliasTargetMissing
        !SemanticFactOccurrenceFingerprint
    | StoreSemanticAliasCollision !SemanticName
    | StoreSemanticGlobalTargetFailure
        !SemanticGlobalKey
        !SemanticGlobalTarget
        !SemanticGlobalTargetError
    | StoreSemanticGlobalCollision
        !SemanticGlobalKey
        !SemanticGlobalTarget
        !SemanticGlobalTarget
    | StoreAssertedChildMissing
        !StoreRelation
        !ByteString
    deriving stock (Show, Eq)

renderStoreFailure :: StoreFailure -> Text
renderStoreFailure = \case
    StoreOperationFailed operation reason ->
        operation <> " failed: " <> reason
    StoreSchemaIntegrityFailure reason ->
        "current store schema is incomplete or inconsistent: " <> reason
    StoreConfigurationFailure reason ->
        "could not configure the current store: " <> reason
    StoreRowPayloadMismatch relation _key ->
        "stored canonical payload disagrees with an equal key in "
            <> renderStoreRelation relation
    StoreRowDecodeFailure relation _key _failure ->
        "stored canonical payload is malformed in "
            <> renderStoreRelation relation
    StoreObjectValidationFailure{} ->
        "stored canonical object failed identity validation"
    StorePropositionValidationFailure{} ->
        "stored canonical proposition failed identity validation"
    StoreValidationRecordKeyMismatch relation ->
        "stored validation row has the wrong key in "
            <> renderStoreRelation relation
    StoreInterfaceIdMismatch relation ->
        "stored interface row has the wrong asserted identity in "
            <> renderStoreRelation relation
    StoreSyntaxInterfaceValidationFailure failure ->
        "supplied syntax interface failed validation: "
            <> Text.pack (show failure)
    StoreSemanticInterfaceValidationFailure failure ->
        "supplied semantic interface failed validation: "
            <> Text.pack (show failure)
    StoreModuleArtifactIdMismatch ->
        "stored module artifact row has the wrong identity"
    StoreParsedArtifactIdMismatch ->
        "parsed artifact identity disagrees with its key and payload"
    StoreModuleArtifactColumnsMismatch ->
        "stored module artifact columns disagree with its canonical payload"
    StoreModuleArtifactSyntaxMismatch{} ->
        "stored module artifact does not match the current syntax interface"
    StoreModuleArtifactOwnerMismatch{} ->
        "stored module artifact has the wrong semantic owner"
    StoreModuleArtifactDirectMismatch{} ->
        "stored module artifact has the wrong direct semantic inputs"
    StoreModuleArtifactTheoryMismatch{} ->
        "stored module artifact belongs to a different theory"
    StoreModulePrefixFailure{} ->
        "stored module artifact has an invalid initial prefix"
    StoreModulePrefixMismatch ->
        "published module prefix does not match its semantic interface"
    StoreImportedOccurrenceValidationFailure{} ->
        "stored semantic occurrence failed authority validation"
    StoreSemanticAliasTargetMissing{} ->
        "stored semantic alias targets a missing occurrence"
    StoreSemanticAliasCollision{} ->
        "stored semantic aliases conflict across the import closure"
    StoreSemanticGlobalTargetFailure{} ->
        "stored semantic global has an invalid target"
    StoreSemanticGlobalCollision{} ->
        "stored semantic globals conflict across the import closure"
    StoreAssertedChildMissing relation _key ->
        "a module row asserts a missing child in "
            <> renderStoreRelation relation

renderStoreRelation :: StoreRelation -> Text
renderStoreRelation = \case
    CanonicalObjects -> "canonical_objects"
    CanonicalPropositions -> "canonical_propositions"
    ProofValidations -> "proof_validations"
    DeclarationValidations -> "declaration_validations"
    SyntaxInterfaces -> "syntax_interfaces"
    SemanticInterfaces -> "semantic_interfaces"
    ModuleArtifacts -> "module_artifacts"
    ParsedArtifacts -> "parsed_artifacts"

quotePath :: FilePath -> Text
quotePath = Text.pack . show

newtype StoreAbort = StoreAbort StoreFailure
    deriving stock (Show)

instance Exception.Exception StoreAbort


openStore
    :: FilePath
    -> TheoryId
    -> IO
        (Either
            StoreOpenError
            (StoreStartup, Store))
openStore path theory =
    Exception.mask \restore -> do
        opened <- trySynchronous (SQLite.open path)
        case opened of
            Left failure ->
                pure
                    (Left
                        (FatalStoreStartup
                            (operationFailure "open store" failure)))
            Right connection -> do
                startup <-
                    trySynchronous
                        (restore
                            (classifyAndStart connection theory))
                    `Exception.onException`
                        closeIgnoringFailure connection
                case startup of
                    Left failure -> do
                        closeIgnoringFailure connection
                        pure
                            (Left
                                (FatalStoreStartup
                                    (operationFailure
                                        "start store"
                                        failure)))
                    Right (Left openError) -> do
                        closeIgnoringFailure connection
                        pure (Left openError)
                    Right (Right status) ->
                        pure
                            (Right
                                ( status
                                , Store path theory connection
                                ))

closeStore :: Store -> IO ()
closeStore (Store _path _theory connection) =
    SQLite.close connection

classifyAndStart
    :: SQLite.Connection
    -> TheoryId
    -> IO (Either StoreOpenError StoreStartup)
classifyAndStart connection theory = do
    objects <- userSchemaObjects connection
    if null objects
        then do
            SQLite.withTransaction connection
                (initializeSchema connection theory)
            schema <- validateCurrentSchema connection
            case schema of
                Left failure ->
                    pure (Left (FatalStoreStartup failure))
                Right () -> do
                    configuration <- configureConnection connection
                    pure
                        (case configuration of
                            Left failure ->
                                Left (FatalStoreStartup failure)
                            Right () ->
                                Right InitializedNewStore)
        else do
            compatibility <- readExistingCompatibility connection objects
            case compatibility of
                Left incompatibility ->
                    pure (Left (IncompatibleStore incompatibility))
                Right actual
                    | actual /= expected ->
                        pure
                            (Left
                                (IncompatibleStore
                                    (StoreCompatibilityMismatch
                                        expected
                                        actual)))
                    | otherwise -> do
                        schema <- validateCurrentSchema connection
                        case schema of
                            Left failure ->
                                pure (Left (FatalStoreStartup failure))
                            Right () -> do
                                configuration <- configureConnection connection
                                pure
                                    (case configuration of
                                        Left failure ->
                                            Left (FatalStoreStartup failure)
                                        Right () ->
                                            Right OpenedCurrentStore)
  where
    expected = currentStoreCompatibility theory

userSchemaObjects
    :: SQLite.Connection
    -> IO [Text]
userSchemaObjects connection =
    fmap (\(Only value) -> value)
        <$> (SQLite.query_ connection
            "SELECT name FROM sqlite_master \
            \WHERE type IN ('table', 'index', 'view', 'trigger') \
            \AND name NOT LIKE 'sqlite_%' ORDER BY type, name"
            :: IO [Only Text])

readExistingCompatibility
    :: SQLite.Connection
    -> [Text]
    -> IO (Either StoreIncompatibility StoreCompatibility)
readExistingCompatibility connection objects
    | compatibilityTableName `notElem` objects =
        pure (Left StoreCompatibilityMissing)
    | otherwise = do
        shapeResult <- trySynchronous
            (SQLite.query_ connection
                "SELECT typeof(cache_epoch), typeof(theory_id) \
                \FROM store_compatibility ORDER BY singleton"
                :: IO [(Text, Text)])
        case shapeResult of
            Left failure ->
                pure
                    (Left
                        (StoreCompatibilityMalformed
                            (exceptionText failure)))
            Right [("integer", "blob")] -> do
                rowResult <- trySynchronous
                    (SQLite.query_ connection
                        "SELECT cache_epoch, theory_id \
                        \FROM store_compatibility ORDER BY singleton"
                        :: IO [(Int64, ByteString)])
                pure
                    (case rowResult of
                        Left failure ->
                            Left
                                (StoreCompatibilityMalformed
                                    (exceptionText failure))
                        Right [row] ->
                            decodeCompatibility row
                        Right rows ->
                            Left
                                (StoreCompatibilityMalformed
                                    ("expected one compatibility row, found "
                                        <> Text.pack (show (length rows)))))
            Right rows ->
                pure
                    (Left
                        (StoreCompatibilityMalformed
                            ("unexpected compatibility field types: "
                                <> Text.pack (show rows))))

decodeCompatibility
    :: (Int64, ByteString)
    -> Either StoreIncompatibility StoreCompatibility
decodeCompatibility (epoch, theoryBytes)
    | epoch < 0
        || toInteger epoch > toInteger (maxBound :: Word32) =
        Left
            (StoreCompatibilityMalformed
                "cache epoch is outside the Word32 range")
    | otherwise =
        case decodeCache getTheoryIdCache theoryBytes of
            Left failure ->
                Left
                    (StoreCompatibilityMalformed
                        (Text.pack (show failure)))
            Right theory ->
                Right
                    (StoreCompatibility
                        (cacheEpochFromValue (fromIntegral epoch))
                        theory)

initializeSchema
    :: SQLite.Connection
    -> TheoryId
    -> IO ()
initializeSchema connection theory = do
    traverse_
        (SQLite.execute_ connection . schemaQuery . snd)
        schemaStatements
    SQLite.execute connection
        "INSERT INTO store_compatibility \
        \(singleton, cache_epoch, theory_id) VALUES (1, ?, ?)"
        ( fromIntegral (cacheEpochValue currentCacheEpoch) :: Int64
        , encodeCache (putTheoryIdCache theory)
        )

validateCurrentSchema
    :: SQLite.Connection
    -> IO (Either StoreFailure ())
validateCurrentSchema connection = do
    actual <- SQLite.query_ connection
        "SELECT name, sql FROM sqlite_master \
        \WHERE type = 'table' AND name NOT LIKE 'sqlite_%' \
        \ORDER BY name"
        :: IO [(Text, Text)]
    let expected =
            Map.fromList
                [ (name, normalizeSchema statement)
                | (name, statement) <- schemaStatements
                ]
        found =
            Map.fromList
                [ (name, normalizeSchema statement)
                | (name, statement) <- actual
                ]
    pure
        (if found == expected
            then Right ()
            else
                Left
                    (StoreSchemaIntegrityFailure
                        (schemaDifference expected found)))

configureConnection
    :: SQLite.Connection
    -> IO (Either StoreFailure ())
configureConnection connection = do
    journal <- SQLite.query_ connection
        "PRAGMA journal_mode = DELETE"
        :: IO [Only Text]
    SQLite.execute_ connection
        "PRAGMA synchronous = NORMAL"
    synchronous <- SQLite.query_ connection
        "PRAGMA synchronous"
        :: IO [Only Int]
    SQLite.execute_ connection
        "PRAGMA foreign_keys = ON"
    foreignKeys <- SQLite.query_ connection
        "PRAGMA foreign_keys"
        :: IO [Only Int]
    pure do
        unless
            (journal == [Only "delete"])
            (Left
                (StoreConfigurationFailure
                    ("unexpected journal mode: "
                        <> Text.pack (show journal))))
        unless
            (synchronous == [Only 1])
            (Left
                (StoreConfigurationFailure
                    ("unexpected synchronous mode: "
                        <> Text.pack (show synchronous))))
        unless
            (foreignKeys == [Only 1])
            (Left
                (StoreConfigurationFailure
                    ("foreign keys were not enabled: "
                        <> Text.pack (show foreignKeys))))


writeCanonicalRows
    :: Store
    -> [AssertedObject]
    -> [CheckedPropositionContent]
    -> Except.ExceptT StoreFailure IO ()
writeCanonicalRows store objects propositions = do
    let Store _path theory connection = store
    proposed <- Except.liftEither
        (indexProposedObjects objects)
    stored <- loadReferencedObjects
        store
        proposed
        (Set.unions
            ( (objectReferences . assertedObjectContent
                <$> objects)
            <> (termReferences
                    . frozenCoreTerm
                    . checkedPropositionTerm
                <$> propositions)
            ))
    closure <- Except.liftEither
        (first StoreObjectValidationFailure
            (validateObjectClosure
                theory
                (Map.elems proposed <> Map.elems stored)))
    checkedPropositions <-
        traverse
            (Except.liftEither
                . first StorePropositionValidationFailure
                . revalidateProposition closure)
            propositions
    traverse_ (insertObject connection) objects
    traverse_
        (insertProposition connection)
        checkedPropositions

loadCanonicalObject
    :: Store
    -> ObjectId
    -> IO (Either StoreFailure (Maybe AssertedObject))
loadCanonicalObject store identity =
    runStoreOperation "load canonical object" do
        root <- Except.runExceptT
            (loadObjectRow store identity)
        case root of
            Left failure ->
                throwIO (StoreAbort failure)
            Right Nothing ->
                pure Nothing
            Right (Just asserted) -> do
                let proposed =
                        Map.singleton identity asserted
                storedResult <- Except.runExceptT
                    (loadReferencedObjects
                        store
                        proposed
                        (objectReferences
                            (assertedObjectContent asserted)))
                stored <-
                    either (throwIO . StoreAbort) pure storedResult
                closure <-
                    either
                        (throwIO
                            . StoreAbort
                            . StoreObjectValidationFailure)
                        pure
                        (validateObjectClosure
                            theory
                            (asserted : Map.elems stored))
                pure
                    (assertedObject identity
                        <$> lookupCheckedObjectContent identity closure)
  where
    Store _path theory _connection = store

loadCanonicalProposition
    :: Store
    -> PropositionId
    -> IO
        (Either
            StoreFailure
            (Maybe CheckedPropositionContent))
loadCanonicalProposition store identity =
    runStoreOperation "load canonical proposition" do
        rowResult <- Except.runExceptT
            (loadPayload
                CanonicalPropositions
                propositionSelect
                (encodeCache (putPropositionIdCache identity))
                connection)
        row <- either (throwIO . StoreAbort) pure rowResult
        case row of
            Nothing ->
                pure Nothing
            Just payload -> do
                term <-
                    either
                        (throwIO
                            . StoreAbort
                            . StoreRowDecodeFailure
                                CanonicalPropositions
                                (encodeCache
                                    (putPropositionIdCache identity)))
                        pure
                        (decodeCache
                            (getCanonicalTermCache getObjectIdCache)
                            payload)
                storedResult <- Except.runExceptT
                    (loadReferencedObjects
                        store
                        Map.empty
                        (termReferences term))
                stored <-
                    either (throwIO . StoreAbort) pure storedResult
                closure <-
                    either
                        (throwIO
                            . StoreAbort
                            . StoreObjectValidationFailure)
                        pure
                        (validateObjectClosure theory (Map.elems stored))
                Just
                    <$> either
                        (throwIO
                            . StoreAbort
                            . StorePropositionValidationFailure)
                        pure
                        (validateAssertedPropositionContent
                            closure identity term)
  where
    Store _path theory connection = store

loadProofValidation
    :: Store
    -> ProofValidationKey
    -> IO (Either StoreFailure (Maybe ProofValidationRecord))
loadProofValidation store key =
    loadExactTyped
        store
        ProofValidations
        (cacheDigestBytes (proofValidationKeyDigest key))
        proofValidationSelect
        getProofValidationRecordCache
        (\record -> proofValidationRecordKey record == key)
        StoreValidationRecordKeyMismatch

loadDeclarationValidation
    :: Store
    -> DeclarationValidationKey
    -> IO (Either StoreFailure (Maybe DeclarationValidationRecord))
loadDeclarationValidation store key =
    loadExactTyped
        store
        DeclarationValidations
        (cacheDigestBytes (declarationValidationKeyDigest key))
        declarationValidationSelect
        getDeclarationValidationRecordCache
        (\record -> declarationValidationRecordKey record == key)
        StoreValidationRecordKeyMismatch

loadParsedArtifact
    :: Store
    -> Parsed.ParsedModuleKey
    -> IO
        (Either
            StoreFailure
            (Maybe ParsedPayload.ParsedArtifact))
loadParsedArtifact (Store _path _theory connection) key =
    runStoreOperation "load parsed artifact" do
        result <- Except.runExceptT do
            let encodedKey =
                    cacheDigestBytes (Parsed.parsedModuleKeyDigest key)
            rows <- liftIO
                (SQLite.query connection parsedArtifactSelect (Only encodedKey)
                    :: IO [(ByteString, ByteString)])
            case rows of
                [] ->
                    pure Nothing
                [(encodedIdentity, encodedPayload)] -> do
                    claimedIdentity <- Except.liftEither
                        (first
                            (StoreRowDecodeFailure
                                ParsedArtifacts encodedKey)
                            (decodeCache
                                Parsed.getParsedModuleIdCache
                                encodedIdentity))
                    payload <- Except.liftEither
                        (first
                            (StoreRowDecodeFailure
                                ParsedArtifacts encodedKey)
                            (ParsedPayload.canonicalParsedPayloadFromBytes
                                encodedPayload))
                    let artifact = ParsedPayload.parsedArtifact key payload
                    unless
                        (claimedIdentity
                            == ParsedPayload.parsedArtifactId artifact)
                        (Except.throwError StoreParsedArtifactIdMismatch)
                    pure (Just artifact)
                _ ->
                    Except.throwError
                        (StoreSchemaIntegrityFailure
                            "primary key returned several parsed artifact rows")
        either (throwIO . StoreAbort) pure result

writeParsedArtifact
    :: Store
    -> Parsed.ParsedModuleKey
    -> ParsedPayload.ParsedArtifact
    -> IO (Either StoreFailure ParsedPayload.ParsedArtifact)
writeParsedArtifact
        (Store _path _theory connection)
        key
        artifact =
    runStoreOperation "write parsed artifact" do
        SQLite.withTransaction connection do
            outcome <- Except.runExceptT do
                let payload = ParsedPayload.parsedArtifactPayload artifact
                    checked = ParsedPayload.parsedArtifact key payload
                unless
                    (ParsedPayload.parsedArtifactId artifact
                        == ParsedPayload.parsedArtifactId checked)
                    (Except.throwError StoreParsedArtifactIdMismatch)
                insertParsedArtifact connection key checked
            either (throwIO . StoreAbort) (const (pure artifact)) outcome

loadSyntaxInterface
    :: Store
    -> Syntax.SyntaxInterfaceId
    -> IO (Either StoreFailure (Maybe Syntax.ModuleSyntaxInterface))
loadSyntaxInterface store key =
    loadExactTyped
        store
        SyntaxInterfaces
        (cacheDigestBytes (Syntax.syntaxInterfaceIdDigest key))
        syntaxInterfaceSelect
        Syntax.getModuleSyntaxInterfaceCache
        (\interface -> Syntax.moduleSyntaxAssertedId interface == key)
        StoreInterfaceIdMismatch

loadSemanticInterface
    :: Store
    -> SemanticInterfaceId
    -> IO (Either StoreFailure (Maybe SemanticInterface))
loadSemanticInterface store key =
    loadExactTyped
        store
        SemanticInterfaces
        (cacheDigestBytes (semanticInterfaceIdDigest key))
        semanticInterfaceSelect
        getSemanticInterfaceCache
        (\interface -> semanticInterfaceAssertedId interface == key)
        StoreInterfaceIdMismatch

loadModuleArtifactResult
    :: Store
    -> ModuleArtifactId
    -> IO (Either StoreFailure (Maybe ModuleArtifactResult))
loadModuleArtifactResult (Store _path _theory connection) key =
    runStoreOperation "load module artifact" do
        result <- Except.runExceptT
            (loadModuleArtifactRow connection key)
        either (throwIO . StoreAbort) pure result

loadModuleArtifactRow
    :: SQLite.Connection
    -> ModuleArtifactId
    -> Except.ExceptT StoreFailure IO (Maybe ModuleArtifactResult)
loadModuleArtifactRow connection key = do
    let encodedKey = cacheDigestBytes (moduleArtifactIdDigest key)
    rows <- liftIO
        (SQLite.query connection moduleArtifactSelect (Only encodedKey)
            :: IO [(ByteString, ByteString, ByteString)])
    case rows of
        [] ->
            pure Nothing
        [(syntaxColumn, semanticColumn, payload)] -> do
            result <- Except.liftEither
                (first
                    (StoreRowDecodeFailure ModuleArtifacts encodedKey)
                    (decodeCache
                        (getModuleArtifactResultCache key)
                        payload))
            unless
                (moduleArtifactResultId result == key)
                (Except.throwError StoreModuleArtifactIdMismatch)
            let expectedSyntax =
                    cacheDigestBytes
                        (Syntax.syntaxInterfaceIdDigest
                            (moduleArtifactResultSyntax result))
                expectedSemantic =
                    cacheDigestBytes
                        (semanticInterfaceIdDigest
                            (moduleArtifactResultSemantic result))
            unless
                (syntaxColumn == expectedSyntax
                    && semanticColumn == expectedSemantic)
                (Except.throwError StoreModuleArtifactColumnsMismatch)
            pure (Just result)
        _ ->
            Except.throwError
                (StoreSchemaIntegrityFailure
                    "primary key returned several module artifact rows")

-- | Validate one exact current module hit before returning any data that can
-- be adopted as runtime authority.
loadCachedModuleInstallation
    :: StoreMemo
    -> Store
    -> ModuleArtifactKey
    -> Syntax.SyntaxInterfaceId
    -> IO
        (Either
            StoreFailure
            (Maybe CachedModuleInstallation))
loadCachedModuleInstallation memo store expectedKey expectedSyntax = do
    let expectedArtifact = moduleArtifactId expectedKey
        Store _path storeTheory _connection = store
    if moduleArtifactKeyTheory expectedKey /= storeTheory
        then
            pure
                (Left
                    (StoreModuleArtifactTheoryMismatch
                        storeTheory
                        (moduleArtifactKeyTheory expectedKey)))
        else
            validateModuleArtifactClosure memo store expectedArtifact
                >>= \case
                    Left failure ->
                        pure (Left failure)
                    Right Nothing ->
                        pure (Right Nothing)
                    Right (Just artifact)
                        | moduleArtifactResultSyntax artifact
                            /= expectedSyntax ->
                            pure
                                (Left
                                    (StoreModuleArtifactSyntaxMismatch
                                        expectedSyntax
                                        (moduleArtifactResultSyntax
                                            artifact)))
                        | otherwise -> do
                            loaded <-
                                loadValidatedModuleForImport
                                    memo store expectedArtifact
                            case loaded of
                                Left failure ->
                                    pure (Left failure)
                                Right Nothing ->
                                    pure
                                        (Left
                                            (StoreAssertedChildMissing
                                                ModuleArtifacts
                                                (cacheDigestBytes
                                                    (moduleArtifactIdDigest
                                                        expectedArtifact))))
                                Right (Just (semantic, objects, propositions)) ->
                                    finish semantic objects propositions
  where
    finish semantic objects propositions
        | semanticInterfaceOwner semantic
            /= moduleArtifactKeyOwner expectedKey =
            pure
                (Left
                    (StoreModuleArtifactOwnerMismatch
                        (moduleArtifactKeyOwner expectedKey)
                        (semanticInterfaceOwner semantic)))
        | semanticInterfaceDirectInputs semantic
            /= moduleArtifactKeyDirectSemanticInputs expectedKey =
            pure
                (Left
                    (StoreModuleArtifactDirectMismatch
                        (moduleArtifactKeyDirectSemanticInputs expectedKey)
                        (semanticInterfaceDirectInputs semantic)))
        | otherwise = do
            syntaxResult <- memoSyntax memo store expectedSyntax
            case syntaxResult of
                Left failure ->
                    pure (Left failure)
                Right Nothing ->
                    pure
                        (Left
                            (StoreAssertedChildMissing
                                SyntaxInterfaces
                                (cacheDigestBytes
                                    (Syntax.syntaxInterfaceIdDigest
                                        expectedSyntax))))
                Right (Just syntax) ->
                    pure do
                        initial <- first StoreModulePrefixFailure
                            (initialPrefixContextId
                                (moduleArtifactKeyTheory expectedKey)
                                (moduleArtifactKeyOwner expectedKey)
                                (moduleArtifactKeyDirectSemanticInputs
                                    expectedKey))
                        let final =
                                foldl'
                                    nextPrefixContextId
                                    initial
                                    (semanticInterfaceDeclarations semantic)
                        pure
                            (Just
                                (CachedModuleInstallation
                                    syntax
                                    semantic
                                    objects
                                    propositions
                                    final))

-- | Flush only completed declaration batches.  This operation does not make
-- any interface or module root visible to importers.
writePendingModulePrefix
    :: Store
    -> Declaration.PendingModulePrefix
    -> IO (Either StoreFailure ())
writePendingModulePrefix store prefix =
    runStoreOperation "write pending module prefix" do
        SQLite.withTransaction connection do
            outcome <- Except.runExceptT do
                writeCanonicalRows
                    store
                    objects
                    propositions
                traverse_
                    (insertProofValidation connection)
                    proofValidations
                traverse_
                    (insertDeclarationValidation connection)
                    declarationValidations
            either (throwIO . StoreAbort) pure outcome
  where
    Store _path _theory connection = store
    batches = Declaration.pendingModulePrefixBatches prefix
    objects = concatMap Declaration.committedBatchObjects batches
    propositions = concatMap Declaration.committedBatchPropositions batches
    proofValidations =
        concatMap Declaration.committedBatchProofValidations batches
    declarationValidations =
        [ validation
        | batch <- batches
        , Just validation <-
            [Declaration.committedBatchDeclarationValidation batch]
        ]

-- | Publish a completed prefix and its sealed interface/root as one short
-- transaction.  The supplied interface lists are the rows needed by the
-- module root; each is checked by its canonical validator before insertion.
writeSealedModule
    :: Store
    -> Declaration.PendingModulePrefix
    -> [Syntax.ModuleSyntaxInterface]
    -> [SemanticInterface]
    -> ModuleArtifactResult
    -> IO (Either StoreFailure ModuleArtifactResult)
writeSealedModule store prefix syntaxInterfaces semanticInterfaces artifact =
    runStoreOperation "write sealed module" do
        SQLite.withTransaction connection do
            outcome <- Except.runExceptT do
                writeCanonicalRows store objects propositions
                traverse_ validateSuppliedSyntaxInterface syntaxInterfaces
                traverse_ validateSuppliedSemanticInterface semanticInterfaces
                traverse_
                    (validateSyntaxInputs store syntaxInterfaces)
                    syntaxInterfaces
                traverse_
                    (validateSemanticInputs store semanticInterfaces)
                    semanticInterfaces
                requireSyntax
                    store
                    syntaxInterfaces
                    (moduleArtifactResultSyntax artifact)
                requireSemantic
                    store
                    semanticInterfaces
                    (moduleArtifactResultSemantic artifact)
                rootSemantic <-
                    maybe
                        (Except.throwError StoreModulePrefixMismatch)
                        pure
                        (find
                            ((== moduleArtifactResultSemantic artifact)
                                . semanticInterfaceAssertedId)
                            semanticInterfaces)
                validatePublishedPrefix rootSemantic
                traverse_ (insertProofValidation connection) proofValidations
                traverse_
                    (insertDeclarationValidation connection)
                    declarationValidations
                traverse_
                    (insertSyntaxInterface connection)
                    syntaxInterfaces
                traverse_
                    (insertSemanticInterface connection)
                    semanticInterfaces
                insertModuleArtifact connection artifact
            either (throwIO . StoreAbort) (const (pure artifact)) outcome
  where
    Store _path theory connection = store
    batches = Declaration.pendingModulePrefixBatches prefix
    objects = concatMap Declaration.committedBatchObjects batches
    propositions = concatMap Declaration.committedBatchPropositions batches
    proofValidations =
        concatMap Declaration.committedBatchProofValidations batches
    declarationValidations =
        [ validation
        | batch <- batches
        , Just validation <-
            [Declaration.committedBatchDeclarationValidation batch]
        ]
    validateSuppliedSyntaxInterface interface =
        Except.liftEither
            (first StoreSyntaxInterfaceValidationFailure
                (Syntax.validateModuleSyntaxInterface
                    (Syntax.moduleSyntaxBase interface)
                    (Syntax.moduleSyntaxDirectInputs interface)
                    (Syntax.moduleSyntaxLocalDelta interface)
                    (Syntax.moduleSyntaxAssertedId interface)))
    validateSuppliedSemanticInterface interface =
        Except.liftEither
            (first StoreSemanticInterfaceValidationFailure
                (validateSemanticInterface
                    (semanticInterfaceOwner interface)
                    (semanticInterfaceDirectInputs interface)
                    (semanticInterfaceDeclarations interface)
                    (semanticInterfaceAssertedId interface)))
    validatePublishedPrefix interface = do
        initial <- Except.liftEither
            (first StoreModulePrefixFailure
                (initialPrefixContextId
                    theory
                    (semanticInterfaceOwner interface)
                    (semanticInterfaceDirectInputs interface)))
        let declarations = semanticInterfaceDeclarations interface
            publishedBatches = Declaration.pendingModulePrefixBatches prefix
            expectedFinal =
                foldl' nextPrefixContextId initial declarations
        unless
            ( (Declaration.committedBatchDelta <$> publishedBatches)
                == declarations
              && Declaration.pendingModulePrefixCurrent prefix
                == expectedFinal
            )
            (Except.throwError StoreModulePrefixMismatch)

validateSyntaxInputs
    :: Store
    -> [Syntax.ModuleSyntaxInterface]
    -> Syntax.ModuleSyntaxInterface
    -> Except.ExceptT StoreFailure IO ()
validateSyntaxInputs store supplied interface = do
    traverse_
        (requireSyntax store supplied)
        (Syntax.moduleSyntaxDirectInputs interface)

requireSyntax
    :: Store
    -> [Syntax.ModuleSyntaxInterface]
    -> Syntax.SyntaxInterfaceId
    -> Except.ExceptT StoreFailure IO ()
requireSyntax store supplied identity = do
    let local =
            find
                ((== identity) . Syntax.moduleSyntaxAssertedId)
                supplied
    case local of
        Just _ ->
            pure ()
        Nothing -> do
            loaded <- Except.liftIO
                (loadSyntaxInterface store identity)
            case loaded of
                Left failure ->
                    Except.throwError failure
                Right (Just _) ->
                    pure ()
                Right Nothing ->
                    Except.throwError
                        (StoreAssertedChildMissing
                            SyntaxInterfaces
                            (cacheDigestBytes
                                (Syntax.syntaxInterfaceIdDigest identity)))

validateSemanticInputs
    :: Store
    -> [SemanticInterface]
    -> SemanticInterface
    -> Except.ExceptT StoreFailure IO ()
validateSemanticInputs store supplied interface = do
    traverse_
        (requireSemantic store supplied)
        (semanticInterfaceDirectInputs interface)
    let declarations = semanticInterfaceDeclarations interface
        objectIds =
            concatMap declarationDeltaObjects declarations
            <> [ semanticGlobalTargetObject
                    (semanticGlobalBindingTarget binding)
               | declaration <- declarations
               , binding <- semanticEnvironmentBindings
                    (declarationDeltaEnvironment declaration)
               ]
        propositionIds =
            concatMap declarationDeltaPropositions declarations
            <> [ semanticFactProposition occurrence
               | declaration <- declarations
               , occurrence <- declarationDeltaFacts declaration
               ]
    traverse_ (requireObject store) (nubOrd objectIds)
    traverse_ (requireProposition store) (nubOrd propositionIds)

requireSemantic
    :: Store
    -> [SemanticInterface]
    -> SemanticInterfaceId
    -> Except.ExceptT StoreFailure IO ()
requireSemantic store supplied identity = do
    let local =
            find
                ((== identity) . semanticInterfaceAssertedId)
                supplied
    case local of
        Just _ ->
            pure ()
        Nothing -> do
            loaded <- Except.liftIO
                (loadSemanticInterface store identity)
            case loaded of
                Left failure ->
                    Except.throwError failure
                Right (Just _) ->
                    pure ()
                Right Nothing ->
                    Except.throwError
                        (StoreAssertedChildMissing
                            SemanticInterfaces
                            (cacheDigestBytes
                                (semanticInterfaceIdDigest identity)))

requireObject
    :: Store
    -> ObjectId
    -> Except.ExceptT StoreFailure IO ()
requireObject store identity = do
    loaded <- Except.liftIO
        (loadCanonicalObject store identity)
    case loaded of
        Left failure ->
            Except.throwError failure
        Right (Just _) ->
            pure ()
        Right Nothing ->
            Except.throwError
                (StoreAssertedChildMissing
                    CanonicalObjects
                    (encodeCache (putObjectIdCache identity)))

requireProposition
    :: Store
    -> PropositionId
    -> Except.ExceptT StoreFailure IO ()
requireProposition store identity = do
    loaded <- Except.liftIO
        (loadCanonicalProposition store identity)
    case loaded of
        Left failure ->
            Except.throwError failure
        Right (Just _) ->
            pure ()
        Right Nothing ->
            Except.throwError
                (StoreAssertedChildMissing
                    CanonicalPropositions
                    (encodeCache (putPropositionIdCache identity)))

loadExactTyped
    :: Store
    -> StoreRelation
    -> ByteString
    -> Query
    -> CacheGet value
    -> (value -> Bool)
    -> (StoreRelation -> StoreFailure)
    -> IO (Either StoreFailure (Maybe value))
loadExactTyped store relation key selectRow decoder validates identityFailure =
    runStoreOperation ("load " <> relationName relation) do
        row <- Except.runExceptT
            (loadPayload relation selectRow key connection)
        payload <- either (throwIO . StoreAbort) pure row
        case payload of
            Nothing ->
                pure Nothing
            Just bytes ->
                case decodeCache decoder bytes of
                    Left failure ->
                        throwIO
                            (StoreAbort
                                (StoreRowDecodeFailure
                                    relation key failure))
                    Right value
                        | validates value ->
                            pure (Just value)
                        | otherwise ->
                            throwIO
                                (StoreAbort (identityFailure relation))
  where
    Store _path _theory connection = store

-- | Validate one complete module-artifact closure.  Every successful decode
-- (including an ordinary miss) is memoized for the lifetime of this
-- invocation, so repeated roots and import diamonds do not re-enter the
-- store boundary.
validateModuleArtifactClosure
    :: StoreMemo
    -> Store
    -> ModuleArtifactId
    -> IO (Either StoreFailure (Maybe ModuleArtifactResult))
validateModuleArtifactClosure memo store root = do
    loaded <- memoArtifact memo store root
    case loaded of
        Left failure ->
            pure (Left failure)
        Right Nothing ->
            pure (Right Nothing)
        Right (Just artifact) -> do
            validated <- IORef.readIORef (memoValidatedArtifacts memo)
            if root `Set.member` validated
                then pure (Right (Just artifact))
                else do
                    IORef.modifyIORef'
                        (memoArtifactValidationVisits memo)
                        (+ 1)
                    checked <- Except.runExceptT do
                        validateSyntax Set.empty
                            (moduleArtifactResultSyntax artifact)
                        validateSemantic Set.empty
                            (moduleArtifactResultSemantic artifact)
                        void
                            (validateSemanticInventory
                                (moduleArtifactResultSemantic artifact))
                    case checked of
                        Left failure ->
                            pure (Left failure)
                        Right () -> do
                            IORef.modifyIORef'
                                (memoValidatedArtifacts memo)
                                (Set.insert root)
                            pure (Right (Just artifact))
  where
    validateSyntax path identity = do
        validated <- Except.liftIO
            (IORef.readIORef (memoValidatedSyntax memo))
        if identity `Set.member` validated
            || identity `Set.member` path
            then pure ()
            else do
                Except.liftIO
                    (IORef.modifyIORef'
                        (memoSyntaxValidationVisits memo)
                        (+ 1))
                interface <- requireMemo
                    SyntaxInterfaces
                    (cacheDigestBytes
                        (Syntax.syntaxInterfaceIdDigest identity))
                    (memoSyntax memo store identity)
                traverse_
                    (validateSyntax (Set.insert identity path))
                    (Syntax.moduleSyntaxDirectInputs interface)
                Except.liftIO
                    (IORef.modifyIORef'
                        (memoValidatedSyntax memo)
                        (Set.insert identity))

    validateSemantic path identity = do
        validated <- Except.liftIO
            (IORef.readIORef (memoValidatedSemantic memo))
        if identity `Set.member` validated
            || identity `Set.member` path
            then pure ()
            else do
                Except.liftIO
                    (IORef.modifyIORef'
                        (memoSemanticValidationVisits memo)
                        (+ 1))
                interface <- requireMemo
                    SemanticInterfaces
                    (cacheDigestBytes
                        (semanticInterfaceIdDigest identity))
                    (memoSemantic memo store identity)
                let declarations = semanticInterfaceDeclarations interface
                    bindings =
                        [ binding
                        | declaration <- declarations
                        , binding <- semanticEnvironmentBindings
                            (declarationDeltaEnvironment declaration)
                        ]
                    objects =
                        nubOrd
                            ( concatMap declarationDeltaObjects declarations
                              <> ( semanticGlobalTargetObject
                                    . semanticGlobalBindingTarget
                                 <$> bindings
                                 )
                            )
                    propositions =
                        nubOrd
                            ( concatMap
                                declarationDeltaPropositions
                                declarations
                              <> [ semanticFactProposition occurrence
                                 | declaration <- declarations
                                 , occurrence <-
                                    declarationDeltaFacts declaration
                                 ]
                            )
                traverse_
                    (validateSemantic (Set.insert identity path))
                    (semanticInterfaceDirectInputs interface)
                operationBindings <-
                    semanticOperationBindings Set.empty identity
                validateObjectRoots objects
                closure <- Except.liftIO
                    (IORef.readIORef (memoCheckedObjects memo))
                traverse_
                    (\binding ->
                        Except.liftEither
                            (first
                                (StoreSemanticGlobalTargetFailure
                                    (semanticGlobalBindingKey binding)
                                    (semanticGlobalBindingTarget binding))
                                (validateSemanticGlobalBindingTarget
                                    operationBindings closure binding)))
                    bindings
                traverse_ validateProposition propositions
                traverse_ validateOccurrence
                    [ occurrence
                    | declaration <- declarations
                    , occurrence <- declarationDeltaFacts declaration
                    ]
                Except.liftIO
                    (IORef.modifyIORef'
                        (memoValidatedSemantic memo)
                        (Set.insert identity))

    semanticOperationBindings path identity
        | identity `Set.member` path = pure Set.empty
        | otherwise = do
            interface <- requireMemo
                SemanticInterfaces
                (cacheDigestBytes
                    (semanticInterfaceIdDigest identity))
                (memoSemantic memo store identity)
            inherited <-
                traverse
                    (semanticOperationBindings
                        (Set.insert identity path))
                    (semanticInterfaceDirectInputs interface)
            let local =
                    Set.fromList
                        [ ( semanticStructureOperationSymbol operation
                          , semanticStructureOperationObject operation
                          )
                        | declaration <-
                            semanticInterfaceDeclarations interface
                        , descriptor <- semanticEnvironmentStructures
                            (declarationDeltaEnvironment declaration)
                        , operation <-
                            semanticStructureDescriptorOperations descriptor
                        ]
            pure (Set.unions (local : inherited))

    validateObjectRoots identities = do
        closure <- Except.liftIO
            (IORef.readIORef (memoCheckedObjects memo))
        additions <- collectObjects
            (checkedObjectIds closure)
            Map.empty
            identities
        unless (Map.null additions) do
            Except.liftIO
                (IORef.modifyIORef'
                    (memoObjectValidationVisits memo)
                    (+ Map.size additions))
            extended <- Except.liftEither
                (first StoreObjectValidationFailure
                    (extendObjectClosure closure (Map.elems additions)))
            Except.liftIO
                (IORef.writeIORef (memoCheckedObjects memo) extended)

    collectObjects checked collected = \case
        [] ->
            pure collected
        identity : remaining
            | identity `Set.member` checked
                || Map.member identity collected ->
                collectObjects checked collected remaining
            | otherwise -> do
                asserted <- requireMemo
                    CanonicalObjects
                    (encodeCache (putObjectIdCache identity))
                    (memoObject memo store identity)
                let collected' = Map.insert identity asserted collected
                    dependencies =
                        Set.toAscList
                            (objectReferences
                                (assertedObjectContent asserted))
                withDependencies <-
                    collectObjects checked collected' dependencies
                collectObjects checked withDependencies remaining

    validateProposition identity = do
        validated <- Except.liftIO
            (IORef.readIORef (memoValidatedPropositions memo))
        unless (Map.member identity validated) do
            Except.liftIO
                (IORef.modifyIORef'
                    (memoPropositionValidationVisits memo)
                    (+ 1))
            term <- requireMemo
                CanonicalPropositions
                (encodeCache (putPropositionIdCache identity))
                (memoPropositionRow memo store identity)
            validateObjectRoots
                (Set.toAscList (termReferences term))
            closure <- Except.liftIO
                (IORef.readIORef (memoCheckedObjects memo))
            proposition <- Except.liftEither
                (first StorePropositionValidationFailure
                    (validateAssertedPropositionContent
                        closure identity term))
            Except.liftIO
                (IORef.modifyIORef'
                    (memoValidatedPropositions memo)
                    (Map.insert identity proposition))

    checkedProposition identity = do
        validateProposition identity
        validated <- Except.liftIO
            (IORef.readIORef (memoValidatedPropositions memo))
        case Map.lookup identity validated of
            Just proposition -> pure proposition
            Nothing -> impossible "validated proposition is absent"

    validateOccurrence occurrence = do
        proposition <- checkedProposition
            (semanticFactProposition occurrence)
        void
            (Except.liftEither
                (first StoreImportedOccurrenceValidationFailure
                    (Materialization.checkImportedOccurrence
                        theory
                        (semanticFactFingerprint occurrence)
                        occurrence
                        proposition
                        (semanticFactAuthority occurrence))))

    validateSemanticInventory identity =
        snd
            <$> foldSemanticInventory
                Set.empty
                (SemanticInventory Set.empty Map.empty Map.empty)
                identity

    foldSemanticInventory visited inventory identity
        | identity `Set.member` visited =
            pure (visited, inventory)
        | otherwise = do
            interface <- requireMemo
                SemanticInterfaces
                (cacheDigestBytes
                    (semanticInterfaceIdDigest identity))
                (memoSemantic memo store identity)
            (parentVisited, parentInventory) <-
                foldM
                    (\(seen, current) parent ->
                        foldSemanticInventory seen current parent)
                    (Set.insert identity visited, inventory)
                    (semanticInterfaceDirectInputs interface)
            let declarations = semanticInterfaceDeclarations interface
                SemanticInventory
                    parentFacts parentAliases parentGlobals =
                        parentInventory
                localFacts = Set.fromList
                    [ semanticFactFingerprint occurrence
                    | declaration <- declarations
                    , occurrence <- declarationDeltaFacts declaration
                    ]
                visibleFacts = parentFacts <> localFacts
            aliases <- foldM
                (insertAlias visibleFacts)
                parentAliases
                [ alias
                | declaration <- declarations
                , alias <- declarationDeltaAliases declaration
                ]
            globals <- foldM
                insertGlobal
                parentGlobals
                [ binding
                | declaration <- declarations
                , binding <- semanticEnvironmentBindings
                    (declarationDeltaEnvironment declaration)
                ]
            pure
                ( parentVisited
                , SemanticInventory visibleFacts aliases globals
                )

    insertGlobal globals binding =
        insertGlobalBinding
            (semanticGlobalBindingKey binding)
            (semanticGlobalBindingTarget binding)
            globals

    insertGlobalBinding key target globals =
        case Map.lookup key globals of
            Nothing -> pure (Map.insert key target globals)
            Just existing
                | existing == target -> pure globals
                | otherwise ->
                    Except.throwError
                        (StoreSemanticGlobalCollision
                            key existing target)

    insertAlias facts aliases alias = do
        let target = semanticAliasTarget alias
        unless
            (target `Set.member` facts)
            (Except.throwError
                (StoreSemanticAliasTargetMissing target))
        insertNamedAlias (semanticAliasName alias) target aliases

    insertNamedAlias name target aliases =
        case Map.lookup name aliases of
            Nothing ->
                pure (Map.insert name target aliases)
            Just existing
                | existing == target ->
                    pure aliases
                | otherwise ->
                    Except.throwError
                        (StoreSemanticAliasCollision name)

    requireMemo relation key loaded = do
        result <- Except.liftIO loaded
        case result of
            Left failure ->
                Except.throwError failure
            Right (Just value) ->
                pure value
            Right Nothing ->
                Except.throwError
                    (StoreAssertedChildMissing relation key)

    Store _path theory _connection = store

-- | Load the semantic payload needed for an importer only after the complete
-- module-artifact closure has validated.  The returned rows remain inert;
-- Declaration creates fresh builder authority from them.
loadValidatedModuleForImport
    :: StoreMemo
    -> Store
    -> ModuleArtifactId
    -> IO
        (Either
            StoreFailure
            (Maybe
                ( SemanticInterface
                , [AssertedObject]
                , [CheckedPropositionContent]
                )))
loadValidatedModuleForImport memo store root = do
    validateModuleArtifactClosure memo store root >>= \case
        Left failure ->
            pure (Left failure)
        Right Nothing ->
            pure (Right Nothing)
        Right (Just artifact) -> do
            semanticResult <-
                memoSemantic
                    memo
                    store
                    (moduleArtifactResultSemantic artifact)
            case semanticResult of
                Left failure ->
                    pure (Left failure)
                Right Nothing ->
                    pure
                        (Left
                            (StoreAssertedChildMissing
                                SemanticInterfaces
                                (encodeCache
                                    (putSemanticInterfaceIdCache
                                        (moduleArtifactResultSemantic
                                            artifact)))))
                Right (Just semantic) -> do
                    let declarations =
                            semanticInterfaceDeclarations semantic
                        propositionIds = nubOrd
                            ( concatMap
                                declarationDeltaPropositions declarations
                              <> [ semanticFactProposition occurrence
                                 | declaration <- declarations
                                 , occurrence <-
                                    declarationDeltaFacts declaration
                                 ]
                            )
                        objectIds = nubOrd
                            (concatMap declarationDeltaObjects declarations)
                    validatedPropositions <-
                        IORef.readIORef
                            (memoValidatedPropositions memo)
                    case traverse
                            (`Map.lookup` validatedPropositions)
                            propositionIds of
                        Nothing ->
                            pure
                                (Left
                                    (StoreSchemaIntegrityFailure
                                        "validated proposition evidence is absent"))
                        Just propositions -> do
                            loadedObjects <- traverse
                                (memoObject memo store)
                                objectIds
                            case sequence loadedObjects of
                                Left failure ->
                                    pure (Left failure)
                                Right objects ->
                                    case sequence objects of
                                        Nothing ->
                                            pure
                                                (Left
                                                    (StoreSchemaIntegrityFailure
                                                        "validated object evidence is absent"))
                                        Just asserted ->
                                            pure
                                                (Right
                                                    (Just
                                                        ( semantic
                                                        , asserted
                                                        , propositions
                                                        )))

memoArtifact
    :: StoreMemo
    -> Store
    -> ModuleArtifactId
    -> IO (Either StoreFailure (Maybe ModuleArtifactResult))
memoArtifact memo store identity =
    memoized (memoArtifactRows memo) identity
        (loadModuleArtifactResult store identity)

memoSyntax
    :: StoreMemo
    -> Store
    -> Syntax.SyntaxInterfaceId
    -> IO (Either StoreFailure (Maybe Syntax.ModuleSyntaxInterface))
memoSyntax memo store identity =
    memoized (memoSyntaxRows memo) identity
        (loadSyntaxInterface store identity)

memoSemantic
    :: StoreMemo
    -> Store
    -> SemanticInterfaceId
    -> IO (Either StoreFailure (Maybe SemanticInterface))
memoSemantic memo store identity =
    memoized (memoSemanticRows memo) identity
        (loadSemanticInterface store identity)

memoObject
    :: StoreMemo
    -> Store
    -> ObjectId
    -> IO (Either StoreFailure (Maybe AssertedObject))
memoObject memo store identity =
    memoized (memoObjectRows memo) identity
        (loadShallowObject store identity)

memoPropositionRow
    :: StoreMemo
    -> Store
    -> PropositionId
    -> IO (Either StoreFailure (Maybe (CanonicalTerm ObjectId)))
memoPropositionRow memo store identity =
    memoized (memoPropositionRows memo) identity
        (loadShallowProposition store identity)

loadShallowObject
    :: Store
    -> ObjectId
    -> IO (Either StoreFailure (Maybe AssertedObject))
loadShallowObject store@(Store _path theory _connection) identity =
    runStoreOperation "load shallow canonical object" do
        row <- Except.runExceptT (loadObjectRow store identity)
        asserted <- either (throwIO . StoreAbort) pure row
        traverse_
            (\object ->
                either
                    (throwIO . StoreAbort . StoreObjectValidationFailure)
                    pure
                    (validateObjectEnvelope theory object))
            asserted
        pure asserted

loadShallowProposition
    :: Store
    -> PropositionId
    -> IO
        (Either
            StoreFailure
            (Maybe (CanonicalTerm ObjectId)))
loadShallowProposition (Store _path _theory connection) identity =
    runStoreOperation "load shallow canonical proposition" do
        result <- Except.runExceptT do
            let key = encodeCache (putPropositionIdCache identity)
            payload <- loadPayload
                CanonicalPropositions propositionSelect key connection
            traverse
                (\bytes -> do
                    term <- Except.liftEither
                        (first
                            (StoreRowDecodeFailure
                                CanonicalPropositions key)
                            (decodeCache
                                (getCanonicalTermCache getObjectIdCache)
                                bytes))
                    let computed = propositionIdOf term
                    unless
                        (computed == identity)
                        (Except.throwError
                            (StorePropositionValidationFailure
                                (PropositionIdPayloadMismatch
                                    identity computed)))
                    pure term)
                payload
        either (throwIO . StoreAbort) pure result

validateObjectEnvelope
    :: TheoryId
    -> AssertedObject
    -> Either ObjectValidationError ()
validateObjectEnvelope expectedTheory asserted = do
    let identity = assertedObjectId asserted
        content = assertedObjectContent asserted
        actualTheory = objectContentTheory content
        expectedFamily = case content of
            IntrinsicObjectContent{} -> IntrinsicObject
            TransparentObjectContent{} -> TransparentObject
            OpaqueObjectContent{} -> OpaqueObject
        actualFamily = objectIdFamily identity
    unless
        (actualTheory == expectedTheory)
        (Left
            (ObjectContentTheoryMismatch
                identity expectedTheory actualTheory))
    unless
        (actualFamily == expectedFamily)
        (Left
            (ObjectContentFamilyMismatch
                identity expectedFamily actualFamily))
    computed <- case content of
        IntrinsicObjectContent theory tag coreType -> do
            let requiredType = coreIntrinsicType tag
            unless
                (coreType == requiredType)
                (Left
                    (IntrinsicObjectTypeMismatch
                        identity tag requiredType coreType))
            pure (intrinsicObjectId theory tag coreType)
        TransparentObjectContent theory coreType body ->
            pure (transparentObjectId theory coreType body)
        OpaqueObjectContent theory seed coreType ->
            pure (opaqueObjectId theory seed coreType)
    unless
        (identity == computed)
        (Left (ObjectIdPayloadMismatch identity computed))

memoized
    :: Ord key
    => IORef.IORef
        (Map key (Either StoreFailure (Maybe value)))
    -> key
    -> IO (Either StoreFailure (Maybe value))
    -> IO (Either StoreFailure (Maybe value))
memoized reference key action = do
    entries <- IORef.readIORef reference
    case Map.lookup key entries of
        Just result ->
            pure result
        Nothing -> do
            result <- action
            IORef.modifyIORef' reference
                (Map.insert key result)
            pure result

indexProposedObjects
    :: [AssertedObject]
    -> Either StoreFailure (Map ObjectId AssertedObject)
indexProposedObjects =
    foldM insertOne Map.empty
  where
    insertOne indexed asserted
        | Map.member identity indexed =
            Left
                (StoreObjectValidationFailure
                    (DuplicateAssertedObjectId identity))
        | otherwise =
            Right (Map.insert identity asserted indexed)
      where
        identity = assertedObjectId asserted

loadReferencedObjects
    :: Store
    -> Map ObjectId AssertedObject
    -> Set ObjectId
    -> Except.ExceptT
        StoreFailure
        IO
        (Map ObjectId AssertedObject)
loadReferencedObjects store proposed =
    go Set.empty Map.empty . Set.toAscList
  where
    go _seen loaded [] =
        pure loaded
    go seen loaded (identity : remaining)
        | identity `Set.member` seen
            || Map.member identity proposed =
            go seen loaded remaining
        | otherwise = do
            row <- loadObjectRow store identity
            case row of
                Nothing ->
                    go
                        (Set.insert identity seen)
                        loaded
                        remaining
                Just asserted ->
                    go
                        (Set.insert identity seen)
                        (Map.insert identity asserted loaded)
                        ( Set.toAscList
                            (objectReferences
                                (assertedObjectContent asserted))
                            <> remaining
                        )

loadObjectRow
    :: Store
    -> ObjectId
    -> Except.ExceptT
        StoreFailure
        IO
        (Maybe AssertedObject)
loadObjectRow (Store _path _theory connection) identity = do
    let key = encodeCache (putObjectIdCache identity)
    payload <- loadPayload
        CanonicalObjects
        objectSelect
        key
        connection
    traverse
        (fmap (assertedObject identity)
            . Except.liftEither
            . first
                (StoreRowDecodeFailure
                    CanonicalObjects
                    key)
            . decodeCache getObjectContentCache)
        payload

revalidateProposition
    :: CheckedObjectClosure
    -> CheckedPropositionContent
    -> Either PropositionValidationError CheckedPropositionContent
revalidateProposition closure proposition =
    validateAssertedPropositionContent
        closure
        (checkedPropositionId proposition)
        (frozenCoreTerm
            (checkedPropositionTerm proposition))

insertObject
    :: SQLite.Connection
    -> AssertedObject
    -> Except.ExceptT StoreFailure IO ()
insertObject connection asserted =
    insertExact
        CanonicalObjects
        objectSelect
        objectInsert
        (encodeCache
            (putObjectIdCache
                (assertedObjectId asserted)))
        (encodeCache
            (putObjectContentCache
                (assertedObjectContent asserted)))
        connection

insertProposition
    :: SQLite.Connection
    -> CheckedPropositionContent
    -> Except.ExceptT StoreFailure IO ()
insertProposition connection proposition =
    insertExact
        CanonicalPropositions
        propositionSelect
        propositionInsert
        (encodeCache
            (putPropositionIdCache
                (checkedPropositionId proposition)))
        (encodeCache
            (putCanonicalTermCache
                putObjectIdCache
                (frozenCoreTerm
                    (checkedPropositionTerm proposition))))
        connection

insertProofValidation
    :: SQLite.Connection
    -> ProofValidationRecord
    -> Except.ExceptT StoreFailure IO ()
insertProofValidation connection record =
    insertExact
        ProofValidations
        proofValidationSelect
        proofValidationInsert
        (cacheDigestBytes
            (proofValidationKeyDigest
                (proofValidationRecordKey record)))
        (encodeCache (putProofValidationRecordCache record))
        connection

insertDeclarationValidation
    :: SQLite.Connection
    -> DeclarationValidationRecord
    -> Except.ExceptT StoreFailure IO ()
insertDeclarationValidation connection record =
    insertExact
        DeclarationValidations
        declarationValidationSelect
        declarationValidationInsert
        (cacheDigestBytes
            (declarationValidationKeyDigest
                (declarationValidationRecordKey record)))
        (encodeCache (putDeclarationValidationRecordCache record))
        connection

insertSyntaxInterface
    :: SQLite.Connection
    -> Syntax.ModuleSyntaxInterface
    -> Except.ExceptT StoreFailure IO ()
insertSyntaxInterface connection interface =
    insertExact
        SyntaxInterfaces
        syntaxInterfaceSelect
        syntaxInterfaceInsert
        (cacheDigestBytes
            (Syntax.syntaxInterfaceIdDigest
                (Syntax.moduleSyntaxAssertedId interface)))
        (encodeCache (Syntax.putModuleSyntaxInterfaceCache interface))
        connection

insertSemanticInterface
    :: SQLite.Connection
    -> SemanticInterface
    -> Except.ExceptT StoreFailure IO ()
insertSemanticInterface connection interface =
    insertExact
        SemanticInterfaces
        semanticInterfaceSelect
        semanticInterfaceInsert
        (cacheDigestBytes
            (semanticInterfaceIdDigest
                (semanticInterfaceAssertedId interface)))
        (encodeCache (putSemanticInterfaceCache interface))
        connection

insertModuleArtifact
    :: SQLite.Connection
    -> ModuleArtifactResult
    -> Except.ExceptT StoreFailure IO ()
insertModuleArtifact connection result =
    do
        let key = cacheDigestBytes
                (moduleArtifactIdDigest
                    (moduleArtifactResultId result))
            syntax = cacheDigestBytes
                (Syntax.syntaxInterfaceIdDigest
                    (moduleArtifactResultSyntax result))
            semantic = cacheDigestBytes
                (semanticInterfaceIdDigest
                    (moduleArtifactResultSemantic result))
            payload = encodeCache (putModuleArtifactResultCache result)
        rows <- liftIO
            (SQLite.query connection moduleArtifactSelect (Only key)
                :: IO [(ByteString, ByteString, ByteString)])
        existing <- case rows of
            [] -> pure Nothing
            [row] -> pure (Just row)
            _ ->
                Except.throwError
                    (StoreSchemaIntegrityFailure
                        "primary key returned several module artifact rows")
        case existing of
            Just stored
                | stored /= (syntax, semantic, payload) ->
                    Except.throwError
                        (StoreRowPayloadMismatch ModuleArtifacts key)
                | otherwise ->
                    pure ()
            _ ->
                liftIO
                    (SQLite.execute
                        connection
                        moduleArtifactInsert
                        ( key
                        , syntax
                        , semantic
                        , payload
                        ))

insertParsedArtifact
    :: SQLite.Connection
    -> Parsed.ParsedModuleKey
    -> ParsedPayload.ParsedArtifact
    -> Except.ExceptT StoreFailure IO ()
insertParsedArtifact connection key artifact = do
    let encodedKey =
            cacheDigestBytes (Parsed.parsedModuleKeyDigest key)
        encodedIdentity =
            cacheDigestBytes
                (Parsed.parsedModuleIdDigest
                    (ParsedPayload.parsedArtifactId artifact))
        encodedPayload =
            ParsedPayload.canonicalParsedPayloadBytes
                (ParsedPayload.parsedArtifactPayload artifact)
    rows <- liftIO
        (SQLite.query connection parsedArtifactSelect (Only encodedKey)
            :: IO [(ByteString, ByteString)])
    case rows of
        [] ->
            liftIO
                (SQLite.execute
                    connection
                    parsedArtifactInsert
                    ( encodedKey
                    , encodedIdentity
                    , encodedPayload
                    ))
        [stored]
            | stored == (encodedIdentity, encodedPayload) ->
                pure ()
            | otherwise ->
                Except.throwError
                    (StoreRowPayloadMismatch ParsedArtifacts encodedKey)
        _ ->
            Except.throwError
                (StoreSchemaIntegrityFailure
                    "primary key returned several parsed artifact rows")

insertExact
    :: StoreRelation
    -> Query
    -> Query
    -> ByteString
    -> ByteString
    -> SQLite.Connection
    -> Except.ExceptT StoreFailure IO ()
insertExact relation selectRow insertRow key payload connection = do
    existing <- loadPayload relation selectRow key connection
    case existing of
        Nothing ->
            liftIO
                (SQLite.execute connection
                    insertRow
                    (key, payload))
        Just stored
            | stored == payload ->
                pure ()
            | otherwise ->
                Except.throwError
                    (StoreRowPayloadMismatch relation key)

loadPayload
    :: StoreRelation
    -> Query
    -> ByteString
    -> SQLite.Connection
    -> Except.ExceptT
        StoreFailure
        IO
        (Maybe ByteString)
loadPayload relation selectRow key connection = do
    rows <- liftIO
        (SQLite.query connection selectRow (Only key)
            :: IO [Only ByteString])
    case rows of
        [] ->
            pure Nothing
        [Only payload] ->
            pure (Just payload)
        _ ->
            Except.throwError
                (StoreSchemaIntegrityFailure
                    ("primary key returned several "
                        <> relationName relation
                        <> " rows"))

objectReferences :: ObjectContent -> Set ObjectId
objectReferences = \case
    IntrinsicObjectContent{} ->
        Set.empty
    TransparentObjectContent _theory _coreType body ->
        termReferences body
    OpaqueObjectContent{} ->
        Set.empty

termReferences :: CanonicalTerm ObjectId -> Set ObjectId
termReferences = \case
    CBound{} ->
        Set.empty
    CGlobal identity ->
        Set.singleton identity
    CIntrinsic{} ->
        Set.empty
    COpaqueInteger{} ->
        Set.empty
    CApp function argument ->
        termReferences function <> termReferences argument
    CLam _binderType body ->
        termReferences body
    CFalsum ->
        Set.empty
    CImp premise conclusion ->
        termReferences premise <> termReferences conclusion
    CEq _operandType left right ->
        termReferences left <> termReferences right
    CForall _binderType body ->
        termReferences body


schemaStatements :: [(Text, Text)]
schemaStatements =
    [ ( compatibilityTableName
      , "CREATE TABLE store_compatibility ( \
        \singleton INTEGER NOT NULL PRIMARY KEY CHECK (singleton = 1), \
        \cache_epoch INTEGER NOT NULL CHECK (cache_epoch >= 0), \
        \theory_id BLOB NOT NULL CHECK (length(theory_id) = 32) )"
      )
    , exactRow
        "canonical_objects"
        "object_id"
        33
    , exactRow
        "canonical_propositions"
        "proposition_id"
        32
    , exactRow
        "proof_validations"
        "validation_key"
        32
    , exactRow
        "declaration_validations"
        "validation_key"
        32
    , exactRow
        "syntax_interfaces"
        "syntax_interface_id"
        32
    , exactRow
        "semantic_interfaces"
        "semantic_interface_id"
        32
    , ( "module_artifacts"
      , "CREATE TABLE module_artifacts ( \
        \module_artifact_id BLOB NOT NULL PRIMARY KEY \
        \CHECK (length(module_artifact_id) = 32), \
        \syntax_interface_id BLOB NOT NULL \
        \CHECK (length(syntax_interface_id) = 32), \
        \semantic_interface_id BLOB NOT NULL \
        \CHECK (length(semantic_interface_id) = 32), \
        \payload BLOB NOT NULL, \
        \FOREIGN KEY (syntax_interface_id) \
        \REFERENCES syntax_interfaces(syntax_interface_id), \
        \FOREIGN KEY (semantic_interface_id) \
        \REFERENCES semantic_interfaces(semantic_interface_id) )"
      )
    , ( "parsed_artifacts"
      , "CREATE TABLE parsed_artifacts ( \
        \parsed_module_key BLOB NOT NULL PRIMARY KEY \
        \CHECK (length(parsed_module_key) = 32), \
        \parsed_module_id BLOB NOT NULL \
        \CHECK (length(parsed_module_id) = 32), \
        \payload BLOB NOT NULL )"
      )
    ]
  where
    exactRow :: Text -> Text -> Int -> (Text, Text)
    exactRow table key keyBytes =
        ( table
        , "CREATE TABLE " <> table <> " ( "
            <> key <> " BLOB NOT NULL PRIMARY KEY "
            <> "CHECK (length(" <> key <> ") = "
            <> Text.pack (show keyBytes) <> "), "
            <> "payload BLOB NOT NULL )"
        )

compatibilityTableName :: Text
compatibilityTableName =
    "store_compatibility"

schemaQuery :: Text -> Query
schemaQuery =
    Query

normalizeSchema :: Text -> Text
normalizeSchema =
    Text.unwords
        . Text.words
        . Text.dropWhileEnd (== ';')

schemaDifference
    :: Map Text Text
    -> Map Text Text
    -> Text
schemaDifference expected actual =
    "expected current schema "
        <> Text.pack (show (Map.keys expected))
        <> ", found "
        <> Text.pack (show (Map.keys actual))
        <> changed
  where
    altered =
        [ name
        | name <- Map.keys expected
        , Map.lookup name expected /= Map.lookup name actual
        , Map.member name actual
        ]
    changed
        | null altered =
            ""
        | otherwise =
            "; altered definitions: "
                <> Text.pack (show altered)

objectSelect, objectInsert, propositionSelect, propositionInsert :: Query
objectSelect =
    "SELECT payload FROM canonical_objects WHERE object_id = ?"
objectInsert =
    "INSERT INTO canonical_objects (object_id, payload) VALUES (?, ?)"
propositionSelect =
    "SELECT payload FROM canonical_propositions WHERE proposition_id = ?"
propositionInsert =
    "INSERT INTO canonical_propositions (proposition_id, payload) VALUES (?, ?)"

proofValidationSelect, proofValidationInsert :: Query
proofValidationSelect =
    "SELECT payload FROM proof_validations WHERE validation_key = ?"
proofValidationInsert =
    "INSERT INTO proof_validations (validation_key, payload) VALUES (?, ?)"

declarationValidationSelect, declarationValidationInsert :: Query
declarationValidationSelect =
    "SELECT payload FROM declaration_validations WHERE validation_key = ?"
declarationValidationInsert =
    "INSERT INTO declaration_validations (validation_key, payload) VALUES (?, ?)"

syntaxInterfaceSelect, syntaxInterfaceInsert :: Query
syntaxInterfaceSelect =
    "SELECT payload FROM syntax_interfaces WHERE syntax_interface_id = ?"
syntaxInterfaceInsert =
    "INSERT INTO syntax_interfaces (syntax_interface_id, payload) VALUES (?, ?)"

semanticInterfaceSelect, semanticInterfaceInsert :: Query
semanticInterfaceSelect =
    "SELECT payload FROM semantic_interfaces WHERE semantic_interface_id = ?"
semanticInterfaceInsert =
    "INSERT INTO semantic_interfaces (semantic_interface_id, payload) VALUES (?, ?)"

moduleArtifactSelect, moduleArtifactInsert :: Query
moduleArtifactSelect =
    "SELECT syntax_interface_id, semantic_interface_id, payload \
    \FROM module_artifacts WHERE module_artifact_id = ?"
moduleArtifactInsert =
    "INSERT INTO module_artifacts \
    \(module_artifact_id, syntax_interface_id, semantic_interface_id, payload) \
    \VALUES (?, ?, ?, ?)"

parsedArtifactSelect, parsedArtifactInsert :: Query
parsedArtifactSelect =
    "SELECT parsed_module_id, payload FROM parsed_artifacts \
    \WHERE parsed_module_key = ?"
parsedArtifactInsert =
    "INSERT INTO parsed_artifacts \
    \(parsed_module_key, parsed_module_id, payload) VALUES (?, ?, ?)"

relationName :: StoreRelation -> Text
relationName = \case
    CanonicalObjects -> "canonical object"
    CanonicalPropositions -> "canonical proposition"
    ProofValidations -> "proof validation"
    DeclarationValidations -> "declaration validation"
    SyntaxInterfaces -> "syntax interface"
    SemanticInterfaces -> "semantic interface"
    ModuleArtifacts -> "module artifact"
    ParsedArtifacts -> "parsed artifact"

runStoreOperation
    :: Text
    -> IO value
    -> IO (Either StoreFailure value)
runStoreOperation label action = do
    result <- trySynchronous action
    pure
        (case result of
            Right value ->
                Right value
            Left failure ->
                case Exception.fromException failure of
                    Just (StoreAbort storeFailure) ->
                        Left storeFailure
                    Nothing ->
                        Left (operationFailure label failure))

operationFailure :: Text -> Exception.SomeException -> StoreFailure
operationFailure label =
    StoreOperationFailed label . exceptionText

exceptionText :: Exception.SomeException -> Text
exceptionText =
    Text.pack . Exception.displayException

trySynchronous
    :: IO value
    -> IO (Either Exception.SomeException value)
trySynchronous action = do
    result <- Exception.try action
    case result of
        Left failure ->
            case Exception.fromException failure
                    :: Maybe Exception.AsyncException of
                Just asynchronous ->
                    Exception.throwIO asynchronous
                Nothing ->
                    pure (Left failure)
        Right value ->
            pure (Right value)

closeIgnoringFailure :: SQLite.Connection -> IO ()
closeIgnoringFailure connection =
    void
        (trySynchronous
            (SQLite.close connection))