pumpkin-core 0.4.0

The core of the Pumpkin constraint programming solver.
Documentation
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
use crate::basic_types::Trail;
use crate::containers::HashMap;
use crate::containers::KeyedVec;
use crate::engine::cp::reason::ReasonRef;
use crate::engine::notifications::NotificationEngine;
use crate::engine::predicates::predicate::Predicate;
use crate::engine::predicates::predicate::PredicateType;
use crate::engine::variables::DomainGeneratorIterator;
use crate::engine::variables::DomainId;
use crate::predicate;
use crate::pumpkin_assert_eq_moderate;
use crate::pumpkin_assert_eq_simple;
use crate::pumpkin_assert_moderate;
use crate::pumpkin_assert_simple;
use crate::variables::IntegerVariable;

#[derive(Clone, Debug)]
pub struct Assignments {
    pub(crate) trail: Trail<ConstraintProgrammingTrailEntry>,
    /// The current bounds of the domain. This is a quick lookup of the data stored more verbosely
    /// in `domains`.
    bounds: KeyedVec<DomainId, (i32, i32)>,
    domains: KeyedVec<DomainId, IntegerDomain>,
    /// The number of values that have been pruned from the domain.
    pruned_values: u64,
}

impl Default for Assignments {
    fn default() -> Self {
        let mut assignments = Self {
            trail: Default::default(),
            bounds: Default::default(),
            domains: Default::default(),
            pruned_values: 0,
        };

        // As a convention, we allocate a dummy domain_id=0, which represents a 0-1 variable that is
        // assigned to one. We use it to represent predicates that are trivially true.
        let dummy_variable = assignments.grow(1, 1);
        assert_eq!(dummy_variable.id(), 0);

        assignments
    }
}

#[derive(Clone, Copy, Debug)]
pub struct EmptyDomain;

impl Assignments {
    #[allow(unused, reason = "Could be used in the future")]
    /// Returns all of the holes in the domain which were created at the provided decision level
    pub(crate) fn get_holes_at_checkpoint(
        &self,
        domain_id: DomainId,
        checkpoint: usize,
    ) -> impl Iterator<Item = i32> + '_ {
        self.domains[domain_id].get_holes_at_checkpoint(checkpoint)
    }

    /// Returns all of the holes in the domain which were created at the current decision level
    pub(crate) fn get_holes_at_current_checkpoint(
        &self,
        domain_id: DomainId,
    ) -> impl Iterator<Item = i32> + '_ {
        self.domains[domain_id].get_holes_from_current_checkpoint(self.get_checkpoint())
    }

    /// Returns all of the holes (currently) in the domain of `var` (including ones which were
    /// created at previous decision levels).
    pub(crate) fn get_holes(&self, domain_id: DomainId) -> impl Iterator<Item = i32> + '_ {
        self.domains[domain_id].get_holes()
    }

    pub(crate) fn new_checkpoint(&mut self) {
        self.trail.new_checkpoint()
    }

    pub(crate) fn find_last_decision(&self) -> Option<Predicate> {
        if self.get_checkpoint() == 0 {
            None
        } else {
            let values_at_current_checkpoint =
                self.trail.values_at_checkpoint(self.get_checkpoint());
            let entry = &values_at_current_checkpoint[0];
            pumpkin_assert_eq_simple!(None, entry.reason);

            Some(entry.predicate)
        }
    }

    pub(crate) fn get_checkpoint(&self) -> usize {
        self.trail.get_checkpoint()
    }

    pub(crate) fn num_domains(&self) -> u32 {
        self.domains.len() as u32
    }

    pub(crate) fn get_domains(&self) -> DomainGeneratorIterator {
        // todo: we use 1 here to prevent the always true literal from ending up in the blocking
        // clause
        DomainGeneratorIterator::new(1, self.num_domains())
    }

    pub(crate) fn num_trail_entries(&self) -> usize {
        self.trail.len()
    }

    pub(crate) fn get_trail_entry(&self, index: usize) -> ConstraintProgrammingTrailEntry {
        self.trail[index].clone()
    }

    // registers the domain of a new integer variable
    // note that this is an internal method that does _not_ allocate additional information
    // necessary for the solver apart from the domain when creating a new integer variable, use
    // create_new_domain_id in the ConstraintSatisfactionSolver
    pub(crate) fn grow(&mut self, lower_bound: i32, upper_bound: i32) -> DomainId {
        // This is necessary for the metric that maintains relative domain size. It is only updated
        // when values are removed at levels beyond the root, and then it becomes a tricky value to
        // update when a fresh domain needs to be considered.
        pumpkin_assert_simple!(
            self.get_checkpoint() == 0,
            "can only create variables at the root"
        );

        let id = DomainId::new(self.num_domains());

        let lower_bound_position = self.trail.len();
        self.trail.push(ConstraintProgrammingTrailEntry {
            predicate: predicate!(id >= lower_bound),
            old_lower_bound: lower_bound,
            old_upper_bound: upper_bound,
            reason: None,
        });
        let upper_bound_position = self.trail.len();
        self.trail.push(ConstraintProgrammingTrailEntry {
            predicate: predicate!(id <= upper_bound),
            old_lower_bound: lower_bound,
            old_upper_bound: upper_bound,
            reason: None,
        });

        let _ = self.domains.push(IntegerDomain::new(
            lower_bound,
            lower_bound_position,
            upper_bound,
            upper_bound_position,
            id,
        ));

        let _ = self.bounds.push((lower_bound, upper_bound));

        id
    }
    pub fn create_new_integer_variable_sparse(&mut self, mut values: Vec<i32>) -> DomainId {
        assert!(
            !values.is_empty(),
            "cannot create a variable with an empty domain"
        );

        values.sort();
        values.dedup();

        let lower_bound = values[0];
        let upper_bound = values[values.len() - 1];

        let domain_id = self.grow(lower_bound, upper_bound);

        let mut next_idx = 0;
        for value in lower_bound..=upper_bound {
            if value == values[next_idx] {
                next_idx += 1;
            } else {
                let _ = self
                    .remove_value_from_domain(domain_id, value, None)
                    .expect("the domain should not be empty");

                self.domains[domain_id].initial_holes.push(value);
            }
        }
        self.domains[domain_id].initial_bounds_below_trail = self.trail.len() - 1;
        pumpkin_assert_simple!(
            next_idx == values.len(),
            "Expected all values to have been processed"
        );

        self.update_bounds_snapshot(domain_id);

        domain_id
    }

    pub(crate) fn debug_create_empty_clone(&self) -> Self {
        let mut new_assignment = Assignments::default();

        // Skip the dummy variable that is already created in `Assignments::default`.
        for domain_id in self.domains.keys().skip(1) {
            let lower_bound = self.get_initial_lower_bound(domain_id);
            let upper_bound = self.get_initial_upper_bound(domain_id);
            let holes = self.get_initial_holes(domain_id);

            let new_domain_id = new_assignment.grow(lower_bound, upper_bound);
            assert_eq!(new_domain_id, domain_id);

            for hole in holes {
                let changed_domain = new_assignment
                    .remove_value_from_domain(domain_id, hole, None)
                    .expect("initial domain cannot be empty");

                assert!(changed_domain);
            }

            new_assignment.domains[new_domain_id].initial_bounds_below_trail =
                new_assignment.trail.len() - 1;
        }

        new_assignment
    }

    pub(crate) fn is_initial_bound(&self, predicate: Predicate) -> bool {
        let domain_id = predicate.get_domain();

        let Some(trail_position) = self.get_trail_position(&predicate) else {
            return false;
        };

        trail_position <= self.domains[domain_id].initial_bounds_below_trail
    }
}

// methods for getting info about the domains
impl Assignments {
    pub(crate) fn get_lower_bound(&self, domain_id: DomainId) -> i32 {
        let (lower_bound, _) = self.bounds[domain_id];

        pumpkin_assert_eq_moderate!(
            lower_bound,
            self.domains[domain_id].lower_bound(),
            "bounds for {domain_id} out of sync"
        );

        lower_bound
    }

    pub(crate) fn get_lower_bound_at_trail_position(
        &self,
        domain_id: DomainId,
        trail_position: usize,
    ) -> i32 {
        self.domains[domain_id].lower_bound_at_trail_position(trail_position)
    }

    pub(crate) fn get_upper_bound(&self, domain_id: DomainId) -> i32 {
        let (_, upper_bound) = self.bounds[domain_id];

        pumpkin_assert_eq_moderate!(
            upper_bound,
            self.domains[domain_id].upper_bound(),
            "bounds for {domain_id} out of sync"
        );

        upper_bound
    }

    pub(crate) fn get_upper_bound_at_trail_position(
        &self,
        domain_id: DomainId,
        trail_position: usize,
    ) -> i32 {
        self.domains[domain_id].upper_bound_at_trail_position(trail_position)
    }

    pub(crate) fn get_initial_lower_bound(&self, domain_id: DomainId) -> i32 {
        self.domains[domain_id].initial_lower_bound()
    }

