helm-schema-gen 0.0.6

Generate an accurate JSON schema for any helm chart
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
use super::*;
use color_eyre::eyre;
use indoc::{formatdoc, indoc};
use test_util::prelude::sim_assert_eq;

#[test]
#[expect(
    clippy::too_many_lines,
    reason = "the full expected schema keeps this precedence regression in one auditable scenario"
)]
fn dependency_global_render_uses_follow_the_parent_key_with_a_child_fallback() -> eyre::Result<()> {
    let mut contract = parse_ir(indoc! {r#"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: config
        data:
          registry: {{ .Values.global.imageRegistry | default "" | b64enc | quote }}
    "#});
    contract.map_value_paths(|path| format!("metrics.{path}"));
    contract.project_dependency_global_contracts(&["metrics".to_string()]);
    let schema = schema_for_values_yaml(contract, None);
    let expected: serde_json::Value = serde_json::from_str(indoc! {r##"
        {
          "$defs": {
            "t": {
              "anyOf": [
                { "const": true },
                { "not": { "const": 0 }, "type": "number" },
                { "minLength": 1, "type": "string" },
                { "minItems": 1, "type": "array" },
                { "minProperties": 1, "type": "object" }
              ]
            }
          },
          "$schema": "http://json-schema.org/draft-07/schema#",
          "additionalProperties": false,
          "allOf": [
            {
              "if": {
                "allOf": [
                  {
                    "properties": {
                      "global": {
                        "properties": {
                          "imageRegistry": { "$ref": "#/$defs/t" }
                        },
                        "required": ["imageRegistry"],
                        "type": "object"
                      }
                    },
                    "required": ["global"],
                    "type": "object"
                  },
                  {
                    "properties": {
                      "global": {
                        "properties": {
                          "imageRegistry": {
                            "not": { "enum": [null] }
                          }
                        },
                        "required": ["imageRegistry"],
                        "type": "object"
                      }
                    },
                    "required": ["global"],
                    "type": "object"
                  },
                  {
                    "properties": {
                      "global": {
                        "required": ["imageRegistry"],
                        "type": "object"
                      }
                    },
                    "required": ["global"],
                    "type": "object"
                  }
                ]
              },
              "then": {
                "additionalProperties": {},
                "properties": {
                  "global": {
                    "additionalProperties": {},
                    "properties": {
                      "imageRegistry": {
                        "type": ["null", "string"]
                      }
                    }
                  }
                }
              }
            },
            {
              "if": {
                "allOf": [
                  {
                    "properties": {
                      "metrics": {
                        "properties": {
                          "global": {
                            "properties": {
                              "imageRegistry": { "$ref": "#/$defs/t" }
                            },
                            "required": ["imageRegistry"],
                            "type": "object"
                          }
                        },
                        "required": ["global"],
                        "type": "object"
                      }
                    },
                    "required": ["metrics"],
                    "type": "object"
                  },
                  {
                    "anyOf": [
                      {
                        "anyOf": [
                          {
                            "not": {
                              "properties": {
                                "global": {
                                  "properties": { "imageRegistry": {} },
                                  "required": ["imageRegistry"],
                                  "type": "object"
                                }
                              },
                              "required": ["global"],
                              "type": "object"
                            }
                          },
                          {
                            "properties": {
                              "global": {
                                "properties": {
                                  "imageRegistry": { "enum": [null] }
                                },
                                "required": ["imageRegistry"],
                                "type": "object"
                              }
                            },
                            "required": ["global"],
                            "type": "object"
                          }
                        ]
                      },
                      {
                        "not": {
                          "properties": {
                            "global": {
                              "required": ["imageRegistry"],
                              "type": "object"
                            }
                          },
                          "required": ["global"],
                          "type": "object"
                        }
                      }
                    ]
                  }
                ]
              },
              "then": {
                "additionalProperties": {},
                "properties": {
                  "metrics": {
                    "additionalProperties": {},
                    "properties": {
                      "global": {
                        "additionalProperties": {},
                        "properties": {
                          "imageRegistry": {
                            "type": ["null", "string"]
                          }
                        }
                      }
                    }
                  }
                }
              }
            },
            {
              "if": {
                "allOf": [
                  {
                    "anyOf": [
                      {
                        "not": {
                          "properties": {
                            "metrics": {
                              "properties": { "global": {} },
                              "required": ["global"],
                              "type": "object"
                            }
                          },
                          "required": ["metrics"],
                          "type": "object"
                        }
                      },
                      {
                        "properties": {
                          "metrics": {
                            "properties": {
                              "global": { "enum": [null] }
                            },
                            "required": ["global"],
                            "type": "object"
                          }
                        },
                        "required": ["metrics"],
                        "type": "object"
                      }
                    ]
                  },
                  {
                    "anyOf": [
                      {
                        "not": {
                          "properties": { "metrics": {} },
                          "required": ["metrics"],
                          "type": "object"
                        }
                      },
                      {
                        "properties": {
                          "metrics": { "enum": [null] }
                        },
                        "required": ["metrics"],
                        "type": "object"
                      }
                    ]
                  }
                ]
              },
              "then": false
            }
          ],
          "properties": {
            "global": {
              "additionalProperties": {},
              "properties": { "imageRegistry": {} }
            },
            "metrics": {
              "additionalProperties": {},
              "allOf": [
                {
                  "if": {
                    "anyOf": [
                      {
                        "not": {
                          "properties": { "global": {} },
                          "required": ["global"],
                          "type": "object"
                        }
                      },
                      {
                        "properties": {
                          "global": { "enum": [null] }
                        },
                        "required": ["global"],
                        "type": "object"
                      }
                    ]
                  },
                  "then": false
                }
              ],
              "properties": {
                "global": {
                  "additionalProperties": {},
                  "properties": { "imageRegistry": {} },
                  "type": "object"
                }
              },
              "type": "object"
            }
          },
          "type": "object"
        }
    "##})?;
    sim_assert_eq!(have: schema, want: expected);

    assert!(schema_accepts_instance(
        &schema,
        &serde_json::json!({
            "global": { "imageRegistry": "registry.example" },
            "metrics": { "global": { "imageRegistry": 7 } }
        })
    ));
    assert!(!schema_accepts_instance(
        &schema,
        &serde_json::json!({
            "global": {},
            "metrics": { "global": { "imageRegistry": 7 } }
        })
    ));
    assert!(!schema_accepts_instance(
        &schema,
        &serde_json::json!({
            "global": { "imageRegistry": 7 },
            "metrics": { "global": { "imageRegistry": "registry.child" } }
        })
    ));
    Ok(())
}

#[test]
fn shadowed_dependency_global_default_does_not_type_ignored_input() {
    let mut contract = ContractIr::default();
    contract.add_type_hint("metrics.agent.replicas", "integer");
    let schema_signals = contract.finalize().into_schema_signals();
    let shadowed =
        std::collections::BTreeSet::from(["metrics.agent.global.imageRegistry".to_string()]);
    let schema = generate_values_schema(
        ValuesSchemaInput::new(&schema_signals, &provider())
            .with_values_documents(&prepared_values_documents(Some(indoc! {"
                metrics:
                  agent:
                    replicas: 1
                    global:
                      imageRegistry: []
            "})))
            .with_shadowed_input_paths(&shadowed),
    );

    sim_assert_eq!(
        have: schema,
        want: serde_json::json!({
            "$schema": "http://json-schema.org/draft-07/schema#",
            "additionalProperties": false,
            "properties": {
                "metrics": {
                    "additionalProperties": {},
                    "properties": {
                        "agent": {
                            "additionalProperties": {},
                            "properties": {
                                "replicas": {
                                    "type": "integer"
                                }
                            },
                            "type": "object"
                        }
                    },
                    "type": "object"
                }
            },
            "type": "object"
        })
    );
}

/// A total stringification is neutral evidence about its own input; an
/// INDEPENDENT unconditional string consumer still binds. Cilium's
/// `cluster.name` is quoted into the configmap, but `replace` also consumes
/// it in validation logic — a map value fails `helm template` there.
#[test]
fn stringified_use_keeps_unconditional_string_transform_contract() {
    let src = indoc! {r#"
        {{- if gt (len (.Values.cluster.name | replace "-" "")) 30 }}
        {{- fail "cluster name too long" }}
        {{- end }}
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: config
        data:
          cluster-name: {{ .Values.cluster.name | quote }}
    "#};
    let values_yaml = indoc! {"
        cluster:
          name: default
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));

    assert!(
        schema_accepts_instance(
            &schema,
            &serde_json::json!({ "cluster": { "name": "prod" } })
        ),
        "string cluster names render: {schema}"
    );
    assert!(
        !schema_accepts_instance(
            &schema,
            &serde_json::json!({ "cluster": { "name": { "bad": true } } })
        ),
        "replace consumes the raw name, so a map fails rendering and must be rejected: {schema}"
    );
}

/// Mutually exclusive guarded uses lower their own domains under their own
/// conditions (falco's `rolearn`): the quote branch renders anything, the
/// b64enc branch fails rendering for non-strings.
#[test]
fn quote_branch_does_not_erase_b64enc_branch_contract() {
    let src = indoc! {r#"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: config
        data:
          {{- if .Values.aws.useirsa }}
          role-arn: {{ .Values.aws.rolearn | quote }}
          {{- else }}
          AWS_ROLEARN: "{{ .Values.aws.rolearn | b64enc }}"
          {{- end }}
    "#};
    let values_yaml = indoc! {r#"
        aws:
          useirsa: true
          rolearn: ""
    "#};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));

    // The b64enc contract rides its own row's condition: it binds only
    // where that branch renders. In the quote branch the same map renders
    // fine (Helm prints it as text).
    assert!(
        schema_accepts_instance(
            &schema,
            &serde_json::json!({ "aws": { "useirsa": true, "rolearn": { "bad": true } } })
        ),
        "the quote branch renders any value: {schema}"
    );
    assert!(
        !schema_accepts_instance(
            &schema,
            &serde_json::json!({ "aws": { "useirsa": false, "rolearn": { "bad": true } } })
        ),
        "the b64enc branch rejects non-strings: {schema}"
    );
    for useirsa in [true, false] {
        assert!(
            schema_accepts_instance(
                &schema,
                &serde_json::json!({ "aws": { "useirsa": useirsa, "rolearn": "arn:aws:iam::1:role/x" } })
            ),
            "strings render in both branches (useirsa={useirsa}): {schema}"
        );
    }
}

/// A `join` occurrence proves nothing about OTHER occurrences: sealed-secrets
/// also `range`s `additionalNamespaces` under its namespaced-roles flag, and
/// a scalar fails that render (`range can\'t iterate over ns-a`).
#[test]
fn join_use_does_not_erase_range_branch() {
    let src = indoc! {r#"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: config
        data:
          {{- if .Values.additionalNamespaces }}
          namespaces: {{ join "," .Values.additionalNamespaces | quote }}
          {{- end }}
        {{- if .Values.rbac.namespacedRoles }}
        {{- range .Values.additionalNamespaces }}
        ---
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: role-{{ . }}
        {{- end }}
        {{- end }}
    "#};
    let values_yaml = indoc! {"
        additionalNamespaces: []
        rbac:
          namespacedRoles: false
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));

    // `.Values.rbac.namespacedRoles` is navigated on every render, so the
    // composed document keeps the `rbac` host.
    assert!(
        schema_accepts_instance(
            &schema,
            &composed_instance(
                values_yaml,
                serde_json::json!({ "additionalNamespaces": "ns-a" })
            )
        ),
        "with namespaced roles off, only the join renders and a scalar is fine: {schema}"
    );
    for namespaces in [
        serde_json::json!(["ns-a"]),
        serde_json::json!({ "a": "ns-a" }),
    ] {
        assert!(
            schema_accepts_instance(
                &schema,
                &serde_json::json!({
                    "rbac": { "namespacedRoles": true },
                    "additionalNamespaces": namespaces
                })
            ),
            "range iterates lists and maps: {schema}"
        );
    }
    // `range` cannot iterate a string, so `namespacedRoles=true` plus a
    // string fails `helm template` and the guarded iterable domain rejects
    // the combination.
    assert!(
        !schema_accepts_instance(
            &schema,
            &serde_json::json!({
                "rbac": { "namespacedRoles": true },
                "additionalNamespaces": "ns-a"
            })
        ),
        "inside the ranged branch a string cannot iterate: {schema}"
    );
    // Integer counts iterate (Helm's `--set` channel delivers int64; a
    // JSON Schema cannot separate that from the failing values-file
    // float64 spelling, so the renderable channel wins); non-integral
    // numbers fail in every channel.
    for count in [2, 0, -1] {
        assert!(
            schema_accepts_instance(
                &schema,
                &serde_json::json!({
                    "rbac": { "namespacedRoles": true },
                    "additionalNamespaces": count
                })
            ),
            "range iterates integer counts: {schema}"
        );
    }
    assert!(
        !schema_accepts_instance(
            &schema,
            &serde_json::json!({
                "rbac": { "namespacedRoles": true },
                "additionalNamespaces": 2.5
            })
        ),
        "non-integral numbers cannot iterate: {schema}"
    );
    assert!(
        schema_accepts_instance(
            &schema,
            &serde_json::json!({ "rbac": { "namespacedRoles": true } })
        ),
        "an absent collection ranges zero times and renders: {schema}"
    );
}

/// printf's format parameter is a real Go `string`: NFS provisioner calls
/// `printf .Values.storageClass.provisionerName`, and a non-string value
/// fails template evaluation (`wrong type for value; expected string`).
#[test]
fn dynamic_printf_format_requires_string() {
    let src = indoc! {r"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: {{ printf .Values.storageClass.provisionerName }}
    "};
    let values_yaml = indoc! {"
        storageClass:
          provisionerName: cluster.local/provisioner
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));

    assert!(
        schema_accepts_instance(
            &schema,
            &serde_json::json!({ "storageClass": { "provisionerName": "x/y" } })
        ),
        "string formats evaluate: {schema}"
    );
    assert!(
        !schema_accepts_instance(
            &schema,
            &serde_json::json!({ "storageClass": { "provisionerName": 7 } })
        ),
        "a non-string printf format fails template evaluation and must be rejected: {schema}"
    );
}

/// Case mapping has two independent effects at an unquoted YAML slot: its
/// operand must be a Go string, and token-breaking characters survive the
/// mapping unchanged. Keeping only the former loses the sink's lexical
/// language (kube-state-metrics' probe schemes).
#[test]
fn case_mapping_keeps_the_plain_slot_language_beside_its_string_contract() {
    let src = indoc! {r"
        apiVersion: v1
        kind: Pod
        metadata:
          name: test
        spec:
          containers:
            - name: test
              image: test
              livenessProbe:
                httpGet:
                  path: /
                  port: 8080
                  scheme: {{ upper .Values.scheme }}
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some("scheme: http\n"));

    for value in ["http", "HTTPS"] {
        let instance = serde_json::json!({ "scheme": value });
        assert!(
            schema_accepts_instance(&schema, &instance),
            "ordinary string schemes render: instance={instance}; schema={schema}"
        );
    }
    let multiline = ['a', '\n', 'b'].into_iter().collect::<String>();
    for value in ["a: b", "a #b", multiline.as_str(), "&anchor"] {
        let instance = serde_json::json!({ "scheme": value });
        assert!(
            !schema_accepts_instance(&schema, &instance),
            "case mapping preserves token-breaking text: instance={instance}; schema={schema}"
        );
    }
    let non_string = serde_json::json!({ "scheme": 7 });
    assert!(
        !schema_accepts_instance(&schema, &non_string),
        "upper still requires a Go string: schema={schema}"
    );
}

/// Helm's `lookup` consumes four strings but returns external cluster state;
/// its result is not any argument's identity. A literal `default` therefore
/// keeps every falsy source spelling out of the strict argument lane
/// (Cilium's configurable cluster-info name and namespace).
#[test]
fn lookup_argument_contract_preserves_a_literal_defaults_falsy_escape() {
    let helpers = indoc! {r#"
        {{- define "lookup-name" -}}
        {{- $name := default "cluster-info" .Values.name -}}
        {{- $configmap := lookup "v1" "ConfigMap" "default" $name -}}
        {{- if $configmap -}}
        {{- get $configmap.data "value" -}}
        {{- else -}}
        fallback
        {{- end -}}
        {{- end -}}
    "#};
    let src = indoc! {r#"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: test
        data:
          value: {{ include "lookup-name" . | quote }}
    "#};
    let schema = schema_for_values_yaml(parse_ir_with_helpers(src, helpers), Some("name: \"\"\n"));

    for value in [
        serde_json::json!("custom"),
        serde_json::json!(""),
        serde_json::json!(false),
        serde_json::json!(0),
        serde_json::json!([]),
        serde_json::json!({}),
        serde_json::json!(null),
    ] {
        let instance = serde_json::json!({ "name": value });
        assert!(
            schema_accepts_instance(&schema, &instance),
            "lookup receives the literal fallback for every falsy source: instance={instance}; schema={schema}"
        );
    }
    for value in [
        serde_json::json!([1]),
        serde_json::json!({ "bad": true }),
        serde_json::json!(7),
        serde_json::json!(true),
    ] {
        let instance = serde_json::json!({ "name": value });
        assert!(
            !schema_accepts_instance(&schema, &instance),
            "truthy non-strings reach lookup and abort: instance={instance}; schema={schema}"
        );
    }
}

/// printf's data parameters render through any verb (Go fmt embeds
/// mismatches in the output): airflow formats `dags.gitSync.subPath` with a
/// literal format and Helm renders `subPath: 7` as `%!s(int64=7)`.
#[test]
fn printf_data_argument_accepts_any_value_through_helper_sink() {
    let helpers = indoc! {r#"
        {{- define "airflow_dags" -}}
        {{- printf "%s/dags/repo/%s" .Values.airflowHome .Values.dags.gitSync.subPath -}}
        {{- end -}}
    "#};
    let src = indoc! {r#"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: config
        data:
          dags_folder: {{ include "airflow_dags" . }}
    "#};
    let values_yaml = indoc! {r#"
        airflowHome: /opt/airflow
        dags:
          gitSync:
            subPath: ""
    "#};
    let schema = schema_for_values_yaml(parse_ir_with_helpers(src, helpers), Some(values_yaml));

    for sub_path in [
        serde_json::json!("repo/dags"),
        serde_json::json!(7),
        serde_json::json!(null),
    ] {
        let instance = serde_json::json!({
            "airflowHome": "/opt/airflow",
            "dags": { "gitSync": { "subPath": sub_path } }
        });
        assert!(
            schema_accepts_instance(&schema, &instance),
            "printf data arguments render any value: instance={instance}; schema={schema}"
        );
    }
}

/// `%s` is total as a formatter argument, but when its diagnostic output
/// opens an unquoted YAML token a non-string or missing value corrupts that
/// token. The same formatter inside explicit quotes remains total
/// (Sealed Secrets' unquoted image registry).
#[test]
fn token_initial_printf_string_argument_uses_the_plain_slot_language() {
    let src = indoc! {r#"
        apiVersion: v1
        kind: Pod
        metadata:
          name: test
          annotations:
            quoted: "{{ printf "%s/suffix" .Values.quoted }}"
            piped: {{ printf "%s/suffix" .Values.piped | quote }}
        spec:
          containers:
            - name: test
              image: {{ printf "%s/repository:tag" .Values.registry }}
    "#};
    let values_yaml = indoc! {"
        registry: registry.example.com
        quoted: value
        piped: value
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));

    for registry in [
        serde_json::json!("registry.example.com"),
        serde_json::json!("true"),
        serde_json::json!("&anchor"),
    ] {
        let instance = serde_json::json!({ "registry": registry, "quoted": 7, "piped": ["any"] });
        assert!(
            schema_accepts_instance(&schema, &instance),
            "a valid leading string and quoted diagnostics both render: \
             instance={instance}; schema={schema}"
        );
    }
    for registry in [
        serde_json::json!(7),
        serde_json::json!(false),
        serde_json::json!([]),
        serde_json::json!(null),
        serde_json::json!("a: b"),
    ] {
        let instance =
            serde_json::json!({ "registry": registry, "quoted": "value", "piped": "value" });
        assert!(
            !schema_accepts_instance(&schema, &instance),
            "a token-opening %s must receive structurally safe string text: \
             instance={instance}; schema={schema}"
        );
    }
    assert!(
        !schema_accepts_instance(&schema, &serde_json::json!({ "quoted": "value" })),
        "a missing token-opening argument renders an invalid fmt diagnostic: {schema}"
    );
}

/// A later encoder consumes the complete formatter result, so the raw `%s` operands no longer
/// reach the YAML slot and remain open to every value Helm's `printf` accepts.
#[test]
fn encoded_printf_result_clears_plain_slot_operand_contracts() {
    let src = indoc! {r#"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: test
        data:
          token: {{ printf "%s:%s" .Values.user .Values.pass | b64enc }}
    "#};
    let values_yaml = indoc! {"
        user: alice
        pass: secret
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));

    for overrides in [
        serde_json::json!({ "user": null }),
        serde_json::json!({ "pass": null }),
        serde_json::json!({ "user": { "name": "alice" }, "pass": ["secret"] }),
    ] {
        let instance = composed_instance(values_yaml, overrides);
        assert!(
            schema_accepts_instance(&schema, &instance),
            "the encoded formatter result is safe for every raw operand: \
             instance={instance}; schema={schema}"
        );
    }
}

/// A token-opening formatter constrains only the operand selected by `default`.
/// A dormant fallback may therefore be absent even though the same absence corrupts YAML when the
/// fallback is selected.
#[test]
fn printf_plain_slot_contract_follows_default_operand_selection() {
    let src = indoc! {r#"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: test
        data:
          token: {{ printf "%s-x" (.Values.primary | default .Values.fallback) }}
    "#};
    let values_yaml = indoc! {"
        primary: primary
        fallback: fallback
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));

    for (overrides, want, label) in [
        (
            serde_json::json!({ "fallback": null }),
            true,
            "a live primary leaves the deleted fallback dormant",
        ),
        (
            serde_json::json!({ "primary": null, "fallback": "fallback" }),
            true,
            "the selected fallback supplies safe text",
        ),
        (
            serde_json::json!({ "primary": null, "fallback": null }),
            false,
            "a missing selected fallback emits an invalid leading diagnostic",
        ),
    ] {
        let instance = composed_instance(values_yaml, overrides);
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "formatter selection ({label}): instance={instance}; want={want}; schema={schema}"
        );
    }
}

/// A nested `default` primary carries every earlier selection predicate to
/// the final fallback, regardless of whether the chain uses pipeline or call
/// syntax.
#[test]
fn printf_plain_slot_contract_follows_chained_default_selection() {
    let values_yaml = indoc! {"
        x: set
        y: fally
        z: fallz
    "};
    for expression in [
        ".Values.x | default .Values.y | default .Values.z",
        "default .Values.z (default .Values.y .Values.x)",
    ] {
        let src = formatdoc! {r#"
            apiVersion: v1
            kind: ConfigMap
            metadata:
              name: test
            data:
              token: {{{{ printf "%s-x" ({expression}) }}}}
        "#};
        let schema = schema_for_values_yaml(parse_ir(&src), Some(values_yaml));
        for (overrides, want, label) in [
            (
                serde_json::json!({ "z": null }),
                true,
                "a live first operand leaves the final fallback dormant",
            ),
            (
                serde_json::json!({ "x": null, "y": null, "z": "selected" }),
                true,
                "the selected final fallback supplies safe text",
            ),
            (
                serde_json::json!({ "x": null, "y": null, "z": null }),
                false,
                "a missing selected final fallback corrupts the YAML token",
            ),
        ] {
            let instance = composed_instance(values_yaml, overrides);
            assert!(
                schema_accepts_instance(&schema, &instance) == want,
                "chained formatter selection ({label}): expression={expression}; \
                 instance={instance}; want={want}; schema={schema}"
            );
        }
    }
}

#[test]
fn opaque_formatter_default_primary_keeps_fallback_consumers_conditional() {
    let values_yaml = indoc! {"
        alpha: seta
        beta: setb
        omega: fallo
    "};
    for (expression, selected_number_accepted, raw_falsy_number_accepted) in [
        (
            r#"printf "%s" .Values.alpha | default .Values.omega | b64enc"#,
            false,
            true,
        ),
        (
            r#"printf "%q" .Values.alpha | default .Values.omega | b64enc"#,
            true,
            true,
        ),
        (
            r#"printf "%s" .Values.alpha | default .Values.omega | trunc 5"#,
            false,
            false,
        ),
        (
            r#"printf "%s" .Values.alpha | default .Values.omega | sha256sum"#,
            false,
            true,
        ),
        (
            r#"printf "%s" .Values.alpha | default .Values.omega | quote"#,
            true,
            true,
        ),
        (
            r#"printf "%s" .Values.alpha | default .Values.omega | trimSuffix "-x""#,
            false,
            false,
        ),
        (
            r#"(printf "%s" .Values.alpha) | default .Values.omega | b64enc"#,
            false,
            true,
        ),
        (
            r#"default .Values.omega (printf "%s" .Values.alpha) | b64enc"#,
            false,
            true,
        ),
        (
            r#"printf "%s" .Values.alpha | default .Values.beta | default .Values.omega | b64enc"#,
            false,
            true,
        ),
    ] {
        let schema = schema_for_formatter_default_expression(expression, values_yaml);
        for (overrides, want, label) in [
            (
                serde_json::json!({ "omega": null }),
                true,
                "deleted dormant fallback",
            ),
            (
                serde_json::json!({ "omega": 7 }),
                true,
                "non-string dormant fallback",
            ),
            (
                serde_json::json!({ "omega": false }),
                true,
                "falsy dormant fallback",
            ),
            (
                serde_json::json!({ "alpha": false, "beta": "", "omega": 7 }),
                raw_falsy_number_accepted,
                "raw-falsy formatter operand renders a truthy string",
            ),
            (
                serde_json::json!({ "alpha": "", "beta": "", "omega": "selected" }),
                true,
                "selected string fallback",
            ),
            (
                serde_json::json!({ "alpha": "", "beta": "", "omega": 7 }),
                selected_number_accepted,
                "selected numeric fallback follows the recoverable selection boundary",
            ),
        ] {
            let instance = composed_instance(values_yaml, overrides);
            assert!(
                schema_accepts_instance(&schema, &instance) == want,
                "opaque formatter fallback ({label}): expression={expression}; \
                 instance={instance}; want={want}; schema={schema}"
            );
        }
    }
}

fn schema_for_formatter_default_expression(expression: &str, values_yaml: &str) -> Value {
    let src = formatdoc! {r"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: test
        data:
          token: {{{{ {expression} }}}}
    "};
    schema_for_values_yaml(parse_ir(&src), Some(values_yaml))
}

#[test]
fn literal_default_primaries_have_exact_fallback_reachability() {
    let values_yaml = indoc! {"
        choose: false
        omega: fallo
    "};
    for (primary, selected) in [
        ("\"\"", true),
        ("\"x\"", false),
        (r#"ternary "" "" .Values.choose"#, true),
        (r#"ternary "x" "y" .Values.choose"#, false),
    ] {
        let src = formatdoc! {r"
            apiVersion: v1
            kind: ConfigMap
            metadata:
              name: test
            data:
              token: {{{{ ({primary}) | default .Values.omega | b64enc }}}}
        "};
        let schema = schema_for_values_yaml(parse_ir(&src), Some(values_yaml));
        for (overrides, want, label) in [
            (
                serde_json::json!({ "omega": null }),
                !selected,
                "deleted fallback",
            ),
            (
                serde_json::json!({ "omega": 7 }),
                !selected,
                "numeric fallback",
            ),
            (
                serde_json::json!({ "omega": "selected" }),
                true,
                "string fallback",
            ),
        ] {
            let instance = composed_instance(values_yaml, overrides);
            assert!(
                schema_accepts_instance(&schema, &instance) == want,
                "literal default primary ({label}): primary={primary}; instance={instance}; \
                 want={want}; schema={schema}"
            );
        }
    }
}

#[test]
fn dead_literal_fallback_keeps_eager_argument_failures() {
    let src = indoc! {r#"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: test
        data:
          token: {{ "live" | default (required "omega is required" .Values.omega) | b64enc }}
    "#};
    let values_yaml = "omega: fallback\n";
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));

    assert!(!schema_accepts_instance(
        &schema,
        &composed_instance(values_yaml, serde_json::json!({ "omega": null }))
    ));
    assert!(schema_accepts_instance(
        &schema,
        &composed_instance(values_yaml, serde_json::json!({ "omega": 7 }))
    ));
}

#[test]
fn identity_default_chain_keeps_exact_final_fallback_selection() {
    let src = indoc! {r"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: test
        data:
          token: {{ .Values.alpha | default .Values.beta | default .Values.omega | b64enc }}
    "};
    let values_yaml = indoc! {"
        alpha: seta
        beta: setb
        omega: fallo
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));

    for (overrides, want, label) in [
        (
            serde_json::json!({ "omega": 7 }),
            true,
            "a live first identity leaves the numeric fallback dormant",
        ),
        (
            serde_json::json!({ "alpha": "", "beta": "", "omega": "selected" }),
            true,
            "the final identity fallback supplies valid text",
        ),
        (
            serde_json::json!({ "alpha": "", "beta": "", "omega": 7 }),
            false,
            "the selected numeric fallback violates the string consumer",
        ),
    ] {
        let instance = composed_instance(values_yaml, overrides);
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "exact identity selection ({label}): instance={instance}; want={want}; schema={schema}"
        );
    }
}

/// A helper-local fallback keeps the formatter contract on the arm that
/// actually supplies its token-opening `%s`. A dormant fallback remains
/// open even though the same helper rejects it when selected (Airflow's
/// image repository selection).
#[test]
fn helper_printf_keeps_its_selected_token_initial_argument() {
    let helpers = indoc! {r#"
        {{- define "image" -}}
        {{- $repository := .Values.primary | default .Values.fallback -}}
        {{- printf "%s:tag" $repository -}}
        {{- end -}}
    "#};
    let src = indoc! {r#"
        apiVersion: v1
        kind: Pod
        metadata:
          name: test
        spec:
          containers:
            - name: test
              image: {{ include "image" . }}
    "#};
    let schema = schema_for_values_yaml(
        parse_ir_with_helpers(src, helpers),
        Some(indoc! {"
            primary: ''
            fallback: repository
        "}),
    );

    for (instance, want, label) in [
        (
            serde_json::json!({ "primary": "", "fallback": "repository" }),
            true,
            "the fallback string is selected",
        ),
        (
            serde_json::json!({ "primary": "", "fallback": "a #b" }),
            true,
            "a selected comment leaves an ordinary string prefix",
        ),
        (
            serde_json::json!({ "primary": "", "fallback": "true #b" }),
            false,
            "a selected comment leaves a Boolean prefix",
        ),
        (
            serde_json::json!({ "primary": "", "fallback": {} }),
            true,
            "a selected empty mapping formats as plain map text",
        ),
        (
            serde_json::json!({ "primary": "", "fallback": { "key": {} } }),
            true,
            "a selected bounded mapping formats as plain map text",
        ),
        (
            serde_json::json!({ "primary": "", "fallback": { "a: b": {} } }),
            false,
            "a mapping key can still break the formatted token",
        ),
        (
            serde_json::json!({ "primary": "repository", "fallback": 7 }),
            true,
            "a live primary leaves the fallback dormant",
        ),
        (
            serde_json::json!({ "primary": "", "fallback": 7 }),
            false,
            "a selected numeric fallback emits an invalid diagnostic",
        ),
        (
            serde_json::json!({ "primary": "" }),
            false,
            "a missing selected fallback emits an invalid diagnostic",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "selected formatter arm ({label}): instance={instance}; want={want}; schema={schema}"
        );
    }
}

#[test]
fn helper_prefix_branch_scopes_the_token_opening_formatter_argument() {
    let helpers = indoc! {r#"
        {{- define "image" -}}
        {{- $registry := default .Values.image.registry .Values.global.registry -}}
        {{- $repository := .Values.image.repository -}}
        {{- if $registry -}}
          {{- printf "%s/%s:tag" $registry $repository -}}
        {{- else -}}
          {{- printf "%s:tag" $repository -}}
        {{- end -}}
        {{- end -}}
    "#};
    let src = indoc! {r#"
        apiVersion: v1
        kind: Pod
        metadata:
          name: test
        spec:
          containers:
            - name: test
              image: {{ include "image" . }}
    "#};
    let schema = schema_for_values_yaml(
        parse_ir_with_helpers(src, helpers),
        Some(indoc! {"
            global:
              registry: docker.io
            image:
              registry: ''
              repository: repo
        "}),
    );

    for (instance, want, label) in [
        (
            serde_json::json!({
                "global": { "registry": "docker.io" },
                "image": { "registry": 7, "repository": 7 }
            }),
            true,
            "the global prefix keeps both local operands away from token opening",
        ),
        (
            serde_json::json!({
                "global": { "registry": "" },
                "image": { "registry": "", "repository": 7 }
            }),
            false,
            "the prefix-free branch makes repository token-opening",
        ),
        (
            serde_json::json!({
                "global": { "registry": "" },
                "image": { "registry": 7, "repository": "repo" }
            }),
            false,
            "the selected local registry opens the prefixed branch",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "formatter branch ({label}): instance={instance}; want={want}; schema={schema}"
        );
    }
}

#[test]
fn quoting_helper_printf_output_clears_its_plain_slot_contract() {
    let helpers = indoc! {r#"
        {{- define "image" -}}
        {{- printf "%s:tag" .Values.repository -}}
        {{- end -}}
    "#};
    let src = indoc! {r#"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: test
        data:
          image: {{ include "image" . | quote }}
    "#};
    let schema = schema_for_values_yaml(
        parse_ir_with_helpers(src, helpers),
        Some("repository: example.com/repository\n"),
    );

    sim_assert_eq!(
        have: schema,
        want: serde_json::json!({
            "$schema": "http://json-schema.org/draft-07/schema#",
            "additionalProperties": false,
            "properties": {
                "repository": {}
            },
            "type": "object"
        })
    );
}

/// Chart repro (sealed-secrets `additionalNamespaces`): a declared-list
/// value joined under a self-truthy guard renders map and scalar values
/// through Sprig's singleton fallback, so the declared array type must not
/// reject them.
#[test]
fn self_guarded_join_of_declared_list_accepts_any_input() {
    let src = indoc! {r#"
        apiVersion: apps/v1
        kind: Deployment
        spec:
          template:
            spec:
              containers:
                - name: controller
                  args:
                    {{- if .Values.additionalNamespaces }}
                    - --additional-namespaces
                    - {{ join "," .Values.additionalNamespaces | quote }}
                    {{- end }}
    "#};
    let values_yaml = indoc! {"
        additionalNamespaces: []
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));

    for probe in [
        serde_json::json!(["ns-a", "ns-b"]),
        serde_json::json!("ns-a"),
        serde_json::json!({ "k": "v" }),
    ] {
        let instance = serde_json::json!({ "additionalNamespaces": probe });
        assert!(
            schema_accepts_instance(&schema, &instance),
            "strslice converts any joined input: instance={instance}; schema={schema}"
        );
    }
}

/// Chart repro (grafana `sidecar.alerts.skipTlsVerify`): an undeclared
/// value quoted into a typed string sink (`env[].value`) under a `with`
/// guard renders any type, so the sink typing must not flow back through the
/// stringification.
#[test]
fn with_guarded_quote_into_string_sink_accepts_any_input() {
    let src = indoc! {r"
        apiVersion: apps/v1
        kind: Deployment
        spec:
          template:
            spec:
              containers:
                - name: sidecar
                  env:
                    {{- with .Values.sidecar.skipTlsVerify }}
                    - name: SKIP_TLS_VERIFY
                      value: {{ quote . }}
                    {{- end }}
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some("sidecar: {}\n"));

    for probe in [
        serde_json::json!(true),
        serde_json::json!("true"),
        serde_json::json!({ "k": "v" }),
        serde_json::json!([1, 2]),
    ] {
        let instance = serde_json::json!({ "sidecar": { "skipTlsVerify": probe } });
        assert!(
            schema_accepts_instance(&schema, &instance),
            "quote erases input shape at the env sink: instance={instance}; schema={schema}"
        );
    }
}

/// `htpasswd` bcrypt-hashes two Go strings, so a non-string member value
/// aborts rendering — including through a destructured range and a helper
/// include (prometheus-pushgateway's `basicAuthUsers`).
#[test]
fn htpasswd_operands_require_strings() {
    let src = indoc! {r#"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: test
        data:
          direct: {{ htpasswd "" .Values.adminPassword | quote }}
          config: |
            {{- include "repro.webConfiguration" . | nindent 4 }}
    "#};
    let helpers = indoc! {r#"
        {{- define "repro.webConfiguration" -}}
        basic_auth_users:
        {{- range $k, $v := .Values.basicAuthUsers }}
          {{ $k }}: {{ htpasswd "" $v | trimPrefix ":" }}
        {{- end }}
        {{- end -}}
    "#};
    let values_yaml = indoc! {"
        adminPassword: hunter2
        basicAuthUsers: {}
    "};
    let schema = schema_for_values_yaml(parse_ir_with_helpers(src, helpers), Some(values_yaml));

    // Cases compose over the declared defaults: the direct `htpasswd` reads
    // `adminPassword` on every render and aborts on a nil operand.
    for (overrides, want) in [
        (serde_json::json!({ "adminPassword": 7 }), false),
        (serde_json::json!({ "adminPassword": "ok" }), true),
        (
            serde_json::json!({ "basicAuthUsers": { "admin": 7 } }),
            false,
        ),
        (
            serde_json::json!({ "basicAuthUsers": { "admin": { "bad": 1 } } }),
            false,
        ),
        (
            serde_json::json!({ "basicAuthUsers": { "admin": "hunter2" } }),
            true,
        ),
    ] {
        let instance = composed_instance(values_yaml, overrides);
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "htpasswd consumes Go strings only: instance={instance}; schema={schema}"
        );
    }
}

/// Sprig's checksum family hashes a typed Go string, so a truthy non-string
/// reaching `sha256sum` aborts rendering — including a ranged member picked
/// through a local `default ""` selection, where only the truthy lane hashes
/// and every falsy spelling escapes to `nopass` (bitnami-redis' ACL users).
#[test]
fn checksum_operands_require_strings_through_ranged_default_selection() {
    let src = indoc! {r#"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: test
        data:
          direct: {{ sha256sum .Values.seed | quote }}
          users.acl: |-
            {{- range .Values.users }}
            {{- $password := .password | default "" }}
            user {{ .username }} {{ if $password }}#{{ sha256sum $password }}{{ else }}nopass{{ end }}
            {{- end }}
    "#};
    let values_yaml = indoc! {"
        seed: audit
        users: []
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));

    // Cases compose over the declared defaults: the direct `sha256sum` reads
    // `seed` on every render and aborts on a nil operand.
    for (overrides, want, label) in [
        (serde_json::json!({ "seed": 7 }), false, "direct numeric"),
        (serde_json::json!({ "seed": "ok" }), true, "direct string"),
        (
            serde_json::json!({ "users": [{ "username": "u", "password": 7 }] }),
            false,
            "truthy numeric member",
        ),
        (
            serde_json::json!({ "users": [{ "username": "u", "password": "s3cret" }] }),
            true,
            "string member",
        ),
        (
            serde_json::json!({ "users": [{ "username": "u" }] }),
            true,
            "absent member selects nopass",
        ),
        (
            serde_json::json!({ "users": [{ "username": "u", "password": 0 }] }),
            true,
            "falsy member escapes the hash",
        ),
    ] {
        let instance = composed_instance(values_yaml, overrides);
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "checksum operand {label}: instance={instance}; schema={schema}"
        );
    }
}

/// The full bitnami-redis ACL shape: the whole document rides an
/// include-result gate (`if (include "redis.createConfigmap" .)`), which
/// decodes through the helper's literal dispatch (`{{- true -}}` under
/// `empty .Values.existingConfigmap`) instead of degrading to an
/// undecodable marker that would drop the member capture; the secret lane
/// and the default-user hash ride includes with no values identity.
#[test]
fn checksum_member_contract_survives_include_result_document_gate() {
    let src = indoc! {r#"
        {{- if (include "redis.createConfigmap" .) }}
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: test
        data:
          users.acl: |-
            {{- if .Values.auth.acl.enabled}}
            {{- $password := include "redis.password" . }}
            user default on {{ if $password}}#{{ sha256sum $password}}{{ else }}nopass{{ end }} ~* &* +@all
            {{- if .Values.auth.acl.users -}}
            {{- $userSecret := .Values.auth.acl.userSecret -}}
            {{- range .Values.auth.acl.users }}
            {{- $userPassword := .password | default "" }}
            {{- if $userSecret }}
            {{- $secretPassword := include "common.secrets.get" (dict "secret" $userSecret "key" .username "context" $) }}
            user {{ .username }} {{ default "on" .enabled }} {{ if $secretPassword }}#{{ sha256sum $secretPassword }}{{ else }}nopass{{ end }} {{ default "~*" .keys }}
            {{- else }}
            user {{ .username }} {{ default "on" .enabled }} {{ if $userPassword }}#{{ sha256sum $userPassword }}{{ else }}nopass{{ end }} {{ default "~*" .keys }}
            {{- end }}
            {{- end }}
            {{- end }}
            {{- end }}
        {{- end }}
    "#};
    let helpers = indoc! {r#"
        {{- define "redis.createConfigmap" -}}
        {{- if empty .Values.existingConfigmap }}
            {{- true -}}
        {{- end -}}
        {{- end -}}
        {{- define "redis.password" -}}
        {{- .Values.auth.password -}}
        {{- end -}}
        {{- define "common.secrets.get" -}}
        secret
        {{- end -}}
    "#};
    let schema = schema_for_values_yaml(
        parse_ir_with_helpers(src, helpers),
        Some(indoc! {r#"
            existingConfigmap: ""
            auth:
              password: ""
              acl:
                enabled: false
                users: []
                userSecret: ""
        "#}),
    );
    for (instance, want, label) in [
        (
            serde_json::json!({
                "auth": { "acl": { "enabled": true, "users": [{ "username": "u", "password": 7 }] } }
            }),
            false,
            "numeric password under the live gate",
        ),
        (
            serde_json::json!({
                "auth": { "acl": { "enabled": true, "users": [{ "username": "u", "password": "ok" }] } }
            }),
            true,
            "string password",
        ),
        (
            serde_json::json!({
                "existingConfigmap": "external",
                "auth": { "acl": { "enabled": true, "users": [{ "username": "u", "password": 7 }] } }
            }),
            true,
            "numeric password behind the dead include gate",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "include-gated checksum member {label}: instance={instance}; schema={schema}"
        );
    }
}

/// The checksum contract survives OUTER branch guards around the range: the
/// selection's per-member truthiness cannot become a root guard, so it scopes
/// the member requirement to truthy values instead, and the enclosing `if`
/// chain lowers as the implication's outer guards (bitnami-redis nests the
/// ACL users range under `acl.enabled` and `acl.users`).
#[test]
fn checksum_member_contract_survives_outer_branch_guards() {
    let src = indoc! {r#"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: test
        data:
          users.acl: |-
            {{- if .Values.auth.acl.enabled}}
            {{- if .Values.auth.acl.users -}}
            {{- $userSecret := .Values.auth.acl.userSecret -}}
            {{- range .Values.auth.acl.users }}
            {{- $userPassword := .password | default "" }}
            {{- if $userSecret }}
            user {{ .username }} secretlane
            {{- else }}
            user {{ .username }} {{ default "on" .enabled }} {{ if $userPassword }}#{{ sha256sum $userPassword }}{{ else }}nopass{{ end }} {{ default "~*" .keys }}
            {{- end }}
            {{- end }}
            {{- end }}
            {{- end }}
    "#};
    let schema = schema_for_values_yaml(
        parse_ir(src),
        Some(indoc! {r#"
            auth:
              acl:
                enabled: false
                users: []
                userSecret: ""
        "#}),
    );

    for (instance, want, label) in [
        (
            serde_json::json!({
                "auth": { "acl": { "enabled": true, "users": [{ "username": "u", "password": 7 }] } }
            }),
            false,
            "numeric password under live guards",
        ),
        (
            serde_json::json!({
                "auth": { "acl": { "enabled": true, "users": [{ "username": "u", "password": "ok" }] } }
            }),
            true,
            "string password under live guards",
        ),
        (
            serde_json::json!({
                "auth": { "acl": { "enabled": true, "users": [{ "username": "u", "password": 0 }] } }
            }),
            true,
            "falsy password escapes to nopass",
        ),
        (
            serde_json::json!({
                "auth": { "acl": { "enabled": false, "users": [{ "username": "u", "password": 7 }] } }
            }),
            true,
            "numeric password in the dead arm",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "guarded checksum member {label}: instance={instance}; schema={schema}"
        );
    }
}

/// A direct `tpl` program input keeps its Go string contract through a
/// `default` selection chain: `tpl` parses the RAW value before any
/// truthiness selection runs, so a map aborts rendering even when its
/// Helm-falsy spelling would select a later arm (oauth2-proxy's
/// `tpl .Values.image.registry $ | default (tpl .Values.global.imageRegistry $) | default "quay.io"`).
#[test]
fn tpl_program_contract_survives_default_chain() {
    let src = indoc! {r#"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: test
        data:
          image: "{{ tpl .Values.image.registry $ | default (tpl .Values.global.imageRegistry $) | default "quay.io" }}/proxy"
    "#};
    let values_yaml = indoc! {r#"
        image:
          registry: ""
        global:
          imageRegistry: ""
    "#};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));

    // Cases compose over the declared defaults: both `image` and `global`
    // are navigated on every render.
    for (overrides, want) in [
        (serde_json::json!({ "image": { "registry": {} } }), false),
        (serde_json::json!({ "image": { "registry": ["x"] } }), false),
        (
            serde_json::json!({ "image": { "registry": "quay.io" } }),
            true,
        ),
        (serde_json::json!({ "image": { "registry": "" } }), true),
        // The eagerly evaluated fallback arm parses its own program too
        (
            serde_json::json!({ "global": { "imageRegistry": {} } }),
            false,
        ),
        (
            serde_json::json!({
                "image": { "registry": "" },
                "global": { "imageRegistry": 7 },
            }),
            false,
        ),
        (
            serde_json::json!({
                "image": { "registry": "quay.io" },
                "global": { "imageRegistry": 7 },
            }),
            false,
        ),
        (
            serde_json::json!({ "global": { "imageRegistry": "ghcr.io" } }),
            true,
        ),
    ] {
        let instance = composed_instance(values_yaml, overrides);
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "tpl parses raw program text before default selection: \
             instance={instance}; schema={schema}"
        );
    }
}

/// A string transform reached only after the operand's own truthiness check
/// constrains the live arm, not the falsy fallback arm.
#[test]
fn self_guarded_string_transform_keeps_every_falsy_spelling() {
    let helpers = indoc! {r#"
        {{- define "repro.rawName" -}}
        {{- .Values.nameOverride | trunc 63 | trimSuffix "-" }}
        {{- end }}
        {{- define "repro.name" -}}
        {{- if .Values.nameOverride }}
        {{- include "repro.rawName" . }}
        {{- else }}
        fallback
        {{- end }}
        {{- end }}
        {{- define "repro.addr" -}}
        {{- with .Values.redis }}
        {{- ternary (printf "%s:6379" (include "repro.name" $)) .external (eq .type "internal") }}
        {{- end }}
        {{- end }}
    "#};
    let src = indoc! {r#"
        {{- if .Values.enabled }}
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: repro
        data:
          endpoint: {{ include "repro.addr" . | quote }}
        {{- end }}
    "#};
    let values_yaml = indoc! {"
        enabled: true
        nameOverride: ''
        redis:
          type: internal
          external: redis.example.com
    "};
    let schema = schema_for_values_yaml(parse_ir_with_helpers(src, helpers), Some(values_yaml));

    for (value, want, label) in [
        (
            serde_json::json!({}),
            true,
            "an empty mapping takes the fallback",
        ),
        (
            serde_json::json!([]),
            true,
            "an empty list takes the fallback",
        ),
        (serde_json::json!(null), true, "null takes the fallback"),
        (
            serde_json::json!("custom"),
            true,
            "a string reaches the transform",
        ),
        (
            serde_json::json!({ "member": "value" }),
            false,
            "a truthy mapping reaches the string transform",
        ),
    ] {
        let instance = composed_instance(
            values_yaml,
            serde_json::json!({ "enabled": true, "nameOverride": value }),
        );
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "{label}: instance={instance}; schema={schema}"
        );
    }
}

#[test]
fn default_before_string_transform_keeps_falsy_primary_spellings() {
    let direct = indoc! {r#"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: {{ default "fallback" .Values.nameOverride | trunc 63 | trimSuffix "-" }}
    "#};
    let values_yaml = indoc! {"
        nameOverride: ''
    "};
    let schema = schema_for_values_yaml(parse_ir(direct), Some(values_yaml));

    for (value, want, label) in [
        (serde_json::json!(false), true, "false selects the fallback"),
        (serde_json::json!(0), true, "zero selects the fallback"),
        (
            serde_json::json!([]),
            true,
            "an empty list selects the fallback",
        ),
        (
            serde_json::json!({}),
            true,
            "an empty mapping selects the fallback",
        ),
        (
            serde_json::json!("custom"),
            true,
            "a string reaches the transform",
        ),
        (
            serde_json::json!({ "member": "value" }),
            false,
            "a truthy mapping reaches the string transform",
        ),
    ] {
        let instance = composed_instance(values_yaml, serde_json::json!({ "nameOverride": value }));
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "{label}: instance={instance}; schema={schema}"
        );
    }
}

/// tempo's jaeger receivers: `regexSplit ":" . -1 | last` extracts the
/// port suffix of an endpoint string into a Service port slot, so the
/// accepted endpoints are strings whose LAST `:`-segment is numeric.
#[test]
fn split_last_segment_into_numeric_slot_requires_numeric_suffix() {
    let src = indoc! {r#"
        apiVersion: v1
        kind: Service
        metadata:
          name: test
        spec:
          ports:
            {{- with .Values.endpoint }}
            - name: grpc
              port: {{ regexSplit ":" . -1 | last }}
              protocol: TCP
            {{- end }}
    "#};
    let schema = schema_for_values_yaml(parse_ir(src), Some("endpoint: ~\n"));
    for (instance, want) in [
        (serde_json::json!({ "endpoint": "0.0.0.0:audit" }), false),
        (serde_json::json!({ "endpoint": "0.0.0.0:14250" }), true),
        (serde_json::json!({ "endpoint": null }), true),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "the endpoint's port suffix feeds an integer slot: \
             instance={instance}; schema={schema}"
        );
    }
}

/// The datadog migration shape: a raw values string is checksummed into an
/// annotation (`userValues | sha256sum`) and spliced verbatim into a block
/// scalar. The annotation slot observes the DIGEST — a plain token for any
/// operand — so the slot's plain-scalar language must not project backward
/// onto the operand: YAML-looking and multiline file contents stay
/// accepted while the checksum's own strict-string contract still rejects
/// non-strings (helm aborts hashing a map or number).
#[test]
fn checksum_digest_splices_project_no_slot_language_onto_the_operand() {
    let src = indoc! {r"
        {{- if or .Values.migration.enabled .Values.migration.preview }}
        {{- if .Values.migration.userValues }}
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: test
          annotations:
            checksum/migration-config: {{ .Values.migration.userValues | sha256sum }}
        data:
          values.yaml: |-
        {{ .Values.migration.userValues | indent 4 }}
        {{- end }}
        {{- end }}
    "};
    let schema = schema_for_values_yaml(
        parse_ir(src),
        Some(indoc! {"
            migration:
              enabled: false
              preview: false
              userValues: null
        "}),
    );
    for (instance, want, label) in [
        (
            serde_json::json!({ "migration": { "enabled": true, "userValues": "datadog: {}" } }),
            true,
            "single-line YAML file content renders",
        ),
        (
            serde_json::json!({ "migration": { "enabled": true, "userValues": indoc! {"
                datadog:
                  apiKey: x
            "} } }),
            true,
            "multiline YAML file content renders",
        ),
        (
            serde_json::json!({ "migration": { "enabled": true, "userValues": "plain" } }),
            true,
            "plain text renders",
        ),
        (
            serde_json::json!({ "migration": { "enabled": true, "userValues": { "a": 1 } } }),
            false,
            "a live map operand aborts the checksum",
        ),
        (
            serde_json::json!({ "migration": { "enabled": true, "userValues": 7 } }),
            false,
            "a live number operand aborts the checksum",
        ),
        (
            serde_json::json!({ "migration": { "userValues": { "a": 1 } } }),
            true,
            "the dormant gate keeps junk open",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "checksum operand slot-language abstention ({label}): \
             instance={instance}; want={want}; schema={schema}"
        );
    }
}

/// Every nil-strict string consumer — `tpl`, `b64enc`, `trim`, `trunc`,
/// `htpasswd`, and the rest of the transform catalog — reads its operand as
/// a Go string, so a NIL operand aborts rendering ("wrong type for value;
/// expected string") wherever the consumer runs. Absence is Helm-falsy, so
/// the truthy⇒string capture cannot state that; the presence claim is its
/// own abort-grade clause, scoped by the consumer's ambient guards and
/// exempt where the operand's own truthiness gates the read.
#[test]
fn nil_strict_string_consumers_require_their_operand_to_exist() {
    let src = indoc! {r#"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: test
        data:
          {{- if .Values.assert }}
          secret: {{ tpl .Values.config.secret $ | b64enc }}
          {{- end }}
          plain: {{ .Values.name | trim }}
          {{- with .Values.guarded }}
          guarded: {{ tpl . $ }}
          {{- end }}
          derived: {{ printf "%s-%s" .Values.name .Values.suffix | trunc 63 }}
    "#};
    let values_yaml = indoc! {"
        assert: true
        config:
          secret: value
        name: chart
        guarded: text
        suffix: x
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));

    for (label, overrides, want) in [
        ("baseline", serde_json::json!({}), true),
        (
            "the live gate's operand must exist",
            serde_json::json!({ "config": { "secret": null } }),
            false,
        ),
        (
            "a dormant gate keeps the deletion open",
            serde_json::json!({ "assert": false, "config": { "secret": null } }),
            true,
        ),
        (
            "an unconditional consumer demands its operand outright",
            serde_json::json!({ "name": null }),
            false,
        ),
        (
            "a with-scoped operand renders when absent",
            serde_json::json!({ "guarded": null }),
            true,
        ),
        (
            // `printf` renders `%!s(<nil>)` for a missing operand, and only
            // its DERIVED text reaches the trim.
            "a derived operand claims nothing about its influences",
            serde_json::json!({ "suffix": null }),
            true,
        ),
    ] {
        let instance = composed_instance(values_yaml, overrides);
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "{label}: instance={instance}; want={want}; schema={schema}"
        );
    }
}

#[test]
fn strict_tpl_in_composed_scalar_keeps_its_input_type() {
    let src = indoc! {r#"
        apiVersion: apps/v1
        {{- if .Values.server.stateful }}
        kind: StatefulSet
        {{- else if .Values.server.daemon }}
        kind: DaemonSet
        {{- else }}
        kind: Deployment
        {{- end }}
        metadata:
          name: test
        spec:
          selector:
            matchLabels:
              app: test
          template:
            metadata:
              labels:
                app: test
            spec:
              containers:
                - name: main
                {{- if .Values.image.digest }}
                  image: "{{ tpl .Values.image.repository . }}@{{ tpl .Values.image.digest . }}"
                {{- else }}
                  image: "{{ tpl .Values.image.repository . }}:{{ tpl .Values.image.tag . | default .Chart.AppVersion }}{{ if .Values.image.distroless }}-distroless{{ end }}"
                {{- end }}
    "#};
    let values_yaml = indoc! {"
        image:
          repository: example/image
          tag: ''
          digest: ''
          distroless: false
        server:
          stateful: false
          daemon: false
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));

    for repository in [serde_json::json!({}), serde_json::json!([])] {
        let instance = composed_instance(
            values_yaml,
            serde_json::json!({ "image": { "repository": repository } }),
        );
        assert!(
            !schema_accepts_instance(&schema, &instance),
            "tpl requires a string even when sibling tag/digest guards are falsy: \
             instance={instance}; schema={schema}"
        );
    }
}

/// A raw splice in an UNQUOTED slot renders the value's own characters, so text
/// that ends the plain token there corrupts the document. Two identities reach
/// such a slot and both now carry the claim: a directly ranged collection's KEY
/// (bare, and through a `replace` whose token cannot change the token-ending
/// characters), and a `tpl` operand — `tpl` is the identity on
/// template-ACTION-free input, so a value carrying `{{` escapes.
#[test]
fn unquoted_slots_bound_the_lexical_language_of_their_source() {
    let key_in_value_slot = indoc! {r#"
        env:
        {{- range $key, $value := .Values.extraEnvVars }}
          - name: {{ $key | replace "." "_" }}
            value: {{ $value | quote }}
        {{- end }}
    "#};
    let key_in_key_slot = indoc! {r"
        apiVersion: v1
        kind: Secret
        data:
        {{- range $key, $value := .Values.data }}
          {{ $key }}: {{ tpl $value $ | b64enc | quote }}
        {{- end }}
    "};
    let tpl_whole_slot = indoc! {r"
        volumeMounts:
          - name: secrets
            mountPath: {{ tpl .Values.mountPath $ }}
    "};
    let tpl_partial_slot = indoc! {r"
        command:
          - --cluster-name={{ tpl (.Values.clusterName) . }}
    "};

    for (label, src, values_yaml, cases) in [
        (
            "a ranged key in a plain value slot",
            key_in_value_slot,
            "extraEnvVars: {}\n",
            vec![
                (
                    serde_json::json!({ "extraEnvVars": { "BAD: KEY": "x" } }),
                    false,
                ),
                (
                    serde_json::json!({ "extraEnvVars": { "A #b": "x" } }),
                    false,
                ),
                (
                    serde_json::json!({ "extraEnvVars": { "GOOD.KEY": "x" } }),
                    true,
                ),
            ],
        ),
        (
            "a ranged key in a mapping-key slot",
            key_in_key_slot,
            "data: {}\n",
            vec![
                (serde_json::json!({ "data": { "BAD: KEY": "x" } }), false),
                (serde_json::json!({ "data": { "GOOD_KEY": "x" } }), true),
                // The VALUE renders through `b64enc | quote`, which reshapes
                // the text, so its own characters never reach a plain token.
                (serde_json::json!({ "data": { "K": "a: b" } }), true),
            ],
        ),
        (
            "a tpl operand filling a whole plain slot",
            tpl_whole_slot,
            "mountPath: /etc/secrets\n",
            vec![
                (serde_json::json!({ "mountPath": "/etc/a: b" }), false),
                (serde_json::json!({ "mountPath": "/etc/secrets" }), true),
                (
                    serde_json::json!({ "mountPath": "{{ .Release.Name }}: x" }),
                    true,
                ),
            ],
        ),
        (
            "a tpl operand inside a partial plain token",
            tpl_partial_slot,
            "clusterName: prod\n",
            vec![
                (serde_json::json!({ "clusterName": "x: y" }), false),
                (serde_json::json!({ "clusterName": "prod" }), true),
                // Literal text opens this token, so a leading indicator is
                // ordinary content rather than YAML structure.
                (serde_json::json!({ "clusterName": "- x" }), true),
            ],
        ),
    ] {
        let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));
        for (instance, want) in cases {
            sim_assert_eq!(
                have: schema_accepts_instance(&schema, &instance),
                want: want,
                "{label}: instance={instance}; schema={schema}"
            );
        }
    }
}

/// A helper body renders at its CALLER's position, so its own plain slots
/// bind a lexical language only where the caller consumes the body's text as
/// YAML. Jenkins routes its `JCasC` defaults through two nested helpers into
/// a config map block scalar keyed `jcasc-default-config.yaml`: the manifest
/// stays valid, but the embedded document no longer parses. A block scalar
/// whose key names no YAML document is opaque text, and a reshaping stage
/// between the body and the sink renders its own characters, so both abstain.
#[test]
fn helper_slots_bind_their_language_where_the_caller_consumes_yaml() {
    let helpers = indoc! {r#"
        {{- define "chart.casc.podTemplate" -}}
        - name: "default"
        {{- if .Values.agent.annotations }}
          annotations:
          {{- range $key, $value := .Values.agent.annotations }}
          - key: {{ $key }}
            value: {{ $value | quote }}
          {{- end }}
        {{- end }}
          envVars:
          {{- range $var := .Values.agent.envVars }}
          - envVar:
              key: {{ $var.name | quote }}
              value: {{ tpl $var.value $ }}
          {{- end }}
        {{- end -}}
        {{- define "chart.casc.defaults" -}}
        jenkins:
          clouds:
          - kubernetes:
              templates:
              {{- include "chart.casc.podTemplate" . | nindent 8 }}
        {{- end -}}
    "#};
    let yaml_document_sink = indoc! {r#"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: casc
        data:
          jcasc-default-config.yaml: |-
            {{- include "chart.casc.defaults" . | nindent 4 }}
    "#};
    let opaque_document_sink = indoc! {r#"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: casc
        data:
          jcasc-default-config.txt: |-
            {{- include "chart.casc.defaults" . | nindent 4 }}
    "#};
    let encoded_sink = indoc! {r#"
        apiVersion: v1
        kind: Secret
        metadata:
          name: casc
        data:
          jcasc-default-config.yaml: {{ include "chart.casc.defaults" . | b64enc | quote }}
    "#};
    let values_yaml = indoc! {"
        agent:
          annotations: {}
          envVars: []
    "};

    let broken_key = serde_json::json!({ "agent": { "annotations": { "broken: key": "x" } } });
    let broken_value = serde_json::json!({
        "agent": { "envVars": [{ "name": "URL", "value": "http: //x" }] },
    });
    let safe = serde_json::json!({
        "agent": {
            "annotations": { "kubernetes.io/scrape": "true" },
            "envVars": [{ "name": "URL", "value": "http://x" }],
        },
    });

    for (label, src, cases) in [
        (
            "a block scalar naming a YAML document",
            yaml_document_sink,
            vec![(&broken_key, false), (&broken_value, false), (&safe, true)],
        ),
        (
            "a block scalar naming no YAML document",
            opaque_document_sink,
            vec![(&broken_key, true), (&broken_value, true), (&safe, true)],
        ),
        (
            "a reshaping stage between the body and the sink",
            encoded_sink,
            vec![(&broken_key, true), (&broken_value, true), (&safe, true)],
        ),
    ] {
        let schema = schema_for_values_yaml(parse_ir_with_helpers(src, helpers), Some(values_yaml));
        for (overrides, want) in cases {
            let instance = composed_instance(values_yaml, overrides.clone());
            sim_assert_eq!(
                have: schema_accepts_instance(&schema, &instance),
                want: want,
                "{label}: instance={instance}; schema={schema}"
            );
        }
    }
}