ommx 3.0.0-beta.2

Open Mathematical prograMming eXchange (OMMX)
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
mod parse;
mod serialize;

use crate::{
    constraint_type::EvaluatedCollection,
    decision_variable::{EvaluatedDecisionVariableTable, VariableLabelStore},
    indicator_constraint::IndicatorConstraint,
    ATol, Constraint, ConstraintID, EvaluatedConstraint, EvaluatedDecisionVariable,
    EvaluatedNamedFunction, NamedFunctionID, NamedFunctionTable, Sense, VariableID,
};
use getset::Getters;
use std::collections::{BTreeMap, BTreeSet, HashMap};

/// Error occurred during Solution validation
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum SolutionError {
    #[error("Inconsistent feasibility for solution: provided={provided_feasible}, computed={computed_feasible}")]
    InconsistentFeasibility {
        provided_feasible: bool,
        computed_feasible: bool,
    },

    #[error("Inconsistent feasibility (relaxed) for solution: provided={provided_feasible_relaxed}, computed={computed_feasible_relaxed}")]
    InconsistentFeasibilityRelaxed {
        provided_feasible_relaxed: bool,
        computed_feasible_relaxed: bool,
    },

    #[error("Inconsistent feasibility for {constraint_family} constraint {constraint_id}: provided={provided_feasible}, computed={computed_feasible}")]
    InconsistentConstraintFeasibility {
        constraint_family: &'static str,
        constraint_id: String,
        provided_feasible: bool,
        computed_feasible: bool,
    },

    #[error("Invalid structure for {constraint_family} constraint {constraint_id}: {message}")]
    InvalidConstraintStructure {
        constraint_family: &'static str,
        constraint_id: String,
        message: String,
    },

    #[error("Inconsistent value for variable {id}: state={state_value}, substituted_value={substituted_value}")]
    InconsistentVariableValue {
        id: u64,
        state_value: f64,
        substituted_value: f64,
    },

    #[error("Missing value for variable {id}: not found in state and no substituted_value")]
    MissingVariableValue { id: u64 },

    #[error("Duplicated variable ID is found in definition: {id:?}")]
    DuplicatedVariableID { id: VariableID },

    #[error("Duplicated named function ID is found in definition: {id:?}")]
    DuplicatedNamedFunctionID { id: NamedFunctionID },

    #[deprecated(
        note = "Parameters are now ignored in extract_decision_variables and extract_all_decision_variables"
    )]
    #[error("Decision variable with parameters is not supported")]
    ParameterizedVariable,

    #[error("Constraint with parameters is not supported")]
    ParameterizedConstraint,

    #[error("Duplicate subscript: {subscripts:?}")]
    DuplicateSubscript { subscripts: Vec<i64> },

    #[error("Unknown constraint ID: {id:?}")]
    UnknownConstraintID { id: ConstraintID },

    #[error("No decision variables with name '{name}' found")]
    UnknownVariableName { name: String },

    #[error("No constraint with name '{name}' found")]
    UnknownConstraintName { name: String },

    #[error("Unknown named function ID: {id:?}")]
    UnknownNamedFunctionID { id: NamedFunctionID },

    #[error("No named function with name '{name}' found")]
    UnknownNamedFunctionName { name: String },

    #[deprecated(
        note = "Parameters are now allowed in extract methods; only subscripts are used as keys"
    )]
    #[error("Named function with parameters is not supported")]
    ParameterizedNamedFunction,

    #[error("Required field is missing: {field}")]
    MissingRequiredField { field: &'static str },

    #[error(
        "Variable ID {id:?} used in constraint {constraint_id:?} is not in decision_variables"
    )]
    UndefinedVariableInConstraint {
        id: VariableID,
        constraint_id: ConstraintID,
    },

    #[error(
        "Variable ID {id:?} used in named function {named_function_id:?} is not in decision_variables"
    )]
    UndefinedVariableInNamedFunction {
        id: VariableID,
        named_function_id: NamedFunctionID,
    },

    #[error("{message}")]
    InvalidSidecar { message: String },
}

/// Single solution result with data integrity guarantees
///
/// Invariants
/// -----------
/// - [`Self::decision_variables`] owns a
///   [`EvaluatedDecisionVariableTable`]; table keys own
///   [`VariableID`] and evaluated decision-variable rows do not carry IDs.
/// - The decision-variable table rejects modeling labels for unknown variable
///   IDs.
/// - The keys of the evaluated constraint collections are the table-owned
///   constraint IDs for each constraint family.
/// - [`Self::evaluated_named_functions`] is keyed by the table-owned
///   [`NamedFunctionID`]; evaluated named-function rows do not carry IDs.
/// - [`Self::decision_variables`] contains all variable IDs referenced in
///   `used_decision_variable_ids` of each evaluated constraint and evaluated
///   named function.
/// - Evaluated special-constraint structural variables are defined in
///   [`Self::decision_variables`]. Indicator variables and one-hot variables
///   must be binary; one-hot and SOS1 variable sets must be non-empty, and
///   `active_variable` values must belong to their structural variable set.
/// - Evaluated special-constraint stage fields are consistent with
///   [`Self::decision_variables`]: `indicator_active` reflects the indicator
///   variable value, and one-hot/SOS1 `active_variable` plus `feasible` reflect
///   the structural variable values under `feasibility_atol`.
/// - `feasibility_atol` is the absolute tolerance used to interpret
///   decision-variable feasibility and to validate serialized per-constraint
///   feasibility columns.
///
/// Note
/// -----
/// - [`Self::optimality`] is determined by the solver, not validated by this struct.
/// - [`Self::relaxation`] is a record of operations, not validated by this struct.
#[derive(Debug, Clone, PartialEq, Getters)]
pub struct Solution {
    #[getset(get = "pub")]
    objective: f64,
    #[getset(get = "pub")]
    evaluated_constraints: EvaluatedCollection<Constraint>,
    #[getset(get = "pub")]
    evaluated_indicator_constraints: EvaluatedCollection<IndicatorConstraint>,
    #[getset(get = "pub")]
    evaluated_one_hot_constraints: EvaluatedCollection<crate::OneHotConstraint>,
    #[getset(get = "pub")]
    evaluated_sos1_constraints: EvaluatedCollection<crate::Sos1Constraint>,
    /// Evaluated named-function rows plus their modeling labels.
    evaluated_named_functions: NamedFunctionTable<EvaluatedNamedFunction>,
    /// Evaluated decision-variable rows plus their modeling labels.
    decision_variables: EvaluatedDecisionVariableTable,
    /// Optimality status - not guaranteed by Solution itself
    pub optimality: crate::v1::Optimality,
    /// Relaxation status - not guaranteed by Solution itself
    pub relaxation: crate::v1::Relaxation,
    #[getset(get = "pub")]
    sense: Option<Sense>,
    /// Absolute tolerance used to compute and validate feasibility fields.
    #[getset(get_copy = "pub")]
    feasibility_atol: ATol,
    /// OMMX-defined provenance metadata.
    pub metadata: Option<crate::v1::ProcessMetadata>,
    /// User-defined or third-party extension annotations.
    pub annotations: HashMap<String, String>,
}

fn validate_evaluated_named_function_used_ids(
    decision_variables: &EvaluatedDecisionVariableTable,
    evaluated_named_functions: &NamedFunctionTable<EvaluatedNamedFunction>,
) -> Result<(), SolutionError> {
    for (named_function_id, named_function) in evaluated_named_functions.iter() {
        for var_id in named_function.used_decision_variable_ids() {
            if !decision_variables.contains_key(var_id) {
                return Err(SolutionError::UndefinedVariableInNamedFunction {
                    id: *var_id,
                    named_function_id: *named_function_id,
                });
            }
        }
    }
    Ok(())
}

impl Solution {
    /// Access evaluated named-function rows plus their modeling labels.
    pub fn evaluated_named_function_table(&self) -> &NamedFunctionTable<EvaluatedNamedFunction> {
        &self.evaluated_named_functions
    }

    /// Access evaluated named-function row payloads keyed by table-owned IDs.
    pub fn evaluated_named_functions(&self) -> &BTreeMap<NamedFunctionID, EvaluatedNamedFunction> {
        self.evaluated_named_functions.entries()
    }

    /// Access the per-named-function modeling-label store.
    pub fn named_function_labels(&self) -> &crate::named_function::NamedFunctionLabelStore {
        self.evaluated_named_functions.labels()
    }

