mold-ai-core 0.21.0

Shared types, API protocol, and HTTP client for mold
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
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
use crate::{
    GenerateRequest, KeyframeCondition, LoraWeight, Ltx2GuidanceOverrides, Ltx2PipelineMode,
    Ltx2SpatialUpscale, OutputFormat, UpscaleRequest,
};

/// Maximum total pixels allowed (~1.8 megapixels). Qwen-Image trains at ~1.6MP
/// (1328x1328), other models at ≤1MP. Headroom for non-square aspect ratios.
pub const MAX_PIXELS: u64 = 1_800_000;
/// LTX-2's own ceiling: upstream's shipped `LTX_2_3_HQ_PARAMS` renders
/// 1920x1088 (stage 1 at 960x544, refined x2), which is 2,088,960 px. The
/// flat 1.8 MP limit made mold unable to express the reference
/// implementation's own top-end preset.
pub const LTX2_MAX_PIXELS: u64 = 1_920 * 1_088;
/// Per-axis span, independent of the pixel budget.
///
/// The checkpoints ship `positional_embedding_max_pos = [20, 2048, 2048]` and
/// RoPE normalizes pixel positions by it, so an axis past 2048 lands outside
/// the trained [-1, 1] range with no error raised. 3200x512 is only 1.64 MP
/// and still out of distribution. Going beyond this needs tiled stage-2
/// refinement with renormalized positions, not a larger single denoise —
/// see [`LTX2_COMPOSED_MAX_AXIS_PIXELS`].
pub const LTX2_MAX_AXIS_PIXELS: u32 = 2_048;

/// Per-axis ceiling for a render that *composes* its output: stage 1 at half
/// the target, one x2 spatial rung, then a tiled stage-2 refinement.
///
/// This is `2 * LTX2_MAX_AXIS_PIXELS` and the factor is not a safety margin —
/// it is exactly where the composition stops working. Stage 1 renders the
/// target halved (`derive_stage1_render_shape`), so a 4096 px target puts
/// stage 1 at 2048 px, the last shape still inside the trained span. Stage 2
/// is tiled, and a tile is always brought back inside that span, so stage 2
/// itself imposes no ceiling. mold applies at most one spatial rung, so there
/// is no second halving to rescue a wider target: past 4096 px, stage 1 is out
/// of distribution and no amount of tiling downstream repairs it.
pub const LTX2_COMPOSED_MAX_AXIS_PIXELS: u32 = 2 * LTX2_MAX_AXIS_PIXELS;

/// Total-pixel ceiling for a composed LTX-2 render (`4096 x 2176`, 8.9 MP).
///
/// Like the single-pass budget this is a resource guard rather than a model
/// limit: it is the widest axis the composition can hold paired with a
/// 4K-class height. It is deliberately *above* the top of
/// [`LTX2_OUTPUT_RUNGS`], which stops at what the bundled H.264 encoder can
/// write — generation and delivery have different ceilings, and conflating
/// them would refuse shapes that render correctly to a non-MP4 target.
pub const LTX2_COMPOSED_MAX_PIXELS: u64 = 4_096 * 2_176;
pub const MAX_INLINE_AUDIO_BYTES: usize = 64 * 1024 * 1024;
pub const MAX_INLINE_SOURCE_VIDEO_BYTES: usize = 64 * 1024 * 1024;
pub const FLUX2_DEV_MAX_REFERENCE_IMAGES: usize = 4;
/// BFL's pixel cap for a single FLUX.2 Dev reference. The upstream value is
/// intentionally 2024 squared, not 2048 squared.
pub const FLUX2_DEV_SINGLE_REFERENCE_MAX_PIXELS: u64 = 2_024 * 2_024;
/// BFL's per-image pixel cap when a FLUX.2 Dev request has multiple references.
pub const FLUX2_DEV_MULTI_REFERENCE_MAX_PIXELS: u64 = 1_024 * 1_024;
pub const LORA_CAPABLE_FAMILIES: &[&str] = &[
    "flux",
    "flux2",
    "ltx2",
    "sd15",
    "sd3",
    "sdxl",
    "qwen-image",
    "qwen-image-edit",
    "z-image",
];

pub fn family_supports_lora(family: &str) -> bool {
    LORA_CAPABLE_FAMILIES.contains(&family)
}

/// Temporal RoPE budget for LTX-2 / LTX-2.3, **in seconds of video runtime**.
///
/// The checkpoints ship `pos_embed_max_pos = 20`, and both upstream `ltx_core`
/// and mold's own RoPE path convert the temporal axis to *seconds* before
/// normalizing by it: `ltx2/model/rope.rs`'s `scale_video_time_to_seconds`
/// divides the pixel-frame coordinate by the request's fps. So `20` bounds
/// twenty seconds of runtime, not twenty latent frames — which is exactly the
/// ~20 s single-generation duration Lightricks advertises for LTX-2.3.
pub const LTX2_MAX_RUNTIME_SECONDS: u32 = 20;

/// fps assumed for LTX-2 when a caller must name a frame ceiling without a
/// request in hand (the `/api/models` scalar fallback, and requests that leave
/// `fps` unset for the server to fill in). Matches the manifest default.
pub const LTX2_DEFAULT_FPS: u32 = 24;

/// Absolute pixel-frame ceiling for LTX-2 regardless of fps.
///
/// This is a resource guard, not a model limit: the seconds budget alone would
/// admit 2404 frames at the maximum allowed 120 fps, which no current GPU can
/// denoise in one pass. 604 is `LTX2_MAX_RUNTIME_SECONDS` at 30 fps — the point
/// where a practical frame budget meets the model's real duration budget.
pub const LTX2_MAX_FRAMES_ABSOLUTE: u32 = LTX2_MAX_RUNTIME_SECONDS * 30 + 4;

/// Global frame ceiling for video families that do not publish their own
/// duration budget (currently `ltx-video`).
pub const MAX_FRAMES_GLOBAL: u32 = 257;

/// Default pixel-frame overlap for `extend_video`, matching the chain
/// motion-tail default so an extend seam and a sequence seam behave the same.
/// 17 pixel frames is three LTX-2 latent frames under the VAE's 8x causal
/// temporal compression.
pub const DEFAULT_EXTEND_OVERLAP_FRAMES: u32 = 17;

/// Inline `extend_video` payloads share the source-video body budget.
pub const MAX_INLINE_EXTEND_VIDEO_BYTES: usize = MAX_INLINE_SOURCE_VIDEO_BYTES;

/// Upper bound for a requested STG block index. The deepest LTX-2 transformer
/// mold runs has 48 layers; the ceiling is loose on purpose because the exact
/// depth is a property of the resolved checkpoint, which validation does not
/// have. The engine rejects an index the loaded transformer does not have.
pub const MAX_STG_BLOCK_INDEX: u32 = 64;

/// Maximum number of simultaneously perturbed STG blocks. Every extra block
/// deepens the perturbed pass; upstream configurations use one or two.
pub const MAX_STG_BLOCKS: usize = 8;

/// Largest pixel-frame count whose final RoPE token still lands inside the
/// LTX-2 temporal budget at `fps`.
///
/// After the causal first-frame fix, latent frame `k` spans pixel bounds
/// `[8k - 7, 8k + 1]`, so the midpoint the RoPE grid actually sees is
/// `(8k - 3) / fps` seconds. `F` pixel frames on the `8n + 1` grid put the last
/// latent at `k = (F - 1) / 8`, giving a midpoint of `(F - 4) / fps`. Requiring
/// that to stay within the budget yields `F <= seconds * fps + 4`.
pub fn ltx2_max_frames_at_fps(fps: u32) -> u32 {
    LTX2_MAX_RUNTIME_SECONDS
        .saturating_mul(fps.max(1))
        .saturating_add(4)
        .min(LTX2_MAX_FRAMES_ABSOLUTE)
}

/// [`ltx2_max_frames_at_fps`] snapped down onto the `8n+1` grid the validator
/// actually enforces.
///
/// The raw cap is not requestable: `20 * 24 + 4 = 484` and `483 % 8 == 3`, so a
/// client that clamps a slider to the advertised maximum and submits gets a
/// 422. At 48 fps the absolute guard bites first — 964 clamps to 604, which is
/// equally off-grid — so this matters at every rate, not just the default.
pub fn ltx2_max_frames_on_grid_at_fps(fps: u32) -> u32 {
    snap_frames_to_8k1(ltx2_max_frames_at_fps(fps))
}

/// Spatial alignment a two-stage LTX-2 render needs. Stage 1 renders at half
/// the requested size, so both axes must survive the halving and still land on
/// the VAE's 32-pixel latent grid. Mirrors upstream `assert_resolution`'s
/// `divisor = 64 if is_two_stage else 32`
/// (`packages/ltx-pipelines/src/ltx_pipelines/utils/helpers.py:326`).
pub const LTX2_TWO_STAGE_ALIGNMENT: u32 = 64;

/// The VAE's causal temporal compression factor: latent frame 0 covers one
/// pixel frame and every later latent frame covers eight, so a renderable
/// pixel-frame count is always `8k + 1`.
pub const LTX2_TEMPORAL_SCALE: u32 = 8;

/// Round `frames` **down** onto the `8k + 1` grid LTX-2 can actually render.
///
/// Mirrors upstream `_snap_frames_to_8k1`
/// (`packages/ltx-pipelines/src/ltx_pipelines/lipdub.py:46-49`). Rounding down
/// matters for lip-dub: the reference clip's frame count is whatever the
/// camera produced, and rounding *up* would ask for frames the reference does
/// not have.
pub fn snap_frames_to_8k1(frames: u32) -> u32 {
    if frames <= 1 {
        return 1;
    }
    frames - ((frames - 1) % LTX2_TEMPORAL_SCALE)
}

/// The frame count and rate a lip-dub render must use, plus anything the
/// caller asked for that the reference video overrode.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LipDubTiming {
    /// Reference frame count snapped down onto the `8k + 1` grid.
    pub frames: u32,
    /// The reference clip's own frame rate.
    pub fps: u32,
    /// Human-readable notes about requested values that were replaced.
    /// Empty when the caller asked for exactly what the reference provides.
    pub warnings: Vec<String>,
}

/// What a probe of the lip-dub reference clip reports.
///
/// A struct rather than positional arguments so every property the pipeline
/// depends on is supplied by name, and so adding one is a compile error at
/// every call site — which is what stops the server and forced-local paths
/// validating different things.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LipDubReference {
    pub frames: u32,
    pub fps: u32,
    /// Whether the clip carries a decodable audio stream. Lip dub imitates the
    /// reference speaker's voice, so a silent reference cannot drive one.
    pub has_audio: bool,
}

/// Resolve a lip-dub render's parameters from its reference video, rejecting a
/// reference that cannot drive one.
///
/// Lip-dub re-voices an existing clip, so the output must land on the
/// reference's own timeline: upstream reads both the frame count and the frame
/// rate straight off the reference stream
/// (`packages/ltx-pipelines/src/ltx_pipelines/lipdub.py:190-192`) rather than
/// taking them from the caller. mold keeps the same rule, but says so out loud
/// when a client asked for something else — a silently retimed dub looks fine
/// and is out of sync.
/// Every precondition lives here rather than at the call sites, so a request
/// that cannot succeed is refused before it is validated, scheduled, and
/// granted VRAM — not several minutes later when the audio VAE has nothing to
/// encode.
pub fn resolve_lip_dub_timing(
    reference: LipDubReference,
    requested_frames: Option<u32>,
    requested_fps: Option<u32>,
) -> Result<LipDubTiming, String> {
    let LipDubReference {
        frames: reference_frames,
        fps: reference_fps,
        has_audio,
    } = reference;
    if reference_fps == 0 {
        return Err("lip-dub reference video reports a frame rate of 0".to_string());
    }
    // Upstream raises on a reference with no audio stream
    // (`lipdub.py:166-170`). Catching it at the request boundary rather than at
    // decode time is the difference between a 422 and a queued job that dies
    // after loading a 22B checkpoint.
    if !has_audio {
        return Err(
            "lip-dub reference video has no audio track; the pipeline re-voices existing \
             speech, so the reference must contain some"
                .to_string(),
        );
    }
    let frames = snap_frames_to_8k1(reference_frames);
    if frames < 9 {
        return Err(format!(
            "lip-dub reference video is too short: {reference_frames} frames snap down to \
             {frames}, and the pipeline needs at least 9"
        ));
    }
    let mut warnings = Vec::new();
    if requested_frames.is_some_and(|requested| requested != frames) {
        warnings.push(format!(
            "lip-dub takes its length from the reference video: rendering {frames} frames \
             instead of the requested {}",
            requested_frames.unwrap_or_default()
        ));
    } else if requested_frames.is_none() && frames != reference_frames {
        warnings.push(format!(
            "lip-dub snapped the reference video's {reference_frames} frames down to {frames} \
             (LTX-2 renders 8k+1 frames)"
        ));
    }
    if requested_fps.is_some_and(|requested| requested != reference_fps) {
        warnings.push(format!(
            "lip-dub takes its frame rate from the reference video: rendering at \
             {reference_fps} fps instead of the requested {}",
            requested_fps.unwrap_or_default()
        ));
    }
    Ok(LipDubTiming {
        frames,
        fps: reference_fps,
        warnings,
    })
}

/// Per-family single-request frame ceiling at `fps` — the value `/api/models`
/// advertises as `max_frames`. Must stay in agreement with
/// `validate_generate_request`'s rejections, which consume this helper.
///
/// LTX-2's ceiling is a duration, so it moves with fps; every other video
/// family reports the flat global ceiling.
pub fn max_frames_for_family_at_fps(family: &str, fps: u32) -> Option<u32> {
    match family {
        // Advertise the value a client can actually submit. The raw duration
        // ceiling sits off the `8n+1` grid at every fps, so a slider clamped
        // to it produced a 422.
        "ltx2" => Some(ltx2_max_frames_on_grid_at_fps(fps)),
        "ltx-video" => Some(MAX_FRAMES_GLOBAL),
        _ => None,
    }
}

/// `max_frames_for_family_at_fps` at each family's default fps, for callers
/// that have no per-model fps to hand.
pub fn max_frames_for_family(family: &str) -> Option<u32> {
    max_frames_for_family_at_fps(family, LTX2_DEFAULT_FPS)
}

/// Single-request runtime ceiling in seconds for families whose real limit is
/// a duration. `None` means the family's ceiling is a plain frame count.
pub fn max_runtime_seconds_for_family(family: &str) -> Option<u32> {
    (family == "ltx2").then_some(LTX2_MAX_RUNTIME_SECONDS)
}

/// fps-independent frame guard, paired with `max_runtime_seconds_for_family`.
pub fn max_frames_absolute_for_family(family: &str) -> Option<u32> {
    (family == "ltx2").then_some(LTX2_MAX_FRAMES_ABSOLUTE)
}

/// Frame-count grid for a family: valid counts are `k * step + 1`. The value
/// `/api/models` advertises as `frame_step`; the validator consumes it.
pub fn frame_step_for_family(family: &str) -> Option<u32> {
    matches!(family, "ltx2" | "ltx-video").then_some(8)
}

fn megapixel_limit_label_for(limit: u64) -> String {
    format!("{:.1}MP", limit as f64 / 1_000_000.0)
}

/// How much spatial work a resolved LTX-2 render splits into.
///
/// This is the only thing that decides whether an axis past the trained RoPE
/// span is renderable, so it is resolved once — from the model and the
/// requested pipeline — rather than inferred separately by each surface.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Ltx2SpatialComposition {
    /// One un-tiled denoise at the requested shape. The trained span is a hard
    /// ceiling: there is nothing downstream to renormalize positions.
    #[default]
    SinglePass,
    /// Stage 1 at half the target, one x2 spatial rung, then a stage-2
    /// refinement over latent tiles each brought back inside the trained span.
    TiledTwoStage,
}

/// Whether a checkpoint ships the spatial upsampler the composition needs.
///
/// Mirrors `Ltx2Pipeline::select_pipeline`: without the upsampler asset every
/// LTX-2 request falls back to a plain one-stage denoise, whatever pipeline was
/// asked for. Single-file catalog checkpoints (`cv:` / `hf:`) have no manifest
/// and therefore no upsampler, which is the conservative answer.
///
/// Component paths supplied through `config.toml` are deliberately not
/// consulted: the validator has no config, and guessing "yes" here would admit
/// a shape the engine then renders out of distribution.
fn model_has_spatial_upsampler(model: &str) -> bool {
    let canonical = crate::manifest::resolve_model_name(model);
    crate::manifest::find_manifest(&canonical).is_some_and(|manifest| {
        manifest
            .files
            .iter()
            .any(|file| file.component == crate::manifest::ModelComponent::SpatialUpscaler)
    })
}

/// Resolve the spatial composition a request will actually run.
///
/// `pipeline` is the request's explicit `ltx2.pipeline`, or `None` to let the
/// engine choose. Either way the answer requires a spatial upsampler on disk,
/// because that is what `select_pipeline` requires before it will pick a
/// refining pipeline at all.
///
/// Prefer [`ltx2_spatial_composition_for_request`] when the request is in
/// hand: with `pipeline: None` this assumes the engine's *default* choice, and
/// several request fields override that default before it is reached.
pub fn ltx2_spatial_composition(
    model: &str,
    pipeline: Option<Ltx2PipelineMode>,
) -> Ltx2SpatialComposition {
    if !model_has_spatial_upsampler(model) {
        return Ltx2SpatialComposition::SinglePass;
    }
    let refines = match pipeline {
        Some(mode) => mode.refines_spatially(),
        // `select_pipeline`'s default for a checkpoint that has the upsampler
        // is `Distilled` or `TwoStage`; both refine.
        None => true,
    };
    if refines {
        Ltx2SpatialComposition::TiledTwoStage
    } else {
        Ltx2SpatialComposition::SinglePass
    }
}

/// The pipeline `select_pipeline` will resolve for a request that names none.
///
/// Mirrors `Ltx2Pipeline::select_pipeline`'s implicit branch order
/// (`ltx2/pipeline.rs:377-388`). Only the *conditioning* selectors are
/// mirrored: the checkpoint-name fallback below them chooses between
/// `Distilled` and `TwoStage`, which both refine, so it cannot change this
/// answer. `retake_range` can and does — retake denoises once.
fn ltx2_implicit_pipeline(req: &GenerateRequest) -> Option<Ltx2PipelineMode> {
    if req.retake_range.is_some() {
        return Some(Ltx2PipelineMode::Retake);
    }
    if req.audio_file.is_some() || req.audio_file_path.is_some() {
        return Some(Ltx2PipelineMode::A2Vid);
    }
    if req.keyframes.as_ref().is_some_and(|items| items.len() > 1) {
        return Some(Ltx2PipelineMode::Keyframe);
    }
    if req.source_video.is_some() || req.source_video_path.is_some() {
        return Some(Ltx2PipelineMode::IcLora);
    }
    None
}

/// [`ltx2_spatial_composition`] resolved from the whole request.
///
/// An explicit `pipeline` wins; otherwise the request's own conditioning
/// decides, exactly as the engine's `select_pipeline` does. Without this a
/// retake — which denoises once — would be admitted at the composed ceiling
/// and only refused by the engine's backstop, minutes later.
pub fn ltx2_spatial_composition_for_request(req: &GenerateRequest) -> Ltx2SpatialComposition {
    ltx2_spatial_composition(
        &req.model,
        req.pipeline.or_else(|| ltx2_implicit_pipeline(req)),
    )
}

/// Total-pixel ceiling for a generation family, assuming no composition.
///
/// Callers that know the resolved model should use
/// [`max_pixels_for_family_composed`]; this is the conservative answer for the
/// ones that only have a family string.
pub fn max_pixels_for_family(family: Option<&str>) -> u64 {
    max_pixels_for_family_composed(family, Ltx2SpatialComposition::SinglePass)
}

/// Composition-aware counterpart to [`max_pixels_for_family`].
pub fn max_pixels_for_family_composed(
    family: Option<&str>,
    composition: Ltx2SpatialComposition,
) -> u64 {
    match (family, composition) {
        (Some("ltx2"), Ltx2SpatialComposition::TiledTwoStage) => LTX2_COMPOSED_MAX_PIXELS,
        (Some("ltx2"), Ltx2SpatialComposition::SinglePass) => LTX2_MAX_PIXELS,
        _ => MAX_PIXELS,
    }
}

/// Per-axis ceiling for a generation family, where one exists.
pub fn max_axis_pixels_for_family(family: Option<&str>) -> Option<u32> {
    max_axis_pixels_for_family_composed(family, Ltx2SpatialComposition::SinglePass)
}

/// Composition-aware counterpart to [`max_axis_pixels_for_family`].
pub fn max_axis_pixels_for_family_composed(
    family: Option<&str>,
    composition: Ltx2SpatialComposition,
) -> Option<u32> {
    match (family, composition) {
        (Some("ltx2"), Ltx2SpatialComposition::TiledTwoStage) => {
            Some(LTX2_COMPOSED_MAX_AXIS_PIXELS)
        }
        (Some("ltx2"), Ltx2SpatialComposition::SinglePass) => Some(LTX2_MAX_AXIS_PIXELS),
        _ => None,
    }
}

/// Required pixel grid for a generation family.
///
/// LTX video VAEs compress spatial dimensions by 32. Every other current
/// family uses the shared 16px generation grid.
pub fn dimension_alignment_for_family(family: Option<&str>) -> u32 {
    if matches!(family, Some("ltx-video" | "ltx2")) {
        32
    } else {
        16
    }
}

/// Validate explicit generation dimensions without rewriting them.
///
/// This is the shared admission boundary for one-shot and chain requests.
/// Clients may project a source image onto this contract, but the server must
/// reject invalid dimensions rather than silently changing the requested
/// canvas.
pub fn validate_generation_dimensions(
    width: u32,
    height: u32,
    family: Option<&str>,
) -> Result<(), String> {
    validate_generation_dimensions_composed(
        width,
        height,
        family,
        Ltx2SpatialComposition::SinglePass,
    )
}

/// Composition-aware counterpart to [`validate_generation_dimensions`].
///
/// Callers that have resolved the model — the HTTP generate and chain paths,
/// and the CLI — pass the real composition so a two-stage LTX-2 render can be
/// admitted past the trained span. Callers that only have a family string keep
/// the conservative single-pass ceiling.
pub fn validate_generation_dimensions_composed(
    width: u32,
    height: u32,
    family: Option<&str>,
    composition: Ltx2SpatialComposition,
) -> Result<(), String> {
    if width == 0 || height == 0 {
        return Err("width and height must be > 0".to_string());
    }

    let alignment = dimension_alignment_for_family(family);
    if !width.is_multiple_of(alignment) || !height.is_multiple_of(alignment) {
        let family_label = family
            .filter(|value| !value.is_empty())
            .map(|value| format!(" for {value} models"))
            .unwrap_or_default();
        return Err(format!(
            "width ({width}) and height ({height}) must be multiples of {alignment}{family_label}"
        ));
    }

    if let Some(axis_limit) = max_axis_pixels_for_family_composed(family, composition) {
        let longest = width.max(height);
        if longest > axis_limit {
            // Two different failures wear the same shape here, and telling
            // them apart is the whole difference between an actionable error
            // and a dead end. Past the composed ceiling nothing helps but a
            // smaller output; past the trained span with a single-pass model,
            // a checkpoint that ships the spatial upsampler does.
            let mut remedy = String::new();
            if composition == Ltx2SpatialComposition::SinglePass
                && longest <= LTX2_COMPOSED_MAX_AXIS_PIXELS
            {
                remedy.push_str(
                    " This checkpoint renders in one pass; reaching that size needs a checkpoint \
                     that ships the spatial upsampler, which renders stage 1 at half size and \
                     refines it over tiles.",
                );
            }
            if let Some(rung) = largest_ltx2_rung_within(axis_limit) {
                remedy.push_str(&format!(
                    " The largest output this render reaches is {} ({}x{}).",
                    rung.label, rung.width, rung.height
                ));
            }
            return Err(format!(
                "{width}x{height} has a {longest}px axis, beyond the {axis_limit}px span this \
                 render can hold — positions past it are out of distribution. Render at or below \
                 {axis_limit}px on the long edge.{remedy}"
            ));
        }
    }

    let limit = max_pixels_for_family_composed(family, composition);
    let pixels = width as u64 * height as u64;
    if pixels > limit {
        return Err(format!(
            "{width}x{height} = {:.2} megapixels exceeds the {} limit (VAE VRAM constraint)",
            pixels as f64 / 1_000_000.0,
            megapixel_limit_label_for(limit)
        ));
    }

    Ok(())
}

