icydb-cli 0.220.0

Developer CLI tools for IcyDB
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
//! Module: diagnostic rendering.
//! Responsibility: render compact IcyDB diagnostic payloads for host/CLI users.
//! Does not own: canister wire shape, core error classification, or recovery policy.
//! Boundary: keeps rich diagnostic prose out of production canister crates.

pub(crate) mod artifact;

use icydb::diagnostic::{
    DiagnosticCode, DiagnosticComponentKind, DiagnosticConstraintContext, DiagnosticConstraintKind,
    DiagnosticDetail, DiagnosticFactTag, DiagnosticMutationOperation, ErrorClass, ErrorCode,
    ErrorOrigin, QueryErrorKind, QueryProjectionCode, QueryReadAdmissionCode, QueryResultShapeCode,
    RuntimeBoundaryCode, RuntimeErrorKind, SchemaDdlAdmissionCode, SchemaMigrationCode,
    SqlFeatureCode, SqlLoweringCode, SqlSurfaceMismatchCode, SqlWriteBoundaryCode,
};
use std::fmt::Write as _;

use crate::{
    cli::DiagnosticArgs,
    diagnostic::artifact::{DiagnosticSchemaArtifact, ResolvedDiagnosticEntity},
    observability::load_schema_report,
};

#[derive(Clone, Copy)]
struct RawDiagnosticFact {
    tag: u8,
    value: u64,
}

#[derive(Clone, Copy)]
struct DiagnosticSchemaIdentity {
    fingerprint_method: u8,
    fingerprint: [u8; 16],
    entity_tag: u64,
    constraint_id: Option<u32>,
}

/// Resolve and print one compact diagnostic entirely from host-side authority.
pub(crate) fn run_diagnostic_command(args: DiagnosticArgs) -> Result<(), String> {
    if args.facts().is_empty()
        && args.artifact().is_none()
        && args.source_metadata().is_none()
        && args.canister_name().is_none()
    {
        println!("{}", render_error_code_report(args.code())?);
        return Ok(());
    }

    let facts = parse_facts(args.facts())?;
    let explicit_artifact = args
        .artifact()
        .map(DiagnosticSchemaArtifact::read_deployment)
        .transpose()?;
    let source_metadata = args
        .source_metadata()
        .map(DiagnosticSchemaArtifact::read_source_metadata)
        .transpose()?;

    let mut notes = Vec::new();
    let explicit_artifact = explicit_artifact.as_ref().filter(|artifact| {
        let Some(canister) = args.canister_name() else {
            return true;
        };
        let matches = artifact.provenance_matches(args.environment(), canister);
        if !matches {
            notes.push(
                "artifact provenance does not match the selected deployment; names withheld"
                    .to_string(),
            );
        }
        matches
    });
    let fact_schema_is_valid =
        diagnostic_fact_schema_mismatch(args.code(), facts.as_slice())?.is_none();
    let identity = fact_schema_is_valid
        .then(|| DiagnosticSchemaIdentity::from_facts(facts.as_slice()))
        .flatten();
    let exact_artifact_found = identity.is_some_and(|identity| {
        explicit_artifact.is_some_and(|artifact| {
            artifact
                .resolve(
                    identity.fingerprint_method,
                    identity.fingerprint,
                    identity.entity_tag,
                    identity.constraint_id,
                )
                .is_some()
        })
    });
    let live_artifact = if !fact_schema_is_valid || exact_artifact_found {
        None
    } else if let Some(canister) = args.canister_name() {
        match load_schema_report(args.environment(), canister) {
            Ok(report) => Some(DiagnosticSchemaArtifact::from_report(
                args.environment(),
                canister,
                report.as_slice(),
            )?),
            Err(err) => {
                notes.push(format!(
                    "live schema introspection unavailable ({err}); continuing with offline resolvers"
                ));
                None
            }
        }
    } else {
        None
    };
    let source_metadata = source_metadata.as_ref().filter(|metadata| {
        let exact = identity.is_some_and(|identity| {
            metadata
                .resolve(
                    identity.fingerprint_method,
                    identity.fingerprint,
                    identity.entity_tag,
                    identity.constraint_id,
                )
                .is_some()
        });
        if identity.is_some() && !exact {
            notes.push(
                "source metadata does not prove the exact accepted fingerprint and entity identity; names withheld"
                    .to_string(),
            );
        }
        exact
    });
    let artifacts = [explicit_artifact, live_artifact.as_ref(), source_metadata]
        .into_iter()
        .flatten()
        .collect::<Vec<_>>();

    let report = render_error_code_report_with_facts(
        args.code(),
        facts.as_slice(),
        artifacts.as_slice(),
        &mut notes,
    )?;
    println!("{report}");
    Ok(())
}

/// Render one compact public IcyDB error code for CLI lookup.
pub(crate) fn render_error_code_report(input: &str) -> Result<String, String> {
    let mut notes = Vec::new();
    render_error_code_report_with_facts(input, &[], &[], &mut notes)
}

fn render_error_code_report_with_facts(
    input: &str,
    facts: &[RawDiagnosticFact],
    artifacts: &[&DiagnosticSchemaArtifact],
    notes: &mut Vec<String>,
) -> Result<String, String> {
    let raw = parse_error_code(input)?;
    let code = ErrorCode::from_raw(raw);
    let diagnostic_code = code.diagnostic_code();
    let default_origin = diagnostic_code.origin();
    let facade_error = icydb::Error::from_error_code(code, default_origin.into());

    let mut lines = Vec::with_capacity(7);
    lines.push(format!("IcyDB diagnostic E{}", code.raw()));
    lines.push(format!("raw code: {}", code.raw()));
    lines.push(format!(
        "known: {}",
        if code.is_known() { "yes" } else { "no" }
    ));
    lines.push(format!("class: {}", class_text(code.class())));
    lines.push(format!("default origin: {}", origin_text(default_origin)));

    if code.is_known() {
        lines.push(format!("reason: {}", render_error(&facade_error)));
    } else {
        lines.push("reason: unknown compact error code".to_string());
        lines.push(format!(
            "registry fallback: {}",
            render_error(&facade_error)
        ));
    }

    if !facts.is_empty() {
        let schema_mismatch = diagnostic_fact_schema_mismatch(input, facts)?;
        let identity = schema_mismatch
            .is_none()
            .then(|| DiagnosticSchemaIdentity::from_facts(facts))
            .flatten();
        let resolved = identity.and_then(|identity| {
            artifacts.iter().find_map(|artifact| {
                artifact.resolve(
                    identity.fingerprint_method,
                    identity.fingerprint,
                    identity.entity_tag,
                    identity.constraint_id,
                )
            })
        });
        lines.push(format!(
            "facts: {}",
            render_raw_facts(facts, resolved.as_ref())
        ));
        if let Some(mismatch) = schema_mismatch {
            notes.push(format!(
                "fact context mismatch: {}",
                fact_schema_mismatch_text(mismatch)
            ));
        }
        if let Some(identity) = identity {
            lines.push(format!(
                "accepted schema identity: method={} fingerprint={} entity_tag={}",
                identity.fingerprint_method,
                render_fingerprint(identity.fingerprint),
                identity.entity_tag
            ));
        }
        match (artifacts.is_empty(), identity, resolved.as_ref()) {
            (_, None, _) => notes.push(
                "numeric fallback: exact fingerprint method, fingerprint, and entity tag facts are required"
                    .to_string(),
            ),
            (true, Some(_), _) => notes.push(
                "numeric fallback: supply --artifact, --canister, or --source-metadata for exact schema labels"
                    .to_string(),
            ),
            (false, Some(_), None) => notes.push(
                "numeric fallback: schema artifact has no exact fingerprint/entity match; names withheld"
                    .to_string(),
            ),
            (false, Some(_), Some(resolved)) => lines.push(format!(
                "accepted entity: {} ({})",
                resolved.entity_name(),
                resolved.entity_path()
            )),
        }
    }
    lines.extend(notes.iter().map(|note| format!("note: {note}")));

    Ok(lines.join("\n"))
}

fn diagnostic_fact_schema_mismatch(
    input: &str,
    facts: &[RawDiagnosticFact],
) -> Result<Option<icydb::diagnostic::DiagnosticFactSchemaMismatch>, String> {
    let code = ErrorCode::from_raw(parse_error_code(input)?);
    let raw = facts
        .iter()
        .map(|fact| (fact.tag, fact.value))
        .collect::<Vec<_>>();
    Ok(icydb::diagnostic::validate_raw_diagnostic_fact_schema(code, raw.as_slice()).err())
}

const fn fact_schema_mismatch_text(
    mismatch: icydb::diagnostic::DiagnosticFactSchemaMismatch,
) -> &'static str {
    use icydb::diagnostic::DiagnosticFactSchemaMismatch;
    match mismatch {
        DiagnosticFactSchemaMismatch::GlobalMaximumExceeded => {
            "fact count exceeds the global maximum"
        }
        DiagnosticFactSchemaMismatch::CodeMaximumExceeded => {
            "fact count exceeds the E-code maximum"
        }
        DiagnosticFactSchemaMismatch::InvalidSequence => {
            "required, allowed, repeated, or ordered tags do not match the E-code"
        }
        DiagnosticFactSchemaMismatch::InvalidValue => {
            "a known tag carries an invalid compact value"
        }
    }
}

fn render_fingerprint(fingerprint: [u8; 16]) -> String {
    let mut rendered = String::with_capacity(32);
    for byte in fingerprint {
        let _ = write!(rendered, "{byte:02x}");
    }
    rendered
}

impl DiagnosticSchemaIdentity {
    fn from_facts(facts: &[RawDiagnosticFact]) -> Option<Self> {
        let fingerprint_method = u8::try_from(single_fact(
            facts,
            DiagnosticFactTag::AcceptedSchemaFingerprintMethod,
        )?)
        .ok()?;
        let high = single_fact(facts, DiagnosticFactTag::AcceptedSchemaFingerprintHigh)?;
        let low = single_fact(facts, DiagnosticFactTag::AcceptedSchemaFingerprintLow)?;
        let entity_tag = single_fact(facts, DiagnosticFactTag::EntityTag)?;
        let mut fingerprint = [0_u8; 16];
        fingerprint[..8].copy_from_slice(high.to_be_bytes().as_slice());
        fingerprint[8..].copy_from_slice(low.to_be_bytes().as_slice());
        let constraint_id = optional_single_fact(facts, DiagnosticFactTag::ConstraintId)
            .and_then(|value| u32::try_from(value).ok());
        Some(Self {
            fingerprint_method,
            fingerprint,
            entity_tag,
            constraint_id,
        })
    }
}

fn parse_facts(inputs: &[String]) -> Result<Vec<RawDiagnosticFact>, String> {
    if inputs.len() > icydb::diagnostic::MAX_PUBLIC_DIAGNOSTIC_FACTS {
        return Err(format!(
            "diagnostic input has {} facts; maximum is {}",
            inputs.len(),
            icydb::diagnostic::MAX_PUBLIC_DIAGNOSTIC_FACTS
        ));
    }
    inputs.iter().map(|input| parse_fact(input)).collect()
}

fn parse_fact(input: &str) -> Result<RawDiagnosticFact, String> {
    let (tag, value) = input
        .split_once('=')
        .ok_or_else(|| format!("invalid diagnostic fact `{input}`; expected TAG=VALUE"))?;
    let tag = parse_fact_tag(tag)?;
    let value = value.parse::<u64>().map_err(|_| {
        format!("invalid diagnostic fact `{input}`; VALUE must be an unsigned integer")
    })?;
    Ok(RawDiagnosticFact { tag, value })
}

fn parse_fact_tag(input: &str) -> Result<u8, String> {
    if let Ok(raw) = input.parse::<u8>() {
        return Ok(raw);
    }
    for raw in u8::MIN..=u8::MAX {
        let Some(tag) = DiagnosticFactTag::known(raw) else {
            continue;
        };
        if fact_tag_text(tag) == input {
            return Ok(raw);
        }
    }
    Err(format!(
        "unknown diagnostic fact tag `{input}`; use a numeric tag or maintained label"
    ))
}