    /// Access evaluated decision-variable rows plus their modeling labels.
    pub fn decision_variable_table(&self) -> &EvaluatedDecisionVariableTable {
        &self.decision_variables
    }

    /// Access evaluated decision-variable rows keyed by table-owned IDs.
    pub fn decision_variables(&self) -> &BTreeMap<VariableID, EvaluatedDecisionVariable> {
        self.decision_variables.entries()
    }

    /// Access the per-variable modeling-label store.
    pub fn variable_labels(&self) -> &VariableLabelStore {
        self.decision_variables.labels()
    }

    /// Get decision variable IDs used in this solution
    pub fn decision_variable_ids(&self) -> BTreeSet<VariableID> {
        self.decision_variables.keys().cloned().collect()
    }

    /// Get constraint IDs evaluated in this solution
    pub fn constraint_ids(&self) -> BTreeSet<ConstraintID> {
        self.evaluated_constraints.keys().cloned().collect()
    }

    /// Get named function IDs evaluated in this solution
    pub fn named_function_ids(&self) -> BTreeSet<NamedFunctionID> {
        self.evaluated_named_functions.keys().cloned().collect()
    }

    /// Check if all decision variables satisfy their kind and bound constraints
    pub fn feasible_decision_variables(&self) -> bool {
        self.decision_variables
            .values()
            .all(|dv| dv.is_valid(self.feasibility_atol))
    }

    /// Check if all constraints are feasible
    ///
    /// Note: This only checks constraints, not decision variable bounds/kinds.
    /// - To check both constraints and decision variables, use [`feasible()`](Self::feasible)
    /// - To check only decision variables, use [`feasible_decision_variables()`](Self::feasible_decision_variables)
    pub fn feasible_constraints(&self) -> bool {
        self.evaluated_constraints.is_feasible()
            && self.evaluated_indicator_constraints.is_feasible()
            && self.evaluated_one_hot_constraints.is_feasible()
            && self.evaluated_sos1_constraints.is_feasible()
    }

    /// Check if all constraints and decision variables are feasible
    ///
    /// This is the most comprehensive feasibility check, verifying:
    /// - All constraints are satisfied (via [`feasible_constraints()`](Self::feasible_constraints))
    /// - All decision variables satisfy their bounds and kinds (via [`feasible_decision_variables()`](Self::feasible_decision_variables))
    pub fn feasible(&self) -> bool {
        self.feasible_constraints() && self.feasible_decision_variables()
    }

    /// Check if all constraints are feasible in the relaxed problem
    ///
    /// Note: This only checks constraints, not decision variable bounds/kinds.
    /// - To check both constraints and decision variables, use [`feasible_relaxed()`](Self::feasible_relaxed)
    /// - To check only decision variables, use [`feasible_decision_variables()`](Self::feasible_decision_variables)
    pub fn feasible_constraints_relaxed(&self) -> bool {
        self.evaluated_constraints.is_feasible_relaxed()
            && self.evaluated_indicator_constraints.is_feasible_relaxed()
            && self.evaluated_one_hot_constraints.is_feasible_relaxed()
            && self.evaluated_sos1_constraints.is_feasible_relaxed()
    }

    /// Check if all constraints and decision variables are feasible in the relaxed problem
    ///
    /// This checks:
    /// - Relaxed constraints are satisfied (via [`feasible_constraints_relaxed()`](Self::feasible_constraints_relaxed))
    /// - All decision variables satisfy their bounds and kinds (via [`feasible_decision_variables()`](Self::feasible_decision_variables))
    pub fn feasible_relaxed(&self) -> bool {
        self.feasible_constraints_relaxed() && self.feasible_decision_variables()
    }

    /// Calculate total constraint violation using L1 norm (sum of absolute violations)
    ///
    /// Returns the sum of violations across all constraints (including removed constraints):
    /// - For equality constraints: `Σ|f(x)|`
    /// - For inequality constraints: `Σmax(0, f(x))`
    ///
    /// This metric is useful for:
    /// - Assessing solution quality when constraints are violated
    /// - Penalty method implementations
    /// - Comparing different solutions
    pub fn total_violation_l1(&self) -> f64 {
        self.evaluated_constraints
            .values()
            .map(|c| c.violation())
            .sum()
    }

    /// Calculate total constraint violation using L2 norm squared (sum of squared violations)
    ///
    /// Returns the sum of squared violations across all constraints (including removed constraints):
    /// - For equality constraints: `Σ(f(x))²`
    /// - For inequality constraints: `Σ(max(0, f(x)))²`
    ///
    /// This metric is useful for:
    /// - Penalty methods that use quadratic penalties
    /// - Emphasizing larger violations over smaller ones
    /// - Smooth optimization objectives
    pub fn total_violation_l2(&self) -> f64 {
        self.evaluated_constraints
            .values()
            .map(|c| {
                let v = c.violation();
                v * v
            })
            .sum()
    }

    /// Generate state from decision variables (for backward compatibility)
    pub fn state(&self) -> crate::v1::State {
        let entries = self
            .decision_variables
            .iter()
            .map(|(id, dv)| (id.into_inner(), *dv.value()))
            .collect();
        crate::v1::State { entries }
    }

    /// Get all unique decision variable names in this solution
    ///
    /// Returns a set of all unique variable names that have at least one named variable.
    /// Variables without names are not included.
    pub fn decision_variable_names(&self) -> BTreeSet<String> {
        self.decision_variables
            .keys()
            .filter_map(|id| self.variable_labels().name(*id).map(|s| s.to_owned()))
            .collect()
    }

    /// Extract decision variables by name with subscripts as key
    ///
    /// Returns a mapping from subscripts (as a vector) to the variable's value.
    /// This is useful for extracting variables that have the same name but different subscripts.
    ///
    /// Note: Parameters in decision variable labels are ignored. Only subscripts are used as keys.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - No decision variables with the given name are found
    /// - The same subscript is found multiple times (which can happen when parameters differ)
    ///
    pub fn extract_decision_variables(
        &self,
        name: &str,
    ) -> Result<BTreeMap<Vec<i64>, f64>, SolutionError> {
        // Collect all variables with the given name from their modeling labels.
        let variables_with_name: Vec<(VariableID, &EvaluatedDecisionVariable)> = self
            .decision_variables
            .iter()
            .filter(|(id, _)| self.variable_labels().name(**id) == Some(name))
            .map(|(id, v)| (*id, v))
            .collect();
        if variables_with_name.is_empty() {
            return Err(SolutionError::UnknownVariableName {
                name: name.to_string(),
            });
        }

        let mut result = BTreeMap::new();
        for (id, dv) in &variables_with_name {
            let key = self.variable_labels().subscripts(*id).to_vec();
            if result.contains_key(&key) {
                return Err(SolutionError::DuplicateSubscript { subscripts: key });
            }
            result.insert(key, *dv.value());
        }
        Ok(result)
    }

    /// Extract all decision variables grouped by name
    ///
    /// Returns a mapping from variable name to a mapping from subscripts to values.
    /// This is useful for extracting all variables at once in a structured format.
    /// Variables without names are not included in the result.
    ///
    /// Note: Parameters in decision variable labels are ignored. Only subscripts are used as keys.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The same name and subscript combination is found multiple times (which can happen when parameters differ)
    ///
    pub fn extract_all_decision_variables(
        &self,
    ) -> Result<BTreeMap<String, BTreeMap<Vec<i64>, f64>>, SolutionError> {
        let mut result: BTreeMap<String, BTreeMap<Vec<i64>, f64>> = BTreeMap::new();

        for (id, dv) in self.decision_variables.iter() {
            let name = match self.variable_labels().name(*id) {
                Some(n) => n.to_owned(),
                None => continue, // Skip variables without names
            };

            let subscripts = self.variable_labels().subscripts(*id).to_vec();
            let value = *dv.value();

            let vars_map = result.entry(name).or_default();
            if vars_map.contains_key(&subscripts) {
                return Err(SolutionError::DuplicateSubscript { subscripts });
            }
            vars_map.insert(subscripts, value);
        }

        Ok(result)
    }