    pub(crate) fn get_initial_upper_bound(&self, domain_id: DomainId) -> i32 {
        self.domains[domain_id].initial_upper_bound()
    }

    pub(crate) fn get_initial_holes(&self, domain_id: DomainId) -> Vec<i32> {
        self.domains[domain_id].initial_holes.clone()
    }

    pub(crate) fn get_assigned_value<Var: IntegerVariable>(&self, var: &Var) -> Option<i32> {
        self.is_domain_assigned(var).then(|| var.lower_bound(self))
    }

    pub(crate) fn is_decision_predicate(&self, predicate: &Predicate) -> bool {
        let domain = predicate.get_domain();
        if let Some(trail_position) = self.get_trail_position(predicate)
            && trail_position > self.domains[domain].initial_bounds_below_trail
        {
            self.trail[trail_position].reason.is_none()
                && self.trail[trail_position].predicate == *predicate
        } else {
            false
        }
    }

    pub(crate) fn get_domain_iterator(&self, domain_id: DomainId) -> IntegerDomainIterator<'_> {
        self.domains[domain_id].domain_iterator()
    }

    /// Returns the conjunction of predicates that define the domain.
    /// Root level predicates are ignored.
    pub(crate) fn get_domain_description(&self, domain_id: DomainId) -> Vec<Predicate> {
        let mut predicates = Vec::new();
        let domain = &self.domains[domain_id];

        // If the domain assigned at a nonroot level, this is just one predicate.
        if domain.lower_bound() == domain.upper_bound()
            && domain.lower_bound_checkpoint() > 0
            && domain.checkpoint() > 0
        {
            predicates.push(predicate![domain_id == domain.lower_bound()]);
            return predicates;
        }

        // Add bounds but avoid root assignments.
        if domain.lower_bound_checkpoint() > 0 {
            predicates.push(predicate![domain_id >= domain.lower_bound()]);
        }

        if domain.checkpoint() > 0 {
            predicates.push(predicate![domain_id <= domain.upper_bound()]);
        }

        // Add holes.
        for hole in &self.domains[domain_id].holes {
            // Only record holes that are within the lower and upper bound,
            // that are not root assignments.
            // Since bound values cannot be in the holes,
            // we can use '<' or '>'.
            if hole.1.checkpoint > 0
                && domain.lower_bound() < *hole.0
                && *hole.0 < domain.upper_bound()
            {
                predicates.push(predicate![domain_id != *hole.0]);
            }
        }
        predicates
    }

    pub(crate) fn is_value_in_domain(&self, domain_id: DomainId, value: i32) -> bool {
        let (lower_bound, upper_bound) = self.bounds[domain_id];

        if value < lower_bound || value > upper_bound {
            return false;
        }

        let domain = &self.domains[domain_id];
        domain.contains(value)
    }

    pub(crate) fn is_value_in_domain_at_trail_position(
        &self,
        domain_id: DomainId,
        value: i32,
        trail_position: usize,
    ) -> bool {
        self.domains[domain_id].contains_at_trail_position(value, trail_position)
    }

    pub(crate) fn is_domain_assigned<Var: IntegerVariable>(&self, var: &Var) -> bool {
        var.lower_bound(self) == var.upper_bound(self)
    }

    /// Returns the index of the trail entry at which point the given predicate became true.
    /// In case the predicate is not true, then the function returns None.
    /// Note that it is not necessary for the predicate to be explicitly present on the trail,
    /// e.g., if [x >= 10] is explicitly present on the trail but not [x >= 6], then the
    /// trail position for [x >= 10] will be returned for the case [x >= 6].
    pub(crate) fn get_trail_position(&self, predicate: &Predicate) -> Option<usize> {
        self.domains[predicate.get_domain()]
            .get_update_info(predicate)
            .map(|u| u.trail_position)
    }

    /// If the predicate is assigned true, returns the decision level of the predicate.
    /// Otherwise returns None.
    pub(crate) fn get_checkpoint_for_predicate(&self, predicate: &Predicate) -> Option<usize> {
        self.domains[predicate.get_domain()]
            .get_update_info(predicate)
            .map(|u| u.checkpoint)
    }

    pub fn get_domain_descriptions(&self) -> Vec<Predicate> {
        let mut descriptions: Vec<Predicate> = vec![];
        for domain in self.domains.iter().enumerate() {
            let domain_id = DomainId::new(domain.0 as u32);
            descriptions.append(&mut self.get_domain_description(domain_id));
        }
        descriptions
    }
}

// methods to change the domains
impl Assignments {
    fn tighten_lower_bound(
        &mut self,
        domain_id: DomainId,
        new_lower_bound: i32,
        reason: Option<ReasonRef>,
    ) -> Result<bool, EmptyDomain> {
        // No need to do any changes if the new lower bound is weaker.
        if new_lower_bound <= self.get_lower_bound(domain_id) {
            return self.domains[domain_id].verify_consistency();
        }

        let predicate = predicate!(domain_id >= new_lower_bound);

        let old_lower_bound = self.get_lower_bound(domain_id);
        let old_upper_bound = self.get_upper_bound(domain_id);

        // important to record trail position _before_ pushing to the trail
        let trail_position = self.trail.len();

        self.trail.push(ConstraintProgrammingTrailEntry {
            predicate,
            old_lower_bound,
            old_upper_bound,
            reason,
        });

        let checkpoint = self.get_checkpoint();
        let domain = &mut self.domains[domain_id];

        let update_took_place = domain.set_lower_bound(new_lower_bound, checkpoint, trail_position);

        self.bounds[domain_id].0 = domain.lower_bound();

        self.pruned_values += domain.lower_bound().abs_diff(old_lower_bound) as u64;

        let _ = domain.verify_consistency()?;

        Ok(update_took_place)
    }

    fn tighten_upper_bound(
        &mut self,
        domain_id: DomainId,
        new_upper_bound: i32,
        reason: Option<ReasonRef>,
    ) -> Result<bool, EmptyDomain> {
        // No need to do any changes if the new upper bound is weaker.
        if new_upper_bound >= self.get_upper_bound(domain_id) {
            return self.domains[domain_id].verify_consistency();
        }

        let predicate = predicate!(domain_id <= new_upper_bound);

        let old_lower_bound = self.get_lower_bound(domain_id);
        let old_upper_bound = self.get_upper_bound(domain_id);

        // important to record trail position _before_ pushing to the trail
        let trail_position = self.trail.len();

        self.trail.push(ConstraintProgrammingTrailEntry {
            predicate,
            old_lower_bound,
            old_upper_bound,
            reason,
        });

        let checkpoint = self.get_checkpoint();
        let domain = &mut self.domains[domain_id];

        let update_took_place = domain.set_upper_bound(new_upper_bound, checkpoint, trail_position);

        self.bounds[domain_id].1 = domain.upper_bound();

        self.pruned_values += old_upper_bound.abs_diff(domain.upper_bound()) as u64;

        let _ = domain.verify_consistency()?;

        Ok(update_took_place)
    }

    fn make_assignment(
        &mut self,
        domain_id: DomainId,
        assigned_value: i32,
        reason: Option<ReasonRef>,
    ) -> Result<bool, EmptyDomain> {
        let mut update_took_place = false;

        let predicate = predicate!(domain_id == assigned_value);

        let old_lower_bound = self.get_lower_bound(domain_id);
        let old_upper_bound = self.get_upper_bound(domain_id);

        if old_lower_bound == assigned_value && old_upper_bound == assigned_value {
            return self.domains[domain_id].verify_consistency();
        }

        // important to record trail position _before_ pushing to the trail
        let trail_position = self.trail.len();

        self.trail.push(ConstraintProgrammingTrailEntry {
            predicate,
            old_lower_bound,
            old_upper_bound,
            reason,
        });

        let checkpoint = self.get_checkpoint();
        let domain = &mut self.domains[domain_id];

        if old_lower_bound < assigned_value {
            update_took_place |= domain.set_lower_bound(assigned_value, checkpoint, trail_position);
            self.bounds[domain_id].0 = domain.lower_bound();
            self.pruned_values += domain.lower_bound().abs_diff(old_lower_bound) as u64;
        }

        if old_upper_bound > assigned_value {
            update_took_place |= domain.set_upper_bound(assigned_value, checkpoint, trail_position);
            self.bounds[domain_id].1 = domain.upper_bound();
            self.pruned_values += domain.upper_bound().abs_diff(old_upper_bound) as u64;
        }

        let _ = self.domains[domain_id].verify_consistency()?;

        Ok(update_took_place)
    }