fn single_fact(facts: &[RawDiagnosticFact], tag: DiagnosticFactTag) -> Option<u64> {
    let mut matching = facts.iter().filter(|fact| fact.tag == tag.raw());
    let value = matching.next()?.value;
    matching.next().is_none().then_some(value)
}

fn optional_single_fact(facts: &[RawDiagnosticFact], tag: DiagnosticFactTag) -> Option<u64> {
    single_fact(facts, tag)
}

fn render_raw_facts(
    facts: &[RawDiagnosticFact],
    resolved: Option<&ResolvedDiagnosticEntity<'_>>,
) -> String {
    let mut rendered = String::new();
    for (index, fact) in facts.iter().enumerate() {
        if index != 0 {
            rendered.push(' ');
        }
        let Some(tag) = DiagnosticFactTag::known(fact.tag) else {
            let _ = write!(rendered, "tag#{}={}", fact.tag, fact.value);
            continue;
        };
        let _ = write!(
            rendered,
            "{}={}",
            fact_tag_text(tag),
            render_fact_value(tag, fact.value, resolved)
        );
    }
    rendered
}

fn render_fact_value(
    tag: DiagnosticFactTag,
    value: u64,
    resolved: Option<&ResolvedDiagnosticEntity<'_>>,
) -> String {
    let label = match tag {
        DiagnosticFactTag::EntityTag => resolved.map(ResolvedDiagnosticEntity::entity_name),
        DiagnosticFactTag::ConstraintId => {
            resolved.and_then(ResolvedDiagnosticEntity::constraint_name)
        }
        DiagnosticFactTag::FieldId | DiagnosticFactTag::RootField => u32::try_from(value)
            .ok()
            .and_then(|id| resolved.and_then(|resolved| resolved.field_name(id))),
        DiagnosticFactTag::IndexId => u32::try_from(value)
            .ok()
            .and_then(|id| resolved.and_then(|resolved| resolved.index_name(id))),
        DiagnosticFactTag::RelationId => u32::try_from(value)
            .ok()
            .and_then(|id| resolved.and_then(|resolved| resolved.relation_name(id))),
        DiagnosticFactTag::ConstraintKind => constraint_kind_text(value)
            .or_else(|| resolved.and_then(ResolvedDiagnosticEntity::constraint_kind)),
        DiagnosticFactTag::ConstraintContext => constraint_context_text(value),
        DiagnosticFactTag::MutationOperation => mutation_operation_text(value),
        DiagnosticFactTag::ComponentKind => component_kind_text(value),
        _ => None,
    };
    label.map_or_else(|| value.to_string(), |label| format!("{value}({label})"))
}

const fn component_kind_text(value: u64) -> Option<&'static str> {
    match DiagnosticComponentKind::known(value) {
        Some(DiagnosticComponentKind::CommitDataKey) => Some("commit-data-key"),
        Some(DiagnosticComponentKind::IndexKey) => Some("index-key"),
        Some(DiagnosticComponentKind::IndexKeyComponent) => Some("index-key-component"),
        Some(DiagnosticComponentKind::RelationTargetPrimaryKey) => {
            Some("relation-target-primary-key")
        }
        None => None,
    }
}

const fn constraint_kind_text(value: u64) -> Option<&'static str> {
    match DiagnosticConstraintKind::known(value) {
        Some(DiagnosticConstraintKind::Check) => Some("check"),
        Some(DiagnosticConstraintKind::NotNull) => Some("not-null"),
        Some(DiagnosticConstraintKind::Relation) => Some("relation"),
        Some(DiagnosticConstraintKind::TargetedRule) => Some("targeted-rule"),
        Some(DiagnosticConstraintKind::Unique) => Some("unique"),
        None => None,
    }
}

const fn constraint_context_text(value: u64) -> Option<&'static str> {
    match DiagnosticConstraintContext::known(value) {
        Some(DiagnosticConstraintContext::Integrity) => Some("integrity"),
        Some(DiagnosticConstraintContext::MigrationValidation) => Some("migration-validation"),
        Some(DiagnosticConstraintContext::WriteAdmission) => Some("write-admission"),
        None => None,
    }
}

const fn mutation_operation_text(value: u64) -> Option<&'static str> {
    match DiagnosticMutationOperation::known(value) {
        Some(DiagnosticMutationOperation::Insert) => Some("insert"),
        Some(DiagnosticMutationOperation::Replace) => Some("replace"),
        Some(DiagnosticMutationOperation::Update) => Some("update"),
        Some(DiagnosticMutationOperation::Delete) => Some("delete"),
        None => None,
    }
}

fn parse_error_code(input: &str) -> Result<u16, String> {
    let trimmed = input.trim().trim_matches(['"', '\'']);
    let digits = match trimmed
        .strip_prefix('E')
        .or_else(|| trimmed.strip_prefix('e'))
    {
        Some(rest) => rest,
        None => trimmed,
    };

    if digits.is_empty() || !digits.chars().all(|ch| ch.is_ascii_digit()) {
        return Err(format!(
            "invalid IcyDB diagnostic code `{input}`; expected E7, 7, E190, or 190"
        ));
    }

    digits
        .parse::<u16>()
        .map_err(|_| format!("invalid IcyDB diagnostic code `{input}`; code does not fit u16"))
}

/// Render one compact public IcyDB error for CLI output.
pub(crate) fn render_error(err: &icydb::Error) -> String {
    let diagnostic = err.diagnostic();
    let code = diagnostic.code();
    let detail = diagnostic
        .detail()
        .copied()
        .map_or_else(|| code_text(code).to_string(), diagnostic_detail_text);
    let summary = format!("{}: {detail}", code_label(code));
    if err.facts().is_empty() {
        return summary;
    }

    let raw_facts = err
        .facts()
        .iter()
        .map(|fact| RawDiagnosticFact {
            tag: fact.tag(),
            value: fact.value(),
        })
        .collect::<Vec<_>>();
    let rendered = render_raw_facts(raw_facts.as_slice(), None);
    let raw_pairs = raw_facts
        .iter()
        .map(|fact| (fact.tag, fact.value))
        .collect::<Vec<_>>();
    if let Err(mismatch) =
        icydb::diagnostic::validate_raw_diagnostic_fact_schema(err.code(), raw_pairs.as_slice())
    {
        return format!(
            "{summary}; facts {rendered}; fact context mismatch: {}",
            fact_schema_mismatch_text(mismatch)
        );
    }

    format!("{summary}; facts {rendered}")
}

const fn fact_tag_text(tag: icydb::diagnostic::DiagnosticFactTag) -> &'static str {
    use icydb::diagnostic::DiagnosticFactTag;

    match tag {
        DiagnosticFactTag::AcceptedSchemaFingerprintMethod => "accepted_schema_fingerprint_method",
        DiagnosticFactTag::AcceptedSchemaFingerprintHigh => "accepted_schema_fingerprint_high",
        DiagnosticFactTag::AcceptedSchemaFingerprintLow => "accepted_schema_fingerprint_low",
        DiagnosticFactTag::ExpectedFingerprintPrefix => "expected_fingerprint_prefix",
        DiagnosticFactTag::ActualFingerprintPrefix => "actual_fingerprint_prefix",
        DiagnosticFactTag::EntityTag => "entity_tag",
        DiagnosticFactTag::ExpectedEntityTag => "expected_entity_tag",
        DiagnosticFactTag::ActualEntityTag => "actual_entity_tag",
        DiagnosticFactTag::ConstraintId => "constraint_id",
        DiagnosticFactTag::FieldId => "field_id",
        DiagnosticFactTag::IndexId => "index_id",
        DiagnosticFactTag::RelationId => "relation_id",
        DiagnosticFactTag::MutationOperation => "mutation_operation",
        DiagnosticFactTag::RowOperation => "row_operation",
        DiagnosticFactTag::BatchPosition => "batch_position",
        DiagnosticFactTag::FirstBatchPosition => "first_batch_position",
        DiagnosticFactTag::DuplicateBatchPosition => "duplicate_batch_position",
        DiagnosticFactTag::ClauseIndex => "clause_index",
        DiagnosticFactTag::TermIndex => "term_index",
        DiagnosticFactTag::FirstTermIndex => "first_term_index",
        DiagnosticFactTag::DuplicateTermIndex => "duplicate_term_index",
        DiagnosticFactTag::ProjectionIndex => "projection_index",
        DiagnosticFactTag::GroupIndex => "group_index",
        DiagnosticFactTag::AggregateIndex => "aggregate_index",
        DiagnosticFactTag::ArgumentIndex => "argument_index",
        DiagnosticFactTag::BranchIndex => "branch_index",
        DiagnosticFactTag::ComponentIndex => "component_index",
        DiagnosticFactTag::ParameterIndex => "parameter_index",
        DiagnosticFactTag::SourceSpanStart => "source_span_start",
        DiagnosticFactTag::SourceSpanEnd => "source_span_end",
        DiagnosticFactTag::Expected => "expected",
        DiagnosticFactTag::Actual => "actual",
        DiagnosticFactTag::Minimum => "minimum",
        DiagnosticFactTag::Maximum => "maximum",
        DiagnosticFactTag::Limit => "limit",
        DiagnosticFactTag::ExpectedCount => "expected_count",
        DiagnosticFactTag::ActualCount => "actual_count",
        DiagnosticFactTag::ExpectedRevision => "expected_revision",
        DiagnosticFactTag::ActualRevision => "actual_revision",
        DiagnosticFactTag::CurrentRevision => "current_revision",
        DiagnosticFactTag::RequestedRevision => "requested_revision",
        DiagnosticFactTag::ExpectedVersion => "expected_version",
        DiagnosticFactTag::ActualVersion => "actual_version",
        DiagnosticFactTag::CurrentVersion => "current_version",
        DiagnosticFactTag::RequestedVersion => "requested_version",
        DiagnosticFactTag::ExpectedOffset => "expected_offset",
        DiagnosticFactTag::ActualOffset => "actual_offset",
        DiagnosticFactTag::ExpectedArity => "expected_arity",
        DiagnosticFactTag::ActualArity => "actual_arity",
        DiagnosticFactTag::ExpectedLength => "expected_length",
        DiagnosticFactTag::ActualLength => "actual_length",
        DiagnosticFactTag::ExpectedSlotCount => "expected_slot_count",
        DiagnosticFactTag::ActualSlotCount => "actual_slot_count",
        DiagnosticFactTag::RowLayout => "row_layout",
        DiagnosticFactTag::HistoryFloor => "history_floor",
        DiagnosticFactTag::CurrentLayout => "current_layout",
        DiagnosticFactTag::PhysicalSlot => "physical_slot",
        DiagnosticFactTag::PhysicalGeneration => "physical_generation",
        DiagnosticFactTag::ExpectedMemoryId => "expected_memory_id",
        DiagnosticFactTag::ActualMemoryId => "actual_memory_id",
        DiagnosticFactTag::ConstraintKind => "constraint_kind",
        DiagnosticFactTag::ConstraintContext => "constraint_context",
        DiagnosticFactTag::FieldKind => "field_kind",
        DiagnosticFactTag::ValueKind => "value_kind",
        DiagnosticFactTag::TypeFamily => "type_family",
        DiagnosticFactTag::FunctionKind => "function_kind",
        DiagnosticFactTag::OperatorKind => "operator_kind",
        DiagnosticFactTag::AggregateKind => "aggregate_kind",
        DiagnosticFactTag::KeyNamespaceKind => "key_namespace_kind",
        DiagnosticFactTag::ComponentKind => "component_kind",
        DiagnosticFactTag::MismatchKind => "mismatch_kind",
        DiagnosticFactTag::DecodeReason => "decode_reason",
        DiagnosticFactTag::BudgetResource => "budget_resource",
        DiagnosticFactTag::MigrationPhase => "migration_phase",
        DiagnosticFactTag::DatabaseControlRecordKind => "database_control_record_kind",
        DiagnosticFactTag::StateKind => "state_kind",
        DiagnosticFactTag::PayloadComponent => "payload_component",
        DiagnosticFactTag::ExpectedSignaturePrefix => "expected_signature_prefix",
        DiagnosticFactTag::ActualSignaturePrefix => "actual_signature_prefix",
        DiagnosticFactTag::FindingPosition => "finding_position",
        DiagnosticFactTag::RootField => "root_field",
        DiagnosticFactTag::RecordMember => "record_member",
        DiagnosticFactTag::TupleElement => "tuple_element",
        DiagnosticFactTag::Newtype => "newtype",
        DiagnosticFactTag::EnumVariant => "enum_variant",
        DiagnosticFactTag::ListElement => "list_element",
        DiagnosticFactTag::SetElement => "set_element",
        DiagnosticFactTag::MapEntryKey => "map_entry_key",
        DiagnosticFactTag::MapEntryValue => "map_entry_value",
    }
}