/// One rung of the LTX-2 output ladder.
///
/// A rung is an output shape plus the composition that reaches it. Every entry
/// is 64-aligned so stage 1 — the target halved — still lands on the VAE's
/// 32 px latent grid, which is upstream's own `divisor = 64 if is_two_stage`
/// rule (`packages/ltx-pipelines/src/ltx_pipelines/utils/helpers.py:326`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Ltx2OutputRung {
    /// Stable identifier, safe to persist and to match on.
    pub id: &'static str,
    /// Human-readable name for pickers and errors.
    pub label: &'static str,
    pub width: u32,
    pub height: u32,
}

impl Ltx2OutputRung {
    /// Shape stage 1 renders at under one x2 spatial rung.
    ///
    /// Mirrors `derive_stage1_render_shape` / `latent_grid_downsample`: the
    /// target's latent grid is halved with ceiling division, then expanded
    /// back to pixels. `advertised_rungs_match_the_engines_own_arithmetic` in
    /// `mold-inference` pins this to the engine's own arithmetic — this crate
    /// cannot see it, and a rung that names a stage-1 shape the engine does not
    /// render is worse than naming none.
    pub const fn stage1_shape(&self) -> (u32, u32) {
        (
            ltx2_stage1_axis_for(self.width, Some(Ltx2SpatialUpscale::X2)),
            ltx2_stage1_axis_for(self.height, Some(Ltx2SpatialUpscale::X2)),
        )
    }

    /// Whether this rung needs the tiled stage-2 refinement, i.e. whether it
    /// has an axis past the span a single denoise can hold.
    pub const fn requires_tiled_stage2(&self) -> bool {
        self.width > LTX2_MAX_AXIS_PIXELS || self.height > LTX2_MAX_AXIS_PIXELS
    }

    /// Spatial tiles stage 2 splits into, as `(columns, rows)`.
    ///
    /// Mirrors `plan_stage2_tiling`: an axis inside the trained span stays
    /// whole, and an oversized one is split into the fewest tiles whose every
    /// tile fits. Pinned to the engine by
    /// `advertised_rungs_match_the_engines_own_arithmetic`.
    pub const fn stage2_tiles(&self) -> (u32, u32) {
        (
            ltx2_axis_tile_count(self.width),
            ltx2_axis_tile_count(self.height),
        )
    }
}

/// Stage-1 extent for one axis under a spatial rung.
///
/// Mirrors `latent_grid_downsample` in `ltx2/model/upsampler.rs`, including
/// its x1.5 case: the rational upsampler emits `floor((3 * latent + 1) / 2)`
/// cells, so stage 1 needs `ceil((2 * target_latent - 1) / 3)` to cover the
/// requested lattice. An absent rung means stage 1 renders the target itself.
pub const fn ltx2_stage1_axis_for(target: u32, upscale: Option<Ltx2SpatialUpscale>) -> u32 {
    let grid = LTX2_SPATIAL_LATENT_STRIDE;
    let Some(upscale) = upscale else {
        return if target < grid { grid } else { target };
    };
    let target_latent = if target < grid {
        1
    } else {
        target.div_ceil(grid)
    };
    let stage1_latent = match upscale {
        Ltx2SpatialUpscale::X2 => target_latent.div_ceil(2),
        Ltx2SpatialUpscale::X1_5 => target_latent
            .saturating_mul(2)
            .saturating_sub(1)
            .div_ceil(3),
    };
    if stage1_latent == 0 {
        grid
    } else {
        stage1_latent * grid
    }
}

/// Largest output axis whose stage 1 still lands inside the trained span
/// under `upscale`.
///
/// x2 halves, so it reaches `2 * span`. x1.5 only divides by 1.5, so it stops
/// at 3072px — asking for 4K with `--spatial-upscale x1.5` puts stage 1 at
/// 2560px, exactly the out-of-distribution render the ceiling exists to
/// prevent.
pub fn ltx2_composed_axis_ceiling(upscale: Option<Ltx2SpatialUpscale>) -> u32 {
    match upscale {
        None | Some(Ltx2SpatialUpscale::X2) => LTX2_COMPOSED_MAX_AXIS_PIXELS,
        Some(Ltx2SpatialUpscale::X1_5) => {
            // Walk the 32px grid rather than inverting the rational
            // downsample in closed form; the loop is bounded by the composed
            // ceiling and runs once per admission.
            let mut ceiling = LTX2_MAX_AXIS_PIXELS;
            while ceiling < LTX2_COMPOSED_MAX_AXIS_PIXELS
                && ltx2_stage1_axis_for(ceiling + LTX2_SPATIAL_LATENT_STRIDE, upscale)
                    <= LTX2_MAX_AXIS_PIXELS
            {
                ceiling += LTX2_SPATIAL_LATENT_STRIDE;
            }
            ceiling
        }
    }
}

/// Refuse a composed render whose *stage 1* leaves the trained span.
///
/// [`LTX2_COMPOSED_MAX_AXIS_PIXELS`] is shorthand for this check under the
/// default x2 rung. A request that names x1.5 instead needs the real one:
/// a 3840px output renders stage 1 at 2560px, and nothing downstream repairs
/// that — stage 2 tiles the *refinement*, never stage 1.
pub fn validate_ltx2_stage1_span(
    width: u32,
    height: u32,
    upscale: Option<Ltx2SpatialUpscale>,
) -> Result<(), String> {
    // An absent rung on a refining pipeline is not "no rung": the runtime
    // applies an implicit x2 so stage 1 renders halved anyway
    // (`ltx2/runtime.rs`'s `implicit_x2_shape`). Reading `None` literally here
    // would refuse every composed render at once.
    let effective = upscale.unwrap_or(Ltx2SpatialUpscale::X2);
    let stage1 = (
        ltx2_stage1_axis_for(width, Some(effective)),
        ltx2_stage1_axis_for(height, Some(effective)),
    );
    let longest = stage1.0.max(stage1.1);
    if longest <= LTX2_MAX_AXIS_PIXELS {
        return Ok(());
    }
    let rung = match effective {
        Ltx2SpatialUpscale::X1_5 => "x1.5",
        Ltx2SpatialUpscale::X2 => "x2",
    };
    let ceiling = ltx2_composed_axis_ceiling(upscale);
    Err(format!(
        "{width}x{height} with {rung} spatial upscale renders stage 1 at {}x{}, whose {longest}px \
         axis is past the {}px span these checkpoints were trained on. The rung sets the ceiling: \
         it reaches {ceiling}px on the long edge. Use a x2 upscale, or render at or below \
         {ceiling}px.",
        stage1.0, stage1.1, LTX2_MAX_AXIS_PIXELS,
    ))
}

/// Number of stage-2 tiles one axis is split into.
const fn ltx2_axis_tile_count(target: u32) -> u32 {
    if target <= LTX2_MAX_AXIS_PIXELS {
        return 1;
    }
    let count = target.div_ceil(LTX2_MAX_AXIS_PIXELS);
    if count < 2 {
        2
    } else {
        count
    }
}

/// The LTX video VAE's spatial compression factor.
pub const LTX2_SPATIAL_LATENT_STRIDE: u32 = 32;

/// The LTX-2 output ladder, smallest rung first.
///
/// Every rung above 1080p is reached by composition, not by a bigger denoise:
/// stage 1 renders the halved shape, one x2 spatial rung upsamples it, and
/// stage 2 refines the result over tiles.
///
/// **The ladder stops at 4K UHD because of the encoder, not the model.**
/// `LTX2_COMPOSED_MAX_AXIS_PIXELS` (4096) is where a single halving stops
/// landing stage 1 inside the trained span, and generation is admitted that
/// far — but the bundled OpenH264 encoder refuses anything past 3840x2160
/// ("Encoder max resolution 3840x2160 horizontal or 2160x3840 vertical"), and
/// MP4 is this family's default container. A rung wider than 3840, or the
/// 3840x2176 that rounding 2160 *up* onto the /64 grid would give, generates
/// fine and then fails at save time — after the whole render. So the rung is
/// 3840x2112, rounding 2160 *down*, which is upstream's own CENTER_CROP
/// alignment and the largest UHD-class shape mold can actually deliver.
///
/// VRAM: see `website/models/ltx2.md`. The numbers live in prose because the
/// only published figures are upstream's, they are for a different pipeline
/// (HDR IC-LoRA, 161 frames, 22B), and pinning them here would read as mold's
/// own measured requirement.
pub const LTX2_OUTPUT_RUNGS: &[Ltx2OutputRung] = &[
    Ltx2OutputRung {
        id: "720p",
        label: "720p HD",
        width: 1_280,
        height: 704,
    },
    Ltx2OutputRung {
        id: "1080p",
        label: "1080p Full HD",
        width: 1_920,
        height: 1_088,
    },
    Ltx2OutputRung {
        id: "1440p",
        label: "1440p QHD",
        width: 2_560,
        height: 1_408,
    },
    Ltx2OutputRung {
        id: "4k-uhd",
        label: "4K UHD",
        width: 3_840,
        height: 2_112,
    },
];

/// The rung an output shape lands on, in either orientation.
///
/// Portrait is the same rung as its landscape transpose: the composition and
/// the cost are identical, and a picker that called 2176x3840 an unnamed shape
/// would be lying about both.
pub fn ltx2_output_rung(width: u32, height: u32) -> Option<&'static Ltx2OutputRung> {
    LTX2_OUTPUT_RUNGS.iter().find(|rung| {
        (rung.width == width && rung.height == height)
            || (rung.width == height && rung.height == width)
    })
}

/// The largest rung whose long edge fits `axis_limit`.
///
/// This is what makes an over-size rejection actionable: naming the ceiling in
/// pixels tells the user what they cannot have, naming the rung tells them
/// what they can.
pub fn largest_ltx2_rung_within(axis_limit: u32) -> Option<&'static Ltx2OutputRung> {
    LTX2_OUTPUT_RUNGS
        .iter()
        .rfind(|rung| rung.width.max(rung.height) <= axis_limit)
}

fn mib_label(bytes: usize) -> String {
    format!("{:.0} MiB", bytes as f64 / (1024.0 * 1024.0))
}

/// Clamp dimensions to fit within the megapixel limit, preserving aspect ratio.
/// Both dimensions are rounded down to multiples of 16.
/// Returns the original dimensions unchanged if already within limits.
pub fn clamp_to_megapixel_limit(w: u32, h: u32) -> (u32, u32) {
    clamp_to_family_pixel_limit(w, h, None)
}

/// Family-aware counterpart to [`clamp_to_megapixel_limit`].
///
/// Both the ceiling and the rounding grid come from the family. Clamping an
/// LTX-2 source projection with the shared 1.8 MP limit and a /16 grid would
/// shrink a canvas the validator would have accepted, and could land off the
/// /32 grid it requires — a silent downgrade followed by a rejection.
pub fn clamp_to_family_pixel_limit(w: u32, h: u32, family: Option<&str>) -> (u32, u32) {
    let limit = max_pixels_for_family(family);
    let align = dimension_alignment_for_family(family);
    let axis_limit = max_axis_pixels_for_family(family);

    let pixels = w as u64 * h as u64;
    let within_axis = axis_limit.is_none_or(|axis| w.max(h) <= axis);
    if pixels <= limit && within_axis {
        return (w, h);
    }

    let mut scale = if pixels > limit {
        (limit as f64 / pixels as f64).sqrt()
    } else {
        1.0
    };
    if let Some(axis) = axis_limit {
        let longest = w.max(h) as f64;
        if longest * scale > axis as f64 {
            scale = axis as f64 / longest;
        }
    }

    let new_w = ((w as f64 * scale) as u32 / align) * align;
    let new_h = ((h as f64 * scale) as u32 / align) * align;
    // Ensure we don't produce zero dimensions
    (new_w.max(align), new_h.max(align))
}

/// Fit source image dimensions into a model's native resolution bounding box,
/// preserving aspect ratio.
///
/// The model's default width/height define the bounding box. The source image's
/// aspect ratio is preserved:
/// - If the source is wider than the model bounds, width is set to `model_w` and
///   height is scaled proportionally.
/// - If the source is taller, height is set to `model_h` and width is scaled.
/// - If the source fits entirely within model bounds (same aspect ratio as the
///   model), the model's native dimensions are used as the output. For sources
///   with a different aspect ratio, the output fills the limiting axis at model
///   scale while keeping the other axis within bounds.
///
/// Output is rounded to 16px alignment and clamped to the megapixel limit.
pub fn fit_to_model_dimensions(src_w: u32, src_h: u32, model_w: u32, model_h: u32) -> (u32, u32) {
    let src_ratio = src_w as f64 / src_h as f64;
    let model_ratio = model_w as f64 / model_h as f64;

    let (w, h) = if src_ratio > model_ratio {
        // Source is wider: width-limited
        (model_w as f64, model_w as f64 / src_ratio)
    } else {
        // Source is taller or same: height-limited
        (model_h as f64 * src_ratio, model_h as f64)
    };

    let w = ((w as u32) / 16 * 16).max(16);
    let h = ((h as u32) / 16 * 16).max(16);
    clamp_to_megapixel_limit(w, h)
}

/// Resize dimensions toward a target pixel area while preserving aspect ratio.
///
/// The result is rounded to the requested alignment and clamped to the shared
/// megapixel safety limit.
pub fn fit_to_target_area(src_w: u32, src_h: u32, target_area: u32, align: u32) -> (u32, u32) {
    let src_w = src_w.max(1);
    let src_h = src_h.max(1);
    let align = align.max(1);
    let scale = (f64::from(target_area) / (f64::from(src_w) * f64::from(src_h))).sqrt();
    let width = ((f64::from(src_w) * scale) / f64::from(align)).round() as u32 * align;
    let height = ((f64::from(src_h) * scale) / f64::from(align)).round() as u32 * align;
    clamp_to_megapixel_limit(width.max(align), height.max(align))
}

/// Check whether `data` starts with a recognized image format magic bytes (PNG or JPEG).
fn is_valid_image_format(data: &[u8]) -> bool {
    let is_png = data.len() >= 4 && data[..4] == [0x89, 0x50, 0x4E, 0x47];
    let is_jpeg = data.len() >= 2 && data[..2] == [0xFF, 0xD8];
    is_png || is_jpeg
}

fn model_family(model_name: &str) -> Option<&str> {
    crate::manifest::find_manifest(model_name)
        .map(|m| m.family.as_str())
        .or_else(|| {
            if model_name.starts_with("qwen-image-edit") {
                Some("qwen-image-edit")
            } else if model_name.starts_with("qwen-image") {
                Some("qwen-image")
            } else {
                None
            }
        })
}

/// Resolve a model's family for validation, preferring an explicit hint when
/// provided. The hint lets callers (e.g. the HTTP server) pass through a family
/// that the manifest layer can't see — most notably catalog IDs like
/// `cv:2781713` whose family is recorded in the catalog DB rather than the
/// hardcoded manifest. When `family_hint` is `None` (or an empty string), the
/// manifest fallback runs as before.
fn resolved_family<'a>(model_name: &'a str, family_hint: Option<&'a str>) -> Option<&'a str> {
    family_hint
        .filter(|h| !h.is_empty())
        .or_else(|| model_family(model_name))
}

/// Whether `req` must carry a non-empty prompt.
///
/// Video families whose text encoder pads to a fixed-width context (LTX-2's
/// Gemma connector replaces every padded position with learned register
/// embeddings, so `""` is a trained context rather than a degenerate one)
/// accept an empty prompt as long as the request carries visual conditioning
/// to continue: a source image, keyframes, a source video, or an extend. Pure
/// text-to-video and every image family keep the prompt required.
///
/// Note this buys no VRAM — the Gemma context is a fixed-size tensor whose
/// footprint is independent of the token count — and an unprompted clip tends
/// toward near-static micro-motion. Callers should surface that as guidance
/// rather than synthesising a placeholder prompt.
///
/// `family_hint` mirrors [`validate_generate_request_with_family`]: pass the
/// catalog-resolved family for `cv:` / `hf:` model IDs, whose family the
/// manifest cannot see.
pub fn prompt_required_for(req: &GenerateRequest, family_hint: Option<&str>) -> bool {
    prompt_required_with_conditioning(
        resolved_family(&req.model, family_hint),
        has_visual_conditioning(req),
    )
}

/// Whether a request carries visual conditioning — a source image, keyframes,
/// a source video (inline or server-local path), or an extend.
///
/// This is the single definition of "conditioned" for the whole request path.
/// Beyond the optional-prompt rule it also separates OOM cooldown buckets, and
/// those must agree: two requests with different conditioning have different
/// VRAM profiles and must never share a cooldown or a reduced memory grant.
pub fn has_visual_conditioning(req: &GenerateRequest) -> bool {
    req.source_image.is_some()
        || req.keyframes.as_ref().is_some_and(|k| !k.is_empty())
        || req.source_video.is_some()
        || req.source_video_path.is_some()
        || req.is_extend()
}

/// Lower-level form of [`prompt_required_for`] for callers that have not yet
/// assembled a [`GenerateRequest`] — the CLI, TUI and Discord front-ends build
/// the request only after the prompt is resolved. `has_visual_conditioning` is
/// true when the request will carry a source image, keyframes, a source video,
/// or an extend.
pub fn prompt_required_with_conditioning(
    family: Option<&str>,
    has_visual_conditioning: bool,
) -> bool {
    !(matches!(family, Some("ltx2" | "ltx-video")) && has_visual_conditioning)
}

fn validate_lora_weight(lora: &LoraWeight, field_name: &str) -> Result<(), String> {
    if lora.scale < 0.0 || lora.scale > 2.0 {
        return Err(format!(
            "{field_name} scale ({}) must be in range [0.0, 2.0]",
            lora.scale
        ));
    }
    if !lora.path.ends_with(".safetensors") && !lora.path.starts_with("camera-control:") {
        return Err(format!(
            "{field_name} file must be a .safetensors file or camera-control preset"
        ));
    }
    Ok(())
}

fn validate_keyframes(
    keyframes: &[KeyframeCondition],
    frames: Option<u32>,
    family: Option<&str>,
) -> Result<(), String> {
    match family {
        Some("ltx2") => {}
        None => {
            return Err(
                "unknown model family; keyframes are only supported for LTX-2 / LTX-2.3 models"
                    .to_string(),
            );
        }
        _ => {
            return Err("keyframes are only supported for LTX-2 / LTX-2.3 models".to_string());
        }
    }
    if keyframes.is_empty() {
        return Err("keyframes must not be empty".to_string());
    }

    let mut seen = std::collections::BTreeSet::new();
    for keyframe in keyframes {
        if !is_valid_image_format(&keyframe.image) {
            return Err("keyframes must contain only PNG or JPEG images".to_string());
        }
        if let Some(total_frames) = frames {
            if keyframe.frame >= total_frames {
                return Err(format!(
                    "keyframe frame ({}) must be less than frames ({total_frames})",
                    keyframe.frame
                ));
            }
        }
        if !seen.insert(keyframe.frame) {
            return Err(format!("duplicate keyframe frame: {}", keyframe.frame));
        }
    }

    Ok(())
}

/// Bounds-check the LTX-2 multimodal guider overrides.
///
/// These are advanced quality/motion knobs, so the ranges are deliberately
/// generous — the job here is to reject values that cannot mean anything
/// (NaN, negatives, block indices no checkpoint has) before a request reaches
/// the queue, not to police taste. The engine re-checks `stg_blocks` against
/// the resolved checkpoint's transformer depth, which validation cannot know.
fn validate_guidance_overrides(overrides: &Ltx2GuidanceOverrides) -> Result<(), String> {
    if overrides.is_empty() {
        return Err(
            "guidance_overrides must set at least one field; omit it to keep pipeline defaults"
                .to_string(),
        );
    }
    let bounded = |value: Option<f64>, name: &str, max: f64| -> Result<(), String> {
        match value {
            Some(value) if !value.is_finite() => Err(format!("{name} must be a finite number")),
            Some(value) if !(0.0..=max).contains(&value) => {
                Err(format!("{name} ({value}) must be between 0.0 and {max}"))
            }
            _ => Ok(()),
        }
    };
    bounded(
        overrides.stg_scale,
        "guidance_overrides.stg_scale",
        Ltx2GuidanceOverrides::MAX_SCALE,
    )?;
    bounded(
        overrides.modality_scale,
        "guidance_overrides.modality_scale",
        Ltx2GuidanceOverrides::MAX_SCALE,
    )?;
    // Rescale is an interpolation factor between the guided prediction and
    // its std-matched form, so anything outside 0..=1 is meaningless.
    bounded(
        overrides.rescale_scale,
        "guidance_overrides.rescale_scale",
        1.0,
    )?;
    if let Some(skip_step) = overrides.skip_step {
        if skip_step > Ltx2GuidanceOverrides::MAX_SKIP_STEP {
            return Err(format!(
                "guidance_overrides.skip_step ({skip_step}) must be <= {}",
                Ltx2GuidanceOverrides::MAX_SKIP_STEP
            ));
        }
    }
    if let Some(blocks) = &overrides.stg_blocks {
        if blocks.is_empty() {
            return Err(
                "guidance_overrides.stg_blocks must not be empty; omit it to keep the pipeline default block"
                    .to_string(),
            );
        }
        if blocks.len() > MAX_STG_BLOCKS {
            return Err(format!(
                "guidance_overrides.stg_blocks lists {} blocks; at most {MAX_STG_BLOCKS} are supported",
                blocks.len()
            ));
        }
        for (index, block) in blocks.iter().enumerate() {
            if *block >= MAX_STG_BLOCK_INDEX {
                return Err(format!(
                    "guidance_overrides.stg_blocks[{index}] ({block}) exceeds the deepest supported transformer block ({})",
                    MAX_STG_BLOCK_INDEX - 1
                ));
            }
            if blocks[..index].contains(block) {
                return Err(format!(
                    "guidance_overrides.stg_blocks[{index}] ({block}) is listed more than once"
                ));
            }
        }
    }
    Ok(())
}

/// Admission rules for `extend_video` / `extend_video_path`.
///
/// Extend reuses the chain motion-tail machinery, so it inherits the same two
/// hard constraints: the overlap has to land on the LTX-2 VAE's `8k+1` causal
/// temporal grid to re-encode cleanly, and it has to be strictly shorter than
/// the rendered clip or the continuation contributes no new frames at all.
fn validate_extend(req: &GenerateRequest, family: Option<&str>) -> Result<(), String> {
    if let Some(video) = &req.extend_video {
        require_ltx2_family(family, "extend_video")?;
        if req.extend_video_path.is_some() {
            return Err("extend_video_path cannot be combined with extend_video".to_string());
        }
        if video.is_empty() {
            return Err("extend_video must not be empty".to_string());
        }
        validate_inline_media_size(video, "extend_video", MAX_INLINE_EXTEND_VIDEO_BYTES)?;
    }
    if let Some(path) = &req.extend_video_path {
        require_ltx2_family(family, "extend_video_path")?;
        if path.trim().is_empty() {
            return Err("extend_video_path must not be empty".to_string());
        }
    }

    if !req.is_extend() {
        if req.extend_overlap_frames.is_some() {
            return Err(
                "extend_overlap_frames requires extend_video or extend_video_path".to_string(),
            );
        }
        return Ok(());
    }

    // Extend continues one clip's motion; a reference video conditions a fresh
    // render. Accepting both would leave two competing sources of truth for
    // what the first frames should look like.
    if req.source_video.is_some() || req.source_video_path.is_some() {
        return Err(
            "extend_video cannot be combined with source_video; extend continues an existing \
             clip, while source_video is reference conditioning for a fresh render"
                .to_string(),
        );
    }
    if req.source_image.is_some() {
        return Err(
            "extend_video cannot be combined with source_image; the continuation's first frames \
             are pinned by the source video's tail"
                .to_string(),
        );
    }
    if req.keyframes.is_some() {
        return Err("extend_video cannot be combined with keyframes".to_string());
    }

    let overlap = req.effective_extend_overlap_frames();
    if overlap == 0 {
        return Err(
            "extend_overlap_frames must be >= 1 so the continuation has motion context".to_string(),
        );
    }
    if overlap % 8 != 1 {
        return Err(format!(
            "extend_overlap_frames ({overlap}) must be 8k+1 (1, 9, 17, 25, …) so the carryover \
             frames re-encode cleanly through the LTX-2 video VAE's 8x causal grid"
        ));
    }
    if let Some(frames) = req.frames {
        if overlap >= frames {
            return Err(format!(
                "extend_overlap_frames ({overlap}) must be strictly less than frames ({frames}) \
                 so the continuation adds at least one new frame"
            ));
        }
    }
    Ok(())
}

fn require_ltx2_family(family: Option<&str>, feature_name: &str) -> Result<(), String> {
    match family {
        Some("ltx2") => Ok(()),
        None => Err(format!(
            "unknown model family; {feature_name} is only supported for LTX-2 / LTX-2.3 models"
        )),
        _ => Err(format!(
            "{feature_name} is only supported for LTX-2 / LTX-2.3 models"
        )),
    }
}