    fn remove_value_from_domain(
        &mut self,
        domain_id: DomainId,
        removed_value_from_domain: i32,
        reason: Option<ReasonRef>,
    ) -> Result<bool, EmptyDomain> {
        // No need to do any changes if the value is not present anyway.
        if !self.domains[domain_id].contains(removed_value_from_domain) {
            return self.domains[domain_id].verify_consistency();
        }

        let predicate = predicate!(domain_id != removed_value_from_domain);

        let old_lower_bound = self.get_lower_bound(domain_id);
        let old_upper_bound = self.get_upper_bound(domain_id);

        // important to record trail position _before_ pushing to the trail
        let trail_position = self.trail.len();

        self.trail.push(ConstraintProgrammingTrailEntry {
            predicate,
            old_lower_bound,
            old_upper_bound,
            reason,
        });

        let checkpoint = self.get_checkpoint();
        let domain = &mut self.domains[domain_id];

        let _ = domain.remove_value(removed_value_from_domain, checkpoint, trail_position);

        let changed_lower_bound = domain.lower_bound().abs_diff(old_lower_bound) as u64;
        let changed_upper_bound = old_upper_bound.abs_diff(domain.upper_bound()) as u64;

        if changed_lower_bound + changed_upper_bound > 0 {
            self.pruned_values += changed_upper_bound + changed_lower_bound;
        } else {
            self.pruned_values += 1;
        }

        self.update_bounds_snapshot(domain_id);
        let _ = self.domains[domain_id].verify_consistency()?;

        Ok(true)
    }

    /// Apply the given [`Predicate`] to the integer domains.
    ///
    /// In case where the [`Predicate`] is already true, this does nothing and will
    /// return `false`. If the predicate was unassigned and became true, then `true`
    /// is returned. If instead applying the [`Predicate`] leads to an
    /// [`EmptyDomain`], the error variant is returned.
    pub(crate) fn post_predicate(
        &mut self,
        predicate: Predicate,
        reason: Option<ReasonRef>,
        notification_engine: &mut NotificationEngine,
    ) -> Result<bool, EmptyDomain> {
        let (lower_bound_before, upper_bound_before) = self.bounds[predicate.get_domain()];

        let mut removal_took_place = false;

        let domain_id = predicate.get_domain();
        let value = predicate.get_right_hand_side();

        let update_took_place = match predicate.get_predicate_type() {
            PredicateType::LowerBound => self.tighten_lower_bound(domain_id, value, reason)?,
            PredicateType::UpperBound => self.tighten_upper_bound(domain_id, value, reason)?,
            PredicateType::NotEqual => {
                removal_took_place = self.remove_value_from_domain(domain_id, value, reason)?;
                removal_took_place
            }
            PredicateType::Equal => self.make_assignment(domain_id, value, reason)?,
        };

        if update_took_place {
            notification_engine.event_occurred(
                lower_bound_before,
                upper_bound_before,
                self.domains[predicate.get_domain()].lower_bound(),
                self.domains[predicate.get_domain()].upper_bound(),
                removal_took_place,
                predicate.get_domain(),
            );
        }

        Ok(update_took_place)
    }

    /// Determines whether the provided [`Predicate`] holds in the current state of the
    /// [`Assignments`]. In case the predicate is not assigned yet (neither true nor false),
    /// returns None.
    pub(crate) fn evaluate_predicate(&self, predicate: Predicate) -> Option<bool> {
        let domain_id = predicate.get_domain();
        let value = predicate.get_right_hand_side();

        match predicate.get_predicate_type() {
            PredicateType::LowerBound => {
                if self.get_lower_bound(domain_id) >= value {
                    Some(true)
                } else if self.get_upper_bound(domain_id) < value {
                    Some(false)
                } else {
                    None
                }
            }
            PredicateType::UpperBound => {
                if self.get_upper_bound(domain_id) <= value {
                    Some(true)
                } else if self.get_lower_bound(domain_id) > value {
                    Some(false)
                } else {
                    None
                }
            }
            PredicateType::NotEqual => {
                if !self.is_value_in_domain(domain_id, value) {
                    Some(true)
                } else if let Some(assigned_value) = self.get_assigned_value(&domain_id) {
                    // Previous branch concluded the value is not in the domain, so if the variable
                    // is assigned, then it is assigned to the not equals value.
                    pumpkin_assert_simple!(assigned_value == value);
                    Some(false)
                } else {
                    None
                }
            }
            PredicateType::Equal => {
                if !self.is_value_in_domain(domain_id, value) {
                    Some(false)
                } else if let Some(assigned_value) = self.get_assigned_value(&domain_id) {
                    pumpkin_assert_moderate!(assigned_value == value);
                    Some(true)
                } else {
                    None
                }
            }
        }
    }

    pub(crate) fn is_predicate_satisfied(&self, predicate: Predicate) -> bool {
        self.evaluate_predicate(predicate)
            .is_some_and(|truth_value| truth_value)
    }

    #[allow(unused, reason = "makes sense to have in this API")]
    pub(crate) fn is_predicate_falsified(&self, predicate: Predicate) -> bool {
        self.evaluate_predicate(predicate)
            .is_some_and(|truth_value| !truth_value)
    }

    /// Synchronises the internal structures of [`Assignments`] based on the fact that
    /// backtracking to `new_checkpoint` is taking place. This method returns the list of
    /// [`DomainId`]s and their values which were fixed (i.e. domain of size one) before
    /// backtracking and are unfixed (i.e. domain of two or more values) after synchronisation.
    pub(crate) fn synchronise(
        &mut self,
        new_checkpoint: usize,
        notification_engine: &mut NotificationEngine,
    ) -> Vec<(DomainId, i32)> {
        let mut unfixed_variables = Vec::new();
        let num_trail_entries_before_synchronisation = self.num_trail_entries();

        pumpkin_assert_simple!(
            new_checkpoint <= self.trail.get_checkpoint(),
            "Expected the new decision level {new_checkpoint} to be less than or equal to the current decision level {}",
            self.trail.get_checkpoint(),
        );

        self.trail
            .synchronise(new_checkpoint)
            .enumerate()
            .for_each(|(index, entry)| {
                // Calculate how many values are re-introduced into the domain.
                let domain_id = entry.predicate.get_domain();
                let lower_bound_before = self.domains[domain_id].lower_bound();
                let upper_bound_before = self.domains[domain_id].upper_bound();

                let trail_index = num_trail_entries_before_synchronisation - index - 1;

                let add_on_upper_bound = entry.old_upper_bound.abs_diff(upper_bound_before) as u64;
                let add_on_lower_bound = entry.old_lower_bound.abs_diff(lower_bound_before) as u64;
                self.pruned_values -= add_on_upper_bound + add_on_lower_bound;

                if entry.predicate.is_not_equal_predicate()
                    && add_on_lower_bound + add_on_upper_bound == 0
                {
                    self.pruned_values -= 1;
                }

                let fixed_before =
                    self.domains[domain_id].lower_bound() == self.domains[domain_id].upper_bound();
                self.domains[domain_id].undo_trail_entry(&entry);

                let new_lower_bound = self.domains[domain_id].lower_bound();
                let new_upper_bound = self.domains[domain_id].upper_bound();
                self.bounds[domain_id] = (new_lower_bound, new_upper_bound);

                notification_engine.undo_trail_entry(
                    fixed_before,
                    lower_bound_before,
                    upper_bound_before,
                    new_lower_bound,
                    new_upper_bound,
                    trail_index,
                    entry.predicate,
                );

                if new_lower_bound != new_upper_bound {
                    // Variable used to be fixed but is not after backtracking
                    unfixed_variables.push((domain_id, lower_bound_before));
                }
            });

        // Drain does not remove the events from the internal data structure. Elements are removed
        // lazily, as the iterator gets executed. For this reason we go through the entire iterator.
        notification_engine.clear_events();

        unfixed_variables
    }

    /// todo: This is a temporary hack, not to be used in general.
    pub(crate) fn remove_last_trail_element(&mut self) -> (Predicate, ReasonRef) {
        let entry = self.trail.pop().unwrap();
        let domain_id = entry.predicate.get_domain();
        self.domains[domain_id].undo_trail_entry(&entry);
        self.update_bounds_snapshot(domain_id);

        let reason_ref = entry.reason.unwrap();

        (entry.predicate, reason_ref)
    }

    /// Get the number of values pruned from all the domains.
    pub(crate) fn get_pruned_value_count(&self) -> u64 {
        self.pruned_values
    }

    fn update_bounds_snapshot(&mut self, domain_id: DomainId) {
        self.bounds[domain_id] = (
            self.domains[domain_id].lower_bound(),
            self.domains[domain_id].upper_bound(),
        );
    }
}

impl Assignments {
    #[deprecated]
    pub(crate) fn get_reason_for_predicate_brute_force(&self, predicate: Predicate) -> ReasonRef {
        self.trail
            .iter()
            .find_map(|entry| {
                if entry.predicate == predicate {
                    entry.reason
                } else {
                    None
                }
            })
            .unwrap_or_else(|| panic!("could not find a reason for predicate {predicate}"))
    }
}

#[derive(Clone, Debug)]
pub(crate) struct ConstraintProgrammingTrailEntry {
    pub predicate: Predicate,
    /// Explicitly store the bound before the predicate was applied so that it is easier later on
    ///  to update the bounds when backtracking.
    pub(crate) old_lower_bound: i32,
    pub(crate) old_upper_bound: i32,
    /// Stores the a reference to the reason in the `ReasonStore`, only makes sense if a
    /// propagation  took place, e.g., does _not_ make sense in the case of a decision or if
    /// the update was due  to synchronisation from the propositional trail.
    pub(crate) reason: Option<ReasonRef>,
}