const fn class_text(class: ErrorClass) -> &'static str {
    match class {
        ErrorClass::Conflict => "conflict",
        ErrorClass::Corruption => "corruption",
        ErrorClass::IncompatiblePersistedFormat => "incompatible-persisted-format",
        ErrorClass::Internal => "internal",
        ErrorClass::InvariantViolation => "invariant-violation",
        ErrorClass::NotFound => "not-found",
        ErrorClass::Query => "query",
        ErrorClass::Unsupported => "unsupported",
    }
}

const fn origin_text(origin: ErrorOrigin) -> &'static str {
    match origin {
        ErrorOrigin::Cursor => "cursor",
        ErrorOrigin::Executor => "executor",
        ErrorOrigin::Identity => "identity",
        ErrorOrigin::Index => "index",
        ErrorOrigin::Interface => "interface",
        ErrorOrigin::Planner => "planner",
        ErrorOrigin::Query => "query",
        ErrorOrigin::Recovery => "recovery",
        ErrorOrigin::Response => "response",
        ErrorOrigin::Runtime => "runtime",
        ErrorOrigin::Serialize => "serialize",
        ErrorOrigin::Store => "store",
    }
}

fn diagnostic_detail_text(detail: DiagnosticDetail) -> String {
    match detail {
        DiagnosticDetail::QueryKind { kind } => query_kind_text(kind).to_string(),
        DiagnosticDetail::RuntimeKind { kind } => runtime_kind_text(kind).to_string(),
        DiagnosticDetail::RuntimeBoundary { boundary } => {
            runtime_boundary_text(boundary).to_string()
        }
        DiagnosticDetail::SchemaDdlAdmission { reason } => {
            format!("SQL DDL admission rejected: {}", schema_ddl_text(reason))
        }
        DiagnosticDetail::SchemaMigration { reason } => {
            format!(
                "schema migration rejected: {}",
                schema_migration_text(reason)
            )
        }
        DiagnosticDetail::UnsupportedSqlFeature { feature } => {
            format!("unsupported SQL feature: {}", sql_feature_text(feature))
        }
        DiagnosticDetail::SqlSurfaceMismatch { mismatch } => {
            sql_surface_mismatch_text(mismatch).to_string()
        }
        DiagnosticDetail::SqlWriteBoundary { boundary } => {
            format!("SQL write rejected: {}", sql_write_boundary_text(boundary))
        }
        DiagnosticDetail::QueryProjection { reason } => {
            format!(
                "query projection rejected: {}",
                query_projection_text(reason)
            )
        }
        DiagnosticDetail::QueryReadAdmission { reason } => {
            format!(
                "query read admission rejected: {}",
                query_read_admission_text(reason)
            )
        }
        DiagnosticDetail::QueryResultShape { reason } => {
            query_result_shape_text(reason).to_string()
        }
        DiagnosticDetail::SqlLowering { reason } => {
            format!("unsupported SQL lowering: {}", sql_lowering_text(reason))
        }
    }
}

const fn code_label(code: DiagnosticCode) -> &'static str {
    match code {
        DiagnosticCode::QueryValidate => "E_QUERY_VALIDATE",
        DiagnosticCode::QueryIntent => "E_QUERY_INTENT",
        DiagnosticCode::QueryPlan => "E_QUERY_PLAN",
        DiagnosticCode::QueryReadAdmission => "E_QUERY_READ_ADMISSION",
        DiagnosticCode::QueryAccessRequirement => "E_QUERY_ACCESS_REQUIREMENT",
        DiagnosticCode::QueryUnorderedPagination => "E_QUERY_UNORDERED_PAGINATION",
        DiagnosticCode::QueryInvalidContinuationCursor => "E_QUERY_INVALID_CONTINUATION_CURSOR",
        DiagnosticCode::QueryNotFound => "E_QUERY_NOT_FOUND",
        DiagnosticCode::QueryNotUnique => "E_QUERY_NOT_UNIQUE",
        DiagnosticCode::QueryNumericOverflow => "E_QUERY_NUMERIC_OVERFLOW",
        DiagnosticCode::QueryNumericNotRepresentable => "E_QUERY_NUMERIC_NOT_REPRESENTABLE",
        DiagnosticCode::QueryUnknownAggregateTargetField => {
            "E_QUERY_UNKNOWN_AGGREGATE_TARGET_FIELD"
        }
        DiagnosticCode::QueryUnsupportedProjection => "E_QUERY_UNSUPPORTED_PROJECTION",
        DiagnosticCode::QueryResultShapeMismatch => "E_QUERY_RESULT_SHAPE_MISMATCH",
        DiagnosticCode::QueryUnsupportedSqlFeature => "E_QUERY_UNSUPPORTED_SQL_FEATURE",
        DiagnosticCode::QuerySqlSurfaceMismatch => "E_QUERY_SQL_SURFACE_MISMATCH",
        DiagnosticCode::QuerySqlWriteBoundary => "E_QUERY_SQL_WRITE_BOUNDARY",
        DiagnosticCode::SchemaDdlAdmission => "E_SCHEMA_DDL_ADMISSION",
        DiagnosticCode::StoreNotFound => "E_STORE_NOT_FOUND",
        DiagnosticCode::StoreCorruption => "E_STORE_CORRUPTION",
        DiagnosticCode::StoreInvariantViolation => "E_STORE_INVARIANT_VIOLATION",
        DiagnosticCode::RuntimeCorruption => "E_RUNTIME_CORRUPTION",
        DiagnosticCode::RuntimeIncompatiblePersistedFormat => {
            "E_RUNTIME_INCOMPATIBLE_PERSISTED_FORMAT"
        }
        DiagnosticCode::RuntimeInvariantViolation => "E_RUNTIME_INVARIANT_VIOLATION",
        DiagnosticCode::RuntimeConflict => "E_RUNTIME_CONFLICT",
        DiagnosticCode::RuntimeNotFound => "E_RUNTIME_NOT_FOUND",
        DiagnosticCode::RuntimeUnsupported => "E_RUNTIME_UNSUPPORTED",
        DiagnosticCode::RuntimeInternal => "E_RUNTIME_INTERNAL",
    }
}

const fn code_text(code: DiagnosticCode) -> &'static str {
    match code {
        DiagnosticCode::QueryValidate => "query validation failed",
        DiagnosticCode::QueryIntent => "query intent is invalid",
        DiagnosticCode::QueryPlan => "query planning failed",
        DiagnosticCode::QueryReadAdmission => "query read admission rejected",
        DiagnosticCode::QueryAccessRequirement => "query access requirement was not met",
        DiagnosticCode::QueryUnorderedPagination => "pagination requires deterministic ordering",
        DiagnosticCode::QueryInvalidContinuationCursor => "continuation cursor is invalid",
        DiagnosticCode::QueryNotFound => "query expected one row but found none",
        DiagnosticCode::QueryNotUnique => "query expected one row but found multiple rows",
        DiagnosticCode::QueryNumericOverflow => "numeric operation overflowed",
        DiagnosticCode::QueryNumericNotRepresentable => "numeric result is not representable",
        DiagnosticCode::QueryUnknownAggregateTargetField => "unknown aggregate target field",
        DiagnosticCode::QueryUnsupportedProjection => "query projection is not supported",
        DiagnosticCode::QueryResultShapeMismatch => "query result shape mismatch",
        DiagnosticCode::QueryUnsupportedSqlFeature => "SQL feature is not supported",
        DiagnosticCode::QuerySqlSurfaceMismatch => "SQL statement used the wrong endpoint surface",
        DiagnosticCode::QuerySqlWriteBoundary => "SQL write boundary rejected",
        DiagnosticCode::SchemaDdlAdmission => "SQL DDL admission rejected",
        DiagnosticCode::StoreNotFound => "store key was not found",
        DiagnosticCode::StoreCorruption => "store corruption detected",
        DiagnosticCode::StoreInvariantViolation => "store invariant was violated",
        DiagnosticCode::RuntimeCorruption => "runtime corruption detected",
        DiagnosticCode::RuntimeIncompatiblePersistedFormat => {
            "persisted data format is incompatible"
        }
        DiagnosticCode::RuntimeInvariantViolation => "runtime invariant was violated",
        DiagnosticCode::RuntimeConflict => "runtime conflict detected",
        DiagnosticCode::RuntimeNotFound => "runtime item was not found",
        DiagnosticCode::RuntimeUnsupported => "operation is not supported",
        DiagnosticCode::RuntimeInternal => "internal runtime failure",
    }
}

const fn query_kind_text(kind: QueryErrorKind) -> &'static str {
    match kind {
        QueryErrorKind::Validate => "query validation failed",
        QueryErrorKind::Intent => "query intent is invalid",
        QueryErrorKind::Plan => "query planning failed",
        QueryErrorKind::AccessRequirement => "query access requirement was not met",
        QueryErrorKind::UnorderedPagination => "pagination requires deterministic ordering",
        QueryErrorKind::InvalidContinuationCursor => "continuation cursor is invalid",
        QueryErrorKind::NotFound => "query expected one row but found none",
        QueryErrorKind::NotUnique => "query expected one row but found multiple rows",
    }
}

const fn query_projection_text(reason: QueryProjectionCode) -> &'static str {
    match reason {
        QueryProjectionCode::NumericLiteralRequired => {
            "scalar numeric projection requires a numeric literal"
        }
        QueryProjectionCode::NumericScaleArguments => {
            "scale-taking numeric projections require a non-negative integer scale"
        }
        QueryProjectionCode::NestedFieldPathPreview => {
            "nested field-path projection preview is not supported"
        }
        QueryProjectionCode::CaseConditionBooleanRequired => {
            "CASE projection conditions must evaluate to boolean values"
        }
        QueryProjectionCode::NumericInputRequired => {
            "numeric projection functions require numeric inputs"
        }
        QueryProjectionCode::TextOrBlobInputRequired => {
            "this projection function requires text or blob input"
        }
        QueryProjectionCode::TextInputRequired => "text projection functions require text input",
        QueryProjectionCode::TextOrNullArgumentRequired => {
            "this projection function requires a text or NULL literal argument"
        }
        QueryProjectionCode::IntegerOrNullArgumentRequired => {
            "this projection function requires an integer or NULL literal argument"
        }
        QueryProjectionCode::UnaryOperandIncompatible => {
            "projection unary operator operand is incompatible"
        }
        QueryProjectionCode::BinaryOperandsIncompatible => {
            "projection binary operator operands are incompatible"
        }
    }
}

fn query_read_admission_text(reason: QueryReadAdmissionCode) -> String {
    format!(
        "{}; fix: {}",
        query_read_admission_reason_text(reason),
        query_read_admission_fix_text(reason),
    )
}

const fn query_read_admission_reason_text(reason: QueryReadAdmissionCode) -> &'static str {
    match reason {
        QueryReadAdmissionCode::PublicQueryRequiresLimit => {
            "public read queries require a bounded read intent"
        }
        QueryReadAdmissionCode::PublicQueryRequiresIndex => {
            "public read queries require an index-backed access path"
        }
        QueryReadAdmissionCode::UnboundedFullScanRejected => {
            "public read queries cannot execute an unbounded full scan"
        }
        QueryReadAdmissionCode::SortRequiresMaterialization => {
            "this read requires materializing rows for ORDER BY"
        }
        QueryReadAdmissionCode::GroupedQueryRequiresLimits => {
            "grouped reads require explicit group and memory budgets"
        }
        QueryReadAdmissionCode::GroupedQueryExceedsBudget => {
            "grouped read planning exceeds this endpoint's group budget"
        }
        QueryReadAdmissionCode::DiagnosticLaneDoesNotExecute => {
            "diagnostic EXPLAIN lanes cannot execute rows"
        }
        QueryReadAdmissionCode::ReturnedRowBoundExceedsPolicy => {
            "the returned-row bound exceeds this endpoint's read budget"
        }
        QueryReadAdmissionCode::PrimaryKeyInputExceedsPolicy => {
            "primary-key input literals exceed this endpoint's read budget"
        }
    }
}