/// LoRA support is available for FLUX, Flux.2, LTX-2, SD1.5, SD3, SDXL,
/// Qwen-Image (and qwen-image-edit), and Z-Image — `mold-inference`'s
/// per-family `lora.rs` modules are the engine paths that know how to merge
/// low-rank adapters into the base weights. Surfacing the gate at validation
/// produces a clear 400 instead of an opaque inference-layer panic when a
/// user picks an unsupported model family + a LoRA.
fn require_lora_capable_family(family: Option<&str>) -> Result<(), String> {
    match family {
        Some(family) if family_supports_lora(family) => Ok(()),
        Some(other) => Err(format!(
            "LoRA is currently supported for FLUX, Flux.2, LTX-2, SD1.5, SD3, SDXL, Qwen-Image, and Z-Image models; got family {other:?}"
        )),
        None => Err(
            "LoRA requires a known model family — pick a FLUX, Flux.2, LTX-2, SD1.5, SD3, SDXL, Qwen-Image, or Z-Image model first"
                .to_string(),
        ),
    }
}

fn require_controlnet_capable_family(family: Option<&str>) -> Result<(), String> {
    match family {
        Some("sd15" | "sd1.5" | "stable-diffusion-1.5") => Ok(()),
        Some(other) => Err(format!(
            "ControlNet generation is currently supported for SD1.5 models; got family {other:?}"
        )),
        None => Err(
            "ControlNet generation requires a known model family — pick an SD1.5 model first"
                .to_string(),
        ),
    }
}

fn validate_inline_media_size(
    bytes: &[u8],
    field_name: &str,
    max_bytes: usize,
) -> Result<(), String> {
    if bytes.len() > max_bytes {
        return Err(format!(
            "{field_name} exceeds the {} inline request limit (got {:.1} MiB)",
            mib_label(max_bytes),
            bytes.len() as f64 / (1024.0 * 1024.0)
        ));
    }
    Ok(())
}

/// Validate a generate request. Returns `Ok(())` if valid, or an error message.
/// Shared between the HTTP server and local CLI inference paths.
///
/// For models whose family can't be derived from the manifest (catalog IDs
/// like `cv:2781713`), use [`validate_generate_request_with_family`] and pass
/// the resolved family from the catalog DB; otherwise the family-gated
/// features (audio, keyframes, retake, …) will fail with
/// `unknown model family` even on legitimate LTX-2 catalog checkpoints.
pub fn validate_generate_request(req: &GenerateRequest) -> Result<(), String> {
    validate_generate_request_with_family(req, None)
}

/// Variant of [`validate_generate_request`] that accepts an explicit family
/// hint. The hint takes precedence over the manifest lookup, letting the HTTP
/// server feed in the catalog-resolved family for `cv:` / `hf:` model IDs.
pub fn validate_generate_request_with_family(
    req: &GenerateRequest,
    family_hint: Option<&str>,
) -> Result<(), String> {
    let family = resolved_family(&req.model, family_hint);

    if req.prompt.trim().is_empty() && prompt_required_for(req, family_hint) {
        return Err("prompt must not be empty".to_string());
    }
    // Resolve the composition from the request itself. A model that ships the
    // spatial upsampler renders stage 1 at half size and refines it over
    // tiles, which is the only way an axis past the trained RoPE span is in
    // distribution; anything else keeps the single-pass ceiling.
    let composition = if family == Some("ltx2") {
        ltx2_spatial_composition_for_request(req)
    } else {
        Ltx2SpatialComposition::SinglePass
    };
    validate_generation_dimensions_composed(req.width, req.height, family, composition)?;
    if composition == Ltx2SpatialComposition::TiledTwoStage {
        // The composed ceiling above is the x2 rung's. A request that names a
        // different rung reaches a different stage-1 shape, and only stage 1's
        // own span decides whether it is in distribution.
        validate_ltx2_stage1_span(req.width, req.height, req.spatial_upscale)?;
    }
    if req.steps == 0 {
        return Err("steps must be >= 1".to_string());
    }
    if req.steps > 100 {
        return Err(format!("steps ({}) must be <= 100", req.steps));
    }
    if req.batch_size == 0 {
        return Err("batch_size must be >= 1".to_string());
    }
    // The shared inference/planning contract intentionally has no generic
    // upper limit. Live atomic HTTP delivery has a separate server-advertised
    // materialization bound because its durable manifest and response are
    // still O(batch_size).
    if req.guidance < 0.0 {
        return Err(format!("guidance ({}) must be >= 0.0", req.guidance));
    }
    if req.guidance > 100.0 {
        return Err(format!("guidance ({}) must be <= 100.0", req.guidance));
    }
    if req.prompt.len() > 77_000 {
        return Err(format!(
            "prompt length ({} bytes) exceeds the 77,000-byte limit",
            req.prompt.len()
        ));
    }
    if let Some(ref neg) = req.negative_prompt {
        if neg.len() > 77_000 {
            return Err(format!(
                "negative_prompt length ({} bytes) exceeds the 77,000-byte limit",
                neg.len()
            ));
        }
    }
    let flux2_dev = is_flux2_dev_model(&req.model);
    if family == Some("qwen-image-edit") {
        if req.edit_images.as_ref().is_none_or(Vec::is_empty) {
            return Err(
                "Qwen Image Edit needs at least one image. Add a Target image and try again."
                    .to_string(),
            );
        }
        if req.batch_size != 1 {
            return Err("qwen-image-edit only supports batch_size = 1".to_string());
        }
        if req.source_image.is_some() {
            return Err("qwen-image-edit uses edit_images instead of source_image".to_string());
        }
        if req.mask_image.is_some() {
            return Err("qwen-image-edit does not support mask_image".to_string());
        }
        if req.control_image.is_some() || req.control_model.is_some() {
            return Err("qwen-image-edit does not support ControlNet inputs".to_string());
        }
        if let Some(ref images) = req.edit_images {
            for image in images {
                if !is_valid_image_format(image) {
                    return Err("edit_images must contain only PNG or JPEG images".to_string());
                }
            }
        }
    } else if flux2_dev {
        if req.batch_size != 1
            && req
                .edit_images
                .as_ref()
                .is_some_and(|images| !images.is_empty())
        {
            return Err("flux2-dev reference editing only supports batch_size = 1".to_string());
        }
        if req.source_image.is_some() {
            return Err("flux2-dev uses edit_images instead of source_image".to_string());
        }
        if req.mask_image.is_some() {
            return Err("flux2-dev does not support mask_image".to_string());
        }
        if req.control_image.is_some() || req.control_model.is_some() {
            return Err("flux2-dev does not support ControlNet inputs".to_string());
        }
        if req.lora.is_some() || req.loras.as_ref().is_some_and(|loras| !loras.is_empty()) {
            return Err("flux2-dev does not support LoRA".to_string());
        }
        if let Some(images) = &req.edit_images {
            if images.len() > FLUX2_DEV_MAX_REFERENCE_IMAGES {
                return Err(format!(
                    "flux2-dev supports at most {FLUX2_DEV_MAX_REFERENCE_IMAGES} ordered reference images"
                ));
            }
            if images.iter().any(|image| !is_valid_image_format(image)) {
                return Err("edit_images must contain only PNG or JPEG images".to_string());
            }
        }
    } else if req.edit_images.is_some() {
        return Err(
            "edit_images are only supported for qwen-image-edit and flux2-dev models".to_string(),
        );
    }
    // img2img validation
    if let Some(ref img) = req.source_image {
        if req.strength < 0.0 || req.strength > 1.0 {
            return Err(format!(
                "strength ({}) must be in range [0.0, 1.0] when source_image is provided",
                req.strength
            ));
        }
        if !is_valid_image_format(img) {
            return Err("source_image must be a PNG or JPEG image".to_string());
        }
    }
    // ControlNet validation
    if let Some(ref ctrl) = req.control_image {
        require_controlnet_capable_family(family)?;
        if req.control_model.is_none() {
            return Err("control_image requires control_model to also be provided".to_string());
        }
        if !is_valid_image_format(ctrl) {
            return Err("control_image must be a PNG or JPEG image".to_string());
        }
        if req.control_scale < 0.0 {
            return Err(format!(
                "control_scale ({}) must be >= 0.0",
                req.control_scale
            ));
        }
    }
    if req.control_model.is_some() && req.control_image.is_none() {
        require_controlnet_capable_family(family)?;
        return Err("control_model requires control_image to also be provided".to_string());
    }
    // Inpainting validation
    if let Some(ref mask) = req.mask_image {
        if req.source_image.is_none() {
            return Err("mask_image requires source_image to also be provided".to_string());
        }
        if !is_valid_image_format(mask) {
            return Err("mask_image must be a PNG or JPEG image".to_string());
        }
    }
    // LoRA validation (format checks only — path existence is checked at the
    // inference layer, since in remote mode the path refers to the server filesystem).
    if let Some(ref lora) = req.lora {
        require_lora_capable_family(family)?;
        validate_lora_weight(lora, "lora")?;
    }
    if let Some(ref loras) = req.loras {
        if loras.is_empty() {
            return Err("loras must not be empty when provided".to_string());
        }
        require_lora_capable_family(family)?;
        for lora in loras {
            validate_lora_weight(lora, "loras")?;
        }
    }
    if let Some(fps) = req.fps {
        if fps == 0 {
            return Err("fps must be >= 1".to_string());
        }
        if fps > 120 {
            return Err(format!("fps ({fps}) must be <= 120"));
        }
    }
    // Video frame validation
    if let Some(frames) = req.frames {
        if frames == 0 {
            return Err("frames must be >= 1".to_string());
        }
        if let Some(step) = family.and_then(frame_step_for_family) {
            if frames > 1 && (frames - 1) % step != 0 {
                return Err(format!(
                    "frames ({frames}) must be {step}n+1 for current LTX-Video / LTX-2 models (e.g. 9, 17, 25, 33, 41, 49, …)"
                ));
            }
        }
        // LTX-2's ceiling is a duration (see `LTX2_MAX_RUNTIME_SECONDS`), so it
        // is derived per request from fps instead of the flat global ceiling.
        if matches!(family, Some("ltx2")) {
            let fps = req.fps.unwrap_or(LTX2_DEFAULT_FPS).max(1);
            // `derive_stage1_render_shape` halves BOTH the frame count and the
            // fps for `--temporal-upscale x2`, so stage 1 renders the same
            // runtime at half the frame rate. Mirror that: temporal upscaling
            // buys temporal resolution, never extra duration.
            let (stage1_frames, stage1_fps) = match req.temporal_upscale {
                Some(crate::Ltx2TemporalUpscale::X2) => {
                    (frames.saturating_sub(1) / 2 + 1, (fps / 2).max(1))
                }
                None => (frames, fps),
            };
            let stage1_cap = ltx2_max_frames_at_fps(stage1_fps);
            if stage1_frames > stage1_cap {
                // Quote a frame count the user can actually submit. The raw
                // duration ceiling is off the 8n+1 grid, so naming it sends
                // them straight into a second rejection.
                let delivered_cap = match req.temporal_upscale {
                    Some(crate::Ltx2TemporalUpscale::X2) => (stage1_cap - 1) * 2 + 1,
                    None => stage1_cap,
                };
                let delivered_cap = if delivered_cap > 1 {
                    delivered_cap - ((delivered_cap - 1) % 8)
                } else {
                    delivered_cap
                };
                return Err(format!(
                    "frames ({frames}) exceeds the LTX-2 / LTX-2.3 temporal RoPE budget of \
                     {LTX2_MAX_RUNTIME_SECONDS}s: at {fps} fps the ceiling is {delivered_cap} frames. \
                     Raise --fps, lower --frames, or render the shot as a multi-clip sequence"
                ));
            }
        } else if frames > MAX_FRAMES_GLOBAL {
            return Err(format!("frames ({frames}) must be <= {MAX_FRAMES_GLOBAL}"));
        }
    }
    if let Some(keyframes) = &req.keyframes {
        validate_keyframes(keyframes, req.frames, family)?;
    }
    if let Some(audio) = &req.audio_file {
        require_ltx2_family(family, "audio_file")?;
        if req.audio_file_path.is_some() {
            return Err("audio_file_path cannot be combined with audio_file".to_string());
        }
        if audio.is_empty() {
            return Err("audio_file must not be empty".to_string());
        }
        validate_inline_media_size(audio, "audio_file", MAX_INLINE_AUDIO_BYTES)?;
    }
    if let Some(path) = &req.audio_file_path {
        require_ltx2_family(family, "audio_file_path")?;
        if path.trim().is_empty() {
            return Err("audio_file_path must not be empty".to_string());
        }
    }
    if let Some(video) = &req.source_video {
        require_ltx2_family(family, "source_video")?;
        if req.source_video_path.is_some() {
            return Err("source_video_path cannot be combined with source_video".to_string());
        }
        if video.is_empty() {
            return Err("source_video must not be empty".to_string());
        }
        validate_inline_media_size(video, "source_video", MAX_INLINE_SOURCE_VIDEO_BYTES)?;
    }
    if let Some(path) = &req.source_video_path {
        require_ltx2_family(family, "source_video_path")?;
        if path.trim().is_empty() {
            return Err("source_video_path must not be empty".to_string());
        }
    }
    validate_extend(req, family)?;
    // Only enforce the LTX-2 family gate when audio is actually requested
    // (`Some(true)`). The web form serializes its tri-state checkbox as
    // `Some(false)` when the user has explicitly turned audio off — which
    // must NOT trip a family error for video-only families, since the user
    // didn't ask for audio at all.
    if req.enable_audio == Some(true) {
        require_ltx2_family(family, "enable_audio")?;
    }
    if req.retake_range.is_some() {
        require_ltx2_family(family, "retake_range")?;
    }
    if req.spatial_upscale.is_some() {
        require_ltx2_family(family, "spatial_upscale")?;
    }
    if req.temporal_upscale.is_some() {
        require_ltx2_family(family, "temporal_upscale")?;
    }
    if req.pipeline.is_some() {
        require_ltx2_family(family, "pipeline")?;
    }
    if let Some(overrides) = &req.guidance_overrides {
        require_ltx2_family(family, "guidance_overrides")?;
        validate_guidance_overrides(overrides)?;
        // Cross-modal guidance needs both modalities resident. An audio-only
        // run has no video branch for `modality_scale` to act on, so a
        // non-1.0 value cannot be honoured — reject it instead of accepting
        // a number that would silently do nothing.
        if req.pipeline.is_some_and(Ltx2PipelineMode::is_audio_only) {
            if let Some(modality_scale) = overrides.modality_scale {
                if (modality_scale - 1.0).abs() > f64::EPSILON {
                    return Err(
                        "guidance_overrides.modality_scale must be 1.0 for pipeline=t2a: \
                         audio-only generation has no video modality to guide against"
                            .to_string(),
                    );
                }
            }
        }
    }
    if let Some(dir) = req.hdr_exr_dir.as_deref() {
        require_ltx2_family(family, "hdr_exr_dir")?;
        if dir.trim().is_empty() {
            return Err("hdr_exr_dir must not be empty".to_string());
        }
        // Today this is also unreachable transitively (hdr needs the ic-lora
        // control, which needs source_video, which extend forbids), but the
        // engine's extend path re-renders through the chain-stage machinery
        // where a per-clip EXR sequence would misalign with the stitched
        // timeline — say it directly instead of leaning on that implication
        // chain staying intact.
        if req.extend_video.is_some() || req.extend_video_path.is_some() {
            return Err("hdr_exr_dir cannot be combined with extend_video".to_string());
        }
        // The adapter is what makes the render HDR. Without it the decode
        // would apply a LogC3 inverse to an ordinary SDR signal and write a
        // wrongly-graded EXR that looks deliberate.
        // Through the shared normalizer, not a raw compare: every other
        // consumer accepts `HDR` and `hdr_`, so a bare `trim()` here would
        // reject spellings the rest of the stack resolves fine.
        if req
            .ic_lora_control
            .as_deref()
            .map(crate::ltx2_control::normalize_control_id)
            .as_deref()
            != Some("hdr")
        {
            return Err(
                "hdr_exr_dir requires ic_lora_control=hdr — EXR output is only meaningful for \
                 the HDR adapter's LogC3 signal"
                    .to_string(),
            );
        }
    } else if req.hdr_exr_full_float {
        return Err("hdr_exr_full_float requires hdr_exr_dir".to_string());
    }

    if let Some(control) = req.ic_lora_control.as_deref() {
        require_ltx2_family(family, "ic_lora_control")?;
        if control.trim().is_empty() {
            return Err("ic_lora_control must not be empty".to_string());
        }
        // Most control adapters drive the generic in-context pipeline. The
        // lip-dub adapter has its own pipeline (frozen stage-2 audio, an
        // appended audio reference, the LoRA on both stages), so it is the one
        // control whose required pipeline is not `ic-lora`.
        let required_pipeline = crate::ltx2_control::pipeline_for_control_id(control);
        if req.pipeline != Some(required_pipeline) {
            return Err(format!(
                "ic_lora_control '{}' requires pipeline={required_pipeline}",
                crate::ltx2_control::normalize_control_id(control)
            ));
        }
        if req.source_video.is_none() && req.source_video_path.is_none() {
            return Err("ic_lora_control requires source_video or source_video_path".to_string());
        }
        let user_loras = usize::from(req.lora.is_some()) + req.loras.as_ref().map_or(0, Vec::len);
        if user_loras + 1 > 4 {
            return Err(
                "ic_lora_control plus custom LoRAs exceeds the four-LoRA stack limit".to_string(),
            );
        }
    }

    if family == Some("ltx2") {
        let audio_only = req.pipeline.is_some_and(Ltx2PipelineMode::is_audio_only);
        match (req.resolved_output_format(), audio_only) {
            (OutputFormat::Wav, true) => {}
            (OutputFormat::Wav, false) => {
                return Err("wav output requires pipeline=t2a".to_string());
            }
            (_, true) => {
                return Err("pipeline=t2a renders audio only; set output_format=wav".to_string());
            }
            (
                OutputFormat::Gif | OutputFormat::Apng | OutputFormat::Webp | OutputFormat::Mp4,
                false,
            ) => {}
            (_, false) => return Err("LTX-2 outputs must use mp4, gif, apng, or webp".to_string()),
        }

        if req.enable_audio == Some(true)
            && !audio_only
            && req.resolved_output_format() != OutputFormat::Mp4
        {
            return Err("audio-enabled LTX-2 outputs must use mp4 format".to_string());
        }
        if req.enable_audio == Some(false) && audio_only {
            return Err("pipeline=t2a cannot be combined with enable_audio=false".to_string());
        }

        if req.retake_range.is_some()
            && req.source_video.is_none()
            && req.source_video_path.is_none()
        {
            return Err(
                "retake_range requires source_video or source_video_path to also be provided"
                    .to_string(),
            );
        }

        if let Some(range) = &req.retake_range {
            if !(range.start_seconds.is_finite() && range.end_seconds.is_finite()) {
                return Err("retake_range values must be finite numbers".to_string());
            }
            if range.start_seconds < 0.0 {
                return Err("retake_range start_seconds must be >= 0.0".to_string());
            }
            if range.end_seconds <= range.start_seconds {
                return Err(
                    "retake_range end_seconds must be greater than start_seconds".to_string(),
                );
            }
        }

        if let Some(pipeline) = req.pipeline {
            match pipeline {
                Ltx2PipelineMode::A2Vid => {
                    if req.audio_file.is_none() && req.audio_file_path.is_none() {
                        return Err(
                            "pipeline=a2-vid requires audio_file or audio_file_path".to_string()
                        );
                    }
                }
                Ltx2PipelineMode::Retake => {
                    if req.source_video.is_none() && req.source_video_path.is_none() {
                        return Err("pipeline=retake requires source_video or source_video_path"
                            .to_string());
                    }
                    if req.retake_range.is_none() {
                        return Err("pipeline=retake requires retake_range".to_string());
                    }
                }
                Ltx2PipelineMode::Keyframe => {
                    let keyframe_count = req.keyframes.as_ref().map_or(0, Vec::len);
                    if keyframe_count < 2 {
                        return Err("pipeline=keyframe requires at least 2 keyframes".to_string());
                    }
                }
                Ltx2PipelineMode::IcLora => {
                    if req.source_video.is_none() && req.source_video_path.is_none() {
                        return Err(
                            "pipeline=ic-lora requires source_video or source_video_path"
                                .to_string(),
                        );
                    }
                    if req.ic_lora_control.is_none()
                        && req.lora.is_none()
                        && req.loras.as_ref().is_none_or(Vec::is_empty)
                    {
                        return Err("pipeline=ic-lora requires at least one LoRA".to_string());
                    }
                }
                Ltx2PipelineMode::LipDub => {
                    if req.source_video.is_none() && req.source_video_path.is_none() {
                        return Err(
                            "pipeline=lip-dub requires source_video or source_video_path (the \
                             clip being re-voiced)"
                                .to_string(),
                        );
                    }
                    if req.ic_lora_control.is_none()
                        && req.lora.is_none()
                        && req.loras.as_ref().is_none_or(Vec::is_empty)
                    {
                        return Err("pipeline=lip-dub requires the lip-dub IC-LoRA; pass \
                             ic_lora_control=lipdub"
                            .to_string());
                    }
                    // Upstream asserts a two-stage resolution before doing any
                    // work (`assert_resolution(..., is_two_stage=True)` in
                    // `utils/helpers.py:321-332`). Lip dub is always two-stage
                    // — stage 1 renders at half size — so an odd multiple of 32
                    // would leave stage 1 off the latent grid.
                    if !req.width.is_multiple_of(LTX2_TWO_STAGE_ALIGNMENT)
                        || !req.height.is_multiple_of(LTX2_TWO_STAGE_ALIGNMENT)
                    {
                        return Err(format!(
                            "pipeline=lip-dub renders in two stages, so width and height must be \
                             multiples of {LTX2_TWO_STAGE_ALIGNMENT}; got {}x{}",
                            req.width, req.height
                        ));
                    }
                    if req.retake_range.is_some() {
                        return Err(
                            "pipeline=lip-dub cannot be combined with retake_range".to_string()
                        );
                    }
                    if req
                        .keyframes
                        .as_ref()
                        .is_some_and(|items| !items.is_empty())
                    {
                        return Err(
                            "pipeline=lip-dub cannot be combined with keyframes".to_string()
                        );
                    }
                    // Both would change the output shape out from under the
                    // reference clip, whose resolution and length the dub has
                    // to match. Upstream's pipeline composes with neither.
                    if req.spatial_upscale.is_some() || req.temporal_upscale.is_some() {
                        return Err(
                            "pipeline=lip-dub cannot be combined with spatial_upscale or \
                             temporal_upscale; the render must match the reference video"
                                .to_string(),
                        );
                    }
                }
                Ltx2PipelineMode::T2a => {
                    // Text-to-audio has no video modality at all: there is no
                    // frame to condition on and no cross-modal path for a
                    // reference to reach. Reject conditioning outright rather
                    // than silently ignoring inputs the caller paid to upload.
                    for (present, field) in [
                        (req.source_image.is_some(), "source_image"),
                        (req.source_video.is_some(), "source_video"),
                        (req.source_video_path.is_some(), "source_video_path"),
                        (req.audio_file.is_some(), "audio_file"),
                        (req.audio_file_path.is_some(), "audio_file_path"),
                        (req.is_extend(), "extend_video"),
                        (
                            req.keyframes.as_ref().is_some_and(|k| !k.is_empty()),
                            "keyframes",
                        ),
                        (req.retake_range.is_some(), "retake_range"),
                        (req.spatial_upscale.is_some(), "spatial_upscale"),
                        (req.temporal_upscale.is_some(), "temporal_upscale"),
                        (req.upscale_model.is_some(), "upscale_model"),
                    ] {
                        if present {
                            return Err(format!(
                                "pipeline=t2a generates audio only and cannot be combined with {field}"
                            ));
                        }
                    }
                }
                Ltx2PipelineMode::OneStage
                | Ltx2PipelineMode::TwoStage
                | Ltx2PipelineMode::TwoStageHq
                | Ltx2PipelineMode::Distilled => {}
            }
        }
    }

    Ok(())
}

/// Whether a stable name or catalog ID denotes the first-party FLUX.2 Dev
/// architecture rather than a Klein checkpoint.
pub fn is_flux2_dev_model(model: &str) -> bool {
    let model = model.to_ascii_lowercase();
    model.contains("flux2-dev") || model.contains("flux.2-dev")
}

/// Validate an upscale request. Returns `Ok(())` if valid, or an error message.
pub fn validate_upscale_request(req: &UpscaleRequest) -> Result<(), String> {
    if req.model.trim().is_empty() {
        return Err("upscale model must not be empty".to_string());
    }
    if req.image.is_empty() {
        return Err("upscale image must not be empty".to_string());
    }
    if !is_valid_image_format(&req.image) {
        return Err("upscale image must be a PNG or JPEG image".to_string());
    }
    if let Some(tile_size) = req.tile_size {
        if tile_size != 0 && tile_size < 64 {
            return Err(format!(
                "tile_size ({tile_size}) must be 0 (disabled) or >= 64"
            ));
        }
    }
    Ok(())
}