    /// Extract constraints by name with subscripts as key
    ///
    /// Returns a mapping from subscripts (as a vector) to the constraint's evaluated value.
    /// This is useful for extracting constraints that have the same name but different subscripts.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - No constraints with the given name are found
    /// - A constraint with parameters is found
    /// - The same subscript is found multiple times
    ///
    pub fn extract_constraints(
        &self,
        name: &str,
    ) -> Result<BTreeMap<Vec<i64>, f64>, SolutionError> {
        // Collect all constraints with the given name from the collection's
        // modeling-label sidecar.
        let context = self.evaluated_constraints.context();
        let matches: Vec<(ConstraintID, &EvaluatedConstraint)> = self
            .evaluated_constraints
            .iter()
            .filter(|(id, _)| context.name(**id) == Some(name))
            .map(|(id, c)| (*id, c))
            .collect();
        if matches.is_empty() {
            return Err(SolutionError::UnknownConstraintName {
                name: name.to_string(),
            });
        }

        let mut result = BTreeMap::new();
        for (id, ec) in &matches {
            if !context.parameters(*id).is_empty() {
                return Err(SolutionError::ParameterizedConstraint);
            }
            let key = context.subscripts(*id).to_vec();
            if result.contains_key(&key) {
                return Err(SolutionError::DuplicateSubscript { subscripts: key });
            }
            result.insert(key, ec.stage.evaluated_value);
        }
        Ok(result)
    }

    /// Get the evaluated value of a specific constraint by ID
    pub fn get_constraint_value(&self, constraint_id: ConstraintID) -> Result<f64, SolutionError> {
        self.evaluated_constraints
            .get(&constraint_id)
            .map(|c| c.stage.evaluated_value)
            .ok_or(SolutionError::UnknownConstraintID { id: constraint_id })
    }

    /// Get the dual variable value of a specific constraint by ID
    pub fn get_dual_variable(
        &self,
        constraint_id: ConstraintID,
    ) -> Result<Option<f64>, SolutionError> {
        self.evaluated_constraints
            .get(&constraint_id)
            .map(|c| c.stage.dual_variable)
            .ok_or(SolutionError::UnknownConstraintID { id: constraint_id })
    }

    /// Set the dual variable value for a specific constraint by ID
    pub fn set_dual_variable(
        &mut self,
        constraint_id: ConstraintID,
        value: Option<f64>,
    ) -> Result<(), SolutionError> {
        if let Some(mut constraint) = self.evaluated_constraints.get(&constraint_id).cloned() {
            constraint.stage.dual_variable = value;
            assert!(
                self.evaluated_constraints
                    .replace_evaluated_row(constraint_id, constraint)
                    .is_some(),
                "constraint presence was verified above"
            );
            Ok(())
        } else {
            Err(SolutionError::UnknownConstraintID { id: constraint_id })
        }
    }

    /// Get all unique named function names in this solution
    ///
    /// Returns a set of all unique function names that have at least one named function.
    /// Named functions without names are not included.
    pub fn named_function_names(&self) -> BTreeSet<String> {
        self.evaluated_named_functions
            .keys()
            .filter_map(|id| self.named_function_labels().name(*id).map(str::to_owned))
            .collect()
    }

    /// Extract named functions by name with subscripts as key
    ///
    /// Returns a mapping from subscripts (as a vector) to the function's evaluated value.
    /// This is useful for extracting named functions that have the same name but different subscripts.
    ///
    /// Note: Parameters in named function are ignored. Only subscripts are used as keys.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - No named functions with the given name are found
    /// - The same subscript is found multiple times
    pub fn extract_named_functions(
        &self,
        name: &str,
    ) -> Result<BTreeMap<Vec<i64>, f64>, SolutionError> {
        // Collect all named functions with the given name
        let functions_with_name: Vec<(NamedFunctionID, &EvaluatedNamedFunction)> = self
            .evaluated_named_functions
            .iter()
            .filter(|(id, _)| self.named_function_labels().name(**id) == Some(name))
            .map(|(id, nf)| (*id, nf))
            .collect();
        if functions_with_name.is_empty() {
            return Err(SolutionError::UnknownNamedFunctionName {
                name: name.to_string(),
            });
        }

        let mut result = BTreeMap::new();
        for (id, nf) in &functions_with_name {
            let key = self.named_function_labels().subscripts(*id).to_vec();
            if result.contains_key(&key) {
                return Err(SolutionError::DuplicateSubscript { subscripts: key });
            }
            result.insert(key, nf.evaluated_value());
        }
        Ok(result)
    }

    /// Extract all named functions grouped by name
    ///
    /// Returns a mapping from function name to a mapping from subscripts to evaluated values.
    /// This is useful for extracting all named functions at once in a structured format.
    /// Named functions without names are not included in the result.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The same name and subscript combination is found multiple times
    pub fn extract_all_named_functions(
        &self,
    ) -> Result<BTreeMap<String, BTreeMap<Vec<i64>, f64>>, SolutionError> {
        let mut result: BTreeMap<String, BTreeMap<Vec<i64>, f64>> = BTreeMap::new();

        for (id, nf) in &self.evaluated_named_functions {
            let name = match self.named_function_labels().name(*id) {
                Some(n) => n.to_string(),
                None => continue, // Skip named functions without names
            };

            let subscripts = self.named_function_labels().subscripts(*id).to_vec();
            let value = nf.evaluated_value();

            let funcs_map = result.entry(name).or_default();
            if funcs_map.contains_key(&subscripts) {
                return Err(SolutionError::DuplicateSubscript { subscripts });
            }
            funcs_map.insert(subscripts, value);
        }

        Ok(result)
    }

    /// Creates a new [`SolutionBuilder`].
    pub fn builder() -> SolutionBuilder {
        SolutionBuilder::new()
    }
}

/// Builder for creating [`Solution`] with validation.
///
/// # Example
/// ```
/// use ommx::{Solution, Sense};
/// use std::collections::BTreeMap;
///
/// let solution = Solution::builder()
///     .objective(0.0)
///     .evaluated_constraints(BTreeMap::new())
///     .decision_variables(BTreeMap::new())
///     .sense(Sense::Minimize)
///     .build()
///     .unwrap();
/// ```
#[derive(Debug, Clone, Default)]
pub struct SolutionBuilder {
    objective: Option<f64>,
    evaluated_constraints: Option<EvaluatedCollection<Constraint>>,
    evaluated_indicator_constraints: EvaluatedCollection<IndicatorConstraint>,
    evaluated_one_hot_constraints: EvaluatedCollection<crate::OneHotConstraint>,
    evaluated_sos1_constraints: EvaluatedCollection<crate::Sos1Constraint>,
    evaluated_named_function_table: Option<NamedFunctionTable<EvaluatedNamedFunction>>,
    evaluated_named_functions: BTreeMap<NamedFunctionID, EvaluatedNamedFunction>,
    decision_variables: Option<BTreeMap<VariableID, EvaluatedDecisionVariable>>,
    variable_labels: VariableLabelStore,
    named_function_labels: crate::named_function::NamedFunctionLabelStore,
    sense: Option<Sense>,
    feasibility_atol: ATol,
    optimality: crate::v1::Optimality,
    relaxation: crate::v1::Relaxation,
}

fn expected_regular_constraint_feasible(
    equality: crate::Equality,
    evaluated_value: f64,
    atol: ATol,
) -> bool {
    match equality {
        crate::Equality::EqualToZero => evaluated_value.abs() < *atol,
        crate::Equality::LessThanOrEqualToZero => evaluated_value < *atol,
    }
}

fn expected_indicator_constraint_feasible(
    equality: crate::Equality,
    evaluated_value: f64,
    indicator_active: bool,
    atol: ATol,
) -> bool {
    if !indicator_active {
        return true;
    }
    expected_regular_constraint_feasible(equality, evaluated_value, atol)
}