const fn query_read_admission_fix_text(reason: QueryReadAdmissionCode) -> &'static str {
    match reason {
        QueryReadAdmissionCode::PublicQueryRequiresLimit => {
            "add a positive limit within policy or use exact selected primary-key access"
        }
        QueryReadAdmissionCode::PublicQueryRequiresIndex
        | QueryReadAdmissionCode::UnboundedFullScanRejected => {
            "add a suitable index, tighten the predicate, or move the query behind a trusted admin endpoint"
        }
        QueryReadAdmissionCode::SortRequiresMaterialization => {
            "order by the selected index order, remove the sort, or keep the query on a trusted admin path"
        }
        QueryReadAdmissionCode::GroupedQueryRequiresLimits => {
            "add grouped_limits(max_groups, max_group_bytes) and keep DISTINCT aggregates within policy"
        }
        QueryReadAdmissionCode::GroupedQueryExceedsBudget => {
            "lower grouped_limits or split the report into a trusted/admin query"
        }
        QueryReadAdmissionCode::DiagnosticLaneDoesNotExecute => {
            "run EXPLAIN for diagnostics only, then execute through an admitted ordinary or trusted lane"
        }
        QueryReadAdmissionCode::ReturnedRowBoundExceedsPolicy => {
            "lower LIMIT or split the query into smaller cursor-paged reads"
        }
        QueryReadAdmissionCode::PrimaryKeyInputExceedsPolicy => {
            "reduce the primary-key IN list or move the read behind a trusted admin endpoint"
        }
    }
}

const fn query_result_shape_text(reason: QueryResultShapeCode) -> &'static str {
    match reason {
        QueryResultShapeCode::ExpectedRows => {
            "grouped query result cannot be consumed as entity rows"
        }
        QueryResultShapeCode::ExpectedGroupedRows => {
            "scalar query result cannot be consumed as grouped rows"
        }
    }
}

const fn sql_lowering_text(reason: SqlLoweringCode) -> &'static str {
    match reason {
        SqlLoweringCode::EntityMismatch => {
            "statement target entity does not match the requested entity"
        }
        SqlLoweringCode::SelectProjectionShape => "unsupported SELECT projection shape",
        SqlLoweringCode::SelectDistinct => "unsupported SELECT DISTINCT shape",
        SqlLoweringCode::DistinctOrderByProjection => {
            "SELECT DISTINCT ORDER BY terms must be derivable from the projected tuple"
        }
        SqlLoweringCode::GlobalAggregateProjection => {
            "unsupported global aggregate projection shape"
        }
        SqlLoweringCode::GlobalAggregateGroupBy => "global aggregate SQL does not support GROUP BY",
        SqlLoweringCode::SelectGroupByShape => "unsupported SELECT GROUP BY shape",
        SqlLoweringCode::GroupedProjectionExplicitListRequired => {
            "grouped SELECT requires an explicit projection list"
        }
        SqlLoweringCode::GroupedProjectionAggregateRequired => {
            "grouped SELECT projection must include at least one aggregate expression"
        }
        SqlLoweringCode::GroupedProjectionNonGroupField => {
            "grouped projection references fields outside GROUP BY keys"
        }
        SqlLoweringCode::GroupedProjectionScalarAfterAggregate => {
            "grouped projection scalar expression appears after aggregate expressions"
        }
        SqlLoweringCode::HavingRequiresGroupBy => "HAVING requires GROUP BY",
        SqlLoweringCode::SelectHavingShape => "unsupported SQL HAVING shape",
        SqlLoweringCode::AggregateInputExpressions => {
            "aggregate input expressions are not executable in this release"
        }
        SqlLoweringCode::WhereExpressionShape => "unsupported SQL WHERE expression shape",
        SqlLoweringCode::ParameterPlacement => "unsupported SQL parameter placement",
        SqlLoweringCode::SqlDdlExecutionUnsupported => {
            "SQL DDL execution is not supported in this release"
        }
    }
}

const fn runtime_kind_text(kind: RuntimeErrorKind) -> &'static str {
    match kind {
        RuntimeErrorKind::Corruption => "runtime corruption detected",
        RuntimeErrorKind::IncompatiblePersistedFormat => "persisted data format is incompatible",
        RuntimeErrorKind::InvariantViolation => "runtime invariant was violated",
        RuntimeErrorKind::Conflict => "runtime conflict detected",
        RuntimeErrorKind::NotFound => "runtime item was not found",
        RuntimeErrorKind::Unsupported => "operation is not supported",
        RuntimeErrorKind::Internal => "internal runtime failure",
    }
}

const fn runtime_boundary_text(boundary: RuntimeBoundaryCode) -> &'static str {
    match boundary {
        RuntimeBoundaryCode::SqlSurfaceControllerRequired => {
            "SQL endpoint requires controller access"
        }
        RuntimeBoundaryCode::SchemaSurfaceControllerRequired => {
            "schema endpoint requires controller access"
        }
        RuntimeBoundaryCode::OperationalSurfaceControllerRequired => {
            "operational endpoint requires controller access"
        }
        RuntimeBoundaryCode::SqlQueryNoConfiguredEntities => {
            "SQL query endpoint has no configured entities"
        }
        RuntimeBoundaryCode::SqlQueryEntityNotConfigured => {
            "SQL query target entity is not configured for this canister"
        }
        RuntimeBoundaryCode::SqlDdlTargetRequired => "SQL DDL requires one target entity",
        RuntimeBoundaryCode::SqlDdlEntityNotConfigured => {
            "SQL DDL target entity is not configured for this canister"
        }
        RuntimeBoundaryCode::QueryResponseRowsRequired => "query response contains grouped rows",
        RuntimeBoundaryCode::QueryResponseGroupedRowsRequired => {
            "query response contains scalar rows"
        }
        RuntimeBoundaryCode::RowProjectionFieldNotConfigured => {
            "requested projection field is not configured for this entity"
        }
        RuntimeBoundaryCode::SqlIntrospectionDisabled => {
            "SQL introspection is disabled for this canister build target"
        }
        RuntimeBoundaryCode::MutationRequiredFieldMissing => {
            "mutation is missing one or more required fields"
        }
        RuntimeBoundaryCode::MutationManagedTimestampRegression => {
            "mutation operation time precedes an accepted managed timestamp"
        }
        RuntimeBoundaryCode::PersistedRowLayoutOutsideAcceptedWindow => {
            "persisted row layout is outside the accepted layout window"
        }
        RuntimeBoundaryCode::PersistedRowSlotCountMismatch => {
            "persisted row slot count does not match its stamped layout"
        }
        RuntimeBoundaryCode::GeneratedFieldAfterDdlField => {
            "generated field would collide with an accepted SQL DDL field slot"
        }
        RuntimeBoundaryCode::JournalMutationRevisionExhausted => {
            "journaled mutation revision space is exhausted"
        }
        RuntimeBoundaryCode::ConstraintViolation => {
            "mutation violates an accepted constraint or activation gate"
        }
        RuntimeBoundaryCode::AcceptedRowConstraintProgramCorrupt => {
            "accepted row-constraint program is corrupt"
        }
        RuntimeBoundaryCode::ConstraintActivationWriteBlocked => {
            "write conflicts with an incomplete constraint activation"
        }
        RuntimeBoundaryCode::GeneratedConstraintActivationStale => {
            "generated constraint proposal no longer matches its live activation"
        }
        RuntimeBoundaryCode::MutationDatabaseOwnedFieldExplicit => {
            "mutation explicitly authors a database-owned field"
        }
        RuntimeBoundaryCode::MutationBatchEmpty => "structural mutation batch is empty",
        RuntimeBoundaryCode::MutationBatchTooManyItems => {
            "structural mutation batch exceeds the operation-count bound"
        }
        RuntimeBoundaryCode::MutationBatchStagedBytesExceeded => {
            "structural mutation batch exceeds the staged-byte bound"
        }
        RuntimeBoundaryCode::MutationBatchResultBytesExceeded => {
            "structural mutation result exceeds the encoded response bound"
        }
        RuntimeBoundaryCode::MutationBatchEntityMismatch => {
            "structural mutation batch targets more than one accepted entity"
        }
        RuntimeBoundaryCode::MutationBatchDuplicateKey => {
            "structural mutation batch targets the same accepted key more than once"
        }
    }
}

const fn schema_ddl_text(reason: SchemaDdlAdmissionCode) -> &'static str {
    match reason {
        SchemaDdlAdmissionCode::MissingExpectedSchemaVersion => "missing EXPECT SCHEMA VERSION",
        SchemaDdlAdmissionCode::MissingNextSchemaVersion => "missing SET SCHEMA VERSION",
        SchemaDdlAdmissionCode::StaleExpectedSchemaVersion => "expected schema version is stale",
        SchemaDdlAdmissionCode::InvalidExpectedSchemaVersion => {
            "expected schema version is invalid"
        }
        SchemaDdlAdmissionCode::InvalidNextSchemaVersion => "next schema version is invalid",
        SchemaDdlAdmissionCode::AcceptedSchemaChangeWithoutVersionBump => {
            "accepted schema changed without a version bump"
        }
        SchemaDdlAdmissionCode::EmptyVersionBump => "schema version bump has no schema change",
        SchemaDdlAdmissionCode::VersionGap => "schema version gap is not allowed",
        SchemaDdlAdmissionCode::VersionRollback => "schema version rollback is not allowed",
        SchemaDdlAdmissionCode::FingerprintMethodMismatch => {
            "schema fingerprint method versions do not match"
        }
        SchemaDdlAdmissionCode::UnsupportedTransitionClass => {
            "DDL transition class is not supported"
        }
        SchemaDdlAdmissionCode::PhysicalRunnerMissing => {
            "required physical runner capability is missing"
        }
        SchemaDdlAdmissionCode::ValidationFailed => "candidate schema validation failed",
        SchemaDdlAdmissionCode::PublicationRaceLost => "accepted schema changed after DDL binding",
        SchemaDdlAdmissionCode::InvalidAddColumnDefault => {
            "ADD COLUMN default value is not encodable"
        }
        SchemaDdlAdmissionCode::InvalidAlterColumnDefault => {
            "ALTER COLUMN SET DEFAULT value is not encodable"
        }
        SchemaDdlAdmissionCode::GeneratedIndexDropRejected => {
            "generated index cannot be dropped by SQL DDL"
        }
        SchemaDdlAdmissionCode::SchemaRewriteRequiresMigration => {
            "nonempty physical schema rewrite requires a migration"
        }
        SchemaDdlAdmissionCode::SchemaTransitionBudgetExceeded => {
            "schema transition exceeded its bounded resource budget"
        }
        SchemaDdlAdmissionCode::GeneratedFieldDefaultChangeRejected => {
            "generated field default cannot be changed by SQL DDL"
        }
        SchemaDdlAdmissionCode::GeneratedFieldNullabilityChangeRejected => {
            "generated field nullability cannot be changed by SQL DDL"
        }
        SchemaDdlAdmissionCode::RowLayoutVersionExhausted => {
            "row-layout version space is exhausted"
        }
    }
}

