helm-schema-gen 0.0.4

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
use color_eyre::eyre::{self, WrapErr as _};
use indoc::indoc;
use test_util::prelude::sim_assert_eq;

use super::*;

#[test]
fn quoted_empty_membership_scopes_raw_provider_preimages() {
    let raw = indoc! {r#"
        apiVersion: apps/v1
        kind: Deployment
        metadata:
          name: test
        spec:
          {{- if not (has (quote .Values.limit) (list "" (quote ""))) }}
          revisionHistoryLimit: {{ .Values.limit }}
          {{- end }}
          selector:
            matchLabels:
              app: test
          template:
            metadata:
              labels:
                app: test
            spec:
              containers:
                - name: test
                  image: busybox
    "#};
    let schema = schema_for_values_yaml(parse_ir(raw), Some("limit: ''\n"));

    for (instance, want, label) in [
        (
            serde_json::json!({ "limit": { "bad": true } }),
            false,
            "map",
        ),
        (serde_json::json!({ "limit": false }), false, "false"),
        (serde_json::json!({ "limit": 7 }), true, "integer"),
        (serde_json::json!({ "limit": "7" }), true, "numeric string"),
        (serde_json::json!({ "limit": "" }), true, "empty string"),
        (serde_json::json!({ "limit": null }), true, "null"),
        (serde_json::json!({}), true, "absent"),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "raw membership {label}: instance={instance}; schema={schema}"
        );
    }

    let converted = raw.replace(
        "revisionHistoryLimit: {{ .Values.limit }}",
        "revisionHistoryLimit: {{ .Values.limit | int64 }}",
    );
    let schema = schema_for_values_yaml(parse_ir(&converted), Some("limit: ''\n"));
    assert!(
        schema_accepts_instance(&schema, &serde_json::json!({ "limit": { "bad": true } })),
        "the int64 conversion makes a live map provider-safe without typing the raw input: {schema}"
    );
}

#[test]
fn plain_string_provider_preimage_rejects_yaml_unsafe_spellings() {
    let src = indoc! {r"
        apiVersion: v1
        kind: Pod
        metadata:
          name: test
        spec:
          containers:
            - name: test
              image: busybox
              env:
                - name: AUDIT
                  value: {{ .Values.value }}
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some("value: safe\n"));

    for (value, want, label) in [
        (serde_json::json!("safe"), true, "ordinary string"),
        (
            serde_json::json!("repo:tag"),
            true,
            "colon without separation",
        ),
        (serde_json::json!("repo: bad"), false, "mapping separator"),
        (
            serde_json::json!("%bad"),
            false,
            "forbidden leading indicator",
        ),
        (serde_json::json!("false"), false, "implicit Boolean"),
        (serde_json::json!("yes"), false, "YAML 1.1 Boolean alias"),
        (serde_json::json!("7"), false, "implicit number"),
        (
            serde_json::json!("1_000"),
            false,
            "underscore-separated number",
        ),
        (serde_json::json!("1."), false, "trailing-dot float"),
        (
            serde_json::json!("+.nan"),
            true,
            "signed NaN stays a string",
        ),
        (
            serde_json::json!("1e999"),
            true,
            "float overflow stays a string",
        ),
        (serde_json::json!("line\nbreak"), false, "line break"),
    ] {
        let instance = serde_json::json!({ "value": value });
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "plain YAML {label}: instance={instance}; schema={schema}"
        );
    }
}

/// A Boolean provider slot accepts every spelling the YAML 1.1 resolver
/// reads back as a Boolean — crossplane renders `hostNetwork: yes` into a
/// valid manifest, so rejecting the alias set falsely narrows the input.
#[test]
fn boolean_slot_accepts_every_resolver_boolean_spelling() {
    let src = indoc! {r"
        apiVersion: v1
        kind: Pod
        metadata:
          name: test
        spec:
          hostNetwork: {{ .Values.hostNetwork }}
          containers:
            - name: test
              image: busybox
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some("hostNetwork: false\n"));

    for (value, want, label) in [
        (serde_json::json!(true), true, "native Boolean"),
        (serde_json::json!("yes"), true, "yes alias"),
        (serde_json::json!("off"), true, "off alias"),
        (serde_json::json!("Y"), true, "single-letter alias"),
        (serde_json::json!("TRUE"), true, "uppercase spelling"),
        (serde_json::json!("yeah"), false, "non-token string"),
    ] {
        let instance = serde_json::json!({ "hostNetwork": value });
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "boolean spelling {label}: instance={instance}; schema={schema}"
        );
    }
}

/// An integer provider slot accepts every spelling the YAML 1.1 resolver
/// reads back as an in-range integer: signs, underscore separators, and
/// radix prefixes all reparse to the integer the slot needs (metrics-server
/// renders `port: +443` into a valid Service).
#[test]
fn integer_slot_accepts_every_resolver_integer_spelling() {
    let src = indoc! {r"
        apiVersion: v1
        kind: Service
        metadata:
          name: test
        spec:
          ports:
            - port: {{ .Values.port }}
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some("port: 443\n"));

    for (value, want, label) in [
        (serde_json::json!(443), true, "native integer"),
        (serde_json::json!("443"), true, "decimal string"),
        (serde_json::json!("+443"), true, "signed decimal"),
        (serde_json::json!("1_000"), true, "underscore separator"),
        (serde_json::json!("0x1F"), true, "hex literal"),
        (
            serde_json::json!("_443"),
            false,
            "leading underscore stays a string",
        ),
        (serde_json::json!("4.5"), false, "float spelling"),
        (serde_json::json!("not-a-port"), false, "non-numeric string"),
    ] {
        let instance = serde_json::json!({ "port": value });
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "integer spelling {label}: instance={instance}; schema={schema}"
        );
    }
}

/// `genSignedCert` passes every ip-list entry through `net.ParseIP` and
/// aborts rendering on nil, so items must additionally spell an IP address —
/// not merely a string (cilium's Hubble certificate SANs).
#[test]
fn signed_cert_ip_list_items_require_the_ip_lexical_domain() {
    let src = indoc! {r#"
        {{- $cert := genSelfSignedCert "audit.example" .Values.ips (list "audit.example") 365 }}
        apiVersion: v1
        kind: Secret
        metadata:
          name: test
        data:
          tls.crt: {{ $cert.Cert | b64enc }}
    "#};
    let schema = schema_for_values_yaml(parse_ir(src), Some("ips: []\n"));

    for (value, want, label) in [
        (serde_json::json!(["10.0.0.7"]), true, "IPv4"),
        (serde_json::json!(["::1"]), true, "IPv6 loopback"),
        (
            serde_json::json!(["2001:db8::8a2e:370:7334"]),
            true,
            "IPv6 full form",
        ),
        (
            serde_json::json!(["::ffff:10.0.0.7"]),
            true,
            "IPv4-mapped IPv6",
        ),
        (
            serde_json::json!(["not-an-ip"]),
            false,
            "non-address string",
        ),
        (
            serde_json::json!(["999.999.999.999"]),
            false,
            "out-of-range octets",
        ),
        (
            serde_json::json!(["10.0.0.07"]),
            false,
            "leading-zero octet",
        ),
        (serde_json::json!([7]), false, "non-string item"),
    ] {
        let instance = serde_json::json!({ "ips": value });
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "ip list item {label}: instance={instance}; schema={schema}"
        );
    }
}

