cloudformation-validate-template-model 1.10.0

AWS CloudFormation Validate
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
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
use crate::authored_template::render_authored_json;
use crate::budget::{BudgetKind, BudgetTracker};
use crate::conditions::{ConditionModel, Satisfiability};
use crate::consts::*;
use crate::defect::{DefectPhase, ParseDefect};
use crate::graph::ReferenceGraph;
use crate::ir::*;
use crate::is_custom_resource_type;
use crate::json_value::JsonValue;
use crate::regions::*;
use crate::resolved_value::*;
use crate::resolver::*;
use crate::sam;
use crate::span::SpanProvider;
use log::{debug, info, warn};
use serde::Serialize;
use std::cmp::Reverse;
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet};
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};

/// A resource property path paired with a string value found at it, such as a substitution variable or literal.
#[derive(Debug, Clone, Serialize, Default)]
#[cfg_attr(feature = "wasm-bindings", derive(tsify::Tsify))]
#[cfg_attr(feature = "uniffi-bindings", derive(uniffi::Record))]
#[serde(rename_all = "camelCase")]
pub struct PathValuePair {
    /// Dot-separated property path within the resource (e.g. 'Properties.BucketName').
    pub path: String,
    pub value: String,
}

/// A property that is dropped (resolves to AWS::NoValue) in one branch of an Fn::If condition.
#[derive(Debug, Clone, Serialize, Default)]
#[cfg_attr(feature = "wasm-bindings", derive(tsify::Tsify))]
#[cfg_attr(feature = "uniffi-bindings", derive(uniffi::Record))]
#[serde(rename_all = "camelCase")]
pub struct ConditionalNullEntry {
    /// Dot-separated property path that becomes absent in one branch.
    pub path: String,
    /// Name of the condition governing the Fn::If that drops this property.
    pub condition: String,
    /// True when the property is absent in the condition's true branch; false when absent in the false branch.
    pub null_in_true_branch: bool,
}

/// Per-resource observations collected while resolving intrinsics, used to drive lint checks.
#[derive(Debug, Clone, Serialize, Default)]
#[cfg_attr(feature = "wasm-bindings", derive(tsify::Tsify))]
#[cfg_attr(feature = "uniffi-bindings", derive(uniffi::Record))]
#[serde(rename_all = "camelCase")]
pub struct ResourceDiagnostics {
    /// Mapping names referenced by Fn::FindInMap within this resource.
    pub find_in_map_refs: Vec<String>,
    /// Fn::Sub uses whose template is a single variable that could be a plain Ref; each pairs the property path with the variable name.
    pub simple_subs: Vec<PathValuePair>,
    /// Property paths where Fn::Sub wraps a constant string with no variables to substitute.
    pub redundant_subs: Vec<String>,
    /// Property paths where Fn::Join uses an empty delimiter, concatenating its elements directly.
    pub empty_joins: Vec<String>,
    /// Names of conditions referenced by this resource's property values.
    pub condition_refs: Vec<String>,
    /// Property paths building ARNs with a hardcoded 'aws' partition instead of AWS::Partition.
    pub hardcoded_partition_arns: Vec<String>,
    pub conditionally_null_props: Vec<ConditionalNullEntry>,
    pub foreach_expansions: Vec<ForEachExpansion>,
    /// Occurrences of ${...} placeholders outside an Fn::Sub that will not be substituted; each pairs the property path with the placeholder text.
    pub unsubstituted_variables: Vec<PathValuePair>,
    /// Fn::Sub map keys not referenced in the template string; each pairs the property path with the unused key name.
    pub unused_sub_keys: Vec<PathValuePair>,
    /// Property values that are a raw pseudo-parameter string (e.g. "AWS::Region") instead of using Ref.
    pub raw_pseudo_params: Vec<PathValuePair>,
    /// Property paths containing a {{resolve:secretsmanager:...}} dynamic reference.
    pub secretsmanager_ref_paths: Vec<String>,
    /// References whose target is not a defined resource, parameter, or pseudo parameter; each pairs the property path with the missing target name.
    pub invalid_refs: Vec<PathValuePair>,
}

/// A template resource with its metadata and properties after intrinsic functions have been resolved.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "wasm-bindings", derive(tsify::Tsify))]
#[cfg_attr(feature = "uniffi-bindings", derive(uniffi::Record))]
#[serde(rename_all = "camelCase")]
pub struct ResolvedResource {
    pub logical_id: String,
    pub resource_type: String,
    #[cfg_attr(feature = "wasm-bindings", tsify(optional))]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub condition: Option<String>,
    pub depends_on: Vec<String>,
    #[cfg_attr(feature = "wasm-bindings", tsify(optional))]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub deletion_policy: Option<ResolvedValue>,
    #[cfg_attr(feature = "wasm-bindings", tsify(optional))]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub update_replace_policy: Option<ResolvedValue>,
    #[cfg_attr(feature = "wasm-bindings", tsify(optional, type = "JsonValue"))]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub update_policy: Option<JsonValue>,
    #[cfg_attr(feature = "wasm-bindings", tsify(optional, type = "JsonValue"))]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub creation_policy: Option<JsonValue>,
    #[cfg_attr(feature = "wasm-bindings", tsify(optional, type = "JsonValue"))]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub metadata: Option<JsonValue>,
    #[cfg_attr(feature = "wasm-bindings", tsify(type = "Record<string, ResolvedValue>"))]
    pub properties: HashMap<String, ResolvedValue>,
    /// True when the entire `Properties` block is a non-map intrinsic (e.g.
    /// `Properties: !Ref AWS::NoValue`) whose effective property set is only known
    /// at deploy time, as distinct from a resource that simply declares no properties.
    pub properties_dynamic: bool,
    pub diagnostics: ResourceDiagnostics,
}

/// Effective top-level state of a lifecycle attribute after reachable
/// `Fn::If` branches and `AWS::NoValue` removal are considered.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct LifecycleAttributeStatus {
    /// At least one reachable branch keeps the attribute on the resource.
    pub may_be_present: bool,
    /// The first reachable authored scalar or list, rendered for a type diagnostic.
    pub invalid_value: Option<String>,
}

struct PrimaryIdentifierScenario {
    identity_tuple: Vec<String>,
    display_tuple: Vec<String>,
    assumptions: Vec<(String, bool)>,
}

/// Where a candidate comparison sits in the original all-pairs traversal: left
/// resource, then right resource, then left scenario, then right scenario. Merging
/// every identity group by this key replays comparisons - and therefore the
/// satisfiability queries they issue - in the identical order and count the
/// all-pairs traversal produced, so the model's shared, cumulative satisfiability
/// budget is drawn down exactly as before.
type PrimaryIdentifierComparisonOrder = (usize, usize, usize, usize);

/// Yields the resource/scenario comparisons within one primary-identifier identity
/// group in [`PrimaryIdentifierComparisonOrder`]. Grouping by identity first skips
/// the cross-identity pairs the all-pairs traversal built only to discard, while
/// this cursor preserves the surviving comparisons' original order so results and
/// satisfiability accounting are unchanged.
struct IdentityGroupPairCursor {
    /// Distinct resources in the group in ascending `per_resource` index, each with
    /// its matching scenario indices in ascending order.
    resources: Vec<(usize, Vec<usize>)>,
    left_resource: usize,
    right_resource: usize,
    left_scenario: usize,
    right_scenario: usize,
}

impl IdentityGroupPairCursor {
    /// A cursor over one identity group's comparisons, or `None` when the group
    /// spans fewer than two resources and so has nothing to compare. `candidates`
    /// are `(per_resource index, scenario index)` pairs in ascending order, so
    /// consecutive entries that share a resource index belong to that resource.
    fn new(candidates: &[(usize, usize)]) -> Option<Self> {
        let mut resources: Vec<(usize, Vec<usize>)> = Vec::new();
        for &(resource_index, scenario_index) in candidates {
            match resources.last_mut() {
                Some((last_resource_index, scenario_indices)) if *last_resource_index == resource_index => {
                    scenario_indices.push(scenario_index);
                }
                _ => resources.push((resource_index, vec![scenario_index])),
            }
        }
        if resources.len() < 2 {
            return None;
        }
        Some(Self { resources, left_resource: 0, right_resource: 1, left_scenario: 0, right_scenario: 0 })
    }
}

impl Iterator for IdentityGroupPairCursor {
    type Item = PrimaryIdentifierComparisonOrder;

    fn next(&mut self) -> Option<Self::Item> {
        while self.left_resource + 1 < self.resources.len() {
            if self.right_resource >= self.resources.len() {
                self.left_resource += 1;
                self.right_resource = self.left_resource + 1;
                self.left_scenario = 0;
                self.right_scenario = 0;
                continue;
            }
            if self.left_scenario >= self.resources[self.left_resource].1.len() {
                self.right_resource += 1;
                self.left_scenario = 0;
                self.right_scenario = 0;
                continue;
            }
            if self.right_scenario >= self.resources[self.right_resource].1.len() {
                self.left_scenario += 1;
                self.right_scenario = 0;
                continue;
            }
            let comparison = (
                self.resources[self.left_resource].0,
                self.resources[self.right_resource].0,
                self.resources[self.left_resource].1[self.left_scenario],
                self.resources[self.right_resource].1[self.right_scenario],
            );
            self.right_scenario += 1;
            return Some(comparison);
        }
        None
    }
}

/// An Fn::ForEach loop within a resource that expands a property over a collection.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "wasm-bindings", derive(tsify::Tsify))]
#[cfg_attr(feature = "uniffi-bindings", derive(uniffi::Record))]
#[serde(rename_all = "camelCase")]
pub struct ForEachExpansion {
    /// Property path within the resource where the Fn::ForEach appears.
    pub property_path: String,
    /// Loop variable name bound to each element during expansion.
    pub identifier: String,
    /// Human-readable description of the collection being iterated over.
    pub collection_source: String,
}

/// A template output with its value and metadata after intrinsic functions have been resolved.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "wasm-bindings", derive(tsify::Tsify))]
#[cfg_attr(feature = "uniffi-bindings", derive(uniffi::Record))]
#[serde(rename_all = "camelCase")]
pub struct ResolvedOutput {
    pub value: ResolvedValue,
    #[cfg_attr(feature = "wasm-bindings", tsify(optional))]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub description: Option<String>,
    #[cfg_attr(feature = "wasm-bindings", tsify(optional))]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub condition: Option<String>,
    #[cfg_attr(feature = "wasm-bindings", tsify(optional))]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub export_name: Option<ResolvedValue>,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TemplateRule {
    pub name: String,
    pub condition: Option<serde_json::Value>,
    #[serde(skip)]
    pub condition_node: crate::ir::NodeRef,
    pub assertions: Vec<RuleAssertion>,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RuleAssertion {
    pub assert: serde_json::Value,
    #[serde(skip)]
    pub assert_node: crate::ir::NodeRef,
    pub description: Option<String>,
}

pub struct SemanticModel {
    pub arena: Arena,
    /// The template's top-level map in `arena`; the authored view is rendered from it.
    root: NodeRef,
    /// The template as CloudFormation JSON, rendered from `arena` on first request
    /// and shared by every consumer that evaluates the authored template.
    authored_template: OnceLock<serde_json::Value>,
    pub span_index: SourceSpanIndex,
    pub format_version: Option<String>,
    pub description: Option<String>,
    pub transforms: Vec<String>,
    pub raw_top_level_keys: Vec<String>,
    pub template_metadata: Option<serde_json::Value>,
    pub rules: Option<serde_json::Value>,
    pub parsed_rules: Vec<TemplateRule>,
    pub parameters: HashMap<String, ParameterInfo>,
    pub mappings: MappingData,
    pub conditions: ConditionModel,
    pub resources: HashMap<String, ResolvedResource>,
    pub outputs: HashMap<String, ResolvedOutput>,
    pub graph: ReferenceGraph,
    pub resources_by_type: HashMap<String, Vec<String>>,
    pub diagnostics: Vec<ParseDefect>,
    pub output_empty_joins: Vec<String>,
    pub sam_globals: HashMap<String, HashMap<String, serde_json::Value>>,
    pub sam_implicit_resources: HashSet<String>,
    pub globals_param_refs: Vec<String>,
    pub is_cdk: bool,
    pub fn_if_conditions: Vec<String>,
    /// Mapping names referenced by an `Fn::FindInMap` with a literal map name,
    /// collected template-wide (resources, outputs, conditions, ForEach bodies).
    pub find_in_map_names: HashSet<String>,
    /// Parameter names referenced from within another parameter's definition
    /// (e.g. a Default of `!Ref OtherParam`); these still count as usage.
    pub params_referenced_in_definitions: HashSet<String>,
    /// True when any `Fn::FindInMap` uses a non-literal map name, which disables
    /// the unused-mapping check because usage can no longer be attributed to a
    /// specific mapping.
    pub has_dynamic_findinmap_name: bool,
    pub resolution_sources: HashMap<(String, String), String>,
    /// Per-resource set of property paths whose value is produced by an intrinsic
    /// function - either recorded with an `Intrinsic/*` resolution source or
    /// anchoring a reference edge. Built once at construction so `is_from_intrinsic`
    /// answers ancestor queries with borrowed lookups instead of rescanning the
    /// resolution sources and outgoing edges on every call.
    intrinsic_source_paths: HashMap<String, HashSet<String>>,
    /// (resource_id, property_path) → authored expression retained for opaque
    /// value identity or concrete intrinsic structure inspection.
    value_nodes: HashMap<(String, String), NodeRef>,
    /// Authored lifecycle attributes retained for condition-aware presence and
    /// top-level shape analysis without changing their public raw JSON view.
    lifecycle_attribute_nodes: HashMap<(String, String), NodeRef>,
    lifecycle_attribute_status_cache: Mutex<HashMap<(String, String), LifecycleAttributeStatus>>,
    /// Resource IDs whose authored `Condition` attribute is present but is not a
    /// condition-name string. Their deployment coexistence cannot be determined.
    invalid_resource_conditions: HashSet<String>,
    /// Synthetic condition names created for `Fn::If` first arguments that are
    /// expressions rather than condition-name strings. The expressions remain
    /// available for best-effort value resolution but cannot prove reachability.
    invalid_inline_conditions: HashSet<String>,
    resolve_memo: Mutex<HashMap<(String, String), Option<ResolvedValue>>>,
    raw_scenario_memo: Mutex<HashMap<(String, String), Vec<(ResolvedValue, HashMap<String, bool>)>>>,
    properties_scenario_cache: Mutex<HashMap<String, Arc<Vec<(ResolvedValue, HashMap<String, bool>)>>>>,
    scenario_memo: Mutex<HashMap<(String, String), Arc<Vec<(serde_json::Value, HashMap<String, bool>)>>>>,
    lifecycle_policy_scenario_cache: Mutex<HashMap<(String, String), Vec<(serde_json::Value, HashMap<String, bool>)>>>,
    /// Cumulative count of scenarios materialized by `resolve_scenarios` across
    /// the whole validation, charged against `MAX_TOTAL_SCENARIO_COMBINATIONS`.
    /// Bounds total scenario-expansion work the way `ConditionModel`'s
    /// `sat_iterations_used` bounds total satisfiability work.
    scenario_combinations_used: AtomicU64,
    /// Deterministic, deduplicating tracker for all validation-budget
    /// exhaustions across model construction and downstream validation.
    budget_tracker: Arc<BudgetTracker>,
    /// Serializes scenario expansion and budget charging. Scenario queries may
    /// run concurrently in rule-engine workers; holding this lock from budget
    /// reservation through accounting prevents concurrent queries from jointly
    /// exceeding the model-wide limit.
    scenario_expansion_lock: Mutex<()>,
    /// Set once when scenario expansion omits at least one possible scenario,
    /// whether because a per-value product or the remaining model-wide budget
    /// was exhausted. The flag is monotonic and produces one advisory later.
    scenario_expansion_curtailed: AtomicBool,
}

/// Values used for AWS pseudo parameters (Ref AWS::Region, AWS::AccountId, ...) when
/// resolving the template; any field left unset falls back to a sensible default.
#[derive(Debug, Clone, Default, Serialize, serde::Deserialize)]
#[cfg_attr(feature = "wasm-bindings", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm-bindings", tsify(from_wasm_abi))]
#[cfg_attr(feature = "uniffi-bindings", derive(uniffi::Record))]
#[serde(rename_all = "camelCase")]
pub struct PseudoParameterOverrides {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub account_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub notification_arns: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub partition: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub region: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub stack_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub stack_name: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub url_suffix: Option<String>,
}

fn is_account_id_shaped(value: &str) -> bool {
    value.len() == 12 && value.bytes().all(|b| b.is_ascii_digit())
}

fn is_partition_shaped(value: &str) -> bool {
    value.starts_with("aws")
}

impl PseudoParameterOverrides {
    pub fn region(&self) -> &str {
        self.region.as_deref().unwrap_or(DEFAULT_REGION)
    }

    pub fn get(&self, name: &str) -> Option<String> {
        match name {
            PSEUDO_ACCOUNT_ID => Some(self.account_id.clone().unwrap_or_else(|| DEFAULT_ACCOUNT_ID.into())),
            PSEUDO_NOTIFICATION_ARNS => Some(self.notification_arns.clone().unwrap_or_else(|| {
                let r = self.region();
                let p = self.partition.as_deref().unwrap_or_else(|| partition_for_region(r));
                format!("arn:{}:sns:{}:{}:notification", p, r, DEFAULT_ACCOUNT_ID)
            })),
            PSEUDO_PARTITION => {
                Some(self.partition.clone().unwrap_or_else(|| partition_for_region(self.region()).into()))
            }
            PSEUDO_REGION => Some(self.region().to_string()),
            PSEUDO_STACK_ID => Some(self.stack_id.clone().unwrap_or_else(|| {
                let r = self.region();
                let p = self.partition.as_deref().unwrap_or_else(|| partition_for_region(r));
                format!(
                    "arn:{}:cloudformation:{}:{}:stack/{}/51af3dc0-da77-11e4-872e-1234567db123",
                    p, r, DEFAULT_ACCOUNT_ID, DEFAULT_STACK_NAME
                )
            })),
            PSEUDO_STACK_NAME => Some(self.stack_name.clone().unwrap_or_else(|| DEFAULT_STACK_NAME.into())),
            PSEUDO_URL_SUFFIX => {
                Some(self.url_suffix.clone().unwrap_or_else(|| url_suffix_for_region(self.region()).into()))
            }
            _ => None,
        }
    }

    #[must_use]
    pub fn invalid_overrides(&self) -> Vec<String> {
        let mut problems = Vec::new();
        if let Some(account_id) = self.account_id.as_deref()
            && !is_account_id_shaped(account_id)
        {
            problems.push(format!("{PSEUDO_ACCOUNT_ID} override '{account_id}' is not a 12-digit AWS account ID"));
        }
        if let Some(partition) = self.partition.as_deref()
            && !is_partition_shaped(partition)
        {
            problems.push(format!(
                "{PSEUDO_PARTITION} override '{partition}' is not a valid partition \
                 (expected an 'aws'-family value such as aws, aws-cn, or aws-us-gov)"
            ));
        }
        problems
    }

    /// Returns the user-supplied override for `name` only when the caller
    /// explicitly set the corresponding field. Auto-derived defaults - e.g. the
    /// commercial-vs-cn-vs-gov partition implied by `region` - are *not*
    /// returned here.
    ///
    /// The satisfiability solver uses this to decide whether a pseudo-parameter
    /// is a constant (user pinned its value) or a free variable ranging over
    /// the literals it is compared against plus a sentinel for "any other
    /// value". `get` always returns a default and would force the solver to
    /// treat every pseudo-parameter as a constant, producing false-positive
    /// "unreachable branch" diagnostics for templates that branch on
    /// `AWS::Partition`, `AWS::Region`, etc. - see `ConditionModel::eval_value_concrete`.
    pub fn fixed_value(&self, name: &str) -> Option<String> {
        match name {
            PSEUDO_ACCOUNT_ID => self.account_id.clone(),
            PSEUDO_NOTIFICATION_ARNS => self.notification_arns.clone(),
            PSEUDO_PARTITION => self.partition.clone(),
            PSEUDO_REGION => self.region.clone(),
            PSEUDO_STACK_ID => self.stack_id.clone(),
            PSEUDO_STACK_NAME => self.stack_name.clone(),
            PSEUDO_URL_SUFFIX => self.url_suffix.clone(),
            _ => None,
        }
    }
}

#[derive(Default)]
pub struct ParseConfig {
    pub parameters: HashMap<String, String>,
    pub pseudo_parameters: PseudoParameterOverrides,
}

#[must_use]
pub struct ParseResult {
    pub model: SemanticModel,
    /// Wall-clock time spent building the model, in milliseconds.
    pub model_build_ms: f64,
}

impl SemanticModel {
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, ParseError> {
        Self::parse(bytes, Default::default()).map(|r| r.model)
    }