const fn schema_migration_text(reason: SchemaMigrationCode) -> &'static str {
    match reason {
        SchemaMigrationCode::Unadopted => "accepted generated entities are not adopted",
        SchemaMigrationCode::MissingMigration => "a required immediate migration is missing",
        SchemaMigrationCode::VersionGap => "an entity source version skips its predecessor",
        SchemaMigrationCode::Downgrade => "an entity source version moves backward",
        SchemaMigrationCode::EmptyEntityVersionBump => {
            "an entity source version changed without a schema change"
        }
        SchemaMigrationCode::DuplicateEntityTransition => {
            "the coordinated plan repeats an entity transition"
        }
        SchemaMigrationCode::StaleAcceptedHead => "the accepted schema head changed",
        SchemaMigrationCode::PlanChanged => "the deployed migration plan changed",
        SchemaMigrationCode::DuplicateRenameSource => "a rename source is used more than once",
        SchemaMigrationCode::DuplicateRenameTarget => "a rename target is used more than once",
        SchemaMigrationCode::UnknownFromObject => "a rename source is not accepted",
        SchemaMigrationCode::UnknownToObject => "a rename target is not declared",
        SchemaMigrationCode::KindMismatch => "a migration object kind does not match",
        SchemaMigrationCode::IdentityConflict => "accepted migration identity conflicts",
        SchemaMigrationCode::IncompleteRenameCoverage => {
            "the migration does not cover every required rename"
        }
        SchemaMigrationCode::UnexplainedSchemaDifference => {
            "the proposal contains an unexplained schema difference"
        }
        SchemaMigrationCode::UnsupportedTransform => "the declared transform is unsupported",
        SchemaMigrationCode::TransformFinding => "a row transform failed validation",
        SchemaMigrationCode::UniqueIndexFinding => "candidate uniqueness validation failed",
        SchemaMigrationCode::RelationFinding => "candidate relation validation failed",
        SchemaMigrationCode::ConstraintFinding => "candidate constraint validation failed",
        SchemaMigrationCode::PhysicalRunnerMissing => {
            "the required physical migration runner is unavailable"
        }
        SchemaMigrationCode::MigrationInProgress => "a schema migration is already in progress",
        SchemaMigrationCode::AbortTooLate => "row rewriting has begun and abort is no longer safe",
        SchemaMigrationCode::ProgressCorrupt => "durable migration progress is corrupt",
        SchemaMigrationCode::CandidateMismatch => {
            "durable candidate state does not match the deployed plan"
        }
        SchemaMigrationCode::PublicationRaceLost => {
            "accepted migration authority changed before publication"
        }
    }
}

const fn sql_surface_mismatch_text(mismatch: SqlSurfaceMismatchCode) -> &'static str {
    match mismatch {
        SqlSurfaceMismatchCode::QueryRejectsInsert => {
            "execute_trusted_sql_query rejects INSERT; use execute_trusted_sql_mutation()"
        }
        SqlSurfaceMismatchCode::QueryRejectsUpdate => {
            "execute_trusted_sql_query rejects UPDATE; use execute_trusted_sql_exact_update() or execute_trusted_sql_prefix_update()"
        }
        SqlSurfaceMismatchCode::QueryRejectsDelete => {
            "execute_trusted_sql_query rejects DELETE; use execute_trusted_sql_mutation()"
        }
        SqlSurfaceMismatchCode::MutationRejectsSelect => {
            "execute_trusted_sql_mutation rejects SELECT; use execute_trusted_sql_query()"
        }
        SqlSurfaceMismatchCode::MutationRejectsExplain => {
            "execute_trusted_sql_mutation rejects EXPLAIN; use execute_trusted_sql_query()"
        }
        SqlSurfaceMismatchCode::MutationRejectsDescribe => {
            "execute_trusted_sql_mutation rejects DESCRIBE; use execute_trusted_sql_query()"
        }
        SqlSurfaceMismatchCode::MutationRejectsShowIndexes => {
            "execute_trusted_sql_mutation rejects SHOW INDEXES; use execute_trusted_sql_query()"
        }
        SqlSurfaceMismatchCode::MutationRejectsShowConstraints => {
            "execute_trusted_sql_mutation rejects SHOW CONSTRAINTS; use execute_trusted_sql_query()"
        }
        SqlSurfaceMismatchCode::MutationRejectsShowColumns => {
            "execute_trusted_sql_mutation rejects SHOW COLUMNS; use execute_trusted_sql_query()"
        }
        SqlSurfaceMismatchCode::MutationRejectsShowEntities => {
            "execute_trusted_sql_mutation rejects SHOW ENTITIES; use execute_trusted_sql_query()"
        }
        SqlSurfaceMismatchCode::MutationRejectsShowStores => {
            "execute_trusted_sql_mutation rejects SHOW STORES; use execute_trusted_sql_query()"
        }
        SqlSurfaceMismatchCode::MutationRejectsShowMemory => {
            "execute_trusted_sql_mutation rejects SHOW MEMORY; use execute_trusted_sql_query()"
        }
        SqlSurfaceMismatchCode::MutationRequiresExplicitUpdateIntent => {
            "execute_trusted_sql_mutation rejects UPDATE; use execute_trusted_sql_exact_update() or execute_trusted_sql_prefix_update()"
        }
    }
}

#[expect(
    clippy::too_many_lines,
    reason = "the exhaustive governed SQL write-code map is clearer as one typed lookup"
)]
const fn sql_write_boundary_text(boundary: SqlWriteBoundaryCode) -> &'static str {
    match boundary {
        SqlWriteBoundaryCode::PrimaryKeyLiteralShape => "primary key literal has the wrong shape",
        SqlWriteBoundaryCode::PrimaryKeyLiteralIncompatible => {
            "primary key literal is not compatible with the entity key type"
        }
        SqlWriteBoundaryCode::MissingPrimaryKey => "INSERT is missing required primary key fields",
        SqlWriteBoundaryCode::MissingRequiredFields => {
            "INSERT is missing required non-generated fields"
        }
        SqlWriteBoundaryCode::ExplicitManagedField => {
            "explicit writes to managed fields are not allowed"
        }
        SqlWriteBoundaryCode::ExplicitGeneratedField => {
            "explicit writes to generated fields are not allowed"
        }
        SqlWriteBoundaryCode::InsertSelectRequiresScalar => {
            "INSERT SELECT requires a scalar SELECT source"
        }
        SqlWriteBoundaryCode::InsertSelectAggregateProjection => {
            "INSERT SELECT does not support aggregate source projections"
        }
        SqlWriteBoundaryCode::InsertSelectWidthMismatch => {
            "INSERT SELECT projection width must match the target column list"
        }
        SqlWriteBoundaryCode::UpdatePrimaryKeyMutation => "UPDATE cannot mutate primary key fields",
        SqlWriteBoundaryCode::InvalidFieldLiteral => {
            "SQL write literal is not compatible with the target field type"
        }
        SqlWriteBoundaryCode::UnknownReturningField => {
            "RETURNING references a field that does not exist on the target entity"
        }
        SqlWriteBoundaryCode::DuplicateReturningField => {
            "RETURNING field lists cannot repeat the same target field"
        }
        SqlWriteBoundaryCode::UpdateMissingWherePredicate => "UPDATE requires a WHERE predicate",
        SqlWriteBoundaryCode::WriteOrderByUnsupportedShape => {
            "SQL write ORDER BY only supports direct field targets"
        }
        SqlWriteBoundaryCode::ReturningResponseTooLarge => {
            "UPDATE RETURNING response exceeds this endpoint's response-size budget"
        }
        SqlWriteBoundaryCode::ReturningRowsTooMany => {
            "UPDATE RETURNING emits more rows than this endpoint's row budget"
        }
        SqlWriteBoundaryCode::StagedRowsTooMany => {
            "SQL write stages more rows than this endpoint's row budget"
        }
        SqlWriteBoundaryCode::InsertDefaultRequiredField => {
            "INSERT DEFAULT cannot resolve a required ordinary field"
        }
        SqlWriteBoundaryCode::UpdateDefaultRequiredField => {
            "UPDATE DEFAULT cannot resolve a required ordinary field"
        }
        SqlWriteBoundaryCode::UpdateDefaultDatabaseOwnedField => {
            "UPDATE DEFAULT cannot assign a generated or managed field"
        }
        SqlWriteBoundaryCode::ExactUpdateAssertionRequired => {
            "exact UPDATE requires a positive require_affected_at_most assertion"
        }
        SqlWriteBoundaryCode::ExactUpdateAssertionTooHigh => {
            "exact UPDATE assertion exceeds the engine row ceiling"
        }
        SqlWriteBoundaryCode::ExactUpdateAffectedRowsExceeded => {
            "exact UPDATE matched more rows than require_affected_at_most"
        }
        SqlWriteBoundaryCode::ExactUpdateWindowUnsupported => {
            "exact UPDATE rejects LIMIT, OFFSET, and non-primary-key ordering"
        }
        SqlWriteBoundaryCode::ExactUpdateScanBudgetExceeded => {
            "exact UPDATE selection exceeded the engine scan budget"
        }
        SqlWriteBoundaryCode::ResumableUpdateWindowUnsupported => {
            "resumable UPDATE rejects LIMIT, OFFSET, and non-primary-key ordering"
        }
        SqlWriteBoundaryCode::ResumableUpdateReturningUnsupported => {
            "resumable UPDATE does not support row RETURNING"
        }
        SqlWriteBoundaryCode::ResumableUpdateRequiresJournaledStore => {
            "resumable UPDATE requires a journaled store"
        }
        SqlWriteBoundaryCode::ResumableUpdateAssignedFieldHasGlobalConstraint => {
            "resumable UPDATE cannot assign a unique- or relation-owned field"
        }
        SqlWriteBoundaryCode::ResumableUpdateScopeDependsOnAssignedField => {
            "resumable UPDATE scope cannot depend on an assigned field"
        }
        SqlWriteBoundaryCode::ResumableUpdateScopeDependencyUnknown => {
            "resumable UPDATE scope dependencies could not be proven"
        }
        SqlWriteBoundaryCode::ResumableUpdateContinuationMalformed => {
            "resumable UPDATE continuation is malformed or not current"
        }
        SqlWriteBoundaryCode::ResumableUpdateContinuationTargetMismatch => {
            "resumable UPDATE continuation belongs to another target"
        }
        SqlWriteBoundaryCode::ResumableUpdateContinuationSchemaMismatch => {
            "resumable UPDATE continuation belongs to another accepted schema"
        }
        SqlWriteBoundaryCode::ResumableUpdateContinuationScopeMismatch => {
            "resumable UPDATE continuation belongs to another scope"
        }
        SqlWriteBoundaryCode::ResumableUpdateContinuationPatchMismatch => {
            "resumable UPDATE continuation belongs to another fixed patch"
        }
        SqlWriteBoundaryCode::ResumableUpdateContinuationBatchPolicyMismatch => {
            "resumable UPDATE continuation uses another engine batch policy"
        }
        SqlWriteBoundaryCode::ResumableUpdateSingleRowResourceExceeded => {
            "one resumable UPDATE row cannot fit the engine commit window"
        }
        SqlWriteBoundaryCode::ResumableUpdateManagedFieldHasGlobalConstraint => {
            "resumable UPDATE cannot refresh a globally constrained managed field"
        }
        SqlWriteBoundaryCode::ResumableUpdateContinuationOperationMismatch => {
            "resumable UPDATE continuation belongs to another application operation"
        }
    }
}