fn validate_solution_constraint_feasibility(
    regular_constraints: &EvaluatedCollection<Constraint>,
    indicator_constraints: &EvaluatedCollection<IndicatorConstraint>,
    one_hot_constraints: &EvaluatedCollection<crate::OneHotConstraint>,
    sos1_constraints: &EvaluatedCollection<crate::Sos1Constraint>,
    atol: ATol,
) -> Result<(), SolutionError> {
    for (id, constraint) in regular_constraints.inner() {
        let computed_feasible = expected_regular_constraint_feasible(
            constraint.equality,
            constraint.stage.evaluated_value,
            atol,
        );
        if constraint.stage.feasible != computed_feasible {
            return Err(SolutionError::InconsistentConstraintFeasibility {
                constraint_family: "regular",
                constraint_id: format!("{id:?}"),
                provided_feasible: constraint.stage.feasible,
                computed_feasible,
            });
        }
    }

    for (id, constraint) in indicator_constraints.inner() {
        let computed_feasible = expected_indicator_constraint_feasible(
            constraint.equality,
            constraint.stage.evaluated_value,
            constraint.stage.indicator_active,
            atol,
        );
        if constraint.stage.feasible != computed_feasible {
            return Err(SolutionError::InconsistentConstraintFeasibility {
                constraint_family: "indicator",
                constraint_id: format!("{id:?}"),
                provided_feasible: constraint.stage.feasible,
                computed_feasible,
            });
        }
    }

    for (id, constraint) in one_hot_constraints.inner() {
        let computed_feasible = constraint.stage.active_variable.is_some();
        if constraint.stage.feasible != computed_feasible {
            return Err(SolutionError::InconsistentConstraintFeasibility {
                constraint_family: "one-hot",
                constraint_id: format!("{id:?}"),
                provided_feasible: constraint.stage.feasible,
                computed_feasible,
            });
        }
    }

    for (id, constraint) in sos1_constraints.inner() {
        if constraint.stage.active_variable.is_some() && !constraint.stage.feasible {
            return Err(SolutionError::InconsistentConstraintFeasibility {
                constraint_family: "SOS1",
                constraint_id: format!("{id:?}"),
                provided_feasible: constraint.stage.feasible,
                computed_feasible: true,
            });
        }
    }

    Ok(())
}

fn validate_solution_special_constraint_structure(
    decision_variables: &EvaluatedDecisionVariableTable,
    indicator_constraints: &EvaluatedCollection<IndicatorConstraint>,
    one_hot_constraints: &EvaluatedCollection<crate::OneHotConstraint>,
    sos1_constraints: &EvaluatedCollection<crate::Sos1Constraint>,
) -> Result<(), SolutionError> {
    for (id, constraint) in indicator_constraints.inner() {
        let variable_id = constraint.indicator_variable;
        let Some(variable) = decision_variables.get(&variable_id) else {
            return Err(SolutionError::InvalidConstraintStructure {
                constraint_family: "indicator",
                constraint_id: format!("{id:?}"),
                message: format!("indicator variable {variable_id:?} is not in decision_variables"),
            });
        };
        if *variable.kind() != crate::decision_variable::Kind::Binary {
            return Err(SolutionError::InvalidConstraintStructure {
                constraint_family: "indicator",
                constraint_id: format!("{id:?}"),
                message: format!("indicator variable {variable_id:?} must be binary"),
            });
        }
    }

    for (id, constraint) in one_hot_constraints.inner() {
        if constraint.variables.is_empty() {
            return Err(SolutionError::InvalidConstraintStructure {
                constraint_family: "one-hot",
                constraint_id: format!("{id:?}"),
                message: "one-hot constraints must contain at least one variable".to_string(),
            });
        }
        for variable_id in &constraint.variables {
            let Some(variable) = decision_variables.get(variable_id) else {
                return Err(SolutionError::InvalidConstraintStructure {
                    constraint_family: "one-hot",
                    constraint_id: format!("{id:?}"),
                    message: format!("variable {variable_id:?} is not in decision_variables"),
                });
            };
            if *variable.kind() != crate::decision_variable::Kind::Binary {
                return Err(SolutionError::InvalidConstraintStructure {
                    constraint_family: "one-hot",
                    constraint_id: format!("{id:?}"),
                    message: format!("variable {variable_id:?} must be binary"),
                });
            }
        }
        if constraint
            .stage
            .active_variable
            .is_some_and(|variable_id| !constraint.variables.contains(&variable_id))
        {
            return Err(SolutionError::InvalidConstraintStructure {
                constraint_family: "one-hot",
                constraint_id: format!("{id:?}"),
                message: "active_variable must be a member of variables".to_string(),
            });
        }
    }

    for (id, constraint) in sos1_constraints.inner() {
        if constraint.variables.is_empty() {
            return Err(SolutionError::InvalidConstraintStructure {
                constraint_family: "SOS1",
                constraint_id: format!("{id:?}"),
                message: "SOS1 constraints must contain at least one variable".to_string(),
            });
        }
        for variable_id in &constraint.variables {
            if !decision_variables.contains_key(variable_id) {
                return Err(SolutionError::InvalidConstraintStructure {
                    constraint_family: "SOS1",
                    constraint_id: format!("{id:?}"),
                    message: format!("variable {variable_id:?} is not in decision_variables"),
                });
            }
        }
        if constraint
            .stage
            .active_variable
            .is_some_and(|variable_id| !constraint.variables.contains(&variable_id))
        {
            return Err(SolutionError::InvalidConstraintStructure {
                constraint_family: "SOS1",
                constraint_id: format!("{id:?}"),
                message: "active_variable must be a member of variables".to_string(),
            });
        }
    }

    Ok(())
}

fn expected_binary_activity(
    variable_id: VariableID,
    value: f64,
    atol: ATol,
    role: &'static str,
) -> Result<bool, String> {
    if (value - 1.0).abs() < *atol {
        Ok(true)
    } else if value.abs() < *atol {
        Ok(false)
    } else {
        Err(format!(
            "{role} variable {variable_id:?} has value {value}, but must be 0 or 1",
        ))
    }
}

fn expected_one_hot_active_variable(
    variables: &BTreeSet<VariableID>,
    decision_variables: &EvaluatedDecisionVariableTable,
    atol: ATol,
) -> (bool, Option<VariableID>) {
    let mut active = None;
    for variable_id in variables {
        let value = *decision_variables
            .get(variable_id)
            .expect("one-hot structural variables must be validated first")
            .value();
        if (value - 1.0).abs() < *atol {
            if active.is_some() {
                return (false, None);
            }
            active = Some(*variable_id);
        } else if value.abs() >= *atol {
            return (false, None);
        }
    }
    match active {
        Some(variable_id) => (true, Some(variable_id)),
        None => (false, None),
    }
}

fn expected_sos1_active_variable(
    variables: &BTreeSet<VariableID>,
    decision_variables: &EvaluatedDecisionVariableTable,
    atol: ATol,
) -> (bool, Option<VariableID>) {
    let mut active = None;
    for variable_id in variables {
        let value = *decision_variables
            .get(variable_id)
            .expect("SOS1 structural variables must be validated first")
            .value();
        if value.abs() >= *atol {
            if active.is_some() {
                return (false, None);
            }
            active = Some(*variable_id);
        }
    }
    (true, active)
}

fn validate_solution_indicator_stage_values(
    decision_variables: &EvaluatedDecisionVariableTable,
    indicator_constraints: &EvaluatedCollection<IndicatorConstraint>,
    atol: ATol,
) -> Result<(), SolutionError> {
    for (id, constraint) in indicator_constraints.inner() {
        let variable = decision_variables
            .get(&constraint.indicator_variable)
            .expect("indicator structural variables must be validated first");
        let computed_indicator_active = expected_binary_activity(
            constraint.indicator_variable,
            *variable.value(),
            atol,
            "indicator",
        )
        .map_err(|message| SolutionError::InvalidConstraintStructure {
            constraint_family: "indicator",
            constraint_id: format!("{id:?}"),
            message,
        })?;
        if constraint.stage.indicator_active != computed_indicator_active {
            return Err(SolutionError::InvalidConstraintStructure {
                constraint_family: "indicator",
                constraint_id: format!("{id:?}"),
                message: format!(
                    "indicator_active={} does not match indicator variable {:?} value {}",
                    constraint.stage.indicator_active,
                    constraint.indicator_variable,
                    variable.value(),
                ),
            });
        }
        let computed_feasible = expected_indicator_constraint_feasible(
            constraint.equality,
            constraint.stage.evaluated_value,
            computed_indicator_active,
            atol,
        );
        if constraint.stage.feasible != computed_feasible {
            return Err(SolutionError::InconsistentConstraintFeasibility {
                constraint_family: "indicator",
                constraint_id: format!("{id:?}"),
                provided_feasible: constraint.stage.feasible,
                computed_feasible,
            });
        }
    }
    Ok(())
}