    pub fn parse(bytes: &[u8], config: ParseConfig) -> Result<ParseResult, ParseError> {
        if bytes.len() > MAX_TEMPLATE_SIZE_BYTES {
            return Err(ParseError {
                message: format!("Template exceeds maximum size of {}MB", MAX_TEMPLATE_SIZE_BYTES / (1024 * 1024)),
                line: None,
                column: None,
            });
        }

        let total_start = web_time::Instant::now();

        info!("Phase 1: Parsing IR ({} bytes)", bytes.len());
        let mut ir = crate::parser::parse(bytes)?;
        let foreach_diagnostics = crate::transform_expansion::expand_language_extensions(&mut ir);
        let condition_shape_diagnostics =
            crate::parser::condition_shape::validate_condition_bodies(&ir.arena, ir.conditions, &ir.span_index);
        let (parameters, parameter_diagnostics) = extract_parameters(&ir);
        // A parameter's definition can reference another parameter (e.g. a
        // Default given as `!Ref OtherParam`). Such a reference still counts as
        // usage, so collect the parameter names referenced from within the
        // Parameters section to feed the unused-parameter check.
        let params_referenced_in_definitions = collect_parameter_definition_refs(&ir, &parameters);
        let (mappings, mapping_diagnostics) = extract_mappings(&ir);

        // Create the shared budget tracker early so it is available before any
        // condition-model or resolver work can exhaust a budget.
        let budget_tracker = Arc::new(BudgetTracker::new());

        let mut conditions = ConditionModel::from_ir_with_tracker(
            &ir,
            &parameters,
            &config.pseudo_parameters,
            &mappings,
            Arc::clone(&budget_tracker),
        );

        let resource_ids: Vec<String> = if ir.resources != NULL_REF {
            ir.arena
                .as_map(ir.resources)
                .map(|entries| entries.iter().map(|(k, _)| k.clone()).collect())
                .unwrap_or_default()
        } else {
            vec![]
        };
        let output_count =
            if ir.outputs != NULL_REF { ir.arena.as_map(ir.outputs).map(|e| e.len()).unwrap_or(0) } else { 0 };
        info!("Phase 2: Resolving {} resources, {} outputs", resource_ids.len(), output_count);

        let mut resolver = Resolver::new(
            &ir.arena,
            &parameters,
            &mappings,
            resource_ids.iter().cloned().collect(),
            &config.parameters,
            &config.pseudo_parameters,
        );
        let mut resources = HashMap::new();
        let mut lifecycle_attribute_nodes = HashMap::new();
        let mut invalid_resource_conditions = HashSet::new();
        if ir.resources != NULL_REF
            && let Some(entries) = ir.arena.as_map(ir.resources)
        {
            // Pre-scan: record each resource's DefinitionSubstitutions keys so
            // definition placeholders can be checked for membership per variable.
            for (rname, rnode) in entries {
                if let Some(props) = ir.arena.as_map(*rnode) {
                    for (key, val) in props {
                        if key == KEY_PROPERTIES
                            && let Some(prop_entries) = ir.arena.as_map(*val)
                            && let Some((_, subs_ref)) =
                                prop_entries.iter().find(|(k, _)| k == "DefinitionSubstitutions")
                            && let Some(subs) = ir.arena.as_map(*subs_ref)
                        {
                            resolver
                                .def_subs_resources
                                .entry(rname.clone())
                                .or_default()
                                .extend(subs.iter().map(|(k, _)| k.clone()));
                        }
                    }
                }
            }
            for (name, node_ref) in entries.iter().cloned() {
                if let Some(resource_entries) = ir.arena.as_map(node_ref) {
                    for attribute in
                        [KEY_CREATION_POLICY, KEY_UPDATE_POLICY, KEY_DELETION_POLICY, KEY_UPDATE_REPLACE_POLICY]
                    {
                        if let Some((_, value_ref)) = resource_entries.iter().find(|(key, _)| key == attribute) {
                            lifecycle_attribute_nodes.insert((name.clone(), attribute.to_string()), *value_ref);
                        }
                    }
                }
                if invalid_resource_condition_ref(&ir.arena, node_ref).is_some() {
                    invalid_resource_conditions.insert(name.clone());
                }
                // Validate resource body shape before resolution. `Fn::ForEach::`
                // synthetic IDs are expanded by the language-extensions transform
                // and do not have standard resource shapes.
                if name != FN_TRANSFORM && !name.starts_with(FN_FOR_EACH_KEY_PREFIX) {
                    let has_sam_transform = ir.transforms.iter().any(|t| t == TRANSFORM_SERVERLESS);
                    let shape_defects =
                        validate_resource_shape(&ir.arena, &name, node_ref, has_sam_transform, &ir.span_index);
                    resolver.diagnostics.extend(shape_defects);
                }
                resolver.set_current_resource(&name);
                let resolved = resolve_resource(&ir.arena, &name, node_ref, &mut resolver);
                resources.insert(name.clone(), resolved);
            }
        }
        for (name, res) in &resources {
            debug!(
                "Resolved '{}' ({}): {} properties, {} edges, condition={:?}",
                name,
                res.resource_type,
                res.properties.len(),
                resolver.edges.iter().filter(|e| e.source_resource == *name).count(),
                res.condition
            );
        }

        let mut outputs = HashMap::new();
        if ir.outputs != NULL_REF
            && let Some(entries) = ir.arena.as_map(ir.outputs)
        {
            for (name, node_ref) in entries.iter().cloned() {
                resolver.set_current_resource(&format!("{}{}", OUTPUT_PSEUDO_RESOURCE_PREFIX, name));
                resolver.set_current_path(&format!("Outputs/{}/Value", name));
                let resolved = resolve_output(&ir.arena, node_ref, &mut resolver);
                outputs.insert(name.clone(), resolved);
            }
        }

        // Walk the Rules section so that `Ref`/`Fn::Sub`/`Fn::ValueOf` etc.
        // appearing inside rule conditions and assertions emit reference
        // edges. Without this pass, parameters used only in Rules-section
        // assertions would appear unreferenced to downstream rule checks.
        if ir.rules != NULL_REF
            && let Some(rule_entries) = ir.arena.as_map(ir.rules)
        {
            for (rule_name, rule_node) in rule_entries.iter().cloned() {
                resolver.set_current_resource(&format!("{}{}", RULE_PSEUDO_RESOURCE_PREFIX, rule_name));
                let cond_ref = ir.arena.map_get(rule_node, KEY_RULE_CONDITION);
                if let Some(cond_ref) = cond_ref {
                    resolver.set_current_path(&format!("Rules/{}/{}", rule_name, KEY_RULE_CONDITION));
                    resolver.resolve_node(cond_ref);
                }
                let assertions_ref = ir.arena.map_get(rule_node, KEY_ASSERTIONS);
                if let Some(assertions_ref) = assertions_ref
                    && let Some(assertion_items) = ir.arena.as_list(assertions_ref)
                {
                    for (idx, item_ref) in assertion_items.to_vec().iter().enumerate() {
                        if let Some(assert_ref) = ir.arena.map_get(*item_ref, KEY_ASSERT) {
                            resolver.set_current_path(&format!(
                                "Rules/{}/{}/{}/{}",
                                rule_name, KEY_ASSERTIONS, idx, KEY_ASSERT
                            ));
                            resolver.resolve_node(assert_ref);
                        }
                    }
                }
            }
        }

        info!("Phase 3: Building reference graph from {} resolver edges", resolver.edges.len());

        // Register inline conditions (from IfExpr) into the condition model in
        // one batch, so the derived mutex/implication passes run once. Preserve
        // their invalid authored origin separately from their best-effort model.
        let invalid_inline_conditions = resolver.inline_conditions.iter().map(|(name, _)| name.clone()).collect();
        conditions.register_inline_batch(resolver.inline_conditions.drain(..));

        // Collect every mapping name referenced by an Fn::FindInMap anywhere in
        // the template (resources, outputs, conditions, ForEach bodies). A literal
        // first argument names a specific mapping; a non-literal one (e.g. a nested
        // Fn::FindInMap or Ref) means the referenced mapping can't be determined
        // statically, which disables the unused-mapping check.
        let mut find_in_map_names: std::collections::HashSet<String> = std::collections::HashSet::new();
        let mut has_dynamic_findinmap_name = false;
        for idx in 0..ir.arena.len() {
            if let Node::Intrinsic(IntrinsicFn::FindInMap(map_name_ref, _, _, _)) = ir.arena.node(idx as NodeRef) {
                match ir.arena.as_str(*map_name_ref) {
                    Some(name) => {
                        find_in_map_names.insert(name.to_string());
                    }
                    None => has_dynamic_findinmap_name = true,
                }
            }
        }

        let resolution_sources = resolver.resolution_sources();
        let value_nodes = resolver.value_nodes();
        let resolver_depth_exceeded = resolver.depth_exceeded;
        let resolver_enum_expansion_exceeded = resolver.enum_expansion_exceeded;
        let mut all_edges = resolver.edges;
        for (id, res) in &resources {
            for dep in &res.depends_on {
                all_edges.push(ResolverEdge {
                    source_resource: id.clone(),
                    source_path: KEY_DEPENDS_ON.to_string(),
                    target: dep.clone(),
                    kind: RefKind::DependsOn,
                    span: UNKNOWN_SPAN,
                    condition_context: None,
                });
            }
        }
        let graph = ReferenceGraph::build(all_edges, &resource_ids);

        let intrinsic_source_paths = build_intrinsic_source_paths(&resolution_sources, &graph);

        let mut resources_by_type: HashMap<String, Vec<String>> = HashMap::new();
        for (id, res) in &resources {
            resources_by_type.entry(res.resource_type.clone()).or_default().push(id.clone());
        }
        // Deterministic iteration across engines and runs: resource IDs within each
        // resource type are returned in template-declaration order (ascending by source
        // line/column). HashMap iteration is otherwise non-deterministic and was causing
        // per-pair diagnostic rules (e.g. subnet overlap) to attribute findings to
        // different resources on different runs.
        for ids in resources_by_type.values_mut() {
            ids.sort_by_key(|id| {
                let key = format!("Resources/{}", id);
                ir.span_index.get(key.as_str()).map(|s| (s.start_line, s.start_column)).unwrap_or((u32::MAX, u32::MAX))
            });
        }

        let mut diagnostics = ir.diagnostics;
        diagnostics.extend(foreach_diagnostics);
        diagnostics.extend(condition_shape_diagnostics);
        diagnostics.extend(mapping_diagnostics);
        diagnostics.extend(parameter_diagnostics);

        diagnostics.extend(crate::nesting::validate_intrinsic_nesting(&ir.arena));
        diagnostics.extend(crate::intrinsic_arg_shapes::validate_intrinsic_arg_shapes(&ir.arena, &ir.transforms));
        diagnostics.extend(crate::lang_ext_shapes::validate_lang_ext_parameter_shapes(&ir.arena, &ir.transforms));
        diagnostics.extend(crate::language_extensions::validate_language_extensions(&ir.arena, &ir.transforms));
        let lifecycle_resource_conditions: HashMap<String, String> = resources
            .iter()
            .filter_map(|(resource_id, resource)| {
                resource.condition.as_ref().map(|condition| (resource_id.clone(), condition.clone()))
            })
            .collect();
        diagnostics.extend(crate::language_extensions::validate_lifecycle_intrinsics(
            &ir.arena,
            &conditions,
            &lifecycle_attribute_nodes,
            &lifecycle_resource_conditions,
        ));
        diagnostics.extend(crate::dynamic_ref::validate_dynamic_references(&ir.arena, ir.resources));

        let mut fn_if_conditions: Vec<String> = Vec::new();
        for idx in 0..ir.arena.len() {
            match ir.arena.node(idx as NodeRef) {
                Node::Intrinsic(IntrinsicFn::If(cond_name, _, _)) => {
                    fn_if_conditions.push(cond_name.clone());
                    // Inside a Conditions-section body, Fn::If is not a valid
                    // condition function at all - that is the not-a-boolean
                    // finding's territory, so the name of a function that is
                    // itself rejected there is not checked.
                    let in_conditions_body =
                        ir.arena.get(idx as NodeRef).path.split('/').next() == Some(SECTION_CONDITIONS);
                    if !in_conditions_body && !conditions.conditions.contains_key(cond_name) {
                        // A single owner for the undefined-Fn::If-condition
                        // finding. Emitting it here (during the arena scan, which
                        // sees every Fn::If regardless of nesting) rather than in
                        // each engine keeps the two engines identical and covers
                        // the no-Conditions-section case, where a condition-name
                        // reference is still invalid.
                        let condition_path = format!("{}/{}/0", ir.arena.get(idx as NodeRef).path, FN_IF);
                        diagnostics.push(crate::make_parse_defect_at(
                            "E1028",
                            format!("Fn::If condition '{}' does not exist in Conditions section", cond_name),
                            ir.span_index
                                .get(&condition_path)
                                .copied()
                                .unwrap_or_else(|| ir.arena.span(idx as NodeRef)),
                            &condition_path,
                        ));
                    }
                }
                // A structurally malformed Fn::If (wrong arity, wrong type) is
                // rejected by the parser and left as a plain `Fn::If` map node
                // rather than an `IntrinsicFn::If`. Its condition is still
                // referenced, so collect the name here too - otherwise the
                // unused-condition check would wrongly flag a condition that the
                // template does reference.
                Node::Map(entries) if entries.len() == 1 && entries[0].0 == FN_IF => {
                    if let Some(first) = ir.arena.as_list(entries[0].1).and_then(|items| items.first())
                        && let Some(cond_name) = ir.arena.as_str(*first)
                    {
                        fn_if_conditions.push(cond_name.to_string());
                        // The structure error is reported separately; the
                        // undefined condition name is its own finding - a
                        // malformed Fn::If gets both. Conditions-section
                        // bodies are excluded for the same reason as the
                        // well-formed arm.
                        let in_conditions_body =
                            ir.arena.get(idx as NodeRef).path.split('/').next() == Some(SECTION_CONDITIONS);
                        if !in_conditions_body && !conditions.conditions.contains_key(cond_name) {
                            diagnostics.push(crate::make_parse_defect_at(
                                "E1028",
                                format!("Fn::If condition '{}' does not exist in Conditions section", cond_name),
                                ir.arena.span(*first),
                                &ir.arena.get(*first).path,
                            ));
                        }
                    }
                }
                _ => {}
            }
        }
        fn_if_conditions.sort();
        fn_if_conditions.dedup();
        let mut output_empty_joins: Vec<String> = Vec::new();
        for (key, joins) in &resolver.empty_joins {
            if key.starts_with(OUTPUT_PSEUDO_RESOURCE_PREFIX) || key == OUTPUTS_PSEUDO_RESOURCE {
                output_empty_joins.extend(joins.iter().cloned());
            }
        }

        // Raw pseudo-parameter strings in the Outputs section. Such findings are
        // collected against the `__output__`/`__outputs__` pseudo-resources,
        // which are filtered out of the serialized model the engines scan, so
        // the engine rule never sees them. Emit them here (both engines share
        // this parse-time output) so a pseudo-parameter used as a plain string
        // in an output Value is reported the same as one in a resource.
        {
            let mut output_raw_pseudo: Vec<(String, String)> = Vec::new();
            for (key, entries) in &resolver.raw_pseudo_params {
                if key.starts_with(OUTPUT_PSEUDO_RESOURCE_PREFIX) || key == OUTPUTS_PSEUDO_RESOURCE {
                    for (path, value) in entries {
                        output_raw_pseudo.push((path.clone(), value.clone()));
                    }
                }
            }
            output_raw_pseudo.sort();
            for (path, value) in output_raw_pseudo {
                diagnostics.push(crate::make_parse_defect(
                    "W1054",
                    format!(
                        "Found a string '{}' that appears to be a pseudo parameter reference; use 'Ref: {}' instead",
                        value, value
                    ),
                    ir.span_index.get(&path).copied().unwrap_or(UNKNOWN_SPAN),
                ));
            }
        }

        // Raw pseudo-parameter strings in parameter Default values: a Default
        // that is exactly a pseudo-parameter string (e.g. "AWS::Region") is
        // almost certainly a mistake. Parameters are not walked by the resolver,
        // so check the raw default strings directly.
        {
            let mut param_names: Vec<&String> = parameters.keys().collect();
            param_names.sort();
            for pname in param_names {
                if let Some(default) = &parameters[pname].default
                    && PSEUDO_PARAMETERS.contains(&default.as_str())
                {
                    diagnostics.push(crate::make_parse_defect(
                        "W1054",
                        format!("Found a string '{}' that appears to be a pseudo parameter reference; use 'Ref: {}' instead", default, default),
                        ir.span_index.get(&format!("Parameters/{}/Default", pname)).copied().unwrap_or(UNKNOWN_SPAN),
                    ));
                }
            }
        }

        // Raw pseudo-parameter strings in Mappings values and Conditions.
        // Neither section is walked by the resolver (it only visits resources
        // and outputs), so scan their string nodes directly. `Ref` targets are
        // not string nodes in the arena, so `Ref: AWS::Region` is naturally
        // exempt - only a pseudo-parameter used as plain string data fires.
        for idx in 0..ir.arena.len() {
            let spanned = ir.arena.get(idx as NodeRef);
            let Node::String(s) = &spanned.node else {
                continue;
            };
            let section = spanned.path.split('/').next().unwrap_or("");
            // A string that is a `Ref` target (path ends in the Ref key, e.g. a
            // raw `{"Ref": "AWS::Region"}` map the parser could not
            // canonicalize) is already a reference - only plain string *data*
            // warrants the use-Ref-instead advice.
            let is_ref_target = spanned.path.rsplit('/').next() == Some(FN_REF);
            if (section == SECTION_MAPPINGS || section == SECTION_CONDITIONS)
                && !is_ref_target
                && PSEUDO_PARAMETERS.contains(&s.as_str())
            {
                diagnostics.push(crate::make_parse_defect(
                    "W1054",
                    format!(
                        "Found a string '{}' that appears to be a pseudo parameter reference; use 'Ref: {}' instead",
                        s, s
                    ),
                    spanned.span,
                ));
            }
        }

        // Unsubstituted `${Variable}` strings in the Outputs section. Like the
        // raw-pseudo-parameter case above, these are collected against the
        // `__output__` pseudo-resources that never reach the engines, so the
        // Sub-needed finding must be emitted here.
        {
            let mut output_unsubstituted: Vec<(String, String)> = Vec::new();
            for (key, entries) in &resolver.unsubstituted_variables {
                if key.starts_with(OUTPUT_PSEUDO_RESOURCE_PREFIX) || key == OUTPUTS_PSEUDO_RESOURCE {
                    for (path, variable) in entries {
                        output_unsubstituted.push((path.clone(), variable.clone()));
                    }
                }
            }
            output_unsubstituted.sort();
            for (path, variable) in output_unsubstituted {
                diagnostics.push(crate::make_parse_defect(
                    "E1029",
                    format!("Found an embedded parameter '{}' outside of an 'Fn::Sub' at {}", variable, path),
                    ir.span_index.get(&path).copied().unwrap_or(UNKNOWN_SPAN),
                ));
            }
        }

        diagnostics.extend(resolver.diagnostics);
        // SAM handling keys on the exact transform id, matching how the engines
        // detect the transform. A substring match would misclassify a non-SAM
        // transform whose name merely contains "Serverless" (e.g. a typo'd date
        // or a custom macro) as SAM, running the transform-error validators and
        // suppressing the correct "serverless type without transform" finding.
        let is_sam = ir.transforms.iter().any(|t| t == TRANSFORM_SERVERLESS);
        for d in graph.cycle_diagnostics(&ir.span_index) {
            if is_sam && sam::cycle_involves_sam_diagnostic(&d, &resources) {
                continue;
            }
            diagnostics.push(d);
        }
        for (cond_name, always_val) in conditions.tautological_equals() {
            let result_str = if always_val { "True" } else { "False" };
            diagnostics.push(crate::make_parse_defect_at(
                "W8003",
                format!("Fn::Equals in condition '{}' will always return {}", cond_name, result_str),
                ir.span_index.get(&format!("Conditions/{}", cond_name)).copied().unwrap_or(UNKNOWN_SPAN),
                &format!("Conditions/{}", cond_name),
            ));
        }
        // A `Condition:` key that names a condition absent from the Conditions
        // section is reported here - a distinct rule for the resource case and
        // the output case, since they are separate concerns. Emitting both
        // during model build anchors each at its own source location and keeps
        // the two engines identical. Names are sorted for deterministic
        // ordering.
        {
            let mut resource_ids_sorted: Vec<&String> = resources.keys().collect();
            resource_ids_sorted.sort();
            for rid in resource_ids_sorted {
                if let Some(cond) = &resources[rid].condition
                    && !conditions.conditions.contains_key(cond)
                {
                    diagnostics.push(crate::make_parse_defect_for_resource(
                        "E8002",
                        format!("Condition '{}' referenced by resource '{}' is not defined", cond, rid),
                        ir.span_index.get(&format!("Resources/{}", rid)).copied().unwrap_or(UNKNOWN_SPAN),
                        rid,
                    ));
                }
            }
            let mut output_names_sorted: Vec<&String> = outputs.keys().collect();
            output_names_sorted.sort();
            for oname in output_names_sorted {
                if let Some(cond) = &outputs[oname].condition
                    && !conditions.conditions.contains_key(cond)
                {
                    diagnostics.push(crate::make_parse_defect_for_resource(
                        "E6005",
                        format!("Condition '{}' referenced by output '{}' is not defined", cond, oname),
                        ir.span_index.get(&format!("Outputs/{}", oname)).copied().unwrap_or(UNKNOWN_SPAN),
                        oname,
                    ));
                }
            }
        }
        for (owner, undefined_ref) in conditions.undefined_condition_refs() {
            // Synthetic conditions (`__`-prefixed, inserted for inline Fn::If and
            // Rules-section assertions) are internal; never surface their names.
            if owner.starts_with("__") || undefined_ref.starts_with("__") {
                continue;
            }
            diagnostics.push(crate::make_parse_defect(
                "E8007",
                format!("Condition '{}' references undefined condition '{}'", owner, undefined_ref),
                ir.span_index.get(&format!("Conditions/{}", owner)).copied().unwrap_or(UNKNOWN_SPAN),
            ));
        }
        for cycle in conditions.detect_cycles() {
            let cycle_desc = cycle.join(" -> ");
            let first = &cycle[0];
            diagnostics.push(crate::make_parse_defect(
                "E9106",
                format!("Circular dependency in conditions: {}", cycle_desc),
                ir.span_index.get(&format!("Conditions/{}", first)).copied().unwrap_or(UNKNOWN_SPAN),
            ));
        }
        for (first, other) in conditions.detect_equivalent_conditions() {
            diagnostics.push(crate::make_parse_defect(
                "W9053",
                format!("Condition '{}' is equivalent to condition '{}' - consider consolidating", other, first),
                ir.span_index.get(&format!("Conditions/{}", other)).copied().unwrap_or(UNKNOWN_SPAN),
            ));
        }
        // The satisfiability-budget-exhaustion advisory is deliberately NOT
        // emitted here: almost every satisfiability query runs later, during
        // engine rule evaluation, so the budget-exhausted set is still empty at
        // model-build time. The validation engine emits it after rule
        // evaluation, once those queries have run.
        let model_build_ms = total_start.elapsed().as_secs_f64() * 1000.0;

        if !diagnostics.is_empty() {
            warn!("{} parse-time diagnostics", diagnostics.len());
        }
        let total_props: usize = resources.values().map(|r| r.properties.len()).sum();
        info!(
            "Semantic model: {} resources ({} types, {} total properties), {} outputs, {} edges, {} conditions, {} diagnostics",
            resources.len(),
            resources_by_type.len(),
            total_props,
            outputs.len(),
            graph.edges.len(),
            conditions.conditions.len(),
            diagnostics.len()
        );

        let template_metadata =
            if ir.template_metadata != NULL_REF { Some(node_to_json(&ir.arena, ir.template_metadata)) } else { None };
        let rules = if ir.rules != NULL_REF { Some(node_to_json(&ir.arena, ir.rules)) } else { None };
        let parsed_rules = parse_rules(&rules, &ir.arena, ir.rules);
        let rule_implications: Vec<(String, crate::ir::NodeRef, Vec<crate::ir::NodeRef>)> = parsed_rules
            .iter()
            .map(|r| {
                let assertion_nodes: Vec<crate::ir::NodeRef> = r.assertions.iter().map(|a| a.assert_node).collect();
                (r.name.clone(), r.condition_node, assertion_nodes)
            })
            .collect();
        if !rule_implications.is_empty() {
            conditions.register_rule_implications(&ir.arena, &rule_implications);
        }
        let rule_diagnostics = crate::rules::validate_rules(&rules, &ir.arena, ir.rules);
        diagnostics.extend(rule_diagnostics);
        let sam_globals = sam::extract_sam_globals(&ir.arena, ir.globals);
        if !sam_globals.is_empty() {
            sam::apply_sam_globals(&mut resources, &sam_globals, &mut ir.span_index);
        }
        let sam_implicit_resources =
            if is_sam { sam::collect_sam_implicit_resources(&resources) } else { HashSet::new() };
        let globals_param_refs =
            if is_sam { sam::collect_globals_param_refs(&ir.arena, ir.globals) } else { Vec::new() };
        if is_sam {
            let parameter_names: HashSet<String> = parameters.keys().cloned().collect();
            diagnostics.extend(sam::collect_transform_errors(
                &ir.arena,
                ir.resources,
                ir.globals,
                &resources,
                &parameter_names,
                &ir.span_index,
            ));
        }
        let is_cdk = resources_by_type.contains_key(CDK_METADATA_TYPE);

        if resolver_depth_exceeded {
            budget_tracker.record(BudgetKind::ResolverDepth);
        }
        if resolver_enum_expansion_exceeded {
            budget_tracker.record(BudgetKind::EnumExpansion);
        }
        // Invalid Ref targets in Outputs. The resolver records these under the
        // `__output__<Name>` pseudo-resource key, but the engines only see
        // top-level edges (which are not created for unknown Ref targets). Emit
        // them here as parse-time diagnostics so both engines surface them.
        // Skip when MODULE resources or unexpanded ForEach are present, since
        // both can synthesize resource names unknown at parse time.
        {
            let has_module_or_foreach = resources.values().any(|r| r.resource_type.ends_with("::MODULE"))
                || resources.keys().any(|k| k.contains("Fn::ForEach"));
            if !has_module_or_foreach {
                let mut output_invalid_refs: Vec<(String, String, String)> = Vec::new();
                for (key, entries) in &resolver.invalid_refs {
                    if let Some(output_name) = key.strip_prefix(OUTPUT_PSEUDO_RESOURCE_PREFIX) {
                        for (path, target) in entries {
                            if sam_implicit_resources.contains(target) {
                                continue;
                            }
                            output_invalid_refs.push((output_name.to_string(), path.clone(), target.clone()));
                        }
                    }
                }
                output_invalid_refs.sort();
                for (output_name, path, target) in &output_invalid_refs {
                    let mut defect =
                        ParseDefect::new(
                            "F6101",
                            format!(
                                "Ref '{}' does not reference a valid resource, parameter, or pseudo-parameter",
                                target,
                            ),
                        )
                        .location(ir.span_index.get(path).copied().unwrap_or(UNKNOWN_SPAN))
                        .phase(DefectPhase::Parse);
                    defect = defect.property_path(format!("Outputs.{}.Value.Ref", output_name));
                    diagnostics.push(defect);
                }
            }
        }

        Ok(ParseResult {
            model: SemanticModel {
                arena: ir.arena,
                root: ir.root,
                authored_template: OnceLock::new(),
                span_index: ir.span_index,
                format_version: ir.format_version,
                description: ir.description,
                transforms: ir.transforms,
                raw_top_level_keys: ir.raw_top_level_keys,
                template_metadata,
                rules,
                parsed_rules,
                parameters,
                mappings,
                conditions,
                resources,
                outputs,
                graph,
                resources_by_type,
                diagnostics,
                output_empty_joins,
                sam_globals,
                sam_implicit_resources,
                globals_param_refs,
                is_cdk,
                fn_if_conditions,
                find_in_map_names,
                params_referenced_in_definitions,
                has_dynamic_findinmap_name,
                resolution_sources,
                intrinsic_source_paths,
                value_nodes,
                lifecycle_attribute_nodes,
                lifecycle_attribute_status_cache: Mutex::new(HashMap::new()),
                invalid_resource_conditions,
                invalid_inline_conditions,
                resolve_memo: Mutex::new(HashMap::new()),
                raw_scenario_memo: Mutex::new(HashMap::new()),
                properties_scenario_cache: Mutex::new(HashMap::new()),
                scenario_memo: Mutex::new(HashMap::new()),
                lifecycle_policy_scenario_cache: Mutex::new(HashMap::new()),
                scenario_combinations_used: AtomicU64::new(0),
                budget_tracker,
                scenario_expansion_lock: Mutex::new(()),
                scenario_expansion_curtailed: AtomicBool::new(false),
            },
            model_build_ms,
        })
    }