const fn sql_feature_text(feature: SqlFeatureCode) -> &'static str {
    match feature {
        SqlFeatureCode::AggregateFilterClause => "aggregate FILTER clauses",
        SqlFeatureCode::AlterStatementBeyondAlterTable
        | SqlFeatureCode::AlterTableAddColumnDuplicateDefault
        | SqlFeatureCode::AlterTableAddColumnModifiers
        | SqlFeatureCode::AlterTableAddStatementBeyondAddColumn
        | SqlFeatureCode::AlterTableAddConstraintBeyondCheck
        | SqlFeatureCode::AlterTableAddConstraintModifiers
        | SqlFeatureCode::AlterTableAlterColumnDropUnsupportedAction
        | SqlFeatureCode::AlterTableAlterColumnModifiers
        | SqlFeatureCode::AlterTableAlterColumnSetUnsupportedAction
        | SqlFeatureCode::AlterTableAlterColumnUnsupportedAction
        | SqlFeatureCode::AlterTableAlterStatementBeyondAlterColumn
        | SqlFeatureCode::AlterTableDropColumnIfExistsSyntax
        | SqlFeatureCode::AlterTableDropColumnModifiers
        | SqlFeatureCode::AlterTableDropStatementBeyondDropColumn
        | SqlFeatureCode::AlterTableDropConstraintIfExistsSyntax
        | SqlFeatureCode::AlterTableDropConstraintModifiers
        | SqlFeatureCode::AlterTableRenameColumnMissingTo
        | SqlFeatureCode::AlterTableRenameColumnModifiers
        | SqlFeatureCode::AlterTableRenameStatementBeyondRenameColumn
        | SqlFeatureCode::AlterTableValidateBeyondConstraint
        | SqlFeatureCode::AlterTableValidateConstraintModifiers
        | SqlFeatureCode::AlterTableUnsupportedOperation
        | SqlFeatureCode::CreateIndexIfNotExistsSyntax
        | SqlFeatureCode::CreateIndexKeyOrderingModifiers
        | SqlFeatureCode::CreateIndexModifiers
        | SqlFeatureCode::CreateStatementBeyondCreateIndex
        | SqlFeatureCode::DdlSchemaVersionDuplicateExpectedClause
        | SqlFeatureCode::DdlSchemaVersionDuplicateSetClause
        | SqlFeatureCode::DropIndexModifiers
        | SqlFeatureCode::DropIndexIfExistsSyntax
        | SqlFeatureCode::DropStatementBeyondDropIndex
        | SqlFeatureCode::ExpressionIndexUnsupportedFunction => sql_ddl_feature_text(feature),
        SqlFeatureCode::ColumnAlias => "column or expression aliases",
        SqlFeatureCode::DescribeModifier => "DESCRIBE modifiers",
        SqlFeatureCode::Having => "HAVING",
        SqlFeatureCode::Insert => "INSERT",
        SqlFeatureCode::Join => "JOIN",
        SqlFeatureCode::LikePatternBeyondTrailingPrefix => {
            "LIKE patterns beyond trailing '%' prefix form"
        }
        SqlFeatureCode::LowerFieldPredicateUnsupported => {
            "LOWER(field) predicate forms beyond LIKE 'prefix%' or ordered text bounds"
        }
        SqlFeatureCode::MultiStatementSql => "multi-statement SQL input",
        SqlFeatureCode::NestedAggregateInput => {
            "nested aggregate references inside aggregate input expressions"
        }
        SqlFeatureCode::NestedProjectionFunctionInArithmetic => {
            "nested projection functions inside arithmetic expressions"
        }
        SqlFeatureCode::NumericScaleFunctionArguments => {
            "scale-taking numeric function arguments beyond supported literal integer scale"
        }
        SqlFeatureCode::OrderByFieldNotOrderable => {
            "ORDER BY fields whose accepted catalog type is not orderable"
        }
        SqlFeatureCode::OrderByUnsupportedForm => "unsupported ORDER BY expression form",
        SqlFeatureCode::Other => "unsupported SQL feature",
        SqlFeatureCode::PredicateStartsWithFirstArgument => {
            "STARTS_WITH first argument forms beyond plain or LOWER field wrappers"
        }
        SqlFeatureCode::QuotedIdentifiers => "quoted identifiers",
        SqlFeatureCode::ReturningUnsupportedShape => "unsupported RETURNING shape",
        SqlFeatureCode::ScalarFunctionExpressionPosition => {
            "functions beyond supported scalar forms in this expression position"
        }
        SqlFeatureCode::ScaleTakingNumericFunctionExpressionPosition => {
            "scale-taking numeric functions in this expression position"
        }
        SqlFeatureCode::SearchedCaseGroupedOrderBy => {
            "searched CASE in grouped ORDER BY expressions"
        }
        SqlFeatureCode::ShowColumnsModifiers => "SHOW COLUMNS modifiers",
        SqlFeatureCode::ShowConstraintsModifiers => "SHOW CONSTRAINTS modifiers",
        SqlFeatureCode::ShowEntitiesModifiers => "SHOW ENTITIES modifiers",
        SqlFeatureCode::ShowIndexesModifiers => "SHOW INDEXES modifiers",
        SqlFeatureCode::ShowMemoryModifiers => "SHOW MEMORY modifiers",
        SqlFeatureCode::ShowStoresModifiers => "SHOW STORES modifiers",
        SqlFeatureCode::ShowUnsupportedCommand => "unsupported SHOW command",
        SqlFeatureCode::SimpleCaseExpression => "simple CASE expressions",
        SqlFeatureCode::StandaloneLiteralProjectionItem => "standalone literal projection items",
        SqlFeatureCode::SupportedGroupedOrderByExpressionFamily => {
            "unsupported grouped ORDER BY expression family"
        }
        SqlFeatureCode::SupportedOrderByExpressionFamily => {
            "unsupported ORDER BY expression family"
        }
        SqlFeatureCode::UnionIntersectExcept => "UNION, INTERSECT, or EXCEPT",
        SqlFeatureCode::UnsupportedFunctionNamespace => "unsupported SQL function namespace",
        SqlFeatureCode::Update => "UPDATE",
        SqlFeatureCode::UpperFieldPredicateUnsupported => {
            "UPPER(field) in reduced predicate-only contracts"
        }
        SqlFeatureCode::WindowFunction => "window functions",
        SqlFeatureCode::With => "WITH",
    }
}

const fn sql_ddl_feature_text(feature: SqlFeatureCode) -> &'static str {
    match feature {
        SqlFeatureCode::AlterStatementBeyondAlterTable => "ALTER statements beyond ALTER TABLE",
        SqlFeatureCode::AlterTableAddColumnDuplicateDefault => {
            "duplicate ALTER TABLE ADD COLUMN DEFAULT clauses"
        }
        SqlFeatureCode::AlterTableAddColumnModifiers => "ALTER TABLE ADD COLUMN modifiers",
        SqlFeatureCode::AlterTableAddStatementBeyondAddColumn => {
            "ALTER TABLE ADD statements beyond ADD COLUMN"
        }
        SqlFeatureCode::AlterTableAddConstraintBeyondCheck => {
            "ALTER TABLE ADD CONSTRAINT kinds beyond CHECK"
        }
        SqlFeatureCode::AlterTableAddConstraintModifiers => "ALTER TABLE ADD CONSTRAINT modifiers",
        SqlFeatureCode::AlterTableAlterColumnDropUnsupportedAction => {
            "ALTER TABLE ALTER COLUMN DROP actions beyond DEFAULT and NOT NULL"
        }
        SqlFeatureCode::AlterTableAlterColumnModifiers => "ALTER TABLE ALTER COLUMN modifiers",
        SqlFeatureCode::AlterTableAlterColumnSetUnsupportedAction => {
            "ALTER TABLE ALTER COLUMN SET actions beyond DEFAULT and NOT NULL"
        }
        SqlFeatureCode::AlterTableAlterColumnUnsupportedAction => {
            "ALTER TABLE ALTER COLUMN actions beyond SET/DROP DEFAULT and SET/DROP NOT NULL"
        }
        SqlFeatureCode::AlterTableAlterStatementBeyondAlterColumn => {
            "ALTER TABLE ALTER statements beyond ALTER COLUMN"
        }
        SqlFeatureCode::AlterTableDropColumnIfExistsSyntax => {
            "ALTER TABLE DROP COLUMN IF EXISTS syntax"
        }
        SqlFeatureCode::AlterTableDropColumnModifiers => "ALTER TABLE DROP COLUMN modifiers",
        SqlFeatureCode::AlterTableDropStatementBeyondDropColumn => {
            "ALTER TABLE DROP statements beyond DROP COLUMN"
        }
        SqlFeatureCode::AlterTableDropConstraintIfExistsSyntax => {
            "ALTER TABLE DROP CONSTRAINT IF EXISTS syntax"
        }
        SqlFeatureCode::AlterTableDropConstraintModifiers => {
            "ALTER TABLE DROP CONSTRAINT modifiers"
        }
        SqlFeatureCode::AlterTableRenameColumnMissingTo => "ALTER TABLE RENAME COLUMN without TO",
        SqlFeatureCode::AlterTableRenameColumnModifiers => "ALTER TABLE RENAME COLUMN modifiers",
        SqlFeatureCode::AlterTableRenameStatementBeyondRenameColumn => {
            "ALTER TABLE RENAME statements beyond RENAME COLUMN"
        }
        SqlFeatureCode::AlterTableValidateBeyondConstraint => {
            "ALTER TABLE VALIDATE operations beyond constraints"
        }
        SqlFeatureCode::AlterTableValidateConstraintModifiers => {
            "ALTER TABLE VALIDATE CONSTRAINT modifiers"
        }
        SqlFeatureCode::AlterTableUnsupportedOperation => "unsupported ALTER TABLE operation",
        SqlFeatureCode::CreateIndexIfNotExistsSyntax => "CREATE INDEX IF NOT EXISTS syntax",
        SqlFeatureCode::CreateIndexKeyOrderingModifiers => "CREATE INDEX key ordering modifiers",
        SqlFeatureCode::CreateIndexModifiers => "CREATE INDEX modifiers",
        SqlFeatureCode::CreateStatementBeyondCreateIndex => "CREATE statements beyond CREATE INDEX",
        SqlFeatureCode::DdlSchemaVersionDuplicateExpectedClause => {
            "duplicate EXPECT SCHEMA VERSION clauses"
        }
        SqlFeatureCode::DdlSchemaVersionDuplicateSetClause => {
            "duplicate SET SCHEMA VERSION clauses"
        }
        SqlFeatureCode::DropIndexModifiers => "DROP INDEX modifiers",
        SqlFeatureCode::DropIndexIfExistsSyntax => "DROP INDEX IF EXISTS syntax",
        SqlFeatureCode::DropStatementBeyondDropIndex => "DROP statements beyond DROP INDEX",
        SqlFeatureCode::ExpressionIndexUnsupportedFunction => {
            "expression index functions beyond LOWER, UPPER, and TRIM"
        }
        _ => "unsupported SQL feature",
    }
}

#[cfg(test)]
mod tests {
    use super::{
        RawDiagnosticFact, artifact::DiagnosticSchemaArtifact, parse_error_code, render_error,
        render_error_code_report, render_error_code_report_with_facts,
    };

    #[test]
    fn renders_compact_query_not_found_code_report() {
        let report = render_error_code_report("E7").expect("E7 should parse");

        assert!(report.contains("IcyDB diagnostic E7"), "{report}");
        assert!(report.contains("known: yes"), "{report}");
        assert!(report.contains("class: not-found"), "{report}");
        assert!(report.contains("default origin: query"), "{report}");
        assert!(
            report.contains("E_QUERY_NOT_FOUND: query expected one row but found none"),
            "{report}"
        );
    }

    #[test]
    fn renders_known_and_unknown_numeric_facts() {
        let err: icydb::Error = serde_json::from_value(serde_json::json!({
            "code": icydb::ErrorCode::RUNTIME_BOUNDARY_MUTATION_BATCH_TOO_MANY_ITEMS.raw(),
            "class": icydb::diagnostic::ErrorClass::Unsupported.wire_code(),
            "origin": icydb::diagnostic::ErrorOrigin::Executor.wire_code(),
            "facts": [
                {
                    "tag": icydb::diagnostic::DiagnosticFactTag::ActualCount.raw(),
                    "value": 5_000,
                },
                {
                    "tag": icydb::diagnostic::DiagnosticFactTag::Limit.raw(),
                    "value": 4_096,
                },
                { "tag": 250, "value": 7 },
            ],
        }))
        .expect("numeric fact error should decode");

        assert_eq!(
            render_error(&err),
            "E_RUNTIME_UNSUPPORTED: structural mutation batch exceeds the operation-count bound; facts actual_count=5000 limit=4096 tag#250=7; fact context mismatch: fact count exceeds the E-code maximum",
        );
    }