fn validate_solution_one_hot_stage_values(
    decision_variables: &EvaluatedDecisionVariableTable,
    one_hot_constraints: &EvaluatedCollection<crate::OneHotConstraint>,
    atol: ATol,
) -> Result<(), SolutionError> {
    for (id, constraint) in one_hot_constraints.inner() {
        let (computed_feasible, computed_active_variable) =
            expected_one_hot_active_variable(&constraint.variables, decision_variables, atol);
        if constraint.stage.active_variable != computed_active_variable {
            return Err(SolutionError::InvalidConstraintStructure {
                constraint_family: "one-hot",
                constraint_id: format!("{id:?}"),
                message: format!(
                    "active_variable={:?} does not match decision-variable values; computed={computed_active_variable:?}",
                    constraint.stage.active_variable,
                ),
            });
        }
        if constraint.stage.feasible != computed_feasible {
            return Err(SolutionError::InconsistentConstraintFeasibility {
                constraint_family: "one-hot",
                constraint_id: format!("{id:?}"),
                provided_feasible: constraint.stage.feasible,
                computed_feasible,
            });
        }
    }
    Ok(())
}

fn validate_solution_sos1_stage_values(
    decision_variables: &EvaluatedDecisionVariableTable,
    sos1_constraints: &EvaluatedCollection<crate::Sos1Constraint>,
    atol: ATol,
) -> Result<(), SolutionError> {
    for (id, constraint) in sos1_constraints.inner() {
        let (computed_feasible, computed_active_variable) =
            expected_sos1_active_variable(&constraint.variables, decision_variables, atol);
        if constraint.stage.active_variable != computed_active_variable {
            return Err(SolutionError::InvalidConstraintStructure {
                constraint_family: "SOS1",
                constraint_id: format!("{id:?}"),
                message: format!(
                    "active_variable={:?} does not match decision-variable values; computed={computed_active_variable:?}",
                    constraint.stage.active_variable,
                ),
            });
        }
        if constraint.stage.feasible != computed_feasible {
            return Err(SolutionError::InconsistentConstraintFeasibility {
                constraint_family: "SOS1",
                constraint_id: format!("{id:?}"),
                provided_feasible: constraint.stage.feasible,
                computed_feasible,
            });
        }
    }
    Ok(())
}

fn validate_solution_special_constraint_stage_values(
    decision_variables: &EvaluatedDecisionVariableTable,
    indicator_constraints: &EvaluatedCollection<IndicatorConstraint>,
    one_hot_constraints: &EvaluatedCollection<crate::OneHotConstraint>,
    sos1_constraints: &EvaluatedCollection<crate::Sos1Constraint>,
    atol: ATol,
) -> Result<(), SolutionError> {
    validate_solution_indicator_stage_values(decision_variables, indicator_constraints, atol)?;
    validate_solution_one_hot_stage_values(decision_variables, one_hot_constraints, atol)?;
    validate_solution_sos1_stage_values(decision_variables, sos1_constraints, atol)
}

impl SolutionBuilder {
    /// Creates a new `SolutionBuilder` with all fields unset.
    pub fn new() -> Self {
        Self {
            optimality: crate::v1::Optimality::Unspecified,
            relaxation: crate::v1::Relaxation::Unspecified,
            ..Default::default()
        }
    }

    /// Sets the objective value.
    pub fn objective(mut self, objective: f64) -> Self {
        self.objective = Some(objective);
        self
    }

    /// Sets the evaluated constraints.
    pub fn evaluated_constraints(
        mut self,
        evaluated_constraints: BTreeMap<ConstraintID, EvaluatedConstraint>,
    ) -> Self {
        self.evaluated_constraints = Some(
            EvaluatedCollection::new(evaluated_constraints, BTreeMap::new())
                .expect("empty removed reasons cannot reference unknown constraints"),
        );
        self
    }

    /// Sets the evaluated constraints from a collection.
    pub fn evaluated_constraints_collection(
        mut self,
        evaluated_constraints: EvaluatedCollection<Constraint>,
    ) -> Self {
        self.evaluated_constraints = Some(evaluated_constraints);
        self
    }

    /// Sets the evaluated indicator constraints from a collection.
    pub fn evaluated_indicator_constraints_collection(
        mut self,
        evaluated_indicator_constraints: EvaluatedCollection<IndicatorConstraint>,
    ) -> Self {
        self.evaluated_indicator_constraints = evaluated_indicator_constraints;
        self
    }

    /// Sets the evaluated indicator constraints.
    pub fn evaluated_indicator_constraints(
        mut self,
        evaluated_indicator_constraints: BTreeMap<
            crate::IndicatorConstraintID,
            crate::indicator_constraint::EvaluatedIndicatorConstraint,
        >,
    ) -> Self {
        self.evaluated_indicator_constraints =
            EvaluatedCollection::new(evaluated_indicator_constraints, BTreeMap::new())
                .expect("empty removed reasons cannot reference unknown constraints");
        self
    }

    /// Sets the evaluated one-hot constraints from a collection.
    pub fn evaluated_one_hot_constraints_collection(
        mut self,
        evaluated_one_hot_constraints: EvaluatedCollection<crate::OneHotConstraint>,
    ) -> Self {
        self.evaluated_one_hot_constraints = evaluated_one_hot_constraints;
        self
    }

    /// Sets the evaluated SOS1 constraints from a collection.
    pub fn evaluated_sos1_constraints_collection(
        mut self,
        evaluated_sos1_constraints: EvaluatedCollection<crate::Sos1Constraint>,
    ) -> Self {
        self.evaluated_sos1_constraints = evaluated_sos1_constraints;
        self
    }

    /// Sets the evaluated named functions.
    pub fn evaluated_named_functions(
        mut self,
        evaluated_named_functions: BTreeMap<NamedFunctionID, EvaluatedNamedFunction>,
    ) -> Self {
        self.evaluated_named_function_table = None;
        self.evaluated_named_functions = evaluated_named_functions;
        self
    }

    /// Sets the evaluated named-function table without splitting rows from labels.
    pub(crate) fn evaluated_named_function_table(
        mut self,
        evaluated_named_functions: NamedFunctionTable<EvaluatedNamedFunction>,
    ) -> Self {
        self.evaluated_named_function_table = Some(evaluated_named_functions);
        self
    }

    /// Sets the decision variables.
    pub fn decision_variables(
        mut self,
        decision_variables: BTreeMap<VariableID, EvaluatedDecisionVariable>,
    ) -> Self {
        self.decision_variables = Some(decision_variables);
        self
    }

    /// Sets the per-variable modeling-label store.
    pub fn variable_labels(mut self, variable_labels: VariableLabelStore) -> Self {
        self.variable_labels = variable_labels;
        self
    }

    /// Sets the per-named-function modeling-label store.
    pub fn named_function_labels(
        mut self,
        named_function_labels: crate::named_function::NamedFunctionLabelStore,
    ) -> Self {
        self.evaluated_named_function_table = None;
        self.named_function_labels = named_function_labels;
        self
    }

    /// Sets the optimization sense.
    pub fn sense(mut self, sense: Sense) -> Self {
        self.sense = Some(sense);
        self
    }

    /// Sets the absolute tolerance used to compute and validate feasibility fields.
    pub fn feasibility_atol(mut self, feasibility_atol: ATol) -> Self {
        self.feasibility_atol = feasibility_atol;
        self
    }

    /// Sets the optimality status.
    pub fn optimality(mut self, optimality: crate::v1::Optimality) -> Self {
        self.optimality = optimality;
        self
    }

    /// Sets the relaxation status.
    pub fn relaxation(mut self, relaxation: crate::v1::Relaxation) -> Self {
        self.relaxation = relaxation;
        self
    }