    pub fn resource(&self, id: &str) -> Option<&ResolvedResource> {
        self.resources.get(id)
    }

    /// The template as the author wrote it, as CloudFormation JSON with every
    /// intrinsic function in long form. This is the view an external evaluator
    /// that understands CloudFormation syntax - rather than this crate's resolved
    /// model - operates on. Rendered once and cached for the model's lifetime.
    pub fn authored_template_json(&self) -> &serde_json::Value {
        self.authored_template.get_or_init(|| render_authored_json(&self.arena, self.root))
    }

    /// Reports whether a lifecycle attribute can legally survive condition
    /// evaluation, and whether any reachable authored value has a non-object
    /// shape. Only `UpdatePolicy` permits `Fn::If` to remove the whole attribute
    /// with `AWS::NoValue`; illegal values on the other attributes remain present
    /// for downstream diagnostics.
    #[must_use]
    pub fn lifecycle_attribute_status(&self, resource_id: &str, attribute: &str) -> LifecycleAttributeStatus {
        if !matches!(
            attribute,
            KEY_CREATION_POLICY | KEY_UPDATE_POLICY | KEY_DELETION_POLICY | KEY_UPDATE_REPLACE_POLICY
        ) {
            return LifecycleAttributeStatus::default();
        }
        let cache_key = (resource_id.to_string(), attribute.to_string());
        let mut cache = self.lifecycle_attribute_status_cache.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
        if let Some(status) = cache.get(&cache_key) {
            return status.clone();
        }

        let mut status = LifecycleAttributeStatus::default();
        if let Some(node) = self.lifecycle_attribute_nodes.get(&cache_key) {
            let mut assumptions = self
                .resources
                .get(resource_id)
                .and_then(|resource| resource.condition.as_ref())
                .map(|condition| vec![(condition.clone(), true)])
                .unwrap_or_default();
            collect_lifecycle_attribute_status(
                &self.arena,
                *node,
                &self.conditions,
                attribute == KEY_UPDATE_POLICY,
                &mut assumptions,
                &mut status,
            );
        }
        cache.insert(cache_key, status.clone());
        status
    }

    /// Expands a lifecycle policy into reachable values while preserving the
    /// assumptions for each branch. Whole dynamic leaves are deferred, while a
    /// list or object remains invalid regardless of dynamic values nested inside it.
    #[must_use]
    pub fn lifecycle_policy_scenarios(
        &self,
        resource_id: &str,
        attribute: &str,
    ) -> Vec<(serde_json::Value, HashMap<String, bool>)> {
        let cache_key = (resource_id.to_string(), attribute.to_string());
        let mut cache = self.lifecycle_policy_scenario_cache.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
        if let Some(scenarios) = cache.get(&cache_key) {
            return scenarios.clone();
        }

        let scenarios = if !self.resource_condition_is_valid(resource_id) {
            Vec::new()
        } else {
            let resolved = match attribute {
                KEY_DELETION_POLICY => self.resources.get(resource_id).and_then(|r| r.deletion_policy.as_ref()),
                KEY_UPDATE_REPLACE_POLICY => {
                    self.resources.get(resource_id).and_then(|r| r.update_replace_policy.as_ref())
                }
                _ => None,
            };
            match resolved {
                None => Vec::new(),
                Some(value) => {
                    let initial_assumptions: HashMap<String, bool> = self
                        .resources
                        .get(resource_id)
                        .and_then(|resource| resource.condition.as_ref())
                        .map(|condition| [(condition.clone(), true)].into_iter().collect())
                        .unwrap_or_default();
                    let assumptions: Vec<_> =
                        initial_assumptions.iter().map(|(name, value)| (name.clone(), *value)).collect();
                    if !assumptions.is_empty() && !self.conditions.is_satisfiable(&assumptions) {
                        Vec::new()
                    } else {
                        self.collect_scenarios_with_budget_from(
                            value,
                            &initial_assumptions,
                            MAX_SCENARIO_COMBINATIONS,
                            MAX_TOTAL_SCENARIO_COMBINATIONS,
                        )
                        .0
                        .into_iter()
                        .filter_map(|(value, conditions)| {
                            let assumptions: Vec<_> =
                                conditions.iter().map(|(name, value)| (name.clone(), *value)).collect();
                            if !assumptions.is_empty() && !self.conditions.is_satisfiable(&assumptions) {
                                return None;
                            }
                            let value = match value {
                                ResolvedValue::Reference { .. }
                                | ResolvedValue::Dynamic { .. }
                                | ResolvedValue::TypedDynamic { .. } => return None,
                                other => crate::serialization::resolved_value_to_json(&other),
                            };
                            Some((value, conditions))
                        })
                        .collect()
                    }
                }
            }
        };
        cache.insert(cache_key, scenarios.clone());
        scenarios
    }

    pub fn resources_of_type(&self, type_name: &str) -> &[String] {
        self.resources_by_type.get(type_name).map(|v| v.as_slice()).unwrap_or(&[])
    }

    #[must_use]
    pub fn resource_condition_is_valid(&self, resource_id: &str) -> bool {
        !self.invalid_resource_conditions.contains(resource_id)
    }

    /// Groups resources that can simultaneously resolve to the same primary-identifier tuple.
    /// Each displayed tuple is paired with the ordered set of resources participating in at
    /// least one satisfiable collision for the corresponding comparison identity.
    #[must_use]
    pub fn primary_identifier_conflicts(
        &self,
        resource_type: &str,
        identifier_properties: &[String],
    ) -> Vec<(Vec<String>, BTreeSet<String>)> {
        let mut per_resource = Vec::new();
        for resource_id in self.resources_of_type(resource_type) {
            let scenarios = self.primary_identifier_scenarios(resource_id, identifier_properties);
            if !scenarios.is_empty() {
                per_resource.push((resource_id, scenarios));
            }
        }

        // When every scenario has one comparison identity, grouping cannot skip
        // any work. Keep the original tight traversal for that dense case so the
        // optimization adds no cursor or heap overhead where it has nothing to
        // prune. The preliminary linear scan is negligible beside the pairwise
        // traversal and establishes that this is exactly one identity group.
        let first_identity = per_resource
            .first()
            .and_then(|(_, scenarios)| scenarios.first())
            .map(|scenario| scenario.identity_tuple.as_slice());
        let has_one_identity = first_identity.is_some_and(|identity| {
            per_resource
                .iter()
                .flat_map(|(_, scenarios)| scenarios)
                .all(|scenario| scenario.identity_tuple.as_slice() == identity)
        });
        if has_one_identity {
            let mut conflicts: BTreeMap<Vec<String>, (Vec<String>, BTreeSet<String>)> = BTreeMap::new();
            for left_index in 0..per_resource.len() {
                for right_index in (left_index + 1)..per_resource.len() {
                    let (left_resource, left_scenarios) = &per_resource[left_index];
                    let (right_resource, right_scenarios) = &per_resource[right_index];
                    for left in left_scenarios {
                        for right in right_scenarios {
                            let mut assumptions = left.assumptions.clone();
                            assumptions.extend(right.assumptions.iter().cloned());
                            if assumptions.is_empty() || self.conditions.is_satisfiable(&assumptions) {
                                let (_, resources) = conflicts
                                    .entry(left.identity_tuple.clone())
                                    .or_insert_with(|| (left.display_tuple.clone(), BTreeSet::new()));
                                resources.insert((*left_resource).clone());
                                resources.insert((*right_resource).clone());
                            }
                        }
                    }
                }
            }
            return conflicts.into_values().collect();
        }

        // Two resources can only collide when their identifier tuples are equal, so
        // group scenarios by comparison identity and confine every comparison to a
        // group. A resource with a unique tuple forms a singleton group and does no
        // cross-resource or satisfiability work - the common case the earlier
        // all-pairs traversal paid for on every template.
        let mut candidates_by_identity: HashMap<&[String], Vec<(usize, usize)>> = HashMap::new();
        for (resource_index, (_, scenarios)) in per_resource.iter().enumerate() {
            for (scenario_index, scenario) in scenarios.iter().enumerate() {
                candidates_by_identity
                    .entry(scenario.identity_tuple.as_slice())
                    .or_default()
                    .push((resource_index, scenario_index));
            }
        }
        let mut cursors: Vec<IdentityGroupPairCursor> = candidates_by_identity
            .into_values()
            .filter_map(|candidates| IdentityGroupPairCursor::new(&candidates))
            .collect();

        let mut conflicts: BTreeMap<Vec<String>, (Vec<String>, BTreeSet<String>)> = BTreeMap::new();
        {
            let mut record_conflict = |comparison: PrimaryIdentifierComparisonOrder| {
                let (left_resource_index, right_resource_index, left_scenario_index, right_scenario_index) = comparison;
                let (left_resource, left_scenarios) = &per_resource[left_resource_index];
                let (right_resource, right_scenarios) = &per_resource[right_resource_index];
                let left = &left_scenarios[left_scenario_index];
                let right = &right_scenarios[right_scenario_index];
                let mut assumptions = left.assumptions.clone();
                assumptions.extend(right.assumptions.iter().cloned());
                if assumptions.is_empty() || self.conditions.is_satisfiable(&assumptions) {
                    let (_, resources) = conflicts
                        .entry(left.identity_tuple.clone())
                        .or_insert_with(|| (left.display_tuple.clone(), BTreeSet::new()));
                    resources.insert((*left_resource).clone());
                    resources.insert((*right_resource).clone());
                }
            };

            // Visit the surviving comparisons in the exact order the all-pairs
            // traversal reached them by merging the groups on comparison order. Every
            // satisfiability query then runs in the identical sequence and count,
            // leaving the model's shared, cumulative budget drawn down exactly as
            // before. A single group is already ordered, so it needs no merge and
            // keeps the all-duplicate case as cheap as the traversal it replaces.
            if cursors.len() <= 1 {
                if let Some(cursor) = cursors.pop() {
                    for comparison in cursor {
                        record_conflict(comparison);
                    }
                }
            } else {
                let mut frontier = BinaryHeap::with_capacity(cursors.len());
                for (cursor_index, cursor) in cursors.iter_mut().enumerate() {
                    if let Some(comparison) = cursor.next() {
                        frontier.push(Reverse((comparison, cursor_index)));
                    }
                }
                while let Some(Reverse((comparison, cursor_index))) = frontier.pop() {
                    record_conflict(comparison);
                    if let Some(next_comparison) = cursors[cursor_index].next() {
                        frontier.push(Reverse((next_comparison, cursor_index)));
                    }
                }
            }
        }
        conflicts.into_values().collect()
    }

    fn primary_identifier_scenarios(
        &self,
        resource_id: &str,
        identifier_properties: &[String],
    ) -> Vec<PrimaryIdentifierScenario> {
        if !self.resource_condition_is_valid(resource_id) {
            return Vec::new();
        }
        let base_assumptions = self
            .resources
            .get(resource_id)
            .and_then(|resource| resource.condition.as_deref())
            .map(|condition| vec![(condition.to_string(), true)])
            .unwrap_or_default();
        let mut scenarios = vec![PrimaryIdentifierScenario {
            identity_tuple: Vec::with_capacity(identifier_properties.len()),
            display_tuple: Vec::with_capacity(identifier_properties.len()),
            assumptions: base_assumptions,
        }];

        for property in identifier_properties {
            let path = format!("Properties.{property}");
            let property_scenarios = self.resolve_scenarios_json(resource_id, &path);
            let expression_identity =
                self.value_identity(resource_id, &path).filter(|identity| identity.starts_with("expr:"));
            let effective_scenarios: Vec<(String, String, HashMap<String, bool>)> = if property_scenarios.is_empty()
                || (expression_identity.is_some()
                    && property_scenarios.iter().all(|(_, conditions)| conditions.is_empty()))
            {
                expression_identity
                    .map(|identity| {
                        let display = identity.strip_prefix("expr:").unwrap_or(&identity).to_string();
                        vec![(identity, display, HashMap::new())]
                    })
                    .unwrap_or_default()
            } else {
                property_scenarios
                    .into_iter()
                    .filter_map(|(value, conditions)| {
                        if value.is_null() {
                            return None;
                        }
                        let display = value.as_str().map(ToOwned::to_owned).unwrap_or_else(|| value.to_string());
                        let identity = format!("value:{}", crate::value_identity::concrete_value_fingerprint(&value));
                        Some((identity, display, conditions))
                    })
                    .collect()
            };
            let mut next = Vec::new();
            for existing in &scenarios {
                for (identity, display, conditions) in &effective_scenarios {
                    let mut assumptions = existing.assumptions.clone();
                    let mut consistent = true;
                    for (condition, truth) in conditions {
                        if let Some((_, prior)) = assumptions.iter().find(|(name, _)| name == condition) {
                            if prior != truth {
                                consistent = false;
                                break;
                            }
                        } else {
                            assumptions.push((condition.clone(), *truth));
                        }
                    }
                    if consistent {
                        let mut identity_tuple = existing.identity_tuple.clone();
                        identity_tuple.push(identity.clone());
                        let mut display_tuple = existing.display_tuple.clone();
                        display_tuple.push(display.clone());
                        next.push(PrimaryIdentifierScenario { identity_tuple, display_tuple, assumptions });
                    }
                }
            }
            scenarios = next;
            if scenarios.is_empty() {
                break;
            }
        }

        scenarios.retain(|scenario| {
            scenario.identity_tuple.len() == identifier_properties.len()
                && (scenario.assumptions.is_empty() || self.conditions.is_satisfiable(&scenario.assumptions))
        });
        scenarios
    }

    #[must_use]
    pub fn condition_is_valid_for_reachability(&self, condition: &str) -> bool {
        !self.invalid_inline_conditions.contains(condition)
    }

    #[must_use]
    pub fn resolve(&self, resource_id: &str, path: &str) -> Option<&ResolvedValue> {
        let resource = self.resources.get(resource_id)?;
        resource.properties.get(path.strip_prefix("Properties.").unwrap_or(path))
    }