/// A `typeOf`-dispatched numeric lane still renders into the provider slot,
/// so the arm's typing must keep the provider's constraint: policy/v1
/// `minAvailable` is int-or-string, and a fractional float in the selected
/// numeric lane renders a manifest the API server rejects (sealed-secrets'
/// PDB dispatch).
#[test]
fn typeof_dispatched_numeric_lane_keeps_the_provider_intersection() {
    let src = indoc! {r#"
        apiVersion: policy/v1
        kind: PodDisruptionBudget
        metadata:
          name: test
        spec:
          {{- if regexMatch "64$" (typeOf .Values.pdb.minAvailable) }}
          minAvailable: {{ .Values.pdb.minAvailable }}
          {{- end }}
          selector:
            matchLabels:
              app: test
    "#};
    let schema = schema_for_values_yaml(
        parse_ir(src),
        Some(indoc! {"
            pdb:
              minAvailable: 1
        "}),
    );

    for (value, want, label) in [
        (serde_json::json!(1), true, "integer"),
        (
            serde_json::json!(2.0),
            true,
            "integral float renders as integer",
        ),
        (
            serde_json::json!("50%"),
            true,
            "string skips the numeric arm",
        ),
        (serde_json::json!(1.5), false, "fractional float"),
    ] {
        let instance = serde_json::json!({ "pdb": { "minAvailable": value } });
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "dispatched numeric lane {label}: instance={instance}; schema={schema}"
        );
    }
}

#[test]
fn inline_conditional_kind_candidates_reach_the_matching_provider_path() {
    let src = indoc! {r"
        apiVersion: apps/v1
        kind: {{ if .Values.stateful }}StatefulSet{{ else }}Deployment{{ end }}
        metadata:
          name: test
        spec:
          {{- if .Values.stateful }}
          serviceName: test
          {{- else }}
          strategy: {{ toYaml .Values.strategy | nindent 4 }}
          {{- end }}
          selector:
            matchLabels:
              app: test
          template:
            metadata:
              labels:
                app: test
            spec:
              containers:
              - name: test
                image: busybox
    "};
    let values_yaml = indoc! {"
        stateful: false
        strategy: {}
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));

    assert!(
        !schema_accepts_instance(
            &schema,
            &serde_json::json!({ "stateful": false, "strategy": 7 })
        ),
        "Deployment strategy is object-typed: {schema}"
    );
    assert!(
        schema_accepts_instance(
            &schema,
            &serde_json::json!({ "stateful": true, "strategy": 7 })
        ),
        "the strategy value is dormant in the StatefulSet branch: {schema}"
    );
    assert!(
        schema_accepts_instance(
            &schema,
            &serde_json::json!({
                "stateful": false,
                "strategy": { "type": "Recreate" }
            })
        ),
        "a valid Deployment strategy remains accepted: {schema}"
    );
}

#[test]
fn values_selected_kind_partitions_provider_contracts() {
    let src = indoc! {r#"
        apiVersion: apps/v1
        kind: {{ .Values.workloadKind }}
        metadata:
          name: test
        spec:
          {{- if not (eq .Values.workloadKind "DaemonSet") }}
          replicas: 1
          {{- end }}
          {{- if eq .Values.workloadKind "StatefulSet" }}
          serviceName: test
          {{- end }}
          {{- if eq .Values.workloadKind "Deployment" }}
          strategy: {{ toYaml .Values.updateStrategy | nindent 4 }}
          {{- else }}
          updateStrategy: {{ toYaml .Values.updateStrategy | nindent 4 }}
          {{- end }}
          selector:
            matchLabels:
              app: test
          template:
            metadata:
              labels:
                app: test
            spec:
              containers:
              - name: test
                image: busybox
    "#};
    let values_yaml = indoc! {"
        workloadKind: Deployment
        updateStrategy: {}
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));
    let stateful_only = serde_json::json!({
        "rollingUpdate": { "partition": "not-an-integer" }
    });
    let deployment_only = serde_json::json!({
        "rollingUpdate": { "maxSurge": false }
    });

    assert!(
        !schema_accepts_instance(
            &schema,
            &serde_json::json!({
                "workloadKind": "Deployment",
                "updateStrategy": deployment_only.clone()
            })
        ),
        "DeploymentStrategy types rollingUpdate.maxSurge as a string or integer: {schema}"
    );
    assert!(
        schema_accepts_instance(
            &schema,
            &serde_json::json!({
                "workloadKind": "StatefulSet",
                "updateStrategy": deployment_only
            })
        ),
        "StatefulSetStrategy leaves Deployment-only rollingUpdate fields open: {schema}"
    );
    assert!(
        !schema_accepts_instance(
            &schema,
            &serde_json::json!({
                "workloadKind": "StatefulSet",
                "updateStrategy": stateful_only.clone()
            })
        ),
        "StatefulSetStrategy types rollingUpdate.partition as an integer: {schema}"
    );
    assert!(
        schema_accepts_instance(
            &schema,
            &serde_json::json!({
                "workloadKind": "Deployment",
                "updateStrategy": stateful_only.clone()
            })
        ),
        "DeploymentStrategy leaves StatefulSet-only rollingUpdate fields open: {schema}"
    );
    assert!(
        schema_accepts_instance(
            &schema,
            &serde_json::json!({
                "workloadKind": "CustomWorkload",
                "updateStrategy": stateful_only
            })
        ),
        "an unknown kind remains an explicit unconstrained complement: {schema}"
    );
}

#[test]
fn helper_return_disjunction_partitions_downstream_provider_contracts() {
    let helpers = indoc! {r#"
        {{- define "provider.name" -}}
        {{- if eq (typeOf .Values.provider) "string" -}}
        {{- .Values.provider -}}
        {{- else -}}
        {{- .Values.provider.name -}}
        {{- end -}}
        {{- end -}}
    "#};
    let src = indoc! {r#"
        {{- $provider_name := tpl (include "provider.name" .) $ -}}
        apiVersion: v1
        kind: Pod
        metadata:
          name: test
        spec:
          containers:
          - name: main
            image: busybox
          {{- if eq $provider_name "webhook" }}
          - name: webhook
            image: webhook:1.0
            livenessProbe: {{ toYaml .Values.provider.webhook.livenessProbe | nindent 6 }}
          {{- end }}
    "#};
    let schema = schema_for_values_yaml(parse_ir_with_helpers(src, helpers), None);

    assert!(
        !schema_accepts_instance(
            &schema,
            &serde_json::json!({
                "provider": {
                    "name": "webhook",
                    "webhook": { "livenessProbe": { "failureThreshold": "audit" } }
                }
            })
        ),
        "the selected webhook helper arm must apply the Probe provider schema: {schema}"
    );
    assert!(
        schema_accepts_instance(
            &schema,
            &serde_json::json!({
                "provider": {
                    "name": "aws",
                    "webhook": { "livenessProbe": { "failureThreshold": "audit" } }
                }
            })
        ),
        "the unselected webhook helper arm must leave its probe dormant: {schema}"
    );
    assert!(
        schema_accepts_instance(
            &schema,
            &serde_json::json!({
                "provider": {
                    "name": "webhook",
                    "webhook": { "livenessProbe": { "failureThreshold": 2 } }
                }
            })
        ),
        "a provider-valid probe remains accepted in the selected helper arm: {schema}"
    );
}

#[test]
fn helper_literal_or_override_return_applies_integer_preimage_to_the_override() {
    let helpers = indoc! {r#"
        {{- define "version.default" -}}
        {{- $old := index . 0 -}}
        {{- $new := index . 1 -}}
        {{- $default := index . 2 -}}
        {{- if kindIs "invalid" $default -}}
          {{- if semverCompare ">= 1.22-0" "1.29.0" -}}
            {{- print $new -}}
          {{- else -}}
            {{- print $old -}}
          {{- end -}}
        {{- else -}}
          {{- print $default -}}
        {{- end -}}
        {{- end -}}
    "#};
    let src = indoc! {r#"
        apiVersion: v1
        kind: Service
        metadata:
          name: test
        spec:
          selector:
            app: test
          ports:
          - name: metrics
            port: {{ include "version.default" (list 10252 10257 .Values.service.port) }}
    "#};
    let schema = schema_for_values_yaml(
        parse_ir_with_helpers(src, helpers),
        Some(indoc! {"
            service:
              port: null
        "}),
    );

    assert!(
        !schema_accepts_instance(
            &schema,
            &serde_json::json!({ "service": { "port": "audit" } })
        ),
        "a selected nonnumeric override renders an invalid Service port: {schema}"
    );
    for port in [
        serde_json::json!(10257),
        serde_json::json!("10257"),
        serde_json::Value::Null,
    ] {
        assert!(
            schema_accepts_instance(
                &schema,
                &serde_json::json!({ "service": { "port": port.clone() } })
            ),
            "a provider-valid override or the literal-default arm must validate: port={port}; schema={schema}"
        );
    }
}

/// A conditional branch rendering a DIRECT scalar hole into a
/// provider-required field (a Service `port`) backprojects presence and
/// non-nullability of the source leaf under the branch's guards: Helm
/// renders a missing or null source as an explicit null the provider
/// rejects. The dormant arm stays open, and a `default` fallback abstains
/// (absence renders the fallback instead).
#[test]
fn provider_required_field_requires_direct_source_leaf() {
    let guarded = indoc! {r"
        {{- if .Values.svc.enabled }}
        apiVersion: v1
        kind: Service
        metadata:
          name: probe
        spec:
          ports:
          - port: {{ .Values.svc.port }}
            name: http
        {{- end }}
    "};
    let values_yaml = indoc! {"
        svc:
          enabled: false
    "};
    let schema = schema_for_values_yaml(parse_ir(guarded), Some(values_yaml));

    for (instance, want, label) in [
        (
            serde_json::json!({ "svc": { "enabled": false } }),
            true,
            "dormant branch stays open",
        ),
        (
            serde_json::json!({ "svc": { "enabled": true, "port": 80 } }),
            true,
            "present integer port renders a valid Service",
        ),
        (
            serde_json::json!({ "svc": { "enabled": true } }),
            false,
            "missing port renders a provider-invalid null",
        ),
        (
            serde_json::json!({ "svc": { "enabled": true, "port": null } }),
            false,
            "explicit null port renders a provider-invalid null",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "{label}: instance={instance}; schema={schema}"
        );
    }

    let defaulted = indoc! {r"
        {{- if .Values.svc.enabled }}
        apiVersion: v1
        kind: Service
        metadata:
          name: probe
        spec:
          ports:
          - port: {{ .Values.svc.port | default 9090 }}
            name: http
        {{- end }}
    "};
    let schema = schema_for_values_yaml(parse_ir(defaulted), Some(values_yaml));
    let instance = serde_json::json!({ "svc": { "enabled": true, "port": null } });
    assert!(
        schema_accepts_instance(&schema, &instance),
        "a default fallback renders on absence, so the source stays optional; schema={schema}"
    );
}

#[test]
fn pathless_dependency_fragment_root_keeps_values_mapping_open_with_descendants() {
    let mut contract = ContractIr::from_contract_uses(vec![ContractUse {
        source_expr: "webhook.serviceAccount.name".to_string(),
        path: YamlPath(vec!["metadata".to_string(), "name".to_string()]),
        kind: ValueKind::Scalar,
        condition: helm_schema_core::GuardDnf::from_guards(vec![Guard::Truthy {
            path: "webhook.enabled".to_string(),
        }]),
        resource: None,
        provenance: Vec::new(),
        has_string_contract: false,
        template_supplied_member_keys: std::collections::BTreeSet::default(),
        split_segment: None,
        merge_layers: None,
        range_key: false,
        nil_omitting: false,
        omitted_members: std::collections::BTreeMap::default(),
        digest: false,
        merge_operand: false,
    }]);
    contract.push_pathless_dependency_fragment("webhook");

    let schema = schema_for_values_yaml(
        contract,
        Some(indoc! {"
            webhook:
              enabled: false
              image:
                repository: webhook
              serviceAccount:
                name: webhook
        "}),
    );
    let webhook = schema
        .pointer("/properties/webhook")
        .expect("webhook schema");

    assert_ne!(
        webhook.get("additionalProperties"),
        Some(&Value::Bool(false)),
        "pathless dependency fragment roots should stay open when descendants are inserted: {webhook}",
    );
}

#[test]
fn type_hint_only_descendant_preserves_object_input_branch() {
    let uses = vec![ContractUse {
        source_expr: "image".to_string(),
        path: YamlPath(vec!["metadata".to_string(), "name".to_string()]),
        kind: ValueKind::Scalar,
        condition: helm_schema_core::GuardDnf::from_guards(Vec::new()),
        resource: Some(ResourceRef::concrete(
            "v1".to_string(),
            "Service".to_string(),
        )),
        provenance: Vec::new(),
        has_string_contract: false,
        template_supplied_member_keys: std::collections::BTreeSet::default(),
        split_segment: None,
        merge_layers: None,
        range_key: false,
        nil_omitting: false,
        omitted_members: std::collections::BTreeMap::default(),
        digest: false,
        merge_operand: false,
    }];
    let contract = with_type_hints(
        ContractIr::from_contract_uses(uses),
        &[("image.tag", "string")],
    );
    let schema = schema_for_values_yaml(&contract, Some("image: {}\n"));
    let variants = schema
        .pointer("/properties/image/anyOf")
        .and_then(Value::as_array)
        .expect("image schema should preserve object and scalar branches");

    assert!(
        variants.iter().any(|variant| {
            variant
                .pointer("/properties/tag/type")
                .and_then(Value::as_str)
                == Some("string")
        }),
        "type-hint descendant should preserve an object input branch with the hinted leaf: {schema:#}",
    );
    assert!(
        variants
            .iter()
            .any(|variant| variant.get("type").and_then(Value::as_str) == Some("string")),
        "rendered scalar sink should still preserve the scalar branch: {schema:#}",
    );
}

#[derive(Debug)]
struct DescriptionProvider;

impl ResourceSchemaOracle for DescriptionProvider {
    fn schema_fragment_for_use(&self, _use_: &ProviderSchemaUse) -> Option<ProviderSchemaFragment> {
        Some(ProviderSchemaFragment::new(serde_json::json!({
            "description": "provider description",
            "type": "string",
        })))
    }
}

#[test]
#[expect(
    clippy::too_many_lines,
    reason = "the complete fixture scenario is clearest as one contiguous test"
)]
fn surveyor_metric_relabelings_keeps_crd_provider_evidence() -> eyre::Result<()> {
    let src = test_util::read_testdata("charts/surveyor/templates/serviceMonitor.yaml")?;
    let mut idx = DefineIndex::new();
    idx.add_file_source(
        "charts/surveyor/templates/_helpers.tpl",
        &test_util::read_testdata("charts/surveyor/templates/_helpers.tpl")?,
    );
    let contract = SymbolicIrContext::new(&idx).generate_contract_ir(&src);
    let schema_signals = contract.finalize().into_schema_signals();
    let values_yaml_source = test_util::read_testdata("charts/surveyor/values.yaml")?;
    let values_yaml: serde_yaml::Value =
        serde_yaml::from_str(&values_yaml_source).wrap_err("parse Surveyor values fixture")?;
    let provider = Chain::new(vec![
        Box::new(
            CrdsCatalogSchemaProvider::new()
                .with_cache_dir(
                    test_util::workspace_testdata().join("provider-bundle/crds-catalog-cache"),
                )
                .with_allow_download(false),
        ),
        Box::new(
            KubernetesJsonSchemaProvider::new("v1.35.0")
                .with_cache_dir(super::bundle_cache_dir())
                .with_allow_download(false)
                .with_api_version_guess(true),
        ),
    ])
    .with_inference_enabled(true);
    let resolved =
        crate::path_resolver::PathSchemaResolver::new(&schema_signals, &values_yaml, &provider)
            .resolve_all();
    let resolved_metric_relabelings = resolved
        .iter()
        .find(|path| path.value_path == "serviceMonitor.metricRelabelings")
        .expect("resolved metricRelabelings");
    assert!(
        schema_signals
            .evidence_for("serviceMonitor.metricRelabelings")
            .is_some_and(|evidence| evidence.provider_schema_uses.is_empty()),
        "metricRelabelings provider evidence should not escape its render guard"
    );
    assert!(
        resolved_metric_relabelings
            .provider_schema_candidate
            .is_none(),
        "metricRelabelings should not have an unconditional provider candidate"
    );
    let overlay = schema_signals
        .evidence_for("serviceMonitor.metricRelabelings")
        .and_then(|evidence| evidence.conditional_overlays.first())
        .expect("metricRelabelings conditional overlay");
    assert!(
        !overlay.evidence.provider_schema_uses.is_empty(),
        "metricRelabelings conditional overlay should keep CRD provider schema uses"
    );
    assert!(
        !overlay.preserve_base_schema,
        "guarded-only metricRelabelings evidence should not preserve a typed base: {overlay:#?}"
    );
    let resolved_overlay = crate::path_resolver::PathSchemaResolver::resolve_single_path_evidence(
        &overlay
            .evidence
            .as_path_evidence("serviceMonitor.metricRelabelings"),
        &provider,
    );
    sim_assert_eq!(
        have: resolved_overlay.schema.pointer("/anyOf/0/type").and_then(Value::as_str),
        want: Some("array"),
        "resolved overlay schema should stay array-shaped: {}",
        resolved_overlay.schema
    );
    sim_assert_eq!(
        have: resolved_overlay
            .schema
            .pointer("/anyOf/0/items/properties/action/type")
            .and_then(Value::as_str),
        want: Some("string"),
        "resolved overlay schema should keep relabel config item shape: {}",
        resolved_overlay.schema
    );

    let generated = generate_values_schema(
        ValuesSchemaInput::new(&schema_signals, &provider)
            .with_values_yaml(Some(&values_yaml_source)),
    );
    for (instance, want, label) in [
        (
            serde_json::json!({
                "serviceMonitor": {
                    "enabled": true,
                    "metricRelabelings": [{ "action": "replace" }]
                }
            }),
            true,
            "enabled provider-shaped relabeling",
        ),
        (
            serde_json::json!({
                "serviceMonitor": {
                    "enabled": true,
                    "metricRelabelings": [{ "action": 7 }]
                }
            }),
            false,
            "enabled invalid relabeling",
        ),
        (
            serde_json::json!({
                "serviceMonitor": {
                    "enabled": false,
                    "metricRelabelings": 7
                }
            }),
            true,
            "disabled unconstrained relabeling",
        ),
    ] {
        assert!(
            schema_accepts_instance(&generated, &instance) == want,
            "{label}: instance={instance}; schema={generated}"
        );
    }
    Ok(())
}

#[test]
fn zalando_extra_envs_keeps_podspec_envvar_shape() -> eyre::Result<()> {
    let src =
        test_util::read_testdata("charts/zalando-postgres-operator/templates/deployment.yaml")?;
    let mut idx = DefineIndex::new();
    idx.add_file_source(
        "charts/zalando-postgres-operator/templates/_helpers.tpl",
        &test_util::read_testdata("charts/zalando-postgres-operator/templates/_helpers.tpl")?,
    );
    let contract = SymbolicIrContext::new(&idx).generate_contract_ir(&src);
    let schema_signals = contract.finalize().into_schema_signals();
    let values_yaml_source =
        test_util::read_testdata("charts/zalando-postgres-operator/values.yaml")?;
    let values_yaml: serde_yaml::Value = serde_yaml::from_str(&values_yaml_source)
        .wrap_err("parse Zalando operator values fixture")?;
    let provider = production_chain_provider();

    let resolved =
        crate::path_resolver::PathSchemaResolver::new(&schema_signals, &values_yaml, &provider)
            .resolve_all();
    let resolved_extra_envs = resolved
        .iter()
        .find(|path| path.value_path == "extraEnvs")
        .expect("resolved extraEnvs");
    assert!(
        resolved_extra_envs.provider_schema_candidate.is_some(),
        "extraEnvs should preserve provider schema candidate: {}; evidence={:#?}",
        resolved_extra_envs.schema,
        schema_signals.evidence_for("extraEnvs")
    );
    sim_assert_eq!(
        have: resolved_extra_envs
            .schema
            .pointer("/anyOf/0/type")
            .and_then(Value::as_str),
        want: Some("array"),
        "extraEnvs should stay array-shaped: {}",
        resolved_extra_envs.schema
    );
    sim_assert_eq!(
        have: resolved_extra_envs
            .schema
            .pointer("/anyOf/0/items/properties/name/type")
            .and_then(Value::as_str),
        want: Some("string"),
        "extraEnvs should keep EnvVar item shape: {}",
        resolved_extra_envs.schema
    );

    let generated = generate_values_schema(
        ValuesSchemaInput::new(&schema_signals, &provider)
            .with_values_yaml(Some(&values_yaml_source)),
    );
    let extra_envs = generated
        .pointer("/properties/extraEnvs")
        .expect("generated extraEnvs property");
    sim_assert_eq!(
        have: extra_envs.pointer("/anyOf/0/type").and_then(Value::as_str),
        want: Some("array"),
        "generated extraEnvs should stay array-shaped: {extra_envs}"
    );
    sim_assert_eq!(
        have: extra_envs
            .pointer("/anyOf/0/items/properties/name/type")
            .and_then(Value::as_str),
        want: Some("string"),
        "generated extraEnvs should keep EnvVar item shape: {extra_envs}"
    );
    Ok(())
}

#[test]
fn unrelated_default_inside_set_does_not_mark_target_as_defaulted() {
    let helpers = indoc! {r#"
        {{- define "synth.defaultValues" }}
        {{- with .Values }}
        {{- $_ := set .serviceAccount "name" (printf "%s" (.other | default "fallback")) }}
        {{- end }}
        {{- end }}
    "#};
    let src = indoc! {r#"
        {{- include "synth.defaultValues" . }}
        apiVersion: v1
        kind: ServiceAccount
        metadata:
          name: {{ .Values.serviceAccount.name | quote }}
    "#};

    let ir = parse_ir_with_helpers(src, helpers);
    let projection = ir.clone().finalize();
    let guarded_target_uses: Vec<_> = projection
        .uses()
        .iter()
        .filter(|use_| {
            use_.source_expr == "serviceAccount.name"
                && use_.path.0 == ["metadata".to_string(), "name".to_string()]
        })
        .collect();
    assert!(
        !guarded_target_uses.is_empty(),
        "expected a rendered use for serviceAccount.name, got {ir:?}"
    );
    assert!(
        guarded_target_uses.iter().all(|use_| {
            !use_.single_guard_conjunction().iter().any(|guard| {
                matches!(
                    guard,
                    Guard::Default { path } if path == "serviceAccount.name"
                )
            })
        }),
        "unrelated default must not mark serviceAccount.name as defaulted: {guarded_target_uses:#?}"
    );
}

#[test]
#[expect(
    clippy::too_many_lines,
    reason = "the complete fixture scenario is clearest as one contiguous test"
)]
fn guarded_fragment_array_provider_schema_stays_precise() {
    #[derive(Debug)]
    struct RelabelingsProvider;

    impl ResourceSchemaOracle for RelabelingsProvider {
        fn schema_fragment_for_use(
            &self,
            use_: &ProviderSchemaUse,
        ) -> Option<ProviderSchemaFragment> {
            (use_.value_path == "serviceMonitor.metricRelabelings"
                && use_.path.0
                    == [
                        "spec".to_string(),
                        "endpoints[*]".to_string(),
                        "metricRelabelings".to_string(),
                    ])
            .then(|| {
                ProviderSchemaFragment::new(serde_json::json!({
                    "description": "provider relabelings",
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "action": { "type": "string" }
                        },
                        "additionalProperties": false
                    }
                }))
            })
        }
    }

    let uses = vec![
        ContractUse {
            source_expr: "serviceMonitor.metricRelabelings".to_string(),
            path: YamlPath(Vec::new()),
            kind: ValueKind::Scalar,
            condition: helm_schema_core::GuardDnf::from_guards(vec![Guard::Truthy {
                path: "serviceMonitor.enabled".to_string(),
            }]),
            resource: Some(ResourceRef::concrete(
                "monitoring.coreos.com/v1".to_string(),
                "ServiceMonitor".to_string(),
            )),
            provenance: Vec::new(),
            has_string_contract: false,
            template_supplied_member_keys: std::collections::BTreeSet::default(),
            split_segment: None,
            merge_layers: None,
            range_key: false,
            nil_omitting: false,
            omitted_members: std::collections::BTreeMap::default(),
            digest: false,
            merge_operand: false,
        },
        ContractUse {
            source_expr: "serviceMonitor.metricRelabelings".to_string(),
            path: YamlPath(vec![
                "spec".to_string(),
                "endpoints[*]".to_string(),
                "metricRelabelings".to_string(),
            ]),
            kind: ValueKind::Fragment,
            condition: helm_schema_core::GuardDnf::from_guards(vec![Guard::Truthy {
                path: "serviceMonitor.enabled".to_string(),
            }]),
            resource: Some(ResourceRef::concrete(
                "monitoring.coreos.com/v1".to_string(),
                "ServiceMonitor".to_string(),
            )),
            provenance: Vec::new(),
            has_string_contract: false,
            template_supplied_member_keys: std::collections::BTreeSet::default(),
            split_segment: None,
            merge_layers: None,
            range_key: false,
            nil_omitting: false,
            omitted_members: std::collections::BTreeMap::default(),
            digest: false,
            merge_operand: false,
        },
    ];

    let schema_signals = schema_signals_for(uses);
    let schema = generate_values_schema(
        ValuesSchemaInput::new(&schema_signals, &RelabelingsProvider).with_values_yaml(Some(
            indoc! {"
                serviceMonitor:
                  metricRelabelings: []
            "},
        )),
    );

    for (instance, want, label) in [
        (
            serde_json::json!({
                "serviceMonitor": {
                    "enabled": true,
                    "metricRelabelings": [{ "action": "replace" }]
                }
            }),
            true,
            "enabled valid relabeling",
        ),
        (
            serde_json::json!({
                "serviceMonitor": {
                    "enabled": true,
                    "metricRelabelings": [{ "action": 7 }]
                }
            }),
            false,
            "enabled invalid relabeling",
        ),
        (
            serde_json::json!({
                "serviceMonitor": {
                    "enabled": false,
                    "metricRelabelings": 7
                }
            }),
            true,
            "disabled unconstrained relabeling",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "{label}: instance={instance}; schema={schema}"
        );
    }
}

#[test]
fn repeated_exact_provider_subtrees_emit_provider_definitions() {
    let resource = ResourceRef::concrete("example.io/v1".to_string(), "Example".to_string());
    let uses = vec![
        ContractUse {
            source_expr: "first".to_string(),
            path: YamlPath(vec!["spec".to_string(), "first".to_string()]),
            kind: ValueKind::Fragment,
            condition: helm_schema_core::GuardDnf::from_guards(Vec::new()),
            resource: Some(resource.clone()),
            provenance: Vec::new(),
            has_string_contract: false,
            template_supplied_member_keys: std::collections::BTreeSet::default(),
            split_segment: None,
            merge_layers: None,
            range_key: false,
            nil_omitting: false,
            omitted_members: std::collections::BTreeMap::default(),
            digest: false,
            merge_operand: false,
        },
        ContractUse {
            source_expr: "second".to_string(),
            path: YamlPath(vec!["spec".to_string(), "second".to_string()]),
            kind: ValueKind::Fragment,
            condition: helm_schema_core::GuardDnf::from_guards(Vec::new()),
            resource: Some(resource),
            provenance: Vec::new(),
            has_string_contract: false,
            template_supplied_member_keys: std::collections::BTreeSet::default(),
            split_segment: None,
            merge_layers: None,
            range_key: false,
            nil_omitting: false,
            omitted_members: std::collections::BTreeMap::default(),
            digest: false,
            merge_operand: false,
        },
    ];
    let schema_signals = schema_signals_for(uses);

    let schema = generate_values_schema(ValuesSchemaInput::new(
        &schema_signals,
        &SharedObjectProvider,
    ));

    let expected_definition = serde_json::json!({
        "type": "array",
        "items": {
            "type": "object",
            "properties": {
                "name": { "type": "string" }
            },
            "additionalProperties": false
        }
    });
    sim_assert_eq!(
        have: schema.pointer("/properties/first"),
        want: Some(&serde_json::json!({ "$ref": "#/$defs/providerSchema1" }))
    );
    sim_assert_eq!(
        have: schema.pointer("/properties/second"),
        want: Some(&serde_json::json!({ "$ref": "#/$defs/providerSchema1" }))
    );
    sim_assert_eq!(
        have: schema.pointer("/$defs/providerSchema1"),
        want: Some(&expected_definition)
    );
}

#[test]
fn values_yaml_comments_override_provider_descriptions() {
    let uses = vec![ContractUse {
        source_expr: "name".to_string(),
        path: YamlPath(vec!["metadata".to_string(), "name".to_string()]),
        kind: ValueKind::Scalar,
        condition: helm_schema_core::GuardDnf::from_guards(Vec::new()),
        resource: Some(ResourceRef::concrete(
            "v1".to_string(),
            "ConfigMap".to_string(),
        )),
        provenance: Vec::new(),
        has_string_contract: false,
        template_supplied_member_keys: std::collections::BTreeSet::default(),
        split_segment: None,
        merge_layers: None,
        range_key: false,
        nil_omitting: false,
        omitted_members: std::collections::BTreeMap::default(),
        digest: false,
        merge_operand: false,
    }];
    let descriptions = BTreeMap::from([("name".to_string(), "chart description".to_string())]);
    let schema_signals = schema_signals_for(uses);

    let schema = generate_values_schema(
        ValuesSchemaInput::new(&schema_signals, &DescriptionProvider)
            .with_values_yaml(Some("name: example\n"))
            .with_values_descriptions(&descriptions),
    );

    sim_assert_eq!(
        have: schema
            .pointer("/properties/name/description")
            .and_then(Value::as_str),
        want: Some("chart description")
    );
}

#[test]
fn values_yaml_comments_do_not_create_schema_paths() {
    let uses = parse_ir(indoc! {r"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: {{ .Values.name }}
    "});
    let descriptions = BTreeMap::from([
        ("name".to_string(), "name description".to_string()),
        (
            "commentedOut.enabled".to_string(),
            "comment-only path".to_string(),
        ),
    ]);
    let provider = Chain::new(Vec::new());
    let schema_signals = schema_signals_for(uses);

    let schema = generate_values_schema(
        ValuesSchemaInput::new(&schema_signals, &provider)
            .with_values_yaml(Some("name: example\n"))
            .with_values_descriptions(&descriptions),
    );

    sim_assert_eq!(
        have: schema
            .pointer("/properties/name/description")
            .and_then(Value::as_str),
        want: Some("name description")
    );
    assert!(
        schema.pointer("/properties/commentedOut").is_none(),
        "description metadata must not create schema paths: {schema}"
    );
}

fn schema_has_format(schema: &Value, format: &str) -> bool {
    if schema.get("format").and_then(Value::as_str) == Some(format) {
        return true;
    }
    ["anyOf", "oneOf", "allOf"]
        .into_iter()
        .filter_map(|key| schema.get(key).and_then(Value::as_array))
        .flatten()
        .any(|variant| schema_has_format(variant, format))
}

#[test]
fn base64_encoded_secret_data_does_not_inherit_rendered_byte_format() {
    let src = indoc! {r"
        apiVersion: v1
        kind: Secret
        metadata:
          name: example
        data:
          direct: {{ .Values.directSecretData }}
          encoded: {{ .Values.password | b64enc | quote }}
    "};
    let values_yaml = indoc! {r#"
        directSecretData: ""
        password: ""
    "#};

    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));

    let direct = schema
        .pointer("/properties/directSecretData")
        .expect("directSecretData present");
    assert!(
        schema_has_format(direct, "byte"),
        "direct Secret.data input should keep provider byte format, got {direct}; schema={schema}"
    );

    let password = schema
        .pointer("/properties/password")
        .expect("password present");
    assert!(
        permits_type(password, "string"),
        "encoded input should remain string-like, got {password}; schema={schema}"
    );
    assert!(
        !schema_has_format(password, "byte"),
        "pre-encoded chart input must not inherit rendered Secret.data byte format, got {password}; schema={schema}"
    );
}

#[test]
fn included_encoded_secret_data_preserves_nullable_source_without_byte_format() {
    let helpers = indoc! {r#"
        {{- define "sample.passwordData" -}}
        {{- if .Values.password }}
        password: {{ .Values.password | b64enc | quote }}
        {{- end }}
        raw: {{ .Values.rawSecretData }}
        {{- end -}}
    "#};
    let src = indoc! {r#"
        apiVersion: v1
        kind: Secret
        metadata:
          name: example
        data:
          {{- include "sample.passwordData" . | nindent 2 }}
    "#};
    let values_yaml = indoc! {r#"
        password: ""
        rawSecretData: ""
    "#};

    let schema = schema_for_values_yaml(parse_ir_with_helpers(src, helpers), Some(values_yaml));
    let password = schema
        .pointer("/properties/password")
        .expect("password present");

    assert!(
        !schema_has_format(password, "byte"),
        "pre-encoded helper input must not inherit rendered Secret.data byte format, got {password}; schema={schema}"
    );
    for (instance, want, label) in [
        (serde_json::json!({ "password": null }), true, "null"),
        (serde_json::json!({ "password": {} }), true, "empty object"),
        (serde_json::json!({ "password": "secret" }), true, "string"),
        (serde_json::json!({ "password": 7 }), false, "truthy number"),
        (
            serde_json::json!({ "password": { "bad": true } }),
            false,
            "truthy object",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "encoded helper input {label}: instance={instance}; schema={schema}"
        );
    }

    let raw = schema
        .pointer("/properties/rawSecretData")
        .expect("rawSecretData present");
    assert!(
        schema_has_format(raw, "byte"),
        "unencoded sibling helper input should still inherit Secret.data byte format, got {raw}; schema={schema}"
    );
}

/// `tpl (toYaml .Values.X) .` re-renders the serialized fragment,
/// so the provider slot projects back to the input exactly like a bare
/// `toYaml` splice (airflow's scheduler command and extraContainers).
#[test]
fn tpl_serialized_fragment_projects_the_provider_slot() {
    let src = indoc! {r"
        apiVersion: apps/v1
        kind: Deployment
        metadata:
          name: test
        spec:
          template:
            spec:
              containers:
                - name: scheduler
                  image: img
                  {{- if .Values.scheduler.command }}
                  command: {{ tpl (toYaml .Values.scheduler.command) . | nindent 12 }}
                  {{- end }}
    "};
    let schema = schema_for_values_yaml(
        parse_ir(src),
        Some(indoc! {"
            scheduler:
              command: ~
        "}),
    );

    for (instance, want) in [
        (serde_json::json!({ "scheduler": { "command": 7 } }), false),
        (
            serde_json::json!({ "scheduler": { "command": ["bash"] } }),
            true,
        ),
        (
            serde_json::json!({ "scheduler": { "command": null } }),
            true,
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "the tpl-serialized command keeps the PodSpec string-array slot: \
             instance={instance}; schema={schema}"
        );
    }
}

/// Helm's YAML resolver reads hex, explicit octal, binary, and legacy
/// leading-zero spellings as integers, so a bare token in any of those
/// forms reparses away from the string a provider slot requires (velero's
/// unquoted `BackupStorageLocation` provider).
#[test]
fn plain_string_slot_excludes_non_decimal_integer_spellings() {
    let src = indoc! {r"
        apiVersion: apps/v1
        kind: Deployment
        metadata:
          name: test
        spec:
          template:
            spec:
              containers:
                - name: {{ .Values.containerName }}
                  image: img
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some("containerName: app\n"));

    for (instance, want) in [
        (serde_json::json!({ "containerName": "0x10" }), false),
        (serde_json::json!({ "containerName": "0o17" }), false),
        (serde_json::json!({ "containerName": "0123" }), false),
        (serde_json::json!({ "containerName": "0b101" }), false),
        (serde_json::json!({ "containerName": "app" }), true),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "non-decimal integer spellings reparse away from the string slot: \
             instance={instance}; schema={schema}"
        );
    }
}

/// A serialized fragment spliced beside a literal sibling (`- name: tmp`
/// above `toYaml .Values.tmpVolume | nindent`) completes an object the
/// template already gives that key: the provider slot's `required` must
/// not re-demand it from the user value (metrics-server's Volume slot),
/// while the slot's member typing still applies.
#[test]
fn template_supplied_sibling_keys_relax_provider_requiredness() {
    #[derive(Debug)]
    struct VolumeProvider;

    impl ResourceSchemaOracle for VolumeProvider {
        fn schema_fragment_for_use(
            &self,
            use_: &ProviderSchemaUse,
        ) -> Option<ProviderSchemaFragment> {
            (use_.value_path == "tmpVolume").then(|| {
                ProviderSchemaFragment::new(serde_json::json!({
                    "type": "object",
                    "additionalProperties": false,
                    "required": ["name"],
                    "properties": {
                        "name": { "type": "string" },
                        "emptyDir": { "type": "object", "additionalProperties": false },
                        "hostPath": {
                            "type": "object",
                            "properties": { "path": { "type": "string" } },
                            "additionalProperties": false
                        }
                    }
                }))
            })
        }
    }

    let src = indoc! {r"
        apiVersion: apps/v1
        kind: Deployment
        metadata:
          name: test
        spec:
          template:
            spec:
              volumes:
                - name: tmp
                  {{- toYaml .Values.tmpVolume | nindent 10 }}
    "};
    let ir = parse_ir(src);
    let schema_signals = ir.into_schema_signals();
    let schema = generate_values_schema(
        ValuesSchemaInput::new(&schema_signals, &VolumeProvider).with_values_yaml(Some(indoc! {"
            tmpVolume:
              emptyDir: {}
        "})),
    );

    for (instance, want, label) in [
        (
            serde_json::json!({ "tmpVolume": { "emptyDir": {} } }),
            true,
            "the template supplies name itself",
        ),
        (
            serde_json::json!({ "tmpVolume": { "hostPath": { "path": "/tmp" } } }),
            true,
            "other volume variants stay open",
        ),
        (
            serde_json::json!({ "tmpVolume": { "emptyDir": 7 } }),
            false,
            "the slot's member typing still applies",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "{label}: instance={instance}; schema={schema}"
        );
    }
}

/// A `tpl`-rendered splice gives the provider slot its OUTPUT, never the
/// raw program text, so the slot's string grammar must not back-project
/// onto the raw value (loki's `secretName: {{ tpl
/// .Values.loki.configObjectName . }}` with the templated default
/// `"{{ include \"loki.name\" . }}"`); `tpl`'s own string-input contract
/// still types the path.
#[test]
fn tpl_rendered_slots_keep_the_raw_program_open() {
    #[derive(Debug)]
    struct SecretNameProvider;

    impl ResourceSchemaOracle for SecretNameProvider {
        fn schema_fragment_for_use(
            &self,
            use_: &ProviderSchemaUse,
        ) -> Option<ProviderSchemaFragment> {
            (use_.value_path == "objectName").then(|| {
                ProviderSchemaFragment::new(serde_json::json!({
                    "type": "string",
                    "pattern": "^[a-z0-9.-]+$"
                }))
            })
        }
    }

    let src = indoc! {r"
        apiVersion: v1
        kind: Pod
        metadata:
          name: test
        spec:
          volumes:
            - name: config
              secret:
                secretName: {{ tpl .Values.objectName . }}
    "};
    let ir = parse_ir(src);
    let schema_signals = ir.into_schema_signals();
    let schema = generate_values_schema(
        ValuesSchemaInput::new(&schema_signals, &SecretNameProvider)
            .with_values_yaml(Some("objectName: \"{{ include \\\"repro.name\\\" . }}\"\n")),
    );

    for (instance, want, label) in [
        (
            serde_json::json!({ "objectName": "{{ include \"repro.name\" . }}" }),
            true,
            "a raw template program renders through tpl",
        ),
        (
            serde_json::json!({ "objectName": "plain-name" }),
            true,
            "plain names render",
        ),
        (
            serde_json::json!({ "objectName": { "a": 1 } }),
            false,
            "tpl requires a string program",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "{label}: instance={instance}; schema={schema}"
        );
    }
}

/// redis-ha's `ConfigMap` fills each `data` value with `redis.conf: |`
/// followed by a COLUMN-ZERO `{{- include "config-redis.conf" . }}`: the
/// include's rendered lines are deeper than the entry, so they continue
/// the still-open block scalar — pure text. Evaluating the include as
/// structure escaping to the parent anchors the helper's ranged `config`
/// members at the `data` field itself, whose object provider schema
/// scalar-restricts to `type: null` and rejects every member Helm renders
/// (oauth2-proxy and argo-cd with redis-ha enabled). The adopted lane must
/// keep the members open while preserving the helper's strict `tpl`
/// string-program contract on `customConfig`.
#[test]
fn block_scalar_adopted_includes_render_as_text_not_structure() {
    let helpers = indoc! {r#"
        {{- define "repro.conf" }}
        {{- if .Values.redis.customConfig }}
        {{ tpl .Values.redis.customConfig . | indent 4 }}
        {{- else }}
            dir "/data"
            port {{ .Values.redis.port }}
            {{- range $key, $value := .Values.redis.config }}
            {{ $key }} {{ $value }}
            {{- end }}
        {{- end }}
        {{- end }}
    "#};
    let src = indoc! {r#"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: test
        data:
          redis.conf: |
        {{- include "repro.conf" . }}
    "#};
    let values_yaml = indoc! {r"
        redis:
          port: 6379
          config: {}
    "};
    let schema = schema_for_values_yaml(parse_ir_with_helpers(src, helpers), Some(values_yaml));
    for (instance, want, label) in [
        (
            composed_instance(values_yaml, serde_json::json!({})),
            true,
            "defaults render",
        ),
        (
            serde_json::json!({ "redis": { "config": { "maxmemory": "100mb" } } }),
            true,
            "string members render as block text",
        ),
        (
            serde_json::json!({ "redis": { "config": { "save": "" } } }),
            true,
            "empty-string members render",
        ),
        (
            serde_json::json!({ "redis": { "config": { "repl-diskless-sync": true } } }),
            true,
            "raw scalars stringify in the loop body",
        ),
        (
            serde_json::json!({ "redis": { "customConfig": "maxmemory 100mb" } }),
            true,
            "string custom config renders through tpl",
        ),
        (
            serde_json::json!({ "redis": { "customConfig": { "bad": true } } }),
            false,
            "tpl requires a string program even under the block",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "block-adopted include ({label}): instance={instance}; schema={schema}"
        );
    }
}

/// traefik's deployment routes its pod template through
/// `include "traefik.podTemplate" . | fromYaml | toYaml | nindent`, and a
/// NESTED helper renders ranged `resourceAttributes` members as container
/// flag args. The roundtrip lane must keep those member rows anchored at
/// the args ITEM depth: anchoring one level short provider-types them by
/// the Container fragment and scalar-restricts the map to `type: null`,
/// rejecting every member Helm renders.
#[test]
fn roundtrip_pod_templates_keep_ranged_flag_rows_at_item_depth() {
    let helpers = indoc! {r#"
        {{- define "repro.flags" }}
          {{- $path := .path -}}
          {{- $cfg := .cfg -}}
          {{- if $cfg.enabled }}
          - "--{{$path}}=true"
           {{- range $name, $value := $cfg.resourceAttributes }}
          -  "--{{$path}}.resourceAttributes.{{ $name }}={{ $value }}"
           {{- end }}
          {{- end }}
        {{- end }}
        {{- define "repro.podTemplate" -}}
        metadata:
          labels:
            app: test
        spec:
          containers:
            - name: test
              image: busybox
              args:
                {{- with .Values.tracing.otlp }}
                 {{- include "repro.flags" (dict "path" "tracing.otlp" "cfg" .) | nindent 8 }}
                {{- end }}
        {{- end }}
    "#};
    let src = indoc! {r#"
        apiVersion: apps/v1
        kind: Deployment
        metadata:
          name: test
        spec:
          selector:
            matchLabels:
              app: test
          template: {{ include "repro.podTemplate" . | fromYaml | toYaml | nindent 4 }}
    "#};
    let values_yaml = indoc! {r"
        tracing:
          otlp:
            enabled: false
    "};
    let schema = schema_for_values_yaml(parse_ir_with_helpers(src, helpers), Some(values_yaml));
    for (instance, want, label) in [
        (
            composed_instance(values_yaml, serde_json::json!({})),
            true,
            "defaults render",
        ),
        (
            serde_json::json!({ "tracing": { "otlp": { "enabled": true,
                "resourceAttributes": { "env": "prod" } } } }),
            true,
            "string members render as flags",
        ),
        (
            serde_json::json!({ "tracing": { "otlp": { "enabled": true,
                "resourceAttributes": { "env": 7 } } } }),
            true,
            "non-string members stringify in the loop body",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "roundtrip flag rows ({label}): instance={instance}; schema={schema}"
        );
    }
}

/// A ranged member LEAF rendered into a provider-REQUIRED field emits an
/// explicit null for every member missing the leaf, which strict provider
/// validation rejects (kube-state-metrics' probe `httpHeaders: [{}]`
/// renders null `name`/`value`; promtail's `extraPorts` render a null
/// Service `port`). Every member must carry the leaf present and
/// non-null; an empty or absent collection runs zero iterations and stays
/// open, and a member-scoped ELSE-arm guard becomes the escape
/// alternative of a per-member disjunction.
#[test]
fn ranged_member_leaves_of_required_provider_fields_bind_presence() {
    let src = indoc! {r"
        apiVersion: apps/v1
        kind: Deployment
        metadata:
          name: test
        spec:
          selector:
            matchLabels:
              app: test
          template:
            metadata:
              labels:
                app: test
            spec:
              containers:
                - name: test
                  image: busybox
                  livenessProbe:
                    httpGet:
                      path: /healthz
                      port: http
                      {{- if .Values.probe.httpHeaders }}
                      httpHeaders:
                      {{- range $_, $header := .Values.probe.httpHeaders }}
                      - name: {{ $header.name }}
                        value: {{ $header.value }}
                      {{- end }}
                      {{- end }}
    "};
    let values_yaml = indoc! {r"
        probe:
          httpHeaders: []
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));
    for (instance, want, label) in [
        (
            composed_instance(values_yaml, serde_json::json!({})),
            true,
            "defaults render",
        ),
        (
            serde_json::json!({ "probe": { "httpHeaders": [] } }),
            true,
            "empty collection runs zero iterations",
        ),
        (
            serde_json::json!({ "probe": { "httpHeaders":
                [{ "name": "X-Audit", "value": "audit" }] } }),
            true,
            "populated headers render",
        ),
        (
            serde_json::json!({ "probe": { "httpHeaders": [{}] } }),
            false,
            "an empty member renders null name and value",
        ),
        (
            serde_json::json!({ "probe": { "httpHeaders": [{ "name": "X-Audit" }] } }),
            false,
            "a missing value renders null",
        ),
        (
            serde_json::json!({ "probe": { "httpHeaders":
                [{ "name": "X-Audit", "value": null }] } }),
            false,
            "an explicit null value renders null",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "ranged required leaf ({label}): instance={instance}; schema={schema}"
        );
    }
}

/// The helper-projection variant of the presence binding: the range lives
/// in a pod-template helper consumed through `include … | fromYaml |
/// toYaml`, and the leaf renders through Sprig `quote` — which SKIPS nil
/// operands, so a missing or null source still forces an explicit null
/// into the provider-required `VolumeMount` `mountPath` (traefik's local
/// plugins).
#[test]
fn quoted_ranged_leaves_bind_presence_through_the_pod_template_projection() {
    let helpers = indoc! {r#"
        {{- define "test.podTemplate" }}
        metadata:
          labels:
            app: test
        spec:
          containers:
            - name: test
              image: busybox
              volumeMounts:
              {{- range $name, $plugin := .Values.plugins }}
              - name: {{ $name | replace "." "-" }}
                mountPath: {{ $plugin.mountPath | quote }}
              {{- end }}
        {{- end }}
    "#};
    let src = indoc! {r#"
        apiVersion: apps/v1
        kind: Deployment
        metadata:
          name: test
        spec:
          selector:
            matchLabels:
              app: test
          template: {{ include "test.podTemplate" . | fromYaml | toYaml | nindent 4 }}
    "#};
    let values_yaml = indoc! {r"
        plugins: {}
    "};
    let schema = schema_for_values_yaml(parse_ir_with_helpers(src, helpers), Some(values_yaml));
    for (instance, want, label) in [
        (
            composed_instance(values_yaml, serde_json::json!({})),
            true,
            "defaults render",
        ),
        (
            serde_json::json!({ "plugins": { "p": { "mountPath": "/x" } } }),
            true,
            "a member with mountPath renders",
        ),
        (
            serde_json::json!({ "plugins": { "p": {} } }),
            false,
            "a member without mountPath renders null",
        ),
        (
            serde_json::json!({ "plugins": { "p": { "mountPath": null } } }),
            false,
            "an explicit null mountPath renders null",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "quoted ranged required leaf ({label}): instance={instance}; schema={schema}"
        );
    }
}

/// The member-scoped else-arm variant: promtail's extra Services render
/// `port: {{ $values.containerPort }}` only for members WITHOUT a truthy
/// `service`, so the presence requirement carries the service escape.
#[test]
fn ranged_member_required_leaves_keep_the_else_arm_escape() {
    let src = indoc! {r"
        {{- range $key, $values := .Values.extraPorts }}
        ---
        apiVersion: v1
        kind: Service
        metadata:
          name: extra-{{ $key }}
        spec:
          ports:
            - name: {{ $key }}
              protocol: TCP
              {{- if $values.service }}
              port: {{ $values.service.port | default $values.containerPort }}
              {{- else }}
              port: {{ $values.containerPort }}
              {{- end }}
          selector:
            app: test
        {{- end }}
    "};
    let values_yaml = indoc! {r"
        extraPorts: {}
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));
    for (member, want, label) in [
        (
            serde_json::json!({ "containerPort": 1234 }),
            true,
            "containerPort renders the port",
        ),
        (
            serde_json::json!({ "service": { "port": 80 } }),
            true,
            "a truthy service escapes the else arm",
        ),
        (serde_json::json!({}), false, "an empty member renders null"),
    ] {
        let instance = serde_json::json!({ "extraPorts": { "audit": member } });
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "else-arm escape ({label}): instance={instance}; schema={schema}"
        );
    }
}