// ── Dimension recommendations ───────────────────────────────────────────────

/// Recommended (width, height) pairs for SD1.5 models (native 512x512).
const SD15_DIMS: &[(u32, u32)] = &[(512, 512), (512, 768), (768, 512), (384, 512), (512, 384)];

/// Official SDXL training buckets from Stability AI (native 1024x1024).
const SDXL_DIMS: &[(u32, u32)] = &[
    (1024, 1024),
    (1152, 896),
    (896, 1152),
    (1216, 832),
    (832, 1216),
    (1344, 768),
    (768, 1344),
    (1536, 640),
    (640, 1536),
];

/// Recommended dimensions for SD3.5 models (native 1024x1024).
const SD3_DIMS: &[(u32, u32)] = &[
    (1024, 1024),
    (1152, 896),
    (896, 1152),
    (1216, 832),
    (832, 1216),
    (1344, 768),
    (768, 1344),
];

/// Recommended dimensions for FLUX models (native 1024x1024).
const FLUX_DIMS: &[(u32, u32)] = &[
    (1024, 1024),
    (1024, 768),
    (768, 1024),
    (1024, 576),
    (576, 1024),
    (768, 768),
];

/// Recommended dimensions for Z-Image models (native 1024x1024).
const ZIMAGE_DIMS: &[(u32, u32)] = &[(1024, 1024), (1024, 768), (768, 1024)];

/// Recommended dimensions for Qwen-Image models (native 1328x1328, ~1.76MP max).
/// Supports dynamic resolution — any dims divisible by 16 within the megapixel budget work,
/// but these are the standard aspect-ratio buckets.
const QWEN_IMAGE_DIMS: &[(u32, u32)] = &[
    (1328, 1328), // 1:1 (native)
    (1024, 1024), // 1:1
    (1152, 896),  // 9:7
    (896, 1152),  // 7:9
    (1216, 832),  // 19:13
    (832, 1216),  // 13:19
    (1344, 768),  // 7:4
    (768, 1344),  // 4:7
    (1664, 928),  // ~16:9
    (928, 1664),  // ~9:16
    (768, 768),   // 1:1 (small)
    (512, 512),   // 1:1 (small, fast)
];

/// Recommended dimensions for Wuerstchen models (native 1024x1024).
const WUERSTCHEN_DIMS: &[(u32, u32)] = &[(1024, 1024)];

/// Recommended dimensions for LTX Video models (native 768x512).
/// LTX Video requires dimensions divisible by 32 (patchification).
const LTX_VIDEO_DIMS: &[(u32, u32)] = &[
    (704, 480),  // 22:15 (compact sample bucket)
    (768, 512),  // 3:2 (native)
    (512, 512),  // 1:1
    (1024, 576), // 16:9
    (1216, 704), // 16:9 (LTX-2 19B/22B default)
    (576, 1024), // 9:16
    (768, 768),  // 1:1
    (512, 768),  // 2:3
];

/// LTX-2 / LTX-2.3. Adds upstream's shipped 1080p HQ pair and the 9:16
/// transpose of the 19B/22B default. Every entry is 32-aligned, inside
/// `LTX2_MAX_PIXELS`, and has both axes within `LTX2_MAX_AXIS_PIXELS`.
const LTX2_DIMS: &[(u32, u32)] = &[
    (704, 480),   // 22:15 (compact sample bucket)
    (768, 512),   // 3:2 (native)
    (512, 512),   // 1:1
    (1024, 576),  // 16:9
    (1216, 704),  // 16:9 (LTX-2 19B/22B default)
    (704, 1216),  // 9:16 portrait transpose of the default
    (576, 1024),  // 9:16
    (768, 768),   // 1:1
    (512, 768),   // 2:3
    (1920, 1088), // 16:9 1080p — upstream's LTX_2_3_HQ_PARAMS
    (1088, 1920), // 9:16 1080p
];

/// Return the list of recommended (width, height) pairs for a model family.
///
/// Returns an empty slice for unknown families, utility models (e.g. `qwen3-expand`),
/// and conditioning models (e.g. ControlNet).
pub fn recommended_dimensions(family: &str) -> &'static [(u32, u32)] {
    match family {
        "sd15" => SD15_DIMS,
        "sdxl" => SDXL_DIMS,
        "sd3" => SD3_DIMS,
        "flux" => FLUX_DIMS,
        "flux2" => FLUX_DIMS,
        "z-image" => ZIMAGE_DIMS,
        "qwen-image" => QWEN_IMAGE_DIMS,
        "qwen-image-edit" => QWEN_IMAGE_DIMS,
        "wuerstchen" => WUERSTCHEN_DIMS,
        "ltx-video" => LTX_VIDEO_DIMS,
        "ltx2" => LTX2_DIMS,
        _ => &[],
    }
}

/// Composition-aware counterpart to [`recommended_dimensions`].
///
/// `/api/models` advertises this per model so a checkpoint that cannot compose
/// never offers a rung it cannot render. Returns an owned list because the
/// composed ladder is the base list plus the composed rungs.
pub fn recommended_dimensions_composed(
    family: &str,
    composition: Ltx2SpatialComposition,
) -> Vec<(u32, u32)> {
    let base = recommended_dimensions(family);
    if family != "ltx2" || composition != Ltx2SpatialComposition::TiledTwoStage {
        return base.to_vec();
    }
    // Derived from the ladder rather than restated beside it. A rung that
    // needs tiling is exactly a rung a single-pass checkpoint cannot render,
    // which is exactly the set to withhold from one.
    let mut out = base.to_vec();
    for rung in LTX2_OUTPUT_RUNGS
        .iter()
        .filter(|rung| rung.requires_tiled_stage2())
    {
        out.push((rung.width, rung.height));
        out.push((rung.height, rung.width));
    }
    out
}

/// Check if the requested dimensions match any recommended resolution for the model family.
///
/// Returns `None` if the dimensions are recommended or the family has no recommendation list.
/// Returns `Some(warning_message)` with suggested alternatives otherwise.
pub fn dimension_warning(width: u32, height: u32, family: &str) -> Option<String> {
    dimension_warning_composed(width, height, family, Ltx2SpatialComposition::SinglePass)
}