    #[must_use]
    pub fn resolve_deep(&self, resource_id: &str, path: &str) -> Option<ResolvedValue> {
        let memo_key = (resource_id.to_string(), path.to_string());
        if let Some(memoized) = self.resolve_memo.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).get(&memo_key)
        {
            return memoized.clone();
        }
        let resource = self.resources.get(resource_id)?;
        let prop_path = path.strip_prefix("Properties.").unwrap_or(path);
        let mut segments = prop_path.splitn(2, '.');
        let top_key = segments.next()?;
        let resolved = resource.properties.get(top_key)?;
        let result = match segments.next() {
            Some(r) if !r.is_empty() => resolved_value_at_path(resolved, r),
            _ => Some(resolved.clone()),
        };
        self.resolve_memo.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).insert(memo_key, result.clone());
        result
    }

    #[must_use]
    pub fn is_from_parameter(&self, resource_id: &str, path: &str) -> bool {
        self.parameter_name_at(resource_id, path).is_some()
    }

    pub(crate) fn authored_sub_template_at(&self, resource_id: &str, path: &str) -> Option<&str> {
        let resource_id = resource_id.to_string();
        let mut current = path;
        loop {
            if let Some(node) = self.value_nodes.get(&(resource_id.clone(), current.to_string()))
                && let Node::Intrinsic(IntrinsicFn::Sub(template, _)) = self.arena.node(*node)
            {
                return Some(template.as_str());
            }
            let (parent, _) = current.rsplit_once('.')?;
            current = parent;
        }
    }

    /// The parameter whose declaration stood in for the value at `path`, or `None`
    /// when the value came from somewhere else. A value that is only known at
    /// deployment is not necessarily a parameter - a cross-stack import and a
    /// dynamic reference are equally unknown - so callers that describe a value to
    /// a reader must ask rather than assume.
    #[must_use]
    pub fn parameter_name_at(&self, resource_id: &str, path: &str) -> Option<&str> {
        let source = self.resolution_sources.get(&(resource_id.to_string(), path.to_string()))?;
        parameter_name_from_source(source)
    }

    /// A key that two values share only when they are provably the same value, or
    /// `None` when nothing about the value settles the question.
    ///
    /// A value that resolves before deployment is keyed by its contents, so the
    /// authored form does not matter. A value that stays opaque is keyed by the
    /// expression that produces it, because that is the only thing that can show
    /// two such values are one value. Callers that compare keys must treat `None`
    /// and two differing keys alike: neither proves the values differ, so neither
    /// permits a claim that they are the same.
    #[must_use]
    pub fn value_identity(&self, resource_id: &str, path: &str) -> Option<String> {
        let resolved = self.resolve_deep(resource_id, path).or_else(|| self.resolve(resource_id, path).cloned())?;
        self.resolved_value_identity(resource_id, path, &resolved)
    }

    /// Builds an identity for an already-resolved value at its authored path.
    /// A concrete result that still depends on a reference uses the complete
    /// expression, because a parameter default may be overridden at deployment.
    pub(crate) fn resolved_value_identity(
        &self,
        resource_id: &str,
        path: &str,
        resolved: &ResolvedValue,
    ) -> Option<String> {
        let reference_prefix = format!("{path}.");
        let depends_on_reference = self
            .graph
            .outgoing_edges(resource_id)
            .any(|edge| edge.source_path == path || edge.source_path.starts_with(&reference_prefix));
        let as_json = crate::serialization::resolved_value_to_json(resolved);
        if !depends_on_reference && !json_contains_markers(&as_json) {
            let fingerprint = crate::value_identity::concrete_value_fingerprint(&as_json);
            return Some(format!("value:{fingerprint}"));
        }
        let node = *self.value_nodes.get(&(resource_id.to_string(), path.to_string()))?;
        let (result, depth_exhausted) = crate::value_identity::expression_fingerprint_signaled(&self.arena, node);
        if depth_exhausted {
            self.budget_tracker.record(BudgetKind::ExpressionFingerprintDepth);
        }
        result.map(|fingerprint| format!("expr:{fingerprint}"))
    }

    /// True when the value at `path` (or any ancestor up to the resource root) was
    /// produced by an intrinsic function. Used by rules that skip hardcoded-literal
    /// checks when the property value comes from `Fn::GetAZs`, `Ref`, etc.
    #[must_use]
    pub fn is_from_intrinsic(&self, resource_id: &str, path: &str) -> bool {
        if self.path_from_intrinsic(resource_id, path) {
            return true;
        }
        // Properties wrapped in Fn::If store per-branch intrinsic sources
        // under branch-qualified paths. When a caller queries the bare
        // `Properties.<prop>` path, also consult the branch-qualified
        // variants so intrinsic-sourced values inside either branch are
        // still recognised.
        let properties_prefix = format!("{}.", KEY_PROPERTIES);
        if let Some(rest) = path.strip_prefix(&properties_prefix) {
            for branch in ["1", "2"] {
                let branch_path = format!("{}.{}.{}.{}", KEY_PROPERTIES, FN_IF, branch, rest);
                if self.path_from_intrinsic(resource_id, &branch_path) {
                    return true;
                }
            }
        }
        false
    }

    #[must_use]
    pub fn substituted_paths_under(&self, resource_id: &str, base_path: &str) -> HashSet<String> {
        let prefix = format!("{}.", base_path);
        let relative_path = |path: &str| {
            if path == base_path { Some(String::new()) } else { path.strip_prefix(&prefix).map(String::from) }
        };
        let mut paths: HashSet<String> =
            self.graph.outgoing_edges(resource_id).filter_map(|edge| relative_path(&edge.source_path)).collect();
        paths.extend(self.resolution_sources.iter().filter_map(|((source_resource, source_path), _)| {
            (source_resource == resource_id).then(|| relative_path(source_path)).flatten()
        }));
        paths
    }

    fn path_from_intrinsic(&self, resource_id: &str, path: &str) -> bool {
        let Some(intrinsic_paths) = self.intrinsic_source_paths.get(resource_id) else {
            return false;
        };
        // Walk the property path and each of its ancestors: an intrinsic value at
        // any level makes this path intrinsic-sourced. The index already holds
        // every such path (from an `Intrinsic/*` resolution source or a reference
        // edge), so ancestors are tested as borrowed slices with no per-level
        // key or tuple allocation and no edge scan.
        let mut ancestor = path;
        loop {
            if intrinsic_paths.contains(ancestor) {
                return true;
            }
            match ancestor.rfind('.') {
                Some(dot) => ancestor = &ancestor[..dot],
                None => return false,
            }
        }
    }

    /// Whether this model has spent its cumulative scenario-expansion budget.
    /// Mirrors `ConditionModel::satisfiability_budget_exhausted` for the
    /// scenario path: callers that drive many `resolve_scenarios` queries stop
    /// producing new scenarios once further expansion would only be truncated.
    #[must_use]
    pub fn scenario_budget_exhausted(&self) -> bool {
        self.scenario_combinations_used.load(Ordering::Relaxed) >= MAX_TOTAL_SCENARIO_COMBINATIONS
    }

    /// Record that a budget kind was exhausted. Delegates to the shared tracker.
    pub fn record_budget_exhaustion(&self, kind: BudgetKind) {
        self.budget_tracker.record(kind);
    }

    /// Returns the set of exhausted budget kinds in deterministic order.
    pub fn exhausted_budget_kinds(&self) -> BTreeSet<BudgetKind> {
        self.budget_tracker.exhausted_kinds()
    }

    /// Whether any exhausted budget makes the analysis incomplete.
    pub fn budget_analysis_incomplete(&self) -> bool {
        self.budget_tracker.analysis_incomplete()
    }

    /// Cumulative scenarios materialized by this model so far.
    #[must_use]
    pub fn scenario_combinations_used(&self) -> u64 {
        self.scenario_combinations_used.load(Ordering::Relaxed)
    }

    /// Whether any scenario expansion for this model omitted possible results
    /// because a per-value or model-wide analysis limit was reached. The flag is
    /// monotonic so callers can distinguish complete expansion from conservative
    /// fallback behavior.
    #[must_use]
    pub fn scenario_expansion_curtailed(&self) -> bool {
        self.scenario_expansion_curtailed.load(Ordering::Relaxed)
    }

    fn collect_scenarios_with_budget_status(
        &self,
        value: &ResolvedValue,
        per_value_limit: usize,
        total_limit: u64,
    ) -> (Vec<(ResolvedValue, HashMap<String, bool>)>, bool) {
        self.collect_scenarios_with_budget_from(value, &HashMap::new(), per_value_limit, total_limit)
    }

    fn collect_scenarios_with_budget_from(
        &self,
        value: &ResolvedValue,
        assumptions: &HashMap<String, bool>,
        per_value_limit: usize,
        total_limit: u64,
    ) -> (Vec<(ResolvedValue, HashMap<String, bool>)>, bool) {
        let _expansion_guard = self.scenario_expansion_lock.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
        let used = self.scenario_combinations_used.load(Ordering::Relaxed);
        if used >= total_limit {
            self.scenario_expansion_curtailed.store(true, Ordering::Relaxed);
            if total_limit == MAX_TOTAL_SCENARIO_COMBINATIONS {
                self.budget_tracker.record(BudgetKind::ScenarioCombinationsTotal);
            }
            return (Vec::new(), true);
        }

        let remaining = total_limit - used;
        let remaining_limit = usize::try_from(remaining).unwrap_or(usize::MAX);
        let effective_limit = per_value_limit.min(remaining_limit);
        let mut scenarios = Vec::new();
        let was_curtailed = collect_scenarios(value, assumptions, effective_limit, &mut scenarios);
        if was_curtailed {
            self.scenario_expansion_curtailed.store(true, Ordering::Relaxed);
            if per_value_limit == MAX_SCENARIO_COMBINATIONS && per_value_limit <= remaining_limit {
                self.budget_tracker.record(BudgetKind::ScenarioCombinationsPerValue);
            }
            if total_limit == MAX_TOTAL_SCENARIO_COMBINATIONS && remaining_limit <= per_value_limit {
                self.budget_tracker.record(BudgetKind::ScenarioCombinationsTotal);
            }
        }
        self.scenario_combinations_used.store(used + scenarios.len() as u64, Ordering::Relaxed);
        (scenarios, was_curtailed)
    }

    fn collect_scenarios_with_budget(
        &self,
        value: &ResolvedValue,
        per_value_limit: usize,
        total_limit: u64,
    ) -> Vec<(ResolvedValue, HashMap<String, bool>)> {
        self.collect_scenarios_with_budget_status(value, per_value_limit, total_limit).0
    }

    /// Test-only: advance the cumulative scenario counter directly, so the
    /// budget threshold and short-circuit behavior can be exercised without
    /// materializing `MAX_TOTAL_SCENARIO_COMBINATIONS` real scenarios.
    #[cfg(test)]
    pub(crate) fn add_scenario_combinations_for_test(&self, count: u64) {
        let _expansion_guard = self.scenario_expansion_lock.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
        self.scenario_combinations_used.fetch_add(count, Ordering::Relaxed);
    }

    /// Test-only: set the curtailment flag directly without needing to
    /// materialize a pathological number of real scenarios.
    #[cfg(test)]
    fn set_scenario_expansion_curtailed_for_test(&self) {
        self.scenario_expansion_curtailed.store(true, Ordering::Relaxed);
    }

    fn resolved_properties_value(&self, resource_id: &str) -> Option<ResolvedValue> {
        let resource = self.resources.get(resource_id)?;
        if resource.properties_dynamic {
            return None;
        }
        if resource.properties.len() == 1
            && let Some(conditional) = resource.properties.get(FN_IF)
        {
            return Some(conditional.clone());
        }
        let mut entries: Vec<MapEntry> = resource
            .properties
            .iter()
            .map(|(key, value)| MapEntry { key: key.clone(), value: value.clone() })
            .collect();
        entries.sort_by(|left, right| left.key.cmp(&right.key));
        Some(ResolvedValue::Map { entries })
    }

    /// Returns one immutable whole-properties scenario allocation shared across
    /// read-only callers, materializing and caching it on first access. The lock
    /// is held across expansion so a resource's scenarios are computed once and
    /// its budget charged once.
    pub fn resolve_properties_scenarios_shared(
        &self,
        resource_id: &str,
    ) -> Arc<Vec<(ResolvedValue, HashMap<String, bool>)>> {
        let mut cache = self.properties_scenario_cache.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
        if let Some(scenarios) = cache.get(resource_id) {
            return Arc::clone(scenarios);
        }
        let scenarios = match self.resolved_properties_value(resource_id) {
            Some(properties) => self.collect_scenarios_with_budget(
                &properties,
                MAX_SCENARIO_COMBINATIONS,
                MAX_TOTAL_SCENARIO_COMBINATIONS,
            ),
            None => Vec::new(),
        };
        let shared = Arc::new(scenarios);
        cache.insert(resource_id.to_string(), Arc::clone(&shared));
        shared
    }

    pub fn resolve_properties_scenarios(&self, resource_id: &str) -> Vec<(ResolvedValue, HashMap<String, bool>)> {
        self.resolve_properties_scenarios_shared(resource_id).as_ref().clone()
    }

    /// Returns the authored, branch-qualified source path for an effective path in
    /// one resolved scenario. The returned path uses the same dotted form as
    /// resolver source paths and can be passed to [`Self::resource_span`].
    pub fn scenario_source_path(
        &self,
        resource_id: &str,
        effective_path: &str,
        conditions: &HashMap<String, bool>,
    ) -> Option<String> {
        let properties = self.resolved_properties_value(resource_id)?;
        let relative_path = effective_path
            .strip_prefix("Properties.")
            .or_else(|| (effective_path == KEY_PROPERTIES).then_some(""))
            .unwrap_or(effective_path);
        scenario_source_path_at(&properties, relative_path, conditions, KEY_PROPERTIES)
    }

    pub fn resolve_scenarios(&self, resource_id: &str, path: &str) -> Vec<(ResolvedValue, HashMap<String, bool>)> {
        let key = (resource_id.to_string(), path.to_string());
        let mut memo = self.raw_scenario_memo.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
        if let Some(scenarios) = memo.get(&key) {
            return scenarios.clone();
        }
        let scenarios = self.resolve_scenarios_with_limit(resource_id, path, MAX_SCENARIO_COMBINATIONS).0;
        memo.insert(key, scenarios.clone());
        scenarios
    }

    pub fn resolve_scenarios_with_limit(
        &self,
        resource_id: &str,
        path: &str,
        per_value_limit: usize,
    ) -> (Vec<(ResolvedValue, HashMap<String, bool>)>, bool) {
        let value = match self.resolve_deep(resource_id, path) {
            Some(value) => value,
            None => match self.resolve(resource_id, path) {
                Some(value) => value.clone(),
                None => match self.resolve_via_properties_if(resource_id, path) {
                    Some(value) => value,
                    None => return (Vec::new(), false),
                },
            },
        };
        self.collect_scenarios_with_budget_status(&value, per_value_limit, MAX_TOTAL_SCENARIO_COMBINATIONS)
    }

    /// Fallback lookup when `Properties` is wrapped in an `Fn::If`: walks
    /// the caller's path inside the synthetic `Fn::If` branch so scenario
    /// resolution still reaches properties that only exist conditionally.
    fn resolve_via_properties_if(&self, resource_id: &str, path: &str) -> Option<ResolvedValue> {
        let resource = self.resources.get(resource_id)?;
        let conditional = resource.properties.get(FN_IF)?;
        let properties_prefix = format!("{}.", KEY_PROPERTIES);
        let prop_path = path.strip_prefix(&properties_prefix).unwrap_or(path);
        if prop_path.is_empty() {
            return Some(conditional.clone());
        }
        resolved_value_at_path(conditional, prop_path)
    }

    fn resolve_scenarios_json_uncached(
        &self,
        resource_id: &str,
        path: &str,
    ) -> Vec<(serde_json::Value, HashMap<String, bool>)> {
        self.resolve_scenarios(resource_id, path)
            .into_iter()
            .filter_map(|(val, conds)| {
                if contains_dynamic_resolved(&val) {
                    return None;
                }
                if !conds.is_empty() {
                    let assumptions: Vec<(String, bool)> = conds.iter().map(|(k, v)| (k.clone(), *v)).collect();
                    if !self.conditions.is_satisfiable(&assumptions) {
                        return None;
                    }
                }
                let json = crate::serialization::resolved_value_to_json_clean(&val)?;
                if json_contains_markers(&json) {
                    return None;
                }
                Some((json, conds))
            })
            .collect()
    }

    fn cache_json_scenarios(
        &self,
        memo_key: (String, String),
        scenarios: Vec<(serde_json::Value, HashMap<String, bool>)>,
    ) -> Arc<Vec<(serde_json::Value, HashMap<String, bool>)>> {
        let mut memo = self.scenario_memo.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
        Arc::clone(memo.entry(memo_key).or_insert_with(|| Arc::new(scenarios)))
    }

    /// Returns one immutable scenario allocation shared across read-only callers.
    pub fn resolve_scenarios_json_shared(
        &self,
        resource_id: &str,
        path: &str,
    ) -> Arc<Vec<(serde_json::Value, HashMap<String, bool>)>> {
        let memo_key = (resource_id.to_string(), path.to_string());
        {
            let memo = self.scenario_memo.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
            if let Some(memoized) = memo.get(&memo_key) {
                return Arc::clone(memoized);
            }
        }
        let scenarios = self.resolve_scenarios_json_uncached(resource_id, path);
        self.cache_json_scenarios(memo_key, scenarios)
    }

    pub fn resolve_scenarios_json(
        &self,
        resource_id: &str,
        path: &str,
    ) -> Vec<(serde_json::Value, HashMap<String, bool>)> {
        let memo_key = (resource_id.to_string(), path.to_string());
        {
            let memo = self.scenario_memo.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
            if let Some(memoized) = memo.get(&memo_key) {
                return memoized.as_ref().clone();
            }
        }
        let scenarios = self.resolve_scenarios_json_uncached(resource_id, path);
        self.cache_json_scenarios(memo_key, scenarios).as_ref().clone()
    }

    pub fn follow_ref(&self, resource_id: &str, path: &str) -> Option<&str> {
        if let Some(ResolvedValue::Reference { target, kind: _ }) = self.resolve(resource_id, path) {
            return Some(target.as_str());
        }
        if let Some(ResolvedValue::Reference { target, kind: _ }) = self.resolve_deep(resource_id, path).as_ref() {
            for edge in self.graph.outgoing_edges(resource_id) {
                if edge.target == *target {
                    return Some(&edge.target);
                }
            }
        }
        None
    }

    pub fn source_location(&self, path: &str) -> Option<&SourceSpan> {
        self.span_index.get(path)
    }

    /// Returns the source span for a resource property path, falling back to
    /// the resource-level span if the specific path is not found.
    ///
    /// The span index is keyed with slash-separated paths, so a dotted,
    /// resource-relative path (`Properties.BucketName`) is normalized to slash
    /// form before lookup - the same normalization [`Self::diagnostic_span`]
    /// applies. Callers pass paths in either form, so accepting only slash form
    /// here would silently mislocate every dotted-path diagnostic onto the
    /// resource declaration line.
    pub fn resource_span(&self, resource_id: &str, prop_path: &str) -> SourceSpan {
        // An empty resource id means the path is already a section-absolute span-index
        // key (e.g. an output's `Outputs/X/Value.Fn::Join`); prefixing it with
        // `Resources/` would mislocate the finding onto the Resources block. Resolve it
        // as-is (no dot-to-slash conversion, since dots in segment names like `Fn::Join`
        // are literal, not path separators). Returns UNKNOWN when nothing resolves so
        // callers fall back to section-level or backfill-based location.
        if resource_id.is_empty() {
            return self.walk_up_span(prop_path).unwrap_or(UNKNOWN_SPAN);
        }
        // Resolver paths preserve literal dots and slashes inside map keys, so converting
        // them into the slash-keyed index can be ambiguous. A terminal intrinsic can be
        // resolved through its exact authored parent path without lossy conversion.
        if let Some((authored_path, function_name)) = prop_path.rsplit_once('.')
            && let Some(node_ref) = self.value_nodes.get(&(resource_id.to_string(), authored_path.to_string()))
            && let Node::Intrinsic(intrinsic) = self.arena.node(*node_ref)
            && cfn_function_name(intrinsic) == function_name
        {
            let intrinsic_path = format!("{}/{}", self.arena.get(*node_ref).path, function_name);
            if let Some(span) = self.walk_up_span(&intrinsic_path) {
                return span;
            }
        }
        let specific = if prop_path.is_empty() {
            format!("Resources/{}", resource_id)
        } else {
            format!("Resources/{}/{}", resource_id, prop_path.replace('.', "/"))
        };
        // Walk up from the exact path to the nearest indexed ancestor, so a leaf that
        // carries no span of its own - a synthetic intrinsic key (`…/Topic/Fn::Sub`),
        // an `Fn::If` branch index - anchors at its closest real parent rather than
        // collapsing straight to the resource declaration. The resource path itself is
        // the final ancestor, preserving the previous resource-level fallback.
        self.walk_up_span(&specific).unwrap_or(UNKNOWN_SPAN)
    }

    /// Walks up `key` (a `/`-separated span-index path), trimming one trailing
    /// segment at a time, and returns the first ancestor with a known span. This
    /// anchors a diagnostic as close to the offending node as the index allows -
    /// an unindexed leaf (e.g. an `Fn::If` branch index) falls back to its parent
    /// property, then the resource, then the section.
    fn walk_up_span(&self, key: &str) -> Option<SourceSpan> {
        let mut current = key;
        loop {
            // A key can be present in the index but mapped to UNKNOWN_SPAN (an
            // interior node whose byte span was never assigned). Treat that as
            // "not found" and keep walking up to the nearest ancestor that does
            // have a real span, rather than returning the unusable UNKNOWN.
            match self.span_index.get(current) {
                Some(&span) if span != UNKNOWN_SPAN => return Some(span),
                _ => match current.rfind('/') {
                    Some(cut) => current = &current[..cut],
                    None => return None,
                },
            }
        }
    }

    /// Best-effort span for a diagnostic identified by its optional resource and
    /// property path, walking up to the nearest indexed ancestor.
    ///
    /// The path form disambiguates how to root it, which matters because a segment
    /// like `Metadata` names both a top-level section and a resource property:
    /// * A **slash** form (`Outputs/X/Value`, `Conditions/C/Fn::And`) is already an
    ///   absolute, section-rooted span-index key and is resolved as written.
    /// * A **bare path with no resource** (`BogusSection`) is a top-level key and is
    ///   also resolved directly.
    /// * A **dotted** or bare form with a resource (`Properties.Foo`, `Metadata`) is
    ///   relative to that resource, so it is rooted at `Resources/<rid>` before
    ///   lookup - never matched against a same-named top-level section.
    ///
    /// Returns `None` when nothing along the chosen candidate is indexed, so callers
    /// can fall back to a section span.
    pub fn diagnostic_span(&self, resource_id: Option<&str>, property_path: &str) -> Option<SourceSpan> {
        let rid = resource_id.filter(|r| !r.is_empty());

        if property_path.contains('/') || (rid.is_none() && !property_path.is_empty()) {
            // Absolute, section-rooted path: resolve directly.
            if let Some(span) = self.walk_up_span(property_path) {
                return Some(span);
            }
        } else if let Some(rid) = rid {
            // Resource-relative path (dotted or bare): root at the resource so a
            // property named after a top-level section cannot mislocate onto it.
            let key = if property_path.is_empty() {
                format!("Resources/{}", rid)
            } else {
                format!("Resources/{}/{}", rid, property_path.replace('.', "/"))
            };
            if let Some(span) = self.walk_up_span(&key) {
                return Some(span);
            }
        }

        // Last resort: the bare resource span, when a resource id is known.
        rid.and_then(|rid| self.span_index.get(&format!("Resources/{}", rid)))
            .filter(|span| **span != UNKNOWN_SPAN)
            .copied()
    }

    /// Bounds on the length of a string value the template does not state
    /// literally - one built by an intrinsic, or chosen from a parameter's
    /// AllowedValues. `None` when the length cannot be pinned for every
    /// possibility, and also when the template does state the value literally,
    /// because schema validation checks a literal against the constraint directly.
    ///
    /// Both engines decide what to report from this one answer, so neither can
    /// reach a different conclusion about the same property.
    pub fn estimated_string_length_bounds(&self, resource_id: &str, path: &str) -> Option<(usize, usize)> {
        let val = self.resolve_deep(resource_id, path).or_else(|| self.resolve(resource_id, path).cloned())?;
        if matches!(&val, ResolvedValue::Concrete { value } if value.is_string()) {
            return None;
        }
        estimate_resolved_string_length_bounds(&val)
    }
}

impl SpanProvider for SemanticModel {
    fn source_location(&self, path: &str) -> Option<SourceSpan> {
        self.span_index.get(path).copied()
    }
}

fn parse_rules(rules_json: &Option<serde_json::Value>, arena: &Arena, rules_node: NodeRef) -> Vec<TemplateRule> {
    let Some(rules) = rules_json else {
        return Vec::new();
    };
    let Some(obj) = rules.as_object() else {
        return Vec::new();
    };

    // Build a lookup from rule name → NodeRef for the rule's IR subtree
    let rule_nodes: HashMap<&str, NodeRef> =
        arena.as_map(rules_node).unwrap_or(&[]).iter().map(|(k, v)| (k.as_str(), *v)).collect();

    obj.iter()
        .filter_map(|(name, rule)| {
            let rule_obj = rule.as_object()?;
            let condition = rule_obj.get(KEY_RULE_CONDITION).cloned();

            // Look up the IR node for this rule to find condition/assertion NodeRefs
            let rule_ir = rule_nodes.get(name.as_str()).copied().unwrap_or(NULL_REF);
            let condition_node = arena.map_get(rule_ir, KEY_RULE_CONDITION).unwrap_or(NULL_REF);

            let assertions_node = arena.map_get(rule_ir, KEY_ASSERTIONS).unwrap_or(NULL_REF);
            let assertion_items = arena.as_list(assertions_node).unwrap_or(&[]);

            let assertions = rule_obj
                .get(KEY_ASSERTIONS)
                .and_then(|a| a.as_array())
                .map(|arr| {
                    arr.iter()
                        .enumerate()
                        .filter_map(|(idx, a)| {
                            let a_obj = a.as_object()?;
                            let assert_node = assertion_items
                                .get(idx)
                                .and_then(|item_ref| arena.map_get(*item_ref, KEY_ASSERT))
                                .unwrap_or(NULL_REF);
                            Some(RuleAssertion {
                                assert: a_obj.get(KEY_ASSERT).cloned().unwrap_or(serde_json::Value::Null),
                                assert_node,
                                description: a_obj
                                    .get(KEY_ASSERT_DESCRIPTION)
                                    .and_then(|d| d.as_str())
                                    .map(String::from),
                            })
                        })
                        .collect()
                })
                .unwrap_or_default();
            Some(TemplateRule { name: name.clone(), condition, condition_node, assertions })
        })
        .collect()
}

/// Collect parameter names that are referenced (via `Ref`/`Fn::Sub`) from within
/// another parameter's definition. These references still count as usage for the
/// unused-parameter check even though they originate in the Parameters section.
fn collect_parameter_definition_refs(ir: &TemplateIR, parameters: &HashMap<String, ParameterInfo>) -> HashSet<String> {
    let mut referenced = HashSet::new();
    if ir.parameters == NULL_REF {
        return referenced;
    }
    let Some(param_entries) = ir.arena.as_map(ir.parameters) else {
        return referenced;
    };
    for (_, param_ref) in param_entries {
        collect_refs_in_subtree(&ir.arena, *param_ref, parameters, &mut referenced);
    }
    referenced
}

fn collect_refs_in_subtree(
    arena: &Arena,
    node_ref: NodeRef,
    parameters: &HashMap<String, ParameterInfo>,
    referenced: &mut HashSet<String>,
) {
    match arena.node(node_ref) {
        Node::Intrinsic(IntrinsicFn::Ref(target)) => {
            if parameters.contains_key(target) {
                referenced.insert(target.clone());
            }
        }
        Node::Intrinsic(IntrinsicFn::Sub(_, Some(bindings))) => {
            for (_, v) in bindings {
                collect_refs_in_subtree(arena, *v, parameters, referenced);
            }
        }
        Node::List(items) => {
            for item in items {
                collect_refs_in_subtree(arena, *item, parameters, referenced);
            }
        }
        Node::Map(entries) => {
            for (_, v) in entries {
                collect_refs_in_subtree(arena, *v, parameters, referenced);
            }
        }
        _ => {}
    }
}