#[derive(Clone, Copy, Debug)]
struct PairDecisionLevelTrailPosition {
    checkpoint: usize,
    trail_position: usize,
}

#[derive(Clone, Debug)]
struct BoundUpdateInfo {
    bound: i32,
    checkpoint: usize,
    trail_position: usize,
}

#[derive(Clone, Debug)]
struct HoleUpdateInfo {
    removed_value: i32,

    checkpoint: usize,

    triggered_lower_bound_update: bool,
    triggered_upper_bound_update: bool,
}

/// This is the CP representation of a domain. It stores the bounds alongside holes in the domain.
/// When the domain is in an empty state, `lower_bound > upper_bound`.
/// The domain tracks all domain changes, so it is possible to query the domain at a given
/// cp trail position, i.e., the domain at some previous point in time.
/// This is needed to support lazy explanations.
#[derive(Clone, Debug)]
struct IntegerDomain {
    id: DomainId,
    /// The 'updates' fields chronologically records the changes to the domain.
    lower_bound_updates: Vec<BoundUpdateInfo>,
    upper_bound_updates: Vec<BoundUpdateInfo>,
    hole_updates: Vec<HoleUpdateInfo>,
    /// Auxiliary data structure to make it easy to check if a value is present or not.
    /// This is done to avoid going through 'hole_updates'.
    /// It maps a removed value with its decision level and trail position.
    /// In the future we could consider using direct hashing if the domain is small.
    holes: HashMap<i32, PairDecisionLevelTrailPosition>,
    // Records the trail entry at which all of the root bounds are true
    initial_bounds_below_trail: usize,
    /// The holes that exist in the input problem.
    initial_holes: Vec<i32>,
}

impl IntegerDomain {
    fn new(
        lower_bound: i32,
        lower_bound_position: usize,
        upper_bound: i32,
        upper_bound_position: usize,
        id: DomainId,
    ) -> IntegerDomain {
        pumpkin_assert_simple!(lower_bound <= upper_bound, "Cannot create an empty domain.");

        let lower_bound_updates = vec![BoundUpdateInfo {
            bound: lower_bound,
            checkpoint: 0,
            trail_position: lower_bound_position,
        }];

        let upper_bound_updates = vec![BoundUpdateInfo {
            bound: upper_bound,
            checkpoint: 0,
            trail_position: upper_bound_position,
        }];

        IntegerDomain {
            id,
            initial_holes: vec![],
            lower_bound_updates,
            upper_bound_updates,
            hole_updates: vec![],
            holes: Default::default(),
            initial_bounds_below_trail: std::cmp::max(lower_bound_position, upper_bound_position),
        }
    }

    fn lower_bound(&self) -> i32 {
        // the last entry contains the current lower bound
        self.lower_bound_updates
            .last()
            .expect("Cannot be empty.")
            .bound
    }

    fn lower_bound_checkpoint(&self) -> usize {
        self.lower_bound_updates
            .last()
            .expect("Cannot be empty.")
            .checkpoint
    }

    fn initial_lower_bound(&self) -> i32 {
        // the first entry is never removed,
        // and contains the bound that was assigned upon creation
        self.lower_bound_updates[0].bound
    }

    fn lower_bound_at_trail_position(&self, trail_position: usize) -> i32 {
        // TODO: could possibly cache old queries, and maybe even first checking large/small trail
        // position values (in case those are commonly used)

        // We find the update with the largest trail position such that it is smaller than or equal
        // to the input trail position
        //
        // Recall that by the nature of the updates, the updates are stored in increasing order of
        // trail position.
        //
        // We find the first index such that `u.trail_position > trail_position` and then we
        // subtract 1 from that
        let index = self
            .lower_bound_updates
            .partition_point(|u| u.trail_position <= trail_position);

        self.lower_bound_updates[index.saturating_sub(1)].bound
    }

    fn upper_bound(&self) -> i32 {
        // the last entry contains the current upper bound
        self.upper_bound_updates
            .last()
            .expect("Cannot be empty.")
            .bound
    }

    fn checkpoint(&self) -> usize {
        self.upper_bound_updates
            .last()
            .expect("Cannot be empty.")
            .checkpoint
    }

    fn initial_upper_bound(&self) -> i32 {
        // the first entry is never removed,
        // and contains the bound that was assigned upon creation
        self.upper_bound_updates[0].bound
    }

    fn upper_bound_at_trail_position(&self, trail_position: usize) -> i32 {
        // TODO: could possibly cache old queries, and maybe even first checking large/small trail
        // position values (in case those are commonly used)

        // We find the update with the largest trail position such that it is smaller than or equal
        // to the input trail position
        //
        // Recall that by the nature of the updates, the updates are stored in increasing order of
        // trail position.
        //
        // We find the first index such that `u.trail_position > trail_position` and then we
        // subtract 1 from that
        let index = self
            .upper_bound_updates
            .partition_point(|u| u.trail_position <= trail_position)
            .saturating_sub(1);

        self.upper_bound_updates[index].bound
    }