/// Composition-aware counterpart to [`dimension_warning`].
///
/// A composing LTX-2 checkpoint has more buckets than its family fallback, so
/// the single-pass list would call 3840x2176 unrecommended on the very
/// checkpoint the rung was added for.
pub fn dimension_warning_composed(
    width: u32,
    height: u32,
    family: &str,
    composition: Ltx2SpatialComposition,
) -> Option<String> {
    let dims = recommended_dimensions_composed(family, composition);
    if dims.is_empty() {
        return None;
    }
    if dims.contains(&(width, height)) {
        return None;
    }
    // Build a compact list of suggested alternatives (show up to 4)
    let suggestions: Vec<String> = dims
        .iter()
        .take(4)
        .map(|(w, h)| format!("{w}x{h}"))
        .collect();
    let more = if dims.len() > 4 {
        format!(", ... ({} total)", dims.len())
    } else {
        String::new()
    };
    Some(format!(
        "{width}x{height} is not a recommended resolution for {family} models. \
         Suggested: {}{}",
        suggestions.join(", "),
        more,
    ))
}

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

    /// Upstream's own shipped LTX-2.3 HQ default is 1920x1088
    /// (`LTX_2_3_HQ_PARAMS`: stage 1 at 960x544, refined x2). That is
    /// 2,088,960 px, so the flat 1.8 MP ceiling made mold unable to express
    /// the reference implementation's own top-end preset.
    #[test]
    fn ltx2_admits_upstreams_shipped_1080p_shape() {
        assert!(validate_generation_dimensions(1920, 1088, Some("ltx2")).is_ok());
        assert!(validate_generation_dimensions(1088, 1920, Some("ltx2")).is_ok());
    }

    #[test]
    fn non_ltx2_families_keep_the_default_ceiling() {
        for family in [Some("flux"), Some("ltx-video"), Some("sdxl"), None] {
            let err = validate_generation_dimensions(1920, 1088, family)
                .expect_err("only LTX-2 gets the raised ceiling");
            assert!(
                err.contains("1.8MP"),
                "{family:?} must still report the default limit, got: {err}"
            );
        }
    }

    /// Independent of the pixel budget. The checkpoints ship
    /// `positional_embedding_max_pos = [20, 2048, 2048]` and normalize pixel
    /// positions by it, so an axis past 2048 is out of distribution even when
    /// the frame is small: 3200x512 is only 1.64 MP but its width position is
    /// 1.5625, far outside the trained [-1, 1].
    #[test]
    fn ltx2_rejects_an_axis_beyond_the_rope_span() {
        let err = validate_generation_dimensions(3200, 512, Some("ltx2"))
            .expect_err("an over-wide axis must be rejected on its own merits");
        assert!(
            err.contains("2048"),
            "the error must name the axis limit, got: {err}"
        );
        // The transpose is equally out of distribution.
        assert!(validate_generation_dimensions(512, 3200, Some("ltx2")).is_err());
        // Exactly at the span is in distribution, when the pixel budget also
        // allows it: 2048x992 is 2.03 MP, 2048x1024 would be 2.10 MP and is
        // rejected on pixels instead. The two limits are independent.
        assert!(validate_generation_dimensions(2048, 992, Some("ltx2")).is_ok());
        assert!(validate_generation_dimensions(2048, 1024, Some("ltx2"))
            .expect_err("over the pixel budget")
            .contains("megapixels"));
    }

    #[test]
    fn ltx2_recommended_dimensions_are_grid_aligned_and_inside_the_family_ceiling() {
        for &(width, height) in recommended_dimensions("ltx2") {
            assert!(
                validate_generation_dimensions(width, height, Some("ltx2")).is_ok(),
                "advertised preset {width}x{height} must be admissible"
            );
        }
    }

    /// The whole point of gating the raised ceiling on the composition is that
    /// nothing renderable today changes. Every shape the single-pass validator
    /// used to accept or reject must still get the same answer, at exactly the
    /// same boundary — a ceiling that leaked into the default path would admit
    /// out-of-distribution renders on one-stage checkpoints.
    #[test]
    fn single_pass_admission_is_byte_for_byte_unchanged() {
        // Accepted before, accepted now.
        for &(width, height) in &[
            (768u32, 512u32),
            (1216, 704),
            (1920, 1088),
            (1088, 1920),
            (2048, 992),
        ] {
            assert!(
                validate_generation_dimensions(width, height, Some("ltx2")).is_ok(),
                "{width}x{height} was admissible before the composed ceiling"
            );
        }
        // Rejected before, rejected now — on the same limit each time.
        assert!(validate_generation_dimensions(2048, 1024, Some("ltx2"))
            .expect_err("2.10 MP is over the single-pass pixel budget")
            .contains("megapixels"));
        assert!(validate_generation_dimensions(3200, 512, Some("ltx2"))
            .expect_err("a 3200px axis is past the trained span")
            .contains("2048"));
        assert!(validate_generation_dimensions(2080, 512, Some("ltx2")).is_err());
    }

    /// The threshold is the trained span itself, not a rounded-down neighbour.
    /// One latent cell either side of 2048 is the difference between the shape
    /// upstream ships and a shape no checkpoint has seen.
    #[test]
    fn the_axis_threshold_fires_exactly_at_the_trained_span() {
        // 2048 is the last in-distribution axis for a single pass; 2080 is the
        // next 32-aligned value and is the first rejected one.
        assert!(validate_generation_dimensions(2048, 512, Some("ltx2")).is_ok());
        assert!(validate_generation_dimensions(2080, 512, Some("ltx2")).is_err());

        // A composed render admits both, and its own ceiling behaves the same
        // way one cell either side of 4096.
        let composed = Ltx2SpatialComposition::TiledTwoStage;
        assert!(validate_generation_dimensions_composed(2080, 512, Some("ltx2"), composed).is_ok());
        assert!(
            validate_generation_dimensions_composed(4096, 2176, Some("ltx2"), composed).is_ok()
        );
        assert!(
            validate_generation_dimensions_composed(4128, 2176, Some("ltx2"), composed).is_err(),
            "past 4096 the halved stage-1 shape is itself out of distribution"
        );
    }

    /// The composed ceiling is `2 * trained span` for a reason that has to
    /// stay true: stage 1 renders the target halved, so 4096 is the widest
    /// target whose stage 1 still lands inside the span.
    #[test]
    fn the_composed_ceiling_is_where_stage_one_leaves_the_trained_span() {
        assert_eq!(LTX2_COMPOSED_MAX_AXIS_PIXELS, 2 * LTX2_MAX_AXIS_PIXELS);
        let widest = Ltx2OutputRung {
            id: "test",
            label: "test",
            width: LTX2_COMPOSED_MAX_AXIS_PIXELS,
            height: 2_176,
        };
        assert_eq!(widest.stage1_shape().0, LTX2_MAX_AXIS_PIXELS);

        // One rung wider and stage 1 is already out of distribution, which no
        // amount of stage-2 tiling repairs.
        let too_wide = Ltx2OutputRung {
            id: "test",
            label: "test",
            width: LTX2_COMPOSED_MAX_AXIS_PIXELS + 64,
            height: 2_176,
        };
        assert!(too_wide.stage1_shape().0 > LTX2_MAX_AXIS_PIXELS);
    }

    /// A checkpoint reaches the composed ceiling only if it can actually
    /// compose: it ships the spatial upsampler *and* runs a refining pipeline.
    #[test]
    fn the_composed_ceiling_requires_a_checkpoint_that_can_compose() {
        // Manifest LTX-2 checkpoints all ship the upsampler.
        assert_eq!(
            ltx2_spatial_composition("ltx-2-19b-distilled:fp8", None),
            Ltx2SpatialComposition::TiledTwoStage
        );
        // A single-file catalog checkpoint has no manifest and no upsampler.
        assert_eq!(
            ltx2_spatial_composition("cv:3143864", None),
            Ltx2SpatialComposition::SinglePass
        );
        // An explicit non-refining pipeline denoises the requested shape once,
        // however capable the checkpoint is.
        for mode in [
            Ltx2PipelineMode::OneStage,
            Ltx2PipelineMode::Retake,
            Ltx2PipelineMode::LipDub,
        ] {
            assert_eq!(
                ltx2_spatial_composition("ltx-2-19b-distilled:fp8", Some(mode)),
                Ltx2SpatialComposition::SinglePass,
                "{mode} denoises once and cannot hold an oversized axis"
            );
        }
        for mode in Ltx2PipelineMode::ALL
            .iter()
            .filter(|m| m.refines_spatially())
        {
            assert_eq!(
                ltx2_spatial_composition("ltx-2-19b-distilled:fp8", Some(*mode)),
                Ltx2SpatialComposition::TiledTwoStage,
                "{mode} refines a halved stage 1 and can hold one"
            );
        }
    }

    /// End-to-end through the request validator: the same 4K request is
    /// admitted on a composing checkpoint and refused on a one-stage one, and
    /// the refusal says what would make it work.
    #[test]
    fn a_4k_request_is_admitted_only_where_the_composition_exists() {
        let mut req = valid_req();
        req.model = "ltx-2-19b-distilled:fp8".to_string();
        req.width = 3_840;
        req.height = 2_176;
        req.frames = Some(25);
        req.fps = Some(24);
        req.output_format = Some(OutputFormat::Mp4);
        validate_generate_request_with_family(&req, Some("ltx2"))
            .expect("a composing checkpoint reaches 4K UHD");

        req.model = "cv:3143864".to_string();
        let err = validate_generate_request_with_family(&req, Some("ltx2"))
            .expect_err("a one-stage checkpoint cannot");
        assert!(
            err.contains("3840") && err.contains("spatial upsampler"),
            "the refusal must name the axis and the way out, got: {err}"
        );

        // Explicitly asking for a one-stage render is refused on the same
        // grounds, even on the composing checkpoint.
        req.model = "ltx-2-19b-distilled:fp8".to_string();
        req.pipeline = Some(Ltx2PipelineMode::OneStage);
        assert!(validate_generate_request_with_family(&req, Some("ltx2")).is_err());
    }

    /// Every advertised rung has to be admissible under the composition that
    /// reaches it — and the composed-only ones have to be refused without it,
    /// or a one-stage checkpoint would be offered a size it cannot render.
    #[test]
    fn every_composed_rung_is_admissible_exactly_under_composition() {
        let two_stage = Ltx2SpatialComposition::TiledTwoStage;
        for (width, height) in recommended_dimensions_composed("ltx2", two_stage) {
            assert!(
                validate_generation_dimensions_composed(width, height, Some("ltx2"), two_stage)
                    .is_ok(),
                "advertised composed preset {width}x{height} must be admissible"
            );
        }
        for rung in LTX2_OUTPUT_RUNGS {
            let (width, height) = (rung.width, rung.height);
            assert!(
                width.is_multiple_of(LTX2_TWO_STAGE_ALIGNMENT)
                    && height.is_multiple_of(LTX2_TWO_STAGE_ALIGNMENT),
                "{width}x{height} must survive halving onto the 32px latent grid"
            );
            if !rung.requires_tiled_stage2() {
                continue;
            }
            for shape in [(width, height), (height, width)] {
                assert!(
                    validate_generation_dimensions(shape.0, shape.1, Some("ltx2")).is_err(),
                    "{}x{} must not be offered to a single-pass checkpoint",
                    shape.0,
                    shape.1
                );
                assert!(
                    recommended_dimensions_composed("ltx2", two_stage).contains(&shape),
                    "{}x{} must be advertised to a composing checkpoint",
                    shape.0,
                    shape.1
                );
            }
        }
        // A single-pass model's advertised list is exactly the old one.
        assert_eq!(
            recommended_dimensions_composed("ltx2", Ltx2SpatialComposition::SinglePass),
            recommended_dimensions("ltx2").to_vec()
        );
    }

    /// The ladder's arithmetic: each rung's stage-1 shape is the target halved
    /// onto the latent grid, and its tile counts are the fewest tiles that
    /// bring every axis back inside the trained span.
    #[test]
    fn rung_composition_arithmetic_is_exact() {
        struct ExpectedRung {
            id: &'static str,
            stage1: (u32, u32),
            /// `(columns, rows)`.
            tiles: (u32, u32),
            tiled: bool,
        }
        let expected = [
            ExpectedRung {
                id: "720p",
                stage1: (640, 352),
                tiles: (1, 1),
                tiled: false,
            },
            ExpectedRung {
                id: "1080p",
                stage1: (960, 544),
                tiles: (1, 1),
                tiled: false,
            },
            ExpectedRung {
                id: "1440p",
                stage1: (1_280, 704),
                tiles: (2, 1),
                tiled: true,
            },
            ExpectedRung {
                id: "4k-uhd",
                stage1: (1_920, 1_056),
                tiles: (2, 2),
                tiled: true,
            },
        ];
        assert_eq!(LTX2_OUTPUT_RUNGS.len(), expected.len());
        for (
            rung,
            ExpectedRung {
                id,
                stage1,
                tiles,
                tiled,
            },
        ) in LTX2_OUTPUT_RUNGS.iter().zip(&expected)
        {
            let (id, stage1, tiles, tiled) = (*id, *stage1, *tiles, *tiled);
            assert_eq!(rung.id, id);
            assert_eq!(rung.stage1_shape(), stage1, "{id} stage-1 shape");
            assert_eq!(rung.stage2_tiles(), tiles, "{id} stage-2 tile counts");
            assert_eq!(rung.requires_tiled_stage2(), tiled, "{id} tiling need");
            // A rung is only meaningful if its own advertised shape is
            // admissible under the composition that reaches it.
            assert!(validate_generation_dimensions_composed(
                rung.width,
                rung.height,
                Some("ltx2"),
                Ltx2SpatialComposition::TiledTwoStage,
            )
            .is_ok());
        }
    }

    /// The composed ceiling is the **x2 rung's**. x1.5 divides by 1.5, so the
    /// same 4K output leaves stage 1 at 2560px — out of distribution, with
    /// nothing downstream to repair it, because stage 2 tiles the refinement
    /// and never stage 1.
    #[test]
    fn a_smaller_spatial_rung_lowers_the_ceiling_it_can_reach() {
        assert_eq!(
            ltx2_composed_axis_ceiling(Some(Ltx2SpatialUpscale::X2)),
            LTX2_COMPOSED_MAX_AXIS_PIXELS
        );
        assert_eq!(
            ltx2_composed_axis_ceiling(None),
            LTX2_COMPOSED_MAX_AXIS_PIXELS
        );
        assert_eq!(
            ltx2_composed_axis_ceiling(Some(Ltx2SpatialUpscale::X1_5)),
            3_072
        );

        // Every ceiling is exactly the largest target its rung can hold, and
        // one grid step past it is not.
        for upscale in [Some(Ltx2SpatialUpscale::X2), Some(Ltx2SpatialUpscale::X1_5)] {
            let ceiling = ltx2_composed_axis_ceiling(upscale);
            assert!(
                ltx2_stage1_axis_for(ceiling, upscale) <= LTX2_MAX_AXIS_PIXELS,
                "{upscale:?} must reach its own ceiling"
            );
            assert!(
                ltx2_stage1_axis_for(ceiling + LTX2_SPATIAL_LATENT_STRIDE, upscale)
                    > LTX2_MAX_AXIS_PIXELS,
                "{upscale:?} must not reach one grid step past it"
            );
        }

        // 4K on x1.5 is refused, and the refusal names the shape stage 1 would
        // have rendered rather than restating the output size.
        let err = validate_ltx2_stage1_span(3_840, 2_176, Some(Ltx2SpatialUpscale::X1_5))
            .expect_err("x1.5 cannot halve 3840 back inside the span");
        assert!(err.contains("2560") && err.contains("3072"), "got: {err}");
        // The same output on x2 is fine.
        assert!(validate_ltx2_stage1_span(3_840, 2_176, Some(Ltx2SpatialUpscale::X2)).is_ok());
        // And x1.5 is fine at its own ceiling.
        assert!(validate_ltx2_stage1_span(3_072, 1_728, Some(Ltx2SpatialUpscale::X1_5)).is_ok());
    }

    /// The whole request decides the pipeline, not just the `pipeline` field.
    /// `select_pipeline` routes a retake before it ever considers the
    /// checkpoint's upsampler, and a retake denoises once.
    #[test]
    fn an_implicit_retake_is_admitted_as_single_pass() {
        let mut req = valid_req();
        req.model = "ltx-2-19b-distilled:fp8".to_string();
        req.width = 3_840;
        req.height = 2_176;
        req.frames = Some(25);
        req.fps = Some(24);
        req.output_format = Some(OutputFormat::Mp4);
        // No explicit pipeline: the composing default admits 4K.
        assert_eq!(
            ltx2_spatial_composition_for_request(&req),
            Ltx2SpatialComposition::TiledTwoStage
        );
        validate_generate_request_with_family(&req, Some("ltx2")).expect("4K composes");

        // Adding a retake range changes what the engine will run, so it has to
        // change what admission allows — otherwise this is refused minutes
        // later by the engine backstop instead of at the request boundary.
        req.retake_range = Some(crate::TimeRange {
            start_seconds: 0.0,
            end_seconds: 0.5,
        });
        req.source_video_path = Some("/tmp/clip.mp4".to_string());
        assert_eq!(
            ltx2_spatial_composition_for_request(&req),
            Ltx2SpatialComposition::SinglePass
        );
        let err = validate_generate_request_with_family(&req, Some("ltx2"))
            .expect_err("a retake denoises once and cannot hold a 3840px axis");
        assert!(err.contains("3840"), "got: {err}");
    }

    /// The other implicit selectors all resolve to refining pipelines, so they
    /// must not narrow the ceiling.
    #[test]
    fn implicit_refining_pipelines_keep_the_composed_ceiling() {
        let mut req = valid_req();
        req.model = "ltx-2-19b-distilled:fp8".to_string();
        req.width = 3_840;
        req.height = 2_176;
        req.frames = Some(25);
        req.fps = Some(24);
        req.output_format = Some(OutputFormat::Mp4);

        let mut with_audio = req.clone();
        with_audio.audio_file_path = Some("/tmp/voice.wav".to_string());
        assert_eq!(
            ltx2_spatial_composition_for_request(&with_audio),
            Ltx2SpatialComposition::TiledTwoStage
        );

        let mut with_source = req.clone();
        with_source.source_video_path = Some("/tmp/clip.mp4".to_string());
        assert_eq!(
            ltx2_spatial_composition_for_request(&with_source),
            Ltx2SpatialComposition::TiledTwoStage
        );

        // An explicit pipeline still wins over every implicit selector.
        let mut explicit = with_source.clone();
        explicit.pipeline = Some(Ltx2PipelineMode::OneStage);
        assert_eq!(
            ltx2_spatial_composition_for_request(&explicit),
            Ltx2SpatialComposition::SinglePass
        );
    }

    /// A rung is the same rung in either orientation — the composition and its
    /// cost are identical under transposition.
    #[test]
    fn rungs_resolve_in_either_orientation() {
        assert_eq!(ltx2_output_rung(3_840, 2_112).map(|r| r.id), Some("4k-uhd"));
        assert_eq!(ltx2_output_rung(2_112, 3_840).map(|r| r.id), Some("4k-uhd"));
        assert_eq!(ltx2_output_rung(1_920, 1_088).map(|r| r.id), Some("1080p"));
        assert_eq!(ltx2_output_rung(1_234, 567), None);
    }

    /// An over-size rejection has to say what the user *can* have. The pixel
    /// ceiling alone says only what they cannot.
    #[test]
    fn an_oversize_rejection_names_the_largest_reachable_rung() {
        assert_eq!(
            largest_ltx2_rung_within(LTX2_MAX_AXIS_PIXELS).map(|rung| rung.id),
            Some("1080p"),
        );
        assert_eq!(
            largest_ltx2_rung_within(LTX2_COMPOSED_MAX_AXIS_PIXELS).map(|rung| rung.id),
            Some("4k-uhd"),
        );
        assert_eq!(largest_ltx2_rung_within(64), None);

        let err = validate_generation_dimensions(3_840, 2_112, Some("ltx2"))
            .expect_err("a single-pass render cannot reach 4K");
        assert!(err.contains("spatial upsampler"), "got: {err}");
        assert!(err.contains("1080p Full HD (1920x1088)"), "got: {err}");

        let err = validate_generation_dimensions_composed(
            4_160,
            2_176,
            Some("ltx2"),
            Ltx2SpatialComposition::TiledTwoStage,
        )
        .expect_err("past the composed ceiling");
        assert!(
            !err.contains("spatial upsampler"),
            "a composing render is already using it, got: {err}"
        );
        assert!(err.contains("4K UHD (3840x2112)"), "got: {err}");
    }

    /// The issue's named 9:16 shape.
    #[test]
    fn ltx2_offers_portrait_presets() {
        let presets = recommended_dimensions("ltx2");
        assert!(
            presets.contains(&(704, 1216)),
            "704x1216 portrait must be advertised, got: {presets:?}"
        );
        assert!(
            presets.iter().any(|(w, h)| h > w && w * h > 1_000_000),
            "a high-resolution portrait preset must be advertised, got: {presets:?}"
        );
    }

    /// The advertised cap must be requestable. A client that clamps to it and
    /// submits should not get a 422 for being off the `8n+1` grid.
    #[test]
    fn ltx2_grid_snapped_cap_is_actually_requestable() {
        for fps in [6, 12, 24, 30, 48, 60, 120] {
            let cap = ltx2_max_frames_on_grid_at_fps(fps);
            assert_eq!(
                (cap - 1) % 8,
                0,
                "the advertised cap at {fps} fps must sit on the 8n+1 grid"
            );
            assert!(cap <= ltx2_max_frames_at_fps(fps));

            let mut req = valid_req();
            req.model = "ltx-2-19b-distilled:fp8".to_string();
            req.width = 768;
            req.height = 512;
            req.output_format = Some(OutputFormat::Mp4);
            req.frames = Some(cap);
            req.fps = Some(fps);
            validate_generate_request_with_family(&req, Some("ltx2")).unwrap_or_else(|err| {
                panic!("the advertised cap {cap} at {fps} fps must validate, got: {err}")
            });
        }
        // The raw ceilings are off-grid in both directions, which is the bug.
        assert_eq!(ltx2_max_frames_at_fps(24), 484);
        assert_eq!(ltx2_max_frames_on_grid_at_fps(24), 481);
        assert_eq!(ltx2_max_frames_at_fps(48), LTX2_MAX_FRAMES_ABSOLUTE);
        assert_eq!(ltx2_max_frames_on_grid_at_fps(48), 601);
    }

    /// EXR output is only meaningful for the HDR adapter's LogC3 signal.
    /// Applying the inverse to an ordinary SDR render would write a
    /// wrongly-graded file that looks deliberate — worse than a rejection.
    #[test]
    fn exr_output_requires_the_hdr_adapter() {
        let mut req = valid_req();
        req.model = "ltx-2.3-22b-distilled:fp8".to_string();
        req.output_format = Some(OutputFormat::Mp4);
        req.hdr_exr_dir = Some("/tmp/shot_exr".to_string());

        let err = validate_generate_request_with_family(&req, Some("ltx2"))
            .expect_err("EXR without the HDR adapter must be rejected");
        assert!(err.contains("ic_lora_control=hdr"), "got: {err}");

        // With the adapter (and the pipeline it forces) it validates.
        req.ic_lora_control = Some("hdr".to_string());
        req.pipeline = Some(Ltx2PipelineMode::IcLora);
        req.source_video_path = Some("/tmp/reference.mp4".to_string());
        req.loras = Some(vec![LoraWeight {
            path: "/models/hdr.safetensors".to_string(),
            scale: 1.0,
        }]);
        validate_generate_request_with_family(&req, Some("ltx2"))
            .expect("the HDR adapter makes EXR output valid");
    }

    /// The extend path re-renders through the chain-stage machinery, where a
    /// per-clip EXR sequence would misalign with the stitched timeline. The
    /// rejection must be direct, not an accident of the ic-lora ⇒
    /// source_video ⇒ extend-exclusive implication chain.
    #[test]
    fn exr_output_rejects_extend_directly() {
        let mut req = valid_req();
        req.model = "ltx-2.3-22b-distilled:fp8".to_string();
        req.output_format = Some(OutputFormat::Mp4);
        req.hdr_exr_dir = Some("/tmp/shot_exr".to_string());
        req.extend_video_path = Some("/tmp/base.mp4".to_string());

        let err = validate_generate_request_with_family(&req, Some("ltx2"))
            .expect_err("EXR + extend must be rejected");
        assert!(err.contains("extend_video"), "got: {err}");
    }

    #[test]
    fn exr_options_are_rejected_for_non_ltx2_families() {
        let mut req = valid_req();
        req.hdr_exr_dir = Some("/tmp/shot_exr".to_string());
        assert!(validate_generate_request_with_family(&req, Some("flux")).is_err());
    }

    #[test]
    fn exr_precision_without_an_output_directory_is_rejected() {
        let mut req = valid_req();
        req.model = "ltx-2.3-22b-distilled:fp8".to_string();
        req.output_format = Some(OutputFormat::Mp4);
        req.hdr_exr_full_float = true;
        let err = validate_generate_request_with_family(&req, Some("ltx2"))
            .expect_err("a precision knob with nothing to write is a mistake");
        assert!(err.contains("hdr_exr_dir"), "got: {err}");
    }

    /// Every other consumer resolves control ids through
    /// `normalize_control_id`, so this gate must accept the same spellings —
    /// otherwise `--ic-lora-control HDR` succeeds everywhere except here.
    #[test]
    fn exr_accepts_any_spelling_the_control_registry_accepts() {
        // Case and surrounding whitespace only. A trailing `_` is *not* an
        // alias: the normalizer maps `_` to `-`, so `hdr_` becomes `hdr-`,
        // which is not a registered id anywhere in the stack.
        for spelling in ["hdr", "HDR", " Hdr ", "\tHDR\n"] {
            let mut req = valid_req();
            req.model = "ltx-2.3-22b-distilled:fp8".to_string();
            req.output_format = Some(OutputFormat::Mp4);
            req.source_video_path = Some("/tmp/reference.mp4".to_string());
            req.pipeline = Some(Ltx2PipelineMode::IcLora);
            req.ic_lora_control = Some(spelling.to_string());
            req.hdr_exr_dir = Some("/tmp/shot_exr".to_string());
            let result = validate_generate_request_with_family(&req, Some("ltx2"));
            assert!(
                result.is_ok(),
                "spelling {spelling:?} must be accepted, got: {result:?}"
            );
        }
    }

    #[test]
    fn exr_still_rejects_a_different_control() {
        let mut req = valid_req();
        req.model = "ltx-2.3-22b-distilled:fp8".to_string();
        req.output_format = Some(OutputFormat::Mp4);
        req.source_video_path = Some("/tmp/reference.mp4".to_string());
        req.pipeline = Some(Ltx2PipelineMode::IcLora);
        req.ic_lora_control = Some("union".to_string());
        req.hdr_exr_dir = Some("/tmp/shot_exr".to_string());
        let err = validate_generate_request_with_family(&req, Some("ltx2"))
            .expect_err("only the HDR adapter produces a LogC3 signal");
        assert!(err.contains("ic_lora_control=hdr"), "got: {err}");
    }

    /// The gallery artifact is the tonemapped video, so the sidecar's location
    /// is only discoverable from saved metadata.
    #[test]
    fn saved_metadata_records_where_the_exr_sequence_went() {
        let mut req = valid_req();
        req.model = "ltx-2.3-22b-distilled:fp8".to_string();
        req.ic_lora_control = Some("hdr".to_string());
        req.hdr_exr_dir = Some("/tmp/shot_exr".to_string());
        req.hdr_exr_full_float = true;

        let metadata = crate::OutputMetadata::from_generate_request(&req, 7, None, "test");
        assert_eq!(metadata.hdr_exr_dir.as_deref(), Some("/tmp/shot_exr"));
        assert!(metadata.hdr_exr_full_float);

        let round_tripped: crate::OutputMetadata =
            serde_json::from_str(&serde_json::to_string(&metadata).unwrap()).unwrap();
        assert_eq!(round_tripped.hdr_exr_dir.as_deref(), Some("/tmp/shot_exr"));
        assert!(round_tripped.hdr_exr_full_float);
    }

    /// An ordinary render must not gain the fields, so existing rows and
    /// older readers see exactly the JSON they saw before.
    #[test]
    fn a_non_hdr_render_serializes_no_exr_fields() {
        let metadata = crate::OutputMetadata::from_generate_request(&valid_req(), 7, None, "test");
        let json = serde_json::to_string(&metadata).unwrap();
        assert!(!json.contains("hdr_exr"), "got: {json}");
    }

    fn valid_req() -> GenerateRequest {
        GenerateRequest {
            hdr_exr_dir: None,
            hdr_exr_full_float: false,
            guidance_overrides: None,
            prompt: "a red apple".to_string(),
            negative_prompt: None,
            model: "test-model".to_string(),
            width: 1024,
            height: 1024,
            steps: 4,
            guidance: 0.0,
            seed: Some(42),
            batch_size: 1,
            output_format: Some(OutputFormat::Png),
            embed_metadata: None,
            scheduler: None,
            cfg_plus: None,
            source_image: None,
            source_image_name: None,
            edit_images: None,
            strength: 0.75,
            mask_image: None,
            control_image: None,
            control_model: None,
            control_scale: 1.0,
            expand: None,
            original_prompt: None,
            batch_id: None,
            batch_index: None,
            batch_count: None,
            lora: None,
            frames: None,
            fps: None,
            upscale_model: None,
            gif_preview: false,
            enable_audio: None,
            audio_file: None,
            audio_file_path: None,
            source_video: None,
            source_video_path: None,
            extend_video: None,
            extend_video_path: None,
            extend_overlap_frames: None,
            keyframes: None,
            pipeline: None,
            ic_lora_control: None,
            loras: None,
            retake_range: None,
            spatial_upscale: None,
            temporal_upscale: None,
            placement: None,
        }
    }

    /// Minimal valid PNG header bytes for testing.
    fn png_bytes() -> Vec<u8> {
        vec![0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
    }

    /// Minimal valid JPEG header bytes for testing.
    fn jpeg_bytes() -> Vec<u8> {
        vec![0xFF, 0xD8, 0xFF, 0xE0]
    }

    // ── clamp_to_megapixel_limit tests ──────────────────────────────────────

    #[test]
    fn clamp_noop_within_limit() {
        assert_eq!(super::clamp_to_megapixel_limit(1024, 1024), (1024, 1024));
    }

    #[test]
    fn clamp_noop_qwen_image_native_resolution() {
        // Qwen-Image trains at 1328x1328 (~1.76MP), must fit within MAX_PIXELS
        assert_eq!(super::clamp_to_megapixel_limit(1328, 1328), (1328, 1328));
    }

    #[test]
    fn clamp_noop_qwen_image_landscape() {
        // Qwen-Image 16:9 training resolution (1664x928 = ~1.54MP)
        assert_eq!(super::clamp_to_megapixel_limit(1664, 928), (1664, 928));
    }

    #[test]
    fn clamp_downscales_oversized() {
        let (w, h) = super::clamp_to_megapixel_limit(1888, 1168);
        assert!(w % 16 == 0 && h % 16 == 0, "must be multiples of 16");
        let pixels = w as u64 * h as u64;
        assert!(
            pixels <= super::MAX_PIXELS,
            "must be within limit: {pixels}"
        );
        // Aspect ratio roughly preserved
        let orig_ratio = 1888.0 / 1168.0;
        let new_ratio = w as f64 / h as f64;
        assert!(
            (orig_ratio - new_ratio).abs() < 0.05,
            "aspect ratio drift too large"
        );
    }

    #[test]
    fn clamp_large_square() {
        let (w, h) = super::clamp_to_megapixel_limit(2048, 2048);
        assert!(w % 16 == 0 && h % 16 == 0);
        assert!(w as u64 * h as u64 <= super::MAX_PIXELS);
    }

    #[test]
    fn clamp_extreme_aspect_ratio() {
        let (w, h) = super::clamp_to_megapixel_limit(4096, 256);
        assert!(w % 16 == 0 && h % 16 == 0);
        assert!(w as u64 * h as u64 <= super::MAX_PIXELS);
        assert!(w > h, "should remain landscape");
    }

    // ── normalise_output_format tests ────────────────────────────────────────

    #[test]
    fn normalise_output_format_unset_for_ltx2_picks_mp4() {
        let mut req = valid_req();
        req.model = "ltx-2-19b-distilled:fp8".to_string();
        req.output_format = None;
        req.normalise_output_format(Some("ltx2"));
        assert_eq!(
            req.resolved_output_format(),
            OutputFormat::Mp4,
            "ltx2 with no explicit format should default to mp4"
        );
    }

    #[test]
    fn normalise_output_format_unset_for_ltx2_with_audio_picks_mp4() {
        let mut req = valid_req();
        req.model = "ltx-2-19b-distilled:fp8".to_string();
        req.output_format = None;
        req.enable_audio = Some(true);
        req.normalise_output_format(Some("ltx2"));
        assert_eq!(
            req.resolved_output_format(),
            OutputFormat::Mp4,
            "ltx2 with audio and no explicit format should default to mp4"
        );
    }

    #[test]
    fn normalise_output_format_unset_for_ltx_video_picks_mp4() {
        let mut req = valid_req();
        req.model = "ltx-video:fp16".to_string();
        req.output_format = None;
        req.normalise_output_format(Some("ltx-video"));
        assert_eq!(
            req.resolved_output_format(),
            OutputFormat::Mp4,
            "ltx-video with no explicit format should default to mp4"
        );
    }

    #[test]
    fn normalise_output_format_unset_for_flux_picks_png() {
        let mut req = valid_req();
        req.model = "flux-schnell:q8".to_string();
        req.output_format = None;
        req.normalise_output_format(Some("flux"));
        assert_eq!(
            req.resolved_output_format(),
            OutputFormat::Png,
            "flux with no explicit format should default to png"
        );
    }

    #[test]
    fn normalise_output_format_explicit_png_for_ltx2_remains_png_and_validation_rejects_it() {
        // When the user explicitly requests PNG for an ltx2 model, normalise
        // must leave it as-is so validation can reject it with a clear error.
        let mut req = valid_req();
        req.model = "ltx-2-19b-distilled:fp8".to_string();
        req.output_format = Some(OutputFormat::Png);
        req.normalise_output_format(Some("ltx2"));
        // normalise must not touch an explicit value
        assert_eq!(req.output_format, Some(OutputFormat::Png));
        // and validation must still reject explicit PNG on ltx2
        let err = validate_generate_request(&req).unwrap_err();
        assert!(
            err.contains("LTX-2 outputs must use"),
            "expected validation error for explicit png on ltx2, got: {err}"
        );
    }

    // ── validate_generate_request tests ──────────────────────────────────────

    #[test]
    fn valid_request_passes() {
        assert!(validate_generate_request(&valid_req()).is_ok());
    }

    #[test]
    fn ltx2_audio_requires_mp4() {
        let mut req = valid_req();
        req.model = "ltx-2-19b-distilled:fp8".to_string();
        req.output_format = Some(OutputFormat::Gif);
        req.enable_audio = Some(true);
        assert!(validate_generate_request(&req).unwrap_err().contains("mp4"));
    }

    /// A T2A request produces a WAV and only a WAV. Both directions of the
    /// pairing are enforced: `t2a` without `wav` would encode frames that
    /// don't exist, and `wav` without `t2a` would ask a video pipeline for a
    /// container it never writes.
    #[test]
    fn ltx2_t2a_requires_wav_output_and_wav_requires_t2a() {
        let mut req = valid_req();
        req.model = "ltx-2.3-22b-dev:fp8".to_string();
        req.pipeline = Some(Ltx2PipelineMode::T2a);
        req.output_format = Some(OutputFormat::Wav);
        assert!(validate_generate_request(&req).is_ok());

        req.output_format = Some(OutputFormat::Mp4);
        let err = validate_generate_request(&req).unwrap_err();
        assert!(err.contains("audio only"), "got: {err}");

        req.pipeline = None;
        req.output_format = Some(OutputFormat::Wav);
        let err = validate_generate_request(&req).unwrap_err();
        assert!(err.contains("pipeline=t2a"), "got: {err}");
    }

    #[test]
    fn ltx2_t2a_rejects_every_conditioning_input() {
        let base = || {
            let mut req = valid_req();
            req.model = "ltx-2.3-22b-dev:fp8".to_string();
            req.pipeline = Some(Ltx2PipelineMode::T2a);
            req.output_format = Some(OutputFormat::Wav);
            req
        };

        let mut with_image = base();
        with_image.source_image = Some(vec![1, 2, 3]);
        assert!(validate_generate_request(&with_image)
            .unwrap_err()
            .contains("source_image"));

        let mut with_audio = base();
        with_audio.audio_file_path = Some("/srv/voice.wav".to_string());
        assert!(validate_generate_request(&with_audio)
            .unwrap_err()
            .contains("audio_file_path"));

        let mut with_upscale = base();
        with_upscale.spatial_upscale = Some(crate::Ltx2SpatialUpscale::X2);
        assert!(validate_generate_request(&with_upscale)
            .unwrap_err()
            .contains("spatial_upscale"));

        let mut with_post_upscale = base();
        with_post_upscale.upscale_model = Some("real-esrgan-x4plus:fp16".to_string());
        assert!(validate_generate_request(&with_post_upscale)
            .unwrap_err()
            .contains("upscale_model"));
    }

    /// ControlNet is refused for `t2a` by the family gate, not by the
    /// pipeline's own conditioning list. A ControlNet pair requires an SD1.5
    /// family and `pipeline` requires `ltx2`, so the two can never both be
    /// satisfied — the audio-only runtime cannot be reached with a control
    /// model loaded. Pinned here because the t2a rejection list reads as
    /// though it were the only guard, and a future refactor that relaxed
    /// `require_controlnet_capable_family` would silently open that door.
    #[test]
    fn ltx2_t2a_cannot_carry_controlnet_inputs() {
        let mut req = valid_req();
        req.model = "ltx-2.3-22b-dev:fp8".to_string();
        req.pipeline = Some(Ltx2PipelineMode::T2a);
        req.output_format = Some(OutputFormat::Wav);
        req.control_image = Some(png_bytes());
        req.control_model = Some("controlnet-canny-sd15".to_string());
        req.control_scale = 0.8;

        let err = validate_generate_request(&req).unwrap_err();
        assert!(err.contains("ControlNet"), "got: {err}");

        // And the mirror case: a control model without an image is refused on
        // the same family grounds rather than reaching the audio pipeline.
        req.control_image = None;
        let err = validate_generate_request(&req).unwrap_err();
        assert!(err.contains("ControlNet"), "got: {err}");
    }

    #[test]
    fn ltx2_t2a_rejects_enable_audio_false() {
        let mut req = valid_req();
        req.model = "ltx-2.3-22b-dev:fp8".to_string();
        req.pipeline = Some(Ltx2PipelineMode::T2a);
        req.output_format = Some(OutputFormat::Wav);
        req.enable_audio = Some(false);
        let err = validate_generate_request(&req).unwrap_err();
        assert!(err.contains("enable_audio=false"), "got: {err}");
    }

    /// `modality_scale` steers the audio↔video cross-attention. Audio-only has
    /// no video branch, so a non-1.0 value cannot be honoured — reject it
    /// rather than accept a number that silently does nothing.
    #[test]
    fn ltx2_t2a_rejects_non_unit_modality_scale_override() {
        let mut req = valid_req();
        req.model = "ltx-2.3-22b-dev:fp8".to_string();
        req.pipeline = Some(Ltx2PipelineMode::T2a);
        req.output_format = Some(OutputFormat::Wav);
        req.guidance_overrides = Some(crate::Ltx2GuidanceOverrides {
            modality_scale: Some(3.0),
            ..Default::default()
        });
        let err = validate_generate_request(&req).unwrap_err();
        assert!(err.contains("modality_scale"), "got: {err}");

        req.guidance_overrides = Some(crate::Ltx2GuidanceOverrides {
            modality_scale: Some(1.0),
            ..Default::default()
        });
        assert!(validate_generate_request(&req).is_ok());
    }

    #[test]
    fn ltx2_retake_requires_source_video() {
        let mut req = valid_req();
        req.model = "ltx-2-19b-distilled:fp8".to_string();
        req.output_format = Some(OutputFormat::Mp4);
        req.retake_range = Some(crate::TimeRange {
            start_seconds: 0.0,
            end_seconds: 1.0,
        });
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("source_video"));
    }

    #[test]
    fn ltx2_audio_file_rejects_inline_payloads_above_limit() {
        let mut req = valid_req();
        req.model = "ltx-2-19b-distilled:fp8".to_string();
        req.output_format = Some(OutputFormat::Mp4);
        req.audio_file = Some(vec![0; MAX_INLINE_AUDIO_BYTES + 1]);
        let err = validate_generate_request(&req).unwrap_err();
        assert!(err.contains("audio_file exceeds"), "got: {err}");
        assert!(err.contains("64 MiB"), "got: {err}");
    }

    #[test]
    fn ltx2_source_video_rejects_inline_payloads_above_limit() {
        let mut req = valid_req();
        req.model = "ltx-2-19b-distilled:fp8".to_string();
        req.output_format = Some(OutputFormat::Mp4);
        req.source_video = Some(vec![0; MAX_INLINE_SOURCE_VIDEO_BYTES + 1]);
        let err = validate_generate_request(&req).unwrap_err();
        assert!(err.contains("source_video exceeds"), "got: {err}");
        assert!(err.contains("64 MiB"), "got: {err}");
    }

    #[test]
    fn ltx2_audio_file_path_is_family_gated_and_preserves_inline_limit() {
        let mut req = valid_req();
        req.model = "ltx-2-19b-distilled:fp8".to_string();
        req.output_format = Some(OutputFormat::Mp4);
        req.audio_file_path = Some("/srv/mold-media/voice.wav".to_string());
        assert!(validate_generate_request(&req).is_ok());

        req.audio_file = Some(vec![0; MAX_INLINE_AUDIO_BYTES + 1]);
        let err = validate_generate_request(&req).unwrap_err();
        assert!(
            err.contains("audio_file_path cannot be combined"),
            "got: {err}"
        );

        let mut wrong_family = valid_req();
        wrong_family.model = "flux-schnell:q8".to_string();
        wrong_family.audio_file_path = Some("/srv/mold-media/voice.wav".to_string());
        let err = validate_generate_request(&wrong_family).unwrap_err();
        assert!(
            err.contains("audio_file_path is only supported"),
            "got: {err}"
        );
    }

    #[test]
    fn ltx2_source_video_path_satisfies_retake_requirements() {
        let mut req = valid_req();
        req.model = "ltx-2-19b-distilled:fp8".to_string();
        req.output_format = Some(OutputFormat::Mp4);
        req.source_video_path = Some("/srv/mold-media/clip.mp4".to_string());
        req.retake_range = Some(crate::TimeRange {
            start_seconds: 0.0,
            end_seconds: 1.0,
        });

        assert!(validate_generate_request(&req).is_ok());

        req.source_video = Some(vec![0; MAX_INLINE_SOURCE_VIDEO_BYTES + 1]);
        let err = validate_generate_request(&req).unwrap_err();
        assert!(
            err.contains("source_video_path cannot be combined"),
            "got: {err}"
        );
    }

    #[test]
    fn ltx2_keyframe_pipeline_requires_multiple_keyframes() {
        let mut req = valid_req();
        req.model = "ltx-2-19b-distilled:fp8".to_string();
        req.output_format = Some(OutputFormat::Mp4);
        req.pipeline = Some(crate::Ltx2PipelineMode::Keyframe);
        req.frames = Some(17);
        req.keyframes = Some(vec![crate::KeyframeCondition {
            frame: 0,
            image: png_bytes(),
        }]);
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("at least 2 keyframes"));
    }

    #[test]
    fn keyframes_on_unknown_family_report_unknown_model_family() {
        let mut req = valid_req();
        req.model = "private-ltx2-style-model".to_string();
        req.frames = Some(17);
        req.keyframes = Some(vec![
            crate::KeyframeCondition {
                frame: 0,
                image: png_bytes(),
            },
            crate::KeyframeCondition {
                frame: 16,
                image: png_bytes(),
            },
        ]);
        let err = validate_generate_request(&req).unwrap_err();
        assert!(err.contains("unknown model family"), "got: {err}");
    }

    fn ltx2_req_with_overrides(overrides: Ltx2GuidanceOverrides) -> GenerateRequest {
        let mut req = valid_req();
        req.model = "ltx-2-19b-distilled:fp8".to_string();
        req.output_format = Some(OutputFormat::Mp4);
        req.frames = Some(17);
        req.guidance_overrides = Some(overrides);
        req
    }

    #[test]
    fn ltx2_guidance_overrides_accept_upstream_ranges() {
        validate_generate_request(&ltx2_req_with_overrides(Ltx2GuidanceOverrides {
            stg_scale: Some(1.5),
            stg_blocks: Some(vec![28, 29]),
            rescale_scale: Some(0.7),
            modality_scale: Some(3.0),
            skip_step: Some(2),
        }))
        .unwrap();
    }

    #[test]
    fn ltx2_guidance_overrides_are_family_gated() {
        let mut req = valid_req();
        req.guidance_overrides = Some(Ltx2GuidanceOverrides {
            stg_scale: Some(1.0),
            ..Ltx2GuidanceOverrides::default()
        });
        let err = validate_generate_request(&req).unwrap_err();
        assert!(err.contains("guidance_overrides"), "got: {err}");
        assert!(err.contains("LTX-2"), "got: {err}");
    }

    #[test]
    fn ltx2_guidance_overrides_reject_empty_objects() {
        let err =
            validate_generate_request(&ltx2_req_with_overrides(Ltx2GuidanceOverrides::default()))
                .unwrap_err();
        assert!(err.contains("at least one field"), "got: {err}");
    }

    #[test]
    fn ltx2_guidance_overrides_reject_out_of_range_scales() {
        let err = validate_generate_request(&ltx2_req_with_overrides(Ltx2GuidanceOverrides {
            stg_scale: Some(-0.5),
            ..Ltx2GuidanceOverrides::default()
        }))
        .unwrap_err();
        assert!(err.contains("stg_scale"), "got: {err}");

        let err = validate_generate_request(&ltx2_req_with_overrides(Ltx2GuidanceOverrides {
            stg_scale: Some(f64::NAN),
            ..Ltx2GuidanceOverrides::default()
        }))
        .unwrap_err();
        assert!(err.contains("finite"), "got: {err}");

        // Rescale is an interpolation factor, so its ceiling is 1.0 even
        // though the other scales accept much larger values.
        let err = validate_generate_request(&ltx2_req_with_overrides(Ltx2GuidanceOverrides {
            rescale_scale: Some(1.5),
            ..Ltx2GuidanceOverrides::default()
        }))
        .unwrap_err();
        assert!(err.contains("rescale_scale"), "got: {err}");
        validate_generate_request(&ltx2_req_with_overrides(Ltx2GuidanceOverrides {
            modality_scale: Some(1.5),
            ..Ltx2GuidanceOverrides::default()
        }))
        .unwrap();
    }

    #[test]
    fn ltx2_guidance_overrides_reject_unusable_stg_blocks() {
        let err = validate_generate_request(&ltx2_req_with_overrides(Ltx2GuidanceOverrides {
            stg_blocks: Some(Vec::new()),
            ..Ltx2GuidanceOverrides::default()
        }))
        .unwrap_err();
        assert!(err.contains("must not be empty"), "got: {err}");

        let err = validate_generate_request(&ltx2_req_with_overrides(Ltx2GuidanceOverrides {
            stg_blocks: Some(vec![MAX_STG_BLOCK_INDEX]),
            ..Ltx2GuidanceOverrides::default()
        }))
        .unwrap_err();
        assert!(err.contains("deepest supported"), "got: {err}");

        let err = validate_generate_request(&ltx2_req_with_overrides(Ltx2GuidanceOverrides {
            stg_blocks: Some(vec![29, 29]),
            ..Ltx2GuidanceOverrides::default()
        }))
        .unwrap_err();
        assert!(err.contains("more than once"), "got: {err}");
    }

    #[test]
    fn ltx2_guidance_overrides_bound_the_skip_stride() {
        let err = validate_generate_request(&ltx2_req_with_overrides(Ltx2GuidanceOverrides {
            skip_step: Some(Ltx2GuidanceOverrides::MAX_SKIP_STEP + 1),
            ..Ltx2GuidanceOverrides::default()
        }))
        .unwrap_err();
        assert!(err.contains("skip_step"), "got: {err}");
    }

    #[test]
    fn enable_audio_some_false_does_not_trip_family_check() {
        // Web form serializes the audio toggle as `Some(false)` whenever the
        // checkbox is explicitly off. That must be a no-op for any family
        // (including the unknown-family case used by catalog `cv:*` IDs)
        // since the user did not ask for audio.
        let mut req = valid_req();
        req.model = "cv:2781713".to_string();
        req.enable_audio = Some(false);
        // No family hint provided — exercises the unknown-family branch.
        validate_generate_request(&req).unwrap();
    }

    #[test]
    fn enable_audio_some_true_with_family_hint_passes_for_catalog_ltx2() {
        // The HTTP server resolves `cv:*` IDs against the catalog DB and
        // passes the family through as a hint. With the LTX-2 hint, audio
        // is allowed even though the manifest layer has no entry for the
        // catalog ID.
        let mut req = valid_req();
        req.model = "cv:2781713".to_string();
        req.output_format = Some(OutputFormat::Mp4);
        req.enable_audio = Some(true);
        validate_generate_request_with_family(&req, Some("ltx2")).unwrap();
    }

    #[test]
    fn enable_audio_some_true_without_hint_still_errors_on_unknown_family() {
        // No hint, no manifest entry — the family gate still fires so the
        // user gets a clear 400 instead of an opaque inference-layer error.
        let mut req = valid_req();
        req.model = "cv:2781713".to_string();
        req.output_format = Some(OutputFormat::Mp4);
        req.enable_audio = Some(true);
        let err = validate_generate_request(&req).unwrap_err();
        assert!(err.contains("unknown model family"), "got: {err}");
        assert!(err.contains("enable_audio"), "got: {err}");
    }

    #[test]
    fn family_hint_overrides_manifest_lookup() {
        // Even when the manifest would resolve the model name to a different
        // family, the explicit hint wins. This lets the server pass the
        // catalog-resolved family through unconditionally.
        let mut req = valid_req();
        req.model = "private-name".to_string();
        req.output_format = Some(OutputFormat::Mp4);
        req.enable_audio = Some(true);
        validate_generate_request_with_family(&req, Some("ltx2")).unwrap();
    }

    #[test]
    fn ltx2_allows_temporal_upscale_request() {
        let mut req = valid_req();
        req.model = "ltx-2-19b-distilled:fp8".to_string();
        req.output_format = Some(OutputFormat::Mp4);
        req.temporal_upscale = Some(crate::Ltx2TemporalUpscale::X2);
        validate_generate_request(&req).unwrap();
    }

    #[test]
    fn ltx2_allows_x1_5_spatial_upscale_request() {
        let mut req = valid_req();
        req.model = "ltx-2.3-22b-distilled:fp8".to_string();
        req.output_format = Some(OutputFormat::Mp4);
        req.spatial_upscale = Some(crate::Ltx2SpatialUpscale::X1_5);
        validate_generate_request(&req).unwrap();
    }

    #[test]
    fn empty_prompt_rejected() {
        // The default `valid_req()` is a text-to-image request with no visual
        // conditioning, so the prompt stays mandatory.
        let mut req = valid_req();
        req.prompt = "   ".to_string();
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("prompt"));
    }

    /// Baseline LTX-2 video request with no visual conditioning attached.
    fn ltx2_video_req() -> GenerateRequest {
        let mut req = valid_req();
        req.model = "ltx-2-19b-distilled:fp8".to_string();
        req.output_format = Some(OutputFormat::Mp4);
        req.fps = Some(24);
        req.frames = Some(97);
        req
    }

    #[test]
    fn empty_prompt_allowed_for_ltx2_with_source_image() {
        let mut req = ltx2_video_req();
        req.prompt = String::new();
        req.source_image = Some(png_bytes());
        validate_generate_request(&req).unwrap();

        // Whitespace-only is the same case as empty.
        req.prompt = "  \n ".to_string();
        validate_generate_request(&req).unwrap();

        // Catalog IDs only resolve to `ltx2` through the family hint.
        let mut catalog = req.clone();
        catalog.model = "cv:2781713".to_string();
        assert!(validate_generate_request(&catalog).is_err());
        validate_generate_request_with_family(&catalog, Some("ltx2")).unwrap();
    }

    #[test]
    fn empty_prompt_allowed_for_ltx2_keyframes_video_and_extend() {
        let mut keyframed = ltx2_video_req();
        keyframed.prompt = String::new();
        keyframed.keyframes = Some(vec![KeyframeCondition {
            frame: 0,
            image: png_bytes(),
        }]);
        validate_generate_request(&keyframed).unwrap();

        let mut from_video = ltx2_video_req();
        from_video.prompt = String::new();
        from_video.source_video = Some(vec![0, 0, 0, 0x20, b'f', b't', b'y', b'p']);
        validate_generate_request(&from_video).unwrap();

        // The server validates before `resolve_server_local_media_paths`, so
        // the `*_path` variants must count as conditioning too.
        let mut from_video_path = ltx2_video_req();
        from_video_path.prompt = String::new();
        from_video_path.source_video_path = Some("/srv/clips/shot.mp4".to_string());
        validate_generate_request(&from_video_path).unwrap();

        let mut extended = extend_req();
        extended.prompt = String::new();
        validate_generate_request(&extended).unwrap();

        let mut extended_path = ltx2_video_req();
        extended_path.prompt = String::new();
        extended_path.extend_video_path = Some("/srv/clips/shot.mp4".to_string());
        validate_generate_request(&extended_path).unwrap();
    }

    #[test]
    fn empty_prompt_allowed_for_ltx_video_with_source_image() {
        let mut req = valid_req();
        req.model = "ltx-video-0.9.8-2b-distilled:bf16".to_string();
        req.output_format = Some(OutputFormat::Mp4);
        req.prompt = String::new();
        req.source_image = Some(png_bytes());
        validate_generate_request(&req).unwrap();
    }

    #[test]
    fn empty_prompt_still_rejected_for_ltx2_text_to_video() {
        let mut req = ltx2_video_req();
        req.prompt = String::new();
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("prompt"));
    }

    #[test]
    fn empty_prompt_still_rejected_for_flux_and_sd() {
        // Image families keep the prompt required even with a source image —
        // an empty img2img prompt is not a trained context there.
        for model in [
            "flux-dev:q8",
            "sd15:fp16",
            "sdxl:fp16",
            "z-image-turbo:bf16",
        ] {
            let mut req = valid_req();
            req.model = model.to_string();
            req.prompt = String::new();
            req.source_image = Some(png_bytes());
            assert!(
                validate_generate_request(&req)
                    .unwrap_err()
                    .contains("prompt"),
                "{model} must still require a prompt"
            );
        }
    }

    #[test]
    fn prompt_required_predicate_matches_validation() {
        let mut req = ltx2_video_req();
        assert!(super::prompt_required_for(&req, None));
        req.source_image = Some(png_bytes());
        assert!(!super::prompt_required_for(&req, None));

        // Unknown family (catalog ID without a hint) stays required.
        let mut catalog = req.clone();
        catalog.model = "hf:Lightricks/LTX-2".to_string();
        assert!(super::prompt_required_for(&catalog, None));
        assert!(!super::prompt_required_for(&catalog, Some("ltx2")));
    }

    #[test]
    fn prompt_length_limit_still_enforced_without_a_prompt_requirement() {
        let mut req = ltx2_video_req();
        req.source_image = Some(png_bytes());
        req.prompt = "a".repeat(77_001);
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("77,000"));
    }

    #[test]
    fn zero_dimensions_rejected() {
        let mut req = valid_req();
        req.width = 0;
        assert!(validate_generate_request(&req).is_err());
        req.width = 1024;
        req.height = 0;
        assert!(validate_generate_request(&req).is_err());
    }

    #[test]
    fn dimensions_must_be_multiple_of_16() {
        let mut req = valid_req();
        req.width = 513; // not multiple of 16
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("multiples of 16"));
    }

    #[test]
    fn ltx2_dimensions_must_be_multiple_of_32() {
        let mut req = valid_req();
        req.width = 1008; // multiple of 16, but not 32
        req.height = 704;

        let error = validate_generate_request_with_family(&req, Some("ltx2"))
            .expect_err("LTX-2 must reject a 16px-only canvas");

        assert!(error.contains("multiples of 32"), "{error}");
        assert!(error.contains("ltx2"), "{error}");
    }

    #[test]
    fn ltx2_accepts_custom_32_aligned_dimensions() {
        let mut req = valid_req();
        req.width = 1056;
        req.height = 736;
        req.output_format = Some(OutputFormat::Mp4);

        assert!(validate_generate_request_with_family(&req, Some("ltx2")).is_ok());
    }

    #[test]
    fn valid_non_square_dimensions() {
        let mut req = valid_req();
        req.width = 512;
        req.height = 768;
        assert!(validate_generate_request(&req).is_ok());
    }

    #[test]
    fn oversized_image_rejected() {
        let mut req = valid_req();
        req.width = 1408;
        req.height = 1408; // ~1.98MP > 1.8MP limit
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("megapixels"));
    }

    #[test]
    fn oversized_image_error_reports_current_megapixel_limit() {
        let mut req = valid_req();
        req.width = 1408;
        req.height = 1408;
        let err = validate_generate_request(&req).unwrap_err();
        assert!(err.contains("1.8MP"), "got: {err}");
    }

    #[test]
    fn zero_steps_rejected() {
        let mut req = valid_req();
        req.steps = 0;
        assert!(validate_generate_request(&req).is_err());
    }

    #[test]
    fn excessive_steps_rejected() {
        let mut req = valid_req();
        req.steps = 101;
        assert!(validate_generate_request(&req).is_err());
    }

    #[test]
    fn valid_step_counts() {
        for steps in [1, 4, 20, 28, 50, 100] {
            let mut req = valid_req();
            req.steps = steps;
            assert!(
                validate_generate_request(&req).is_ok(),
                "steps={steps} should be valid"
            );
        }
    }

    #[test]
    fn ltx2_frames_must_still_follow_8n_plus_1() {
        let mut req = valid_req();
        req.model = "ltx-2-19b-distilled:fp8".to_string();
        req.output_format = Some(OutputFormat::Mp4);
        req.frames = Some(10);
        let err = validate_generate_request(&req).unwrap_err();
        assert!(err.contains("8n+1"), "got: {err}");
        assert!(err.contains("LTX-Video / LTX-2"), "got: {err}");
    }

    fn extend_req() -> GenerateRequest {
        let mut req = valid_req();
        req.model = "ltx-2-19b-distilled:fp8".to_string();
        req.output_format = Some(OutputFormat::Mp4);
        req.fps = Some(24);
        req.frames = Some(97);
        req.extend_video = Some(vec![0, 0, 0, 0x20, b'f', b't', b'y', b'p']);
        req
    }

    #[test]
    fn extend_accepts_a_video_with_the_default_overlap() {
        let req = extend_req();
        assert!(validate_generate_request(&req).is_ok());
        assert!(req.is_extend());
        assert_eq!(
            req.effective_extend_overlap_frames(),
            DEFAULT_EXTEND_OVERLAP_FRAMES
        );
        // 97 rendered frames minus the 17-frame overlap that reproduces the
        // source tail = 80 genuinely new frames appended.
        assert_eq!(req.extend_new_frames(), Some(80));
    }

    #[test]
    fn extend_is_ltx2_only() {
        let mut req = extend_req();
        req.model = "ltx-video-0.9.6-distilled:bf16".to_string();
        let err = validate_generate_request(&req).unwrap_err();
        assert!(err.contains("extend_video"), "got: {err}");
    }

    #[test]
    fn extend_rejects_both_inline_bytes_and_a_path() {
        let mut req = extend_req();
        req.extend_video_path = Some("/srv/mold/clip.mp4".to_string());
        let err = validate_generate_request(&req).unwrap_err();
        assert!(err.contains("cannot be combined"), "got: {err}");
    }

    #[test]
    fn extend_rejects_empty_payloads() {
        let mut req = extend_req();
        req.extend_video = Some(Vec::new());
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("must not be empty"));

        let mut req = extend_req();
        req.extend_video = None;
        req.extend_video_path = Some("   ".to_string());
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("must not be empty"));
    }

    /// The overlap re-encodes through the VAE's 8x causal temporal grid, so an
    /// off-grid value would not map onto whole latent slots.
    #[test]
    fn extend_overlap_must_sit_on_the_latent_grid() {
        let mut req = extend_req();
        req.extend_overlap_frames = Some(12);
        let err = validate_generate_request(&req).unwrap_err();
        assert!(err.contains("8k+1"), "got: {err}");

        for overlap in [1u32, 9, 17, 25] {
            let mut req = extend_req();
            req.extend_overlap_frames = Some(overlap);
            assert!(
                validate_generate_request(&req).is_ok(),
                "{overlap} is on the 8k+1 grid",
            );
        }
    }

    /// An overlap at or above the clip length means every rendered frame
    /// reproduces the source and the continuation adds nothing.
    #[test]
    fn extend_overlap_must_leave_room_for_new_frames() {
        let mut req = extend_req();
        req.frames = Some(25);
        req.extend_overlap_frames = Some(25);
        let err = validate_generate_request(&req).unwrap_err();
        assert!(err.contains("strictly less than"), "got: {err}");

        req.extend_overlap_frames = Some(17);
        assert!(validate_generate_request(&req).is_ok());
        assert_eq!(req.extend_new_frames(), Some(8));
    }

    #[test]
    fn extend_overlap_requires_a_video_to_extend() {
        let mut req = valid_req();
        req.model = "ltx-2-19b-distilled:fp8".to_string();
        req.output_format = Some(OutputFormat::Mp4);
        req.frames = Some(97);
        req.extend_overlap_frames = Some(17);
        let err = validate_generate_request(&req).unwrap_err();
        assert!(err.contains("requires extend_video"), "got: {err}");
    }

    /// Extend continues one clip's motion; the other conditioning inputs each
    /// claim authority over the same opening frames.
    #[test]
    fn extend_rejects_competing_conditioning_inputs() {
        let mut req = extend_req();
        req.source_video = Some(vec![1, 2, 3]);
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("source_video"));

        let mut req = extend_req();
        req.source_image = Some(png_bytes());
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("source_image"));

        let mut req = extend_req();
        req.keyframes = Some(vec![KeyframeCondition {
            frame: 0,
            image: png_bytes(),
        }]);
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("keyframes"));
    }

    /// An extend clip is an ordinary render, so it is bound by the same
    /// duration budget as any other single request.
    #[test]
    fn extend_respects_the_temporal_budget() {
        let mut req = extend_req();
        req.frames = Some(481);
        assert!(validate_generate_request(&req).is_ok());

        req.frames = Some(489);
        let err = validate_generate_request(&req).unwrap_err();
        assert!(err.contains("RoPE"), "got: {err}");
    }

    /// Extend provenance must reach saved metadata, and must not appear on
    /// ordinary renders where it would read as a continuation that never was.
    #[test]
    fn extend_provenance_reaches_output_metadata() {
        let mut req = extend_req();
        req.extend_video = None;
        req.extend_video_path = Some("/srv/mold/clip.mp4".to_string());
        req.extend_overlap_frames = Some(25);
        let metadata = crate::OutputMetadata::from_generate_request(&req, 7, None, "test");
        assert_eq!(
            metadata.extend_video_path.as_deref(),
            Some("/srv/mold/clip.mp4")
        );
        assert_eq!(metadata.extend_overlap_frames, Some(25));

        let plain = crate::OutputMetadata::from_generate_request(&valid_req(), 7, None, "test");
        assert_eq!(plain.extend_video_path, None);
        assert_eq!(plain.extend_overlap_frames, None);
    }

    /// The RoPE temporal axis is expressed in *seconds* (`rope.rs`'s
    /// `scale_video_time_to_seconds` divides the pixel-frame coordinate by fps
    /// before `max_pos` normalization), so the ceiling is a duration and must
    /// scale with fps rather than sit at a fixed frame count.
    #[test]
    fn ltx2_frame_ceiling_tracks_fps() {
        // Latent k spans pixel [8k-7, 8k+1] after the causal fix, so F frames
        // put the last RoPE midpoint at (F-4)/fps seconds: F = 20*fps + 4.
        assert_eq!(ltx2_max_frames_at_fps(24), 484);
        assert_eq!(ltx2_max_frames_at_fps(25), 504);
        assert_eq!(ltx2_max_frames_at_fps(12), 244);
        assert_eq!(ltx2_max_frames_at_fps(8), 164);
        // Low fps is *tighter* than the old flat 153: 6 fps only buys 20s of
        // runtime, which the previous constant silently over-admitted.
        assert_eq!(ltx2_max_frames_at_fps(6), 124);
        // The absolute resource guard binds before the seconds budget does at
        // high frame rates.
        assert_eq!(ltx2_max_frames_at_fps(60), LTX2_MAX_FRAMES_ABSOLUTE);
        assert_eq!(ltx2_max_frames_at_fps(120), LTX2_MAX_FRAMES_ABSOLUTE);
        // fps=0 is rejected elsewhere; the helper must not divide by zero.
        assert_eq!(ltx2_max_frames_at_fps(0), ltx2_max_frames_at_fps(1));
    }

    /// The helper values are what /api/models advertises as max_frames /
    /// frame_step; they must agree with what the validator enforces so the
    /// wire contract can't drift from the actual rejection rules.
    #[test]
    fn frame_constraint_helpers_match_validator_behavior() {
        // Advertised values are grid-snapped so a client that clamps to them
        // can actually submit; the raw duration ceiling is off the 8n+1 grid.
        assert_eq!(
            max_frames_for_family("ltx2"),
            Some(ltx2_max_frames_on_grid_at_fps(LTX2_DEFAULT_FPS))
        );
        assert_eq!(max_frames_for_family_at_fps("ltx2", 12), Some(241));
        assert_eq!(max_frames_for_family_at_fps("ltx-video", 12), Some(257));
        assert_eq!(max_frames_for_family("ltx-video"), Some(257));
        assert_eq!(max_frames_for_family("flux"), None);
        assert_eq!(max_frames_for_family("sdxl"), None);
        assert_eq!(frame_step_for_family("ltx2"), Some(8));
        assert_eq!(frame_step_for_family("ltx-video"), Some(8));
        assert_eq!(frame_step_for_family("flux"), None);

        // One grid step past the advertised ltx-video cap must be rejected,
        // and the rejection must quote the same cap the wire advertises.
        let cap = max_frames_for_family("ltx-video").unwrap();
        let mut req = valid_req();
        req.model = "ltx-video-0.9.6-distilled:bf16".to_string();
        req.output_format = Some(OutputFormat::Mp4);
        req.frames = Some(cap + 8); // stays on the 8n+1 grid so only the cap trips
        let err = validate_generate_request(&req).unwrap_err();
        assert!(err.contains(&cap.to_string()), "got: {err}");

        // Same agreement for the ltx2 ceiling, which is fps-dependent, so the
        // request has to name the fps the helper was asked about.
        let cap = max_frames_for_family_at_fps("ltx2", 12).unwrap();
        let mut req = valid_req();
        req.model = "ltx-2-19b-distilled:fp8".to_string();
        req.output_format = Some(OutputFormat::Mp4);
        req.fps = Some(12);
        req.frames = Some(249); // first 8n+1 value past the 244-frame cap
        let err = validate_generate_request(&req).unwrap_err();
        assert!(err.contains(&cap.to_string()), "got: {err}");
    }

    #[test]
    fn ltx2_frames_at_rope_budget_accepted() {
        let mut req = valid_req();
        req.model = "ltx-2-19b-distilled:fp8".to_string();
        req.output_format = Some(OutputFormat::Mp4);
        req.fps = Some(24);
        // 481 = 20s at 24 fps on the 8n+1 grid (484 is the exact ceiling).
        req.frames = Some(481);
        assert!(validate_generate_request(&req).is_ok());
    }

    /// The old flat 153 was a floor, not a ceiling, at the default frame rate:
    /// LTX-2.3 advertises ~20s single-shot generation and the checkpoint budget
    /// agrees. Frame counts that used to be rejected out of hand must pass.
    #[test]
    fn ltx2_frames_over_the_old_flat_cap_are_accepted_within_the_duration_budget() {
        for frames in [161u32, 193, 257, 401] {
            let mut req = valid_req();
            req.model = "ltx-2-19b-distilled:fp8".to_string();
            req.output_format = Some(OutputFormat::Mp4);
            req.fps = Some(24);
            req.frames = Some(frames);
            assert!(
                validate_generate_request(&req).is_ok(),
                "{frames} frames at 24 fps is {:.1}s, inside the {LTX2_MAX_RUNTIME_SECONDS}s budget",
                frames as f64 / 24.0,
            );
        }
    }

    #[test]
    fn ltx2_frames_over_rope_budget_rejected() {
        let mut req = valid_req();
        req.model = "ltx-2-19b-distilled:fp8".to_string();
        req.output_format = Some(OutputFormat::Mp4);
        req.fps = Some(24);
        req.frames = Some(489); // 20.2s at 24 fps — one grid step past the budget
        let err = validate_generate_request(&req).unwrap_err();
        assert!(err.contains("489"), "got: {err}");
        // The quoted ceiling is grid-snapped so it is directly usable: 484 is
        // the exact budget but 483 % 8 == 3, so retrying at 484 would fail again.
        assert!(err.contains("481"), "got: {err}");
        assert!(err.contains("RoPE"), "got: {err}");
    }

    /// The same frame count can be inside or outside the budget depending on
    /// fps — this is the whole point of deriving the ceiling instead of fixing
    /// it. 193 frames is 8s at 24 fps but 32s at 6 fps.
    #[test]
    fn ltx2_frame_budget_is_a_duration_not_a_frame_count() {
        let mut req = valid_req();
        req.model = "ltx-2-19b-distilled:fp8".to_string();
        req.output_format = Some(OutputFormat::Mp4);
        req.frames = Some(193);

        req.fps = Some(24);
        assert!(validate_generate_request(&req).is_ok());

        req.fps = Some(6);
        let err = validate_generate_request(&req).unwrap_err();
        // 20s at 6 fps is 124 frames; 121 is that budget on the 8n+1 grid.
        assert!(err.contains("121"), "got: {err}");
    }

    #[test]
    fn ltx2_absolute_frame_guard_binds_above_thirty_fps() {
        let mut req = valid_req();
        req.model = "ltx-2.3-22b-distilled:fp8".to_string();
        req.output_format = Some(OutputFormat::Mp4);
        req.fps = Some(120);
        req.frames = Some(609); // first 8n+1 value past the 604-frame guard
        let err = validate_generate_request(&req).unwrap_err();
        // The absolute guard binds here, quoted on the 8n+1 grid (604 -> 601).
        assert!(
            err.contains(&ltx2_max_frames_on_grid_at_fps(120).to_string()),
            "got: {err}"
        );
        assert_eq!(ltx2_max_frames_on_grid_at_fps(120), 601);
    }

    #[test]
    fn ltx_video_family_is_not_subject_to_the_ltx2_rope_cap() {
        let mut req = valid_req();
        req.model = "ltx-video-0.9.6-distilled:bf16".to_string();
        req.output_format = Some(OutputFormat::Mp4);
        req.frames = Some(161);
        assert!(validate_generate_request(&req).is_ok());
    }

    /// `ltx-video` keeps the flat global ceiling; only `ltx2` publishes a
    /// duration budget, so the two families must not share a cap.
    #[test]
    fn ltx_video_keeps_the_flat_global_ceiling() {
        let mut req = valid_req();
        req.model = "ltx-video-0.9.6-distilled:bf16".to_string();
        req.output_format = Some(OutputFormat::Mp4);
        req.fps = Some(30);
        req.frames = Some(MAX_FRAMES_GLOBAL + 8);
        let err = validate_generate_request(&req).unwrap_err();
        assert!(err.contains(&MAX_FRAMES_GLOBAL.to_string()), "got: {err}");
    }

    /// `derive_stage1_render_shape` halves the frame count *and* the fps, so an
    /// x2 temporal upscale renders the same runtime — it never buys duration.
    #[test]
    fn ltx2_temporal_upscale_x2_does_not_extend_the_duration_budget() {
        let mut req = valid_req();
        req.model = "ltx-2-19b-distilled:fp8".to_string();
        req.output_format = Some(OutputFormat::Mp4);
        req.fps = Some(24);
        req.temporal_upscale = Some(crate::Ltx2TemporalUpscale::X2);

        // stage 1 = (481-1)/2+1 = 241 frames at 12 fps, ceiling 244 → fits.
        req.frames = Some(481);
        assert!(validate_generate_request(&req).is_ok());

        // 20.4s of runtime is over budget with or without temporal upscaling.
        req.frames = Some(497);
        let err = validate_generate_request(&req).unwrap_err();
        assert!(err.contains("RoPE"), "got: {err}");
    }

    #[test]
    fn non_ltx_models_do_not_apply_the_ltx_frame_grid_rule() {
        let mut req = valid_req();
        req.frames = Some(10);
        assert!(validate_generate_request(&req).is_ok());
    }

    #[test]
    fn zero_batch_rejected() {
        let mut req = valid_req();
        req.batch_size = 0;
        assert!(validate_generate_request(&req).is_err());
    }

    #[test]
    fn large_batch_accepted() {
        let mut req = valid_req();
        req.batch_size = 100;
        assert!(validate_generate_request(&req).is_ok());
    }

    #[test]
    fn negative_guidance_rejected() {
        let mut req = valid_req();
        req.guidance = -1.0;
        assert!(validate_generate_request(&req).is_err());
    }

    #[test]
    fn zero_guidance_valid() {
        let mut req = valid_req();
        req.guidance = 0.0;
        assert!(validate_generate_request(&req).is_ok());
    }

    #[test]
    fn high_guidance_valid() {
        let mut req = valid_req();
        req.guidance = 20.0;
        assert!(validate_generate_request(&req).is_ok());
    }

    #[test]
    fn guidance_over_100_rejected() {
        let mut req = valid_req();
        req.guidance = 100.1;
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("guidance"));
    }

    #[test]
    fn guidance_at_100_valid() {
        let mut req = valid_req();
        req.guidance = 100.0;
        assert!(validate_generate_request(&req).is_ok());
    }

    #[test]
    fn prompt_too_long_rejected() {
        let mut req = valid_req();
        req.prompt = "x".repeat(77_001);
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("77,000"));
    }

    #[test]
    fn prompt_at_limit_valid() {
        let mut req = valid_req();
        req.prompt = "x".repeat(77_000);
        assert!(validate_generate_request(&req).is_ok());
    }

    #[test]
    fn negative_prompt_too_long_rejected() {
        let mut req = valid_req();
        req.negative_prompt = Some("x".repeat(77_001));
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("negative_prompt"));
    }

    #[test]
    fn negative_prompt_at_limit_valid() {
        let mut req = valid_req();
        req.negative_prompt = Some("x".repeat(77_000));
        assert!(validate_generate_request(&req).is_ok());
    }

    #[test]
    fn negative_prompt_none_valid() {
        let req = valid_req();
        assert!(req.negative_prompt.is_none());
        assert!(validate_generate_request(&req).is_ok());
    }

    #[test]
    fn negative_prompt_empty_valid() {
        let mut req = valid_req();
        req.negative_prompt = Some(String::new());
        assert!(validate_generate_request(&req).is_ok());
    }

    #[test]
    fn seed_is_optional() {
        let mut req = valid_req();
        req.seed = None;
        assert!(validate_generate_request(&req).is_ok());
    }

    // ── img2img validation tests ────────────────────────────────────────────

    #[test]
    fn img2img_strength_zero_accepted() {
        let mut req = valid_req();
        req.source_image = Some(png_bytes());
        req.strength = 0.0;
        assert!(validate_generate_request(&req).is_ok());
    }

    #[test]
    fn img2img_strength_negative_rejected() {
        let mut req = valid_req();
        req.source_image = Some(png_bytes());
        req.strength = -0.1;
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("strength"));
    }

    #[test]
    fn img2img_strength_one_accepted() {
        let mut req = valid_req();
        req.source_image = Some(png_bytes());
        req.strength = 1.0;
        assert!(validate_generate_request(&req).is_ok());
    }

    #[test]
    fn img2img_strength_half_accepted() {
        let mut req = valid_req();
        req.source_image = Some(png_bytes());
        req.strength = 0.5;
        assert!(validate_generate_request(&req).is_ok());
    }

    #[test]
    fn img2img_invalid_magic_bytes_rejected() {
        let mut req = valid_req();
        req.source_image = Some(vec![0x00, 0x01, 0x02, 0x03]);
        req.strength = 0.75;
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("PNG or JPEG"));
    }

    #[test]
    fn img2img_jpeg_accepted() {
        let mut req = valid_req();
        req.source_image = Some(jpeg_bytes());
        req.strength = 0.75;
        assert!(validate_generate_request(&req).is_ok());
    }

    #[test]
    fn img2img_no_source_image_skips_strength_check() {
        let mut req = valid_req();
        req.source_image = None;
        req.strength = 0.0; // Would fail if source_image present, but should pass without
        assert!(validate_generate_request(&req).is_ok());
    }

    #[test]
    fn qwen_image_edit_requires_edit_images() {
        let mut req = valid_req();
        req.model = "qwen-image-edit:q4".to_string();
        let err = validate_generate_request(&req).unwrap_err();
        assert_eq!(
            err,
            "Qwen Image Edit needs at least one image. Add a Target image and try again."
        );
    }

    #[test]
    fn qwen_image_edit_rejects_batch_size_above_one() {
        let mut req = valid_req();
        req.model = "qwen-image-edit:q4".to_string();
        req.edit_images = Some(vec![png_bytes()]);
        req.batch_size = 2;
        let err = validate_generate_request(&req).unwrap_err();
        assert!(err.contains("batch_size = 1"), "got: {err}");
    }

    #[test]
    fn qwen_image_edit_accepts_edit_images() {
        let mut req = valid_req();
        req.model = "qwen-image-edit:q4".to_string();
        req.edit_images = Some(vec![png_bytes()]);
        req.guidance = 4.0;
        assert!(validate_generate_request(&req).is_ok());
    }

    #[test]
    fn flux2_dev_accepts_text_only_and_ordered_references() {
        let mut req = valid_req();
        req.model = "flux2-dev:bf16".to_string();
        req.guidance = 4.0;
        assert!(validate_generate_request(&req).is_ok());

        req.edit_images = Some(vec![png_bytes(), jpeg_bytes()]);
        assert!(validate_generate_request(&req).is_ok());
    }

    #[test]
    fn flux2_dev_catalog_id_accepts_references_but_rejects_img2img_fields() {
        let mut req = valid_req();
        req.model = "hf:black-forest-labs/FLUX.2-dev".to_string();
        req.edit_images = Some(vec![png_bytes()]);
        assert!(validate_generate_request_with_family(&req, Some("flux2")).is_ok());

        req.source_image = Some(png_bytes());
        let error = validate_generate_request_with_family(&req, Some("flux2")).unwrap_err();
        assert!(error.contains("edit_images instead of source_image"));
    }

    #[test]
    fn flux2_dev_bounds_reference_count_and_rejects_lora() {
        let mut req = valid_req();
        req.model = "flux2-dev:bf16".to_string();
        req.edit_images = Some(vec![png_bytes(); FLUX2_DEV_MAX_REFERENCE_IMAGES + 1]);
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("at most"));

        req.edit_images = None;
        req.lora = Some(LoraWeight {
            path: "adapter.safetensors".into(),
            scale: 1.0,
        });
        assert_eq!(
            validate_generate_request(&req).unwrap_err(),
            "flux2-dev does not support LoRA"
        );
    }

    #[test]
    fn qwen_image_edit_rejects_source_image_field() {
        let mut req = valid_req();
        req.model = "qwen-image-edit:q4".to_string();
        req.edit_images = Some(vec![png_bytes()]);
        req.source_image = Some(png_bytes());
        let err = validate_generate_request(&req).unwrap_err();
        assert!(
            err.contains("edit_images instead of source_image"),
            "got: {err}"
        );
    }

    #[test]
    fn non_edit_models_reject_edit_images() {
        let mut req = valid_req();
        req.model = "flux-schnell:q8".to_string();
        req.edit_images = Some(vec![png_bytes()]);
        let err = validate_generate_request(&req).unwrap_err();
        assert!(
            err.contains("only supported for qwen-image-edit"),
            "got: {err}"
        );
    }

    #[test]
    fn non_edit_models_reject_edit_images_before_format_validation() {
        let mut req = valid_req();
        req.model = "flux-schnell:q8".to_string();
        req.edit_images = Some(vec![b"not-an-image".to_vec()]);
        let err = validate_generate_request(&req).unwrap_err();
        assert!(
            err.contains("only supported for qwen-image-edit"),
            "got: {err}"
        );
    }

    // ── ControlNet validation tests ────────────────────────────────────────

    #[test]
    fn controlnet_valid_request() {
        let mut req = valid_req();
        req.model = "dreamshaper-v8:fp16".to_string();
        req.control_image = Some(png_bytes());
        req.control_model = Some("controlnet-canny-sd15".to_string());
        req.control_scale = 0.8;
        assert!(validate_generate_request(&req).is_ok());
    }

    #[test]
    fn controlnet_image_without_model_rejected() {
        let mut req = valid_req();
        req.model = "dreamshaper-v8:fp16".to_string();
        req.control_image = Some(png_bytes());
        req.control_model = None;
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("control_model"));
    }

    #[test]
    fn controlnet_model_without_image_rejected() {
        let mut req = valid_req();
        req.model = "dreamshaper-v8:fp16".to_string();
        req.control_image = None;
        req.control_model = Some("controlnet-canny-sd15".to_string());
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("control_image"));
    }

    #[test]
    fn controlnet_invalid_image_rejected() {
        let mut req = valid_req();
        req.model = "dreamshaper-v8:fp16".to_string();
        req.control_image = Some(vec![0x00, 0x01, 0x02, 0x03]);
        req.control_model = Some("controlnet-canny-sd15".to_string());
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("PNG or JPEG"));
    }

    #[test]
    fn controlnet_negative_scale_rejected() {
        let mut req = valid_req();
        req.model = "dreamshaper-v8:fp16".to_string();
        req.control_image = Some(png_bytes());
        req.control_model = Some("controlnet-canny-sd15".to_string());
        req.control_scale = -0.1;
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("control_scale"));
    }

    #[test]
    fn controlnet_zero_scale_accepted() {
        let mut req = valid_req();
        req.model = "dreamshaper-v8:fp16".to_string();
        req.control_image = Some(png_bytes());
        req.control_model = Some("controlnet-canny-sd15".to_string());
        req.control_scale = 0.0;
        assert!(validate_generate_request(&req).is_ok());
    }

    #[test]
    fn controlnet_high_scale_accepted() {
        let mut req = valid_req();
        req.model = "dreamshaper-v8:fp16".to_string();
        req.control_image = Some(png_bytes());
        req.control_model = Some("controlnet-canny-sd15".to_string());
        req.control_scale = 2.0;
        assert!(validate_generate_request(&req).is_ok());
    }

    #[test]
    fn controlnet_jpeg_accepted() {
        let mut req = valid_req();
        req.model = "dreamshaper-v8:fp16".to_string();
        req.control_image = Some(jpeg_bytes());
        req.control_model = Some("controlnet-canny-sd15".to_string());
        assert!(validate_generate_request(&req).is_ok());
    }

    #[test]
    fn controlnet_rejected_for_non_sd15_family() {
        let mut req = valid_req();
        req.model = "sdxl:fp16".to_string();
        req.control_image = Some(png_bytes());
        req.control_model = Some("controlnet-canny-sd15".to_string());

        let err = validate_generate_request(&req).unwrap_err();
        assert!(err.contains("SD1.5"), "got: {err}");
    }
    // ── Inpainting validation tests ───────────────────────────────────────

    #[test]
    fn mask_without_source_image_rejected() {
        let mut req = valid_req();
        req.mask_image = Some(png_bytes());
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("mask_image requires source_image"));
    }

    #[test]
    fn mask_with_source_image_accepted() {
        let mut req = valid_req();
        req.source_image = Some(png_bytes());
        req.mask_image = Some(png_bytes());
        assert!(validate_generate_request(&req).is_ok());
    }

    #[test]
    fn mask_jpeg_accepted() {
        let mut req = valid_req();
        req.source_image = Some(png_bytes());
        req.mask_image = Some(jpeg_bytes());
        assert!(validate_generate_request(&req).is_ok());
    }

    #[test]
    fn mask_invalid_bytes_rejected() {
        let mut req = valid_req();
        req.source_image = Some(png_bytes());
        req.mask_image = Some(vec![0x00, 0x01, 0x02, 0x03]);
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("mask_image must be a PNG or JPEG"));
    }

    #[test]
    fn no_mask_no_source_passes() {
        let req = valid_req();
        assert!(validate_generate_request(&req).is_ok());
    }

    // ── fit_to_model_dimensions tests ────────────────────────────────────

    #[test]
    fn fit_same_aspect_downscale() {
        // 1024x1024 source -> 512x512 SD1.5 model
        assert_eq!(fit_to_model_dimensions(1024, 1024, 512, 512), (512, 512));
    }

    #[test]
    fn fit_wide_source_downscale() {
        // 1920x1080 source -> 512x512 SD1.5 model
        // width-limited: w=512, h=512/1.778=287.9 -> 288 (16px aligned)
        assert_eq!(fit_to_model_dimensions(1920, 1080, 512, 512), (512, 288));
    }

    #[test]
    fn fit_small_source_upscale_to_model_native() {
        // 512x512 source -> 1024x1024 FLUX model (upscale to native)
        assert_eq!(fit_to_model_dimensions(512, 512, 1024, 1024), (1024, 1024));
    }

    #[test]
    fn fit_portrait_source() {
        // 768x1024 source -> 512x512 model
        // height-limited: h=512, w=512*0.75=384
        assert_eq!(fit_to_model_dimensions(768, 1024, 512, 512), (384, 512));
    }

    #[test]
    fn fit_identity() {
        assert_eq!(
            fit_to_model_dimensions(1024, 1024, 1024, 1024),
            (1024, 1024)
        );
    }

    #[test]
    fn fit_extreme_landscape() {
        // 3840x720 -> 1024x1024 model
        // width-limited: w=1024, h=1024/5.333=192
        assert_eq!(fit_to_model_dimensions(3840, 720, 1024, 1024), (1024, 192));
    }

    #[test]
    fn fit_non_square_model_bounds() {
        // 1920x1080 -> 1024x768 model
        // src_ratio=1.778, model_ratio=1.333, width-limited: w=1024, h=1024/1.778=575.8 -> 576
        assert_eq!(fit_to_model_dimensions(1920, 1080, 1024, 768), (1024, 576));
    }

    #[test]
    fn fit_dimensions_are_16px_aligned() {
        let (w, h) = fit_to_model_dimensions(1000, 600, 512, 512);
        assert!(w % 16 == 0, "width {w} must be 16px aligned");
        assert!(h % 16 == 0, "height {h} must be 16px aligned");
    }

    #[test]
    fn fit_within_megapixel_limit() {
        let (w, h) = fit_to_model_dimensions(4096, 4096, 2048, 2048);
        let pixels = w as u64 * h as u64;
        assert!(
            pixels <= MAX_PIXELS,
            "{}x{} = {} pixels exceeds limit",
            w,
            h,
            pixels
        );
    }

    #[test]
    fn fit_tiny_source_gets_model_native() {
        // 64x64 source -> 1024x1024 model
        assert_eq!(fit_to_model_dimensions(64, 64, 1024, 1024), (1024, 1024));
    }

    #[test]
    fn fit_to_target_area_preserves_ratio_and_alignment() {
        let (w, h) = fit_to_target_area(1600, 900, 1024 * 1024, 16);
        assert_eq!((w, h), (1360, 768));
    }

    // ── LoRA validation tests ──────────────────────────────────────────────

    /// Build a FLUX-model request — the only family that supports LoRAs
    /// today. Tests that exercise LoRA value-validation (scale, extension)
    /// must use a LoRA-capable family or they fail on the upstream
    /// family-gate before the value check can trip.
    fn valid_flux_req() -> GenerateRequest {
        GenerateRequest {
            model: "flux-dev".to_string(),
            ..valid_req()
        }
    }

    #[test]
    fn lora_none_valid() {
        let req = valid_req();
        assert!(req.lora.is_none());
        assert!(validate_generate_request(&req).is_ok());
    }

    #[test]
    fn lora_scale_too_low_rejected() {
        let mut req = valid_flux_req();
        req.lora = Some(crate::LoraWeight {
            path: "adapter.safetensors".to_string(),
            scale: -0.1,
        });
        let err = validate_generate_request(&req).unwrap_err();
        assert!(
            err.contains("lora scale"),
            "expected lora scale error: {err}"
        );
    }

    #[test]
    fn lora_scale_too_high_rejected() {
        let mut req = valid_flux_req();
        req.lora = Some(crate::LoraWeight {
            path: "adapter.safetensors".to_string(),
            scale: 2.1,
        });
        let err = validate_generate_request(&req).unwrap_err();
        assert!(
            err.contains("lora scale"),
            "expected lora scale error: {err}"
        );
    }

    #[test]
    fn lora_scale_boundary_valid() {
        for scale in [0.0, 1.0, 2.0] {
            let mut req = valid_flux_req();
            req.lora = Some(crate::LoraWeight {
                path: "adapter.safetensors".to_string(),
                scale,
            });
            assert!(
                validate_generate_request(&req).is_ok(),
                "scale={scale} should be valid"
            );
        }
    }

    #[test]
    fn lora_path_not_found_passes_validation() {
        // Path existence is checked at the inference layer, not validation,
        // so remote LoRA paths (server-side files) work correctly.
        let mut req = valid_flux_req();
        req.lora = Some(crate::LoraWeight {
            path: "/nonexistent/path/adapter.safetensors".to_string(),
            scale: 1.0,
        });
        assert!(validate_generate_request(&req).is_ok());
    }

    #[test]
    fn lora_wrong_extension_rejected() {
        let mut req = valid_flux_req();
        req.lora = Some(crate::LoraWeight {
            path: "/some/path/adapter.bin".to_string(),
            scale: 1.0,
        });
        let err = validate_generate_request(&req).unwrap_err();
        assert!(
            err.contains("safetensors"),
            "expected safetensors error: {err}"
        );
    }

    fn valid_sdxl_req() -> GenerateRequest {
        // Pick a real manifest-known SDXL name so `model_family` resolves to
        // `sdxl`. The test surface mirrors `valid_flux_req` / `valid_ltx2_req`.
        GenerateRequest {
            model: "sdxl-base:fp16".to_string(),
            ..valid_req()
        }
    }

    /// SDXL gained LoRA support in Wave 1 of the LoRA-all-families work —
    /// `mold-inference::sdxl::lora` wraps the UNet `VarBuilder` with an
    /// `SdxlLoraBackend` that merges `W' = W + scale·(B @ A)` on the fly.
    /// The validator must now accept LoRAs on SDXL.
    #[test]
    fn lora_on_sdxl_accepted() {
        let mut req = valid_sdxl_req();
        req.lora = Some(crate::LoraWeight {
            path: "adapter.safetensors".to_string(),
            scale: 1.0,
        });
        assert!(
            validate_generate_request(&req).is_ok(),
            "SDXL + LoRA must pass validation now that sdxl/lora.rs is live"
        );
    }

    #[test]
    fn loras_plural_on_sdxl_accepted() {
        let mut req = valid_sdxl_req();
        req.loras = Some(vec![
            crate::LoraWeight {
                path: "a.safetensors".to_string(),
                scale: 0.8,
            },
            crate::LoraWeight {
                path: "b.safetensors".to_string(),
                scale: 0.4,
            },
        ]);
        assert!(
            validate_generate_request(&req).is_ok(),
            "SDXL + plural LoRAs (multi-LoRA stack) must pass validation"
        );
    }

    #[test]
    fn loras_plural_on_flux_valid() {
        // Multi-LoRA is supported on FLUX. The validator must not block
        // the plural form just because the singular form already gates.
        let mut req = valid_flux_req();
        req.loras = Some(vec![
            crate::LoraWeight {
                path: "a.safetensors".into(),
                scale: 0.8,
            },
            crate::LoraWeight {
                path: "b.safetensors".into(),
                scale: 0.4,
            },
        ]);
        assert!(validate_generate_request(&req).is_ok());
    }

    fn valid_ltx2_req() -> GenerateRequest {
        GenerateRequest {
            model: "ltx-2-19b-distilled:fp8".to_string(),
            output_format: Some(OutputFormat::Mp4),
            ..valid_req()
        }
    }

    #[test]
    fn lora_on_ltx2_accepted() {
        // LTX-2 has a full LoRA engine path (ltx2/lora.rs) — the validator
        // must not block it.
        let mut req = valid_ltx2_req();
        req.lora = Some(crate::LoraWeight {
            path: "LTX2.3_Crisp_Enhance.safetensors".to_string(),
            scale: 1.0,
        });
        assert!(
            validate_generate_request(&req).is_ok(),
            "LTX-2 + LoRA must pass validation"
        );
    }

    #[test]
    fn loras_plural_on_ltx2_accepted() {
        // The loras-plural path routes through the same gate; confirm LTX-2
        // passes there too.
        let mut req = valid_ltx2_req();
        req.loras = Some(vec![
            crate::LoraWeight {
                path: "a.safetensors".into(),
                scale: 0.8,
            },
            crate::LoraWeight {
                path: "b.safetensors".into(),
                scale: 0.4,
            },
        ]);
        assert!(
            validate_generate_request(&req).is_ok(),
            "LTX-2 + loras plural must pass validation"
        );
    }

    fn valid_zimage_req() -> GenerateRequest {
        GenerateRequest {
            model: "z-image-turbo:bf16".to_string(),
            ..valid_req()
        }
    }

    fn valid_sd3_req() -> GenerateRequest {
        GenerateRequest {
            model: "sd3.5-large".to_string(),
            ..valid_req()
        }
    }

    #[test]
    fn lora_on_sd3_accepted() {
        // SD3.5 has a full LoRA engine path (sd3/lora.rs) — the validator
        // must not block it.
        let mut req = valid_sd3_req();
        req.lora = Some(crate::LoraWeight {
            path: "sd35_style.safetensors".to_string(),
            scale: 1.0,
        });
        assert!(
            validate_generate_request(&req).is_ok(),
            "SD3 + LoRA must pass validation: {:?}",
            validate_generate_request(&req)
        );
    }

    #[test]
    fn loras_plural_on_sd3_accepted() {
        let mut req = valid_sd3_req();
        req.loras = Some(vec![
            crate::LoraWeight {
                path: "a.safetensors".into(),
                scale: 0.8,
            },
            crate::LoraWeight {
                path: "b.safetensors".into(),
                scale: 0.4,
            },
        ]);
        assert!(
            validate_generate_request(&req).is_ok(),
            "SD3 + loras plural must pass validation"
        );
    }

    #[test]
    fn lora_rejection_message_lists_sd3() {
        // The rejection message must enumerate every supported family.
        // wuerstchen has no LoRA path so the request is rejected; the message
        // must include SD3 in the supported list.
        let mut req = valid_req();
        req.model = "wuerstchen-c".to_string();
        req.lora = Some(crate::LoraWeight {
            path: "adapter.safetensors".to_string(),
            scale: 1.0,
        });
        let err = validate_generate_request(&req).unwrap_err();
        assert!(
            err.to_lowercase().contains("sd3"),
            "rejection message must list SD3 alongside FLUX/LTX-2: {err}"
        );
    }

    #[test]
    fn lora_on_zimage_accepted() {
        // Z-Image grew a LoRA engine path (zimage/lora.rs) — the validator
        // must let it through.
        let mut req = valid_zimage_req();
        req.lora = Some(crate::LoraWeight {
            path: "NSFW_master_ZIT_000017532.safetensors".to_string(),
            scale: 1.0,
        });
        assert!(
            validate_generate_request(&req).is_ok(),
            "Z-Image + LoRA must pass validation"
        );
    }

    #[test]
    fn loras_plural_on_zimage_accepted() {
        let mut req = valid_zimage_req();
        req.loras = Some(vec![
            crate::LoraWeight {
                path: "a.safetensors".into(),
                scale: 0.8,
            },
            crate::LoraWeight {
                path: "b.safetensors".into(),
                scale: 0.4,
            },
        ]);
        assert!(
            validate_generate_request(&req).is_ok(),
            "Z-Image + loras plural must pass validation"
        );
    }

    #[test]
    fn lora_on_flux2_accepted() {
        // Flux.2 has a full LoRA engine path (flux2/lora.rs) — the validator
        // must not block it. The validator only sees the family resolved
        // from the model name; Flux.2 LoRAs from Civitai (cv:2682864 and
        // siblings) reach this code via the `family_hint` carried by the
        // catalog, but a stable model name like `flux2-klein` works the
        // same way.
        let mut req = valid_req();
        req.model = "flux2-klein".to_string();
        req.lora = Some(crate::LoraWeight {
            path: "DarkKlein9b.safetensors".to_string(),
            scale: 1.0,
        });
        assert!(
            validate_generate_request(&req).is_ok(),
            "Flux.2 + LoRA must pass validation"
        );
    }

    #[test]
    fn loras_plural_on_flux2_accepted() {
        // The plural loras stack must also pass on Flux.2.
        let mut req = valid_req();
        req.model = "flux2-klein-9b".to_string();
        req.loras = Some(vec![
            crate::LoraWeight {
                path: "lora-a.safetensors".into(),
                scale: 0.8,
            },
            crate::LoraWeight {
                path: "lora-b.safetensors".into(),
                scale: 0.4,
            },
        ]);
        assert!(
            validate_generate_request(&req).is_ok(),
            "Flux.2 + loras plural must pass validation"
        );
    }

    #[test]
    fn lora_on_unsupported_family_lists_sdxl_in_message() {
        // SD3 / Qwen-Image still lack a LoRA engine path. The validator must
        // reject and the message must enumerate every supported family so
        // the user knows what to pick instead.
        let mut req = valid_req();
        req.model = "wuerstchen-c".to_string();
        req.lora = Some(crate::LoraWeight {
            path: "adapter.safetensors".to_string(),
            scale: 1.0,
        });
        let err = validate_generate_request(&req).unwrap_err();
        assert!(
            err.to_lowercase().contains("flux"),
            "error must mention FLUX: {err}"
        );
        assert!(
            err.to_lowercase().contains("flux.2") || err.to_lowercase().contains("flux2"),
            "error must mention Flux.2: {err}"
        );
        assert!(
            err.to_lowercase().contains("ltx-2") || err.to_lowercase().contains("ltx2"),
            "error must mention LTX-2: {err}"
        );
        assert!(
            err.to_lowercase().contains("sdxl"),
            "error must mention SDXL: {err}"
        );
        assert!(
            err.to_lowercase().contains("qwen-image"),
            "error must mention Qwen-Image: {err}"
        );
    }

    /// Qwen-Image gained LoRA support in feat/lora-all-families. The
    /// validator must let `qwen-image` through.
    #[test]
    fn lora_on_qwen_image_accepted() {
        let mut req = valid_req();
        req.model = "qwen-image-2512".to_string();
        req.lora = Some(crate::LoraWeight {
            path: "adapter.safetensors".to_string(),
            scale: 1.0,
        });
        assert!(
            validate_generate_request(&req).is_ok(),
            "Qwen-Image + LoRA must pass validation",
        );
    }

    /// `qwen-image-edit` shares the LoRA family gate with `qwen-image`.
    /// The edit family also requires a target image separately, so this
    /// test exercises just the LoRA gate by inspecting the rejection
    /// message: it must NOT mention LoRA when the only non-LoRA failure
    /// is the missing target image.
    #[test]
    fn lora_on_qwen_image_edit_passes_lora_gate() {
        let mut req = valid_req();
        req.model = "qwen-image-edit-2511:q4".to_string();
        req.lora = Some(crate::LoraWeight {
            path: "adapter.safetensors".to_string(),
            scale: 1.0,
        });
        // The request fails on its target-image requirement, but the
        // LoRA gate is permissive.
        let err = validate_generate_request(&req).unwrap_err();
        assert!(
            !err.to_lowercase().contains("lora"),
            "LoRA gate must not reject qwen-image-edit; remaining failure should be on the target image: {err}",
        );
        assert!(
            err.contains("Add a Target image"),
            "expected the only failure to be the target-image requirement: {err}",
        );
    }

    #[test]
    fn loras_plural_on_qwen_image_accepted() {
        let mut req = valid_req();
        req.model = "qwen-image-2512".to_string();
        req.loras = Some(vec![
            crate::LoraWeight {
                path: "a.safetensors".into(),
                scale: 0.8,
            },
            crate::LoraWeight {
                path: "b.safetensors".into(),
                scale: 0.4,
            },
        ]);
        assert!(
            validate_generate_request(&req).is_ok(),
            "Qwen-Image + multi-LoRA must pass validation",
        );
    }

    #[test]
    fn lora_on_unknown_family_still_rejected() {
        // family: None (no manifest match) must still produce an error.
        let mut req = valid_req();
        req.model = "some-unknown-model-xyz".to_string();
        req.lora = Some(crate::LoraWeight {
            path: "adapter.safetensors".to_string(),
            scale: 1.0,
        });
        let err = validate_generate_request(&req).unwrap_err();
        assert!(
            !err.is_empty(),
            "unknown family with LoRA must produce an error: {err}"
        );
    }

    /// SD1.5 LoRA support landed in `crates/mold-inference/src/sd15/lora.rs` —
    /// the validator must accept it, just like FLUX and LTX-2.
    #[test]
    fn lora_on_sd15_accepted() {
        let mut req = valid_req();
        req.model = "sd15:fp16".to_string();
        req.width = 512;
        req.height = 512;
        req.guidance = 7.0;
        req.lora = Some(crate::LoraWeight {
            path: "adapter.safetensors".to_string(),
            scale: 0.8,
        });
        assert!(
            validate_generate_request(&req).is_ok(),
            "SD1.5 + LoRA must pass validation"
        );
    }

    /// The plural `loras` form must accept SD1.5 too — the gate must apply
    /// uniformly to both shapes.
    #[test]
    fn loras_plural_on_sd15_accepted() {
        let mut req = valid_req();
        req.model = "sd15:fp16".to_string();
        req.width = 512;
        req.height = 512;
        req.guidance = 7.0;
        req.loras = Some(vec![
            crate::LoraWeight {
                path: "a.safetensors".into(),
                scale: 0.8,
            },
            crate::LoraWeight {
                path: "b.safetensors".into(),
                scale: 0.4,
            },
        ]);
        assert!(
            validate_generate_request(&req).is_ok(),
            "SD1.5 + loras plural must pass validation"
        );
    }

    /// The rejection message lists every supported family; SDXL still isn't
    /// supported, so a SDXL request with a LoRA should mention SD1.5 in the
    /// list of available alternatives.
    #[test]
    fn lora_on_sdxl_message_now_lists_sd15() {
        let mut req = valid_req();
        req.model = "sdxl".to_string();
        req.lora = Some(crate::LoraWeight {
            path: "adapter.safetensors".to_string(),
            scale: 1.0,
        });
        let err = validate_generate_request(&req).unwrap_err();
        assert!(
            err.to_lowercase().contains("sd1.5")
                || err.to_lowercase().contains("sd15")
                || err.to_lowercase().contains("sd 1.5"),
            "error must list SD1.5 as a supported family: {err}"
        );
    }

    // ── dimension_warning tests ────────────────────────────────────────────

    #[test]
    fn dimension_warning_matching_returns_none() {
        assert!(dimension_warning(1024, 1024, "flux").is_none());
        assert!(dimension_warning(512, 512, "sd15").is_none());
        assert!(dimension_warning(1024, 1024, "sdxl").is_none());
        assert!(dimension_warning(1024, 1024, "wuerstchen").is_none());
    }

    #[test]
    fn dimension_warning_non_matching_returns_some() {
        let warning = dimension_warning(256, 256, "flux");
        assert!(warning.is_some());
        let msg = warning.unwrap();
        assert!(msg.contains("256x256"), "should mention requested dims");
        assert!(msg.contains("flux"), "should mention model family");
        assert!(msg.contains("Suggested"), "should include suggestions");
    }

    #[test]
    fn dimension_warning_unknown_family_returns_none() {
        assert!(dimension_warning(256, 256, "unknown-model").is_none());
    }

    #[test]
    fn dimension_warning_empty_family_returns_none() {
        assert!(dimension_warning(512, 512, "").is_none());
    }

    #[test]
    fn dimension_warning_sd15_at_1024_warns() {
        let warning = dimension_warning(1024, 1024, "sd15");
        assert!(warning.is_some(), "SD1.5 at 1024x1024 should warn");
        assert!(warning.unwrap().contains("512x512"));
    }

    #[test]
    fn dimension_warning_sdxl_buckets_accepted() {
        for (w, h) in recommended_dimensions("sdxl") {
            assert!(
                dimension_warning(*w, *h, "sdxl").is_none(),
                "SDXL bucket {w}x{h} should not warn"
            );
        }
    }

    #[test]
    fn dimension_warning_qwen_image_has_native_resolution() {
        let dims = recommended_dimensions("qwen-image");
        assert!(
            dims.contains(&(1328, 1328)),
            "must include native 1328x1328"
        );
        assert!(dims.contains(&(512, 512)), "must include 512x512");
        assert!(dims.contains(&(1024, 1024)), "must include 1024x1024");
        assert_eq!(dimension_warning(1328, 1328, "qwen-image"), None);
        assert_eq!(dimension_warning(512, 512, "qwen-image"), None);
    }

    #[test]
    fn dimension_warning_qwen_image_edit_reuses_qwen_dimensions() {
        assert_eq!(
            recommended_dimensions("qwen-image-edit"),
            recommended_dimensions("qwen-image")
        );
        assert_eq!(dimension_warning(1024, 1024, "qwen-image-edit"), None);
    }

    #[test]
    fn dimension_warning_flux2_uses_flux_dims() {
        assert_eq!(
            recommended_dimensions("flux2"),
            recommended_dimensions("flux"),
            "flux2 should share FLUX dimensions"
        );
    }

    #[test]
    fn every_family_native_in_recommendations() {
        // Each family's native resolution (from ManifestDefaults) should appear
        // in its recommended list.
        let families = &[
            ("sd15", 512, 512),
            ("sdxl", 1024, 1024),
            ("sd3", 1024, 1024),
            ("flux", 1024, 1024),
            ("flux2", 1024, 1024),
            ("z-image", 1024, 1024),
            ("qwen-image", 1024, 1024),
            ("qwen-image-edit", 1024, 1024),
            ("wuerstchen", 1024, 1024),
            ("ltx-video", 768, 512),
        ];
        for (family, w, h) in families {
            let dims = recommended_dimensions(family);
            assert!(
                dims.contains(&(*w, *h)),
                "{family} native {w}x{h} missing from recommended list"
            );
        }
    }

    #[test]
    fn dimension_warning_message_format() {
        let msg = dimension_warning(800, 600, "sd15").unwrap();
        assert!(msg.contains("800x600"));
        assert!(msg.contains("sd15"));
        assert!(msg.contains("Suggested:"));
        // Should list known alternatives
        assert!(msg.contains("512x512"));
    }

    #[test]
    fn dimension_warning_truncates_long_lists() {
        // SDXL has 9 buckets but warning should show at most 4 + "N total"
        let msg = dimension_warning(800, 600, "sdxl").unwrap();
        assert!(msg.contains("total"), "long lists should show total count");
    }

    // ── validate_upscale_request tests ────────────────────────────────────

    fn valid_upscale_req() -> crate::UpscaleRequest {
        crate::UpscaleRequest {
            model: "real-esrgan-x4plus:fp16".to_string(),
            image: png_bytes(),
            output_format: crate::OutputFormat::Png,
            tile_size: None,
            metadata: None,
        }
    }

    #[test]
    fn upscale_valid_request_passes() {
        assert!(validate_upscale_request(&valid_upscale_req()).is_ok());
    }

    #[test]
    fn upscale_empty_model_rejected() {
        let mut req = valid_upscale_req();
        req.model = "  ".to_string();
        assert!(validate_upscale_request(&req)
            .unwrap_err()
            .contains("model"));
    }

    #[test]
    fn upscale_empty_image_rejected() {
        let mut req = valid_upscale_req();
        req.image = vec![];
        assert!(validate_upscale_request(&req)
            .unwrap_err()
            .contains("empty"));
    }

    #[test]
    fn upscale_invalid_image_format_rejected() {
        let mut req = valid_upscale_req();
        req.image = vec![0x00, 0x01, 0x02, 0x03];
        assert!(validate_upscale_request(&req)
            .unwrap_err()
            .contains("PNG or JPEG"));
    }

    #[test]
    fn upscale_jpeg_accepted() {
        let mut req = valid_upscale_req();
        req.image = jpeg_bytes();
        assert!(validate_upscale_request(&req).is_ok());
    }

    #[test]
    fn upscale_tile_size_too_small_rejected() {
        let mut req = valid_upscale_req();
        req.tile_size = Some(32);
        assert!(validate_upscale_request(&req)
            .unwrap_err()
            .contains("tile_size"));
    }

    #[test]
    fn upscale_tile_size_zero_accepted() {
        let mut req = valid_upscale_req();
        req.tile_size = Some(0);
        assert!(validate_upscale_request(&req).is_ok());
    }

    #[test]
    fn upscale_tile_size_64_accepted() {
        let mut req = valid_upscale_req();
        req.tile_size = Some(64);
        assert!(validate_upscale_request(&req).is_ok());
    }

    #[test]
    fn upscale_tile_size_none_accepted() {
        let req = valid_upscale_req();
        assert!(validate_upscale_request(&req).is_ok());
    }

    #[test]
    fn built_in_ic_lora_control_requires_video_pipeline_and_reserves_a_stack_slot() {
        let mut req = valid_req();
        req.model = "ltx-2-19b-distilled:fp8".to_string();
        req.output_format = Some(crate::OutputFormat::Mp4);
        req.frames = Some(97);
        req.ic_lora_control = Some("union".to_string());
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("pipeline=ic-lora"));

        req.pipeline = Some(crate::Ltx2PipelineMode::IcLora);
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("source_video"));
        req.source_video_path = Some("/guides/canny.mp4".to_string());
        assert!(validate_generate_request(&req).is_ok());

        req.loras = Some(
            (0..4)
                .map(|index| crate::LoraWeight {
                    path: format!("/loras/{index}.safetensors"),
                    scale: 1.0,
                })
                .collect(),
        );
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("four-LoRA"));
    }

    // ── lip-dub ─────────────────────────────────────────────────────────────

    fn lip_dub_req() -> GenerateRequest {
        let mut req = valid_req();
        req.model = "ltx-2.3-22b-distilled:fp8".to_string();
        req.output_format = Some(OutputFormat::Mp4);
        req.width = 1216;
        req.height = 704;
        req.pipeline = Some(Ltx2PipelineMode::LipDub);
        req.ic_lora_control = Some("lipdub".to_string());
        req.source_video_path = Some("/clips/speaker.mp4".to_string());
        req
    }

    #[test]
    fn snap_frames_to_8k1_rounds_down_never_up() {
        // Exactly on the grid stays put.
        for on_grid in [1, 9, 17, 97, 121, 481] {
            assert_eq!(super::snap_frames_to_8k1(on_grid), on_grid);
        }
        // Everything between two grid points falls back to the lower one, so a
        // dub never asks for frames the reference video does not have.
        assert_eq!(super::snap_frames_to_8k1(2), 1);
        assert_eq!(super::snap_frames_to_8k1(8), 1);
        assert_eq!(super::snap_frames_to_8k1(16), 9);
        assert_eq!(super::snap_frames_to_8k1(96), 89);
        assert_eq!(super::snap_frames_to_8k1(100), 97);
        assert_eq!(super::snap_frames_to_8k1(0), 1);
        // The advertised LTX-2 ceiling is derived from the same snap.
        assert_eq!(super::ltx2_max_frames_on_grid_at_fps(24), 481);
    }

    /// A reference clip that could drive a dub, unless a test says otherwise.
    fn lip_dub_reference(frames: u32, fps: u32) -> super::LipDubReference {
        super::LipDubReference {
            frames,
            fps,
            has_audio: true,
        }
    }

    #[test]
    fn lip_dub_timing_comes_from_the_reference_video() {
        let timing = super::resolve_lip_dub_timing(lip_dub_reference(120, 25), None, None).unwrap();
        assert_eq!(timing.frames, 113);
        assert_eq!(timing.fps, 25);
        assert_eq!(timing.warnings.len(), 1, "{:?}", timing.warnings);
        assert!(timing.warnings[0].contains("113"));

        // Already on the grid at the requested values: nothing to say.
        let timing =
            super::resolve_lip_dub_timing(lip_dub_reference(97, 24), Some(97), Some(24)).unwrap();
        assert_eq!((timing.frames, timing.fps), (97, 24));
        assert!(timing.warnings.is_empty());
    }

    #[test]
    fn lip_dub_timing_overrides_and_reports_conflicting_requests() {
        let timing =
            super::resolve_lip_dub_timing(lip_dub_reference(97, 24), Some(241), Some(30)).unwrap();
        assert_eq!((timing.frames, timing.fps), (97, 24));
        assert_eq!(timing.warnings.len(), 2, "{:?}", timing.warnings);
        assert!(timing.warnings[0].contains("241") && timing.warnings[0].contains("97"));
        assert!(timing.warnings[1].contains("30") && timing.warnings[1].contains("24"));
    }

    #[test]
    fn lip_dub_timing_rejects_unusable_references() {
        assert!(
            super::resolve_lip_dub_timing(lip_dub_reference(97, 0), None, None)
                .unwrap_err()
                .contains("frame rate")
        );
        assert!(
            super::resolve_lip_dub_timing(lip_dub_reference(8, 24), None, None)
                .unwrap_err()
                .contains("too short")
        );
        // A silent reference is refused here, at the request boundary, rather
        // than minutes later when the audio VAE has nothing to encode.
        let silent = super::LipDubReference {
            has_audio: false,
            ..lip_dub_reference(97, 24)
        };
        assert!(super::resolve_lip_dub_timing(silent, None, None)
            .unwrap_err()
            .contains("no audio track"));
    }

    #[test]
    fn lip_dub_requires_a_reference_video_and_the_adapter() {
        let mut req = lip_dub_req();
        req.source_video_path = None;
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("source_video"));

        let mut req = lip_dub_req();
        req.ic_lora_control = None;
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("ic_lora_control=lipdub"));

        assert!(validate_generate_request(&lip_dub_req()).is_ok());
    }

    #[test]
    fn lip_dub_rejects_dimensions_that_are_not_multiples_of_64() {
        // 1216x704 is fine; 1216x736 is a multiple of 32 but not of 64, which
        // is exactly the case a one-stage-only check would let through.
        let mut req = lip_dub_req();
        req.height = 736;
        let err = validate_generate_request(&req).unwrap_err();
        assert!(err.contains("multiples of 64"), "{err}");

        let mut req = lip_dub_req();
        req.width = 1184;
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("multiples of 64"));
    }

    #[test]
    fn lip_dub_control_id_routes_to_the_lip_dub_pipeline_not_ic_lora() {
        use crate::ltx2_control::pipeline_for_control_id;
        assert_eq!(pipeline_for_control_id("lipdub"), Ltx2PipelineMode::LipDub);
        assert_eq!(pipeline_for_control_id("LipDub"), Ltx2PipelineMode::LipDub);
        assert_eq!(pipeline_for_control_id("union"), Ltx2PipelineMode::IcLora);

        // Asking for the lip-dub adapter on the generic in-context pipeline is
        // a mistake worth naming: the weights would load and the wrong graph
        // would run.
        let mut req = lip_dub_req();
        req.pipeline = Some(Ltx2PipelineMode::IcLora);
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("requires pipeline=lip-dub"));

        let mut req = lip_dub_req();
        req.ic_lora_control = Some("union".to_string());
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("requires pipeline=ic-lora"));
    }

    #[test]
    fn lip_dub_rejects_conflicting_conditioning_modes() {
        let mut req = lip_dub_req();
        req.retake_range = Some(crate::TimeRange {
            start_seconds: 0.0,
            end_seconds: 1.0,
        });
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("retake_range"));

        let mut req = lip_dub_req();
        req.keyframes = Some(vec![KeyframeCondition {
            frame: 0,
            image: png_bytes(),
        }]);
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("keyframes"));

        // Upscaling would change the output shape out from under the clip the
        // dub has to line up with.
        let mut req = lip_dub_req();
        req.spatial_upscale = Some(crate::Ltx2SpatialUpscale::X2);
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("spatial_upscale"));

        let mut req = lip_dub_req();
        req.temporal_upscale = Some(crate::Ltx2TemporalUpscale::X2);
        assert!(validate_generate_request(&req)
            .unwrap_err()
            .contains("temporal_upscale"));
    }
}