    #[test]
    fn exact_artifact_humanizes_constraint_facts_and_stale_artifact_does_not() {
        use icydb::diagnostic::DiagnosticFactTag;

        let high = u64::from_be_bytes([7; 8]);
        let facts = [
            RawDiagnosticFact {
                tag: DiagnosticFactTag::AcceptedSchemaFingerprintMethod.raw(),
                value: 1,
            },
            RawDiagnosticFact {
                tag: DiagnosticFactTag::AcceptedSchemaFingerprintHigh.raw(),
                value: high,
            },
            RawDiagnosticFact {
                tag: DiagnosticFactTag::AcceptedSchemaFingerprintLow.raw(),
                value: high,
            },
            RawDiagnosticFact {
                tag: DiagnosticFactTag::EntityTag.raw(),
                value: 42,
            },
            RawDiagnosticFact {
                tag: DiagnosticFactTag::ConstraintId.raw(),
                value: 3,
            },
            RawDiagnosticFact {
                tag: DiagnosticFactTag::ConstraintKind.raw(),
                value: 5,
            },
            RawDiagnosticFact {
                tag: DiagnosticFactTag::ConstraintContext.raw(),
                value: icydb::diagnostic::DiagnosticConstraintContext::WriteAdmission.raw(),
            },
            RawDiagnosticFact {
                tag: DiagnosticFactTag::MutationOperation.raw(),
                value: 1,
            },
            RawDiagnosticFact {
                tag: DiagnosticFactTag::BatchPosition.raw(),
                value: 0,
            },
        ];
        let artifact = DiagnosticSchemaArtifact::test_fixture();
        let mut notes = Vec::new();
        let report =
            render_error_code_report_with_facts("E223", facts.as_slice(), &[&artifact], &mut notes)
                .expect("exact diagnostic should render");
        assert!(report.contains("entity_tag=42(Account)"), "{report}");
        assert!(
            report.contains("constraint_id=3(account_name_unique)"),
            "{report}"
        );
        assert!(report.contains("constraint_kind=5(unique)"), "{report}");
        assert!(report.contains("mutation_operation=1(insert)"), "{report}");
        assert!(
            report.contains("accepted entity: Account (schema::Account)"),
            "{report}"
        );

        let mut stale_facts = facts;
        stale_facts[1].value = u64::from_be_bytes([8; 8]);
        let mut notes = Vec::new();
        let report = render_error_code_report_with_facts(
            "E223",
            stale_facts.as_slice(),
            &[&artifact],
            &mut notes,
        )
        .expect("stale diagnostic should render numerically");
        assert!(!report.contains("Account"), "{report}");
        assert!(report.contains("names withheld"), "{report}");

        let mut malformed_facts = facts;
        malformed_facts.swap(4, 5);
        let mut notes = Vec::new();
        let report = render_error_code_report_with_facts(
            "E223",
            malformed_facts.as_slice(),
            &[&artifact],
            &mut notes,
        )
        .expect("malformed known context should remain numerically renderable");
        assert!(!report.contains("Account"), "{report}");
        assert!(report.contains("fact context mismatch"), "{report}");
    }

    #[test]
    fn exact_schema_facts_without_resolver_explain_numeric_fallback() {
        use icydb::diagnostic::DiagnosticFactTag;

        let facts = [
            RawDiagnosticFact {
                tag: DiagnosticFactTag::AcceptedSchemaFingerprintMethod.raw(),
                value: 1,
            },
            RawDiagnosticFact {
                tag: DiagnosticFactTag::AcceptedSchemaFingerprintHigh.raw(),
                value: 1,
            },
            RawDiagnosticFact {
                tag: DiagnosticFactTag::AcceptedSchemaFingerprintLow.raw(),
                value: 2,
            },
            RawDiagnosticFact {
                tag: DiagnosticFactTag::EntityTag.raw(),
                value: 3,
            },
            RawDiagnosticFact {
                tag: DiagnosticFactTag::ConstraintId.raw(),
                value: 4,
            },
            RawDiagnosticFact {
                tag: DiagnosticFactTag::ConstraintKind.raw(),
                value: icydb::diagnostic::DiagnosticConstraintKind::Unique.raw(),
            },
            RawDiagnosticFact {
                tag: DiagnosticFactTag::ConstraintContext.raw(),
                value: icydb::diagnostic::DiagnosticConstraintContext::WriteAdmission.raw(),
            },
        ];
        let mut notes = Vec::new();
        let report = render_error_code_report_with_facts("E223", facts.as_slice(), &[], &mut notes)
            .expect("numeric diagnostic should render");

        assert!(report.contains("entity_tag=3"), "{report}");
        assert!(
            report.contains("supply --artifact, --canister, or --source-metadata"),
            "{report}"
        );
    }

    #[test]
    fn exact_source_metadata_humanizes_only_its_bound_schema_identity() {
        use icydb::diagnostic::DiagnosticFactTag;

        let high = u64::from_be_bytes([7; 8]);
        let facts = [
            RawDiagnosticFact {
                tag: DiagnosticFactTag::AcceptedSchemaFingerprintMethod.raw(),
                value: 1,
            },
            RawDiagnosticFact {
                tag: DiagnosticFactTag::AcceptedSchemaFingerprintHigh.raw(),
                value: high,
            },
            RawDiagnosticFact {
                tag: DiagnosticFactTag::AcceptedSchemaFingerprintLow.raw(),
                value: high,
            },
            RawDiagnosticFact {
                tag: DiagnosticFactTag::EntityTag.raw(),
                value: 42,
            },
            RawDiagnosticFact {
                tag: DiagnosticFactTag::ConstraintId.raw(),
                value: 3,
            },
            RawDiagnosticFact {
                tag: DiagnosticFactTag::ConstraintKind.raw(),
                value: icydb::diagnostic::DiagnosticConstraintKind::Unique.raw(),
            },
            RawDiagnosticFact {
                tag: DiagnosticFactTag::ConstraintContext.raw(),
                value: icydb::diagnostic::DiagnosticConstraintContext::WriteAdmission.raw(),
            },
        ];
        let metadata = DiagnosticSchemaArtifact::test_source_fixture();
        let mut notes = Vec::new();
        let report =
            render_error_code_report_with_facts("E223", facts.as_slice(), &[&metadata], &mut notes)
                .expect("exact source-bound diagnostic should render");

        assert!(report.contains("entity_tag=42(SourceAccount)"), "{report}");
        assert!(
            report.contains("constraint_id=3(source_account_name_unique)"),
            "{report}"
        );

        let deployment = DiagnosticSchemaArtifact::test_fixture();
        let mut notes = Vec::new();
        let report = render_error_code_report_with_facts(
            "E223",
            facts.as_slice(),
            &[&deployment, &metadata],
            &mut notes,
        )
        .expect("higher-priority deployment metadata should render");
        assert!(report.contains("entity_tag=42(Account)"), "{report}");
        assert!(!report.contains("SourceAccount"), "{report}");

        let mut stale_facts = facts;
        stale_facts[2].value = u64::from_be_bytes([8; 8]);
        let mut notes = Vec::new();
        let report = render_error_code_report_with_facts(
            "E223",
            stale_facts.as_slice(),
            &[&metadata],
            &mut notes,
        )
        .expect("stale source metadata should fall back numerically");
        assert!(!report.contains("SourceAccount"), "{report}");
        assert!(report.contains("names withheld"), "{report}");
    }

    #[test]
    fn renders_cursor_and_recovery_fact_tags_without_canister_prose() {
        let cursor: icydb::Error = serde_json::from_value(serde_json::json!({
            "code": icydb::ErrorCode::QUERY_INVALID_CONTINUATION_CURSOR.raw(),
            "class": icydb::diagnostic::ErrorClass::Unsupported.wire_code(),
            "origin": icydb::diagnostic::ErrorOrigin::Cursor.wire_code(),
            "facts": [
                {
                    "tag": icydb::diagnostic::DiagnosticFactTag::ComponentIndex.raw(),
                    "value": 1,
                },
                {
                    "tag": icydb::diagnostic::DiagnosticFactTag::DecodeReason.raw(),
                    "value": icydb::diagnostic::DiagnosticDecodeReason::CursorInvalidHex.raw(),
                },
            ],
        }))
        .expect("cursor fact error should decode");
        assert!(render_error(&cursor).ends_with("facts component_index=1 decode_reason=4"),);

        let recovery: icydb::Error = serde_json::from_value(serde_json::json!({
            "code": icydb::ErrorCode::RUNTIME_INCOMPATIBLE_PERSISTED_FORMAT.raw(),
            "class": icydb::diagnostic::ErrorClass::IncompatiblePersistedFormat.wire_code(),
            "origin": icydb::diagnostic::ErrorOrigin::Recovery.wire_code(),
            "facts": [
                {
                    "tag": icydb::diagnostic::DiagnosticFactTag::ExpectedVersion.raw(),
                    "value": 9,
                },
                {
                    "tag": icydb::diagnostic::DiagnosticFactTag::ActualVersion.raw(),
                    "value": 7,
                },
            ],
        }))
        .expect("recovery fact error should decode");
        assert!(render_error(&recovery).ends_with("facts expected_version=9 actual_version=7"),);

        let component: icydb::Error = serde_json::from_value(serde_json::json!({
            "code": icydb::ErrorCode::STORE_CORRUPTION.raw(),
            "class": icydb::diagnostic::ErrorClass::Corruption.wire_code(),
            "origin": icydb::diagnostic::ErrorOrigin::Store.wire_code(),
            "facts": [
                {
                    "tag": icydb::diagnostic::DiagnosticFactTag::ComponentKind.raw(),
                    "value": icydb::diagnostic::DiagnosticComponentKind::CommitDataKey.raw(),
                },
                {
                    "tag": icydb::diagnostic::DiagnosticFactTag::ActualLength.raw(),
                    "value": 513,
                },
                {
                    "tag": icydb::diagnostic::DiagnosticFactTag::Limit.raw(),
                    "value": 512,
                },
            ],
        }))
        .expect("component fact error should decode");
        assert!(
            render_error(&component)
                .ends_with("facts component_kind=1(commit-data-key) actual_length=513 limit=512"),
        );
    }

    #[test]
    fn renders_compact_read_admission_code_report() {
        let report = render_error_code_report("184").expect("184 should parse");

        assert!(report.contains("IcyDB diagnostic E184"), "{report}");
        assert!(report.contains("E_QUERY_READ_ADMISSION"), "{report}");
        assert!(
            report.contains("public read queries cannot execute an unbounded full scan"),
            "{report}"
        );
        assert!(
            report.contains("add a suitable index"),
            "read-admission report should include fix guidance: {report}"
        );
    }

    #[test]
    fn diagnostic_code_parser_accepts_quoted_e_prefix() {
        assert_eq!(parse_error_code("\"e7\""), Ok(7));
    }

    #[test]
    fn diagnostic_code_parser_rejects_non_numeric_input() {
        let err = parse_error_code("banana").expect_err("non-code input should fail");

        assert!(err.contains("expected E7"), "{err}");
    }

    #[test]
    fn unknown_compact_code_report_is_explicit() {
        let report = render_error_code_report("9999").expect("numeric code should parse");

        assert!(report.contains("known: no"), "{report}");
        assert!(
            report.contains("reason: unknown compact error code"),
            "{report}"
        );
        assert!(
            report.contains("registry fallback: E_RUNTIME_INTERNAL"),
            "{report}"
        );
    }

    #[test]
    fn renders_schema_ddl_admission_detail() {
        let err = icydb::Error::from_diagnostic(icydb::diagnostic::Diagnostic::new(
            icydb::diagnostic::DiagnosticCode::SchemaDdlAdmission,
            icydb::diagnostic::ErrorOrigin::Query,
            Some(icydb::diagnostic::DiagnosticDetail::SchemaDdlAdmission {
                reason: icydb::diagnostic::SchemaDdlAdmissionCode::PublicationRaceLost,
            }),
        ));

        assert_eq!(
            render_error(&err),
            "E_SCHEMA_DDL_ADMISSION: SQL DDL admission rejected: accepted schema changed after DDL binding",
        );
    }

    #[test]
    fn renders_unsupported_sql_feature_detail() {
        let err = icydb::Error::from_diagnostic(icydb::diagnostic::Diagnostic::new(
            icydb::diagnostic::DiagnosticCode::QueryUnsupportedSqlFeature,
            icydb::diagnostic::ErrorOrigin::Query,
            Some(icydb::diagnostic::DiagnosticDetail::UnsupportedSqlFeature {
                feature: icydb::diagnostic::SqlFeatureCode::Join,
            }),
        ));

        assert_eq!(
            render_error(&err),
            "E_QUERY_UNSUPPORTED_SQL_FEATURE: unsupported SQL feature: JOIN",
        );
    }

    #[test]
    fn renders_sql_surface_mismatch_detail() {
        let err = icydb::Error::from_diagnostic(icydb::diagnostic::Diagnostic::new(
            icydb::diagnostic::DiagnosticCode::QuerySqlSurfaceMismatch,
            icydb::diagnostic::ErrorOrigin::Query,
            Some(icydb::diagnostic::DiagnosticDetail::SqlSurfaceMismatch {
                mismatch: icydb::diagnostic::SqlSurfaceMismatchCode::QueryRejectsInsert,
            }),
        ));

        assert_eq!(
            render_error(&err),
            "E_QUERY_SQL_SURFACE_MISMATCH: execute_trusted_sql_query rejects INSERT; use execute_trusted_sql_mutation()",
        );
    }