    /// Builds the `Solution` with full validation.
    ///
    /// # Errors
    /// Returns an error if:
    /// - Required fields (`objective`, `evaluated_constraints`, `decision_variables`, `sense`) are not set
    /// - Constraint collection sidecars contain invalid keys
    /// - Named-function labels reference IDs not present in the evaluated named-function table
    /// - Variables referenced in constraints' or named functions'
    ///   `used_decision_variable_ids` are not in `decision_variables`
    pub fn build(self) -> crate::Result<Solution> {
        let objective = self
            .objective
            .ok_or(SolutionError::MissingRequiredField { field: "objective" })?;
        let evaluated_constraints =
            self.evaluated_constraints
                .ok_or(SolutionError::MissingRequiredField {
                    field: "evaluated_constraints",
                })?;
        let decision_variables =
            self.decision_variables
                .ok_or(SolutionError::MissingRequiredField {
                    field: "decision_variables",
                })?;
        let sense = self
            .sense
            .ok_or(SolutionError::MissingRequiredField { field: "sense" })?;

        let decision_variables =
            EvaluatedDecisionVariableTable::new(decision_variables, self.variable_labels)?;
        let evaluated_named_functions = match self.evaluated_named_function_table {
            Some(evaluated_named_functions) => evaluated_named_functions,
            None => {
                NamedFunctionTable::new(self.evaluated_named_functions, self.named_function_labels)?
            }
        };
        evaluated_constraints.validate_context_ids()?;
        self.evaluated_indicator_constraints
            .validate_context_ids()?;
        self.evaluated_one_hot_constraints.validate_context_ids()?;
        self.evaluated_sos1_constraints.validate_context_ids()?;
        validate_solution_constraint_feasibility(
            &evaluated_constraints,
            &self.evaluated_indicator_constraints,
            &self.evaluated_one_hot_constraints,
            &self.evaluated_sos1_constraints,
            self.feasibility_atol,
        )?;
        validate_solution_special_constraint_structure(
            &decision_variables,
            &self.evaluated_indicator_constraints,
            &self.evaluated_one_hot_constraints,
            &self.evaluated_sos1_constraints,
        )?;
        validate_solution_special_constraint_stage_values(
            &decision_variables,
            &self.evaluated_indicator_constraints,
            &self.evaluated_one_hot_constraints,
            &self.evaluated_sos1_constraints,
            self.feasibility_atol,
        )?;

        // Validate all used_decision_variable_ids in indicator constraints
        for (ic_id, ic) in self.evaluated_indicator_constraints.iter() {
            for var_id in &ic.stage.used_decision_variable_ids {
                if !decision_variables.contains_key(var_id) {
                    crate::bail!(
                        { ?var_id, ?ic_id },
                        "Variable {var_id:?} used in indicator constraint {ic_id:?} is not defined in decision_variables",
                    );
                }
            }
        }

        // Validate all used_decision_variable_ids in one-hot constraints
        for (oh_id, oh) in self.evaluated_one_hot_constraints.iter() {
            for var_id in &oh.stage.used_decision_variable_ids {
                if !decision_variables.contains_key(var_id) {
                    crate::bail!(
                        { ?var_id, ?oh_id },
                        "Variable {var_id:?} used in one-hot constraint {oh_id:?} is not defined in decision_variables",
                    );
                }
            }
        }

        // Validate all used_decision_variable_ids in SOS1 constraints
        for (s1_id, s1) in self.evaluated_sos1_constraints.iter() {
            for var_id in &s1.stage.used_decision_variable_ids {
                if !decision_variables.contains_key(var_id) {
                    crate::bail!(
                        { ?var_id, ?s1_id },
                        "Variable {var_id:?} used in SOS1 constraint {s1_id:?} is not defined in decision_variables",
                    );
                }
            }
        }

        // Validate all used_decision_variable_ids are in decision_variables
        for (constraint_id, constraint) in evaluated_constraints.iter() {
            for var_id in &constraint.stage.used_decision_variable_ids {
                if !decision_variables.contains_key(var_id) {
                    return Err(SolutionError::UndefinedVariableInConstraint {
                        id: *var_id,
                        constraint_id: *constraint_id,
                    }
                    .into());
                }
            }
        }
        validate_evaluated_named_function_used_ids(
            &decision_variables,
            &evaluated_named_functions,
        )?;

        Ok(Solution {
            objective,
            evaluated_constraints,
            evaluated_indicator_constraints: self.evaluated_indicator_constraints,
            evaluated_one_hot_constraints: self.evaluated_one_hot_constraints,
            evaluated_sos1_constraints: self.evaluated_sos1_constraints,
            evaluated_named_functions,
            decision_variables,
            optimality: self.optimality,
            relaxation: self.relaxation,
            sense: Some(sense),
            feasibility_atol: self.feasibility_atol,
            metadata: Default::default(),
            annotations: Default::default(),
        })
    }