    fn domain_iterator(&self) -> IntegerDomainIterator<'_> {
        // Ideally we use into_iter but I did not manage to get it to work,
        // because the iterator takes a lifelines
        // (the iterator takes a reference to the domain).
        // So this will do for now.
        IntegerDomainIterator::new(self)
    }

    fn contains(&self, value: i32) -> bool {
        self.lower_bound() <= value
            && value <= self.upper_bound()
            && !self.holes.contains_key(&value)
    }

    fn contains_at_trail_position(&self, value: i32, trail_position: usize) -> bool {
        // If the value is out of bounds,
        // then we can safety say that the value is not in the domain.
        if self.lower_bound_at_trail_position(trail_position) > value
            || self.upper_bound_at_trail_position(trail_position) < value
        {
            return false;
        }
        // Otherwise we need to check if there is a hole with that specific value.

        // In case the hole is made at the given trail position or earlier,
        // the value is not in the domain.
        if let Some(hole_info) = self.holes.get(&value)
            && hole_info.trail_position <= trail_position
        {
            return false;
        }

        // Since none of the previous checks triggered, the value is in the domain.
        true
    }

    fn remove_value(
        &mut self,
        removed_value: i32,
        checkpoint: usize,
        trail_position: usize,
    ) -> bool {
        if removed_value < self.lower_bound()
            || removed_value > self.upper_bound()
            || self.holes.contains_key(&removed_value)
        {
            return false;
        }

        self.hole_updates.push(HoleUpdateInfo {
            removed_value,
            checkpoint,
            triggered_lower_bound_update: false,
            triggered_upper_bound_update: false,
        });
        // Note that it is important to remove the hole now,
        // because the later if statements may use the holes.
        let old_none_entry = self.holes.insert(
            removed_value,
            PairDecisionLevelTrailPosition {
                checkpoint,
                trail_position,
            },
        );
        pumpkin_assert_moderate!(old_none_entry.is_none());

        // Check if removing a value triggers a lower bound update.
        if self.lower_bound() == removed_value {
            let _ = self.set_lower_bound(removed_value + 1, checkpoint, trail_position);
            self.hole_updates
                .last_mut()
                .expect("we just pushed a value, so must be present")
                .triggered_lower_bound_update = true;
        }
        // Check if removing the value triggers an upper bound update.
        if self.upper_bound() == removed_value {
            let _ = self.set_upper_bound(removed_value - 1, checkpoint, trail_position);
            self.hole_updates
                .last_mut()
                .expect("we just pushed a value, so must be present")
                .triggered_upper_bound_update = true;
        }

        true
    }

    fn debug_is_valid_upper_bound_domain_update(
        &self,
        checkpoint: usize,
        trail_position: usize,
    ) -> bool {
        self.upper_bound_updates.last().unwrap().checkpoint <= checkpoint
            && self.upper_bound_updates.last().unwrap().trail_position < trail_position
    }

    fn set_upper_bound(
        &mut self,
        new_upper_bound: i32,
        checkpoint: usize,
        trail_position: usize,
    ) -> bool {
        pumpkin_assert_moderate!(
            self.debug_is_valid_upper_bound_domain_update(checkpoint, trail_position)
        );

        if new_upper_bound >= self.upper_bound() {
            return false;
        }

        self.upper_bound_updates.push(BoundUpdateInfo {
            bound: new_upper_bound,
            checkpoint,
            trail_position,
        });
        self.update_upper_bound_with_respect_to_holes();

        true
    }

    fn update_upper_bound_with_respect_to_holes(&mut self) {
        while self.holes.contains_key(&self.upper_bound())
            && self.lower_bound() <= self.upper_bound()
        {
            self.upper_bound_updates.last_mut().unwrap().bound -= 1;
        }
    }

    fn debug_is_valid_lower_bound_domain_update(
        &self,
        checkpoint: usize,
        trail_position: usize,
    ) -> bool {
        trail_position == 0
            || self.lower_bound_updates.last().unwrap().checkpoint <= checkpoint
                && self.lower_bound_updates.last().unwrap().trail_position < trail_position
    }

    fn set_lower_bound(
        &mut self,
        new_lower_bound: i32,
        checkpoint: usize,
        trail_position: usize,
    ) -> bool {
        pumpkin_assert_moderate!(
            self.debug_is_valid_lower_bound_domain_update(checkpoint, trail_position)
        );

        if new_lower_bound <= self.lower_bound() {
            return false;
        }

        self.lower_bound_updates.push(BoundUpdateInfo {
            bound: new_lower_bound,
            checkpoint,
            trail_position,
        });
        self.update_lower_bound_with_respect_to_holes();

        true
    }

    fn update_lower_bound_with_respect_to_holes(&mut self) {
        while self.holes.contains_key(&self.lower_bound())
            && self.lower_bound() <= self.upper_bound()
        {
            self.lower_bound_updates.last_mut().unwrap().bound += 1;
        }
    }

    fn debug_bounds_check(&self) -> bool {
        // If the domain is empty, the lower bound will be greater than the upper bound.
        if self.lower_bound() > self.upper_bound() {
            true
        } else {
            self.lower_bound() >= self.initial_lower_bound()
                && self.upper_bound() <= self.initial_upper_bound()
                && !self.holes.contains_key(&self.lower_bound())
                && !self.holes.contains_key(&self.upper_bound())
        }
    }

    fn verify_consistency(&self) -> Result<bool, EmptyDomain> {
        if self.lower_bound() > self.upper_bound() {
            Err(EmptyDomain)
        } else {
            Ok(false)
        }
    }

    fn undo_trail_entry(&mut self, entry: &ConstraintProgrammingTrailEntry) {
        let domain_id = entry.predicate.get_domain();
        match entry.predicate.get_predicate_type() {
            PredicateType::LowerBound => {
                pumpkin_assert_moderate!(domain_id == self.id);

                let _ = self.lower_bound_updates.pop();
                pumpkin_assert_moderate!(!self.lower_bound_updates.is_empty());
            }
            PredicateType::UpperBound => {
                pumpkin_assert_moderate!(domain_id == self.id);

                let _ = self.upper_bound_updates.pop();
                pumpkin_assert_moderate!(!self.upper_bound_updates.is_empty());
            }
            PredicateType::NotEqual => {
                pumpkin_assert_moderate!(domain_id == self.id);

                let not_equal_constant = entry.predicate.get_right_hand_side();

                let hole_update = self
                    .hole_updates
                    .pop()
                    .expect("Must have record of domain removal.");
                pumpkin_assert_moderate!(hole_update.removed_value == not_equal_constant);

                let _ = self
                    .holes
                    .remove(&not_equal_constant)
                    .expect("Must be present.");

                if hole_update.triggered_lower_bound_update {
                    let _ = self.lower_bound_updates.pop();
                    pumpkin_assert_moderate!(!self.lower_bound_updates.is_empty());
                }

                if hole_update.triggered_upper_bound_update {
                    let _ = self.upper_bound_updates.pop();
                    pumpkin_assert_moderate!(!self.upper_bound_updates.is_empty());
                }
            }
            PredicateType::Equal => {
                let lower_bound_update = self.lower_bound_updates.last().unwrap();
                let upper_bound_update = self.upper_bound_updates.last().unwrap();

                if lower_bound_update.trail_position > upper_bound_update.trail_position {
                    let _ = self.lower_bound_updates.pop();
                } else if upper_bound_update.trail_position > lower_bound_update.trail_position {
                    let _ = self.upper_bound_updates.pop();
                } else {
                    let _ = self.lower_bound_updates.pop();
                    let _ = self.upper_bound_updates.pop();
                }
            }
        };

        // these asserts will be removed, for now it is a sanity check
        // later we may remove the old bound from the trail entry since it is not needed
        pumpkin_assert_eq_simple!(self.lower_bound(), entry.old_lower_bound);
        pumpkin_assert_eq_simple!(self.upper_bound(), entry.old_upper_bound);

        pumpkin_assert_moderate!(self.debug_bounds_check());
    }

    fn get_update_info(&self, predicate: &Predicate) -> Option<PairDecisionLevelTrailPosition> {
        // Perhaps the recursion could be done in a cleaner way,
        // e.g., separate functions dependibng on the type of predicate.
        // For the initial version, the current version is okay.
        let domain_id = predicate.get_domain();
        let value = predicate.get_right_hand_side();

        match predicate.get_predicate_type() {
            PredicateType::LowerBound => {
                // Recall that by the nature of the updates,
                // the updates are stored in increasing order of the lower bound.

                // find the update with smallest lower bound
                // that is greater than or equal to the input lower bound
                let position = self
                    .lower_bound_updates
                    .partition_point(|u| u.bound < value);

                (position < self.lower_bound_updates.len()).then(|| {
                    let u = &self.lower_bound_updates[position];
                    PairDecisionLevelTrailPosition {
                        checkpoint: u.checkpoint,
                        trail_position: u.trail_position,
                    }
                })
            }
            PredicateType::UpperBound => {
                // Recall that by the nature of the updates,
                // the updates are stored in decreasing order of the upper bound.

                // find the update with greatest upper bound
                // that is smaller than or equal to the input upper bound
                let position = self
                    .upper_bound_updates
                    .partition_point(|u| u.bound > value);

                (position < self.upper_bound_updates.len()).then(|| {
                    let u = &self.upper_bound_updates[position];
                    PairDecisionLevelTrailPosition {
                        checkpoint: u.checkpoint,
                        trail_position: u.trail_position,
                    }
                })
            }
            PredicateType::NotEqual => {
                // Check the explictly stored holes.
                // If the value has been removed explicitly,
                // then the stored time is the first time the value was removed.
                if let Some(hole_info) = self.holes.get(&value) {
                    Some(*hole_info)
                } else {
                    // Otherwise, check the case when the lower/upper bound surpassed the value.
                    // If this never happened, then report that the predicate is not true.

                    // Note that it cannot be that both the lower bound and upper bound surpassed
                    // the not equals constant, i.e., at most one of the two may happen.
                    // So we can stop as soon as we find one of the two.

                    // Check the lower bound first.
                    if let Some(trail_position) =
                        self.get_update_info(&predicate!(domain_id >= value + 1))
                    {
                        // The lower bound removed the value from the domain,
                        // report the trail position of the lower bound.
                        Some(trail_position)
                    } else {
                        // The lower bound did not surpass the value,
                        // now check the upper bound.
                        self.get_update_info(&predicate!(domain_id <= value - 1))
                    }
                }
            }
            PredicateType::Equal => {
                // For equality to hold, both the lower and upper bound predicates must hold.
                // Check lower bound first.
                if let Some(lb_trail_position) =
                    self.get_update_info(&predicate!(domain_id >= value))
                {
                    // The lower bound found,
                    // now the check depends on the upper bound.

                    // If both the lower and upper bounds are present,
                    // report the trail position of the bound that was set last.
                    // Otherwise, return that the predicate is not on the trail.
                    self.get_update_info(&predicate!(domain_id <= value))
                        .map(|ub_trail_position| {
                            if lb_trail_position.trail_position > ub_trail_position.trail_position {
                                lb_trail_position
                            } else {
                                ub_trail_position
                            }
                        })
                }
                // If the lower bound is never reached,
                // then surely the equality predicate cannot be true.
                else {
                    None
                }
            }
        }
    }

    /// Returns the holes which were created on the provided decision level.
    pub(crate) fn get_holes_at_checkpoint(
        &self,
        checkpoint: usize,
    ) -> impl Iterator<Item = i32> + '_ {
        self.hole_updates
            .iter()
            .filter(move |entry| entry.checkpoint == checkpoint)
            .map(|entry| entry.removed_value)
    }

    /// Returns the holes which were created on the current decision level.
    pub(crate) fn get_holes_from_current_checkpoint(
        &self,
        current_checkpoint: usize,
    ) -> impl Iterator<Item = i32> + '_ {
        self.hole_updates
            .iter()
            .rev()
            .take_while(move |entry| entry.checkpoint == current_checkpoint)
            .map(|entry| entry.removed_value)
    }

    /// Returns all of the holes (currently) in the domain of `var` (including ones which were
    /// created at previous decision levels).
    pub(crate) fn get_holes(&self) -> impl Iterator<Item = i32> + '_ {
        self.holes.keys().copied()
    }
}

#[derive(Debug)]
pub(crate) struct IntegerDomainIterator<'a> {
    domain: &'a IntegerDomain,
    current_value: i32,
}

impl IntegerDomainIterator<'_> {
    fn new(domain: &IntegerDomain) -> IntegerDomainIterator<'_> {
        IntegerDomainIterator {
            domain,
            current_value: domain.lower_bound(),
        }
    }
}