fn parameter_name_from_source(source: &str) -> Option<&str> {
    let rest = source.strip_prefix(SECTION_PARAMETERS)?.strip_prefix('/')?;
    let name = rest.split('/').next()?;
    if name.is_empty() { None } else { Some(name) }
}

/// Resolution-source marker for a value produced by an intrinsic function.
const INTRINSIC_SOURCE_PREFIX: &str = "Intrinsic/";

/// Builds the per-resource intrinsic-source path index consulted by
/// `is_from_intrinsic`. A path counts as intrinsic-sourced when its resolution
/// source is an `Intrinsic/*` entry or when it anchors a reference edge (Ref,
/// GetAtt, Sub) - the two conditions the ancestor walk previously re-derived by
/// probing the resolution sources and rescanning the outgoing edges on every
/// query. Materializing them once trades a small, bounded amount of memory for
/// allocation-free borrowed lookups on the hot path.
fn build_intrinsic_source_paths(
    resolution_sources: &HashMap<(String, String), String>,
    graph: &ReferenceGraph,
) -> HashMap<String, HashSet<String>> {
    let mut paths_by_resource: HashMap<String, HashSet<String>> = HashMap::new();
    for ((resource_id, path), source) in resolution_sources {
        if source.starts_with(INTRINSIC_SOURCE_PREFIX) {
            paths_by_resource.entry(resource_id.clone()).or_default().insert(path.clone());
        }
    }
    for edge in &graph.edges {
        paths_by_resource.entry(edge.source_resource.clone()).or_default().insert(edge.source_path.clone());
    }
    paths_by_resource
}

/// Some intrinsic nodes stand in for a whole object - most notably
/// `Properties: {Fn::If: [...]}` which the parser folds into an
/// `IntrinsicFn::If` node. Return the CloudFormation function-name key
/// (`Fn::If`, `Fn::ForEach::*`, etc.) when the node is one of these
/// object-wrapping intrinsics, so downstream resolution can address the
/// conditional by a synthetic path.
fn intrinsic_synthetic_key(arena: &Arena, node_ref: NodeRef) -> Option<String> {
    let Node::Intrinsic(func) = arena.node(node_ref) else {
        return None;
    };
    match func {
        IntrinsicFn::If(_, _, _) | IntrinsicFn::IfExpr(_, _, _) => Some(FN_IF.to_string()),
        IntrinsicFn::ForEach(uid, _, _, _) => Some(format!("{}::{}", FN_FOR_EACH, uid)),
        _ => None,
    }
}

/// Valid resource-level attributes per the CloudFormation template anatomy.
/// These are the keys CloudFormation accepts directly under a resource's logical
/// ID in the `Resources` section.
const VALID_RESOURCE_ATTRIBUTES: &[&str] = &[
    KEY_TYPE,
    KEY_PROPERTIES,
    KEY_DEPENDS_ON,
    KEY_CONDITION,
    SECTION_METADATA,
    KEY_DELETION_POLICY,
    KEY_UPDATE_REPLACE_POLICY,
    KEY_UPDATE_POLICY,
    KEY_CREATION_POLICY,
    FN_TRANSFORM,
    "Version",
];

/// Additional resource-level attributes valid only when the SAM transform is
/// declared. These are SAM-specific extensions that the Serverless transform
/// processes before CloudFormation sees the resource.
const SAM_RESOURCE_ATTRIBUTES: &[&str] = &["Connectors", "IgnoreGlobals"];

fn invalid_resource_condition_ref(arena: &Arena, node_ref: NodeRef) -> Option<NodeRef> {
    let entries = arena.as_map(node_ref)?;
    let condition_ref = entries.iter().find(|(key, _)| key == KEY_CONDITION).map(|(_, value)| *value)?;
    (!matches!(arena.node(condition_ref), Node::String(_))).then_some(condition_ref)
}

/// Validates the structural shape of a resource body, producing diagnostics for
/// bodies that CloudFormation would reject: a non-object resource, a missing
/// `Type`, or unknown resource-level attribute keys.
fn validate_resource_shape(
    arena: &Arena,
    name: &str,
    node_ref: NodeRef,
    is_sam: bool,
    span_index: &SourceSpanIndex,
) -> Vec<ParseDefect> {
    let mut out = Vec::new();
    let resource_span = span_index.get(&format!("Resources/{}", name)).copied().unwrap_or(UNKNOWN_SPAN);

    // The resource body must be an object.
    let entries = match arena.as_map(node_ref) {
        Some(entries) => entries,
        None => {
            let shape = match arena.node(node_ref) {
                Node::Null => "null",
                Node::Bool(_) => "a boolean",
                Node::Int(_) | Node::Float(_) => "a number",
                Node::String(_) => "a string",
                Node::List(_) => "a list",
                Node::Intrinsic(_) => "an intrinsic function",
                Node::Map(_) => return out,
            };
            out.push(crate::make_parse_defect_for_resource(
                "E3001",
                format!("Resource '{}' body must be an object, got {}", name, shape),
                resource_span,
                name,
            ));
            return out;
        }
    };

    // `Type` is required and must be a string.
    match entries.iter().find(|(k, _)| k == KEY_TYPE) {
        None => {
            out.push(crate::make_parse_defect_for_resource(
                "E3001",
                format!("Resource '{}' is missing required property 'Type'", name),
                resource_span,
                name,
            ));
        }
        Some((_, type_ref)) if !matches!(arena.node(*type_ref), Node::String(_)) => {
            let type_span = span_index.get(&format!("Resources/{}/Type", name)).copied().unwrap_or(resource_span);
            out.push(crate::make_parse_defect_for_resource(
                "E3001",
                format!("Resource '{}' property 'Type' must be a string", name),
                type_span,
                name,
            ));
        }
        _ => {}
    }

    // `Condition` must be a string when present.
    if invalid_resource_condition_ref(arena, node_ref).is_some() {
        let cond_span = span_index.get(&format!("Resources/{}/Condition", name)).copied().unwrap_or(resource_span);
        out.push(crate::make_parse_defect_for_resource(
            "E3001",
            format!("Resource '{}' property 'Condition' must be a string", name),
            cond_span,
            name,
        ));
    }

    // `DependsOn` must be a string or a list of strings when present.
    if let Some((_, dep_ref)) = entries.iter().find(|(k, _)| k == KEY_DEPENDS_ON) {
        match arena.node(*dep_ref) {
            Node::String(_) => {}
            Node::List(items) => {
                for item_ref in items {
                    if !matches!(arena.node(*item_ref), Node::String(_)) {
                        let dep_span =
                            span_index.get(&format!("Resources/{}/DependsOn", name)).copied().unwrap_or(resource_span);
                        out.push(crate::make_parse_defect_for_resource(
                            "E3001",
                            format!("Resource '{}' property 'DependsOn' list elements must be strings", name),
                            dep_span,
                            name,
                        ));
                        break;
                    }
                }
            }
            _ => {
                let dep_span =
                    span_index.get(&format!("Resources/{}/DependsOn", name)).copied().unwrap_or(resource_span);
                out.push(crate::make_parse_defect_for_resource(
                    "E3001",
                    format!("Resource '{}' property 'DependsOn' must be a string or list of strings", name),
                    dep_span,
                    name,
                ));
            }
        }
    }

    let resource_type = entries.iter().find(|(key, _)| key == KEY_TYPE).and_then(|(_, value)| arena.as_str(*value));
    if let Some(resource_type) = resource_type {
        let is_custom_resource = is_custom_resource_type(resource_type);
        if let Some((_, version_ref)) = entries.iter().find(|(key, _)| key == "Version") {
            let version_span = span_index.get(&format!("Resources/{}/Version", name)).copied().unwrap_or(resource_span);
            if !is_custom_resource {
                out.push(crate::make_parse_defect_for_resource(
                    "E3001",
                    format!("Resource '{}' property 'Version' is only valid for custom resources", name),
                    version_span,
                    name,
                ));
            } else if !matches!(arena.node(*version_ref), Node::String(_) | Node::Int(_)) {
                out.push(crate::make_parse_defect_for_resource(
                    "E3001",
                    format!("Resource '{}' property 'Version' must be a string or integer", name),
                    version_span,
                    name,
                ));
            }
        }

        for policy_name in [KEY_CREATION_POLICY, KEY_UPDATE_POLICY] {
            let Some((_, policy_ref)) = entries.iter().find(|(key, _)| key == policy_name) else {
                continue;
            };
            let policy_span =
                span_index.get(&format!("Resources/{}/{}", name, policy_name)).copied().unwrap_or(resource_span);
            if is_custom_resource {
                out.push(crate::make_parse_defect_for_resource(
                    "E3001",
                    format!("Resource '{}' property '{}' is not valid for custom resources", name, policy_name),
                    policy_span,
                    name,
                ));
            } else if !matches!(arena.node(*policy_ref), Node::Map(_) | Node::Intrinsic(_)) {
                out.push(crate::make_parse_defect_for_resource(
                    "E3001",
                    format!("Resource '{}' property '{}' must be an object", name, policy_name),
                    policy_span,
                    name,
                ));
            }
        }
    }

    for (key, _) in entries {
        if VALID_RESOURCE_ATTRIBUTES.contains(&key.as_str()) {
            continue;
        }
        if is_sam && SAM_RESOURCE_ATTRIBUTES.contains(&key.as_str()) {
            continue;
        }
        let key_span = span_index.get(&format!("Resources/{}/{}", name, key)).copied().unwrap_or(resource_span);
        out.push(crate::make_parse_defect_for_resource(
            "E3001",
            format!(
                "Resource '{}' has invalid property '{}'. Valid resource attributes: {}",
                name,
                key,
                valid_attributes_display(is_sam),
            ),
            key_span,
            name,
        ));
    }

    out
}

/// Builds the human-readable list of valid resource attributes for error messages.
fn valid_attributes_display(is_sam: bool) -> String {
    let mut attrs: Vec<&str> = VALID_RESOURCE_ATTRIBUTES.to_vec();
    if is_sam {
        attrs.extend_from_slice(SAM_RESOURCE_ATTRIBUTES);
    }
    attrs.join(", ")
}

fn collect_lifecycle_attribute_status(
    arena: &Arena,
    node: NodeRef,
    conditions: &ConditionModel,
    allows_no_value_omission: bool,
    assumptions: &mut Vec<(String, bool)>,
    status: &mut LifecycleAttributeStatus,
) {
    if matches!(conditions.satisfiability(assumptions), Satisfiability::Unsatisfiable) {
        return;
    }

    if !allows_no_value_omission {
        status.may_be_present = true;
        if matches!(
            arena.node(node),
            Node::Null | Node::Bool(_) | Node::Int(_) | Node::Float(_) | Node::String(_) | Node::List(_)
        ) && status.invalid_value.is_none()
        {
            status.invalid_value = Some(crate::message::render_value(&node_to_json(arena, node)));
        }
        return;
    }

    match arena.node(node) {
        Node::Intrinsic(IntrinsicFn::Ref(target)) if target == PSEUDO_NO_VALUE => {}
        Node::Intrinsic(IntrinsicFn::If(condition, when_true, when_false)) => {
            assumptions.push((condition.clone(), true));
            collect_lifecycle_attribute_status(
                arena,
                *when_true,
                conditions,
                allows_no_value_omission,
                assumptions,
                status,
            );
            assumptions.pop();
            assumptions.push((condition.clone(), false));
            collect_lifecycle_attribute_status(
                arena,
                *when_false,
                conditions,
                allows_no_value_omission,
                assumptions,
                status,
            );
            assumptions.pop();
        }
        Node::Intrinsic(_) | Node::Map(_) => status.may_be_present = true,
        Node::Null | Node::Bool(_) | Node::Int(_) | Node::Float(_) | Node::String(_) | Node::List(_) => {
            status.may_be_present = true;
            if status.invalid_value.is_none() {
                status.invalid_value = Some(crate::message::render_value(&node_to_json(arena, node)));
            }
        }
    }
}

fn resolve_resource(arena: &Arena, name: &str, node_ref: NodeRef, resolver: &mut Resolver) -> ResolvedResource {
    let entries = arena.as_map(node_ref).unwrap_or(&[]);
    let resource_type =
        entries.iter().find(|(k, _)| k == KEY_TYPE).and_then(|(_, v)| arena.as_str(*v)).unwrap_or("").to_string();
    let condition =
        entries.iter().find(|(k, _)| k == KEY_CONDITION).and_then(|(_, v)| arena.as_str(*v)).map(|s| s.to_string());
    let depends_on = entries
        .iter()
        .find(|(k, _)| k == KEY_DEPENDS_ON)
        .map(|(_, v)| match arena.node(*v) {
            Node::String(s) => vec![s.clone()],
            Node::List(items) => items.iter().filter_map(|r| arena.as_str(*r).map(|s| s.to_string())).collect(),
            _ => vec![],
        })
        .unwrap_or_default();
    let deletion_policy =
        entries.iter().find(|(k, _)| k == KEY_DELETION_POLICY).map(|(_, v)| resolver.resolve_node(*v));
    let update_replace_policy =
        entries.iter().find(|(k, _)| k == KEY_UPDATE_REPLACE_POLICY).map(|(_, v)| resolver.resolve_node(*v));
    let metadata_ref = entries.iter().find(|(k, _)| k == SECTION_METADATA).map(|(_, v)| *v);
    let metadata = metadata_ref.map(|v| node_to_json(arena, v));
    let update_policy = entries.iter().find(|(k, _)| k == KEY_UPDATE_POLICY).map(|(_, v)| node_to_json(arena, *v));
    let creation_policy = entries.iter().find(|(k, _)| k == KEY_CREATION_POLICY).map(|(_, v)| node_to_json(arena, *v));

    let resolved_metadata = if let Some(meta_ref) = metadata_ref {
        resolver.set_current_path(SECTION_METADATA);
        Some(resolver.resolve_node(meta_ref))
    } else {
        None
    };

    let mut properties = HashMap::new();
    let mut properties_dynamic = false;
    if let Some((_, props_ref)) = entries.iter().find(|(k, _)| k == KEY_PROPERTIES) {
        if let Some(prop_entries) = arena.as_map(*props_ref) {
            for (key, val_ref) in prop_entries {
                resolver.set_current_path(&format!("Properties.{}", key));
                properties.insert(key.clone(), resolver.resolve_node(*val_ref));
            }
        } else if let Some(synthetic_key) = intrinsic_synthetic_key(arena, *props_ref) {
            // `Properties: {Fn::If: [...]}` collapses in the IR into an intrinsic
            // node rather than a map. Preserve the intrinsic as a single entry so
            // downstream validators can enumerate each branch via scenario
            // resolution without losing the original conditional structure.
            // Use bare `Properties` as the base path so the Fn::If handler in
            // the resolver records branch sources at the single-prefix path
            // rather than doubling the `Fn::If` segment.
            resolver.set_current_path(KEY_PROPERTIES);
            properties.insert(synthetic_key, resolver.resolve_node(*props_ref));
        } else if matches!(arena.node(*props_ref), Node::Intrinsic(_)) {
            // The whole Properties block is an intrinsic (e.g. `!Ref AWS::NoValue`)
            // that did not collapse into a per-branch synthetic key. Its effective
            // properties are only known at deploy time.
            properties_dynamic = true;
        }
    }

    let mut conditionally_null_props = Vec::new();
    for (key, val) in &properties {
        collect_conditional_nulls(val, key, &mut conditionally_null_props);
    }

    let mut condition_refs = Vec::new();
    for v in properties.values() {
        collect_condition_refs_from_resolved(v, &mut condition_refs);
    }
    if let Some(ref meta_resolved) = resolved_metadata {
        collect_condition_refs_from_resolved(meta_resolved, &mut condition_refs);
    }
    if let Some(ref dp) = deletion_policy {
        collect_condition_refs_from_resolved(dp, &mut condition_refs);
    }
    if let Some(ref urp) = update_replace_policy {
        collect_condition_refs_from_resolved(urp, &mut condition_refs);
    }
    if let Some(mut extra) = resolver.extra_condition_refs.remove(name) {
        condition_refs.append(&mut extra);
    }
    condition_refs.sort();
    condition_refs.dedup();

    ResolvedResource {
        logical_id: name.to_string(),
        resource_type,
        condition,
        depends_on,
        deletion_policy,
        update_replace_policy,
        update_policy: update_policy.map(JsonValue),
        creation_policy: creation_policy.map(JsonValue),
        metadata: metadata.map(JsonValue),
        properties,
        properties_dynamic,
        diagnostics: ResourceDiagnostics {
            find_in_map_refs: resolver.find_in_map_refs.remove(name).unwrap_or_default(),
            simple_subs: resolver
                .simple_subs
                .remove(name)
                .unwrap_or_default()
                .into_iter()
                .map(|(a, b)| PathValuePair { path: a, value: b })
                .collect(),
            redundant_subs: resolver.redundant_subs.remove(name).unwrap_or_default(),
            empty_joins: resolver.empty_joins.remove(name).unwrap_or_default(),
            hardcoded_partition_arns: collapse_list_sibling_arn_paths(
                resolver.hardcoded_partition_arns.remove(name).unwrap_or_default(),
            ),
            foreach_expansions: resolver
                .foreach_expansions
                .remove(name)
                .unwrap_or_default()
                .into_iter()
                .map(|(path, ident, coll)| ForEachExpansion {
                    property_path: path,
                    identifier: ident,
                    collection_source: coll,
                })
                .collect(),
            unsubstituted_variables: resolver
                .unsubstituted_variables
                .remove(name)
                .unwrap_or_default()
                .into_iter()
                .map(|(a, b)| PathValuePair { path: a, value: b })
                .collect(),
            unused_sub_keys: resolver
                .unused_sub_keys
                .remove(name)
                .unwrap_or_default()
                .into_iter()
                .map(|(a, b)| PathValuePair { path: a, value: b })
                .collect(),
            raw_pseudo_params: resolver
                .raw_pseudo_params
                .remove(name)
                .unwrap_or_default()
                .into_iter()
                .map(|(a, b)| PathValuePair { path: a, value: b })
                .collect(),
            secretsmanager_ref_paths: resolver.secretsmanager_ref_paths.remove(name).unwrap_or_default(),
            invalid_refs: resolver
                .invalid_refs
                .remove(name)
                .unwrap_or_default()
                .into_iter()
                .map(|(a, b)| PathValuePair { path: a, value: b })
                .collect(),
            conditionally_null_props: conditionally_null_props
                .into_iter()
                .map(|(a, b, c)| ConditionalNullEntry { path: a, condition: b, null_in_true_branch: c })
                .collect(),
            condition_refs,
        },
    }
}

/// Collapses hardcoded-partition ARN paths that are list siblings sharing one
/// source location into a single path at the lowest index.
///
/// When several `Fn::Sub` ARNs are list elements of the same property (e.g.
/// `Principal.AWS.0.Fn::Sub`, `Principal.AWS.1.Fn::Sub`), they map to the same
/// source span - the list's location - so they are one observable finding, not
/// several. Paths whose only difference is the list index immediately before the
/// trailing `.Fn::Sub` segment are therefore folded to the smallest index.
fn collapse_list_sibling_arn_paths(paths: Vec<String>) -> Vec<String> {
    // Group key: the path with the final list index (the segment just before
    // `.Fn::Sub`) blanked out. Tracks the minimum index seen per group so the
    // surviving path reports the first sibling.
    let mut min_index: HashMap<String, usize> = HashMap::new();
    let mut ungrouped: Vec<String> = Vec::new();
    for path in &paths {
        match split_trailing_list_index(path) {
            Some((prefix, idx, suffix)) => {
                let key = format!("{}\u{0}{}", prefix, suffix);
                min_index.entry(key).and_modify(|m| *m = (*m).min(idx)).or_insert(idx);
            }
            None => ungrouped.push(path.clone()),
        }
    }
    let mut out = ungrouped;
    for (key, idx) in min_index {
        let (prefix, suffix) = key.split_once('\u{0}').unwrap_or((key.as_str(), ""));
        out.push(format!("{}{}.{}", prefix, idx, suffix));
    }
    out.sort();
    out
}

/// Splits a path like `a.b.2.Fn::Sub` into (`"a.b."`, `2`, `"Fn::Sub"`) when a
/// numeric list index directly precedes the trailing `.Fn::Sub` segment.
fn split_trailing_list_index(path: &str) -> Option<(String, usize, String)> {
    let suffix = "Fn::Sub";
    let stem = path.strip_suffix(suffix)?.strip_suffix('.')?;
    let (head, last) = stem.rsplit_once('.')?;
    let idx: usize = last.parse().ok()?;
    Some((format!("{}.", head), idx, suffix.to_string()))
}

/// An output `Value` must resolve to a string. A literal non-empty list or map,
/// or a function whose result is a list (`Fn::GetAZs`, `Fn::Split`, `Fn::Cidr`),
/// can never be a string and is a guaranteed template error. `Fn::If` is
/// transparent: each branch is checked at its own location, so a conditional
/// that picks a string in one branch and a list in the other is flagged only on
/// the offending branch. Empty containers are accepted (they carry no members to
/// stringify) and every other function (`Ref`, `Fn::Sub`, `Fn::Join`,
/// `Fn::Select`, `Fn::FindInMap`, `Fn::ImportValue`, …) is treated as
/// string-producing here - a `Fn::GetAtt` returning a non-string is caught later
/// against the resource schema, which this parse-time shape check cannot see.
fn check_output_value_is_string(arena: &Arena, value_ref: NodeRef, output_name: &str, resolver: &mut Resolver) {
    let build_path = format!("Outputs/{}/Value", output_name);
    check_output_value_node(arena, value_ref, output_name, &build_path, resolver);
}

/// Recursive worker for [`check_output_value_is_string`]. `build_path` is the
/// slash path of the node under inspection; each `Fn::If` branch is visited with
/// its own branch path so that a conditional with a bad value in both branches
/// yields a separate, correctly-located diagnostic per branch rather than
/// collapsing to one.
fn check_output_value_node(
    arena: &Arena,
    value_ref: NodeRef,
    output_name: &str,
    build_path: &str,
    resolver: &mut Resolver,
) {
    let span = arena.span(value_ref);
    match arena.node(value_ref) {
        Node::List(items) if !items.is_empty() => {
            resolver.diagnostics.push(crate::make_parse_defect_at(
                "F6101",
                format!("Output '{}' value must be a string, not a list", output_name),
                span,
                build_path,
            ));
        }
        Node::Map(entries) if !entries.is_empty() => {
            resolver.diagnostics.push(crate::make_parse_defect_at(
                "F6101",
                format!("Output '{}' value must be a string, not an object", output_name),
                span,
                build_path,
            ));
        }
        Node::Intrinsic(IntrinsicFn::If(_, if_true, if_false) | IntrinsicFn::IfExpr(_, if_true, if_false)) => {
            let (if_true, if_false) = (*if_true, *if_false);
            check_output_value_node(arena, if_true, output_name, &format!("{}/{}/1", build_path, FN_IF), resolver);
            check_output_value_node(arena, if_false, output_name, &format!("{}/{}/2", build_path, FN_IF), resolver);
        }
        Node::Intrinsic(intrinsic) if returns_list(intrinsic) => {
            resolver.diagnostics.push(crate::make_parse_defect_at(
                "F6101",
                format!("Output '{}' value must be a string, not a list", output_name),
                span,
                build_path,
            ));
        }
        _ => {}
    }
}