    /// Builds the `Solution` without host-level revalidation.
    ///
    /// # Safety
    /// This method still constructs table owners through their checked
    /// constructors, so table-level invariants such as label IDs referring to
    /// existing table rows are enforced. It does not revalidate host-level
    /// cross references. The caller must ensure:
    /// - `decision_variables` is keyed by the intended [`VariableID`] for each row
    /// - All `used_decision_variable_ids` in constraints and evaluated named
    ///   functions exist in `decision_variables`
    /// - Special-constraint `indicator_active`, `active_variable`, and
    ///   per-constraint `feasible` fields are consistent with
    ///   `decision_variables` under `feasibility_atol`
    ///
    /// Use [`Self::build`] for validated construction.
    /// This method is useful when invariants are guaranteed by construction,
    /// such as when creating a Solution from `Instance::evaluate`.
    ///
    /// # Errors
    /// Returns an error if required fields are not set or table-level sidecar
    /// invariants fail.
    pub unsafe fn build_unchecked(self) -> crate::Result<Solution> {
        let objective = self
            .objective
            .ok_or(SolutionError::MissingRequiredField { field: "objective" })?;
        let evaluated_constraints =
            self.evaluated_constraints
                .ok_or(SolutionError::MissingRequiredField {
                    field: "evaluated_constraints",
                })?;
        let decision_variables =
            self.decision_variables
                .ok_or(SolutionError::MissingRequiredField {
                    field: "decision_variables",
                })?;
        let decision_variables =
            EvaluatedDecisionVariableTable::new(decision_variables, self.variable_labels)?;
        let sense = self
            .sense
            .ok_or(SolutionError::MissingRequiredField { field: "sense" })?;
        let evaluated_named_functions = match self.evaluated_named_function_table {
            Some(evaluated_named_functions) => evaluated_named_functions,
            None => {
                NamedFunctionTable::new(self.evaluated_named_functions, self.named_function_labels)?
            }
        };

        Ok(Solution {
            objective,
            evaluated_constraints,
            evaluated_indicator_constraints: self.evaluated_indicator_constraints,
            evaluated_one_hot_constraints: self.evaluated_one_hot_constraints,
            evaluated_sos1_constraints: self.evaluated_sos1_constraints,
            evaluated_named_functions,
            decision_variables,
            optimality: self.optimality,
            relaxation: self.relaxation,
            sense: Some(sense),
            feasibility_atol: self.feasibility_atol,
            metadata: Default::default(),
            annotations: Default::default(),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Coefficient, Constraint, Evaluate, Function};

    #[test]
    fn test_total_violation_l1_all_satisfied() {
        // All constraints satisfied → total violation = 0
        let mut constraints = BTreeMap::new();

        // Equality constraint: f(x) = 0.0001 (near zero, but not exactly zero due to Coefficient restrictions)
        let c1 =
            Constraint::equal_to_zero(Function::Constant(Coefficient::try_from(0.0001).unwrap()));
        let state = crate::v1::State::default();
        constraints.insert(
            ConstraintID::from(1),
            c1.evaluate(&state, crate::ATol::default()).unwrap(),
        );

        // Inequality constraint: f(x) = -1.0 ≤ 0 (satisfied)
        let c2 = Constraint::less_than_or_equal_to_zero(Function::Constant(
            Coefficient::try_from(-1.0).unwrap(),
        ));
        constraints.insert(
            ConstraintID::from(2),
            c2.evaluate(&state, crate::ATol::default()).unwrap(),
        );

        // SAFETY: Test data is constructed to satisfy invariants
        let solution = unsafe {
            Solution::builder()
                .objective(0.0)
                .evaluated_constraints(constraints)
                .decision_variables(BTreeMap::new())
                .sense(Sense::Minimize)
                .build_unchecked()
                .unwrap()
        };

        // L1: |0.0001| + max(0, -1.0) = 0.0001 + 0 = 0.0001
        assert_eq!(solution.total_violation_l1(), 0.0001);
    }

    #[test]
    fn test_total_violation_l1_mixed() {
        // Mix of satisfied and violated constraints
        let mut constraints = BTreeMap::new();
        let state = crate::v1::State::default();

        // Equality constraint violated: f(x) = 2.5
        let c1 = Constraint::equal_to_zero(Function::Constant(Coefficient::try_from(2.5).unwrap()));
        constraints.insert(
            ConstraintID::from(1),
            c1.evaluate(&state, crate::ATol::default()).unwrap(),
        );

        // Inequality constraint violated: f(x) = 1.5 > 0
        let c2 = Constraint::less_than_or_equal_to_zero(Function::Constant(
            Coefficient::try_from(1.5).unwrap(),
        ));
        constraints.insert(
            ConstraintID::from(2),
            c2.evaluate(&state, crate::ATol::default()).unwrap(),
        );

        // Inequality constraint satisfied: f(x) = -0.5 ≤ 0
        let c3 = Constraint::less_than_or_equal_to_zero(Function::Constant(
            Coefficient::try_from(-0.5).unwrap(),
        ));
        constraints.insert(
            ConstraintID::from(3),
            c3.evaluate(&state, crate::ATol::default()).unwrap(),
        );

        // SAFETY: Test data is constructed to satisfy invariants
        let solution = unsafe {
            Solution::builder()
                .objective(0.0)
                .evaluated_constraints(constraints)
                .decision_variables(BTreeMap::new())
                .sense(Sense::Minimize)
                .build_unchecked()
                .unwrap()
        };

        // L1: |2.5| + max(0, 1.5) + max(0, -0.5) = 2.5 + 1.5 + 0 = 4.0
        assert_eq!(solution.total_violation_l1(), 4.0);
    }

    #[test]
    fn test_total_violation_l2_mixed() {
        // Same constraints as L1 test
        let mut constraints = BTreeMap::new();
        let state = crate::v1::State::default();

        // Equality constraint violated: f(x) = 2.5
        let c1 = Constraint::equal_to_zero(Function::Constant(Coefficient::try_from(2.5).unwrap()));
        constraints.insert(
            ConstraintID::from(1),
            c1.evaluate(&state, crate::ATol::default()).unwrap(),
        );

        // Inequality constraint violated: f(x) = 1.5 > 0
        let c2 = Constraint::less_than_or_equal_to_zero(Function::Constant(
            Coefficient::try_from(1.5).unwrap(),
        ));
        constraints.insert(
            ConstraintID::from(2),
            c2.evaluate(&state, crate::ATol::default()).unwrap(),
        );

        // Inequality constraint satisfied: f(x) = -0.5 ≤ 0
        let c3 = Constraint::less_than_or_equal_to_zero(Function::Constant(
            Coefficient::try_from(-0.5).unwrap(),
        ));
        constraints.insert(
            ConstraintID::from(3),
            c3.evaluate(&state, crate::ATol::default()).unwrap(),
        );

        // SAFETY: Test data is constructed to satisfy invariants
        let solution = unsafe {
            Solution::builder()
                .objective(0.0)
                .evaluated_constraints(constraints)
                .decision_variables(BTreeMap::new())
                .sense(Sense::Minimize)
                .build_unchecked()
                .unwrap()
        };

        // L2: (2.5)² + (1.5)² + 0² = 6.25 + 2.25 + 0 = 8.5
        assert_eq!(solution.total_violation_l2(), 8.5);
    }

    #[test]
    fn test_total_violation_empty() {
        // No constraints → total violation = 0
        // SAFETY: Test data is constructed to satisfy invariants
        let solution = unsafe {
            Solution::builder()
                .objective(0.0)
                .evaluated_constraints(BTreeMap::new())
                .decision_variables(BTreeMap::new())
                .sense(Sense::Minimize)
                .build_unchecked()
                .unwrap()
        };

        assert_eq!(solution.total_violation_l1(), 0.0);
        assert_eq!(solution.total_violation_l2(), 0.0);
    }

    #[test]
    fn test_total_violation_equality_negative() {
        // Test with negative value for equality constraint
        let mut constraints = BTreeMap::new();
        let state = crate::v1::State::default();

        // Equality constraint: f(x) = -3.0
        let c1 =
            Constraint::equal_to_zero(Function::Constant(Coefficient::try_from(-3.0).unwrap()));
        constraints.insert(
            ConstraintID::from(1),
            c1.evaluate(&state, crate::ATol::default()).unwrap(),
        );

        // SAFETY: Test data is constructed to satisfy invariants
        let solution = unsafe {
            Solution::builder()
                .objective(0.0)
                .evaluated_constraints(constraints)
                .decision_variables(BTreeMap::new())
                .sense(Sense::Minimize)
                .build_unchecked()
                .unwrap()
        };

        // L1: |-3.0| = 3.0
        assert_eq!(solution.total_violation_l1(), 3.0);
        // L2: (-3.0)² = 9.0
        assert_eq!(solution.total_violation_l2(), 9.0);
    }

    #[test]
    fn test_extract_parameterized_variable_success() {
        use crate::{
            decision_variable::{DecisionVariable, DecisionVariableLabel, Kind},
            EvaluatedDecisionVariable, Sense, VariableID,
        };

        // Create a parameterized decision variable (should succeed - parameters are ignored)
        let mut decision_variables = BTreeMap::new();

        let dv = DecisionVariable::new(
            Kind::Continuous,
            crate::Bound::new(f64::NEG_INFINITY, f64::INFINITY).unwrap(),
            crate::ATol::default(),
        )
        .unwrap();
        let mut variable_labels = VariableLabelStore::default();
        variable_labels.insert(
            VariableID::from(1),
            DecisionVariableLabel {
                name: Some("x".to_string()),
                subscripts: vec![0],
                parameters: {
                    let mut params = fnv::FnvHashMap::default();
                    params.insert("param1".to_string(), "value1".to_string());
                    params
                },
                ..Default::default()
            },
        );

        decision_variables.insert(
            VariableID::from(1),
            EvaluatedDecisionVariable::new(VariableID::from(1), dv, 1.0).unwrap(),
        );

        // SAFETY: Test data is constructed to satisfy invariants
        let solution = unsafe {
            Solution::builder()
                .objective(0.0)
                .evaluated_constraints(BTreeMap::new())
                .decision_variables(decision_variables)
                .variable_labels(variable_labels)
                .sense(Sense::Minimize)
                .build_unchecked()
                .unwrap()
        };

        // Test that extracting parameterized variable succeeds (parameters are ignored)
        let result = solution.extract_decision_variables("x");
        assert!(result.is_ok());
        let vars = result.unwrap();
        assert_eq!(vars.len(), 1);
        assert_eq!(vars[&vec![0]], 1.0);
    }

    #[test]
    fn test_extract_duplicate_subscripts_error() {
        use crate::{
            decision_variable::{DecisionVariable, DecisionVariableLabel, Kind},
            EvaluatedDecisionVariable, Sense, VariableID,
        };

        // Create two variables with same name and subscripts but different parameters
        let mut decision_variables = BTreeMap::new();
        let mut variable_labels = VariableLabelStore::default();

        // First variable
        let dv1 = DecisionVariable::new(
            Kind::Continuous,
            crate::Bound::new(f64::NEG_INFINITY, f64::INFINITY).unwrap(),
            crate::ATol::default(),
        )
        .unwrap();
        variable_labels.insert(
            VariableID::from(1),
            DecisionVariableLabel {
                name: Some("x".to_string()),
                subscripts: vec![0],
                parameters: {
                    let mut params = fnv::FnvHashMap::default();
                    params.insert("param".to_string(), "value1".to_string());
                    params
                },
                ..Default::default()
            },
        );

        decision_variables.insert(
            VariableID::from(1),
            EvaluatedDecisionVariable::new(VariableID::from(1), dv1, 1.0).unwrap(),
        );

        // Second variable with same name and subscripts
        let dv2 = DecisionVariable::new(
            Kind::Continuous,
            crate::Bound::new(f64::NEG_INFINITY, f64::INFINITY).unwrap(),
            crate::ATol::default(),
        )
        .unwrap();
        variable_labels.insert(
            VariableID::from(2),
            DecisionVariableLabel {
                name: Some("x".to_string()),
                subscripts: vec![0], // Same subscripts
                parameters: {
                    let mut params = fnv::FnvHashMap::default();
                    params.insert("param".to_string(), "value2".to_string());
                    params
                },
                ..Default::default()
            },
        );

        decision_variables.insert(
            VariableID::from(2),
            EvaluatedDecisionVariable::new(VariableID::from(2), dv2, 2.0).unwrap(),
        );

        // SAFETY: Test data is constructed to satisfy invariants
        let solution = unsafe {
            Solution::builder()
                .objective(0.0)
                .evaluated_constraints(BTreeMap::new())
                .decision_variables(decision_variables)
                .variable_labels(variable_labels)
                .sense(Sense::Minimize)
                .build_unchecked()
                .unwrap()
        };

        // Test that extracting variables with duplicate subscripts fails
        let result = solution.extract_decision_variables("x");
        assert!(matches!(
            result,
            Err(SolutionError::DuplicateSubscript { .. })
        ));
    }

    #[test]
    fn test_builder_missing_required_field() {
        // Missing objective
        let err = Solution::builder()
            .evaluated_constraints(BTreeMap::new())
            .decision_variables(BTreeMap::new())
            .sense(Sense::Minimize)
            .build()
            .unwrap_err();
        let solution_err = err.downcast_ref::<SolutionError>().unwrap();
        assert!(matches!(
            solution_err,
            SolutionError::MissingRequiredField { field: "objective" }
        ));

        // Missing sense
        let err = Solution::builder()
            .objective(0.0)
            .evaluated_constraints(BTreeMap::new())
            .decision_variables(BTreeMap::new())
            .build()
            .unwrap_err();
        let solution_err = err.downcast_ref::<SolutionError>().unwrap();
        assert!(matches!(
            solution_err,
            SolutionError::MissingRequiredField { field: "sense" }
        ));
    }

    #[test]
    fn builder_rejects_orphan_variable_label_id() {
        let mut variable_labels = VariableLabelStore::default();
        variable_labels.set_name(VariableID::from(99), "orphan");

        let err = Solution::builder()
            .objective(0.0)
            .evaluated_constraints(BTreeMap::new())
            .decision_variables(BTreeMap::new())
            .variable_labels(variable_labels)
            .sense(Sense::Minimize)
            .build()
            .unwrap_err();

        assert!(
            err.to_string().contains("unknown decision variable ID")
                && err.to_string().contains("VariableID(99)"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn builder_rejects_inconsistent_regular_constraint_feasibility() {
        let constraint = EvaluatedConstraint {
            equality: crate::Equality::EqualToZero,
            stage: crate::constraint::EvaluatedData {
                evaluated_value: 1.0,
                feasible: true,
                used_decision_variable_ids: BTreeSet::new(),
                dual_variable: None,
            },
        };

        let err = Solution::builder()
            .objective(0.0)
            .evaluated_constraints(BTreeMap::from([(ConstraintID::from(1), constraint)]))
            .decision_variables(BTreeMap::new())
            .sense(Sense::Minimize)
            .feasibility_atol(ATol::new(0.1).unwrap())
            .build()
            .unwrap_err();

        assert!(
            err.to_string()
                .contains("Inconsistent feasibility for regular constraint"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn builder_rejects_unknown_one_hot_structural_variable() {
        let variable_id = VariableID::from(1);
        let one_hot = crate::one_hot_constraint::EvaluatedOneHotConstraint {
            variables: BTreeSet::from([variable_id]),
            stage: crate::one_hot_constraint::OneHotEvaluatedData {
                feasible: false,
                active_variable: None,
                used_decision_variable_ids: BTreeSet::new(),
            },
        };

        let err = Solution::builder()
            .objective(0.0)
            .evaluated_constraints(BTreeMap::new())
            .evaluated_one_hot_constraints_collection(
                EvaluatedCollection::new(
                    BTreeMap::from([(crate::OneHotConstraintID::from(1), one_hot)]),
                    BTreeMap::new(),
                )
                .unwrap(),
            )
            .decision_variables(BTreeMap::new())
            .sense(Sense::Minimize)
            .build()
            .unwrap_err();

        assert!(
            err.to_string()
                .contains("Invalid structure for one-hot constraint"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn unchecked_builder_rejects_orphan_variable_label_id() {
        let mut variable_labels = VariableLabelStore::default();
        variable_labels.set_name(VariableID::from(99), "orphan");

        // SAFETY: This test intentionally exercises the unchecked host-level
        // constructor boundary. Table-level label ownership is still checked.
        let err = unsafe {
            Solution::builder()
                .objective(0.0)
                .evaluated_constraints(BTreeMap::new())
                .decision_variables(BTreeMap::new())
                .variable_labels(variable_labels)
                .sense(Sense::Minimize)
                .build_unchecked()
                .unwrap_err()
        };

        assert!(
            err.to_string().contains("unknown decision variable ID")
                && err.to_string().contains("VariableID(99)"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn builder_rejects_orphan_named_function_label_id() {
        let mut named_function_labels = crate::named_function::NamedFunctionLabelStore::default();
        named_function_labels.set_name(NamedFunctionID::from(99), "orphan");

        let err = Solution::builder()
            .objective(0.0)
            .evaluated_constraints(BTreeMap::new())
            .decision_variables(BTreeMap::new())
            .named_function_labels(named_function_labels)
            .sense(Sense::Minimize)
            .build()
            .unwrap_err();

        assert!(
            err.to_string().contains("unknown named function ID")
                && err.to_string().contains("NamedFunctionID(99)"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn unchecked_builder_rejects_orphan_named_function_label_id() {
        let mut named_function_labels = crate::named_function::NamedFunctionLabelStore::default();
        named_function_labels.set_name(NamedFunctionID::from(99), "orphan");

        // SAFETY: This test intentionally exercises the unchecked host-level
        // constructor boundary. Table-level label ownership is still checked.
        let err = unsafe {
            Solution::builder()
                .objective(0.0)
                .evaluated_constraints(BTreeMap::new())
                .decision_variables(BTreeMap::new())
                .named_function_labels(named_function_labels)
                .sense(Sense::Minimize)
                .build_unchecked()
                .unwrap_err()
        };

        assert!(
            err.to_string().contains("unknown named function ID")
                && err.to_string().contains("NamedFunctionID(99)"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn builder_rejects_undefined_variable_in_evaluated_named_function() {
        use crate::parse::Parse as _;

        let var_id = VariableID::from(1);
        let nf_id = NamedFunctionID::from(7);
        let parsed: crate::named_function::parse::ParsedEvaluatedNamedFunction =
            crate::v1::EvaluatedNamedFunction {
                id: nf_id.into_inner(),
                evaluated_value: 1.0,
                used_decision_variable_ids: vec![var_id.into_inner()],
                ..Default::default()
            }
            .parse(&())
            .unwrap();

        let err = Solution::builder()
            .objective(0.0)
            .evaluated_constraints(BTreeMap::new())
            .evaluated_named_functions(BTreeMap::from([(nf_id, parsed.evaluated_named_function)]))
            .decision_variables(BTreeMap::new())
            .sense(Sense::Minimize)
            .build()
            .unwrap_err();
        let solution_err = err.downcast_ref::<SolutionError>().unwrap();
        assert!(matches!(
            solution_err,
            SolutionError::UndefinedVariableInNamedFunction { id, named_function_id }
                if *id == var_id && *named_function_id == nf_id
        ));
    }

    #[test]
    fn test_builder_undefined_variable_in_constraint() {
        use crate::linear;

        let state = crate::v1::State::from(std::collections::HashMap::from([(1, 1.0)]));
        let constraint_id = ConstraintID::from(1);
        let var_id = VariableID::from(1);

        // Constraint uses variable ID 1
        let c = Constraint::equal_to_zero(Function::from(linear!(1)));
        let evaluated_c = c.evaluate(&state, crate::ATol::default()).unwrap();

        let mut evaluated_constraints = BTreeMap::new();
        evaluated_constraints.insert(constraint_id, evaluated_c);

        // decision_variables is empty, so variable ID 1 is undefined
        let err = Solution::builder()
            .objective(0.0)
            .evaluated_constraints(evaluated_constraints)
            .decision_variables(BTreeMap::new())
            .sense(Sense::Minimize)
            .build()
            .unwrap_err();
        let solution_err = err.downcast_ref::<SolutionError>().unwrap();
        assert!(matches!(
            solution_err,
            SolutionError::UndefinedVariableInConstraint { id, constraint_id: cid }
                if *id == var_id && *cid == constraint_id
        ));
    }

    #[test]
    fn test_builder_success() {
        use crate::DecisionVariable;

        let var_id = VariableID::from(1);
        let dv = DecisionVariable::binary();
        let evaluated_dv = EvaluatedDecisionVariable::new(var_id, dv, 1.0).unwrap();

        let mut decision_variables = BTreeMap::new();
        decision_variables.insert(var_id, evaluated_dv);

        let solution = Solution::builder()
            .objective(42.0)
            .evaluated_constraints(BTreeMap::new())
            .decision_variables(decision_variables)
            .sense(Sense::Maximize)
            .build()
            .unwrap();

        assert_eq!(*solution.objective(), 42.0);
        assert_eq!(*solution.sense(), Some(Sense::Maximize));
    }
}