    #[test]
    fn renders_sql_write_boundary_detail() {
        let err = icydb::Error::from_diagnostic(icydb::diagnostic::Diagnostic::new(
            icydb::diagnostic::DiagnosticCode::QuerySqlWriteBoundary,
            icydb::diagnostic::ErrorOrigin::Query,
            Some(icydb::diagnostic::DiagnosticDetail::SqlWriteBoundary {
                boundary: icydb::diagnostic::SqlWriteBoundaryCode::MissingPrimaryKey,
            }),
        ));

        assert_eq!(
            render_error(&err),
            "E_QUERY_SQL_WRITE_BOUNDARY: SQL write rejected: INSERT is missing required primary key fields",
        );
    }

    #[test]
    fn renders_sql_write_staged_row_boundary_detail() {
        let err = icydb::Error::from_diagnostic(icydb::diagnostic::Diagnostic::new(
            icydb::diagnostic::DiagnosticCode::QuerySqlWriteBoundary,
            icydb::diagnostic::ErrorOrigin::Query,
            Some(icydb::diagnostic::DiagnosticDetail::SqlWriteBoundary {
                boundary: icydb::diagnostic::SqlWriteBoundaryCode::StagedRowsTooMany,
            }),
        ));

        assert_eq!(
            render_error(&err),
            "E_QUERY_SQL_WRITE_BOUNDARY: SQL write rejected: SQL write stages more rows than this endpoint's row budget",
        );
    }

    #[test]
    fn renders_query_projection_detail() {
        let err = icydb::Error::from_diagnostic(icydb::diagnostic::Diagnostic::new(
            icydb::diagnostic::DiagnosticCode::QueryUnsupportedProjection,
            icydb::diagnostic::ErrorOrigin::Query,
            Some(icydb::diagnostic::DiagnosticDetail::QueryProjection {
                reason: icydb::diagnostic::QueryProjectionCode::NumericScaleArguments,
            }),
        ));

        assert_eq!(
            render_error(&err),
            "E_QUERY_UNSUPPORTED_PROJECTION: query projection rejected: scale-taking numeric projections require a non-negative integer scale",
        );
    }

    #[test]
    fn renders_query_read_admission_detail() {
        let err = icydb::Error::from_diagnostic(icydb::diagnostic::Diagnostic::new(
            icydb::diagnostic::DiagnosticCode::QueryReadAdmission,
            icydb::diagnostic::ErrorOrigin::Query,
            Some(icydb::diagnostic::DiagnosticDetail::QueryReadAdmission {
                reason: icydb::diagnostic::QueryReadAdmissionCode::PublicQueryRequiresLimit,
            }),
        ));

        assert_eq!(
            render_error(&err),
            "E_QUERY_READ_ADMISSION: query read admission rejected: public read queries require a bounded read intent; fix: add a positive limit within policy or use exact selected primary-key access",
        );
    }

    #[test]
    fn renders_query_read_admission_fix_hints_for_common_public_read_rejections() {
        let cases = [
            (
                icydb::diagnostic::QueryReadAdmissionCode::UnboundedFullScanRejected,
                "E_QUERY_READ_ADMISSION: query read admission rejected: public read queries cannot execute an unbounded full scan; fix: add a suitable index, tighten the predicate, or move the query behind a trusted admin endpoint",
            ),
            (
                icydb::diagnostic::QueryReadAdmissionCode::GroupedQueryRequiresLimits,
                "E_QUERY_READ_ADMISSION: query read admission rejected: grouped reads require explicit group and memory budgets; fix: add grouped_limits(max_groups, max_group_bytes) and keep DISTINCT aggregates within policy",
            ),
            (
                icydb::diagnostic::QueryReadAdmissionCode::SortRequiresMaterialization,
                "E_QUERY_READ_ADMISSION: query read admission rejected: this read requires materializing rows for ORDER BY; fix: order by the selected index order, remove the sort, or keep the query on a trusted admin path",
            ),
            (
                icydb::diagnostic::QueryReadAdmissionCode::PrimaryKeyInputExceedsPolicy,
                "E_QUERY_READ_ADMISSION: query read admission rejected: primary-key input literals exceed this endpoint's read budget; fix: reduce the primary-key IN list or move the read behind a trusted admin endpoint",
            ),
        ];

        for (reason, expected) in cases {
            let err = icydb::Error::from_diagnostic(icydb::diagnostic::Diagnostic::new(
                icydb::diagnostic::DiagnosticCode::QueryReadAdmission,
                icydb::diagnostic::ErrorOrigin::Query,
                Some(icydb::diagnostic::DiagnosticDetail::QueryReadAdmission { reason }),
            ));

            assert_eq!(render_error(&err), expected);
        }
    }

    #[test]
    fn renders_query_read_admission_fix_hint_for_every_rejection_code() {
        let reasons = [
            icydb::diagnostic::QueryReadAdmissionCode::PublicQueryRequiresLimit,
            icydb::diagnostic::QueryReadAdmissionCode::PublicQueryRequiresIndex,
            icydb::diagnostic::QueryReadAdmissionCode::UnboundedFullScanRejected,
            icydb::diagnostic::QueryReadAdmissionCode::SortRequiresMaterialization,
            icydb::diagnostic::QueryReadAdmissionCode::GroupedQueryRequiresLimits,
            icydb::diagnostic::QueryReadAdmissionCode::GroupedQueryExceedsBudget,
            icydb::diagnostic::QueryReadAdmissionCode::DiagnosticLaneDoesNotExecute,
            icydb::diagnostic::QueryReadAdmissionCode::ReturnedRowBoundExceedsPolicy,
            icydb::diagnostic::QueryReadAdmissionCode::PrimaryKeyInputExceedsPolicy,
        ];

        for reason in reasons {
            let rendered = render_query_read_admission_error(reason);
            let (_, fix) = rendered
                .split_once("; fix: ")
                .expect("read-admission diagnostics should render a fix hint");

            assert!(
                !fix.is_empty(),
                "read-admission diagnostics should render a non-empty fix hint: {rendered}",
            );
        }
    }

    #[test]
    fn renders_unknown_aggregate_target_field_code() {
        let err = icydb::Error::from_diagnostic(icydb::diagnostic::Diagnostic::from_code(
            icydb::diagnostic::DiagnosticCode::QueryUnknownAggregateTargetField,
        ));

        assert_eq!(
            render_error(&err),
            "E_QUERY_UNKNOWN_AGGREGATE_TARGET_FIELD: unknown aggregate target field",
        );
    }

    #[test]
    fn renders_query_result_shape_detail() {
        let err = icydb::Error::from_diagnostic(icydb::diagnostic::Diagnostic::new(
            icydb::diagnostic::DiagnosticCode::QueryResultShapeMismatch,
            icydb::diagnostic::ErrorOrigin::Query,
            Some(icydb::diagnostic::DiagnosticDetail::QueryResultShape {
                reason: icydb::diagnostic::QueryResultShapeCode::ExpectedRows,
            }),
        ));

        assert_eq!(
            render_error(&err),
            "E_QUERY_RESULT_SHAPE_MISMATCH: grouped query result cannot be consumed as entity rows",
        );
    }

    #[test]
    fn renders_sql_lowering_detail() {
        let err = icydb::Error::from_diagnostic(icydb::diagnostic::Diagnostic::new(
            icydb::diagnostic::DiagnosticCode::QueryUnsupportedSqlFeature,
            icydb::diagnostic::ErrorOrigin::Query,
            Some(icydb::diagnostic::DiagnosticDetail::SqlLowering {
                reason: icydb::diagnostic::SqlLoweringCode::DistinctOrderByProjection,
            }),
        ));

        assert_eq!(
            render_error(&err),
            "E_QUERY_UNSUPPORTED_SQL_FEATURE: unsupported SQL lowering: SELECT DISTINCT ORDER BY terms must be derivable from the projected tuple",
        );
    }

    #[test]
    fn renders_runtime_boundary_details() {
        let cases = [
            (
                icydb::diagnostic::RuntimeBoundaryCode::OperationalSurfaceControllerRequired,
                "E_RUNTIME_UNSUPPORTED: operational endpoint requires controller access",
            ),
            (
                icydb::diagnostic::RuntimeBoundaryCode::SqlDdlTargetRequired,
                "E_RUNTIME_UNSUPPORTED: SQL DDL requires one target entity",
            ),
            (
                icydb::diagnostic::RuntimeBoundaryCode::MutationRequiredFieldMissing,
                "E_RUNTIME_UNSUPPORTED: mutation is missing one or more required fields",
            ),
            (
                icydb::diagnostic::RuntimeBoundaryCode::MutationManagedTimestampRegression,
                "E_RUNTIME_INVARIANT_VIOLATION: mutation operation time precedes an accepted managed timestamp",
            ),
            (
                icydb::diagnostic::RuntimeBoundaryCode::MutationDatabaseOwnedFieldExplicit,
                "E_RUNTIME_UNSUPPORTED: mutation explicitly authors a database-owned field",
            ),
            (
                icydb::diagnostic::RuntimeBoundaryCode::MutationBatchEmpty,
                "E_RUNTIME_UNSUPPORTED: structural mutation batch is empty",
            ),
            (
                icydb::diagnostic::RuntimeBoundaryCode::MutationBatchDuplicateKey,
                "E_RUNTIME_CONFLICT: structural mutation batch targets the same accepted key more than once",
            ),
            (
                icydb::diagnostic::RuntimeBoundaryCode::PersistedRowLayoutOutsideAcceptedWindow,
                "E_RUNTIME_CORRUPTION: persisted row layout is outside the accepted layout window",
            ),
            (
                icydb::diagnostic::RuntimeBoundaryCode::PersistedRowSlotCountMismatch,
                "E_RUNTIME_CORRUPTION: persisted row slot count does not match its stamped layout",
            ),
            (
                icydb::diagnostic::RuntimeBoundaryCode::GeneratedFieldAfterDdlField,
                "E_RUNTIME_UNSUPPORTED: generated field would collide with an accepted SQL DDL field slot",
            ),
            (
                icydb::diagnostic::RuntimeBoundaryCode::ConstraintViolation,
                "E_RUNTIME_INVARIANT_VIOLATION: mutation violates an accepted constraint or activation gate",
            ),
            (
                icydb::diagnostic::RuntimeBoundaryCode::AcceptedRowConstraintProgramCorrupt,
                "E_RUNTIME_CORRUPTION: accepted row-constraint program is corrupt",
            ),
            (
                icydb::diagnostic::RuntimeBoundaryCode::ConstraintActivationWriteBlocked,
                "E_RUNTIME_CONFLICT: write conflicts with an incomplete constraint activation",
            ),
            (
                icydb::diagnostic::RuntimeBoundaryCode::GeneratedConstraintActivationStale,
                "E_RUNTIME_CONFLICT: generated constraint proposal no longer matches its live activation",
            ),
        ];

        for (boundary, expected) in cases {
            let err = icydb::Error::from_runtime_boundary(boundary, icydb::ErrorOrigin::Interface);
            assert_eq!(render_error(&err), expected);
        }
    }

    #[test]
    fn falls_back_to_code_text_without_detail() {
        let err = icydb::Error::from_code(
            icydb::diagnostic::DiagnosticCode::RuntimeInternal,
            icydb::ErrorOrigin::Runtime,
        );

        assert_eq!(
            render_error(&err),
            "E_RUNTIME_INTERNAL: internal runtime failure"
        );
    }

    fn render_query_read_admission_error(
        reason: icydb::diagnostic::QueryReadAdmissionCode,
    ) -> String {
        let err = icydb::Error::from_diagnostic(icydb::diagnostic::Diagnostic::new(
            icydb::diagnostic::DiagnosticCode::QueryReadAdmission,
            icydb::diagnostic::ErrorOrigin::Query,
            Some(icydb::diagnostic::DiagnosticDetail::QueryReadAdmission { reason }),
        ));

        render_error(&err)
    }
}