/// Whether an intrinsic's result is a list value (never a string). These are the
/// only list-returning functions that can stand as a whole output `Value`;
/// `Fn::If` is handled separately (its branches are checked), and every other
/// function yields a string or an opaque deploy-time value.
fn returns_list(intrinsic: &IntrinsicFn) -> bool {
    matches!(intrinsic, IntrinsicFn::GetAZs(_) | IntrinsicFn::Split(_, _) | IntrinsicFn::Cidr(_, _, _))
}

fn resolve_output(arena: &Arena, node_ref: NodeRef, resolver: &mut Resolver) -> ResolvedOutput {
    let entries = arena.as_map(node_ref).unwrap_or(&[]);

    // Validate output property keys
    const VALID_OUTPUT_KEYS: &[&str] = &[KEY_VALUE, SECTION_DESCRIPTION, KEY_CONDITION, KEY_EXPORT];
    let output_name = resolver.current_resource.as_deref().unwrap_or("");
    let display_name = output_name.strip_prefix(OUTPUT_PSEUDO_RESOURCE_PREFIX).unwrap_or(output_name);
    for (key, _) in entries {
        if !VALID_OUTPUT_KEYS.contains(&key.as_str()) {
            resolver.diagnostics.push(crate::make_parse_defect(
                "E6001",
                format!(
                    "Output '{}' has invalid property '{}'. Valid properties: Value, Description, Condition, Export",
                    display_name, key
                ),
                crate::ir::UNKNOWN_SPAN,
            ));
        }
    }

    if let Some((_, value_ref)) = entries.iter().find(|(k, _)| k == KEY_VALUE) {
        let value_ref = *value_ref;
        let name = display_name.to_string();
        check_output_value_is_string(arena, value_ref, &name, resolver);
    }

    let value = entries
        .iter()
        .find(|(k, _)| k == KEY_VALUE)
        .map(|(_, v)| resolver.resolve_node(*v))
        .unwrap_or(ResolvedValue::Dynamic { reason: "missing output value".into() });
    let description = entries
        .iter()
        .find(|(k, _)| k == SECTION_DESCRIPTION)
        .and_then(|(_, v)| arena.as_str(*v))
        .map(|s| s.to_string());
    let condition =
        entries.iter().find(|(k, _)| k == KEY_CONDITION).and_then(|(_, v)| arena.as_str(*v)).map(|s| s.to_string());
    let export_name = entries
        .iter()
        .find(|(k, _)| k == KEY_EXPORT)
        .and_then(|(_, v)| arena.as_map(*v))
        .and_then(|m| m.iter().find(|(k, _)| k == KEY_NAME))
        .map(|(_, v)| resolver.resolve_node(*v));
    ResolvedOutput { value, description, condition, export_name }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn invalid_overrides_reports_nothing_when_unset_or_valid() {
        assert!(PseudoParameterOverrides::default().invalid_overrides().is_empty(), "unset overrides are valid");
        let valid = PseudoParameterOverrides {
            account_id: Some("123456789012".to_string()),
            partition: Some("aws-cn".to_string()),
            ..Default::default()
        };
        assert!(valid.invalid_overrides().is_empty(), "well-formed overrides produce no warnings");
    }

    #[test]
    fn invalid_overrides_reports_each_malformed_provided_value() {
        let bad = PseudoParameterOverrides {
            account_id: Some("unknown-account".to_string()),
            partition: Some("gcp".to_string()),
            ..Default::default()
        };
        let problems = bad.invalid_overrides();
        assert_eq!(problems.len(), 2, "one entry per invalid provided field");
        assert!(problems.iter().any(|p| p.contains("AccountId") && p.contains("unknown-account")));
        assert!(problems.iter().any(|p| p.contains("Partition") && p.contains("gcp")));
    }

    #[test]
    fn invalid_overrides_only_checks_account_id_and_partition() {
        let only_region = PseudoParameterOverrides { region: Some("not a region".to_string()), ..Default::default() };
        assert!(only_region.invalid_overrides().is_empty());
    }

    #[test]
    fn account_id_shape_requires_exactly_twelve_digits() {
        assert!(is_account_id_shaped("123456789012"));
        assert!(!is_account_id_shaped("12345678901"));
        assert!(!is_account_id_shaped("1234567890123"));
        assert!(!is_account_id_shaped("12345678901a"));
        assert!(!is_account_id_shaped(""));
    }

    #[test]
    fn partition_shape_accepts_aws_family_and_rejects_others() {
        for ok in ["aws", "aws-cn", "aws-us-gov", "aws-iso", "aws-iso-b"] {
            assert!(is_partition_shaped(ok), "{ok} should be accepted");
        }
        for bad in ["gcp", "AWS", "azure", ""] {
            assert!(!is_partition_shaped(bad), "{bad} should be rejected");
        }
    }

    #[test]
    fn model_from_simple_template() {
        let input = r#"
AWSTemplateFormatVersion: "2010-09-09"
Resources:
  MyBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: my-bucket
  MyBucket2:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: my-bucket-2
"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        assert_eq!(model.resources.len(), 2);
        assert_eq!(model.resources_of_type("AWS::S3::Bucket").len(), 2);
        assert_eq!(model.resources_of_type("AWS::Fake::Thing").len(), 0);
    }

    /// Resource `R` mixes literal and intrinsic-sourced properties; `IfR` wraps
    /// its whole `Properties` block in an `Fn::If` whose first branch sets
    /// `TopicName` via `Ref` and `DisplayName` to a literal. Exercises every
    /// `is_from_intrinsic` path: reference edges, concretely-resolved intrinsics,
    /// ancestor inheritance, `Fn::If` branch attribution, and plain literals.
    fn intrinsic_source_probe_model() -> SemanticModel {
        let input = r#"
Resources:
  Other:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: other-bucket
  R:
    Type: AWS::SNS::Topic
    Properties:
      LiteralProp: plain-literal
      RefProp: !Ref Other
      GetAttProp: !GetAtt Other.Arn
      JoinProp: !Join ["-", ["a", "b"]]
      NestedRef:
        Inner: !Ref Other
  IfR:
    Type: AWS::SNS::Topic
    Condition: MakeIt
    Properties:
      Fn::If:
        - MakeIt
        - TopicName: !Ref Other
          DisplayName: literal-in-true-branch
          BranchLiteral: literal-one
        - TopicName: plain-literal-two
          DisplayName: !Ref Other
          BranchLiteral: literal-two
Conditions:
  MakeIt: !Equals ["a", "a"]
"#;
        SemanticModel::from_bytes(input.as_bytes()).unwrap()
    }

    #[test]
    fn is_from_intrinsic_separates_intrinsic_values_from_literals() {
        let model = intrinsic_source_probe_model();
        assert!(model.is_from_intrinsic("R", "Properties.RefProp"), "a Ref value is intrinsic-sourced");
        assert!(model.is_from_intrinsic("R", "Properties.GetAttProp"), "a GetAtt value is intrinsic-sourced");
        assert!(
            model.is_from_intrinsic("R", "Properties.JoinProp"),
            "an Fn::Join value keeps its Intrinsic/* source even when it resolves concretely"
        );
        assert!(!model.is_from_intrinsic("R", "Properties.LiteralProp"), "a plain literal is not intrinsic-sourced");
    }

    #[test]
    fn is_from_intrinsic_inherits_from_intrinsic_ancestors() {
        let model = intrinsic_source_probe_model();
        // The Ref lives at Properties.NestedRef.Inner; that exact path and any
        // descendant of it are intrinsic-sourced through ancestor inheritance.
        assert!(model.is_from_intrinsic("R", "Properties.NestedRef.Inner"));
        assert!(model.is_from_intrinsic("R", "Properties.NestedRef.Inner.Deeper"));
        // The enclosing map itself holds no intrinsic; only its Inner value does.
        assert!(!model.is_from_intrinsic("R", "Properties.NestedRef"));
        // A resource that anchors no intrinsic paths is never intrinsic-sourced.
        assert!(!model.is_from_intrinsic("Missing", "Properties.Anything"));
    }

    #[test]
    fn is_from_intrinsic_attributes_fn_if_branch_sources_to_the_bare_path() {
        let model = intrinsic_source_probe_model();
        // The true branch sets TopicName via Ref, so the bare property path is
        // intrinsic-sourced through the branch-qualified index entry.
        assert!(model.is_from_intrinsic("IfR", "Properties.TopicName"));
        // The false branch independently sets DisplayName via Ref.
        assert!(model.is_from_intrinsic("IfR", "Properties.DisplayName"));
        // A property that is literal in both branches remains non-intrinsic.
        assert!(!model.is_from_intrinsic("IfR", "Properties.BranchLiteral"));
    }

    #[test]
    fn diagnostic_span_resolves_dotted_resource_property_path() {
        let input = r#"
Resources:
  MyBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: my-bucket
"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        // A dotted, resource-relative path is normalized to the slash-keyed index
        // entry and resolves to the specific property span (the BucketName value).
        let via_diag = model.diagnostic_span(Some("MyBucket"), "Properties.BucketName").expect("should resolve");
        let expected = model.source_location("Resources/MyBucket/Properties/BucketName").copied().expect("indexed");
        assert_eq!(via_diag, expected, "dotted path should resolve to the exact property span");
    }

    #[test]
    fn diagnostic_span_resolves_bare_top_level_path_without_resource() {
        let input = r#"
BogusSection:
  Value: invalid
Resources:
  MyBucket:
    Type: AWS::S3::Bucket
"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        let via_diag = model.diagnostic_span(None, "BogusSection").expect("should resolve");
        let expected = model.source_location("BogusSection").copied().expect("indexed");
        assert_eq!(via_diag, expected, "bare top-level path should resolve to its authored key");
    }

    #[test]
    fn diagnostic_span_resource_relative_path_never_matches_top_level_section() {
        // A resource property named after a top-level section (Metadata) must anchor
        // at the resource's own Metadata, not the unrelated top-level Metadata block.
        let input = r#"
Metadata:
  AWS::CloudFormation::Interface:
    ParameterGroups: []
Resources:
  MyBucket:
    Type: AWS::S3::Bucket
    Metadata:
      cfn_nag: skip
"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        let via_diag = model.diagnostic_span(Some("MyBucket"), "Metadata").expect("should resolve");
        let resource_meta = model.source_location("Resources/MyBucket/Metadata").copied().expect("indexed");
        let top_level_meta = model.source_location("Metadata").copied().expect("indexed");
        assert_eq!(via_diag, resource_meta, "resource-relative Metadata must anchor at the resource");
        assert_ne!(via_diag, top_level_meta, "must not mislocate onto the top-level Metadata section");
    }

    #[test]
    fn diagnostic_span_resolves_absolute_section_rooted_path() {
        let input = r#"
Resources:
  MyBucket:
    Type: AWS::S3::Bucket
Outputs:
  BucketRef:
    Value: !Ref MyBucket
"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        // An output-anchored path cannot be reached via resource_span (it only roots
        // at Resources/), but diagnostic_span resolves it directly from the index.
        let span = model.diagnostic_span(Some("BucketRef"), "Outputs/BucketRef/Value");
        assert!(span.is_some() && span != Some(UNKNOWN_SPAN), "output path should resolve to a real span");
    }

    #[test]
    fn diagnostic_span_walks_up_when_leaf_node_is_unindexed() {
        let input = r#"
Resources:
  MyBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: my-bucket
"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        // A deeper path that was never indexed falls back to the nearest indexed
        // ancestor (the property, then the resource) rather than UNKNOWN.
        let span = model.diagnostic_span(Some("MyBucket"), "Properties.BucketName.DoesNotExist.Deeper");
        assert!(span.is_some() && span != Some(UNKNOWN_SPAN), "unindexed leaf should walk up to a real span");
    }

    #[test]
    fn diagnostic_span_returns_none_when_nothing_resolvable() {
        let input = r#"
Resources:
  MyBucket:
    Type: AWS::S3::Bucket
"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        // No resource and no property path: there is no candidate key to resolve.
        assert_eq!(model.diagnostic_span(None, ""), None, "no resource and no path yields no span");
        // A property path whose every ancestor is unindexed (no matching section)
        // resolves to nothing.
        assert_eq!(
            model.diagnostic_span(None, "NoSuchSection/Deep/Path"),
            None,
            "an unindexed absolute path yields no span"
        );
    }

    #[test]
    fn model_resolve_property() {
        let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"Name":"hello"}}}}"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        match model.resolve("R", "Properties.Name").unwrap() {
            ResolvedValue::Concrete { value: v } => assert_eq!(v.as_str().unwrap(), "hello"),
            other => panic!("Expected Concrete, got {:?}", other),
        }
    }

    #[test]
    fn model_follow_ref() {
        let input = r#"{"Resources":{"Svc":{"Type":"T","Properties":{"TaskDef":{"Ref":"TD"}}},"TD":{"Type":"T2"}}}"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        assert_eq!(model.follow_ref("Svc", "Properties.TaskDef"), Some("TD"));
    }

    #[test]
    fn model_to_diagnostic_json() {
        let input = r#"{"Resources":{"R":{"Type":"AWS::S3::Bucket","Properties":{"Name":"test"}}}}"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        let json = serde_json::to_value(model.to_diagnostic_json()).unwrap();
        assert_ne!(json.get("resources"), None, "expected 'resources' key in diagnostic JSON");
        assert_ne!(json["resources"].get("R"), None, "expected resource 'R' in diagnostic JSON");
    }

    #[test]
    fn model_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<SemanticModel>();
    }

    #[test]
    fn model_with_conditions() {
        let input = r#"
Parameters:
  Env:
    Type: String
    AllowedValues: [Prod, Dev]
Conditions:
  IsProd:
    Fn::Equals: [!Ref Env, Prod]
Resources:
  R:
    Type: T
    Condition: IsProd
    Properties:
      Size:
        Fn::If: [IsProd, 100, 20]
"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        assert_eq!(model.conditions.conditions.len(), 1);
        let r = model.resource("R").unwrap();
        assert_eq!(r.condition.as_deref(), Some("IsProd"));
        assert!(matches!(
            r.properties.get("Size"),
            Some(ResolvedValue::Conditional { condition: _, if_true: _, if_false: _ })
        ));
    }

    #[test]
    fn model_with_outputs() {
        let input =
            "Resources:\n  R:\n    Type: T\nOutputs:\n  Out1:\n    Value: !Ref R\n    Description: test output\n";
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        assert_eq!(model.outputs.len(), 1);
        assert!(model.outputs.contains_key("Out1"));
    }

    #[test]
    fn resolve_deep_nested_object() {
        let input =
            r#"{"Resources":{"R":{"Type":"T","Properties":{"Config":{"SubKey":"value","Nested":{"Deep":"found"}}}}}}"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        match model.resolve_deep("R", "Properties.Config.SubKey") {
            Some(ResolvedValue::Concrete { value: v }) => assert_eq!(v.as_str().unwrap(), "value"),
            other => panic!("Expected Concrete, got {:?}", other),
        }
        match model.resolve_deep("R", "Properties.Config.Nested.Deep") {
            Some(ResolvedValue::Concrete { value: v }) => assert_eq!(v.as_str().unwrap(), "found"),
            other => panic!("Expected Concrete, got {:?}", other),
        }
    }

    #[test]
    fn resolve_deep_array_index() {
        let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"Tags":[{"Key":"Env","Value":"prod"},{"Key":"App","Value":"web"}]}}}}"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        match model.resolve_deep("R", "Properties.Tags.0.Key") {
            Some(ResolvedValue::Concrete { value: v }) => assert_eq!(v.as_str().unwrap(), "Env"),
            other => panic!("Expected Concrete, got {:?}", other),
        }
    }

    #[test]
    fn resolve_deep_out_of_bounds() {
        let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"Tags":[{"Key":"A"}]}}}}"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        assert!(model.resolve_deep("R", "Properties.Tags.5.Key").is_none(), "out-of-bounds index should return None");
    }

    #[test]
    fn resolve_deep_missing_intermediate() {
        let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"Name":"hello"}}}}"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        assert!(model.resolve_deep("R", "Properties.NonExistent.Sub").is_none());
    }

    #[test]
    fn resolve_deep_top_level_still_works() {
        let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"Name":"hello"}}}}"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        match model.resolve_deep("R", "Properties.Name") {
            Some(ResolvedValue::Concrete { value: v }) => assert_eq!(v.as_str().unwrap(), "hello"),
            other => panic!("Expected Concrete, got {:?}", other),
        }
    }

    #[test]
    fn model_findinmap_refs_tracked() {
        let input = br#"{"Resources":{"R":{"Type":"T","Properties":{"V":{"Fn::FindInMap":["MyMap","k1","k2"]}}}}}"#;
        let model = SemanticModel::from_bytes(input).unwrap();
        assert!(model.resource("R").unwrap().diagnostics.find_in_map_refs.contains(&"MyMap".to_string()));
    }

    #[test]
    fn model_findinmap_refs_tracked_yaml() {
        let input = b"Resources:\n  R:\n    Type: T\n    Properties:\n      V: !FindInMap [MyMap, k1, k2]\n";
        let model = SemanticModel::from_bytes(input).unwrap();
        assert!(model.resource("R").unwrap().diagnostics.find_in_map_refs.contains(&"MyMap".to_string()));
    }

    #[test]
    fn model_to_diagnostic_json_has_outputs_and_mappings() {
        let input = b"AWSTemplateFormatVersion: '2010-09-09'\nMappings:\n  M:\n    k1:\n      k2: val\nResources:\n  R:\n    Type: AWS::S3::Bucket\nOutputs:\n  Out:\n    Value: !Ref R\n";
        let model = SemanticModel::from_bytes(input).unwrap();
        let json = serde_json::to_value(model.to_diagnostic_json()).unwrap();
        assert_ne!(json.get("outputs"), None, "expected 'outputs' key in diagnostic JSON");
        assert_ne!(json.get("mappings"), None, "expected 'mappings' key in diagnostic JSON");
        assert_eq!(json["mappings"]["M"]["k1"]["k2"], "val");
    }

    #[test]
    fn resolve_deep_into_reference() {
        let input = r#"{"Resources":{"Svc":{"Type":"T","Properties":{"TaskDef":{"Ref":"TD"}}},"TD":{"Type":"T2"}}}"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        assert!(
            model.resolve_deep("Svc", "Properties.TaskDef.Something").is_none(),
            "path through Reference should return None"
        );
        match model.resolve_deep("Svc", "Properties.TaskDef") {
            Some(ResolvedValue::Reference { target, kind: _ }) => assert_eq!(target, "TD"),
            other => panic!("Expected Reference, got {:?}", other),
        }
    }

    #[test]
    fn scenario_source_path_maps_effective_indexes_to_authored_branches() {
        let input = br#"{
            "Parameters": {"Mode": {"Type": "String"}},
            "Conditions": {"ChooseFirst": {"Fn::Equals": [{"Ref": "Mode"}, "first"]}},
            "Resources": {"R": {"Type": "T", "Properties": {
                "Values": {"Fn::If": ["ChooseFirst", ["bad"], ["good"]]}
            }}}
        }"#;
        let model = SemanticModel::from_bytes(input).unwrap();
        let true_conditions = HashMap::from([("ChooseFirst".to_string(), true)]);
        let false_conditions = HashMap::from([("ChooseFirst".to_string(), false)]);
        assert_eq!(
            model.scenario_source_path("R", "Properties.Values.0", &true_conditions),
            Some("Properties.Values.Fn::If.1.0".to_string())
        );
        assert_eq!(
            model.scenario_source_path("R", "Properties.Values.0", &false_conditions),
            Some("Properties.Values.Fn::If.2.0".to_string())
        );
    }

    #[test]
    fn resolve_scenarios_json_filters_dynamic() {
        let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"V":{"Fn::ImportValue":"Stack"}}}}}"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        let scenarios = model.resolve_scenarios_json("R", "Properties.V");
        assert!(scenarios.is_empty(), "ImportValue should be filtered as dynamic");
    }

    #[test]
    fn resolve_scenarios_json_returns_concrete() {
        let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"V":"hello"}}}}"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        let scenarios = model.resolve_scenarios_json("R", "Properties.V");
        assert_eq!(scenarios.len(), 1);
        assert_eq!(scenarios[0].0, serde_json::json!("hello"));
    }

    #[test]
    fn resolve_scenarios_json_memoized() {
        let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"V":"hello"}}}}"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        let s1 = model.resolve_scenarios_json("R", "Properties.V");
        let s2 = model.resolve_scenarios_json("R", "Properties.V");
        assert_eq!(s1, s2);
    }

    #[test]
    fn resolve_scenarios_json_shared_reuses_allocation_and_matches_owned() {
        let input = br#"{
            "Parameters": {"Mode": {"Type": "String"}},
            "Conditions": {"ChooseFirst": {"Fn::Equals": [{"Ref": "Mode"}, "first"]}},
            "Resources": {"R": {"Type": "T", "Properties": {
                "V": {"Fn::If": ["ChooseFirst", "a", "b"]}
            }}}
        }"#;
        let model = SemanticModel::from_bytes(input).unwrap();

        let first = model.resolve_scenarios_json_shared("R", "Properties.V");
        let combinations_after_first = model.scenario_combinations_used();
        let second = model.resolve_scenarios_json_shared("R", "Properties.V");
        let owned = model.resolve_scenarios_json("R", "Properties.V");

        assert!(Arc::ptr_eq(&first, &second));
        assert_eq!(first.as_ref(), owned.as_slice());
        assert!(combinations_after_first > 0);
        assert_eq!(model.scenario_combinations_used(), combinations_after_first);
    }

    #[test]
    fn resolve_properties_scenarios_shared_reuses_allocation_and_matches_owned() {
        let input = br#"{
            "Parameters": {"Mode": {"Type": "String"}},
            "Conditions": {"ChooseFirst": {"Fn::Equals": [{"Ref": "Mode"}, "first"]}},
            "Resources": {"R": {"Type": "T", "Properties": {
                "V": {"Fn::If": ["ChooseFirst", "a", "b"]}
            }}}
        }"#;
        let model = SemanticModel::from_bytes(input).unwrap();

        let first = model.resolve_properties_scenarios_shared("R");
        let combinations_after_first = model.scenario_combinations_used();
        let second = model.resolve_properties_scenarios_shared("R");
        let owned = model.resolve_properties_scenarios("R");

        assert!(Arc::ptr_eq(&first, &second), "repeated shared access must reuse one allocation");
        assert!(first.len() > 1, "the Fn::If value must expand the whole-properties object into multiple scenarios");
        assert_eq!(
            serde_json::to_value(first.as_ref()).expect("shared scenarios serialize"),
            serde_json::to_value(&owned).expect("owned scenarios serialize"),
            "the owned API must return the same scenarios as the shared accessor"
        );
        assert_eq!(
            model.scenario_combinations_used(),
            combinations_after_first,
            "a cached shared access must not consume additional scenario budget"
        );
    }

    #[test]
    fn default_scenario_queries_are_memoized_and_global_budget_halts_uncached_expansion() {
        let input = br#"{
            "Parameters": {"Env": {"Type": "String"}},
            "Conditions": {"IsProd": {"Fn::Equals": [{"Ref": "Env"}, "prod"]}},
            "Resources": {"R": {"Type": "T", "Properties": {
                "V": {"Fn::If": ["IsProd", "a", "b"]},
                "W": {"Fn::If": ["IsProd", "c", "d"]},
                "X": {"Fn::If": ["IsProd", "e", "f"]}
            }}}
        }"#;
        let model = SemanticModel::from_bytes(input).unwrap();

        assert_eq!(model.scenario_combinations_used(), 0, "a freshly built model has materialized no scenarios");
        assert!(!model.scenario_budget_exhausted());

        let first = model.resolve_scenarios("R", "Properties.V");
        assert!(first.len() > 1, "an Fn::If value must expand into multiple scenarios; got {}", first.len());
        let after_first = model.scenario_combinations_used();
        assert_eq!(after_first, first.len() as u64, "the first query charges exactly the scenarios it produced");

        let repeated = model.resolve_scenarios("R", "Properties.V");
        assert_eq!(repeated.len(), first.len());
        assert_eq!(
            model.scenario_combinations_used(),
            after_first,
            "a repeated default-limit query must reuse its raw scenarios without consuming budget"
        );

        let distinct = model.resolve_scenarios("R", "Properties.W");
        assert!(!distinct.is_empty());
        assert!(
            model.scenario_combinations_used() > after_first,
            "a distinct scenario path must still charge the model-wide budget"
        );

        let to_threshold = MAX_TOTAL_SCENARIO_COMBINATIONS - model.scenario_combinations_used();
        model.add_scenario_combinations_for_test(to_threshold);
        assert!(model.scenario_budget_exhausted());

        let cached = model.resolve_scenarios("R", "Properties.V");
        assert_eq!(
            cached.len(),
            first.len(),
            "cached scenarios remain usable after unrelated queries consume the budget"
        );
        assert!(!model.scenario_expansion_curtailed(), "reading a cached result does not curtail expansion");

        let before_short_circuit = model.scenario_combinations_used();
        let curtailed = model.resolve_scenarios("R", "Properties.X");
        assert!(curtailed.is_empty(), "an uncached query must stop when the model-wide budget is exhausted");
        assert_eq!(model.scenario_combinations_used(), before_short_circuit);
        assert!(model.scenario_expansion_curtailed());
    }

    fn two_scenario_value() -> ResolvedValue {
        ResolvedValue::Conditional {
            condition: "C".to_string(),
            if_true: Box::new(ResolvedValue::Concrete { value: serde_json::json!("yes").into() }),
            if_false: Box::new(ResolvedValue::Concrete { value: serde_json::json!("no").into() }),
        }
    }

    #[test]
    fn exact_remaining_scenario_budget_does_not_mark_curtailment() {
        let model = SemanticModel::from_bytes(br#"{"Resources":{"R":{"Type":"T"}}}"#).unwrap();
        let scenarios = model.collect_scenarios_with_budget(&two_scenario_value(), 8, 2);
        assert_eq!(scenarios.len(), 2);
        assert_eq!(model.scenario_combinations_used(), 2);
        assert!(
            !model.scenario_expansion_curtailed(),
            "materializing exactly every possible scenario at the budget boundary is not curtailment"
        );
    }

    #[test]
    fn remaining_scenario_budget_truncates_and_marks_curtailment() {
        let model = SemanticModel::from_bytes(br#"{"Resources":{"R":{"Type":"T"}}}"#).unwrap();
        let first = model.collect_scenarios_with_budget(&two_scenario_value(), 8, 3);
        assert_eq!(first.len(), 2);
        assert!(!model.scenario_expansion_curtailed());

        let second = model.collect_scenarios_with_budget(&two_scenario_value(), 8, 3);
        assert_eq!(second.len(), 1, "only the one remaining global slot may be used");
        assert_eq!(model.scenario_combinations_used(), 3);
        assert!(model.scenario_expansion_curtailed());

        let exhausted = model.collect_scenarios_with_budget(&two_scenario_value(), 8, 3);
        assert!(exhausted.is_empty());
        assert_eq!(model.scenario_combinations_used(), 3, "the global limit must never be exceeded");
    }

    #[test]
    fn concurrent_scenario_queries_cannot_exceed_global_budget() {
        let model = std::sync::Arc::new(SemanticModel::from_bytes(br#"{"Resources":{"R":{"Type":"T"}}}"#).unwrap());
        let handles: Vec<_> = (0..8)
            .map(|_| {
                let model = std::sync::Arc::clone(&model);
                std::thread::spawn(move || {
                    let value = ResolvedValue::Concrete { value: serde_json::json!("value").into() };
                    model.collect_scenarios_with_budget(&value, 8, 4).len()
                })
            })
            .collect();
        let produced: usize =
            handles.into_iter().map(|handle| handle.join().expect("scenario worker must not panic")).sum();

        assert_eq!(produced, 4, "exactly the global budget may be materialized across all workers");
        assert_eq!(model.scenario_combinations_used(), 4, "concurrent accounting must not overshoot the limit");
        assert!(model.scenario_expansion_curtailed(), "workers denied by exhaustion must mark curtailment");
    }

    #[test]
    fn scenario_expansion_curtailment_flag_starts_false() {
        let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"V":"literal"}}}}"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        assert!(
            !model.scenario_expansion_curtailed(),
            "a freshly built model must not have scenario expansion curtailed"
        );
    }

    #[test]
    fn scenario_expansion_curtailment_flag_set_by_test_helper() {
        let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"V":"literal"}}}}"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        model.set_scenario_expansion_curtailed_for_test();
        assert!(model.scenario_expansion_curtailed(), "the test helper must set the curtailment flag");
    }

    #[test]
    fn scenario_expansion_curtailment_flag_is_monotonic() {
        // Once set, the flag never resets — regardless of subsequent queries that
        // stay within budget.
        let input = r#"{
            "Resources": {"R": {"Type": "T", "Properties": {"V": {"Fn::If": ["C", "a", "b"]}}}}
        }"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        model.set_scenario_expansion_curtailed_for_test();
        // A normal query should not reset the flag.
        let _ = model.resolve_scenarios("R", "Properties.V");
        assert!(model.scenario_expansion_curtailed(), "the curtailment flag must be monotonic — once set it stays set");
    }

    #[test]
    fn estimated_bounds_are_absent_for_a_literal_string() {
        // Schema validation checks a literal against its constraint directly, so
        // the estimating rule is deliberately given nothing for one.
        let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"V":"hello"}}}}"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        assert_eq!(model.estimated_string_length_bounds("R", "Properties.V"), None);
    }

    #[test]
    fn estimated_bounds_span_every_allowed_value() {
        let input = r#"{"Parameters":{"Size":{"Type":"String","AllowedValues":["xs","large"]}},
            "Resources":{"R":{"Type":"T","Properties":{"V":{"Ref":"Size"}}}}}"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        assert_eq!(model.estimated_string_length_bounds("R", "Properties.V"), Some((2, 5)));
    }

    #[test]
    fn estimated_bounds_are_absent_when_a_possibility_is_unknown() {
        let input = r#"{"Parameters":{"Free":{"Type":"String"}},
            "Resources":{"R":{"Type":"T","Properties":{"V":{"Ref":"Free"}}}}}"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        assert_eq!(model.estimated_string_length_bounds("R", "Properties.V"), None);
    }

    #[test]
    fn estimate_string_length_missing_property() {
        let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"V":"hello"}}}}"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        assert!(model.estimated_string_length_bounds("R", "Properties.Missing").is_none());
    }

    #[test]
    fn resource_span_specific_path() {
        let input = "Resources:\n  R:\n    Type: T\n    Properties:\n      Name: hello\n";
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        let span = model.resource_span("R", "Properties/Name");
        // Should find a span (not UNKNOWN_SPAN) for the specific path
        assert!(span.start_line > 0 || span.end_line > 0, "expected non-zero span for Properties/Name");
    }

    #[test]
    fn resource_span_specific_path_dotted_form() {
        let input = "Resources:\n  R:\n    Type: T\n    Properties:\n      Name: hello\n";
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        // A dotted, resource-relative path must resolve to the SAME specific span
        // as its slash-form equivalent - not fall back to the resource span.
        let dotted = model.resource_span("R", "Properties.Name");
        let slashed = model.resource_span("R", "Properties/Name");
        let resource = model.resource_span("R", "");
        assert_eq!(dotted, slashed, "dotted and slash forms must resolve to the same span");
        assert_ne!(dotted, resource, "specific property span must differ from the resource span");
    }

    #[test]
    fn resource_span_falls_back_to_resource() {
        let input = "Resources:\n  R:\n    Type: T\n    Properties:\n      Name: hello\n";
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        let span = model.resource_span("R", "Properties/NonExistent/Deep");
        // Should fall back to the resource-level span
        assert!(span.start_line > 0 || span.end_line > 0, "expected non-zero span, got {:?}", span);
    }

    #[test]
    fn resource_span_nested_array_property_anchors_at_element() {
        // A property inside an array element must anchor at that element, not at the
        // array or the resource. The span index is keyed with the array index.
        let input =
            "Resources:\n  R:\n    Type: T\n    Properties:\n      Ingress:\n      - Port: 80\n      - Port: 443\n";
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        let first = model.resource_span("R", "Properties.Ingress.0.Port");
        let second = model.resource_span("R", "Properties.Ingress.1.Port");
        assert_eq!(first.start_line, 6, "Ingress[0].Port is on line 6, got {:?}", first);
        assert_eq!(second.start_line, 7, "Ingress[1].Port is on line 7, got {:?}", second);
    }

    #[test]
    fn resource_span_empty_id_resolves_section_absolute_path_precisely() {
        // A finding with no resource id (e.g. an Outputs-level diagnostic) carries a
        // section-absolute span-index path. It must resolve against that path directly,
        // NOT be prefixed with `Resources/` (which would mislocate onto the Resources
        // block). A path whose exact node is indexed resolves to that node.
        let input = concat!(
            "Resources:\n  R:\n    Type: T\n",                                  // lines 1-3
            "Outputs:\n  Combined:\n    Value: !Join [\"\", [\"a\", \"b\"]]\n", // lines 4-6
        );
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        // The `Value` node is indexed (line 6) - resolution lands on it exactly.
        let value = model.resource_span("", "Outputs/Combined/Value");
        assert_eq!(value.start_line, 6, "Outputs/Combined/Value is on line 6, got {:?}", value);
        // The output key itself resolves to its own line (line 5).
        let combined = model.resource_span("", "Outputs/Combined");
        assert_eq!(combined.start_line, 5, "Outputs/Combined is on line 5, got {:?}", combined);
    }

    #[test]
    fn resource_span_empty_id_fused_intrinsic_suffix_anchors_at_nearest_slash_ancestor() {
        // A synthetic intrinsic suffix (`.Fn::Join`) is joined to its parent by a DOT,
        // which is deliberately not treated as a path separator here: real span-index
        // keys contain literal dots inside a single segment (e.g. API Gateway's
        // `method.request.path.proxy`), so splitting on dots would shred those paths and
        // mis-anchor. The walk-up therefore trims the whole `Value.Fn::Join` segment on
        // the nearest `/`, landing on the enclosing output - still within Outputs, never
        // on the Resources block. Both engines resolve this identically, which is what
        // keeps them at parity.
        let input = concat!(
            "Resources:\n  R:\n    Type: T\n",                                  // lines 1-3
            "Outputs:\n  Combined:\n    Value: !Join [\"\", [\"a\", \"b\"]]\n", // lines 4-6
        );
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        let span = model.resource_span("", "Outputs/Combined/Value.Fn::Join");
        assert_eq!(
            span.start_line, 5,
            "fused-suffix path must anchor at the enclosing output (line 5), got {:?}",
            span
        );
    }

    #[test]
    fn resource_span_empty_id_does_not_leak_onto_resources_block() {
        // Regression guard: an unresolvable empty-id path must return UNKNOWN rather
        // than walking up a spuriously `Resources/`-prefixed key onto the Resources
        // section. This is the divergence that made the two engines disagree.
        let input = "Resources:\n  R:\n    Type: T\n";
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        let span = model.resource_span("", "Outputs/DoesNotExist/Value");
        assert_eq!(span, UNKNOWN_SPAN, "unresolvable empty-id path must be UNKNOWN, got {:?}", span);
    }

    #[test]
    fn resource_span_empty_path_returns_resource_span() {
        let input = "Resources:\n  R:\n    Type: T\n";
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        let span = model.resource_span("R", "");
        assert!(span.start_line > 0 || span.end_line > 0, "expected non-zero span, got {:?}", span);
    }

    #[test]
    fn resolve_nonexistent_resource_returns_none() {
        let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"V":"x"}}}}"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        assert!(model.resolve("NoSuchResource", "Properties.V").is_none(), "nonexistent resource should return None");
        assert!(model.resolve_deep("NoSuchResource", "Properties.V").is_none());
    }

    #[test]
    fn parse_config_with_parameter_overrides() {
        let input = r#"{"Parameters":{"Env":{"Type":"String","AllowedValues":["dev","prod"]}},"Resources":{"R":{"Type":"T","Properties":{"V":{"Ref":"Env"}}}}}"#;
        let config = ParseConfig {
            parameters: [("Env".to_string(), "staging".to_string())].into_iter().collect(),
            pseudo_parameters: PseudoParameterOverrides::default(),
        };
        let result = SemanticModel::parse(input.as_bytes(), config).unwrap();
        match result.model.resolve("R", "Properties.V") {
            Some(ResolvedValue::Concrete { value: v }) => {
                assert_eq!(v.as_str().unwrap(), "staging")
            }
            other => panic!("Expected Concrete(\"staging\"), got {:?}", other),
        }
    }

    #[test]
    fn parse_config_with_pseudo_parameter_overrides() {
        let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"V":{"Ref":"AWS::Region"}}}}}"#;
        let config = ParseConfig {
            parameters: HashMap::new(),
            pseudo_parameters: PseudoParameterOverrides { region: Some("eu-west-1".to_string()), ..Default::default() },
        };
        let result = SemanticModel::parse(input.as_bytes(), config).unwrap();
        match result.model.resolve("R", "Properties.V") {
            Some(ResolvedValue::Concrete { value: v }) => {
                assert_eq!(v.as_str().unwrap(), "eu-west-1")
            }
            other => panic!("Expected Concrete(\"eu-west-1\"), got {:?}", other),
        }
    }

    #[test]
    fn pseudo_parameter_overrides_defaults() {
        let overrides = PseudoParameterOverrides::default();
        assert_eq!(overrides.region(), DEFAULT_REGION);
        assert_eq!(overrides.get("AWS::AccountId").unwrap(), DEFAULT_ACCOUNT_ID);
        assert_eq!(overrides.get("AWS::Partition").unwrap(), DEFAULT_PARTITION);
        assert_eq!(overrides.get("AWS::StackName").unwrap(), DEFAULT_STACK_NAME);
        assert_eq!(overrides.get("AWS::URLSuffix").unwrap(), DEFAULT_URL_SUFFIX);
        assert!(overrides.get("AWS::StackId").unwrap().contains("arn:"));
        assert!(overrides.get("AWS::NotificationARNs").unwrap().contains("sns"));
        assert_eq!(overrides.get("Unknown"), None, "unknown pseudo-param should return None");
    }

    #[test]
    fn pseudo_parameter_overrides_china_region() {
        let overrides = PseudoParameterOverrides { region: Some("cn-north-1".to_string()), ..Default::default() };
        assert_eq!(overrides.get("AWS::Partition").unwrap(), "aws-cn");
        assert_eq!(overrides.get("AWS::URLSuffix").unwrap(), "amazonaws.com.cn");
    }

    /// `fixed_value` underpins the SAT-solver decision "treat this pseudo-param
    /// as a constant or a free variable". It must return `Some` only when the
    /// caller pinned the corresponding field - never for region-derived
    /// defaults - otherwise `Fn::Equals[Ref AWS::Partition, "aws"]` would be
    /// falsely deterministic and `find_unreachable_branches` would emit
    /// false-positive unreachable-branch diagnostics.
    #[test]
    fn fixed_value_returns_none_for_unset_pseudo_parameters() {
        let overrides = PseudoParameterOverrides::default();

        for name in [
            "AWS::AccountId",
            "AWS::NotificationARNs",
            "AWS::Partition",
            "AWS::Region",
            "AWS::StackId",
            "AWS::StackName",
            "AWS::URLSuffix",
        ] {
            assert_eq!(
                overrides.fixed_value(name),
                None,
                "{name} must be a free variable when the user has not explicitly pinned it"
            );
        }
    }

    #[test]
    fn parameter_name_at_names_the_parameter_behind_a_value() {
        let input = r#"{"Parameters":{"BucketName":{"Type":"String"}},
            "Resources":{"R":{"Type":"AWS::S3::Bucket","Properties":{"BucketName":{"Ref":"BucketName"}}}}}"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        assert_eq!(model.parameter_name_at("R", "Properties.BucketName"), Some("BucketName"));
        assert!(model.is_from_parameter("R", "Properties.BucketName"));
    }

    #[test]
    fn parameter_name_at_is_absent_for_a_value_no_parameter_produced() {
        // A cross-stack import is unknown until deployment without being a
        // parameter, so nothing may name one.
        let input = r#"{"Resources":{"R":{"Type":"AWS::S3::Bucket",
            "Properties":{"BucketName":{"Fn::ImportValue":"SharedName"}}}}}"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        assert_eq!(model.parameter_name_at("R", "Properties.BucketName"), None);
        assert!(!model.is_from_parameter("R", "Properties.BucketName"));
    }

    #[test]
    fn fixed_value_returns_user_supplied_overrides() {
        let overrides = PseudoParameterOverrides {
            account_id: Some("999999999999".to_string()),
            partition: Some("aws-cn".to_string()),
            region: Some("cn-north-1".to_string()),
            stack_name: Some("MyStack".to_string()),
            ..Default::default()
        };

        assert_eq!(overrides.fixed_value("AWS::AccountId"), Some("999999999999".to_string()));
        assert_eq!(overrides.fixed_value("AWS::Partition"), Some("aws-cn".to_string()));
        assert_eq!(overrides.fixed_value("AWS::Region"), Some("cn-north-1".to_string()));
        assert_eq!(overrides.fixed_value("AWS::StackName"), Some("MyStack".to_string()));
        assert_eq!(overrides.fixed_value("AWS::URLSuffix"), None, "URLSuffix not set; must remain a free variable");
        assert_eq!(overrides.fixed_value("Unknown"), None);
    }

    #[test]
    fn parameter_name_from_source_reads_only_a_parameter_entry() {
        assert_eq!(parameter_name_from_source("Parameters/InstanceType/Default"), Some("InstanceType"));
        assert_eq!(parameter_name_from_source("Parameters/InstanceType/AllowedValues"), Some("InstanceType"));
        assert_eq!(parameter_name_from_source("Parameters/InstanceType"), Some("InstanceType"));
        assert_eq!(parameter_name_from_source("Intrinsic/Ref"), None);
        assert_eq!(parameter_name_from_source("Parameters/"), None);
        assert_eq!(parameter_name_from_source("ParametersLookAlike/Name"), None);
    }

    /// Setting `region` alone must NOT cause `fixed_value("AWS::Partition")`
    /// to return a value. The convenience defaulting that `get` performs (so
    /// resource-property substitution sees a sensible partition string) is
    /// deliberately separate from the SAT-solver pinning, because constraining
    /// the region constrains where the stack deploys, not the partition the
    /// template was written against.
    #[test]
    fn fixed_value_does_not_propagate_region_to_partition() {
        let overrides = PseudoParameterOverrides { region: Some("cn-north-1".to_string()), ..Default::default() };

        assert_eq!(overrides.fixed_value("AWS::Region"), Some("cn-north-1".to_string()));
        assert_eq!(
            overrides.fixed_value("AWS::Partition"),
            None,
            "region override must not propagate to partition - partition stays free unless the caller pins it"
        );
    }

    #[test]
    fn model_rejects_oversized_template() {
        let huge = vec![b' '; 11 * 1024 * 1024];
        let result = SemanticModel::from_bytes(&huge);
        match result {
            Err(e) => assert!(e.message.contains("maximum size")),
            Ok(_) => panic!("Expected error for oversized template"),
        }
    }

    #[test]
    fn follow_ref_returns_none_for_non_reference() {
        let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"V":"hello"}}}}"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        assert_eq!(model.follow_ref("R", "Properties.V"), None, "non-reference value should return None");
    }

    #[test]
    fn resolve_deep_memoization_consistency() {
        let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"Config":{"A":"1","B":"2"}}}}}"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        let r1 = model.resolve_deep("R", "Properties.Config.A");
        let r2 = model.resolve_deep("R", "Properties.Config.A");
        match (&r1, &r2) {
            (Some(ResolvedValue::Concrete { value: a }), Some(ResolvedValue::Concrete { value: b })) => {
                assert_eq!(a, b);
            }
            _ => panic!("Expected matching Concrete values"),
        }
    }

    #[test]
    fn model_with_mappings_and_findinmap() {
        let input = r#"
Mappings:
  RegionMap:
    us-east-1:
      AMI: ami-12345
    us-west-2:
      AMI: ami-67890
Resources:
  R:
    Type: T
    Properties:
      ImageId: !FindInMap [RegionMap, us-east-1, AMI]
"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        match model.resolve("R", "Properties.ImageId") {
            Some(ResolvedValue::Concrete { value: v }) => {
                assert_eq!(v.as_str().unwrap(), "ami-12345")
            }
            other => panic!("Expected Concrete, got {:?}", other),
        }
    }

    #[test]
    fn model_invalid_ref_tracked() {
        let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"V":{"Ref":"NonExistent"}}}}}"#;
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        let r = model.resource("R").unwrap();
        assert!(!r.diagnostics.invalid_refs.is_empty());
        assert!(r.diagnostics.invalid_refs.iter().any(|s| s.value == "NonExistent"));
    }

    #[test]
    fn collapse_arn_paths_folds_list_siblings_to_lowest_index() {
        let input = vec![
            "Properties.KeyPolicy.Statement.2.Principal.AWS.1.Fn::Sub".to_string(),
            "Properties.KeyPolicy.Statement.2.Principal.AWS.0.Fn::Sub".to_string(),
        ];
        let out = collapse_list_sibling_arn_paths(input);
        assert_eq!(out, vec!["Properties.KeyPolicy.Statement.2.Principal.AWS.0.Fn::Sub".to_string()]);
    }

    #[test]
    fn collapse_arn_paths_keeps_distinct_parent_lists() {
        // Differing index is the Statement index, not the one before Fn::Sub, so
        // these are separate source locations and must both survive.
        let input = vec![
            "Properties.PolicyDocument.Statement.0.Resource.Fn::Sub".to_string(),
            "Properties.PolicyDocument.Statement.1.Resource.Fn::Sub".to_string(),
        ];
        let mut out = collapse_list_sibling_arn_paths(input.clone());
        out.sort();
        assert_eq!(out, input);
    }

    #[test]
    fn collapse_arn_paths_leaves_scalar_paths_untouched() {
        let input = vec![
            "Properties.KeyPolicy.Statement.0.Principal.AWS.Fn::Sub".to_string(),
            "Properties.KeyPolicy.Statement.1.Principal.AWS.Fn::Sub".to_string(),
        ];
        let mut out = collapse_list_sibling_arn_paths(input.clone());
        out.sort();
        assert_eq!(out, input);
    }

    /// Number of output value-type diagnostics (F6101) the parse phase produced.
    fn output_string_type_diagnostics(template: &str) -> usize {
        let model = SemanticModel::from_bytes(template.as_bytes()).unwrap();
        model.diagnostics.iter().filter(|d| d.rule_id == "F6101").count()
    }

    #[test]
    fn output_literal_list_value_flagged() {
        let template = "Resources:\n  R:\n    Type: T\nOutputs:\n  O:\n    Value:\n      - a\n      - b\n";
        assert_eq!(output_string_type_diagnostics(template), 1);
    }

    #[test]
    fn output_literal_object_value_flagged() {
        let template = "Resources:\n  R:\n    Type: T\nOutputs:\n  O:\n    Value:\n      Key: v\n";
        assert_eq!(output_string_type_diagnostics(template), 1);
    }

    #[test]
    fn output_list_returning_functions_flagged() {
        for value in ["!GetAZs \"\"", "!Split [\",\", \"a,b\"]", "!Cidr [\"10.0.0.0/16\", 1, 8]"] {
            let template = format!("Resources:\n  R:\n    Type: T\nOutputs:\n  O:\n    Value: {}\n", value);
            assert_eq!(output_string_type_diagnostics(&template), 1, "expected F6101 for output value {}", value);
        }
    }

    #[test]
    fn output_empty_container_value_not_flagged() {
        // An empty list/object has no members to stringify; CloudFormation does
        // not reject it, so neither does the parse-time check.
        for value in ["[]", "{}"] {
            let template = format!("Resources:\n  R:\n    Type: T\nOutputs:\n  O:\n    Value: {}\n", value);
            assert_eq!(output_string_type_diagnostics(&template), 0, "empty container {} must not be flagged", value);
        }
    }

    #[test]
    fn output_string_producing_values_not_flagged() {
        // Scalars coerce to strings; Ref/Fn::Sub/Fn::Join/Fn::Select/Fn::ImportValue
        // produce (or are treated as) strings. None are string-type violations.
        for value in ["hello", "42", "true", "!Ref R", "!Sub \"${R}\"", "!Join [\",\", [\"a\"]]", "!ImportValue X"] {
            let template = format!("Resources:\n  R:\n    Type: T\nOutputs:\n  O:\n    Value: {}\n", value);
            assert_eq!(output_string_type_diagnostics(&template), 0, "string-valued output {} must not fire", value);
        }
    }

    #[test]
    fn output_find_in_map_list_value_not_flagged() {
        // Fn::FindInMap can resolve to a list, but it is not flagged here (the
        // mapping's shape is validated elsewhere): only literal lists and
        // list-returning functions are string-type violations. This is exactly
        // the case a resolved-value check would get wrong, since the resolved
        // value is indistinguishable from a literal list.
        let template = "Mappings:\n  M:\n    k:\n      l:\n        - a\n        - b\nResources:\n  R:\n    Type: T\nOutputs:\n  O:\n    Value: !FindInMap [M, k, l]\n";
        assert_eq!(output_string_type_diagnostics(template), 0);
    }

    #[test]
    fn output_fn_if_flags_each_list_branch() {
        // Fn::If is transparent: each branch is checked. Both branches are lists,
        // so both are flagged.
        let template = "Conditions:\n  C:\n    Fn::Equals: [\"a\", \"a\"]\nResources:\n  R:\n    Type: T\nOutputs:\n  O:\n    Value:\n      Fn::If: [C, [\"a\"], [\"b\"]]\n";
        assert_eq!(output_string_type_diagnostics(template), 2);
    }

    #[test]
    fn output_fn_if_string_branches_not_flagged() {
        let template = "Conditions:\n  C:\n    Fn::Equals: [\"a\", \"a\"]\nResources:\n  R:\n    Type: T\nOutputs:\n  O:\n    Value:\n      Fn::If: [C, \"yes\", \"no\"]\n";
        assert_eq!(output_string_type_diagnostics(template), 0);
    }

    #[test]
    fn join_with_enum_list_exact_4096_not_curtailed() {
        use crate::consts::MAX_ENUM_EXPANSION;
        use crate::resolver::join_with_enum_list;
        // Build items that produce exactly MAX_ENUM_EXPANSION combinations:
        // 64 * 64 = 4096 (no truncation needed)
        let variants_a: Vec<ResolvedValue> = (0..64)
            .map(|i| ResolvedValue::Concrete { value: serde_json::Value::String(format!("a{i}")).into() })
            .collect();
        let variants_b: Vec<ResolvedValue> = (0..64)
            .map(|i| ResolvedValue::Concrete { value: serde_json::Value::String(format!("b{i}")).into() })
            .collect();
        let items = vec![ResolvedValue::Enum { variants: variants_a }, ResolvedValue::Enum { variants: variants_b }];
        let (result, curtailed) = join_with_enum_list(",", &items);
        assert!(!curtailed, "exactly {MAX_ENUM_EXPANSION} combinations must not signal curtailment");
        if let ResolvedValue::Enum { variants } = &result {
            assert_eq!(variants.len(), MAX_ENUM_EXPANSION);
        } else {
            panic!("expected Enum result");
        }
    }

    #[test]
    fn join_with_enum_list_one_over_curtailed() {
        use crate::consts::MAX_ENUM_EXPANSION;
        use crate::resolver::join_with_enum_list;
        // 65 * 64 = 4160 > 4096 — must curtail
        let variants_a: Vec<ResolvedValue> = (0..65)
            .map(|i| ResolvedValue::Concrete { value: serde_json::Value::String(format!("a{i}")).into() })
            .collect();
        let variants_b: Vec<ResolvedValue> = (0..64)
            .map(|i| ResolvedValue::Concrete { value: serde_json::Value::String(format!("b{i}")).into() })
            .collect();
        let items = vec![ResolvedValue::Enum { variants: variants_a }, ResolvedValue::Enum { variants: variants_b }];
        let (result, curtailed) = join_with_enum_list(",", &items);
        assert!(curtailed, "exceeding {MAX_ENUM_EXPANSION} combinations must signal curtailment");
        if let ResolvedValue::Enum { variants } = &result {
            assert_eq!(variants.len(), MAX_ENUM_EXPANSION);
        } else {
            panic!("expected Enum result");
        }
    }

    #[test]
    fn primary_id_same_parameter_across_ref_sub_join_collides() {
        let template = r#"
Parameters:
  Name: {Type: String}
Resources:
  A:
    Type: AWS::S3::Bucket
    Properties: {BucketName: !Ref Name}
  B:
    Type: AWS::S3::Bucket
    Properties: {BucketName: !Sub '${Name}'}
  C:
    Type: AWS::S3::Bucket
    Properties: {BucketName: !Sub ['${V}', {V: !Ref Name}]}
  D:
    Type: AWS::S3::Bucket
    Properties: {BucketName: !Join ['', [!Ref Name]]}
"#;
        let model = SemanticModel::from_bytes(template.as_bytes()).unwrap();
        let conflicts = model.primary_identifier_conflicts("AWS::S3::Bucket", &["BucketName".to_string()]);
        assert_eq!(conflicts.len(), 1, "all four forms must collide into one group");
        let (_, resources) = conflicts.into_iter().next().unwrap();
        assert_eq!(resources.len(), 4, "all four resources must be in the group");
    }

    #[test]
    fn primary_id_different_parameters_with_equal_defaults_stay_distinct() {
        let template = r#"
Parameters:
  A: {Type: String, Default: shared}
  B: {Type: String, Default: shared}
Resources:
  One:
    Type: AWS::S3::Bucket
    Properties: {BucketName: !Ref A}
  Two:
    Type: AWS::S3::Bucket
    Properties: {BucketName: !Ref B}
"#;
        let model = SemanticModel::from_bytes(template.as_bytes()).unwrap();
        let conflicts = model.primary_identifier_conflicts("AWS::S3::Bucket", &["BucketName".to_string()]);
        assert!(conflicts.is_empty(), "different overridable parameters must not collide: {:?}", conflicts);
    }

    #[test]
    fn primary_id_comparison_identity_is_separate_from_display_value() {
        let template = r#"
Parameters:
  Name: {Type: String}
Resources:
  DynamicOne:
    Type: AWS::S3::Bucket
    Properties: {BucketName: !Ref Name}
  DynamicTwo:
    Type: AWS::S3::Bucket
    Properties: {BucketName: !Ref Name}
  LiteralOne:
    Type: AWS::S3::Bucket
    Properties: {BucketName: 'Ref("Name")'}
  LiteralTwo:
    Type: AWS::S3::Bucket
    Properties: {BucketName: 'Ref("Name")'}
"#;
        let model = SemanticModel::from_bytes(template.as_bytes()).unwrap();
        let conflicts = model.primary_identifier_conflicts("AWS::S3::Bucket", &["BucketName".to_string()]);
        assert_eq!(conflicts.len(), 2, "equal display text must not merge distinct identities");
        assert!(
            conflicts
                .iter()
                .all(|(tuple, resources)| { tuple == &["Ref(\"Name\")".to_string()] && resources.len() == 2 })
        );
    }

    #[test]
    fn primary_id_mutually_exclusive_conditions_do_not_collide() {
        let template = r#"
Parameters:
  Env: {Type: String}
  Name: {Type: String}
Conditions:
  IsProd: !Equals [!Ref Env, prod]
  IsNotProd: !Not [!Condition IsProd]
Resources:
  ProdBucket:
    Type: AWS::S3::Bucket
    Condition: IsProd
    Properties: {BucketName: !Ref Name}
  DevBucket:
    Type: AWS::S3::Bucket
    Condition: IsNotProd
    Properties: {BucketName: !Ref Name}
"#;
        let model = SemanticModel::from_bytes(template.as_bytes()).unwrap();
        let conflicts = model.primary_identifier_conflicts("AWS::S3::Bucket", &["BucketName".to_string()]);
        assert!(conflicts.is_empty(), "mutually exclusive conditions must not collide");
    }

    #[test]
    fn primary_id_no_internal_marker_leakage_in_tuple_values() {
        let template = r#"
Parameters:
  Name: {Type: String}
Resources:
  A:
    Type: AWS::S3::Bucket
    Properties: {BucketName: !Ref Name}
  B:
    Type: AWS::S3::Bucket
    Properties: {BucketName: !Ref Name}
"#;
        let model = SemanticModel::from_bytes(template.as_bytes()).unwrap();
        let conflicts = model.primary_identifier_conflicts("AWS::S3::Bucket", &["BucketName".to_string()]);
        assert_eq!(conflicts.len(), 1);
        let (tuple, _) = conflicts.into_iter().next().unwrap();
        let value = &tuple[0];
        assert!(!value.contains("$dyn:"), "tuple value must not contain $dyn: marker");
        assert!(!value.contains("expr:"), "tuple value must not contain expr: prefix");
    }

    /// The pre-grouping all-pairs traversal, kept verbatim so tests can prove the
    /// grouped implementation is byte-for-byte equivalent - including how the shared
    /// satisfiability budget is spent.
    fn primary_identifier_conflicts_all_pairs_reference(
        model: &SemanticModel,
        resource_type: &str,
        identifier_properties: &[String],
    ) -> Vec<(Vec<String>, BTreeSet<String>)> {
        let mut per_resource = Vec::new();
        for resource_id in model.resources_of_type(resource_type) {
            let scenarios = model.primary_identifier_scenarios(resource_id, identifier_properties);
            if !scenarios.is_empty() {
                per_resource.push((resource_id, scenarios));
            }
        }
        let mut conflicts: BTreeMap<Vec<String>, (Vec<String>, BTreeSet<String>)> = BTreeMap::new();
        for left_index in 0..per_resource.len() {
            for right_index in (left_index + 1)..per_resource.len() {
                let (left_resource, left_scenarios) = &per_resource[left_index];
                let (right_resource, right_scenarios) = &per_resource[right_index];
                for left in left_scenarios {
                    for right in right_scenarios {
                        if left.identity_tuple != right.identity_tuple {
                            continue;
                        }
                        let mut assumptions = left.assumptions.clone();
                        assumptions.extend(right.assumptions.iter().cloned());
                        if assumptions.is_empty() || model.conditions.is_satisfiable(&assumptions) {
                            let (_, resources) = conflicts
                                .entry(left.identity_tuple.clone())
                                .or_insert_with(|| (left.display_tuple.clone(), BTreeSet::new()));
                            resources.insert((*left_resource).clone());
                            resources.insert((*right_resource).clone());
                        }
                    }
                }
            }
        }
        conflicts.into_values().collect()
    }

    #[test]
    fn primary_id_unconditional_resource_collides_with_every_conditional_duplicate() {
        let template = r#"
Parameters:
  Env: {Type: String}
Conditions:
  IsAlpha: !Equals [!Ref Env, alpha]
  IsBeta: !Equals [!Ref Env, beta]
Resources:
  Always:
    Type: AWS::S3::Bucket
    Properties: {BucketName: shared}
  WhenAlpha:
    Type: AWS::S3::Bucket
    Condition: IsAlpha
    Properties: {BucketName: shared}
  WhenBeta:
    Type: AWS::S3::Bucket
    Condition: IsBeta
    Properties: {BucketName: shared}
"#;
        let model = SemanticModel::from_bytes(template.as_bytes()).unwrap();
        let conflicts = model.primary_identifier_conflicts("AWS::S3::Bucket", &["BucketName".to_string()]);
        assert_eq!(conflicts.len(), 1, "the single shared name is one collision group: {conflicts:?}");
        let (display, resources) = conflicts.into_iter().next().unwrap();
        assert_eq!(display, vec!["shared".to_string()]);
        assert_eq!(
            resources,
            BTreeSet::from(["Always".to_string(), "WhenAlpha".to_string(), "WhenBeta".to_string()]),
            "the unconditional resource collides with each conditional duplicate, joining all three even though the two conditions are themselves mutually exclusive"
        );
    }

    #[test]
    fn primary_id_mutually_exclusive_conditions_across_identities_never_collide() {
        let template = r#"
Parameters:
  Env: {Type: String}
  Left: {Type: String}
  Right: {Type: String}
Conditions:
  IsProd: !Equals [!Ref Env, prod]
  IsNotProd: !Not [!Condition IsProd]
Resources:
  LeftProd:
    Type: AWS::S3::Bucket
    Condition: IsProd
    Properties: {BucketName: !Ref Left}
  LeftDev:
    Type: AWS::S3::Bucket
    Condition: IsNotProd
    Properties: {BucketName: !Ref Left}
  RightProd:
    Type: AWS::S3::Bucket
    Condition: IsProd
    Properties: {BucketName: !Ref Right}
  RightDev:
    Type: AWS::S3::Bucket
    Condition: IsNotProd
    Properties: {BucketName: !Ref Right}
"#;
        let model = SemanticModel::from_bytes(template.as_bytes()).unwrap();
        let conflicts = model.primary_identifier_conflicts("AWS::S3::Bucket", &["BucketName".to_string()]);
        assert!(
            conflicts.is_empty(),
            "each identity's two resources are guarded by mutually exclusive conditions, so neither identity group yields a collision: {conflicts:?}"
        );
    }

    #[test]
    fn primary_id_duplicate_scenarios_of_one_resource_do_not_self_collide() {
        let template = r#"
Parameters:
  Env: {Type: String}
Conditions:
  IsProd: !Equals [!Ref Env, prod]
Resources:
  Lonely:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !If [IsProd, shared, shared]
"#;
        let model = SemanticModel::from_bytes(template.as_bytes()).unwrap();
        let scenarios = model.primary_identifier_scenarios("Lonely", &["BucketName".to_string()]);
        assert!(
            scenarios.len() >= 2,
            "the Fn::If must expand into multiple scenarios so self-comparison is actually exercised: {}",
            scenarios.len()
        );
        let identities: BTreeSet<Vec<String>> =
            scenarios.iter().map(|scenario| scenario.identity_tuple.clone()).collect();
        assert_eq!(identities.len(), 1, "the branches must share one comparison identity so they land in one group");

        let conflicts = model.primary_identifier_conflicts("AWS::S3::Bucket", &["BucketName".to_string()]);
        assert!(
            conflicts.is_empty(),
            "a single resource whose branches produce the same identifier must not be reported as colliding with itself: {conflicts:?}"
        );
    }

    #[test]
    fn primary_id_overlapping_conditions_collide() {
        let template = r#"
Parameters:
  Env: {Type: String}
  Name: {Type: String}
Conditions:
  NotAlpha: !Not [!Equals [!Ref Env, alpha]]
  NotBeta: !Not [!Equals [!Ref Env, beta]]
Resources:
  One:
    Type: AWS::S3::Bucket
    Condition: NotAlpha
    Properties: {BucketName: !Ref Name}
  Two:
    Type: AWS::S3::Bucket
    Condition: NotBeta
    Properties: {BucketName: !Ref Name}
"#;
        let model = SemanticModel::from_bytes(template.as_bytes()).unwrap();
        let conflicts = model.primary_identifier_conflicts("AWS::S3::Bucket", &["BucketName".to_string()]);
        assert_eq!(
            conflicts.len(),
            1,
            "the two resources share one identity and their conditions can both hold: {conflicts:?}"
        );
        let (_, resources) = conflicts.into_iter().next().unwrap();
        assert_eq!(resources, BTreeSet::from(["One".to_string(), "Two".to_string()]));
    }

    #[test]
    fn primary_id_display_tuple_comes_from_first_compatible_pair_not_first_candidate() {
        let template = r#"
Parameters:
  Env: {Type: String}
Conditions:
  IsProd: !Equals [!Ref Env, prod]
  IsDev: !Not [!Condition IsProd]
Resources:
  ProdKeyed:
    Type: AWS::S3::Bucket
    Condition: IsProd
    Properties:
      BucketName: {alpha: one, beta: two}
  DevKeyedFirst:
    Type: AWS::S3::Bucket
    Condition: IsDev
    Properties:
      BucketName: {beta: two, alpha: one}
  DevKeyedSecond:
    Type: AWS::S3::Bucket
    Condition: IsDev
    Properties:
      BucketName: {beta: two, alpha: one}
"#;
        let model = SemanticModel::from_bytes(template.as_bytes()).unwrap();
        let conflicts = model.primary_identifier_conflicts("AWS::S3::Bucket", &["BucketName".to_string()]);
        assert_eq!(conflicts.len(), 1, "all three author the same key-sorted identity: {conflicts:?}");
        let (display, resources) = conflicts.into_iter().next().unwrap();
        assert_eq!(
            resources,
            BTreeSet::from(["DevKeyedFirst".to_string(), "DevKeyedSecond".to_string()]),
            "the earlier-declared prod resource is mutually exclusive with both dev resources, so it never forms a compatible pair and is absent from the group"
        );
        assert!(
            display[0].starts_with("{\"beta\""),
            "display must come from the left scenario of the first compatible pair (a dev resource, authored beta-first), not the earlier incompatible prod candidate authored alpha-first: {display:?}"
        );
    }

    #[test]
    fn primary_id_grouped_traversal_matches_all_pairs_reference_and_sat_budget() {
        let template = r#"
Parameters:
  Env: {Type: String}
  Shared: {Type: String}
Conditions:
  IsProd: !Equals [!Ref Env, prod]
  IsStaging: !Equals [!Ref Env, staging]
  IsProdAlias: !Equals [!Ref Env, prod]
Resources:
  AlphaAlways:
    Type: AWS::S3::Bucket
    Properties: {BucketName: alpha}
  AlphaProd:
    Type: AWS::S3::Bucket
    Condition: IsProd
    Properties: {BucketName: alpha}
  AlphaStaging:
    Type: AWS::S3::Bucket
    Condition: IsStaging
    Properties: {BucketName: alpha}
  BetaProd:
    Type: AWS::S3::Bucket
    Condition: IsProd
    Properties: {BucketName: beta}
  BetaProdAlias:
    Type: AWS::S3::Bucket
    Condition: IsProdAlias
    Properties: {BucketName: beta}
  SharedOne:
    Type: AWS::S3::Bucket
    Properties: {BucketName: !Ref Shared}
  SharedTwo:
    Type: AWS::S3::Bucket
    Properties: {BucketName: !Ref Shared}
  Unique:
    Type: AWS::S3::Bucket
    Properties: {BucketName: unique}
"#;
        let identifier_properties = ["BucketName".to_string()];

        let reference_model = SemanticModel::from_bytes(template.as_bytes()).unwrap();
        let reference = primary_identifier_conflicts_all_pairs_reference(
            &reference_model,
            "AWS::S3::Bucket",
            &identifier_properties,
        );
        let reference_budget = reference_model.conditions.sat_iterations_used();

        let model = SemanticModel::from_bytes(template.as_bytes()).unwrap();
        let grouped = model.primary_identifier_conflicts("AWS::S3::Bucket", &identifier_properties);
        let grouped_budget = model.conditions.sat_iterations_used();

        assert_eq!(
            grouped, reference,
            "grouped traversal must produce the identical conflicts as the all-pairs reference"
        );
        assert!(
            reference_budget > 0,
            "the fixture must drive the satisfiability solver so the budget comparison is meaningful"
        );
        assert_eq!(
            grouped_budget, reference_budget,
            "grouped traversal must issue satisfiability queries in the same order and count, spending the shared budget identically across multiple identities"
        );
    }

    #[test]
    fn output_invalid_ref_has_canonical_path() {
        let template = "Resources:\n  R:\n    Type: T\nOutputs:\n  Bad:\n    Value: !Ref Missing\n";
        let result = SemanticModel::parse(template.as_bytes(), ParseConfig::default()).unwrap();
        let ref_defect = result
            .model
            .diagnostics
            .iter()
            .find(|d| d.rule_id == "F6101" && d.message.contains("Missing"))
            .expect("F6101 for missing ref");
        assert_eq!(
            ref_defect.property_path.as_deref(),
            Some("Outputs.Bad.Value.Ref"),
            "parse-time output ref diagnostic must have dot-separated path"
        );
        assert_ne!(ref_defect.span, crate::UNKNOWN_SPAN, "span must be resolved");
    }
}