summaryrefslogtreecommitdiff
path: root/source/Test/Unit/Store.hs
blob: e2896c3b4bad21d3b6aeb0a3e7a95db2c44bc41e (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
{-# LANGUAGE NoImplicitPrelude #-}

module Test.Unit.Store (unitTests) where

import Base
import Checking.Authority qualified as Authority
import Checking.Core qualified as Core
import Checking.Declaration qualified as Declaration
import Checking.Foundation qualified as Foundation
import Checking.Identity qualified as Identity
import Checking.Module qualified as Typed
import Checking.Semantic qualified as Semantic
import Felix.Cache.Codec qualified as Cache
import Felix.Math.Codec
import Felix.Module
import Felix.Parsed.Identity qualified as Parsed
import Felix.Parsed.Payload qualified as ParsedPayload
import Felix.Source.Content qualified as Content
import Felix.Source
import Felix.Store qualified as Store
import Provers qualified
import Syntax.Interface qualified as Syntax

import Control.Concurrent (threadDelay)
import Control.Exception qualified as Exception
import Data.ByteString qualified as ByteString
import Data.ByteString.Char8 qualified as ByteString.Char8
import Data.IORef qualified as IORef
import Database.SQLite.Simple qualified as SQLite
import Database.SQLite.Simple.Types (Only(..))
import System.Directory qualified as Directory
import System.Environment qualified as Environment
import System.FilePath.Posix qualified as Posix
import System.IO.Temp qualified as Temp
import Test.Tasty
import Test.Tasty.HUnit
import UnliftIO.Async (concurrently)


unitTests :: TestTree
unitTests =
    testGroup "SQLite store"
        [ testCase "initializes and reopens the current schema"
            initializesAndReopensCurrentSchema
        , testCase "serializes invocation-local coordinator access"
            serializesCoordinatorAccess
        , testCase "rejects incompatibility without configuring the store"
            rejectsIncompatibilityWithoutConfiguration
        , testCase "rejects malformed compatibility metadata"
            rejectsMalformedCompatibilityMetadata
        , testCase "rejects a compatible incomplete schema"
            rejectsCompatibleIncompleteSchema
        , testCase "round-trips exact parsed artifacts"
            roundTripsExactParsedArtifacts
        , testCase "rejects malformed parsed payloads"
            rejectsMalformedParsedPayloads
        , testCase "rejects disagreeing parsed artifact identities"
            rejectsDisagreeingParsedArtifactIdentities
        , testCase "rejects malformed typed validation rows"
            rejectsMalformedTypedValidationRows
        , testCase "publishes a completed prefix before readiness"
            publishesCompletedPrefixBeforeReadiness
        , testCase "installs a sealed producer for a cached importer"
            installsSealedProducerForCachedImporter
        , testCase "validates exact cached installation inputs"
            validatesExactCachedInstallationInputs
        , testCase "rejects invalid cached root authority and closure"
            rejectsInvalidCachedRootAuthorityAndClosure
        , testCase "rejects disagreeing module artifact columns"
            rejectsDisagreeingModuleArtifactColumns
        , testCase "validates shared closures once per invocation"
            validatesSharedClosuresOncePerInvocation
        , testCase "rolls back a failed readiness transaction"
            rollsBackFailedReadiness
        , testCase "rolls back an unequal duplicate batch"
            rollsBackUnequalDuplicateBatch
        , testCase "rejects malformed canonical payloads"
            rejectsMalformedCanonicalPayloads
        , testCase "plans default and explicit persistent stores"
            plansPersistentStores
        , testCase "cleans fresh stores on return and exceptions"
            cleansFreshStores
        , testCase "does not fall back after fatal startup"
            doesNotFallBackAfterFatalStartup
        ]

serializesCoordinatorAccess :: Assertion
serializesCoordinatorAccess = do
    coordinator <- Store.newStoreCoordinator
    active <- IORef.newIORef (0 :: Int)
    maximumActive <- IORef.newIORef (0 :: Int)
    let operation =
            Store.withStoreCoordinator coordinator
                (Exception.bracket_
                    (IORef.atomicModifyIORef' active
                        (\current ->
                            let next = current + 1
                            in (next, ())))
                    (IORef.atomicModifyIORef' active
                        (\current -> (current - 1, ())))
                    (do
                        current <- IORef.readIORef active
                        IORef.atomicModifyIORef' maximumActive
                            (\observed -> (max current observed, ()))
                        threadDelay 50000))
    void (concurrently operation operation)
    IORef.readIORef maximumActive >>= assertEqual "maximum owner count" 1

roundTripsExactParsedArtifacts :: Assertion
roundTripsExactParsedArtifacts =
    withStoreFixture "felix-store-parsed" \path theory _fixture -> do
        (_startup, store) <- expectOpen path theory
        (key, artifact, unequal) <- makeParsedArtifacts
        assertEqual "initial exact lookup misses" (Right Nothing)
            =<< Store.loadParsedArtifact store key
        assertEqual "published parsed artifact"
            (Right artifact)
            =<< Store.writeParsedArtifact store key artifact
        assertEqual "exact parsed round trip"
            (Right (Just artifact))
            =<< Store.loadParsedArtifact store key
        assertEqual "equal publication is idempotent"
            (Right artifact)
            =<< Store.writeParsedArtifact store key artifact
        Store.writeParsedArtifact store key unequal >>= \case
            Left Store.StoreRowPayloadMismatch{} ->
                pure ()
            other ->
                assertFailure
                    ("unexpected unequal parsed publication: " <> show other)
        Store.closeStore store

rejectsMalformedParsedPayloads :: Assertion
rejectsMalformedParsedPayloads = do
    check "malformed" (ByteString.singleton 0xff)
    check "noncanonical" . (<> ByteString.singleton 0x00)
        =<< parsedPayloadBytes
  where
    check label corrupted =
        withStoreFixture ("felix-store-parsed-" <> label)
            \path theory _fixture -> do
                (_startup, store) <- expectOpen path theory
                (key, artifact, _unequal) <- makeParsedArtifacts
                _ <- expectRightIO
                    (Store.writeParsedArtifact store key artifact)
                Store.closeStore store
                updateParsedPayload path key corrupted
                (_reopened, current) <- expectOpen path theory
                Store.loadParsedArtifact current key >>= \case
                    Left Store.StoreRowDecodeFailure{} ->
                        pure ()
                    other ->
                        assertFailure
                            ("unexpected " <> label
                                <> " parsed row result: " <> show other)
                Store.closeStore current

    parsedPayloadBytes = do
        (_key, artifact, _unequal) <- makeParsedArtifacts
        pure
            (ParsedPayload.canonicalParsedPayloadBytes
                (ParsedPayload.parsedArtifactPayload artifact))

rejectsDisagreeingParsedArtifactIdentities :: Assertion
rejectsDisagreeingParsedArtifactIdentities =
    withStoreFixture "felix-store-parsed-id" \path theory _fixture -> do
        (_startup, store) <- expectOpen path theory
        (key, artifact, _unequal) <- makeParsedArtifacts
        _ <- expectRightIO (Store.writeParsedArtifact store key artifact)
        Store.closeStore store
        connection <- SQLite.open path
        SQLite.execute connection
            "UPDATE parsed_artifacts SET parsed_module_id = ? \
            \WHERE parsed_module_key = ?"
            ( ByteString.replicate 32 0
            , Cache.cacheDigestBytes (Parsed.parsedModuleKeyDigest key)
            )
        SQLite.close connection
        (_reopened, current) <- expectOpen path theory
        Store.loadParsedArtifact current key >>= \case
            Left Store.StoreParsedArtifactIdMismatch ->
                pure ()
            other ->
                assertFailure
                    ("unexpected parsed identity result: " <> show other)
        Store.closeStore current

makeParsedArtifacts
    :: IO
        ( Parsed.ParsedModuleKey
        , ParsedPayload.ParsedArtifact
        , ParsedPayload.ParsedArtifact
        )
makeParsedArtifacts = do
    key <- expectRight
        (Parsed.parsedModuleKey
            (Content.sourceContentIdBytes "parsed-source")
            Syntax.baseSyntaxInterfaceId
            [])
    emptyDelta <- expectRight (Syntax.canonicalSyntaxDelta [])
    emptySyntax <- expectRight (Syntax.moduleSyntaxInterface [] emptyDelta)
    otherDelta <- expectRight
        (Syntax.canonicalSyntaxDelta
            [Syntax.CanonicalStructureOperation "other"])
    otherSyntax <- expectRight
        (Syntax.moduleSyntaxInterface [] otherDelta)
    let payload syntax =
            ParsedPayload.canonicalParsedPayload
                [] [] [] (Syntax.moduleSyntaxAssertedId syntax)
    pure
        ( key
        , ParsedPayload.parsedArtifact key (payload emptySyntax)
        , ParsedPayload.parsedArtifact key (payload otherSyntax)
        )

updateParsedPayload
    :: FilePath
    -> Parsed.ParsedModuleKey
    -> ByteString.ByteString
    -> IO ()
updateParsedPayload path key payload = do
    connection <- SQLite.open path
    SQLite.execute connection
        "UPDATE parsed_artifacts SET payload = ? \
        \WHERE parsed_module_key = ?"
        ( payload
        , Cache.cacheDigestBytes (Parsed.parsedModuleKeyDigest key)
        )
    SQLite.close connection

rejectsMalformedTypedValidationRows :: Assertion
rejectsMalformedTypedValidationRows =
    withStoreFixture "felix-store-malformed-typed" \path theory fixture -> do
        (_startup, store) <- expectOpen path theory
        (_owner, prefix, _syntax, _semantic, _key, _artifact, _proposition) <-
            makeCommittedModule theory fixture
        batch <- case Declaration.pendingModulePrefixBatches prefix of
            [one] -> pure one
            batches ->
                assertFailure
                    ("unexpected prefix batch count: " <> show (length batches))
                    >> fail "unreachable"
        proof <- case Declaration.committedBatchProofValidations batch of
            [one] -> pure one
            proofs ->
                assertFailure
                    ("unexpected proof validation count: " <> show (length proofs))
                    >> fail "unreachable"
        let key = Semantic.proofValidationRecordKey proof
            certificate = Semantic.proofValidationRecordCertificate proof
            theorem = Identity.theoremId
                (Authority.factAuthorityTheorem
                    (Authority.validationTarget certificate))
            wrongKey = Semantic.proofValidationKey
                theorem
                (Semantic.proofSyntaxId "other-row")
                (Declaration.committedBatchPreviousPrefix batch)
            wrongProof =
                Semantic.proofValidationRecord wrongKey certificate
        expectRightIO (Store.writePendingModulePrefix store prefix)
        Store.closeStore store
        connection <- SQLite.open path
        SQLite.execute connection
            "UPDATE proof_validations SET payload = ? \
            \WHERE validation_key = ?"
            ( Cache.encodeCache
                (Semantic.putProofValidationRecordCache wrongProof)
            , Cache.cacheDigestBytes
                (Semantic.proofValidationKeyDigest key)
            )
        SQLite.close connection
        (_reopened, current) <- expectOpen path theory
        Store.loadProofValidation current key >>= \case
            Left Store.StoreValidationRecordKeyMismatch{} -> pure ()
            Left other ->
                assertFailure
                    ("unexpected typed key mismatch: " <> show other)
            Right _ ->
                assertFailure "typed key mismatch was accepted"
        Store.closeStore current
        connection' <- SQLite.open path
        SQLite.execute connection'
            "UPDATE proof_validations SET payload = ? \
            \WHERE validation_key = ?"
            ( ByteString.singleton 0xff
            , Cache.cacheDigestBytes
                (Semantic.proofValidationKeyDigest key)
            )
        SQLite.close connection'
        (_reopenedMalformed, malformed) <- expectOpen path theory
        Store.loadProofValidation malformed key >>= \case
            Left Store.StoreRowDecodeFailure{} -> pure ()
            Left other ->
                assertFailure
                    ("unexpected malformed typed row: " <> show other)
            Right _ ->
                assertFailure "malformed typed row was accepted"
        Store.closeStore malformed

publishesCompletedPrefixBeforeReadiness :: Assertion
publishesCompletedPrefixBeforeReadiness =
    withStoreFixture "felix-store-prefix" \path theory fixture -> do
        (_startup, store) <- expectOpen path theory
        (_owner, prefix, syntax, semantic, artifactKey, artifact, proposition) <-
            makeCommittedModule theory fixture
        expectRightIO (Store.writePendingModulePrefix store prefix)
        connection <- SQLite.open path
        [Only propositionRows] <- SQLite.query connection
            "SELECT COUNT(*) FROM canonical_propositions \
            \WHERE proposition_id = ?"
            (Only
                (Cache.encodeCache
                    (Identity.putPropositionIdCache
                        (Identity.checkedPropositionId proposition))))
            :: IO [Only Int]
        [Only artifactRowsBefore] <- SQLite.query_ connection
            "SELECT COUNT(*) FROM module_artifacts"
            :: IO [Only Int]
        SQLite.close connection
        assertEqual "completed prefix proposition is visible" 1 propositionRows
        assertEqual "prefix publication does not publish readiness"
            0 artifactRowsBefore
        expectRightIO
            (Store.writeSealedModule
                store
                prefix
                [syntax]
                [semantic]
                artifact)
        memo <- Store.newStoreMemo store
        installation <- expectRightIO
            (Store.loadCachedModuleInstallation
                memo
                store
                artifactKey
                (Syntax.moduleSyntaxAssertedId syntax))
        case installation of
            Just loaded -> do
                assertEqual "validated semantic interface" semantic
                    (Store.cachedInstallationSemantic loaded)
                assertEqual "validated imported proposition count" 1
                    (length (Store.cachedInstallationPropositions loaded))
            Nothing ->
                assertFailure "validated module installation was absent"
        Store.closeStore store

installsSealedProducerForCachedImporter :: Assertion
installsSealedProducerForCachedImporter =
    withStoreFixture "felix-store-cached-import" \path theory fixture -> do
        (_startup, store) <- expectOpen path theory
        foundation <- expectRight Foundation.checkedFoundation
        (_owner, prefix, syntax, semantic, artifactKey, artifact, proposition) <-
            makeCommittedModule theory fixture
        expectRightIO
            (Store.writeSealedModule
                store
                prefix
                [syntax]
                [semantic]
                artifact)
        memo <- Store.newStoreMemo store
        installation <-
            expectRightIO
                (Store.loadCachedModuleInstallation
                    memo
                    store
                    artifactKey
                    (Syntax.moduleSyntaxAssertedId syntax))
            >>= \case
                Nothing ->
                    assertFailure "sealed producer was not loadable"
                        >> fail "unreachable"
                Just loaded ->
                    pure loaded
        cached <- expectRight
            (Typed.cachedSealedTypedModule
                foundation
                []
                installation)
        let loadedSemantic = Store.cachedInstallationSemantic installation
        fingerprint <-
            case concatMap
                    Semantic.declarationDeltaFacts
                    (Semantic.semanticInterfaceDeclarations loadedSemantic) of
                [occurrence] ->
                    pure (Semantic.semanticFactFingerprint occurrence)
                occurrences ->
                    assertFailure
                        ("unexpected cached producer facts: "
                            <> show (length occurrences))
                        >> fail "unreachable"
        namespaceDigest <- expectRight
            (hashCanonicalFields
                "store-cached-import-consumer"
                ["consumer"])
        relative <- expectRight (safeRelativePath "consumer.tex")
        let consumerOwner =
                moduleNameFromParts
                    (sourceNamespaceIdFromDigest namespaceDigest)
                    relative
            resolver = Declaration.vampireResolver \_ ->
                pure
                    (Left
                        (Provers.ProverLaunchFailed
                            "unused"
                            "cached importer does not run Vampire"))
        result <-
            (Declaration.runModuleDriver
                foundation
                consumerOwner
                [Semantic.semanticInterfaceAssertedId loadedSemantic]
                resolver
                Declaration.FreshValidation
                do
                    Declaration.importSealedModuleDriver
                        (Typed.sealedTypedModuleEvidence cached)
                    (_value, batch) <- Declaration.commitProofDeclaration
                        (Semantic.proofSyntaxId "cached-import-consumer") do
                            candidate <- Declaration.reserveCandidate
                                (Declaration.candidateSpec
                                    proposition
                                    Semantic.SearchIneligible
                                    [])
                            Declaration.authorizeOmittedCandidate candidate do
                                _ <- Declaration.useAuthorizedFact fingerprint
                                Declaration.recordOmittedUse
                    pure batch
                :: IO
                    (Either
                        Declaration.DriverOpenError
                        (Declaration.DriverResult Text
                            Declaration.CommittedDeclarationBatch)))
        case result of
            Left failure ->
                assertFailure ("cached importer could not open: " <> show failure)
            Right (Declaration.DriverSucceeded _ _ _ _closure) ->
                pure ()
            Right (Declaration.DriverFailed failure _prefix) ->
                assertFailure ("cached importer failed: " <> show failure)
            Right (Declaration.DriverSealFailed failure _prefix) ->
                assertFailure ("cached importer did not seal: " <> show failure)
        Store.closeStore store

validatesExactCachedInstallationInputs :: Assertion
validatesExactCachedInstallationInputs =
    withStoreFixture "felix-store-exact-install" \path theory fixture -> do
        (_startup, store) <- expectOpen path theory
        (owner, prefix, syntax, semantic, artifactKey, artifact, proposition) <-
            makeCommittedModule theory fixture
        _ <- expectRightIO
            (Store.writeSealedModule
                store prefix [syntax] [semantic] artifact)
        otherDelta <- expectRight
            (Syntax.canonicalSyntaxDelta
                [Syntax.CanonicalStructureOperation "other-syntax"])
        otherSyntax <- expectRight
            (Syntax.moduleSyntaxInterface [] otherDelta)
        wrongSyntaxMemo <- Store.newStoreMemo store
        Store.loadCachedModuleInstallation
            wrongSyntaxMemo
            store
            artifactKey
            (Syntax.moduleSyntaxAssertedId otherSyntax)
            >>= \case
                Left Store.StoreModuleArtifactSyntaxMismatch{} -> pure ()
                _ ->
                    assertFailure "unexpected syntax-input result"

        parent <- expectRight
            (Semantic.semanticInterface preludeModuleName [] [])
        mismatched <- expectRight
            (Semantic.semanticInterface
                owner
                [Semantic.semanticInterfaceAssertedId parent]
                (Semantic.semanticInterfaceDeclarations semantic))
        mismatchKey <- makeArtifactKey owner theory "direct-mismatch"
        let mismatchArtifact =
                Semantic.moduleArtifactResult
                    mismatchKey
                    (Syntax.moduleSyntaxAssertedId syntax)
                    (Semantic.semanticInterfaceAssertedId mismatched)
        writeRawModuleRows
            path
            [fixtureFirstObject fixture]
            [proposition]
            syntax
            [parent, mismatched]
            mismatchArtifact
        directMemo <- Store.newStoreMemo store
        Store.loadCachedModuleInstallation
            directMemo
            store
            mismatchKey
            (Syntax.moduleSyntaxAssertedId syntax)
            >>= \case
                Left Store.StoreModuleArtifactDirectMismatch{} -> pure ()
                _ ->
                    assertFailure "unexpected direct-input result"
        Store.closeStore store

rejectsInvalidCachedRootAuthorityAndClosure :: Assertion
rejectsInvalidCachedRootAuthorityAndClosure =
    withStoreFixture "felix-store-invalid-install" \path theory fixture -> do
        (_startup, store) <- expectOpen path theory
        (owner, _prefix, syntax, semantic, _artifactKey, _artifact, proposition) <-
            makeCommittedModule theory fixture
        otherTheory <- expectRight
            (Cache.decodeCache
                Identity.getTheoryIdCache
                (ByteString.replicate 32 0x5a))
        original <- case Semantic.semanticInterfaceDeclarations semantic of
            [delta] -> pure delta
            deltas ->
                assertFailure
                    ("unexpected declaration count: " <> show (length deltas))
                    >> fail "unreachable"
        occurrence <- case Semantic.declarationDeltaFacts original of
            [fact] -> pure fact
            facts ->
                assertFailure
                    ("unexpected fact count: " <> show (length facts))
                    >> fail "unreachable"
        let badAuthority =
                Authority.factAuthority
                    (Identity.theoremRef
                        otherTheory
                        (Semantic.semanticFactProposition occurrence))
                    (Authority.factAuthoritySafety
                        (Semantic.semanticFactAuthority occurrence))
            badOccurrence =
                Semantic.semanticFactOccurrence
                    (Semantic.semanticFactSlot occurrence)
                    badAuthority
                    (Semantic.semanticFactSearchEligibility occurrence)
        badDelta <- expectRight
            (Semantic.declarationInterfaceDelta
                (Semantic.declarationDeltaSlot original)
                [badOccurrence]
                (Semantic.declarationDeltaAliases original)
                (Semantic.declarationDeltaObjects original)
                (Semantic.declarationDeltaPropositions original)
                (Semantic.declarationDeltaEnvironment original))
        badSemantic <- expectRight
            (Semantic.semanticInterface owner [] [badDelta])
        badKey <- makeArtifactKey owner theory "bad-authority"
        let badArtifact =
                Semantic.moduleArtifactResult
                    badKey
                    (Syntax.moduleSyntaxAssertedId syntax)
                    (Semantic.semanticInterfaceAssertedId badSemantic)
        writeRawModuleRows
            path
            [fixtureFirstObject fixture]
            [proposition]
            syntax
            [badSemantic]
            badArtifact
        badMemo <- Store.newStoreMemo store
        Store.loadCachedModuleInstallation
            badMemo store badKey (Syntax.moduleSyntaxAssertedId syntax)
            >>= \case
                Left Store.StoreImportedOccurrenceValidationFailure{} -> pure ()
                _ ->
                    assertFailure "unexpected root-authority result"

        childKey <- makeArtifactKey owner theory "missing-late-child"
        let childArtifact =
                Semantic.moduleArtifactResult
                    childKey
                    (Syntax.moduleSyntaxAssertedId syntax)
                    (Semantic.semanticInterfaceAssertedId semantic)
        writeRawModuleRows
            path
            [fixtureFirstObject fixture]
            [proposition]
            syntax
            [semantic]
            childArtifact
        connection <- SQLite.open path
        SQLite.execute connection
            "DELETE FROM canonical_objects WHERE object_id = ?"
            (Only
                (Cache.encodeCache
                    (Identity.putObjectIdCache
                        (Identity.assertedObjectId
                            (fixtureFirstObject fixture)))))
        SQLite.close connection
        childMemo <- Store.newStoreMemo store
        Store.loadCachedModuleInstallation
            childMemo store childKey (Syntax.moduleSyntaxAssertedId syntax)
            >>= \case
                Left Store.StoreAssertedChildMissing{} -> pure ()
                _ ->
                    assertFailure "unexpected missing-child result"
        Store.closeStore store

rejectsDisagreeingModuleArtifactColumns :: Assertion
rejectsDisagreeingModuleArtifactColumns =
    withStoreFixture "felix-store-artifact-columns" \path theory fixture -> do
        (_startup, store) <- expectOpen path theory
        (_owner, prefix, syntax, semantic, key, artifact, _proposition) <-
            makeCommittedModule theory fixture
        _ <- expectRightIO
            (Store.writeSealedModule
                store prefix [syntax] [semantic] artifact)
        connection <- SQLite.open path
        SQLite.execute_ connection "PRAGMA foreign_keys = OFF"
        SQLite.execute connection
            "UPDATE module_artifacts SET syntax_interface_id = ? \
            \WHERE module_artifact_id = ?"
            ( ByteString.replicate 32 0x3c
            , Cache.cacheDigestBytes
                (Semantic.moduleArtifactIdDigest
                    (Semantic.moduleArtifactResultId artifact))
            )
        SQLite.close connection
        memo <- Store.newStoreMemo store
        Store.loadCachedModuleInstallation
            memo
            store
            key
            (Syntax.moduleSyntaxAssertedId syntax)
            >>= \case
                Left Store.StoreModuleArtifactColumnsMismatch -> pure ()
                Left other ->
                    assertFailure
                        ("unexpected artifact-column load: " <> show other)
                Right _ ->
                    assertFailure "disagreeing artifact columns were accepted"
        Store.writeSealedModule
            store prefix [syntax] [semantic] artifact >>= \case
            Left Store.StoreRowPayloadMismatch{} -> pure ()
            other ->
                assertFailure
                    ("unexpected artifact-column rewrite: " <> show other)
        Store.closeStore store

validatesSharedClosuresOncePerInvocation :: Assertion
validatesSharedClosuresOncePerInvocation =
    withStoreFixture "felix-store-linear-closure" \path theory fixture -> do
        (_startup, store) <- expectOpen path theory
        let baseObject = fixtureFirstObject fixture
            first = transparentSetObject theory baseObject
            second = transparentSetObject theory first
            third = transparentSetObject theory second
            objects = [baseObject, first, second, third]
        closure <- expectRight
            (Identity.validateObjectClosure theory objects)
        proposition <- expectRight
            (Identity.validatePropositionContent
                closure
                (Core.CEq
                    Core.TySet
                    (Core.CGlobal (Identity.assertedObjectId third))
                    (Core.CGlobal (Identity.assertedObjectId third))))
        baseOwner <- testModuleName "linear-base.tex"
        leftOwner <- testModuleName "linear-left.tex"
        rightOwner <- testModuleName "linear-right.tex"
        rootOwner <- testModuleName "linear-root.tex"
        let theorem = Identity.theoremRef
                theory
                (Identity.checkedPropositionId proposition)
            occurrence = Semantic.semanticFactOccurrence
                (Semantic.factSlot baseOwner (localFactOrdinal 0))
                (Authority.factAuthority
                    theorem Authority.cleanAuthoritySafety)
                Semantic.SearchEligible
        baseDelta <- expectRight
            (Semantic.declarationInterfaceDelta
                (Semantic.declarationSlot
                    baseOwner
                    (localDeclarationOrdinal 0))
                [occurrence]
                []
                (Identity.assertedObjectId <$> objects)
                [Identity.checkedPropositionId proposition]
                Semantic.emptySemanticEnvironmentDelta)
        baseSemantic <- expectRight
            (Semantic.semanticInterface baseOwner [] [baseDelta])
        leftSemantic <- expectRight
            (Semantic.semanticInterface
                leftOwner
                [Semantic.semanticInterfaceAssertedId baseSemantic]
                [])
        rightSemantic <- expectRight
            (Semantic.semanticInterface
                rightOwner
                [Semantic.semanticInterfaceAssertedId baseSemantic]
                [])
        rootSemantic <- expectRight
            (Semantic.semanticInterface
                rootOwner
                [ Semantic.semanticInterfaceAssertedId leftSemantic
                , Semantic.semanticInterfaceAssertedId rightSemantic
                ]
                [])

        emptyDelta <- expectRight (Syntax.canonicalSyntaxDelta [])
        leftDelta <- expectRight
            (Syntax.canonicalSyntaxDelta
                [Syntax.CanonicalStructureOperation "linear-left"])
        rightDelta <- expectRight
            (Syntax.canonicalSyntaxDelta
                [Syntax.CanonicalStructureOperation "linear-right"])
        baseSyntax <- expectRight
            (Syntax.moduleSyntaxInterface [] emptyDelta)
        leftSyntax <- expectRight
            (Syntax.moduleSyntaxInterface
                [Syntax.moduleSyntaxAssertedId baseSyntax]
                leftDelta)
        rightSyntax <- expectRight
            (Syntax.moduleSyntaxInterface
                [Syntax.moduleSyntaxAssertedId baseSyntax]
                rightDelta)
        rootSyntax <- expectRight
            (Syntax.moduleSyntaxInterface
                [ Syntax.moduleSyntaxAssertedId leftSyntax
                , Syntax.moduleSyntaxAssertedId rightSyntax
                ]
                emptyDelta)

        rootKey <- makeArtifactKeyWithDirect
            rootOwner
            theory
            [ Semantic.semanticInterfaceAssertedId leftSemantic
            , Semantic.semanticInterfaceAssertedId rightSemantic
            ]
            "linear-root"
        leftKey <- makeArtifactKeyWithDirect
            leftOwner
            theory
            [Semantic.semanticInterfaceAssertedId baseSemantic]
            "linear-left"
        let rootArtifact = Semantic.moduleArtifactResult
                rootKey
                (Syntax.moduleSyntaxAssertedId rootSyntax)
                (Semantic.semanticInterfaceAssertedId rootSemantic)
            leftArtifact = Semantic.moduleArtifactResult
                leftKey
                (Syntax.moduleSyntaxAssertedId leftSyntax)
                (Semantic.semanticInterfaceAssertedId leftSemantic)
        connection <- SQLite.open path
        SQLite.withTransaction connection do
            traverse_ (insertRawObject connection) objects
            insertRawProposition connection proposition
            traverse_
                (insertRawSyntaxInterface connection)
                [baseSyntax, leftSyntax, rightSyntax, rootSyntax]
            traverse_
                (insertRawSemanticInterface connection)
                [baseSemantic, leftSemantic, rightSemantic, rootSemantic]
            insertRawModuleArtifact connection rootArtifact
            insertRawModuleArtifact connection leftArtifact
        SQLite.close connection

        memo <- Store.newStoreMemo store
        expectInstallation memo store rootKey rootSyntax
        expectInstallation memo store leftKey leftSyntax
        expectInstallation memo store rootKey rootSyntax
        visits <- Store.storeMemoVisits memo
        assertEqual "unique artifact rows" 2
            (Store.storeArtifactRowsDecoded visits)
        assertEqual "unique artifact validations" 2
            (Store.storeArtifactsValidated visits)
        assertEqual "syntax diamond rows" 4
            (Store.storeSyntaxRowsDecoded visits)
        assertEqual "syntax diamond validations" 4
            (Store.storeSyntaxRowsValidated visits)
        assertEqual "semantic diamond rows" 4
            (Store.storeSemanticRowsDecoded visits)
        assertEqual "semantic diamond validations" 4
            (Store.storeSemanticRowsValidated visits)
        assertEqual "transparent-chain rows" 4
            (Store.storeObjectRowsDecoded visits)
        assertEqual "transparent-chain validations" 4
            (Store.storeObjectRowsValidated visits)
        assertEqual "proposition rows" 1
            (Store.storePropositionRowsDecoded visits)
        assertEqual "proposition validations" 1
            (Store.storePropositionRowsValidated visits)
        Store.closeStore store
  where
    expectInstallation memo store key syntax =
        Store.loadCachedModuleInstallation
            memo store key (Syntax.moduleSyntaxAssertedId syntax)
            >>= \case
                Right (Just _installation) -> pure ()
                _ -> assertFailure "cached closure installation failed"

transparentSetObject
    :: Identity.TheoryId
    -> Identity.AssertedObject
    -> Identity.AssertedObject
transparentSetObject theory dependency =
    Identity.assertedObject identity content
  where
    content = Identity.TransparentObjectContent
        theory
        Core.TySet
        (Core.CGlobal (Identity.assertedObjectId dependency))
    identity = Identity.transparentObjectId
        theory
        Core.TySet
        (Core.CGlobal (Identity.assertedObjectId dependency))

testModuleName :: FilePath -> IO ModuleName
testModuleName path = do
    digest <- expectRight
        (hashCanonicalFields
            "store-linear-module"
            [ByteString.Char8.pack path])
    relative <- expectRight (safeRelativePath path)
    pure
        (moduleNameFromParts
            (sourceNamespaceIdFromDigest digest)
            relative)

makeArtifactKey
    :: ModuleName
    -> Identity.TheoryId
    -> ByteString.ByteString
    -> IO Semantic.ModuleArtifactKey
makeArtifactKey owner theory label = do
    makeArtifactKeyWithDirect owner theory [] label

makeArtifactKeyWithDirect
    :: ModuleName
    -> Identity.TheoryId
    -> [Semantic.SemanticInterfaceId]
    -> ByteString.ByteString
    -> IO Semantic.ModuleArtifactKey
makeArtifactKeyWithDirect owner theory direct label = do
    parsedKey <- expectRight
        (Parsed.parsedModuleKey
            (Content.sourceContentIdBytes label)
            Syntax.baseSyntaxInterfaceId
            [])
    expectRight
        (Semantic.moduleArtifactKey
            owner
            (Parsed.parsedModuleId parsedKey label)
            direct
            theory)

writeRawModuleRows
    :: FilePath
    -> [Identity.AssertedObject]
    -> [Identity.CheckedPropositionContent]
    -> Syntax.ModuleSyntaxInterface
    -> [Semantic.SemanticInterface]
    -> Semantic.ModuleArtifactResult
    -> IO ()
writeRawModuleRows path objects propositions syntax semantics artifact = do
    connection <- SQLite.open path
    SQLite.withTransaction connection do
        traverse_ (insertRawObject connection) objects
        traverse_ (insertRawProposition connection) propositions
        insertRawSyntaxInterface connection syntax
        traverse_ (insertRawSemanticInterface connection) semantics
        insertRawModuleArtifact connection artifact
    SQLite.close connection

insertRawObject :: SQLite.Connection -> Identity.AssertedObject -> IO ()
insertRawObject connection object =
    SQLite.execute connection
        "INSERT OR IGNORE INTO canonical_objects (object_id, payload) \
        \VALUES (?, ?)"
        ( Cache.encodeCache
            (Identity.putObjectIdCache
                (Identity.assertedObjectId object))
        , Cache.encodeCache
            (Identity.putObjectContentCache
                (Identity.assertedObjectContent object))
        )

insertRawProposition
    :: SQLite.Connection
    -> Identity.CheckedPropositionContent
    -> IO ()
insertRawProposition connection proposition =
    SQLite.execute connection
        "INSERT OR IGNORE INTO canonical_propositions \
        \(proposition_id, payload) VALUES (?, ?)"
        ( Cache.encodeCache
            (Identity.putPropositionIdCache
                (Identity.checkedPropositionId proposition))
        , Cache.encodeCache
            (Cache.putCanonicalTermCache
                Identity.putObjectIdCache
                (Core.frozenCoreTerm
                    (Identity.checkedPropositionTerm proposition)))
        )

insertRawSyntaxInterface
    :: SQLite.Connection
    -> Syntax.ModuleSyntaxInterface
    -> IO ()
insertRawSyntaxInterface connection interface =
    SQLite.execute connection
        "INSERT OR IGNORE INTO syntax_interfaces \
        \(syntax_interface_id, payload) VALUES (?, ?)"
        ( Cache.cacheDigestBytes
            (Syntax.syntaxInterfaceIdDigest
                (Syntax.moduleSyntaxAssertedId interface))
        , Cache.encodeCache
            (Syntax.putModuleSyntaxInterfaceCache interface)
        )

insertRawSemanticInterface
    :: SQLite.Connection
    -> Semantic.SemanticInterface
    -> IO ()
insertRawSemanticInterface connection interface =
    SQLite.execute connection
        "INSERT OR IGNORE INTO semantic_interfaces \
        \(semantic_interface_id, payload) VALUES (?, ?)"
        ( Cache.cacheDigestBytes
            (Semantic.semanticInterfaceIdDigest
                (Semantic.semanticInterfaceAssertedId interface))
        , Cache.encodeCache
            (Semantic.putSemanticInterfaceCache interface)
        )

insertRawModuleArtifact
    :: SQLite.Connection
    -> Semantic.ModuleArtifactResult
    -> IO ()
insertRawModuleArtifact connection artifact =
    SQLite.execute connection
        "INSERT OR IGNORE INTO module_artifacts \
        \(module_artifact_id, syntax_interface_id, \
        \semantic_interface_id, payload) VALUES (?, ?, ?, ?)"
        ( Cache.cacheDigestBytes
            (Semantic.moduleArtifactIdDigest
                (Semantic.moduleArtifactResultId artifact))
        , Cache.cacheDigestBytes
            (Syntax.syntaxInterfaceIdDigest
                (Semantic.moduleArtifactResultSyntax artifact))
        , Cache.cacheDigestBytes
            (Semantic.semanticInterfaceIdDigest
                (Semantic.moduleArtifactResultSemantic artifact))
        , Cache.encodeCache
            (Semantic.putModuleArtifactResultCache artifact)
        )

storedPropositionCount
    :: FilePath
    -> Identity.PropositionId
    -> IO Int
storedPropositionCount path identity = do
    connection <- SQLite.open path
    [Only rowCount] <- SQLite.query connection
        "SELECT COUNT(*) FROM canonical_propositions \
        \WHERE proposition_id = ?"
        (Only
            (Cache.encodeCache
                (Identity.putPropositionIdCache identity)))
    SQLite.close connection
    pure rowCount

storedObjectCount
    :: FilePath
    -> Identity.ObjectId
    -> IO Int
storedObjectCount path identity = do
    connection <- SQLite.open path
    [Only rowCount] <- SQLite.query connection
        "SELECT COUNT(*) FROM canonical_objects WHERE object_id = ?"
        (Only
            (Cache.encodeCache
                (Identity.putObjectIdCache identity)))
    SQLite.close connection
    pure rowCount

storedArtifactCount
    :: FilePath
    -> Semantic.ModuleArtifactId
    -> IO Int
storedArtifactCount path identity = do
    connection <- SQLite.open path
    [Only rowCount] <- SQLite.query connection
        "SELECT COUNT(*) FROM module_artifacts \
        \WHERE module_artifact_id = ?"
        (Only
            (Cache.cacheDigestBytes
                (Semantic.moduleArtifactIdDigest identity)))
    SQLite.close connection
    pure rowCount

rollsBackFailedReadiness :: Assertion
rollsBackFailedReadiness =
    withStoreFixture "felix-store-readiness-rollback" \path theory fixture -> do
        (_startup, store) <- expectOpen path theory
        (owner, prefix, _syntax, semantic, _artifactKey, artifact, proposition) <-
            makeCommittedModule theory fixture
        missingDelta <- expectRight
            (Syntax.canonicalSyntaxDelta
                [Syntax.CanonicalStructureOperation "missing-child"])
        missingInterface <- expectRight
            (Syntax.moduleSyntaxInterface [] missingDelta)
        syntaxDelta <- expectRight
            (Syntax.canonicalSyntaxDelta [])
        brokenSyntax <- expectRight
            (Syntax.moduleSyntaxInterface
                [Syntax.moduleSyntaxAssertedId missingInterface]
                syntaxDelta)
        brokenParsedKey <- expectRight
            (Parsed.parsedModuleKey
                (Content.sourceContentIdBytes "rollback-source")
                Syntax.baseSyntaxInterfaceId
                [])
        brokenArtifactKey <- expectRight
            (Semantic.moduleArtifactKey
                owner
                (Parsed.parsedModuleId
                    brokenParsedKey
                    "rollback-parsed")
                []
                theory)
        let brokenArtifact =
                Semantic.moduleArtifactResult
                    brokenArtifactKey
                    (Syntax.moduleSyntaxAssertedId brokenSyntax)
                    (Semantic.semanticInterfaceAssertedId semantic)
        result <- Store.writeSealedModule
            store
            prefix
            [brokenSyntax]
            [semantic]
            brokenArtifact
        case result of
            Left Store.StoreAssertedChildMissing{} ->
                pure ()
            Left other ->
                assertFailure
                    ("unexpected readiness failure: " <> show other)
            Right _ ->
                assertFailure "broken readiness transaction was accepted"
        assertEqual "failed readiness did not publish the prefix" 0
            =<< storedPropositionCount
                path
                (Identity.checkedPropositionId proposition)
        assertEqual "failed readiness leaves no module root" 0
            =<< storedArtifactCount
                path
                (Semantic.moduleArtifactResultId artifact)
        -- A later failed seal must not erase a prefix published by an
        -- earlier successful source prefix flush.
        expectRightIO (Store.writePendingModulePrefix store prefix)
        assertEqual "successful prefix is visible before retry" 1
            =<< storedPropositionCount
                path
                (Identity.checkedPropositionId proposition)
        retry <- Store.writeSealedModule
            store
            prefix
            [brokenSyntax]
            [semantic]
            brokenArtifact
        case retry of
            Left Store.StoreAssertedChildMissing{} ->
                pure ()
            Left other ->
                assertFailure
                    ("unexpected retry readiness failure: " <> show other)
            Right _ ->
                assertFailure "broken readiness retry was accepted"
        assertEqual "failed retry retains successful prefix" 1
            =<< storedPropositionCount
                path
                (Identity.checkedPropositionId proposition)
        assertEqual "failed retry still leaves no module root" 0
            =<< storedArtifactCount
                path
                (Semantic.moduleArtifactResultId artifact)
        Store.closeStore store
makeCommittedModule
    :: Identity.TheoryId
    -> StoreFixture
    -> IO
        ( ModuleName
        , Declaration.PendingModulePrefix
        , Syntax.ModuleSyntaxInterface
        , Semantic.SemanticInterface
        , Semantic.ModuleArtifactKey
        , Semantic.ModuleArtifactResult
        , Identity.CheckedPropositionContent
        )
makeCommittedModule theory fixture = do
    foundation <- expectRight Foundation.checkedFoundation
    namespaceDigest <- expectRight
        (hashCanonicalFields "store-module-test" ["prefix"])
    relative <- expectRight (safeRelativePath "module.tex")
    let owner =
            moduleNameFromParts
                (sourceNamespaceIdFromDigest namespaceDigest)
                relative
        proposition = fixtureProposition fixture
        resolver = Declaration.vampireResolver \_ ->
            pure
                (Left
                    (Provers.ProverLaunchFailed
                        "unused"
                        "store fixture does not run Vampire"))
    driver <- Declaration.runModuleDriver
        foundation
        owner
        []
        resolver
        Declaration.FreshValidation
        do
            (_value, _batch) <- Declaration.commitProofDeclaration
                (Semantic.proofSyntaxId "store-prefix") do
                    Declaration.addDeclarationObject
                        (fixtureFirstObject fixture)
                    candidate <- Declaration.reserveCandidate
                        (Declaration.candidateSpec
                            proposition
                            Semantic.SearchIneligible
                            [])
                    Declaration.authorizeOmittedCandidate candidate
                        Declaration.recordOmittedUse
            pure ()
    (_value, prefix, semantic) <-
        case driver of
            Right (Declaration.DriverSucceeded value interface pending _closure) ->
                pure (value, pending, interface)
            Right (Declaration.DriverFailed failure _prefix) ->
                assertFailure
                    ("unexpected declaration failure: "
                        <> show
                            (failure
                                :: Declaration.DriverFailure
                                    Declaration.DeclarationError))
                    >> fail "unreachable"
            Right (Declaration.DriverSealFailed failure _prefix) ->
                assertFailure ("unexpected seal failure: " <> show failure)
                    >> fail "unreachable"
            Left failure ->
                assertFailure ("unexpected driver-open failure: " <> show failure)
                    >> fail "unreachable"
    delta <- expectRight (Syntax.canonicalSyntaxDelta [])
    syntax <- expectRight (Syntax.moduleSyntaxInterface [] delta)
    parsedKey <- expectRight
        (Parsed.parsedModuleKey
            (Content.sourceContentIdBytes "store-module-source")
            Syntax.baseSyntaxInterfaceId
            [])
    artifactKey <- expectRight
        (Semantic.moduleArtifactKey
            owner
            (Parsed.parsedModuleId parsedKey "store-module-parsed")
            []
            theory)
    let artifact =
            Semantic.moduleArtifactResult
                artifactKey
                (Syntax.moduleSyntaxAssertedId syntax)
                (Semantic.semanticInterfaceAssertedId semantic)
    pure
        ( owner
        , prefix
        , syntax
        , semantic
        , artifactKey
        , artifact
        , proposition
        )

makePendingPrefix
    :: StoreFixture
    -> [Identity.AssertedObject]
    -> IO Declaration.PendingModulePrefix
makePendingPrefix fixture objects = do
    foundation <- expectRight Foundation.checkedFoundation
    owner <- testModuleName "rollback-prefix.tex"
    let proposition = fixtureProposition fixture
        resolver = Declaration.vampireResolver \_ ->
            pure
                (Left
                    (Provers.ProverLaunchFailed
                        "unused"
                        "store fixture does not run Vampire"))
    driver <- Declaration.runModuleDriver
        foundation
        owner
        []
        resolver
        Declaration.FreshValidation
        do
            (_value, _batch) <- Declaration.commitProofDeclaration
                (Semantic.proofSyntaxId "store-rollback") do
                    traverse_ Declaration.addDeclarationObject objects
                    candidate <- Declaration.reserveCandidate
                        (Declaration.candidateSpec
                            proposition
                            Semantic.SearchIneligible
                            [])
                    Declaration.authorizeOmittedCandidate candidate
                        Declaration.recordOmittedUse
            pure ()
    case driver of
        Right (Declaration.DriverSucceeded _value _interface prefix _closure) ->
            pure prefix
        Right (Declaration.DriverFailed failure _prefix) ->
            assertFailure
                ("unexpected declaration failure: "
                    <> show
                        (failure
                            :: Declaration.DriverFailure
                                Declaration.DeclarationError))
                >> fail "unreachable"
        Right (Declaration.DriverSealFailed failure _prefix) ->
            assertFailure ("unexpected seal failure: " <> show failure)
                >> fail "unreachable"
        Left failure ->
            assertFailure ("unexpected driver-open failure: " <> show failure)
                >> fail "unreachable"

initializesAndReopensCurrentSchema :: Assertion
initializesAndReopensCurrentSchema =
    withStoreFixture "felix-store-startup" \path theory _fixture -> do
        (startup, store) <- expectOpen path theory
        assertEqual "new store status"
            Store.InitializedNewStore startup
        Store.closeStore store

        (reopened, current) <- expectOpen path theory
        assertEqual "current store status"
            Store.OpenedCurrentStore reopened
        Store.closeStore current

        connection <- SQLite.open path
        names <- SQLite.query_ connection
            "SELECT name FROM sqlite_master \
            \WHERE type = 'table' AND name NOT LIKE 'sqlite_%' \
            \ORDER BY name"
            :: IO [Only Text]
        journal <- SQLite.query_ connection
            "PRAGMA journal_mode"
            :: IO [Only Text]
        SQLite.close connection
        assertEqual "complete schema table count" 9 (length names)
        assertEqual "rollback journal persists"
            [Only "delete"] journal

rejectsIncompatibilityWithoutConfiguration :: Assertion
rejectsIncompatibilityWithoutConfiguration =
    withStoreFixture "felix-store-incompatible" \path theory _fixture -> do
        connection <- SQLite.open path
        _ <- SQLite.query_ connection
            "PRAGMA journal_mode = WAL"
            :: IO [Only Text]
        SQLite.execute_ connection
            "CREATE TABLE store_compatibility ( \
            \singleton INTEGER, cache_epoch INTEGER, theory_id BLOB )"
        SQLite.execute connection
            "INSERT INTO store_compatibility VALUES (1, ?, ?)"
            ( 999 :: Int
            , Cache.encodeCache (Identity.putTheoryIdCache theory)
            )
        SQLite.execute_ connection
            "CREATE TABLE untouched (value INTEGER)"
        SQLite.close connection

        result <- Store.openStore path theory
        case result of
            Left
                (Store.IncompatibleStore
                    Store.StoreCompatibilityMismatch{}) ->
                pure ()
            Left other ->
                assertFailure
                    ("unexpected incompatibility result: " <> show other)
            Right (_startup, store) -> do
                Store.closeStore store
                assertFailure "incompatible store was accepted"

        inspected <- SQLite.open path
        names <- SQLite.query_ inspected
            "SELECT name FROM sqlite_master \
            \WHERE type = 'table' AND name NOT LIKE 'sqlite_%' \
            \ORDER BY name"
            :: IO [Only Text]
        journal <- SQLite.query_ inspected
            "PRAGMA journal_mode"
            :: IO [Only Text]
        SQLite.close inspected
        assertEqual "startup creates no schema"
            [Only "store_compatibility", Only "untouched"] names
        assertEqual "startup applies no journal configuration"
            [Only "wal"] journal

rejectsMalformedCompatibilityMetadata :: Assertion
rejectsMalformedCompatibilityMetadata =
    withStoreFixture "felix-store-malformed" \path theory _fixture -> do
        connection <- SQLite.open path
        SQLite.execute_ connection
            "CREATE TABLE store_compatibility ( \
            \singleton INTEGER, cache_epoch, theory_id )"
        SQLite.execute connection
            "INSERT INTO store_compatibility VALUES (1, ?, ?)"
            ( "not-an-epoch" :: Text
            , Cache.encodeCache (Identity.putTheoryIdCache theory)
            )
        SQLite.close connection

        result <- Store.openStore path theory
        case result of
            Left
                (Store.IncompatibleStore
                    Store.StoreCompatibilityMalformed{}) ->
                pure ()
            Left other ->
                assertFailure
                    ("unexpected malformed result: " <> show other)
            Right (_startup, store) -> do
                Store.closeStore store
                assertFailure "malformed metadata was accepted"

rejectsCompatibleIncompleteSchema :: Assertion
rejectsCompatibleIncompleteSchema =
    withStoreFixture "felix-store-incomplete" \path theory _fixture -> do
        (_startup, store) <- expectOpen path theory
        Store.closeStore store
        connection <- SQLite.open path
        SQLite.execute_ connection
            "DROP TABLE canonical_propositions"
        SQLite.close connection

        result <- Store.openStore path theory
        case result of
            Left
                (Store.FatalStoreStartup
                    Store.StoreSchemaIntegrityFailure{}) ->
                pure ()
            Left other ->
                assertFailure
                    ("unexpected incomplete-schema result: " <> show other)
            Right (_startup, current) -> do
                Store.closeStore current
                assertFailure "incomplete current schema was accepted"

rollsBackUnequalDuplicateBatch :: Assertion
rollsBackUnequalDuplicateBatch =
    withStoreFixture "felix-store-rollback" \path theory fixture -> do
        (_startup, store) <- expectOpen path theory
        let first = fixtureFirstObject fixture
            second = fixtureSecondObject fixture
        prefix <- makePendingPrefix fixture [first, second]
        Store.closeStore store

        connection <- SQLite.open path
        SQLite.execute connection
            "INSERT INTO canonical_objects (object_id, payload) VALUES (?, ?)"
            ( Cache.encodeCache
                (Identity.putObjectIdCache
                    (Identity.assertedObjectId second))
            , Cache.encodeCache
                (Identity.putObjectContentCache
                    (Identity.assertedObjectContent
                        first))
            )
        SQLite.close connection

        (_reopened, current) <- expectOpen path theory
        result <- Store.writePendingModulePrefix current prefix
        case result of
            Left Store.StoreRowPayloadMismatch{} ->
                pure ()
            Left other ->
                assertFailure
                    ("unexpected duplicate result: " <> show other)
            Right () ->
                assertFailure "unequal duplicate was accepted"
        assertEqual "earlier insertion was rolled back" 0
            =<< storedObjectCount path (Identity.assertedObjectId first)
        Store.closeStore current

rejectsMalformedCanonicalPayloads :: Assertion
rejectsMalformedCanonicalPayloads =
    withStoreFixture "felix-store-decode" \path theory fixture -> do
        (_startup, store) <- expectOpen path theory
        let object = fixtureFirstObject fixture
        (_owner, prefix, syntax, semantic, key, artifact, _proposition) <-
            makeCommittedModule theory fixture
        expectRightIO
            (Store.writeSealedModule
                store prefix [syntax] [semantic] artifact)
        Store.closeStore store

        connection <- SQLite.open path
        SQLite.execute connection
            "UPDATE canonical_objects SET payload = ? \
            \WHERE object_id = ?"
            ( ByteString.singleton 0xff
            , Cache.encodeCache
                (Identity.putObjectIdCache
                    (Identity.assertedObjectId object))
            )
        SQLite.close connection

        (_reopened, current) <- expectOpen path theory
        memo <- Store.newStoreMemo current
        result <- Store.loadCachedModuleInstallation
            memo current key (Syntax.moduleSyntaxAssertedId syntax)
        case result of
            Left Store.StoreRowDecodeFailure{} ->
                pure ()
            Left other ->
                assertFailure
                    ("unexpected malformed-row result: " <> show other)
            Right _ ->
                assertFailure "malformed canonical payload was accepted"
        Store.closeStore current

plansPersistentStores :: Assertion
plansPersistentStores =
    Temp.withSystemTempDirectory "felix-store-planning" \root -> do
        (theory, _fixture) <- makeStoreFixture
        let cacheRoot = root Posix.</> "cache"
            expectedDefault =
                cacheRoot Posix.</> "felix" Posix.</> "store.sqlite"
            explicitParent = root Posix.</> "explicit"
            explicitPath = explicitParent Posix.</> "selected.sqlite"
        Directory.createDirectory cacheRoot
        Directory.createDirectory explicitParent
        withEnvironment "XDG_CACHE_HOME" cacheRoot do
            defaultPlan <- expectRightIO
                (Store.planStore Store.DefaultStore)
            defaultResult <- Store.withStoreLease defaultPlan \lease -> do
                assertEqual "default store path"
                    expectedDefault
                    (Store.storePathFilePath
                        (Store.storeLeasePath lease))
                assertBool "planning does not create the default parent"
                    . not
                    =<< Directory.doesPathExist
                        (cacheRoot Posix.</> "felix")
                Store.withOpenStore lease theory \_startup _store ->
                    Directory.doesFileExist expectedDefault
            assertEqual "default store opens at the XDG path"
                (Right True) defaultResult

        explicitPlan <- expectRightIO
            (Store.planStore
                (Store.ExplicitStore explicitPath))
        explicitResult <- Store.withStoreLease explicitPlan \lease -> do
            assertEqual "explicit store path"
                explicitPath
                (Store.storePathFilePath
                    (Store.storeLeasePath lease))
            Store.withOpenStore lease theory \_startup _store ->
                Directory.doesFileExist explicitPath
        assertEqual "explicit store opens without creating its parent"
            (Right True) explicitResult

        missing <- Store.planStore
            (Store.ExplicitStore
                (root Posix.</> "missing" Posix.</> "store.sqlite"))
        case missing of
            Left Store.ExplicitStoreParentMissing{} ->
                pure ()
            Left other ->
                assertFailure
                    ("unexpected missing-parent result: " <> show other)
            Right _ ->
                assertFailure "missing explicit parent was accepted"

cleansFreshStores :: Assertion
cleansFreshStores = do
    (theory, _fixture) <- makeStoreFixture
    plan <- expectRightIO
        (Store.planStore Store.FreshTemporaryStore)

    successPath <- IORef.newIORef Nothing
    success <- Store.withStoreLease plan \lease -> do
        let path = Store.storePathFilePath
                (Store.storeLeasePath lease)
        IORef.writeIORef successPath (Just path)
        Store.withOpenStore lease theory \_startup _store ->
            Directory.doesFileExist path
    assertEqual "fresh store opened" (Right True) success
    assertFreshRemoved successPath

    failurePath <- IORef.newIORef Nothing
    failed <- Exception.try
        (Store.withStoreLease plan \lease -> do
            let path = Store.storePathFilePath
                    (Store.storeLeasePath lease)
            IORef.writeIORef failurePath (Just path)
            void
                (Store.withOpenStore lease theory \_startup _store ->
                    ioError (userError "fresh action failed")))
        :: IO (Either IOError ())
    case failed of
        Left _ ->
            pure ()
        Right () ->
            assertFailure "fresh-store action exception did not escape"
    assertFreshRemoved failurePath

doesNotFallBackAfterFatalStartup :: Assertion
doesNotFallBackAfterFatalStartup =
    Temp.withSystemTempDirectory "felix-store-no-fallback" \root -> do
        (theory, _fixture) <- makeStoreFixture
        let persistentParent = root Posix.</> "persistent"
            persistentPath = persistentParent Posix.</> "store.sqlite"
            cacheRoot = root Posix.</> "cache"
        Directory.createDirectory persistentParent
        Directory.createDirectory cacheRoot
        plan <- expectRightIO
            (Store.planStore
                (Store.ExplicitStore persistentPath))
        initialized <- Store.withStoreLease plan \lease ->
            Store.withOpenStore lease theory \_startup _store ->
                pure ()
        assertEqual "fixture store initialized"
            (Right ()) initialized
        connection <- SQLite.open persistentPath
        SQLite.execute_ connection
            "DROP TABLE canonical_objects"
        SQLite.close connection

        withEnvironment "XDG_CACHE_HOME" cacheRoot do
            result <- Store.withStoreLease plan \lease ->
                Store.withOpenStore lease theory \_startup _store ->
                    pure ()
            case result of
                Left
                    (Store.StoreLifecycleOpenFailed
                        (Store.FatalStoreStartup
                            Store.StoreSchemaIntegrityFailure{})) ->
                    pure ()
                Left other ->
                    assertFailure
                        ("unexpected fatal-startup result: " <> show other)
                Right () ->
                    assertFailure "corrupt persistent store was accepted"
            assertBool "fatal startup creates no default fallback"
                . not
                =<< Directory.doesPathExist
                    (cacheRoot Posix.</> "felix")


data StoreFixture = StoreFixture
    !Identity.AssertedObject
    !Identity.AssertedObject
    !Identity.CheckedPropositionContent

fixtureFirstObject :: StoreFixture -> Identity.AssertedObject
fixtureFirstObject (StoreFixture object _second _proposition) =
    object

fixtureSecondObject :: StoreFixture -> Identity.AssertedObject
fixtureSecondObject (StoreFixture _first object _proposition) =
    object

fixtureProposition
    :: StoreFixture
    -> Identity.CheckedPropositionContent
fixtureProposition (StoreFixture _first _second proposition) =
    proposition

makeStoreFixture
    :: IO (Identity.TheoryId, StoreFixture)
makeStoreFixture = do
    foundation <- expectRight Foundation.checkedFoundation
    let theory = Identity.theoryId foundation
        first = intrinsicObject theory Core.Empty
        second = intrinsicObject theory Core.PairSet
    closure <- expectRight
        (Identity.validateObjectClosure theory [first, second])
    proposition <- expectRight
        (Identity.validatePropositionContent
            closure
            (Core.CEq
                Core.TySet
                (Core.CGlobal (Identity.assertedObjectId first))
                (Core.CGlobal (Identity.assertedObjectId first))))
    pure
        ( theory
        , StoreFixture first second proposition
        )

intrinsicObject
    :: Identity.TheoryId
    -> Core.CoreIntrinsicTag
    -> Identity.AssertedObject
intrinsicObject theory tag =
    Identity.assertedObject identity content
  where
    coreType = Core.coreIntrinsicType tag
    content =
        Identity.IntrinsicObjectContent
            theory tag coreType
    identity =
        Identity.intrinsicObjectId
            theory tag coreType

withStoreFixture
    :: String
    -> ( FilePath
        -> Identity.TheoryId
        -> StoreFixture
        -> IO a
       )
    -> IO a
withStoreFixture template action =
    Temp.withSystemTempDirectory template \root -> do
        (theory, fixture) <- makeStoreFixture
        action
            (root Posix.</> "store.sqlite")
            theory
            fixture

expectOpen
    :: FilePath
    -> Identity.TheoryId
    -> IO (Store.StoreStartup, Store.Store)
expectOpen path theory = do
    result <- Store.openStore path theory
    case result of
        Left failure ->
            assertFailure (show failure) >> fail "unreachable"
        Right opened ->
            pure opened

expectRight :: Show failure => Either failure value -> IO value
expectRight = \case
    Left failure ->
        assertFailure (show failure) >> fail "unreachable"
    Right value ->
        pure value

expectRightIO
    :: Show failure
    => IO (Either failure value)
    -> IO value
expectRightIO action =
    expectRight =<< action

assertFreshRemoved :: IORef.IORef (Maybe FilePath) -> Assertion
assertFreshRemoved pathReference = do
    selected <- IORef.readIORef pathReference
    case selected of
        Nothing ->
            assertFailure "fresh store path was not allocated"
        Just path -> do
            assertBool "fresh database was removed"
                . not
                =<< Directory.doesPathExist path
            assertBool "fresh database directory was removed"
                . not
                =<< Directory.doesPathExist
                    (Posix.takeDirectory path)

withEnvironment
    :: String
    -> String
    -> IO value
    -> IO value
withEnvironment name value action =
    Exception.bracket
        (Environment.lookupEnv name)
        restore
        \_previous -> do
            Environment.setEnv name value
            action
  where
    restore = \case
        Nothing ->
            Environment.unsetEnv name
        Just previous ->
            Environment.setEnv name previous