impl Iterator for IntegerDomainIterator<'_> {
    type Item = i32;
    fn next(&mut self) -> Option<i32> {
        // We would not expect to iterate through inconsistent domains,
        // although we support trying to do so. Not sure if this is good a idea?
        if self.domain.verify_consistency().is_err() {
            return None;
        }

        // Note that the current value is never a hole. This is guaranteed by 1) having
        // a consistent domain, 2) the iterator starts with the lower bound,
        // and 3) the while loop after this if statement updates the current value
        // to a non-hole value (if there are any left within the bounds).
        let result = if self.current_value <= self.domain.upper_bound() {
            Some(self.current_value)
        } else {
            None
        };

        self.current_value += 1;
        // If the current value is within the bounds, but is not in the domain,
        // linearly look for the next non-hole value.
        while self.current_value <= self.domain.upper_bound()
            && !self.domain.contains(self.current_value)
        {
            self.current_value += 1;
        }
        result
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::engine::notifications::DomainEvent;

    #[test]
    fn jump_in_bound_change_lower_and_upper_bound_event_backtrack() {
        let mut notification_engine = NotificationEngine::test_default();
        let mut assignment = Assignments::default();
        let d1 = assignment.grow(1, 5);
        notification_engine.grow();

        assignment.new_checkpoint();

        let _ = assignment
            .post_predicate(predicate!(d1 != 1), None, &mut notification_engine)
            .expect("non-empty domain");
        let _ = assignment
            .post_predicate(predicate!(d1 != 5), None, &mut notification_engine)
            .expect("non-empty domain");

        let _ = assignment.synchronise(0, &mut notification_engine);

        let events = notification_engine
            .drain_backtrack_domain_events()
            .collect::<Vec<_>>();
        assert_eq!(events.len(), 3);

        assert_contains_events(&events, d1, [DomainEvent::LowerBound]);
        assert_contains_events(&events, d1, [DomainEvent::UpperBound]);
        assert_contains_events(&events, d1, [DomainEvent::Removal]);
    }

    #[test]
    fn jump_in_bound_change_assign_event_backtrack() {
        let mut notification_engine = NotificationEngine::test_default();
        let mut assignment = Assignments::default();
        let d1 = assignment.grow(1, 5);
        notification_engine.grow();

        assignment.new_checkpoint();

        let _ = assignment
            .post_predicate(predicate!(d1 != 2), None, &mut notification_engine)
            .expect("non-empty domain");
        let _ = assignment
            .post_predicate(predicate!(d1 != 3), None, &mut notification_engine)
            .expect("non-empty domain");
        let _ = assignment
            .post_predicate(predicate!(d1 != 4), None, &mut notification_engine)
            .expect("non-empty domain");
        let _ = assignment
            .post_predicate(predicate!(d1 != 5), None, &mut notification_engine)
            .expect("non-empty domain");
        let _ = assignment
            .post_predicate(predicate!(d1 != 1), None, &mut notification_engine)
            .expect_err("empty domain");

        let _ = assignment.synchronise(0, &mut notification_engine);

        let events = notification_engine
            .drain_backtrack_domain_events()
            .collect::<Vec<_>>();
        assert_eq!(events.len(), 4);

        assert_contains_events(&events, d1, [DomainEvent::LowerBound]);
        assert_contains_events(&events, d1, [DomainEvent::UpperBound]);
        assert_contains_events(&events, d1, [DomainEvent::Removal]);
        assert_contains_events(&events, d1, [DomainEvent::Assign]);
    }

    #[test]
    fn jump_in_bound_change_upper_bound_event_backtrack() {
        let mut notification_engine = NotificationEngine::test_default();
        let mut assignment = Assignments::default();
        let d1 = assignment.grow(1, 5);
        notification_engine.grow();

        assignment.new_checkpoint();

        let _ = assignment
            .post_predicate(predicate!(d1 != 3), None, &mut notification_engine)
            .expect("non-empty domain");
        let _ = assignment
            .post_predicate(predicate!(d1 != 4), None, &mut notification_engine)
            .expect("non-empty domain");
        let _ = assignment
            .post_predicate(predicate!(d1 != 5), None, &mut notification_engine)
            .expect("non-empty domain");

        let _ = assignment.synchronise(0, &mut notification_engine);

        let events = notification_engine
            .drain_backtrack_domain_events()
            .collect::<Vec<_>>();
        assert_eq!(events.len(), 2);

        assert_contains_events(&events, d1, [DomainEvent::UpperBound]);
        assert_contains_events(&events, d1, [DomainEvent::Removal]);
    }

    #[test]
    fn jump_in_bound_change_lower_bound_event_backtrack() {
        let mut notification_engine = NotificationEngine::test_default();
        let mut assignment = Assignments::default();
        let d1 = assignment.grow(1, 5);
        notification_engine.grow();

        assignment.new_checkpoint();

        let _ = assignment
            .remove_value_from_domain(d1, 3, None)
            .expect("non-empty domain");
        let _ = assignment
            .remove_value_from_domain(d1, 2, None)
            .expect("non-empty domain");
        let _ = assignment
            .remove_value_from_domain(d1, 1, None)
            .expect("non-empty domain");

        let _ = assignment.synchronise(0, &mut notification_engine);

        let events = notification_engine
            .drain_backtrack_domain_events()
            .collect::<Vec<_>>();
        assert_eq!(events.len(), 2);

        assert_contains_events(&events, d1, [DomainEvent::LowerBound]);
        assert_contains_events(&events, d1, [DomainEvent::Removal]);
    }

    #[test]
    fn lower_bound_change_lower_bound_event() {
        let mut notification_engine = NotificationEngine::default();
        let mut assignment = Assignments::default();
        let d1 = assignment.grow(1, 5);
        notification_engine.grow();

        let _ = assignment
            .post_predicate(predicate!(d1 >= 2), None, &mut notification_engine)
            .expect("non-empty domain");

        let events = notification_engine
            .drain_domain_events()
            .collect::<Vec<_>>();
        assert_eq!(events.len(), 1);

        assert_contains_events(&events, d1, [DomainEvent::LowerBound]);
    }

    #[test]
    fn upper_bound_change_triggers_upper_bound_event() {
        let mut notification_engine = NotificationEngine::default();
        let mut assignment = Assignments::default();
        let d1 = assignment.grow(1, 5);
        notification_engine.grow();

        let _ = assignment
            .post_predicate(predicate!(d1 <= 2), None, &mut notification_engine)
            .expect("non-empty domain");

        let events = notification_engine
            .drain_domain_events()
            .collect::<Vec<_>>();
        assert_eq!(events.len(), 1);
        assert_contains_events(&events, d1, [DomainEvent::UpperBound]);
    }

    #[test]
    fn bounds_change_can_also_trigger_assign_event() {
        let mut notification_engine = NotificationEngine::default();
        let mut assignment = Assignments::default();

        let d1 = assignment.grow(1, 5);
        let d2 = assignment.grow(1, 5);
        notification_engine.grow();
        notification_engine.grow();

        let _ = assignment
            .post_predicate(predicate!(d1 >= 5), None, &mut notification_engine)
            .expect("non-empty domain");
        let _ = assignment
            .post_predicate(predicate!(d2 <= 1), None, &mut notification_engine)
            .expect("non-empty domain");

        let events = notification_engine
            .drain_domain_events()
            .collect::<Vec<_>>();
        assert_eq!(events.len(), 4, "expected more than 4 events: {events:?}");

        assert_contains_events(&events, d1, [DomainEvent::LowerBound, DomainEvent::Assign]);
        assert_contains_events(&events, d2, [DomainEvent::UpperBound, DomainEvent::Assign]);
    }

    #[test]
    fn making_assignment_triggers_appropriate_events() {
        let mut notification_engine = NotificationEngine::default();
        let mut assignment = Assignments::default();

        let d1 = assignment.grow(1, 5);
        let d2 = assignment.grow(1, 5);
        let d3 = assignment.grow(1, 5);
        notification_engine.grow();
        notification_engine.grow();
        notification_engine.grow();

        let _ = assignment
            .post_predicate(predicate!(d1 == 1), None, &mut notification_engine)
            .expect("non-empty domain");
        let _ = assignment
            .post_predicate(predicate!(d2 == 5), None, &mut notification_engine)
            .expect("non-empty domain");
        let _ = assignment
            .post_predicate(predicate!(d3 == 3), None, &mut notification_engine)
            .expect("non-empty domain");

        let events = notification_engine
            .drain_domain_events()
            .collect::<Vec<_>>();
        assert_eq!(events.len(), 7);

        assert_contains_events(&events, d1, [DomainEvent::Assign, DomainEvent::UpperBound]);
        assert_contains_events(&events, d2, [DomainEvent::Assign, DomainEvent::LowerBound]);
        assert_contains_events(
            &events,
            d3,
            [
                DomainEvent::Assign,
                DomainEvent::LowerBound,
                DomainEvent::UpperBound,
            ],
        );
    }

    #[test]
    fn removal_triggers_removal_event() {
        let mut notification_engine = NotificationEngine::default();
        let mut assignment = Assignments::default();
        let d1 = assignment.grow(1, 5);
        notification_engine.grow();

        let _ = assignment
            .post_predicate(predicate!(d1 != 2), None, &mut notification_engine)
            .expect("non-empty domain");

        let events = notification_engine
            .drain_domain_events()
            .collect::<Vec<_>>();
        assert_eq!(events.len(), 1);
        assert!(events.contains(&(DomainEvent::Removal, d1)));
    }

    #[test]
    fn value_can_be_removed_from_domains() {
        let mut domain = IntegerDomain::new(1, 0, 5, 1, DomainId::new(0));
        let _ = domain.remove_value(1, 1, 2);

        assert!(domain.contains(2));
        assert!(!domain.contains(1));
    }

    #[test]
    fn removing_the_lower_bound_updates_that_lower_bound() {
        let mut domain = IntegerDomain::new(1, 0, 5, 1, DomainId::new(0));
        let _ = domain.remove_value(1, 1, 1);
        let _ = domain.remove_value(2, 1, 2);

        assert_eq!(3, domain.lower_bound());
    }

    #[test]
    fn removing_the_upper_bound_updates_the_upper_bound() {
        let mut domain = IntegerDomain::new(1, 0, 5, 1, DomainId::new(0));
        let _ = domain.remove_value(4, 0, 1);
        let _ = domain.remove_value(5, 0, 2);

        assert_eq!(3, domain.upper_bound());
    }

    #[test]
    fn an_empty_domain_accepts_removal_operations() {
        let mut domain = IntegerDomain::new(1, 0, 5, 1, DomainId::new(0));
        let _ = domain.remove_value(4, 0, 1);
        let _ = domain.remove_value(1, 0, 2);
        let _ = domain.remove_value(1, 0, 3);
    }

    #[test]
    fn setting_lower_bound_rounds_up_to_nearest_value_in_domain() {
        let mut domain = IntegerDomain::new(1, 0, 5, 1, DomainId::new(0));
        let _ = domain.remove_value(2, 1, 2);
        let _ = domain.remove_value(3, 1, 3);
        let _ = domain.set_lower_bound(2, 1, 4);

        assert_eq!(4, domain.lower_bound());
    }

    #[test]
    fn setting_upper_bound_rounds_down_to_nearest_value_in_domain() {
        let mut domain = IntegerDomain::new(1, 0, 5, 1, DomainId::new(0));
        let _ = domain.remove_value(4, 0, 1);
        let _ = domain.set_upper_bound(4, 0, 2);

        assert_eq!(3, domain.upper_bound());
    }

    #[test]
    fn undo_removal_at_bounds_indexes_into_values_domain_correctly() {
        let mut notification_engine = NotificationEngine::default();
        let mut assignment = Assignments::default();
        let d1 = assignment.grow(1, 5);
        notification_engine.grow();

        assignment.new_checkpoint();

        let _ = assignment
            .post_predicate(predicate!(d1 != 5), None, &mut notification_engine)
            .expect("non-empty domain");

        let _ = assignment.synchronise(0, &mut notification_engine);

        assert_eq!(5, assignment.get_upper_bound(d1));
    }

    fn assert_contains_events(
        slice: &[(DomainEvent, DomainId)],
        domain: DomainId,
        required_events: impl IntoIterator<Item = DomainEvent>,
    ) {
        for event in required_events {
            assert!(slice.contains(&(event, domain)));
        }
    }

    fn get_domain1() -> (DomainId, IntegerDomain) {
        let domain_id = DomainId::new(0);
        let mut domain = IntegerDomain::new(0, 0, 100, 1, domain_id);
        let _ = domain.set_lower_bound(1, 0, 1);
        let _ = domain.set_lower_bound(5, 1, 2);
        let _ = domain.set_lower_bound(10, 2, 10);
        let _ = domain.set_lower_bound(20, 5, 50);
        let _ = domain.set_lower_bound(50, 10, 70);

        (domain_id, domain)
    }

    #[test]
    fn lower_bound_trail_position_inbetween_value() {
        let (domain_id, domain) = get_domain1();

        assert_eq!(
            domain
                .get_update_info(&predicate!(domain_id >= 12))
                .unwrap()
                .trail_position,
            50
        );
    }

    #[test]
    fn lower_bound_trail_position_last_bound() {
        let (domain_id, domain) = get_domain1();

        assert_eq!(
            domain
                .get_update_info(&predicate!(domain_id >= 50))
                .unwrap()
                .trail_position,
            70
        );
    }

    #[test]
    fn lower_bound_trail_position_beyond_value() {
        let (domain_id, domain) = get_domain1();

        assert!(
            domain
                .get_update_info(&predicate!(domain_id >= 101))
                .is_none()
        );
    }

    #[test]
    fn lower_bound_trail_position_trivial() {
        let (domain_id, domain) = get_domain1();

        assert_eq!(
            domain
                .get_update_info(&predicate!(domain_id >= -10))
                .unwrap()
                .trail_position,
            0
        );
    }

    #[test]
    fn lower_bound_trail_position_with_removals() {
        let (domain_id, mut domain) = get_domain1();
        let _ = domain.remove_value(50, 11, 75);
        let _ = domain.remove_value(51, 11, 77);
        let _ = domain.remove_value(52, 11, 80);

        assert_eq!(
            domain
                .get_update_info(&predicate!(domain_id >= 52))
                .unwrap()
                .trail_position,
            77
        );
    }

    #[test]
    fn removal_trail_position() {
        let (domain_id, mut domain) = get_domain1();
        let _ = domain.remove_value(50, 11, 75);
        let _ = domain.remove_value(51, 11, 77);
        let _ = domain.remove_value(52, 11, 80);

        assert_eq!(
            domain
                .get_update_info(&predicate!(domain_id != 50))
                .unwrap()
                .trail_position,
            75
        );
    }

    #[test]
    fn removal_trail_position_after_lower_bound() {
        let (domain_id, mut domain) = get_domain1();
        let _ = domain.remove_value(50, 11, 75);
        let _ = domain.remove_value(51, 11, 77);
        let _ = domain.remove_value(52, 11, 80);
        let _ = domain.set_lower_bound(60, 11, 150);

        assert_eq!(
            domain
                .get_update_info(&predicate!(domain_id != 55))
                .unwrap()
                .trail_position,
            150
        );
    }

    #[test]
    fn lower_bound_change_backtrack() {
        let mut notification_engine = NotificationEngine::default();
        let mut assignment = Assignments::default();
        let domain_id1 = assignment.grow(0, 100);
        let domain_id2 = assignment.grow(0, 50);
        notification_engine.grow();
        notification_engine.grow();

        // decision level 1
        assignment.new_checkpoint();
        let _ = assignment
            .post_predicate(predicate!(domain_id1 >= 2), None, &mut notification_engine)
            .expect("");
        let _ = assignment
            .post_predicate(predicate!(domain_id2 >= 25), None, &mut notification_engine)
            .expect("");

        // decision level 2
        assignment.new_checkpoint();
        let _ = assignment
            .post_predicate(predicate!(domain_id1 >= 5), None, &mut notification_engine)
            .expect("");

        // decision level 3
        assignment.new_checkpoint();
        let _ = assignment
            .post_predicate(predicate!(domain_id1 >= 7), None, &mut notification_engine)
            .expect("");

        assert_eq!(assignment.get_lower_bound(domain_id1), 7);

        let _ = assignment.synchronise(1, &mut notification_engine);

        assert_eq!(assignment.get_lower_bound(domain_id1), 2);
    }

    #[test]
    fn lower_bound_inbetween_updates() {
        let (_, domain) = get_domain1();
        assert_eq!(domain.lower_bound_at_trail_position(25), 10);
    }

    #[test]
    fn lower_bound_beyond_trail_position() {
        let (_, domain) = get_domain1();
        assert_eq!(domain.lower_bound_at_trail_position(1000), 50);
    }

    #[test]
    fn lower_bound_at_update() {
        let (_, domain) = get_domain1();
        assert_eq!(domain.lower_bound_at_trail_position(50), 20);
    }

    #[test]
    fn lower_bound_at_trail_position_after_removals() {
        let (_, mut domain) = get_domain1();
        let _ = domain.remove_value(50, 11, 75);
        let _ = domain.remove_value(51, 11, 77);
        let _ = domain.remove_value(52, 11, 80);

        assert_eq!(domain.lower_bound_at_trail_position(77), 52);
    }

    #[test]
    fn lower_bound_at_trail_position_after_removals_and_bound_update() {
        let (_, mut domain) = get_domain1();
        let _ = domain.remove_value(50, 11, 75);
        let _ = domain.remove_value(51, 11, 77);
        let _ = domain.remove_value(52, 11, 80);
        let _ = domain.set_lower_bound(60, 11, 150);

        assert_eq!(domain.lower_bound_at_trail_position(100), 53);
    }

    #[test]
    fn inconsistent_bound_updates() {
        let domain_id = DomainId::new(0);
        let mut domain = IntegerDomain::new(0, 0, 2, 1, domain_id);
        let _ = domain.set_lower_bound(2, 1, 1);
        let _ = domain.set_upper_bound(1, 1, 2);
        assert!(domain.verify_consistency().is_err());
    }

    #[test]
    fn inconsistent_domain_removals() {
        let domain_id = DomainId::new(0);
        let mut domain = IntegerDomain::new(0, 0, 2, 1, domain_id);
        let _ = domain.remove_value(1, 1, 1);
        let _ = domain.remove_value(2, 1, 2);
        let _ = domain.remove_value(0, 1, 3);
        assert!(domain.verify_consistency().is_err());
    }

    #[test]
    fn domain_iterator_simple() {
        let domain_id = DomainId::new(0);
        let domain = IntegerDomain::new(0, 0, 5, 1, domain_id);
        let mut iter = domain.domain_iterator();
        assert_eq!(iter.next(), Some(0));
        assert_eq!(iter.next(), Some(1));
        assert_eq!(iter.next(), Some(2));
        assert_eq!(iter.next(), Some(3));
        assert_eq!(iter.next(), Some(4));
        assert_eq!(iter.next(), Some(5));
        assert_eq!(iter.next(), None);
    }

    #[test]
    fn domain_iterator_skip_holes() {
        let domain_id = DomainId::new(0);
        let mut domain = IntegerDomain::new(0, 0, 5, 1, domain_id);
        let _ = domain.remove_value(1, 0, 5);
        let _ = domain.remove_value(4, 0, 10);

        let mut iter = domain.domain_iterator();
        assert_eq!(iter.next(), Some(0));
        assert_eq!(iter.next(), Some(2));
        assert_eq!(iter.next(), Some(3));
        assert_eq!(iter.next(), Some(5));
        assert_eq!(iter.next(), None);
    }

    #[test]
    fn domain_iterator_removed_bounds() {
        let domain_id = DomainId::new(0);
        let mut domain = IntegerDomain::new(0, 0, 5, 1, domain_id);
        let _ = domain.remove_value(0, 0, 1);
        let _ = domain.remove_value(5, 0, 10);

        let mut iter = domain.domain_iterator();
        assert_eq!(iter.next(), Some(1));
        assert_eq!(iter.next(), Some(2));
        assert_eq!(iter.next(), Some(3));
        assert_eq!(iter.next(), Some(4));
        assert_eq!(iter.next(), None);
    }

    #[test]
    fn domain_iterator_removed_values_present_beyond_bounds() {
        let domain_id = DomainId::new(0);
        let mut domain = IntegerDomain::new(0, 0, 10, 1, domain_id);
        let _ = domain.remove_value(7, 0, 1);
        let _ = domain.remove_value(9, 0, 5);
        let _ = domain.remove_value(2, 0, 10);
        let _ = domain.set_upper_bound(6, 1, 10);

        let mut iter = domain.domain_iterator();
        assert_eq!(iter.next(), Some(0));
        assert_eq!(iter.next(), Some(1));
        assert_eq!(iter.next(), Some(3));
        assert_eq!(iter.next(), Some(4));
        assert_eq!(iter.next(), Some(5));
        assert_eq!(iter.next(), Some(6));
        assert_eq!(iter.next(), None);
    }

    #[test]
    fn various_tests_evaluate_predicate() {
        let mut notification_engine = NotificationEngine::default();
        let mut assignments = Assignments::default();
        // Create the domain {0, 1, 3, 4, 5, 6}
        let domain_id = assignments.grow(0, 10);
        notification_engine.grow();

        let _ =
            assignments.post_predicate(predicate!(domain_id != 7), None, &mut notification_engine);
        let _ =
            assignments.post_predicate(predicate!(domain_id != 9), None, &mut notification_engine);
        let _ =
            assignments.post_predicate(predicate!(domain_id != 2), None, &mut notification_engine);
        let _ =
            assignments.post_predicate(predicate!(domain_id <= 6), None, &mut notification_engine);

        let lb_predicate = |lower_bound: i32| -> Predicate { predicate!(domain_id >= lower_bound) };
        let ub_predicate = |upper_bound: i32| -> Predicate { predicate!(domain_id <= upper_bound) };
        let eq_predicate =
            |equality_constant: i32| -> Predicate { predicate!(domain_id == equality_constant) };
        let neq_predicate =
            |not_equal_constant: i32| -> Predicate { predicate!(domain_id != not_equal_constant) };

        assert!(
            assignments
                .evaluate_predicate(lb_predicate(0))
                .is_some_and(|x| x)
        );
        assert!(assignments.evaluate_predicate(lb_predicate(1)).is_none());
        assert!(assignments.evaluate_predicate(lb_predicate(2)).is_none());
        assert!(assignments.evaluate_predicate(lb_predicate(3)).is_none());
        assert!(assignments.evaluate_predicate(lb_predicate(4)).is_none());
        assert!(assignments.evaluate_predicate(lb_predicate(5)).is_none());
        assert!(assignments.evaluate_predicate(lb_predicate(6)).is_none());
        assert!(
            assignments
                .evaluate_predicate(lb_predicate(7))
                .is_some_and(|x| !x)
        );
        assert!(
            assignments
                .evaluate_predicate(lb_predicate(8))
                .is_some_and(|x| !x)
        );
        assert!(
            assignments
                .evaluate_predicate(lb_predicate(9))
                .is_some_and(|x| !x)
        );
        assert!(
            assignments
                .evaluate_predicate(lb_predicate(10))
                .is_some_and(|x| !x)
        );

        assert!(assignments.evaluate_predicate(ub_predicate(0)).is_none());
        assert!(assignments.evaluate_predicate(ub_predicate(1)).is_none());
        assert!(assignments.evaluate_predicate(ub_predicate(2)).is_none());
        assert!(assignments.evaluate_predicate(ub_predicate(3)).is_none());
        assert!(assignments.evaluate_predicate(ub_predicate(4)).is_none());
        assert!(assignments.evaluate_predicate(ub_predicate(5)).is_none());
        assert!(
            assignments
                .evaluate_predicate(ub_predicate(6))
                .is_some_and(|x| x)
        );
        assert!(
            assignments
                .evaluate_predicate(ub_predicate(7))
                .is_some_and(|x| x)
        );
        assert!(
            assignments
                .evaluate_predicate(ub_predicate(8))
                .is_some_and(|x| x)
        );
        assert!(
            assignments
                .evaluate_predicate(ub_predicate(9))
                .is_some_and(|x| x)
        );
        assert!(
            assignments
                .evaluate_predicate(ub_predicate(10))
                .is_some_and(|x| x)
        );

        assert!(assignments.evaluate_predicate(neq_predicate(0)).is_none());
        assert!(assignments.evaluate_predicate(neq_predicate(1)).is_none());
        assert!(
            assignments
                .evaluate_predicate(neq_predicate(2))
                .is_some_and(|x| x)
        );
        assert!(assignments.evaluate_predicate(neq_predicate(3)).is_none());
        assert!(assignments.evaluate_predicate(neq_predicate(4)).is_none());
        assert!(assignments.evaluate_predicate(neq_predicate(5)).is_none());
        assert!(assignments.evaluate_predicate(neq_predicate(6)).is_none());
        assert!(
            assignments
                .evaluate_predicate(neq_predicate(7))
                .is_some_and(|x| x)
        );
        assert!(
            assignments
                .evaluate_predicate(neq_predicate(8))
                .is_some_and(|x| x)
        );
        assert!(
            assignments
                .evaluate_predicate(neq_predicate(9))
                .is_some_and(|x| x)
        );
        assert!(
            assignments
                .evaluate_predicate(neq_predicate(10))
                .is_some_and(|x| x)
        );

        assert!(assignments.evaluate_predicate(eq_predicate(0)).is_none());
        assert!(assignments.evaluate_predicate(eq_predicate(1)).is_none());
        assert!(
            assignments
                .evaluate_predicate(eq_predicate(2))
                .is_some_and(|x| !x)
        );
        assert!(assignments.evaluate_predicate(eq_predicate(3)).is_none());
        assert!(assignments.evaluate_predicate(eq_predicate(4)).is_none());
        assert!(assignments.evaluate_predicate(eq_predicate(5)).is_none());
        assert!(assignments.evaluate_predicate(eq_predicate(6)).is_none());
        assert!(
            assignments
                .evaluate_predicate(eq_predicate(7))
                .is_some_and(|x| !x)
        );
        assert!(
            assignments
                .evaluate_predicate(eq_predicate(8))
                .is_some_and(|x| !x)
        );
        assert!(
            assignments
                .evaluate_predicate(eq_predicate(9))
                .is_some_and(|x| !x)
        );
        assert!(
            assignments
                .evaluate_predicate(eq_predicate(10))
                .is_some_and(|x| !x)
        );

        let _ =
            assignments.post_predicate(predicate!(domain_id >= 6), None, &mut notification_engine);

        assert!(
            assignments
                .evaluate_predicate(neq_predicate(6))
                .is_some_and(|x| !x)
        );
        assert!(
            assignments
                .evaluate_predicate(eq_predicate(6))
                .is_some_and(|x| x)
        );
        assert!(
            assignments
                .evaluate_predicate(lb_predicate(6))
                .is_some_and(|x| x)
        );
        assert!(
            assignments
                .evaluate_predicate(ub_predicate(6))
                .is_some_and(|x| x)
        );
    }
}