feldera-types 0.375.0

Public API types for Feldera
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
//! Controller configuration.
//!
//! This module defines the controller configuration structure.  The leaves of
//! this structure are individual transport-specific and data-format-specific
//! endpoint configs.  We represent these configs as opaque JSON values, so
//! that the entire configuration tree can be deserialized from a JSON file.

use crate::duration::ConfigDuration;
use crate::postprocess::PostprocessorConfig;
use crate::preprocess::PreprocessorConfig;
use crate::secret_ref::MaybeSecretRef;
use crate::secret_resolver::default_secrets_directory;
use crate::size::{ConfigSize, LegacySizeUnit};
use crate::transport::adhoc::AdHocInputConfig;
use crate::transport::clock::{ClockConfig, ClockTimezoneOffset};
use crate::transport::datagen::DatagenInputConfig;
use crate::transport::delta_table::{DeltaTableReaderConfig, DeltaTableWriterConfig};
use crate::transport::dynamodb::DynamoDBWriterConfig;
use crate::transport::file::{FileInputConfig, FileOutputConfig};
use crate::transport::http::{HttpInputConfig, HttpOutputConfig};
use crate::transport::iceberg::IcebergReaderConfig;
use crate::transport::kafka::{KafkaInputConfig, KafkaOutputConfig};
use crate::transport::nats::{NatsInputConfig, NatsOutputConfig};
use crate::transport::nexmark::NexmarkInputConfig;
use crate::transport::postgres::{
    PostgresCdcReaderConfig, PostgresReaderConfig, PostgresWriterConfig,
};
use crate::transport::pubsub::PubSubInputConfig;
use crate::transport::redis::RedisOutputConfig;
use crate::transport::s2::{S2InputConfig, S2OutputConfig};
use crate::transport::s3::S3InputConfig;
use crate::transport::url::UrlInputConfig;
use crate::{duration::LegacyUnit, duration_setting, nullable_duration_setting, size_setting};
use core::fmt;
use feldera_ir::{MirNode, MirNodeId};
use serde::de::{self, MapAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value as JsonValue;
use std::collections::HashMap;
use std::fmt::Display;
use std::path::Path;
use std::str::FromStr;
use std::time::Duration;
use std::{borrow::Cow, cmp::max, collections::BTreeMap};
use utoipa::ToSchema;
use utoipa::openapi::{ObjectBuilder, OneOfBuilder, Ref, RefOr, Schema, SchemaType};

pub mod dev_tweaks;
pub mod ignored;
pub use dev_tweaks::DevTweaks;

const DEFAULT_MAX_PARALLEL_CONNECTOR_INIT: u64 = 10;

/// Default maximum number of updates to be kept in the output buffer.
const DEFAULT_MAX_OUTPUT_BUFFER_SIZE_RECORDS: usize = 10_000_000;

/// Default value of `ConnectorConfig::max_queued_records`.
pub const fn default_max_queued_records() -> u64 {
    1_000_000
}

pub const DEFAULT_MAX_WORKER_BATCH_SIZE: u64 = 10_000;

/// Default resolution of the real-time clock that drives SQL `NOW()`.
pub const DEFAULT_CLOCK_RESOLUTION: ConfigDuration = ConfigDuration::from_secs(1);

/// Default interval between automatic checkpoints.
pub const DEFAULT_CHECKPOINT_INTERVAL: ConfigDuration = ConfigDuration::from_secs(60);

/// Default interval between standby checkpoint fetches.
pub const DEFAULT_PULL_INTERVAL: ConfigDuration = ConfigDuration::from_secs(10);

/// Default minimum age a checkpoint reaches before it may be deleted.
pub const DEFAULT_RETENTION_MIN_AGE: ConfigDuration = ConfigDuration::from_days(30);

// The defaults as the OpenAPI schema shows them, one function per
// `#[schema(default = ...)]`.
fn default_clock_resolution() -> String {
    DEFAULT_CLOCK_RESOLUTION.to_string()
}
fn default_checkpoint_interval() -> String {
    DEFAULT_CHECKPOINT_INTERVAL.to_string()
}
fn default_pull_interval() -> String {
    DEFAULT_PULL_INTERVAL.to_string()
}
fn default_retention_min_age() -> String {
    DEFAULT_RETENTION_MIN_AGE.to_string()
}

duration_setting!(
    duration_standby_pull_interval,
    "standby_pull_interval",
    LegacyUnit::Secs
);
duration_setting!(
    duration_checkpoint_push_interval,
    "checkpoint_push_interval",
    LegacyUnit::Secs
);
duration_setting!(duration_min_retention, "min_retention", LegacyUnit::Days);
duration_setting!(duration_ioop_latency, "ioop_latency", LegacyUnit::Millis);
duration_setting!(
    duration_max_buffering_delay,
    "max_buffering_delay",
    LegacyUnit::Micros
);
duration_setting!(
    duration_clock_resolution,
    "clock_resolution",
    LegacyUnit::Micros
);
duration_setting!(
    duration_provisioning_timeout,
    "provisioning_timeout",
    LegacyUnit::Secs
);
nullable_duration_setting!(
    duration_checkpoint_interval,
    "checkpoint_interval",
    LegacyUnit::Secs
);
duration_setting!(
    duration_max_output_buffer_time,
    "max_output_buffer_time",
    LegacyUnit::Millis
);
size_setting!(size_max_rss, "max_rss", LegacySizeUnit::Megabytes);
size_setting!(
    size_datafusion_memory,
    "datafusion_memory",
    LegacySizeUnit::Megabytes
);
size_setting!(size_cache_size, "cache_size", LegacySizeUnit::Mebibytes);
size_setting!(size_min_spill_size, "min_spill_size", LegacySizeUnit::Bytes);
size_setting!(
    size_min_step_spill_size,
    "min_step_spill_size",
    LegacySizeUnit::Bytes
);
size_setting!(size_memory_min, "memory_min", LegacySizeUnit::Megabytes);
size_setting!(size_memory_max, "memory_max", LegacySizeUnit::Megabytes);
size_setting!(size_storage_min, "storage_min", LegacySizeUnit::Megabytes);
size_setting!(size_storage_max, "storage_max", LegacySizeUnit::Megabytes);
size_setting!(
    size_scale_threshold_available,
    "scale_threshold_available",
    LegacySizeUnit::Megabytes
);
size_setting!(
    size_max_queued_size,
    "max_queued_size",
    LegacySizeUnit::Bytes
);

/// Program information included in the pipeline configuration.
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)]
pub struct ProgramIr {
    /// The MIR of the program.
    pub mir: HashMap<MirNodeId, MirNode>,
    /// Program schema.
    pub program_schema: serde_json::Value,
    /// The circuit IR (the compiler's JIT `allOperators` form) that the Gen-2
    /// engine lowers onto the runtime to build the circuit. `None` for
    /// Rust-compiled pipelines, whose circuit is statically linked into the binary.
    #[serde(default)]
    pub circuit_ir: Option<serde_json::Value>,
    /// The program's Rust UDFs compiled to a native shared library (a Linux `cdylib`), which
    /// the Gen-2 engine loads into its process. `None` when the program has no Rust UDFs, and
    /// for Rust-compiled pipelines, which link their UDFs into the binary.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub udf_library: Option<UdfLibrary>,
}

/// A program's UDF library, named by the same checksums as a pipeline binary.
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)]
pub struct UdfLibrary {
    /// Checksum of the sources the library was built from.
    pub source_checksum: String,
    /// sha256 checksum of the library file.
    pub integrity_checksum: String,
}

/// Identity of a pipeline, used to record and check ownership of an S3
/// checkpoint bucket.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PipelineIdentity {
    /// System-generated name of the pipeline (format `pipeline-<uuid>`).
    pub name: String,
    /// Name given to the pipeline by the tenant.
    pub given_name: Option<String>,
}

impl Display for PipelineIdentity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.given_name {
            Some(given_name) => write!(f, "{given_name} (id: {})", self.name),
            None => write!(f, "{}", self.name),
        }
    }
}

/// Pipeline deployment configuration.
/// It represents configuration entries directly provided by the user
/// (e.g., runtime configuration) and entries derived from the schema
/// of the compiled program (e.g., connectors). Storage configuration,
/// if applicable, is set by the runner.
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq)]
pub struct PipelineConfig {
    /// Global controller configuration.
    #[serde(flatten)]
    #[schema(inline)]
    pub global: RuntimeConfig,

    /// Configuration for multihost pipelines.
    ///
    /// The presence of this field indicates that the pipeline is running in
    /// multihost mode.  In the pod with ordinal 0, this triggers starting the
    /// coordinator process.  In all pods, this tells the pipeline process to
    /// await a connection from the coordinator instead of initializing the
    /// pipeline immediately.
    pub multihost: Option<MultihostConfig>,

    /// Unique system-generated name of the pipeline (format: `pipeline-<uuid>`).
    /// It is unique across all tenants and cannot be changed.
    ///
    /// The `<uuid>` is also used in the naming of various resources that back the pipeline,
    /// and as such this name is useful to find/identify corresponding resources.
    pub name: Option<String>,

    /// Name given by the tenant to the pipeline. It is only unique within the same tenant, and can
    /// be changed by the tenant when the pipeline is stopped.
    ///
    /// Given a specific tenant, it can be used to find/identify a specific pipeline of theirs.
    pub given_name: Option<String>,

    /// Configuration for persistent storage
    ///
    /// If `global.storage` is `Some(_)`, this field must be set to some
    /// [`StorageConfig`].  If `global.storage` is `None``, the pipeline ignores
    /// this field.
    #[serde(default)]
    pub storage_config: Option<StorageConfig>,

    /// Directory containing values of secrets.
    ///
    /// If this is not set, a default directory is used.
    pub secrets_dir: Option<String>,

    /// Input endpoint configuration.
    #[serde(default)]
    pub inputs: BTreeMap<Cow<'static, str>, InputEndpointConfig>,

    /// Output endpoint configuration.
    #[serde(default)]
    pub outputs: BTreeMap<Cow<'static, str>, OutputEndpointConfig>,

    /// Program information.
    #[serde(default)]
    pub program_ir: Option<ProgramIr>,
}

impl PipelineConfig {
    pub fn max_parallel_connector_init(&self) -> u64 {
        max(
            self.global
                .max_parallel_connector_init
                .unwrap_or(DEFAULT_MAX_PARALLEL_CONNECTOR_INIT),
            1,
        )
    }

    /// Extract the compiler-generated subset of the configuration (connectors
    /// and program IR) used to compute pipeline diffs.
    pub fn program_info_subset(&self) -> PipelineConfigProgramInfo {
        PipelineConfigProgramInfo {
            inputs: self.inputs.clone(),
            outputs: self.outputs.clone(),
            program_ir: self.program_ir.clone(),
        }
    }

    pub fn with_storage(self, storage: Option<(StorageConfig, StorageOptions)>) -> Self {
        let (storage_config, storage_options) = storage.unzip();
        Self {
            global: RuntimeConfig {
                storage: storage_options,
                ..self.global
            },
            storage_config,
            ..self
        }
    }

    pub fn storage(&self) -> Option<(&StorageConfig, &StorageOptions)> {
        let storage_options = self.global.storage.as_ref();
        let storage_config = self.storage_config.as_ref();
        storage_config.zip(storage_options)
    }

    /// Returns this pipeline's [`PipelineIdentity`], used to identify the
    /// pipeline that owns an S3 checkpoint bucket.
    ///
    /// Returns `None` when the pipeline has no system-generated [`name`](Self::name).
    pub fn pipeline_identity(&self) -> Option<PipelineIdentity> {
        self.name.as_ref().map(|name| PipelineIdentity {
            name: name.clone(),
            given_name: self.given_name.clone(),
        })
    }

    /// Returns `self.secrets_dir`, or the default secrets directory if it isn't
    /// set.
    pub fn secrets_dir(&self) -> &Path {
        match &self.secrets_dir {
            Some(dir) => Path::new(dir.as_str()),
            None => default_secrets_directory(),
        }
    }

    /// Abbreviated config that can be printed in the log on pipeline startup.
    pub fn display_summary(&self) -> String {
        // TODO: we may want to further abbreviate connector config.
        let summary = serde_json::json!({
            "name": self.name,
            "given_name": self.given_name,
            "global": self.global,
            "storage_config": self.storage_config,
            "secrets_dir": self.secrets_dir,
            "inputs": self.inputs,
            "outputs": self.outputs
        });

        serde_json::to_string_pretty(&summary).unwrap_or_else(|_| "{}".to_string())
    }
}

/// A subset of fields in `PipelineConfig` that are generated by the compiler.
/// These fields are shipped to the pipeline by the compilation server along with
/// the program binary.
// Note: An alternative would be to embed these fields in the program binary itself
// as static strings. This would work well for program IR, but it would require recompiling
// the program anytime a connector config changes, whereas today connector changes
// do not require recompilation.
#[derive(Default, Deserialize, Serialize, Eq, PartialEq, Debug, Clone)]
pub struct PipelineConfigProgramInfo {
    /// Input endpoint configuration.
    pub inputs: BTreeMap<Cow<'static, str>, InputEndpointConfig>,

    /// Output endpoint configuration.
    #[serde(default)]
    pub outputs: BTreeMap<Cow<'static, str>, OutputEndpointConfig>,

    /// Program information.
    #[serde(default)]
    pub program_ir: Option<ProgramIr>,
}

/// Configuration for a multihost Feldera pipeline.
///
/// This configuration is primarily for the coordinator.
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct MultihostConfig {
    /// Number of hosts to launch.
    ///
    /// For the configuration to be truly multihost, this should be at least 2.
    /// A value of 1 still runs the multihost coordinator but it only
    /// coordinates a single host.
    pub hosts: usize,
}

impl Default for MultihostConfig {
    fn default() -> Self {
        Self { hosts: 1 }
    }
}

/// Configuration for persistent storage in a [`PipelineConfig`].
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct StorageConfig {
    /// A directory to keep pipeline state, as a path on the filesystem of the
    /// machine or container where the pipeline will run.
    ///
    /// When storage is enabled, this directory stores the data for
    /// [StorageBackendConfig::Default].
    ///
    /// When fault tolerance is enabled, this directory stores checkpoints and
    /// the log.
    pub path: String,

    /// How to cache access to storage in this pipeline.
    #[serde(default)]
    pub cache: StorageCacheConfig,
}

impl StorageConfig {
    pub fn path(&self) -> &Path {
        Path::new(&self.path)
    }
}

/// How to cache access to storage within a Feldera pipeline.
#[derive(Copy, Clone, Default, Deserialize, Serialize, Debug, PartialEq, Eq, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum StorageCacheConfig {
    /// Use the operating system's page cache as the primary storage cache.
    ///
    /// This is the default because it currently performs better than
    /// `FelderaCache`.
    #[default]
    PageCache,

    /// Use Feldera's internal cache implementation.
    ///
    /// This is under development. It will become the default when its
    /// performance exceeds that of `PageCache`.
    FelderaCache,
}

impl StorageCacheConfig {
    #[cfg(unix)]
    pub fn to_custom_open_flags(&self) -> i32 {
        match self {
            StorageCacheConfig::PageCache => (),
            StorageCacheConfig::FelderaCache => {
                #[cfg(target_os = "linux")]
                return libc::O_DIRECT;
            }
        }
        0
    }
}

/// Storage configuration for a pipeline.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
#[serde(default)]
pub struct StorageOptions {
    /// How to connect to the underlying storage.
    pub backend: StorageBackendConfig,

    /// For a batch of data maintained as part of a persistent index during a
    /// pipeline run, the minimum estimated size to write it to storage, such
    /// as `"10Mi"`.
    ///
    /// This is provided for debugging and fine-tuning and should ordinarily be
    /// left unset.
    ///
    /// A value of 0 will write even empty batches to storage, and nonzero
    /// values provide a threshold.  A very large value effectively disables
    /// storage for such batches.  The default is `"10Mi"`.
    ///
    /// Before release 0.367.0 this setting was `min_storage_bytes`, a number
    /// of bytes. That name is deprecated but still read.
    #[serde(
        alias = "min_storage_bytes",
        deserialize_with = "size_min_spill_size",
        skip_serializing_if = "Option::is_none"
    )]
    #[schema(value_type = Option<String>)]
    pub min_spill_size: Option<ConfigSize>,

    /// For a batch of data passed through the pipeline during a single step,
    /// the minimum estimated size to write it to storage, such as `"64Mi"`.
    ///
    /// This is provided for debugging and fine-tuning and should ordinarily be
    /// left unset.  A value of 0 writes every batch that holds anything to
    /// storage; an empty batch stays in memory, since it has nothing to spill
    /// and a layer file is not free.  Nonzero values provide a threshold.
    /// Unset, the default, effectively disables storage for such batches.
    /// If it is set, it should ordinarily be greater than or equal to
    /// `min_spill_size`.
    ///
    /// Before release 0.367.0 this setting was `min_step_storage_bytes`, a
    /// number of bytes. That name is deprecated but still read.
    #[serde(
        alias = "min_step_storage_bytes",
        deserialize_with = "size_min_step_spill_size",
        skip_serializing_if = "Option::is_none"
    )]
    #[schema(value_type = Option<String>)]
    pub min_step_spill_size: Option<ConfigSize>,

    /// The form of compression to use in data batches.
    ///
    /// Compression has a CPU cost but it can take better advantage of limited
    /// NVMe and network bandwidth, which means that it can increase overall
    /// performance.
    pub compression: StorageCompression,

    /// Compression level, for compression algorithms that have one.
    ///
    /// Only `StorageCompression::Zstd` uses this. Higher levels compress
    /// harder and more slowly; decompression speed is largely unaffected, so
    /// the tradeoff is write throughput against stored size. Zstd accepts
    /// roughly 1 to 22, and a value outside the range its build supports is
    /// clamped into it.
    ///
    /// This is provided for fine-tuning and should ordinarily be left unset,
    /// which selects the algorithm's own default.
    pub compression_level: Option<i32>,

    /// The maximum size of the in-memory storage cache, such as `"4Gi"`.
    ///
    /// If set, the specified cache size is spread across all the foreground and
    /// background threads. If unset, each foreground or background thread cache
    /// is limited to 256 MiB.
    ///
    /// Before release 0.367.0 this setting was `cache_mib`, a number of
    /// mebibytes. That name is deprecated but still read.
    #[serde(
        alias = "cache_mib",
        deserialize_with = "size_cache_size",
        skip_serializing_if = "Option::is_none"
    )]
    #[schema(value_type = Option<String>)]
    pub cache_size: Option<ConfigSize>,

    /// False-positive rate for Bloom filters on batches on storage, as a
    /// fraction f, where 0 < f < 1.
    ///
    /// The false-positive rate trades off between the amount of memory used by
    /// Bloom filters and how frequently storage needs to be searched for keys
    /// that are not actually present.  Typical false-positive rates and their
    /// corresponding memory costs are:
    ///
    /// - 0.1: 4.8 bits per key
    /// - 0.01: 9.6 bits per key
    /// - 0.001: 14.4 bits per key
    /// - 0.0001: 19.2 bits per key (default)
    ///
    /// Values outside the valid range, such as 0.0, disable Bloom filters.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default, deserialize_with = "crate::serde_via_value::deserialize")]
    pub bloom_false_positive_rate: Option<f64>,
}

// `f64` does not implement `Eq`, but `bloom_false_positive_rate` is always
// finite, so `PartialEq` is an equivalence relation here.
impl Eq for StorageOptions {}

/// Backend storage configuration.
#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
#[serde(tag = "name", content = "config", rename_all = "snake_case")]
pub enum StorageBackendConfig {
    /// Use the default storage configuration.
    ///
    /// This currently uses the local file system.
    #[default]
    Default,

    /// Use the local file system.
    ///
    /// This uses ordinary system file operations.
    File(Box<FileBackendConfig>),

    /// Object storage.
    Object(ObjectStorageConfig),
}

impl Display for StorageBackendConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            StorageBackendConfig::Default => write!(f, "default"),
            StorageBackendConfig::File(_) => write!(f, "file"),
            StorageBackendConfig::Object(_) => write!(f, "object"),
        }
    }
}

/// Storage compression algorithm.
#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum StorageCompression {
    /// Use Feldera's default compression algorithm, currently [`Self::Lz4`].
    ///
    /// The default may change as Feldera's performance is tuned and new
    /// algorithms are introduced.
    #[default]
    Default,

    /// Do not compress.
    None,

    /// Use [Snappy](https://en.wikipedia.org/wiki/Snappy_(compression)) compression.
    Snappy,

    /// Use [LZ4](https://en.wikipedia.org/wiki/LZ4_(compression_algorithm)) compression.
    ///
    /// Compresses better than Snappy and decompresses several times faster, at
    /// a similar compression rate.
    Lz4,

    /// Use [Zstandard](https://en.wikipedia.org/wiki/Zstd) compression.
    ///
    /// Roughly halves LZ4's output at a comparable decompression rate, for
    /// slower compression. `StorageOptions::compression_level` selects the
    /// speed/size tradeoff.
    Zstd,
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub enum StartFromCheckpoint {
    Latest,
    Uuid(uuid::Uuid),
}

impl ToSchema<'_> for StartFromCheckpoint {
    fn schema() -> (
        &'static str,
        utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>,
    ) {
        (
            "StartFromCheckpoint",
            utoipa::openapi::RefOr::T(Schema::OneOf(
                OneOfBuilder::new()
                    .item(
                        ObjectBuilder::new()
                            .schema_type(SchemaType::String)
                            .enum_values(Some(["latest"].into_iter()))
                            .build(),
                    )
                    .item(
                        ObjectBuilder::new()
                            .schema_type(SchemaType::String)
                            .format(Some(utoipa::openapi::SchemaFormat::KnownFormat(
                                utoipa::openapi::KnownFormat::Uuid,
                            )))
                            .build(),
                    )
                    .nullable(true)
                    .build(),
            )),
        )
    }
}

impl<'de> Deserialize<'de> for StartFromCheckpoint {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct StartFromCheckpointVisitor;

        impl<'de> Visitor<'de> for StartFromCheckpointVisitor {
            type Value = StartFromCheckpoint;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("a UUID string or the string \"latest\"")
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                if value == "latest" {
                    Ok(StartFromCheckpoint::Latest)
                } else {
                    uuid::Uuid::parse_str(value)
                        .map(StartFromCheckpoint::Uuid)
                        .map_err(|_| E::invalid_value(serde::de::Unexpected::Str(value), &self))
                }
            }
        }

        deserializer.deserialize_str(StartFromCheckpointVisitor)
    }
}

impl Serialize for StartFromCheckpoint {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            StartFromCheckpoint::Latest => serializer.serialize_str("latest"),
            StartFromCheckpoint::Uuid(uuid) => serializer.serialize_str(&uuid.to_string()),
        }
    }
}

#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct SyncConfig {
    /// The endpoint URL for the storage service.
    ///
    /// This is typically required for custom or local S3-compatible storage providers like MinIO.
    /// Example: `http://localhost:9000`
    ///
    /// For a `gs://` bucket this is the Google Cloud Storage JSON API base URL;
    /// a bare host gets `/storage/v1/` appended. Leave empty for the public service.
    ///
    /// Relevant rclone config key: [`endpoint`](https://rclone.org/s3/#s3-endpoint)
    pub endpoint: Option<String>,

    /// The name of the storage bucket.
    ///
    /// This may include a path to a folder inside the bucket (e.g., `my-bucket/data`).
    ///
    /// Prefix it with `gs://` to sync to Google Cloud Storage through its native
    /// API instead of S3. `provider`, `access_key`, and `secret_key` are then
    /// ignored; rclone authenticates with Application Default Credentials, for
    /// example a GKE Workload Identity.
    pub bucket: String,

    /// The region that this bucket is in.
    ///
    /// Leave empty for Minio or the default region (`us-east-1` for AWS).
    pub region: Option<String>,

    /// The name of the cloud storage provider (e.g., `"AWS"`, `"Minio"`).
    ///
    /// Used for provider-specific behavior in rclone.
    /// If omitted, defaults to `"Other"`.
    ///
    /// See [rclone S3 provider documentation](https://rclone.org/s3/#s3-provider)
    pub provider: Option<String>,

    /// The access key used to authenticate with the storage provider.
    ///
    /// If not provided, rclone will fall back to environment-based credentials, such as
    /// `RCLONE_S3_ACCESS_KEY_ID`. In Kubernetes environments using IRSA (IAM Roles for Service Accounts),
    /// this can be left empty to allow automatic authentication via the pod's service account.
    pub access_key: Option<String>,

    /// The secret key used together with the access key for authentication.
    ///
    /// If not provided, rclone will fall back to environment-based credentials, such as
    /// `RCLONE_S3_SECRET_ACCESS_KEY`. In Kubernetes environments using IRSA (IAM Roles for Service Accounts),
    /// this can be left empty to allow automatic authentication via the pod's service account.
    pub secret_key: Option<String>,

    /// When set, the pipeline will try fetch the specified checkpoint from the
    /// object store.
    ///
    /// If `fail_if_no_checkpoint` is `true`, the pipeline will fail to initialize.
    pub start_from_checkpoint: Option<StartFromCheckpoint>,

    /// When true, the pipeline will fail to initialize if fetching the
    /// specified checkpoint fails (missing, download error).
    /// When false, the pipeline will start from scratch instead.
    ///
    /// False by default.
    #[schema(default = std::primitive::bool::default)]
    #[serde(default)]
    pub fail_if_no_checkpoint: bool,

    /// The number of file transfers to run in parallel.
    /// Default: 20
    pub transfers: Option<u8>,

    /// The number of checkers to run in parallel.
    /// Default: 20
    pub checkers: Option<u8>,

    /// Set to skip post copy check of checksums, and only check the file sizes.
    /// This can significantly improve the throughput.
    /// Defualt: false
    pub ignore_checksum: Option<bool>,

    /// Number of streams to use for multi-thread downloads.
    /// Default: 10
    pub multi_thread_streams: Option<u8>,

    /// Use multi-thread download for files above this size.
    /// Format: `[size][Suffix]` (Example: 1G, 500M)
    /// Supported suffixes: k|M|G|T
    /// Default: 100M
    pub multi_thread_cutoff: Option<String>,

    /// When true, checkpoint downloads use the maximum resources available on
    /// the host: `transfers` and `checkers` are scaled to the number of CPUs,
    /// and the download buffer is allowed to grow up to most of the available
    /// memory. This maximizes download throughput at the cost of higher CPU and
    /// memory usage during a pull.
    ///
    /// When false, downloads use the values configured via `transfers`,
    /// `checkers`, and the rclone defaults instead.
    ///
    /// Default: true
    #[schema(default = default_optimize_download_resources)]
    #[serde(default = "default_optimize_download_resources")]
    pub optimize_download_resources: bool,

    /// The number of chunks of the same file that are uploaded for multipart uploads.
    /// Default: 10
    pub upload_concurrency: Option<u8>,

    /// **Deprecated.** Use `initial=standby` when starting the pipeline instead.
    #[deprecated(note = "Use `initial=standby` when starting the pipeline instead.")]
    #[schema(default = std::primitive::bool::default)]
    #[serde(default)]
    pub standby: bool,

    /// The interval between each attempt to fetch the latest checkpoint from
    /// object store while in standby mode, for example `10s`.
    ///
    /// Applies only when `start_from_checkpoint` is set to `latest`. Unset
    /// selects the default, `DEFAULT_PULL_INTERVAL`.
    #[serde(
        default,
        alias = "pull_interval",
        deserialize_with = "duration_standby_pull_interval",
        skip_serializing_if = "Option::is_none"
    )]
    #[schema(value_type = Option<String>, default = default_pull_interval)]
    pub standby_pull_interval: Option<ConfigDuration>,

    /// The interval between each push of checkpoints to object store, for
    /// example `1h`.
    ///
    /// The default is no periodic push; `null` disables periodic pushes
    /// explicitly.
    #[serde(
        default,
        alias = "push_interval",
        deserialize_with = "duration_checkpoint_push_interval",
        skip_serializing_if = "Option::is_none"
    )]
    #[schema(value_type = Option<String>)]
    pub checkpoint_push_interval: Option<ConfigDuration>,

    /// Extra flags to pass to `rclone`.
    ///
    /// WARNING: Supplying incorrect or conflicting flags can break `rclone`.
    /// Use with caution.
    ///
    /// Refer to the docs to see the supported flags:
    /// - [Global flags](https://rclone.org/flags/)
    /// - [S3 specific flags](https://rclone.org/s3/)
    pub flags: Option<Vec<String>>,

    /// The minimum number of checkpoints to retain in object store.
    /// No checkpoints will be deleted if the total count is below this threshold.
    ///
    /// Default: 10
    #[schema(default = default_retention_min_count)]
    #[serde(default = "default_retention_min_count")]
    pub retention_min_count: u32,

    /// The minimum age a checkpoint must reach before it becomes eligible for
    /// deletion, for example `30d`. All younger checkpoints will be preserved.
    /// Unset selects the default, `DEFAULT_RETENTION_MIN_AGE`.
    #[serde(
        default,
        alias = "retention_min_age",
        deserialize_with = "duration_min_retention",
        skip_serializing_if = "Option::is_none"
    )]
    #[schema(value_type = Option<String>, default = default_retention_min_age)]
    pub min_retention: Option<ConfigDuration>,

    /// A read-only bucket used as a fallback checkpoint source.
    ///
    /// When the pipeline has no local checkpoint and `bucket` contains no
    /// checkpoint either, it will attempt to fetch the checkpoint from this
    /// location instead.  All connection settings (`endpoint`, `region`,
    /// `provider`, `access_key`, `secret_key`) are shared with `bucket`. The
    /// scheme is not: a `gs://` `bucket` needs a `gs://` `read_bucket` too,
    /// because the prefix alone selects the object store.
    ///
    /// The pipeline **never writes** to `read_bucket`.
    ///
    /// Must point to a different location than `bucket`.
    #[serde(default)]
    pub read_bucket: Option<String>,

    /// Take ownership of `bucket` when the pipeline starts, even if another
    /// pipeline owns it.
    ///
    /// A pipeline records its ownership of `bucket` in an `owner.json` file
    /// at the root of `bucket`, and a push fails without writing anything if
    /// that file names a different pipeline.  When this is `true`, the
    /// pipeline takes ownership as it starts (a standby pipeline, when it is
    /// activated): it logs a warning naming the previous and new owners and
    /// overwrites `owner.json`.  The previous owner's later pushes to
    /// `bucket` then fail.
    ///
    /// This only applies at startup.  If another pipeline takes ownership of
    /// `bucket` while this pipeline is running, this pipeline's pushes fail.
    ///
    /// Ownership changes before the pipeline opens its checkpoint, so it
    /// sticks even if the pipeline then fails to start: the previous owner's
    /// pushes keep failing.  To give `bucket` back, start the previous owner
    /// with `take_bucket_ownership` set.
    ///
    /// Use this to hand a checkpoint location over to a pipeline that
    /// replaces another one, e.g., after deleting and recreating a pipeline.
    /// Stop the previous owner first, and set this on only one of the
    /// pipelines that share a `bucket`.
    ///
    /// Default: false
    #[schema(default = std::primitive::bool::default)]
    #[serde(default)]
    pub take_bucket_ownership: bool,
}

fn default_retention_min_count() -> u32 {
    10
}

fn default_optimize_download_resources() -> bool {
    true
}

impl SyncConfig {
    /// The standby pull interval in effect, or [`DEFAULT_PULL_INTERVAL`].
    ///
    /// The enterprise crates read the sync durations through these accessors
    /// rather than the fields, so that one version of them compiles against
    /// every `feldera-types` a pinned runtime may bring: the accessors exist
    /// with these names on both sides of the rename.
    pub fn standby_pull_interval(&self) -> ConfigDuration {
        self.standby_pull_interval.unwrap_or(DEFAULT_PULL_INTERVAL)
    }

    /// The interval between checkpoint pushes, or `None` for no periodic push.
    pub fn checkpoint_push_interval(&self) -> Option<ConfigDuration> {
        self.checkpoint_push_interval
    }

    /// The checkpoint retention age in effect, or
    /// [`DEFAULT_RETENTION_MIN_AGE`].
    pub fn min_retention(&self) -> ConfigDuration {
        self.min_retention.unwrap_or(DEFAULT_RETENTION_MIN_AGE)
    }

    pub fn validate(&self) -> Result<(), String> {
        #[allow(deprecated)]
        if self.standby {
            return Err(
                "The `standby` config field has been deprecated. Use `initial=standby` when starting the pipeline instead.".to_owned()
            );
        }

        if let Some(ref rb) = self.read_bucket {
            if rb == &self.bucket {
                return Err(
                    "invalid sync config: `read_bucket` and `bucket` must point to different locations"
                        .to_owned(),
                );
            }
            // The `gs://` prefix selects the object store, so a mismatch would
            // send the fallback pull to the wrong service.
            if is_gcs_bucket(rb) != is_gcs_bucket(&self.bucket) {
                return Err(format!(
                    "invalid sync config: `bucket` ('{}') and `read_bucket` ('{}') must use the same object store; prefix both with `gs://` for Google Cloud Storage or neither for S3",
                    self.bucket, rb
                ));
            }
        }

        Ok(())
    }
}

/// Whether a sync `bucket` names Google Cloud Storage rather than S3.
fn is_gcs_bucket(bucket: &str) -> bool {
    bucket.starts_with("gs://")
}

/// Configuration for supplying a custom pipeline StatefulSet template via a Kubernetes ConfigMap.
///
/// Operators can provide a custom StatefulSet YAML that the Kubernetes runner will use when
/// creating pipeline StatefulSets for a pipeline. The custom template must be stored as the
/// value of a key in a ConfigMap in the same namespace as the pipeline; set `name` to the
/// ConfigMap name and `key` to the entry that contains the template.
///
/// Recommendations and requirements:
/// - **Start from the default template and modify it as needed.** The default template is present
///   in ConfigMap named as `<release-name>-pipeline-template`, with key `pipelineTemplate` in the release
///   namespace and should be used as a reference.
/// - The template must contain a valid Kubernetes `StatefulSet` manifest in YAML form. The
///   runner substitutes variables in the template before parsing; therefore the final YAML
///   must be syntactically valid.
/// - The runner performs simple string substitution for the following placeholders. Please ensure these
///   placeholders are placed at appropriate location for their semantics:
///   - `{id}`: pipeline Kubernetes name (used for object names and labels)
///   - `{name}`: pipeline name as a quoted JSON string (use it only as a whole YAML value)
///   - `{namespace}`: Kubernetes namespace where the pipeline runs
///   - `{pipeline_executor_image}`: container image used to run the pipeline executor
///   - `{binary_ref}`: program binary reference passed as an argument
///   - `{program_info_ref}`: program info reference passed as an argument
///   - `{pipeline_storage_path}`: mount path for persistent pipeline storage
///   - `{storage_class_name}`: storage class name to use for PVCs (if applicable)
///   - `{deployment_id}`: UUID identifying the deployment instance
///   - `{deployment_initial}`: initial desired runtime status (e.g., `provisioning`)
///   - `{bootstrap_policy}`: bootstrap policy value when applicable, otherwise `none`
///   - `{silent_bootstrap}`: `yes` or `no`
///   - `{concurrent_bootstrap}`: `yes` or `no`
///   - `{hosts}`: number of hosts the pipeline runs on
///   - `{multihost}`: `yes` or `no`
///
///   The substitution has no escape: do not use these names in braces as literal text.
// Keep the placeholder list in sync with the table in
// docs.feldera.com/docs/get-started/enterprise/helm-chart-reference.md.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
pub struct PipelineTemplateConfig {
    /// Name of the ConfigMap containing the pipeline template.
    pub name: String,
    /// Key in the ConfigMap containing the pipeline template.
    ///
    /// If not set, defaults to `pipelineTemplate`.
    #[schema(default = default_pipeline_template_key)]
    #[serde(default = "default_pipeline_template_key")]
    pub key: String,
}

fn default_pipeline_template_key() -> String {
    "pipelineTemplate".to_string()
}

#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct ObjectStorageConfig {
    /// URL.
    ///
    /// The following URL schemes are supported:
    ///
    /// * S3:
    ///   - `s3://<bucket>/<path>`
    ///   - `s3a://<bucket>/<path>`
    ///   - `https://s3.<region>.amazonaws.com/<bucket>`
    ///   - `https://<bucket>.s3.<region>.amazonaws.com`
    ///   - `https://ACCOUNT_ID.r2.cloudflarestorage.com/bucket`
    /// * Google Cloud Storage:
    ///   - `gs://<bucket>/<path>`
    /// * Microsoft Azure Blob Storage:
    ///   - `abfs[s]://<container>/<path>` (according to [fsspec](https://github.com/fsspec/adlfs))
    ///   - `abfs[s]://<file_system>@<account_name>.dfs.core.windows.net/<path>`
    ///   - `abfs[s]://<file_system>@<account_name>.dfs.fabric.microsoft.com/<path>`
    ///   - `az://<container>/<path>` (according to [fsspec](https://github.com/fsspec/adlfs))
    ///   - `adl://<container>/<path>` (according to [fsspec](https://github.com/fsspec/adlfs))
    ///   - `azure://<container>/<path>` (custom)
    ///   - `https://<account>.dfs.core.windows.net`
    ///   - `https://<account>.blob.core.windows.net`
    ///   - `https://<account>.blob.core.windows.net/<container>`
    ///   - `https://<account>.dfs.fabric.microsoft.com`
    ///   - `https://<account>.dfs.fabric.microsoft.com/<container>`
    ///   - `https://<account>.blob.fabric.microsoft.com`
    ///   - `https://<account>.blob.fabric.microsoft.com/<container>`
    ///
    /// Settings derived from the URL will override other settings.
    pub url: String,

    /// Additional options as key-value pairs.
    ///
    /// The following keys are supported:
    ///
    /// * S3:
    ///   - `access_key_id`: AWS Access Key.
    ///   - `secret_access_key`: AWS Secret Access Key.
    ///   - `region`: Region.
    ///   - `default_region`: Default region.
    ///   - `endpoint`: Custom endpoint for communicating with S3,
    ///     e.g. `https://localhost:4566` for testing against a localstack
    ///     instance.
    ///   - `token`: Token to use for requests (passed to underlying provider).
    ///   - [Other keys](https://docs.rs/object_store/latest/object_store/aws/enum.AmazonS3ConfigKey.html#variants).
    /// * Google Cloud Storage:
    ///   - `service_account`: Path to the service account file.
    ///   - `service_account_key`: The serialized service account key.
    ///   - `google_application_credentials`: Application credentials path.
    ///   - [Other keys](https://docs.rs/object_store/latest/object_store/gcp/enum.GoogleConfigKey.html).
    /// * Microsoft Azure Blob Storage:
    ///   - `access_key`: Azure Access Key.
    ///   - `container_name`: Azure Container Name.
    ///   - `account`: Azure Account.
    ///   - `bearer_token_authorization`: Static bearer token for authorizing requests.
    ///   - `client_id`: Client ID for use in client secret or Kubernetes federated credential flow.
    ///   - `client_secret`: Client secret for use in client secret flow.
    ///   - `tenant_id`: Tenant ID for use in client secret or Kubernetes federated credential flow.
    ///   - `endpoint`: Override the endpoint for communicating with blob storage.
    ///   - [Other keys](https://docs.rs/object_store/latest/object_store/azure/enum.AzureConfigKey.html#variants).
    ///
    /// Options set through the URL take precedence over those set with these
    /// options.
    #[serde(flatten)]
    pub other_options: BTreeMap<String, String>,
}

/// Configuration for local file system access.
#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
#[serde(default)]
pub struct FileBackendConfig {
    /// Whether to use background threads for file I/O.
    ///
    /// Background threads should improve performance, but they can reduce
    /// performance if too few cores are available. This is provided for
    /// debugging and fine-tuning and should ordinarily be left unset.
    pub async_threads: Option<bool>,

    /// Per-I/O operation sleep duration, for example `5ms`.
    ///
    /// This is for simulating slow storage devices.  Do not use this in
    /// production.
    #[serde(
        default,
        alias = "ioop_delay",
        deserialize_with = "duration_ioop_latency",
        skip_serializing_if = "Option::is_none"
    )]
    #[schema(value_type = Option<String>)]
    pub ioop_latency: Option<ConfigDuration>,

    /// Configuration to synchronize checkpoints to object store.
    pub sync: Option<SyncConfig>,

    /// How to make files durable when committing a checkpoint.
    ///
    /// This is provided for debugging and fine-tuning and should ordinarily be
    /// left unset.
    pub sync_mode: Option<StorageSyncMode>,
}

/// How a pipeline makes its files durable when it commits a checkpoint.
///
/// A checkpoint can hold tens of thousands of files, so committing them one at
/// a time is the dominant cost of making one. Both alternatives below fix that,
/// but they suit different deployments.
#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum StorageSyncMode {
    /// Use `syncfs` when storage has a filesystem to itself, and fsync files in
    /// parallel otherwise.
    #[default]
    Auto,

    /// Always `syncfs`.
    ///
    /// One syscall makes the whole filesystem durable, which is the cheapest
    /// option by far when storage is a dedicated volume. On a filesystem shared
    /// with anything else, it also writes back that other data.
    ///
    /// A pipeline falls back to `per_file` where `syncfs` cannot report a failed
    /// writeback, rather than honoring this setting: off Linux, and before Linux
    /// 5.8, where `syncfs` returned success and discarded the error.
    Syncfs,

    /// Always fsync each file, spread across several threads.
    ///
    /// Slower than `syncfs` on a dedicated volume, but it touches only this
    /// pipeline's files.
    PerFile,
}

/// Global pipeline configuration settings. This is the publicly
/// exposed type for users to configure pipelines.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
#[serde(default)]
pub struct RuntimeConfig {
    /// Number of DBSP worker threads.
    ///
    /// Each DBSP "foreground" worker thread is paired with a "background"
    /// thread for LSM merging, making the total number of threads twice the
    /// specified number.
    ///
    /// The typical sweet spot for the number of workers is between 4 and 16.
    /// Each worker increases overall memory consumption for data structures
    /// used during a step.
    pub workers: u16,

    /// The maximum amount of memory that the pipeline is allowed to use on
    /// each host, such as `"16G"` or `"16Gi"`.
    ///
    /// Setting this property activates memory pressure monitoring and backpressure
    /// mechanisms. The pipeline will track the amount of remaining memory and
    /// report the memory pressure level via the `memory_pressure` metric.
    ///
    /// As the memory pressure increases, the system will apply increasing backpressure
    /// to push state cached in memory to storage, preventing the pipeline from running
    /// out of memory at the cost of some performance degradation.
    ///
    /// It is strongly recommended to set this property to prevent the pipeline from
    /// running out of memory. The setting should not exceed the memory limit of the pipeline
    /// instance.
    ///
    /// When `max_rss` is not specified but `resources.memory_max` is set, the
    /// latter is used as the effective memory cap for the pipeline.
    ///
    /// The pipeline caps this limit at the memory available to it, which is the
    /// host's memory or the container's memory limit, whichever is smaller. It
    /// rechecks the available memory every second.
    ///
    /// Before release 0.367.0 this setting was `max_rss_mb`, a number of
    /// megabytes. That name is deprecated but still read.
    ///
    /// See [documentation on the pipeline's memory usage](https://docs.feldera.com/operations/memory)
    /// for more details.
    #[serde(
        default,
        alias = "max_rss_mb",
        deserialize_with = "size_max_rss",
        skip_serializing_if = "Option::is_none"
    )]
    #[schema(value_type = Option<String>)]
    pub max_rss: Option<ConfigSize>,

    /// DataFusion memory pool size, such as `"1Gi"`, shared by the ad-hoc
    /// query engine and the Delta Lake / Iceberg connectors.
    ///
    /// Carved out of `max_rss` (falling back to `resources.memory_max`); the
    /// remainder goes to the DBSP circuit, so the two do not double-book RAM.
    ///
    /// Unset: defaults to 5% of the effective budget, capped at 2 GB.
    /// Pipelines that don't run heavy ad-hoc / Delta / Iceberg workloads
    /// can leave this unset.
    ///
    /// Set this explicitly for ad-hoc queries, or Delta / Iceberg scans,
    /// over data too large for the default share. A pool that cannot hold
    /// the query surfaces as `ResourcesExhausted` on that query alone; the
    /// pipeline keeps running.
    ///
    /// No pool limit applied if no overall budget is configured.
    ///
    /// Before release 0.367.0 this setting was `datafusion_memory_mb`, a
    /// number of megabytes. That name is deprecated but still read.
    ///
    /// See [documentation on the pipeline's memory usage](https://docs.feldera.com/operations/memory)
    /// for more details.
    #[serde(
        default,
        alias = "datafusion_memory_mb",
        deserialize_with = "size_datafusion_memory",
        skip_serializing_if = "Option::is_none"
    )]
    #[schema(value_type = Option<String>)]
    pub datafusion_memory: Option<ConfigSize>,

    /// Number of DBSP hosts.
    ///
    /// The worker threads are evenly divided among the hosts.  For single-host
    /// deployments, this should be 1 (the default).
    ///
    /// Multihost pipelines are an enterprise-only preview feature.
    pub hosts: usize,

    /// Storage configuration.
    ///
    /// - If this is `None`, the default, the pipeline's state is kept in
    ///   in-memory data-structures.  This is useful if the pipeline's state
    ///   will fit in memory and if the pipeline is ephemeral and does not need
    ///   to be recovered after a restart. The pipeline will most likely run
    ///   faster since it does not need to access storage.
    ///
    /// - If set, the pipeline's state is kept on storage.  This allows the
    ///   pipeline to work with state that will not fit into memory. It also
    ///   allows the state to be checkpointed and recovered across restarts.
    #[serde(deserialize_with = "deserialize_storage_options")]
    pub storage: Option<StorageOptions>,

    /// Fault tolerance configuration.
    #[serde(deserialize_with = "deserialize_fault_tolerance")]
    pub fault_tolerance: FtConfig,

    /// Enable CPU profiler.
    ///
    /// The default value is `true`.
    pub cpu_profiler: bool,

    /// Enable pipeline tracing.
    pub tracing: bool,

    /// Jaeger tracing endpoint to send tracing information to.
    pub tracing_endpoint_jaeger: String,

    /// Minimal input batch size.
    ///
    /// The controller delays pushing input records to the circuit until at
    /// least `min_batch_size_records` records have been received (total
    /// across all endpoints) or `max_buffering_delay` has passed
    /// since the first input record was buffered.
    /// Defaults to 0.
    pub min_batch_size_records: u64,

    /// Maximal delay to wait for `min_batch_size_records` to get buffered by
    /// the controller, for example `10ms`. Defaults to no delay.
    #[serde(
        default,
        alias = "max_buffering_delay_usecs",
        deserialize_with = "duration_max_buffering_delay",
        skip_serializing_if = "Option::is_none"
    )]
    #[schema(value_type = Option<String>)]
    pub max_buffering_delay: Option<ConfigDuration>,

    /// Resource reservations and limits. This is enforced
    /// only in Feldera Cloud.
    pub resources: ResourceConfig,

    /// Real-time clock resolution, for example `1s`.
    ///
    /// This parameter controls the execution of queries that use the `NOW()` function.  The output of such
    /// queries depends on the real-time clock and can change over time without any external
    /// inputs.  If the query uses `NOW()`, the pipeline will update the clock value and trigger incremental
    /// recomputation at most once per `clock_resolution`.  If the query does not use
    /// `NOW()`, then clock value updates are suppressed and the pipeline ignores this setting.
    ///
    /// Unset or `null` selects the default, `DEFAULT_CLOCK_RESOLUTION`.
    #[serde(
        default,
        alias = "clock_resolution_usecs",
        deserialize_with = "duration_clock_resolution",
        skip_serializing_if = "Option::is_none"
    )]
    #[schema(value_type = Option<String>, default = default_clock_resolution)]
    pub clock_resolution: Option<ConfigDuration>,

    /// Fixed timezone offset for the SQL `NOW()` clock.
    ///
    /// An ISO-8601 UTC offset, for example `"+05:30"` or `"-08:00"`, that the
    /// clock connector adds to every `NOW()` value it emits, so `NOW()`
    /// returns local time in that fixed timezone instead of UTC.
    ///
    /// The offset is baked into the pipeline's checkpointed state and cannot
    /// be changed when the pipeline resumes from a checkpoint: the value from
    /// the checkpoint stays in effect, and a differing new value is ignored
    /// with a warning in the pipeline log.
    #[schema(value_type = Option<String>, example = "+05:30")]
    pub clock_timezone_offset: Option<ClockTimezoneOffset>,

    /// Optionally, a list of CPU numbers for CPUs to which the pipeline may pin
    /// its worker threads.  Specify at least twice as many CPU numbers as
    /// workers.  CPUs are generally numbered starting from 0.  The pipeline
    /// might not be able to honor CPU pinning requests.
    ///
    /// CPU pinning can make pipelines run faster and perform more consistently,
    /// as long as different pipelines running on the same machine are pinned to
    /// different CPUs.
    pub pin_cpus: Vec<usize>,

    /// Timeout for the `Provisioning` phase of the pipeline, for example `5m`.
    /// Setting this value will override the default of the runner.
    #[serde(
        default,
        alias = "provisioning_timeout_secs",
        deserialize_with = "duration_provisioning_timeout",
        skip_serializing_if = "Option::is_none"
    )]
    #[schema(value_type = Option<String>)]
    pub provisioning_timeout: Option<ConfigDuration>,

    /// The maximum number of connectors initialized in parallel during pipeline
    /// startup.
    ///
    /// At startup, the pipeline must initialize all of its input and output connectors.
    /// Depending on the number and types of connectors, this can take a long time.
    /// To accelerate the process, multiple connectors are initialized concurrently.
    /// This option controls the maximum number of connectors that can be initialized
    /// in parallel.
    ///
    /// The default is 10.
    pub max_parallel_connector_init: Option<u64>,

    /// Specification of additional (sidecar) containers.
    pub init_containers: Option<serde_json::Value>,

    /// Deprecated: setting this true or false does not have an effect anymore.
    pub checkpoint_during_suspend: bool,

    /// Sets the number of available runtime threads for the http server.
    ///
    /// In most cases, this does not need to be set explicitly and
    /// the default is sufficient. Can be increased in case the
    /// pipeline HTTP API operations are a bottleneck.
    ///
    /// If not specified, the default is set to `workers`.
    pub http_workers: Option<u64>,

    /// Sets the number of available runtime threads for async IO tasks.
    ///
    /// This affects some networking and file I/O operations
    /// especially adapters and ad-hoc queries.
    ///
    /// In most cases, this does not need to be set explicitly and
    /// the default is sufficient. Can be increased in case
    /// ingress, egress or ad-hoc queries are a bottleneck.
    ///
    /// If not specified, the default is set to `workers`.
    pub io_workers: Option<u64>,

    /// Environment variables for the pipeline process.
    ///
    /// These are key-value pairs injected into the pipeline process environment.
    /// Some variable names are reserved by the platform and cannot be overridden
    /// (for example `RUST_LOG`, and variables in the `FELDERA_`,
    /// `KUBERNETES_`, and `TOKIO_` namespaces).
    #[serde(default)]
    pub env: BTreeMap<String, String>,

    /// Optional settings for tweaking Feldera internals.
    pub dev_tweaks: DevTweaks,

    /// Log filtering directives.
    ///
    /// If set to a valid [tracing-subscriber] filter, this controls the log
    /// messages emitted by the pipeline process.  Otherwise, or if the filter
    /// has invalid syntax, messages at "info" severity and higher are written
    /// to the log and all others are discarded.
    ///
    /// [tracing-subscriber]: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html#directives
    pub logging: Option<String>,

    /// ConfigMap containing a custom pipeline template (Enterprise only).
    ///
    /// This feature is only available in Feldera Enterprise. If set, the Kubernetes runner
    /// will read the template from the specified ConfigMap and use it instead of the default
    /// StatefulSet template for the configured pipeline.
    ///
    /// check [`PipelineTemplateConfig`] documentation for details.
    pub pipeline_template_configmap: Option<PipelineTemplateConfig>,
}

/// Accepts "true" and "false" and converts them to the new format.
fn deserialize_storage_options<'de, D>(deserializer: D) -> Result<Option<StorageOptions>, D::Error>
where
    D: Deserializer<'de>,
{
    struct BoolOrStruct;

    impl<'de> Visitor<'de> for BoolOrStruct {
        type Value = Option<StorageOptions>;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("boolean or StorageOptions")
        }

        fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            match v {
                false => Ok(None),
                true => Ok(Some(StorageOptions::default())),
            }
        }

        fn visit_unit<E>(self) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(None)
        }

        fn visit_none<E>(self) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(None)
        }

        fn visit_map<M>(self, map: M) -> Result<Option<StorageOptions>, M::Error>
        where
            M: MapAccess<'de>,
        {
            Deserialize::deserialize(de::value::MapAccessDeserializer::new(map)).map(Some)
        }
    }

    deserializer.deserialize_any(BoolOrStruct)
}

/// Accepts very old 'initial_state' and 'latest_checkpoint' as enabling fault
/// tolerance.
///
/// Accepts `null` as disabling fault tolerance.
///
/// Otherwise, deserializes [FtConfig] in the way that one might otherwise
/// expect.
fn deserialize_fault_tolerance<'de, D>(deserializer: D) -> Result<FtConfig, D::Error>
where
    D: Deserializer<'de>,
{
    struct StringOrStruct;

    impl<'de> Visitor<'de> for StringOrStruct {
        type Value = FtConfig;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("none or FtConfig or 'initial_state' or 'latest_checkpoint'")
        }

        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            match v {
                "initial_state" | "latest_checkpoint" => Ok(FtConfig {
                    model: Some(FtModel::default()),
                    ..FtConfig::default()
                }),
                _ => Err(de::Error::invalid_value(de::Unexpected::Str(v), &self)),
            }
        }

        fn visit_unit<E>(self) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(FtConfig::default())
        }

        fn visit_none<E>(self) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(FtConfig::default())
        }

        fn visit_map<M>(self, map: M) -> Result<FtConfig, M::Error>
        where
            M: MapAccess<'de>,
        {
            Deserialize::deserialize(de::value::MapAccessDeserializer::new(map))
        }
    }

    deserializer.deserialize_any(StringOrStruct)
}

impl Default for RuntimeConfig {
    fn default() -> Self {
        Self {
            workers: 8,
            max_rss: None,
            datafusion_memory: None,
            hosts: 1,
            storage: Some(StorageOptions::default()),
            fault_tolerance: FtConfig::default(),
            cpu_profiler: true,
            tracing: {
                // We discovered that the jaeger crate can use up gigabytes of RAM, so it's not harmless
                // to keep it on by default.
                false
            },
            tracing_endpoint_jaeger: "127.0.0.1:6831".to_string(),
            min_batch_size_records: 0,
            max_buffering_delay: None,
            resources: ResourceConfig::default(),
            clock_resolution: None,
            clock_timezone_offset: None,
            pin_cpus: Vec::new(),
            provisioning_timeout: None,
            max_parallel_connector_init: None,
            init_containers: None,
            checkpoint_during_suspend: true,
            io_workers: None,
            http_workers: None,
            env: BTreeMap::default(),
            dev_tweaks: DevTweaks::default(),
            logging: None,
            pipeline_template_configmap: None,
        }
    }
}

/// Upper bound on the default DataFusion pool size.
///
/// Spill-to-disk handles overflow; reserving more starves the circuit.
pub const DEFAULT_DATAFUSION_MEMORY_CEILING: ConfigSize = ConfigSize::from_mb(2048);

/// Default DataFusion pool size as a percentage of the pipeline's
/// effective memory budget. The remainder is left for the DBSP circuit.
pub const DEFAULT_DATAFUSION_MEMORY_PERCENT: u64 = 5;

impl RuntimeConfig {
    /// The input buffering delay in effect, or no delay.
    pub fn max_buffering_delay(&self) -> ConfigDuration {
        self.max_buffering_delay.unwrap_or(ConfigDuration::ZERO)
    }

    /// The clock resolution in effect, or [`DEFAULT_CLOCK_RESOLUTION`].
    pub fn clock_resolution(&self) -> ConfigDuration {
        self.clock_resolution.unwrap_or(DEFAULT_CLOCK_RESOLUTION)
    }

    /// Pipeline's effective memory budget: `max_rss`, falling back to
    /// `resources.memory_max` (the k8s pod limit).
    pub fn effective_memory(&self) -> Option<ConfigSize> {
        self.max_rss.or(self.resources.memory_max)
    }

    /// Resolved DataFusion pool size: explicit `datafusion_memory` if set,
    /// else 5% of the effective budget capped at
    /// `DEFAULT_DATAFUSION_MEMORY_CEILING`. `None` if no budget is
    /// configured.
    pub fn resolved_datafusion_memory(&self) -> Option<ConfigSize> {
        if let Some(explicit) = self.datafusion_memory {
            return Some(explicit);
        }
        let effective = self.effective_memory()?.as_bytes();
        // In `u128`: a budget near `u64::MAX` times the percentage overflows.
        let fraction = u128::from(effective) * u128::from(DEFAULT_DATAFUSION_MEMORY_PERCENT) / 100;
        let fraction = u64::try_from(fraction).unwrap_or(u64::MAX);
        Some(ConfigSize::from_bytes(fraction).min(DEFAULT_DATAFUSION_MEMORY_CEILING))
    }
}

/// Fault-tolerance configuration.
///
/// The default [FtConfig] (via [FtConfig::default]) disables fault tolerance,
/// which is the configuration that one gets if [RuntimeConfig] omits fault
/// tolerance configuration.
///
/// The default value for [FtConfig::model] enables fault tolerance, as
/// `Some(FtModel::default())`.  This is the configuration that one gets if
/// [RuntimeConfig] includes a fault tolerance configuration but does not
/// specify a particular model.
#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub struct FtConfig {
    /// Fault tolerance model to use.
    #[serde(with = "none_as_string")]
    #[serde(default = "default_model")]
    #[schema(
        schema_with = none_as_string_schema::<FtModel>,
    )]
    pub model: Option<FtModel>,

    /// Interval between automatic checkpoints, for example `60s`.
    ///
    /// Unset selects the default, `DEFAULT_CHECKPOINT_INTERVAL`; `null`
    /// disables periodic checkpointing.
    /// Values less than 1 second or greater than 1 hour will be forced into
    /// that range.
    #[serde(
        default,
        alias = "checkpoint_interval_secs",
        deserialize_with = "duration_checkpoint_interval",
        skip_serializing_if = "Option::is_none"
    )]
    #[schema(value_type = Option<String>, default = default_checkpoint_interval)]
    pub checkpoint_interval: Option<Option<ConfigDuration>>,
}

fn default_model() -> Option<FtModel> {
    Some(FtModel::default())
}

/// Rewrites the duration settings of a serialized pipeline configuration in the
/// spelling that Feldera releases before the duration rename read: under the
/// older key, as a whole number of the unit that key named.
///
/// `config` is a serialized [`RuntimeConfig`], or a serialized
/// [`PipelineConfig`], which flattens one and carries the connectors in
/// `inputs` and `outputs`; both levels are rewritten. The pipeline manager
/// applies this to the configuration it hands a pipeline pinned to another
/// runtime version, or compiled by a platform before the rename and not yet
/// updated: such a runtime may predate the rename, and a runtime that does
/// ignores the current names and silently runs on its defaults, or, for a
/// Kafka connector, rejects them. Every Feldera release so far accepts the
/// older spelling, so writing it is safe whichever runtime runs.
///
/// A duration that is not a whole number of the older unit rounds up to the
/// next one, so a positive duration never becomes a `0` the older runtime
/// reads as "no timeout" or "pull without pause", and is capped at the largest
/// value the older field holds; a value that does not parse is left as it is,
/// for the runtime to reject.
pub fn to_legacy_duration_spelling(config: &mut serde_json::Value) {
    use crate::duration::LegacyUnit;
    use serde_json::{Map, Value};

    /// How one setting is spelled before the rename.
    struct Rule {
        new: &'static str,
        old: &'static str,
        unit: LegacyUnit,
        /// The largest number the older field holds.
        max: u64,
        /// Whether the older field took a `null`; where it did not, a `null`
        /// meant "unset" and the key is dropped.
        null_allowed: bool,
    }
    const fn rule(
        new: &'static str,
        old: &'static str,
        unit: LegacyUnit,
        max: u64,
        null_allowed: bool,
    ) -> Rule {
        Rule {
            new,
            old,
            unit,
            max,
            null_allowed,
        }
    }
    const U32: u64 = u32::MAX as u64;
    const U64: u64 = u64::MAX;
    use LegacyUnit::{Days, Micros, Millis, Secs};

    fn apply(object: &mut Map<String, Value>, rules: &[Rule]) {
        for rule in rules {
            let Some(value) = object.remove(rule.new) else {
                continue;
            };
            let legacy = match &value {
                Value::String(text) => match text.parse::<ConfigDuration>() {
                    Ok(duration) => {
                        let nanos = std::time::Duration::from(duration).as_nanos();
                        let unit_nanos = u128::from(rule.unit.nanos());
                        let whole = nanos.div_ceil(unit_nanos);
                        Value::from(u64::try_from(whole).unwrap_or(U64).min(rule.max))
                    }
                    Err(_) => {
                        object.insert(rule.new.to_string(), value);
                        continue;
                    }
                },
                Value::Null if !rule.null_allowed => continue,
                // A bare number or a null already has the older meaning.
                other => other.clone(),
            };
            object.insert(rule.old.to_string(), legacy);
        }
    }
    fn child<'a>(
        object: &'a mut Map<String, Value>,
        key: &str,
    ) -> Option<&'a mut Map<String, Value>> {
        object.get_mut(key).and_then(Value::as_object_mut)
    }
    /// The NATS consumer's expiry was a `std::time::Duration`, which serde
    /// writes as `{secs, nanos}`, rather than a number.
    fn max_expiry(consumer: &mut Map<String, Value>) {
        let Some(Value::String(text)) = consumer.get("max_expiry") else {
            return;
        };
        let Ok(duration) = text.parse::<ConfigDuration>() else {
            return;
        };
        let duration = std::time::Duration::from(duration);
        consumer.remove("max_expiry");
        consumer.insert(
            "max_expires".to_string(),
            serde_json::json!({"secs": duration.as_secs(), "nanos": duration.subsec_nanos()}),
        );
    }
    /// The connection options both NATS transports share.
    fn nats_connection(transport: &mut Map<String, Value>) {
        if let Some(connection) = child(transport, "connection_config") {
            apply(
                connection,
                &[
                    rule(
                        "connection_timeout",
                        "connection_timeout_secs",
                        Secs,
                        U64,
                        false,
                    ),
                    rule("request_timeout", "request_timeout_secs", Secs, U64, false),
                ],
            );
        }
    }
    /// One connector of `inputs` or `outputs`.
    fn connector(endpoint: &mut Map<String, Value>) {
        apply(
            endpoint,
            &[rule(
                "max_output_buffer_time",
                "max_output_buffer_time_millis",
                Millis,
                U64,
                false,
            )],
        );
        let name = endpoint
            .get("transport")
            .and_then(|transport| transport.get("name"))
            .and_then(Value::as_str)
            .map(str::to_string);
        if let Some(transport) = child(endpoint, "transport").and_then(|t| child(t, "config")) {
            match name.as_deref() {
                Some("url_input") => apply(
                    transport,
                    &[rule("pause_linger", "pause_timeout", Secs, U32, false)],
                ),
                Some("kafka_input") => apply(
                    transport,
                    &[rule(
                        "group_join_timeout",
                        "group_join_timeout_secs",
                        Secs,
                        U32,
                        false,
                    )],
                ),
                Some("kafka_output") => apply(
                    transport,
                    &[rule(
                        "initialization_timeout",
                        "initialization_timeout_secs",
                        Secs,
                        U32,
                        false,
                    )],
                ),
                Some("clock_input") => apply(
                    transport,
                    &[rule(
                        "clock_resolution",
                        "clock_resolution_usecs",
                        Micros,
                        U64,
                        false,
                    )],
                ),
                Some("pub_sub_input") => apply(
                    transport,
                    &[
                        rule("timeout", "timeout_seconds", Secs, U32, true),
                        rule(
                            "connect_timeout",
                            "connect_timeout_seconds",
                            Secs,
                            U32,
                            true,
                        ),
                    ],
                ),
                Some("nats_input") => {
                    apply(
                        transport,
                        &[
                            rule(
                                "inactivity_timeout",
                                "inactivity_timeout_secs",
                                Secs,
                                U64,
                                false,
                            ),
                            rule("retry_interval", "retry_interval_secs", Secs, U64, false),
                        ],
                    );
                    nats_connection(transport);
                    if let Some(consumer) = child(transport, "consumer_config") {
                        max_expiry(consumer);
                    }
                }
                Some("nats_output") => {
                    apply(
                        transport,
                        &[rule(
                            "publish_timeout",
                            "publish_timeout_secs",
                            Secs,
                            U64,
                            false,
                        )],
                    );
                    nats_connection(transport);
                }
                _ => {}
            }
        }
        let is_avro = endpoint
            .get("format")
            .and_then(|format| format.get("name"))
            .and_then(Value::as_str)
            == Some("avro");
        if is_avro && let Some(format) = child(endpoint, "format").and_then(|f| child(f, "config"))
        {
            apply(
                format,
                &[rule(
                    "registry_timeout",
                    "registry_timeout_secs",
                    Secs,
                    U64,
                    true,
                )],
            );
        }
    }

    let Some(global) = config.as_object_mut() else {
        return;
    };
    apply(
        global,
        &[
            rule(
                "clock_resolution",
                "clock_resolution_usecs",
                Micros,
                U64,
                true,
            ),
            rule(
                "max_buffering_delay",
                "max_buffering_delay_usecs",
                Micros,
                U64,
                false,
            ),
            rule(
                "provisioning_timeout",
                "provisioning_timeout_secs",
                Secs,
                U64,
                true,
            ),
        ],
    );
    if let Some(ft) = child(global, "fault_tolerance") {
        // An explicit null disables periodic checkpoints under either key.
        apply(
            ft,
            &[rule(
                "checkpoint_interval",
                "checkpoint_interval_secs",
                Secs,
                U64,
                true,
            )],
        );
    }
    let backend = child(global, "storage")
        .and_then(|storage| child(storage, "backend"))
        .filter(|backend| backend.get("name").and_then(Value::as_str) == Some("file"))
        .and_then(|backend| child(backend, "config"));
    if let Some(file) = backend {
        apply(
            file,
            &[rule("ioop_latency", "ioop_delay", Millis, U64, true)],
        );
        if let Some(sync) = child(file, "sync") {
            apply(
                sync,
                &[
                    rule("standby_pull_interval", "pull_interval", Secs, U64, false),
                    rule("checkpoint_push_interval", "push_interval", Secs, U64, true),
                    rule("min_retention", "retention_min_age", Days, U32, false),
                ],
            );
        }
    }
    for endpoints in ["inputs", "outputs"] {
        if let Some(endpoints) = child(global, endpoints) {
            for endpoint in endpoints.values_mut().filter_map(Value::as_object_mut) {
                connector(endpoint);
            }
        }
    }
}

/// Which settings a runtime reads only in their older spelling, because it
/// predates the release that renamed them.
///
/// The pipeline manager computes this for the runtime a pipeline runs, and the
/// executors apply it to the configuration they hand the pipeline process.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct LegacySpelling {
    /// The runtime predates the duration rename (release 0.366.0).
    pub durations: bool,
    /// The runtime predates the size rename (release 0.367.0).
    pub sizes: bool,
}

impl LegacySpelling {
    /// A runtime that reads every current spelling.
    pub const NONE: LegacySpelling = LegacySpelling {
        durations: false,
        sizes: false,
    };

    /// Whether any setting must be rewritten.
    pub fn any(self) -> bool {
        self.durations || self.sizes
    }

    /// Rewrites `config`, a serialized [`RuntimeConfig`] or
    /// [`PipelineConfig`], in the spellings the runtime reads.
    pub fn apply(self, config: &mut serde_json::Value) {
        if self.durations {
            to_legacy_duration_spelling(config);
        }
        if self.sizes {
            to_legacy_size_spelling(config);
        }
    }
}

/// Rewrites the size settings of a serialized pipeline configuration in the
/// spelling that Feldera releases before the size rename read: under the older
/// key, as a whole number of the unit that key named.
///
/// `config` is a serialized [`RuntimeConfig`] or [`PipelineConfig`], as for
/// [`to_legacy_duration_spelling`], and the pipeline manager applies it in the
/// same cases, to a runtime that may predate the rename. A size that is not a
/// whole number of the older unit rounds up to the next one, so a positive
/// limit never becomes a `0`; a value that does not parse is left as it is,
/// for the runtime to reject.
pub fn to_legacy_size_spelling(config: &mut serde_json::Value) {
    use crate::size::LegacySizeUnit::{self, Bytes, Mebibytes, Megabytes};
    use serde_json::{Map, Value};

    /// How one setting is spelled before the rename.
    struct Rule {
        new: &'static str,
        old: &'static str,
        unit: LegacySizeUnit,
    }
    const fn rule(new: &'static str, old: &'static str, unit: LegacySizeUnit) -> Rule {
        Rule { new, old, unit }
    }

    fn apply(object: &mut Map<String, Value>, rules: &[Rule]) {
        for rule in rules {
            let Some(value) = object.remove(rule.new) else {
                continue;
            };
            let legacy = match &value {
                Value::String(text) => match text.parse::<ConfigSize>() {
                    Ok(size) => Value::from(size.as_bytes().div_ceil(rule.unit.bytes())),
                    Err(_) => {
                        object.insert(rule.new.to_string(), value);
                        continue;
                    }
                },
                // The older keys took no `null`: it meant "unset".
                Value::Null => continue,
                // A bare number already has the older meaning.
                other => other.clone(),
            };
            object.insert(rule.old.to_string(), legacy);
        }
    }
    fn child<'a>(
        object: &'a mut Map<String, Value>,
        key: &str,
    ) -> Option<&'a mut Map<String, Value>> {
        object.get_mut(key).and_then(Value::as_object_mut)
    }
    /// One connector of `inputs` or `outputs`.
    fn connector(endpoint: &mut Map<String, Value>) {
        apply(
            endpoint,
            &[rule("max_queued_size", "max_queued_bytes", Bytes)],
        );
        let name = endpoint
            .get("transport")
            .and_then(|transport| transport.get("name"))
            .and_then(Value::as_str)
            .map(str::to_string);
        if let Some(transport) = child(endpoint, "transport").and_then(|t| child(t, "config")) {
            match name.as_deref() {
                Some("file_input") => apply(
                    transport,
                    &[rule("buffer_size", "buffer_size_bytes", Bytes)],
                ),
                Some("dynamodb_output" | "postgres_output") => apply(
                    transport,
                    &[rule("max_buffer_size", "max_buffer_size_bytes", Bytes)],
                ),
                Some("postgres_cdc_input") => {
                    if let Some(batch) = child(transport, "batch") {
                        apply(batch, &[rule("max_size", "max_bytes", Bytes)]);
                    }
                }
                _ => {}
            }
        }
    }

    let Some(global) = config.as_object_mut() else {
        return;
    };
    apply(
        global,
        &[
            rule("max_rss", "max_rss_mb", Megabytes),
            rule("datafusion_memory", "datafusion_memory_mb", Megabytes),
        ],
    );
    if let Some(storage) = child(global, "storage") {
        apply(
            storage,
            &[
                rule("cache_size", "cache_mib", Mebibytes),
                rule("min_spill_size", "min_storage_bytes", Bytes),
                rule("min_step_spill_size", "min_step_storage_bytes", Bytes),
            ],
        );
    }
    if let Some(resources) = child(global, "resources") {
        apply(
            resources,
            &[
                rule("memory_min", "memory_mb_min", Megabytes),
                rule("memory_max", "memory_mb_max", Megabytes),
                rule("storage_min", "storage_mb_min", Megabytes),
                rule("storage_max", "storage_mb_max", Megabytes),
            ],
        );
        if let Some(storage) = child(resources, "autoscaling").and_then(|a| child(a, "storage")) {
            apply(
                storage,
                &[rule(
                    "scale_threshold_available",
                    "scale_threshold_available_mb",
                    Megabytes,
                )],
            );
        }
    }
    if let Some(tweaks) = child(global, "dev_tweaks") {
        apply(
            tweaks,
            &[
                rule("storage_max", "storage_mb_max", Mebibytes),
                rule(
                    "fbuf_slab_size_per_class",
                    "fbuf_slab_bytes_per_class",
                    Bytes,
                ),
                rule(
                    "lazy_input_map_key_block_size",
                    "lazy_input_map_key_block_bytes",
                    Bytes,
                ),
                rule(
                    "exchange_channel_capacity",
                    "exchange_channel_capacity_bytes",
                    Bytes,
                ),
            ],
        );
    }
    for endpoints in ["inputs", "outputs"] {
        if let Some(endpoints) = child(global, endpoints) {
            for endpoint in endpoints.values_mut().filter_map(Value::as_object_mut) {
                connector(endpoint);
            }
        }
    }
}

#[cfg(test)]
mod test {
    use super::deserialize_fault_tolerance;
    use crate::config::{
        ConnectorConfig, DEFAULT_CLOCK_RESOLUTION, DEFAULT_DATAFUSION_MEMORY_CEILING,
        DEFAULT_PULL_INTERVAL, DEFAULT_RETENTION_MIN_AGE, FileBackendConfig, FtConfig, FtModel,
        OutputBufferConfig, PipelineConfig, ResourceConfig, RuntimeConfig, StorageBackendConfig,
        StorageOptions, SyncConfig, TransportConfig,
    };
    use crate::duration::ConfigDuration;
    use crate::size::ConfigSize;
    use serde::{Deserialize, Serialize};
    use serde_json::json;
    use std::time::Duration;

    /// Reads `value` as a `T`, writes it back, and reads that again: the
    /// configuration Feldera stores must load the way the one it was given did.
    fn assert_reloads<T>(value: serde_json::Value)
    where
        T: Serialize + for<'de> Deserialize<'de>,
    {
        let first: T = serde_json::from_value(value.clone())
            .unwrap_or_else(|e| panic!("{value} does not load: {e}"));
        let written = serde_json::to_value(&first).unwrap();
        let second: T = serde_json::from_value(written.clone()).unwrap_or_else(|e| {
            panic!("{value} is written as {written}, which does not load: {e}")
        });
        assert_eq!(serde_json::to_value(&second).unwrap(), written, "{value}");
    }

    /// Every size setting reloads from what Feldera writes back, whatever the
    /// size. Zero, and a size no named unit divides, are written in bytes,
    /// and a setting that once counted megabytes refuses a string without a
    /// unit, so that form must carry one.
    #[test]
    fn size_settings_reload_from_what_is_written() {
        use crate::transport::dynamodb::DynamoDBWriterConfig;
        use crate::transport::file::FileInputConfig;
        use crate::transport::postgres::{PostgresCdcBatchConfig, PostgresWriterConfig};

        // Under the earlier names, a bare number in the earlier unit, as
        // `datafusion_memory_mb: 0` or `cache_mib: 0`.
        for number in [0u64, 1, 1_100, u64::MAX] {
            assert_reloads::<RuntimeConfig>(json!({
                "max_rss_mb": number,
                "datafusion_memory_mb": number,
                "storage": {"cache_mib": number, "min_storage_bytes": number},
                "resources": {"memory_mb_min": number, "storage_mb_max": number},
                "dev_tweaks": {"storage_mb_max": number},
            }));
        }

        let max = format!("{}B", u64::MAX);
        for size in ["0B", "1B", "999B", "1.1Gi", "1.1G", "16G", "8Gi", &max] {
            assert_reloads::<RuntimeConfig>(json!({
                "max_rss": size,
                "datafusion_memory": size,
                "storage": {
                    "cache_size": size,
                    "min_spill_size": size,
                    "min_step_spill_size": size,
                },
                "resources": {
                    "memory_min": size,
                    "memory_max": size,
                    "storage_min": size,
                    "storage_max": size,
                    "autoscaling": {"storage": {"scale_threshold_available": size}},
                },
                "dev_tweaks": {
                    "storage_max": size,
                    "fbuf_slab_size_per_class": size,
                    "exchange_channel_capacity": size,
                },
            }));
            assert_reloads::<ConnectorConfig>(json!({
                "transport": {
                    "name": "file_input",
                    "config": {"path": "input.csv", "buffer_size": size},
                },
                "max_queued_size": size,
            }));
            assert_reloads::<FileInputConfig>(json!({"path": "input.csv", "buffer_size": size}));
            assert_reloads::<PostgresCdcBatchConfig>(json!({"max_size": size}));
            assert_reloads::<PostgresWriterConfig>(json!({
                "uri": "postgres://localhost/db",
                "table": "t",
                "max_buffer_size": size,
            }));
            assert_reloads::<DynamoDBWriterConfig>(json!({
                "table": "t",
                "region": "us-east-1",
                "max_buffer_size": size,
            }));
        }
    }

    /// A configuration written by an older version of Feldera carries no
    /// `soft_delete` field, and a connector that does not use soft deletes
    /// serializes exactly as it did before the field existed.  This keeps
    /// configurations readable and writable across versions.
    #[test]
    fn soft_delete_is_backward_compatible() {
        let config: ConnectorConfig = serde_json::from_value(json!({
            "transport": {"name": "empty_input"}
        }))
        .unwrap();
        assert!(!config.soft_delete);

        let serialized = serde_json::to_value(&config).unwrap();
        assert_eq!(serialized.get("soft_delete"), None);

        let config: ConnectorConfig = serde_json::from_value(json!({
            "transport": {"name": "empty_input"},
            "soft_delete": true
        }))
        .unwrap();
        assert!(config.soft_delete);
        assert_eq!(
            serde_json::to_value(&config).unwrap().get("soft_delete"),
            Some(&json!(true))
        );
    }

    /// Soft deletes change how input is interpreted, so flipping the flag must
    /// count as a connector change even where flow-control settings do not.
    #[test]
    fn soft_delete_invalidates_checkpointed_connector_state() {
        let config = ConnectorConfig::new(TransportConfig::EmptyInput, None);
        let mut soft_delete = config.clone();
        soft_delete.soft_delete = true;

        assert!(config.equal_for_input_checkpoint_replay(&config));
        assert!(!config.equal_for_input_checkpoint_replay(&soft_delete));
    }

    fn config_with_name(name: Option<&str>) -> PipelineConfig {
        PipelineConfig {
            global: RuntimeConfig::default(),
            multihost: None,
            name: name.map(str::to_string),
            given_name: None,
            storage_config: None,
            secrets_dir: None,
            inputs: Default::default(),
            outputs: Default::default(),
            program_ir: None,
        }
    }

    #[test]
    fn pipeline_identity_uses_system_and_given_names() {
        let mut config = config_with_name(Some("pipeline-018f6f57-4e15-7438-91af-3fd21ff2a8d3"));
        config.given_name = Some("my-pipeline".to_string());

        let metadata = config.pipeline_identity().unwrap();
        assert_eq!(
            metadata.name,
            "pipeline-018f6f57-4e15-7438-91af-3fd21ff2a8d3"
        );
        assert_eq!(metadata.given_name.as_deref(), Some("my-pipeline"));
    }

    #[test]
    fn pipeline_identity_is_none_without_system_name() {
        assert_eq!(config_with_name(None).pipeline_identity(), None);
    }

    #[test]
    fn resolved_datafusion_memory_explicit_passes_through() {
        let config = RuntimeConfig {
            max_rss: Some(ConfigSize::from_mb(8_000)),
            datafusion_memory: Some(ConfigSize::from_mb(1_500)),
            ..Default::default()
        };
        assert_eq!(
            config.resolved_datafusion_memory(),
            Some(ConfigSize::from_mb(1_500))
        );
    }

    #[test]
    fn resolved_datafusion_memory_unconfigured_returns_none() {
        let config = RuntimeConfig::default();
        assert!(config.max_rss.is_none());
        assert!(config.resources.memory_max.is_none());
        assert_eq!(config.resolved_datafusion_memory(), None);
    }

    #[test]
    fn resolved_datafusion_memory_small_budget_scales_down() {
        // Small pipelines must provision cleanly; the default just shrinks.
        let config = RuntimeConfig {
            max_rss: Some(ConfigSize::from_mb(256)),
            ..Default::default()
        };
        assert_eq!(
            config.resolved_datafusion_memory(),
            Some(ConfigSize::from_bytes(12_800_000))
        );

        let config = RuntimeConfig {
            max_rss: Some(ConfigSize::from_mb(512)),
            ..Default::default()
        };
        assert_eq!(
            config.resolved_datafusion_memory(),
            Some(ConfigSize::from_bytes(25_600_000))
        );
    }

    #[test]
    fn resolved_datafusion_memory_clamps_to_ceiling_for_large_budgets() {
        // 5% of 64 GB = 3.2 GB, above the 2 GB ceiling.
        let config = RuntimeConfig {
            max_rss: Some(ConfigSize::from_mb(64_000)),
            ..Default::default()
        };
        assert_eq!(
            config.resolved_datafusion_memory(),
            Some(DEFAULT_DATAFUSION_MEMORY_CEILING),
        );
    }

    #[test]
    fn resolved_datafusion_memory_midrange_uses_five_percent() {
        // 5% of 16 GB = 800 MB, inside the clamp range.
        let config = RuntimeConfig {
            max_rss: Some(ConfigSize::from_mb(16_000)),
            ..Default::default()
        };
        assert_eq!(
            config.resolved_datafusion_memory(),
            Some(ConfigSize::from_mb(800))
        );
    }

    #[test]
    fn resolved_datafusion_memory_falls_back_to_resources() {
        // No max_rss, but resources.memory_max is set.
        let config = RuntimeConfig {
            max_rss: None,
            resources: ResourceConfig {
                memory_max: Some(ConfigSize::from_mb(16_000)),
                ..Default::default()
            },
            ..Default::default()
        };
        assert_eq!(
            config.resolved_datafusion_memory(),
            Some(ConfigSize::from_mb(800))
        );
    }

    #[test]
    fn ft_config() {
        #[derive(Serialize, Deserialize, Default, PartialEq, Eq, Debug)]
        #[serde(default)]
        struct Wrapper {
            #[serde(deserialize_with = "deserialize_fault_tolerance")]
            config: FtConfig,
        }

        // Omitting FtConfig, or specifying null, or specifying model "none",
        // disables fault tolerance.
        for s in [
            "{}",
            r#"{"config": null}"#,
            r#"{"config": {"model": "none"}}"#,
        ] {
            let config: Wrapper = serde_json::from_str(s).unwrap();
            assert_eq!(config.config.model, None);
            assert_eq!(config.config.checkpoint_interval(), None);
        }

        // Serializing disabled FT produces explicit "none" form.
        let s = serde_json::to_string(&Wrapper {
            config: FtConfig::default(),
        })
        .unwrap();
        assert!(s.contains("\"none\""));

        // `{}` for FtConfig, or `{...}` with an interval but no `model`,
        // enables fault tolerance with a 60 second interval.
        for s in [
            r#"{}"#,
            r#"{"checkpoint_interval": "60s"}"#,
            r#"{"checkpoint_interval_secs": 60}"#,
        ] {
            let config = serde_json::from_str::<FtConfig>(s).unwrap();
            assert_eq!(config.model, Some(FtModel::default()), "parsing {s}");
            assert_eq!(
                config.checkpoint_interval(),
                Some(Duration::from_secs(60)),
                "parsing {s}"
            );
        }

        // An explicit `null` interval disables periodic checkpointing, under
        // the current name and under the deprecated one.
        for s in [
            r#"{"checkpoint_interval": null}"#,
            r#"{"checkpoint_interval_secs": null}"#,
        ] {
            let config = serde_json::from_str::<FtConfig>(s).unwrap();
            assert_eq!(config.model, Some(FtModel::default()), "parsing {s}");
            assert_eq!(config.checkpoint_interval(), None, "parsing {s}");
        }

        // Both spellings reach one field, so writing both is a duplicate, not
        // a contest one of them wins.
        let error = serde_json::from_str::<FtConfig>(
            r#"{"checkpoint_interval": "5m", "checkpoint_interval_secs": 10}"#,
        )
        .unwrap_err()
        .to_string();
        assert!(error.contains("duplicate field"), "{error}");

        // The interval is clamped to between one second and one hour.
        for (json, expected_secs) in [
            (r#"{"checkpoint_interval": "1ms"}"#, 1),
            (r#"{"checkpoint_interval": "10h"}"#, 3600),
        ] {
            assert_eq!(
                serde_json::from_str::<FtConfig>(json)
                    .unwrap()
                    .checkpoint_interval(),
                Some(Duration::from_secs(expected_secs)),
                "parsing {json}"
            );
        }
    }

    /// The configuration handed to a pinned runtime carries every duration
    /// setting under its older key, in the older unit, and nothing under the
    /// current names, which a runtime older than the rename ignores.
    #[test]
    fn legacy_duration_spelling_uses_the_older_keys() {
        let mut config = serde_json::json!({
            "workers": 2,
            "clock_resolution": "250ms",
            "max_buffering_delay": "3ms",
            "provisioning_timeout": "15m",
            "fault_tolerance": {"model": "at_least_once", "checkpoint_interval": "20s"},
            "storage": {"backend": {"name": "file", "config": {
                "ioop_latency": "5ms",
                "sync": {"bucket": "b", "standby_pull_interval": "10s",
                         "checkpoint_push_interval": "1h", "min_retention": "30d"}}}},
        });
        super::to_legacy_duration_spelling(&mut config);
        assert_eq!(
            config,
            serde_json::json!({
                "workers": 2,
                "clock_resolution_usecs": 250_000,
                "max_buffering_delay_usecs": 3_000,
                "provisioning_timeout_secs": 900,
                "fault_tolerance": {"model": "at_least_once", "checkpoint_interval_secs": 20},
                "storage": {"backend": {"name": "file", "config": {
                    "ioop_delay": 5,
                    "sync": {"bucket": "b", "pull_interval": 10,
                             "push_interval": 3_600, "retention_min_age": 30}}}},
            })
        );
    }

    /// Every connector that has a duration setting, in the current spelling.
    fn pipeline_with_every_duration_connector() -> serde_json::Value {
        serde_json::json!({
            "name": "p",
            "clock_resolution": "250ms",
            "inputs": {
                "t.kafka": {"stream": "t", "transport": {"name": "kafka_input", "config": {
                    "topic": "t", "group_join_timeout": "30s"}}},
                "t.url": {"stream": "t", "transport": {"name": "url_input", "config": {
                    "path": "http://x", "pause_linger": "7s"}}},
                "t.nats": {"stream": "t", "transport": {"name": "nats_input", "config": {
                    "connection_config": {"server_url": "nats://x",
                        "connection_timeout": "5s", "request_timeout": "6s"},
                    "stream_name": "s",
                    "consumer_config": {"deliver_policy": "All", "max_expiry": "45.5s"},
                    "inactivity_timeout": "90s", "retry_interval": "3s"}}},
                "t.pubsub": {"stream": "t", "transport": {"name": "pub_sub_input", "config": {
                    "subscription": "s", "timeout": "20s", "connect_timeout": "4s"}}},
            },
            "outputs": {
                "v.kafka": {"stream": "v",
                    "transport": {"name": "kafka_output", "config": {
                        "topic": "v", "initialization_timeout": "40s"}},
                    "format": {"name": "avro", "config": {"registry_urls": ["http://r"],
                        "registry_timeout": "8s"}},
                    "enable_output_buffer": true,
                    "max_output_buffer_time": "500ms"},
                "v.nats": {"stream": "v", "transport": {"name": "nats_output", "config": {
                    "connection_config": {"server_url": "nats://x",
                        "connection_timeout": "5s", "request_timeout": "6s"},
                    "subject": "s", "publish_timeout": "9s"}}},
            },
        })
    }

    /// Connectors are rewritten too, each under the key and in the unit its
    /// transport used before the rename; the NATS expiry becomes the
    /// `{secs, nanos}` object it was.
    #[test]
    fn legacy_duration_spelling_rewrites_every_connector() {
        let mut config = pipeline_with_every_duration_connector();
        super::to_legacy_duration_spelling(&mut config);
        let i = &config["inputs"];
        assert_eq!(
            i["t.kafka"]["transport"]["config"]["group_join_timeout_secs"],
            30
        );
        assert_eq!(i["t.url"]["transport"]["config"]["pause_timeout"], 7);
        let nats = &i["t.nats"]["transport"]["config"];
        assert_eq!(nats["connection_config"]["connection_timeout_secs"], 5);
        assert_eq!(nats["connection_config"]["request_timeout_secs"], 6);
        assert_eq!(nats["inactivity_timeout_secs"], 90);
        assert_eq!(nats["retry_interval_secs"], 3);
        assert_eq!(
            nats["consumer_config"]["max_expires"],
            serde_json::json!({"secs": 45, "nanos": 500_000_000})
        );
        let pubsub = &i["t.pubsub"]["transport"]["config"];
        assert_eq!(pubsub["timeout_seconds"], 20);
        assert_eq!(pubsub["connect_timeout_seconds"], 4);
        let out = &config["outputs"]["v.kafka"];
        assert_eq!(
            out["transport"]["config"]["initialization_timeout_secs"],
            40
        );
        assert_eq!(out["format"]["config"]["registry_timeout_secs"], 8);
        assert_eq!(out["max_output_buffer_time_millis"], 500);
        let nats = &config["outputs"]["v.nats"]["transport"]["config"];
        assert_eq!(nats["connection_config"]["connection_timeout_secs"], 5);
        assert_eq!(nats["connection_config"]["request_timeout_secs"], 6);
        assert_eq!(nats["publish_timeout_secs"], 9);

        // No current name survives anywhere in the file.
        let text = config.to_string();
        for new in [
            "\"group_join_timeout\"",
            "\"pause_linger\"",
            "\"connection_timeout\"",
            "\"request_timeout\"",
            "\"inactivity_timeout\"",
            "\"retry_interval\"",
            "\"max_expiry\"",
            "\"timeout\"",
            "\"connect_timeout\"",
            "\"initialization_timeout\"",
            "\"registry_timeout\"",
            "\"max_output_buffer_time\"",
            "\"publish_timeout\"",
            "\"clock_resolution\"",
        ] {
            assert!(!text.contains(new), "{new} survived in {text}");
        }
    }

    /// The rewritten connectors mean the same to this release as the originals.
    #[test]
    fn legacy_duration_spelling_round_trips_connectors() {
        let original: PipelineConfig =
            serde_json::from_value(pipeline_with_every_duration_connector()).unwrap();
        let mut value = serde_json::to_value(&original).unwrap();
        super::to_legacy_duration_spelling(&mut value);
        let mut reread: PipelineConfig = serde_json::from_value(value).unwrap();

        // The format config stays raw JSON until the encoder parses it, so
        // compare it the way the encoder reads it.
        let registry = |config: &PipelineConfig| {
            let format = config.outputs["v.kafka"]
                .connector_config
                .format
                .clone()
                .unwrap();
            serde_json::from_value::<crate::format::avro::AvroEncoderConfig>(format.config)
                .unwrap()
                .registry_config
                .registry_timeout
        };
        assert_eq!(registry(&reread), registry(&original));
        let mut original = original;
        for config in [&mut reread, &mut original] {
            config
                .outputs
                .get_mut("v.kafka")
                .unwrap()
                .connector_config
                .format = None;
        }
        assert_eq!(reread, original);
    }

    /// A duration too long for the older field is capped at the largest value
    /// it holds, rather than wrapping; a bare number already under the current
    /// key keeps its value, since it already counts the older unit.
    #[test]
    fn legacy_duration_spelling_caps_and_keeps_bare_numbers() {
        let mut config = serde_json::json!({
            "inputs": {
                "t.kafka": {"transport": {"name": "kafka_input", "config": {
                    "group_join_timeout": "100000000000s"}}},
                "t.url": {"transport": {"name": "url_input", "config": {"pause_linger": 9}}},
            },
            "storage": {"backend": {"name": "file", "config": {
                "sync": {"min_retention": "100000000000d"}}}},
        });
        super::to_legacy_duration_spelling(&mut config);
        let i = &config["inputs"];
        assert_eq!(
            i["t.kafka"]["transport"]["config"]["group_join_timeout_secs"],
            u64::from(u32::MAX)
        );
        assert_eq!(i["t.url"]["transport"]["config"]["pause_timeout"], 9);
        assert_eq!(
            config["storage"]["backend"]["config"]["sync"]["retention_min_age"],
            u64::from(u32::MAX)
        );
    }

    /// The older spelling means the same settings to this release, so the
    /// rewrite changes what an older runtime reads without changing what a
    /// newer one does.
    #[test]
    fn legacy_duration_spelling_round_trips() {
        let original: RuntimeConfig = serde_json::from_value(serde_json::json!({
            "clock_resolution": "250ms",
            "max_buffering_delay": "3ms",
            "provisioning_timeout": "15m",
            "fault_tolerance": {"model": "at_least_once", "checkpoint_interval": "20s"},
        }))
        .unwrap();
        let mut value = serde_json::to_value(&original).unwrap();
        super::to_legacy_duration_spelling(&mut value);
        let reread: RuntimeConfig = serde_json::from_value(value).unwrap();
        assert_eq!(reread.clock_resolution(), original.clock_resolution());
        assert_eq!(reread.max_buffering_delay(), original.max_buffering_delay());
        assert_eq!(reread.provisioning_timeout, original.provisioning_timeout);
        assert_eq!(
            reread.fault_tolerance.checkpoint_interval(),
            original.fault_tolerance.checkpoint_interval()
        );
    }

    /// Durations that are not a whole number of the older unit round up, so a
    /// short timeout never becomes a zero one; a disabled checkpoint stays
    /// disabled; an unset required field is dropped rather than written as
    /// `null`; a value that does not parse is left for the runtime to reject.
    #[test]
    fn legacy_duration_spelling_edge_cases() {
        let mut config = serde_json::json!({
            "max_buffering_delay": null,
            "provisioning_timeout": "1.5s",
            "fault_tolerance": {"checkpoint_interval": null},
            "clock_resolution": "10sec",
            "storage": {"backend": {"name": "file", "config": {
                "ioop_latency": "400us",
                "sync": {"bucket": "b", "min_retention": "11h", "standby_pull_interval": "400ms"}}}},
        });
        super::to_legacy_duration_spelling(&mut config);
        assert_eq!(
            config,
            serde_json::json!({
                "provisioning_timeout_secs": 2,
                "fault_tolerance": {"checkpoint_interval_secs": null},
                "clock_resolution": "10sec",
                "storage": {"backend": {"name": "file", "config": {
                    "ioop_delay": 1,
                    "sync": {"bucket": "b", "retention_min_age": 1, "pull_interval": 1}}}},
            })
        );

        // A zero stays a zero: only a positive duration is pushed up to one unit.
        let mut zero = serde_json::json!({"provisioning_timeout": "0"});
        super::to_legacy_duration_spelling(&mut zero);
        assert_eq!(zero, serde_json::json!({"provisioning_timeout_secs": 0}));

        // Already in the older spelling: nothing to do.
        let legacy = serde_json::json!({"clock_resolution_usecs": 5, "workers": 1});
        let mut again = legacy.clone();
        super::to_legacy_duration_spelling(&mut again);
        assert_eq!(again, legacy);
    }

    /// The configuration handed to a runtime from before the size rename
    /// carries every size setting under its older key, as a whole number of
    /// the older unit rounded up, and nothing under the current names.
    #[test]
    fn legacy_size_spelling_uses_the_older_keys() {
        let mut config = serde_json::json!({
            "workers": 2,
            "max_rss": "16G",
            "datafusion_memory": "1.5G",
            "storage": {"cache_size": "4Gi", "min_spill_size": "10Mi", "min_step_spill_size": "0"},
            "resources": {
                "memory_min": "4G", "memory_max": "16Gi",
                "storage_min": "100G", "storage_max": "400Gi",
                "autoscaling": {"storage": {"scale_threshold_available": "10G", "scale_factor": 2.0}}
            },
            "dev_tweaks": {
                "storage_max": "1Gi", "fbuf_slab_size_per_class": "16Mi",
                "lazy_input_map_key_block_size": "32Ki", "exchange_channel_capacity": "10M"
            },
            "inputs": {
                "t.file": {"stream": "t", "max_queued_size": "1Mi",
                    "transport": {"name": "file_input", "config": {"path": "x", "buffer_size": "64Ki"}}},
                "t.cdc": {"stream": "t",
                    "transport": {"name": "postgres_cdc_input", "config": {"batch": {"max_size": "32Mi"}}}},
            },
            "outputs": {
                "v.ddb": {"stream": "v",
                    "transport": {"name": "dynamodb_output", "config": {"max_buffer_size": "1Mi"}}},
                "v.pg": {"stream": "v",
                    "transport": {"name": "postgres_output", "config": {"max_buffer_size": "2Mi"}}},
            },
        });
        super::to_legacy_size_spelling(&mut config);
        assert_eq!(
            config,
            serde_json::json!({
                "workers": 2,
                "max_rss_mb": 16_000,
                "datafusion_memory_mb": 1_500,
                "storage": {"cache_mib": 4096, "min_storage_bytes": 10 * 1024 * 1024, "min_step_storage_bytes": 0},
                "resources": {
                    // 16Gi and 400Gi are not whole megabytes: they round up.
                    "memory_mb_min": 4_000, "memory_mb_max": 17_180,
                    "storage_mb_min": 100_000, "storage_mb_max": 429_497,
                    "autoscaling": {"storage": {"scale_threshold_available_mb": 10_000, "scale_factor": 2.0}}
                },
                "dev_tweaks": {
                    "storage_mb_max": 1024, "fbuf_slab_bytes_per_class": 16 * 1024 * 1024,
                    "lazy_input_map_key_block_bytes": 32 * 1024, "exchange_channel_capacity_bytes": 10_000_000
                },
                "inputs": {
                    "t.file": {"stream": "t", "max_queued_bytes": 1024 * 1024,
                        "transport": {"name": "file_input", "config": {"path": "x", "buffer_size_bytes": 64 * 1024}}},
                    "t.cdc": {"stream": "t",
                        "transport": {"name": "postgres_cdc_input", "config": {"batch": {"max_bytes": 32 * 1024 * 1024}}}},
                },
                "outputs": {
                    "v.ddb": {"stream": "v",
                        "transport": {"name": "dynamodb_output", "config": {"max_buffer_size_bytes": 1024 * 1024}}},
                    "v.pg": {"stream": "v",
                        "transport": {"name": "postgres_output", "config": {"max_buffer_size_bytes": 2 * 1024 * 1024}}},
                },
            })
        );
    }

    /// The older size spelling means the same settings to this release, so a
    /// configuration survives the trip out to a pinned runtime and back.
    #[test]
    fn legacy_size_spelling_round_trips() {
        let config: PipelineConfig = serde_json::from_value(serde_json::json!({
            "name": "p",
            "max_rss": "16G",
            // Whole megabytes, mebibytes and bytes: a size the older unit
            // cannot express rounds up and does not come back the same.
            "datafusion_memory": "1G",
            "storage": {"cache_size": "4Gi", "min_spill_size": "10Mi"},
            "resources": {"memory_max": "16G", "storage_max": "400G"},
            "dev_tweaks": {"lazy_input_map_key_block_size": "32Ki"},
            "inputs": {"t.file": {"stream": "t", "max_queued_size": "1Mi",
                "transport": {"name": "file_input", "config": {"path": "x", "buffer_size": "64Ki"}}}},
            "outputs": {},
        }))
        .unwrap();
        let mut value = serde_json::to_value(&config).unwrap();
        super::to_legacy_size_spelling(&mut value);
        assert_eq!(value["max_rss_mb"], serde_json::json!(16_000));
        assert_eq!(
            value["inputs"]["t.file"]["max_queued_bytes"],
            serde_json::json!(1024 * 1024)
        );
        let reread: PipelineConfig = serde_json::from_value(value).unwrap();
        assert_eq!(reread, config);
    }

    /// The executors rewrite only what the runtime needs: a runtime from
    /// between the two renames gets the current durations and the older sizes.
    #[test]
    fn legacy_spelling_applies_each_rename_separately() {
        let current = serde_json::json!({"clock_resolution": "1s", "max_rss": "16G"});
        let mut both = current.clone();
        super::LegacySpelling {
            durations: true,
            sizes: true,
        }
        .apply(&mut both);
        assert_eq!(
            both,
            serde_json::json!({"clock_resolution_usecs": 1_000_000, "max_rss_mb": 16_000})
        );
        let mut sizes_only = current.clone();
        super::LegacySpelling {
            durations: false,
            sizes: true,
        }
        .apply(&mut sizes_only);
        assert_eq!(
            sizes_only,
            serde_json::json!({"clock_resolution": "1s", "max_rss_mb": 16_000})
        );
        let mut none = current.clone();
        super::LegacySpelling::NONE.apply(&mut none);
        assert_eq!(none, current);
        assert!(!super::LegacySpelling::NONE.any());
    }

    #[test]
    fn legacy_size_spelling_edge_cases() {
        // A value that does not parse stays under the current key, for the
        // runtime to reject, and a `null` meant "unset" under either key.
        let mut config = serde_json::json!({
            "max_rss": "lots",
            "resources": {"memory_max": null, "memory_min": 4000}
        });
        super::to_legacy_size_spelling(&mut config);
        assert_eq!(
            config,
            serde_json::json!({"max_rss": "lots", "resources": {"memory_mb_min": 4000}})
        );

        // A fraction of the older unit rounds up, so a small cap never
        // becomes a `0` the older runtime reads as no cap.
        let mut small = serde_json::json!({"max_rss": "1"});
        super::to_legacy_size_spelling(&mut small);
        assert_eq!(small, serde_json::json!({"max_rss_mb": 1}));

        // Already in the older spelling: nothing to do.
        let legacy = serde_json::json!({"max_rss_mb": 5, "workers": 1});
        let mut again = legacy.clone();
        super::to_legacy_size_spelling(&mut again);
        assert_eq!(again, legacy);
    }

    /// A connector nobody touched compares equal across the rename.
    ///
    /// A configuration stored by an older release carries each duration at its
    /// default, because the fields it used could not be absent. A freshly
    /// parsed one leaves them out. Both mean the same thing, and the diff that
    /// decides whether to keep a connector's checkpointed position has to agree
    /// with that: otherwise the connector reads as modified and the controller
    /// restarts its ingestion from the beginning.
    #[test]
    fn a_stored_default_matches_an_omitted_one() {
        let stored: ConnectorConfig = serde_json::from_value(serde_json::json!({
            "transport": {
                "name": "url_input",
                "config": {"path": "http://example.com/x", "pause_timeout": 60},
            }
        }))
        .unwrap();
        let fresh: ConnectorConfig = serde_json::from_value(serde_json::json!({
            "transport": {
                "name": "url_input",
                "config": {"path": "http://example.com/x"},
            }
        }))
        .unwrap();

        // The two differ field by field, which is what the derived `PartialEq`
        // sees, yet they configure the same connector.
        assert_ne!(stored, fresh);
        assert!(stored.equal_for_input_checkpoint_replay(&fresh));

        // A real difference still reads as one.
        let changed: ConnectorConfig = serde_json::from_value(serde_json::json!({
            "transport": {
                "name": "url_input",
                "config": {"path": "http://example.com/x", "pause_linger": "90s"},
            }
        }))
        .unwrap();
        assert!(!stored.equal_for_input_checkpoint_replay(&changed));
    }

    /// An Avro schema registry timeout compares equal across the rename.
    ///
    /// The format configuration stays raw JSON until the format parses it, so
    /// the connector comparison has to read the timeout the way the format
    /// does: otherwise following the deprecation warning, from
    /// `registry_timeout_secs: 10` to `registry_timeout: "10s"`, reads as a
    /// modified connector and an Avro input is read again from the beginning.
    #[test]
    fn an_avro_registry_timeout_compares_equal_across_the_rename() {
        let connector = |registry: serde_json::Value| -> ConnectorConfig {
            let mut format = serde_json::json!({"registry_urls": ["http://registry:8081"]});
            format
                .as_object_mut()
                .unwrap()
                .extend(registry.as_object().unwrap().clone());
            serde_json::from_value(serde_json::json!({
                "transport": {
                    "name": "url_input",
                    "config": {"path": "http://example.com/x"},
                },
                "format": {"name": "avro", "config": format},
            }))
            .unwrap()
        };
        let stored = connector(serde_json::json!({"registry_timeout_secs": 10}));
        let current = connector(serde_json::json!({"registry_timeout": "10s"}));
        let spelled_out = connector(serde_json::json!({"registry_timeout": "10000ms"}));
        let changed = connector(serde_json::json!({"registry_timeout": "11s"}));
        let unset = connector(serde_json::json!({}));

        assert!(stored.equal_modulo_paused(&current));
        assert!(stored.equal_for_input_checkpoint_replay(&current));
        assert!(current.equal_modulo_paused(&spelled_out));
        assert!(!stored.equal_modulo_paused(&changed));
        assert!(!stored.equal_modulo_paused(&unset));
        // The other formats carry no duration and are left alone.
        let json: ConnectorConfig = serde_json::from_value(serde_json::json!({
            "transport": {"name": "url_input", "config": {"path": "http://example.com/x"}},
            "format": {"name": "json", "config": {"registry_timeout_secs": 10}},
        }))
        .unwrap();
        assert!(!json.equal_modulo_paused(&stored));
    }

    /// The defaults an older release wrote out still load.
    ///
    /// `max_output_buffer_time_millis` defaulted to `usize::MAX` and was
    /// serialized into every output connector, so scaling it into nanoseconds
    /// has to survive rather than reject the configuration.
    #[test]
    fn the_largest_legacy_defaults_still_load() {
        let buffer: OutputBufferConfig = serde_json::from_value(serde_json::json!({
            "enable_output_buffer": false,
            "max_output_buffer_time_millis": u64::MAX,
            "max_output_buffer_size_records": 10_000_000u64,
        }))
        .unwrap();
        assert_eq!(
            buffer.max_output_buffer_time,
            Some(ConfigDuration::from_millis(u64::MAX))
        );

        // The widest legacy unit, days, also survives.
        let sync: SyncConfig =
            serde_json::from_str(r#"{"bucket": "b", "retention_min_age": 4000000000}"#).unwrap();
        assert_eq!(
            sync.min_retention(),
            ConfigDuration::from_days(4_000_000_000)
        );
    }

    /// A legacy number too large for a `u64` of seconds saturates at the
    /// longest duration there is rather than failing to load: an older
    /// release accepted it.
    #[test]
    fn a_legacy_number_past_u64_seconds_saturates() {
        let sync: SyncConfig =
            serde_json::from_str(r#"{"bucket": "b", "retention_min_age": 18446744073709551615}"#)
                .unwrap();
        assert_eq!(
            sync.min_retention(),
            ConfigDuration::from(std::time::Duration::MAX)
        );
    }

    /// Kafka input and NATS connectors stored by an older release carry their
    /// duration defaults spelled out; a fresh configuration leaves them out.
    /// The checkpoint replay comparison must see the two as the same connector.
    #[test]
    fn spelled_out_defaults_match_for_kafka_input_and_nats() {
        fn connector(value: serde_json::Value) -> ConnectorConfig {
            serde_json::from_value(value).unwrap()
        }
        fn secs(duration: ConfigDuration) -> u64 {
            std::time::Duration::from(duration).as_secs()
        }
        let fresh_kafka = connector(serde_json::json!({
            "transport": {"name": "kafka_input", "config": {"topic": "t"}}}));
        let TransportConfig::KafkaInput(kafka) = &fresh_kafka.transport else {
            unreachable!()
        };
        let stored_kafka = connector(serde_json::json!({
            "transport": {"name": "kafka_input", "config": {
                "topic": "t",
                "group_join_timeout_secs": secs(kafka.group_join_timeout())}}}));
        assert_ne!(stored_kafka, fresh_kafka);
        assert!(stored_kafka.equal_for_input_checkpoint_replay(&fresh_kafka));

        let base = serde_json::json!({
            "connection_config": {"server_url": "nats://x"},
            "stream_name": "s",
            "consumer_config": {"deliver_policy": "All"}});
        let fresh_nats = connector(serde_json::json!({
            "transport": {"name": "nats_input", "config": base.clone()}}));
        let TransportConfig::NatsInput(nats) = &fresh_nats.transport else {
            unreachable!()
        };
        let mut spelled_out = base;
        spelled_out["inactivity_timeout_secs"] = secs(nats.inactivity_timeout()).into();
        spelled_out["retry_interval_secs"] = secs(nats.retry_interval()).into();
        spelled_out["connection_config"]["connection_timeout_secs"] =
            secs(nats.connection_config.connection_timeout()).into();
        spelled_out["connection_config"]["request_timeout_secs"] =
            secs(nats.connection_config.request_timeout()).into();
        let stored_nats = connector(serde_json::json!({
            "transport": {"name": "nats_input", "config": spelled_out}}));
        assert_ne!(stored_nats, fresh_nats);
        assert!(stored_nats.equal_for_input_checkpoint_replay(&fresh_nats));
    }

    /// A configuration written before the rename converts itself: the manager
    /// deserializes it and writes it back (`validate_runtime_config`, then
    /// `serde_json::to_value`), so the superseded keys disappear and the
    /// current ones take their place with the same lengths of time. Only then
    /// does the pipeline stop warning about a configuration nobody has edited.
    #[test]
    fn superseded_keys_are_normalised_by_a_round_trip() {
        let stored = serde_json::json!({
            "workers": 4,
            "clock_resolution_usecs": 100_000,
            "max_buffering_delay_usecs": 0,
            "provisioning_timeout_secs": 300,
        });

        let config: RuntimeConfig = serde_json::from_value(stored).unwrap();
        let written = serde_json::to_value(&config).unwrap();

        assert_eq!(written["clock_resolution"], "100ms");
        assert_eq!(written["max_buffering_delay"], "0s");
        assert_eq!(written["provisioning_timeout"], "5m");
        for superseded in [
            "clock_resolution_usecs",
            "max_buffering_delay_usecs",
            "provisioning_timeout_secs",
        ] {
            assert!(
                written.get(superseded).is_none(),
                "`{superseded}` survived the round trip: {written}"
            );
        }

        // The round trip is a fixed point: reading what was written back gives
        // the same document, so a configuration converts once and then settles.
        let reparsed: RuntimeConfig = serde_json::from_value(written.clone()).unwrap();
        assert_eq!(serde_json::to_value(&reparsed).unwrap(), written);
    }

    /// The simulated per-I/O delay reads back from both spellings. Its
    /// superseded name counted milliseconds, one of only two settings that
    /// did, so the unit is worth pinning: `ioop_delay: 5` is five
    /// milliseconds, not five seconds.
    #[test]
    fn ioop_latency_accepts_both_spellings() {
        for (json, expected) in [
            (r#"{"name": "file", "config": {}}"#, None),
            (
                r#"{"name": "file", "config": {"ioop_latency": "5ms"}}"#,
                Some(ConfigDuration::from_millis(5)),
            ),
            (
                r#"{"name": "file", "config": {"ioop_delay": 5}}"#,
                Some(ConfigDuration::from_millis(5)),
            ),
            (
                r#"{"name": "file", "config": {"ioop_latency": "1s"}}"#,
                Some(ConfigDuration::from_secs(1)),
            ),
        ] {
            let backend: StorageBackendConfig = serde_json::from_str(json).unwrap();
            let StorageBackendConfig::File(file) = backend else {
                panic!("expected the file backend, parsing {json}");
            };
            assert_eq!(file.ioop_latency, expected, "parsing {json}");
        }
    }

    /// The clock resolution reads back from both the current field and the one
    /// it deprecates. An explicit `null` selects the default, which is what the
    /// deprecated field did before it gained a replacement.
    #[test]
    fn clock_resolution_falls_back_to_the_deprecated_field() {
        for (json, expected) in [
            (r#"{}"#, DEFAULT_CLOCK_RESOLUTION),
            (
                r#"{"clock_resolution": "100ms"}"#,
                ConfigDuration::from_millis(100),
            ),
            (
                r#"{"clock_resolution_usecs": 100000}"#,
                ConfigDuration::from_millis(100),
            ),
            (r#"{"clock_resolution": null}"#, DEFAULT_CLOCK_RESOLUTION),
            (
                r#"{"clock_resolution_usecs": null}"#,
                DEFAULT_CLOCK_RESOLUTION,
            ),
        ] {
            assert_eq!(
                serde_json::from_str::<RuntimeConfig>(json)
                    .unwrap()
                    .clock_resolution(),
                expected,
                "parsing {json}"
            );
        }
    }

    /// Every duration field reads back from the field it deprecates, in the
    /// unit that field used.
    #[test]
    fn deprecated_duration_fields_still_work() {
        let runtime: RuntimeConfig = serde_json::from_str(
            r#"{"max_buffering_delay_usecs": 5000, "provisioning_timeout_secs": 1200}"#,
        )
        .unwrap();
        assert_eq!(
            runtime.max_buffering_delay(),
            ConfigDuration::from_millis(5)
        );
        assert_eq!(
            runtime.provisioning_timeout,
            Some(ConfigDuration::from_secs(1200))
        );

        let sync: SyncConfig = serde_json::from_str(
            r#"{"bucket": "b", "pull_interval": 30, "push_interval": 300, "retention_min_age": 7}"#,
        )
        .unwrap();
        assert_eq!(sync.standby_pull_interval(), ConfigDuration::from_secs(30));
        assert_eq!(
            sync.checkpoint_push_interval(),
            Some(ConfigDuration::from_secs(300))
        );
        assert_eq!(sync.min_retention(), ConfigDuration::from_days(7));

        let storage: FileBackendConfig = serde_json::from_str(r#"{"ioop_delay": 5}"#).unwrap();
        assert_eq!(storage.ioop_latency, Some(ConfigDuration::from_millis(5)));

        let buffer: OutputBufferConfig =
            serde_json::from_str(r#"{"max_output_buffer_time_millis": 250}"#).unwrap();
        assert_eq!(
            buffer.max_output_buffer_time(),
            ConfigDuration::from_millis(250)
        );
    }

    /// Defaults apply when neither the current field nor the deprecated one is
    /// set.
    #[test]
    fn duration_fields_default_when_unset() {
        let sync: SyncConfig = serde_json::from_str(r#"{"bucket": "b"}"#).unwrap();
        assert_eq!(sync.standby_pull_interval(), DEFAULT_PULL_INTERVAL);
        assert_eq!(sync.checkpoint_push_interval(), None);
        assert_eq!(sync.min_retention(), DEFAULT_RETENTION_MIN_AGE);

        let runtime = RuntimeConfig::default();
        assert_eq!(runtime.max_buffering_delay(), ConfigDuration::ZERO);
        assert_eq!(runtime.clock_resolution(), DEFAULT_CLOCK_RESOLUTION);
        assert_eq!(runtime.provisioning_timeout, None);
    }

    /// Regression test: `Option<f64>` fields inside `StorageOptions` must
    /// survive a JSON-string round-trip through `PipelineConfig`, which uses
    /// `#[serde(flatten)]` on `RuntimeConfig`.
    #[test]
    fn storage_options_f64_roundtrip_through_pipeline_config() {
        let pc = PipelineConfig {
            global: RuntimeConfig {
                storage: Some(StorageOptions {
                    bloom_false_positive_rate: Some(0.01),
                    ..Default::default()
                }),
                ..Default::default()
            },
            multihost: None,
            name: Some("test-pipeline".into()),
            given_name: None,
            storage_config: None,
            secrets_dir: None,
            inputs: Default::default(),
            outputs: Default::default(),
            program_ir: None,
        };

        // JSON string round-trip (the path the pipeline process takes).
        let json = serde_json::to_string_pretty(&pc).unwrap();
        let pc2: PipelineConfig = serde_json::from_str(&json).expect(
            "JSON string round-trip of PipelineConfig with f64 StorageOptions must succeed",
        );
        assert_eq!(
            pc2.global.storage.unwrap().bloom_false_positive_rate,
            Some(0.01)
        );

        // serde_json::Value round-trip (the path the pipeline manager takes).
        let value = serde_json::to_value(&pc).unwrap();
        let pc3: PipelineConfig = serde_json::from_value(value)
            .expect("Value round-trip of PipelineConfig with f64 StorageOptions must succeed");
        assert_eq!(
            pc3.global.storage.unwrap().bloom_false_positive_rate,
            Some(0.01)
        );
    }
}

impl FtConfig {
    pub fn is_enabled(&self) -> bool {
        self.model.is_some()
    }

    /// Returns the checkpoint interval, if fault tolerance is enabled, and
    /// otherwise `None`.
    ///
    /// Falls back to the deprecated `checkpoint_interval_secs` and then to
    /// [`DEFAULT_CHECKPOINT_INTERVAL`]. The interval is clamped to between one
    /// second and one hour.
    pub fn checkpoint_interval(&self) -> Option<Duration> {
        if !self.is_enabled() {
            return None;
        }

        let interval = self
            .checkpoint_interval
            .unwrap_or(Some(DEFAULT_CHECKPOINT_INTERVAL))?;

        Some(Duration::from(interval).clamp(Duration::from_secs(1), Duration::from_secs(3600)))
    }
}

/// Serde implementation for de/serializing a string into `Option<T>` where
/// `"none"` indicates `None` and any other string indicates `Some`.
///
/// This could be extended to handle non-strings by adding more forwarding
/// `visit_*` methods to the Visitor implementation.  I don't see a way to write
/// them automatically.
mod none_as_string {
    use std::marker::PhantomData;

    use serde::de::{Deserialize, Deserializer, IntoDeserializer, Visitor};
    use serde::ser::{Serialize, Serializer};

    pub(super) fn serialize<S, T>(value: &Option<T>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
        T: Serialize,
    {
        match value.as_ref() {
            Some(value) => value.serialize(serializer),
            None => "none".serialize(serializer),
        }
    }

    struct NoneAsString<T>(PhantomData<fn() -> T>);

    impl<'de, T> Visitor<'de> for NoneAsString<T>
    where
        T: Deserialize<'de>,
    {
        type Value = Option<T>;

        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
            formatter.write_str("string")
        }

        fn visit_none<E>(self) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            Ok(None)
        }

        fn visit_str<E>(self, value: &str) -> Result<Option<T>, E>
        where
            E: serde::de::Error,
        {
            if &value.to_ascii_lowercase() == "none" {
                Ok(None)
            } else {
                Ok(Some(T::deserialize(value.into_deserializer())?))
            }
        }
    }

    pub(super) fn deserialize<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
    where
        D: Deserializer<'de>,
        T: Deserialize<'de>,
    {
        deserializer.deserialize_str(NoneAsString(PhantomData))
    }
}

/// Generates an OpenAPI schema for an `Option<T>` field serialized with `none_as_string`.
/// The schema is a `oneOf` with a reference to `T`'s schema and a `"none"` string enum.
fn none_as_string_schema<'a, T: ToSchema<'a> + Default + Serialize>() -> Schema {
    Schema::OneOf(
        OneOfBuilder::new()
            .item(RefOr::Ref(Ref::new(format!(
                "#/components/schemas/{}",
                T::schema().0
            ))))
            .item(
                ObjectBuilder::new()
                    .schema_type(SchemaType::String)
                    .enum_values(Some(vec!["none"])),
            )
            .default(Some(
                serde_json::to_value(T::default()).expect("Failed to serialize default value"),
            ))
            .build(),
    )
}

/// Fault tolerance model.
///
/// The ordering is significant: we consider [Self::ExactlyOnce] to be a "higher
/// level" of fault tolerance than [Self::AtLeastOnce].
#[derive(
    Debug, Copy, Clone, Default, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize, ToSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum FtModel {
    /// Each record is output at least once.  Crashes may duplicate output, but
    /// no input or output is dropped.
    AtLeastOnce,

    /// Each record is output exactly once.  Crashes do not drop or duplicate
    /// input or output.
    #[default]
    ExactlyOnce,
}

impl FtModel {
    pub fn option_as_str(value: Option<FtModel>) -> &'static str {
        value.map_or("no", |model| model.as_str())
    }

    pub fn as_str(&self) -> &'static str {
        match self {
            FtModel::AtLeastOnce => "at_least_once",
            FtModel::ExactlyOnce => "exactly_once",
        }
    }
}

/// The string does not name a fault tolerance model.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FtModelUnknown;

impl std::fmt::Display for FtModelUnknown {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("expected `exactly_once` or `at_least_once`")
    }
}

impl std::error::Error for FtModelUnknown {}

impl FromStr for FtModel {
    type Err = FtModelUnknown;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_ascii_lowercase().as_str() {
            "exactly_once" => Ok(Self::ExactlyOnce),
            "at_least_once" => Ok(Self::AtLeastOnce),
            _ => Err(FtModelUnknown),
        }
    }
}

/// Describes an input connector configuration
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct InputEndpointConfig {
    /// The name of the input stream of the circuit that this endpoint is
    /// connected to.
    pub stream: Cow<'static, str>,

    /// Connector configuration.
    #[serde(flatten)]
    pub connector_config: ConnectorConfig,
}

impl InputEndpointConfig {
    pub fn new(stream: impl Into<Cow<'static, str>>, connector_config: ConnectorConfig) -> Self {
        Self {
            stream: stream.into(),
            connector_config,
        }
    }
}

/// Deserialize the `start_after` property of a connector configuration.
/// It requires a non-standard deserialization because we want to accept
/// either a string or an array of strings.
fn deserialize_start_after<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
where
    D: Deserializer<'de>,
{
    let value = Option::<JsonValue>::deserialize(deserializer)?;
    match value {
        Some(JsonValue::String(s)) => Ok(Some(vec![s])),
        Some(JsonValue::Array(arr)) => {
            let vec = arr
                .into_iter()
                .map(|item| {
                    item.as_str()
                        .map(|s| s.to_string())
                        .ok_or_else(|| serde::de::Error::custom("invalid 'start_after' property: expected a string, an array of strings, or null"))
                })
                .collect::<Result<Vec<String>, _>>()?;
            Ok(Some(vec))
        }
        Some(JsonValue::Null) | None => Ok(None),
        _ => Err(serde::de::Error::custom(
            "invalid 'start_after' property: expected a string, an array of strings, or null",
        )),
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct ConnectorConfig {
    /// Send a full snapshot of a materialized view when the connector first
    /// starts. Valid for output connectors only.
    ///
    /// When `true`, the pipeline emits the current contents of the view as the
    /// initial batch the first time the connector runs. The view must be
    /// materialized (declared with `CREATE MATERIALIZED VIEW`).
    ///
    /// The snapshot is sent exactly once per connector lifetime: it does not
    /// fire again when the pipeline resumes from a checkpoint. Modifying the
    /// connector configuration or invoking the reset API triggers a fresh
    /// snapshot when the connector supports reset (e.g., Delta Lake in
    /// `truncate` mode and Postgres).
    #[serde(default)]
    pub send_snapshot: bool,

    /// Ingest deletions as insertions, recording the original polarity in the
    /// `is_delete` metadata attribute. Valid for input connectors only.
    ///
    /// When `true`, a delete received by the connector is pushed to the table
    /// as an insertion of the same record, and the connector attaches the
    /// `is_delete` metadata attribute set to `true` to it. Insertions carry no
    /// `is_delete` attribute, so a column declared as
    /// `DEFAULT CAST(CONNECTOR_METADATA()['is_delete'] AS BOOLEAN)` is `NULL`
    /// for them. The table then contains the entire history of the input
    /// stream instead of tracking its current contents.
    ///
    /// Only tables without a primary key support this mode, since deletions in
    /// a table with a primary key delete a key rather than a record.
    ///
    /// Versions of Feldera that predate this option ignore it and apply
    /// deletions as regular deletions.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub soft_delete: bool,

    /// Transport endpoint configuration.
    pub transport: TransportConfig,

    /// Optional preprocessor configuration
    #[serde(skip_serializing_if = "Option::is_none")]
    pub preprocessor: Option<Vec<PreprocessorConfig>>,

    /// Parser configuration.
    pub format: Option<FormatConfig>,

    /// Optional postprocessor configuration
    #[serde(skip_serializing_if = "Option::is_none")]
    pub postprocessor: Option<Vec<PostprocessorConfig>>,

    /// Name of the index that the connector is attached to.
    ///
    /// This property is valid for output connectors only.  It is used with data
    /// transports and formats that expect output updates in the form of key/value
    /// pairs, where the key typically represents a unique id associated with the
    /// table or view.
    ///
    /// To support such output formats, an output connector can be attached to an
    /// index created using the SQL CREATE INDEX statement.  An index of a table
    /// or view contains the same updates as the table or view itself, indexed by
    /// one or more key columns.
    ///
    /// See individual connector documentation for details on how they work
    /// with indexes.
    pub index: Option<String>,

    /// Output buffer configuration.
    #[serde(flatten)]
    pub output_buffer_config: OutputBufferConfig,

    /// Maximum number of records from this connector to process in a single batch.
    ///
    /// When set, this caps how many records are taken from the connector’s input
    /// buffer and pushed through the circuit at once.
    ///
    /// This is typically configured lower than `max_queued_records` to allow the
    /// connector time to restart and refill its buffer while a batch is being
    /// processed.
    ///
    /// Not all input adapters honor this limit.
    ///
    /// If this is not set, the batch size is derived from `max_worker_batch_size`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_batch_size: Option<u64>,

    /// Maximum number of records processed per batch, per worker thread.
    ///
    /// When `max_batch_size` is not set, this setting is used to cap
    /// the number of records that can be taken from the connector’s input
    /// buffer and pushed through the circuit at once.  The effective batch size is computed as:
    /// `max_worker_batch_size × workers`.
    ///
    /// This provides an alternative to `max_batch_size` that automatically adjusts batch
    /// size as the number of worker threads changes to maintain constant amount of
    /// work per worker per batch.
    ///
    /// Defaults to 10,000 records per worker.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_worker_batch_size: Option<u64>,

    /// Backpressure threshold, in records.
    ///
    /// Maximal number of records queued by the endpoint before the endpoint
    /// is paused by the backpressure mechanism.
    ///
    /// For input endpoints, this setting bounds the number of records that have
    /// been received from the input transport but haven't yet been consumed by
    /// the circuit, since the circuit is still busy processing previous inputs.
    /// For a distributed input connector, the bound applies to the connector as
    /// a whole, and each host queues its share of it.
    ///
    /// For output endpoints, this setting bounds the number of records that have
    /// been produced by the circuit but not yet sent via the output transport endpoint
    /// nor stored in the output buffer (see `enable_output_buffer`).
    ///
    /// Note that this is not a hard bound: there can be a small delay between
    /// the backpressure mechanism is triggered and the endpoint is paused, during
    /// which more data may be queued.
    ///
    /// The default is 1 million.
    #[serde(default = "default_max_queued_records")]
    pub max_queued_records: u64,

    /// Backpressure threshold, in bytes.
    ///
    /// Maximal number of bytes queued by the endpoint before the endpoint
    /// is paused by the backpressure mechanism.
    ///
    /// For input endpoints, this setting bounds the number of bytes that have
    /// been received from the input transport but haven't yet been consumed by
    /// the circuit since the circuit, since the circuit is still busy processing
    /// previous inputs.  For a distributed input connector, the bound applies
    /// to the connector as a whole, and each host queues its share of it.
    ///
    /// This setting is not yet implemented for output endpoints.
    ///
    /// Note that this is not a hard bound: there can be a small delay between
    /// the backpressure mechanism is triggered and the endpoint is paused, during
    /// which more data may be queued.
    ///
    /// When this is unspecified, it defaults to `1000 * max_queued_records`
    /// bytes.
    ///
    /// Before release 0.367.0 this setting was `max_queued_bytes`, a number
    /// of bytes. That name is deprecated but still read.
    #[serde(
        default,
        alias = "max_queued_bytes",
        deserialize_with = "size_max_queued_size",
        skip_serializing_if = "Option::is_none"
    )]
    #[schema(value_type = Option<String>)]
    pub max_queued_size: Option<ConfigSize>,

    /// Create connector in paused state.
    ///
    /// A paused input connector does not fetch data from its source. A paused
    /// output connector discards the output it receives instead of sending it
    /// to its sink.
    ///
    /// A connector is started at runtime with the `start` action of the
    /// connector API and paused again with `pause`.
    ///
    /// The default is `false`.
    #[serde(default)]
    pub paused: bool,

    /// Arbitrary user-defined text labels associated with the connector.
    ///
    /// These labels can be used in conjunction with the `start_after` property
    /// to control the start order of connectors.
    #[serde(default)]
    pub labels: Vec<String>,

    /// Start the connector after all connectors with specified labels.
    ///
    /// This property is used to control the start order of connectors.
    /// The connector will not start until all connectors with the specified
    /// labels have finished processing all inputs.
    #[serde(deserialize_with = "deserialize_start_after")]
    #[serde(default)]
    pub start_after: Option<Vec<String>>,

    /// Divide the input of this connector among the hosts of a multihost
    /// pipeline. Valid for input connectors only.
    ///
    /// When `false` (the default), the connector runs on one host, which
    /// reads all of its input. When `true`, the connector runs on every host,
    /// and each host reads a different part of the input. Only the Kafka,
    /// Delta Lake, and Iceberg input transports support this setting.
    ///
    /// In a single-host pipeline, this setting has no effect.
    ///
    /// Versions of Feldera that predate this option ignore it.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub distributed: bool,
}

impl ConnectorConfig {
    pub fn new(transport: TransportConfig, format: Option<FormatConfig>) -> Self {
        Self {
            send_snapshot: false,
            soft_delete: false,
            transport,
            preprocessor: None,
            format,
            postprocessor: None,
            index: None,
            output_buffer_config: Default::default(),
            max_batch_size: None,
            max_worker_batch_size: None,
            max_queued_records: default_max_queued_records(),
            max_queued_size: None,
            paused: false,
            labels: Vec::new(),
            start_after: None,
            distributed: false,
        }
    }

    pub fn with_max_batch_size(mut self, max_batch_size: Option<u64>) -> Self {
        self.max_batch_size = max_batch_size;
        self
    }

    pub fn with_max_queued_records(mut self, max_queued_records: u64) -> Self {
        self.max_queued_records = max_queued_records;
        self
    }

    /// Compare two configs modulo the `paused` field and how their duration
    /// settings are spelled.
    ///
    /// Used to compare checkpointed and current connector configs.
    pub fn equal_modulo_paused(&self, other: &Self) -> bool {
        let mut a = self.clone();
        let mut b = other.clone();
        a.paused = false;
        b.paused = false;
        a.normalize_durations();
        b.normalize_durations();
        a == b
    }

    /// Writes each duration setting out as the value in effect.
    ///
    /// A setting left out and the same setting written explicitly at its
    /// default mean the same thing, but the derived `PartialEq` sees `None`
    /// against `Some(default)` and calls them different. Configurations stored
    /// before the rename carry the defaults explicitly, because the fields they
    /// used had no way to be absent: every output connector, for instance,
    /// carries `max_output_buffer_time_millis` at `u64::MAX`. Without this a
    /// connector nobody touched compares as modified, and the pipeline diff that
    /// follows an upgrade is never empty.
    fn normalize_durations(&mut self) {
        self.transport.normalize_durations();
        self.output_buffer_config.max_output_buffer_time =
            Some(self.output_buffer_config.max_output_buffer_time());
        if let Some(format) = &mut self.format {
            format.normalize_durations();
        }
    }

    /// Compare two input connector configs modulo fields that only affect
    /// runtime flow control and do not invalidate checkpointed connector state.
    pub fn equal_for_input_checkpoint_replay(&self, other: &Self) -> bool {
        let mut a = self.clone();
        let mut b = other.clone();
        a.normalize_for_input_checkpoint_replay();
        b.normalize_for_input_checkpoint_replay();
        a == b
    }

    fn normalize_for_input_checkpoint_replay(&mut self) {
        self.paused = false;
        self.max_batch_size = None;
        self.max_worker_batch_size = None;
        self.max_queued_records = default_max_queued_records();
        self.max_queued_size = None;
        self.normalize_durations();
    }

    /// Adopt input connector settings that are safe to change while replaying
    /// checkpointed connector state.
    pub fn apply_input_checkpoint_replay_config_from(&mut self, other: &Self) {
        self.max_batch_size = other.max_batch_size;
        self.max_worker_batch_size = other.max_worker_batch_size;
        self.max_queued_records = other.max_queued_records;
        self.max_queued_size = other.max_queued_size;
    }

    /// Returns `max_queued_records` or, if it is not set, the default.
    pub fn max_queued_records(&self) -> u64 {
        self.max_queued_records
    }

    /// Returns `max_queued_size` in bytes or, if it is not set, the default
    /// based on `max_queued_records`.
    pub fn max_queued_bytes(&self) -> u64 {
        self.max_queued_size
            .map(ConfigSize::as_bytes)
            .unwrap_or_else(|| self.max_queued_records().saturating_mul(1000))
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
#[serde(default)]
pub struct OutputBufferConfig {
    /// Enable output buffering.
    ///
    /// The output buffering mechanism allows decoupling the rate at which the pipeline
    /// pushes changes to the output transport from the rate of input changes.
    ///
    /// By default, output updates produced by the pipeline are pushed directly to
    /// the output transport. Some destinations may prefer to receive updates in fewer
    /// bigger batches. For instance, when writing Parquet files, producing
    /// one bigger file every few minutes is usually better than creating
    /// small files every few milliseconds.
    ///
    /// To achieve such input/output decoupling, users can enable output buffering by
    /// setting the `enable_output_buffer` flag to `true`.  When buffering is enabled, output
    /// updates produced by the pipeline are consolidated in an internal buffer and are
    /// pushed to the output transport when one of several conditions is satisfied:
    ///
    /// * data has been accumulated in the buffer for longer than
    ///   `max_output_buffer_time`.
    /// * buffer size exceeds `max_output_buffer_size_records` records.
    ///
    /// This flag is `false` by default.
    // TODO: on-demand output triggered via the API.
    pub enable_output_buffer: bool,

    /// Maximum time data is kept in the output buffer, for example `500ms`.
    ///
    /// By default, data is kept in the buffer indefinitely until one of
    /// the other output conditions is satisfied.  When this option is
    /// set the buffer will be flushed at least that often.
    ///
    /// NOTE: this configuration option requires the `enable_output_buffer` flag
    /// to be set.
    #[serde(
        default,
        alias = "max_output_buffer_time_millis",
        deserialize_with = "duration_max_output_buffer_time",
        skip_serializing_if = "Option::is_none"
    )]
    #[schema(value_type = Option<String>)]
    pub max_output_buffer_time: Option<ConfigDuration>,

    /// Maximum number of updates to be kept in the output buffer.
    ///
    /// This parameter bounds the maximal size of the buffer.
    /// Note that the size of the buffer is not always equal to the
    /// total number of updates output by the pipeline. Updates to the
    /// same record can overwrite or cancel previous updates.
    ///
    /// The default is 10,000,000.
    ///
    /// NOTE: this configuration option requires the `enable_output_buffer` flag
    /// to be set.
    pub max_output_buffer_size_records: usize,
}

impl OutputBufferConfig {
    /// The output buffering time limit in effect, or no limit.
    pub fn max_output_buffer_time(&self) -> ConfigDuration {
        self.max_output_buffer_time
            .unwrap_or(ConfigDuration::from_millis(u64::MAX))
    }
}

impl Default for OutputBufferConfig {
    fn default() -> Self {
        Self {
            enable_output_buffer: false,
            max_output_buffer_size_records: DEFAULT_MAX_OUTPUT_BUFFER_SIZE_RECORDS,
            max_output_buffer_time: None,
        }
    }
}

/// Describes an output connector configuration
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct OutputEndpointConfig {
    /// The name of the output stream of the circuit that this endpoint is
    /// connected to.
    pub stream: Cow<'static, str>,

    /// Connector configuration.
    #[serde(flatten)]
    pub connector_config: ConnectorConfig,
}

impl OutputEndpointConfig {
    pub fn new(stream: impl Into<Cow<'static, str>>, connector_config: ConnectorConfig) -> Self {
        Self {
            stream: stream.into(),
            connector_config,
        }
    }
}

/// Transport-specific endpoint configuration passed to
/// `crate::OutputTransport::new_endpoint`
/// and `crate::InputTransport::new_endpoint`.
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
#[serde(tag = "name", content = "config", rename_all = "snake_case")]
pub enum TransportConfig {
    FileInput(FileInputConfig),
    FileOutput(FileOutputConfig),
    // Boxed: `NatsInputConfig` is far larger than any other variant, and an
    // unboxed copy would set the size of every `TransportConfig`.
    NatsInput(Box<NatsInputConfig>),
    NatsOutput(NatsOutputConfig),
    KafkaInput(KafkaInputConfig),
    KafkaOutput(KafkaOutputConfig),
    PubSubInput(PubSubInputConfig),
    UrlInput(UrlInputConfig),
    S3Input(S3InputConfig),
    DeltaTableInput(DeltaTableReaderConfig),
    DeltaTableOutput(DeltaTableWriterConfig),
    // Snake case would rename "DynamoDBOutput" to `dynamo_db_output`.
    // However, DynamoDB is a single word, so override the tag to `dynamodb_output`.
    #[serde(rename = "dynamodb_output")]
    DynamoDBOutput(DynamoDBWriterConfig),
    RedisOutput(RedisOutputConfig),
    // Prevent rust from complaining about large size difference between enum variants.
    IcebergInput(Box<IcebergReaderConfig>),
    PostgresInput(PostgresReaderConfig),
    PostgresCdcInput(PostgresCdcReaderConfig),
    PostgresOutput(PostgresWriterConfig),
    Datagen(DatagenInputConfig),
    Nexmark(NexmarkInputConfig),
    /// Direct HTTP input: cannot be instantiated through API
    HttpInput(HttpInputConfig),
    /// Direct HTTP output: cannot be instantiated through API
    HttpOutput(HttpOutputConfig),
    /// Ad hoc input: cannot be instantiated through API
    AdHocInput(AdHocInputConfig),
    ClockInput(ClockConfig),
    S2Input(S2InputConfig),
    S2Output(S2OutputConfig),
    /// Output connector that discards all data.
    NullOutput,
    /// Input connector that produces no data.
    EmptyInput,
}

/// When set to any value except `false`, `0` or empty, the pipeline refuses connector paths
/// on its local filesystem.
pub const REFUSE_LOCAL_FILE_URIS_ENV: &str = "FELDERA_REFUSE_LOCAL_FILE_URIS";

/// A `file:` URL, or a string without a URL scheme. A one-letter scheme is a Windows drive.
fn is_local_file_uri(location: &str) -> bool {
    let Some((scheme, _)) = location.split_once(':') else {
        return true;
    };
    let valid_scheme = scheme.len() > 1
        && scheme.starts_with(|c: char| c.is_ascii_alphabetic())
        && scheme
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
    !valid_scheme || scheme.eq_ignore_ascii_case("file")
}

impl TransportConfig {
    /// The local paths of a Delta Lake or Iceberg connector, as (property, value) pairs.
    /// Before references are `resolved`, skips them. After, checks every value, because a
    /// resolved value can look like a reference.
    pub fn local_file_uris(&self, resolved: bool) -> Vec<(&'static str, &str)> {
        let locations = match self {
            TransportConfig::DeltaTableInput(config) => vec![("uri", Some(&*config.uri))],
            TransportConfig::DeltaTableOutput(config) => vec![("uri", Some(&*config.uri))],
            TransportConfig::IcebergInput(config) => vec![
                ("metadata_location", config.metadata_location.as_deref()),
                (
                    "glue.warehouse",
                    config.glue_catalog_config.warehouse.as_deref(),
                ),
            ],
            _ => Vec::new(),
        };
        locations
            .into_iter()
            .filter_map(|(property, location)| Some((property, location?)))
            .filter(|(_, location)| {
                (resolved
                    || matches!(
                        MaybeSecretRef::new(location.to_string()),
                        Ok(MaybeSecretRef::String(_))
                    ))
                    && is_local_file_uri(location)
            })
            .collect()
    }

    /// Writes each of the transport's duration settings out as the value in
    /// effect; see `ConnectorConfig::normalize_durations`.
    pub fn normalize_durations(&mut self) {
        match self {
            TransportConfig::UrlInput(config) => {
                config.pause_linger = Some(config.pause_linger());
            }
            TransportConfig::KafkaInput(config) => {
                config.group_join_timeout = Some(config.group_join_timeout());
            }
            TransportConfig::KafkaOutput(config) => {
                config.initialization_timeout = Some(config.initialization_timeout());
            }
            TransportConfig::NatsInput(config) => {
                config.connection_config.connection_timeout =
                    Some(config.connection_config.connection_timeout());
                config.connection_config.request_timeout =
                    Some(config.connection_config.request_timeout());
                config.inactivity_timeout = Some(config.inactivity_timeout());
                config.retry_interval = Some(config.retry_interval());
            }
            TransportConfig::NatsOutput(config) => {
                config.connection_config.connection_timeout =
                    Some(config.connection_config.connection_timeout());
                config.connection_config.request_timeout =
                    Some(config.connection_config.request_timeout());
                config.publish_timeout = Some(config.publish_timeout());
            }
            _ => {}
        }
    }

    pub fn name(&self) -> String {
        match self {
            TransportConfig::FileInput(_) => "file_input".to_string(),
            TransportConfig::FileOutput(_) => "file_output".to_string(),
            TransportConfig::NatsInput(_) => "nats_input".to_string(),
            TransportConfig::NatsOutput(_) => "nats_output".to_string(),
            TransportConfig::KafkaInput(_) => "kafka_input".to_string(),
            TransportConfig::KafkaOutput(_) => "kafka_output".to_string(),
            TransportConfig::PubSubInput(_) => "pub_sub_input".to_string(),
            TransportConfig::UrlInput(_) => "url_input".to_string(),
            TransportConfig::S3Input(_) => "s3_input".to_string(),
            TransportConfig::DeltaTableInput(_) => "delta_table_input".to_string(),
            TransportConfig::DeltaTableOutput(_) => "delta_table_output".to_string(),
            TransportConfig::DynamoDBOutput(_) => "dynamodb_output".to_string(),
            TransportConfig::IcebergInput(_) => "iceberg_input".to_string(),
            TransportConfig::PostgresInput(_) => "postgres_input".to_string(),
            TransportConfig::PostgresCdcInput(_) => "postgres_cdc_input".to_string(),
            TransportConfig::PostgresOutput(_) => "postgres_output".to_string(),
            TransportConfig::Datagen(_) => "datagen".to_string(),
            TransportConfig::Nexmark(_) => "nexmark".to_string(),
            TransportConfig::HttpInput(_) => "http_input".to_string(),
            TransportConfig::HttpOutput(_) => "http_output".to_string(),
            TransportConfig::AdHocInput(_) => "adhoc_input".to_string(),
            TransportConfig::RedisOutput(_) => "redis_output".to_string(),
            TransportConfig::ClockInput(_) => "clock".to_string(),
            TransportConfig::S2Input(_) => "s2_input".to_string(),
            TransportConfig::S2Output(_) => "s2_output".to_string(),
            TransportConfig::NullOutput => "null_output".to_string(),
            TransportConfig::EmptyInput => "empty_input".to_string(),
        }
    }

    /// Returns a mutable reference to the transport's metadata map, if the
    /// transport supports arbitrary key-value metadata (e.g., NATS consumer
    /// metadata). The controller uses this to inject pipeline identity into
    /// transport-level metadata without transport-specific knowledge.
    pub fn transport_metadata_mut(&mut self) -> Option<&mut HashMap<String, String>> {
        match self {
            TransportConfig::NatsInput(cfg) => Some(&mut cfg.consumer_config.metadata),
            _ => None,
        }
    }

    /// Returns true if the connector is transient, i.e., is created and destroyed
    /// at runtime on demand, rather than being configured as part of the pipeline.
    pub fn is_transient(&self) -> bool {
        matches!(
            self,
            TransportConfig::AdHocInput(_)
                | TransportConfig::HttpInput(_)
                | TransportConfig::HttpOutput(_)
                | TransportConfig::ClockInput(_)
        )
    }

    pub fn is_http_input(&self) -> bool {
        matches!(self, TransportConfig::HttpInput(_))
    }

    /// Returns true if an input connector with this transport can divide its
    /// input among the hosts of a multihost pipeline (see
    /// [`ConnectorConfig::distributed`]).
    pub fn supports_distribution(&self) -> bool {
        matches!(
            self,
            TransportConfig::KafkaInput(_)
                | TransportConfig::DeltaTableInput(_)
                | TransportConfig::IcebergInput(_)
        )
    }

    /// Returns true if host 0 of a distributed input connector with this
    /// transport must choose a value for all of the hosts before they read any
    /// input.
    ///
    /// For example, the hosts of a Delta Lake connector must read the snapshot
    /// at the same table version, and the hosts of an Iceberg connector at the
    /// same snapshot ID, or they could lose or duplicate records.
    /// Host 0 chooses the value, and the coordinator passes it to the other
    /// hosts in [CoordinationActivate::input_choices].
    ///
    /// [CoordinationActivate::input_choices]: crate::coordination::CoordinationActivate::input_choices
    pub fn needs_input_choice(&self) -> bool {
        matches!(
            self,
            TransportConfig::DeltaTableInput(_) | TransportConfig::IcebergInput(_)
        )
    }

    /// Returns how to combine the completed frontiers' metadata that the hosts
    /// of a distributed input connector with this transport report.
    pub fn frontier_merge(&self) -> crate::adapter_stats::FrontierMerge {
        use crate::adapter_stats::FrontierMerge;
        match self {
            TransportConfig::KafkaInput(_) => FrontierMerge::Partitioned,
            TransportConfig::DeltaTableInput(_) | TransportConfig::IcebergInput(_) => {
                FrontierMerge::Shared
            }
            _ => FrontierMerge::Opaque,
        }
    }
}

/// Data format specification used to parse raw data received from the
/// endpoint or to encode data sent to the endpoint.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, ToSchema)]
pub struct FormatConfig {
    /// Format name, e.g., "csv", "json", "bincode", etc.
    pub name: Cow<'static, str>,

    /// Format-specific parser or encoder configuration.
    #[serde(default)]
    #[schema(value_type = Object)]
    pub config: JsonValue,
}

impl FormatConfig {
    /// Writes the Avro schema registry timeout, the one duration a format
    /// carries, in one spelling; see `ConnectorConfig::normalize_durations`.
    ///
    /// The format configuration stays raw JSON until the format parses it, so
    /// the timeout is read the way the format reads it and written back under
    /// the current key. A configuration the format would reject is left alone.
    pub fn normalize_durations(&mut self) {
        if self.name != "avro" {
            return;
        }
        let has_timeout = self.config.as_object().is_some_and(|object| {
            object.contains_key("registry_timeout") || object.contains_key("registry_timeout_secs")
        });
        if !has_timeout {
            return;
        }
        let Ok(registry) = serde_json::from_value::<crate::format::avro::AvroSchemaRegistryConfig>(
            self.config.clone(),
        ) else {
            return;
        };
        let object = self.config.as_object_mut().unwrap();
        object.remove("registry_timeout_secs");
        match registry.registry_timeout {
            Some(timeout) => object.insert(
                "registry_timeout".to_string(),
                JsonValue::String(timeout.to_string()),
            ),
            None => object.remove("registry_timeout"),
        };
    }
}

/// The part of a pipeline's config that can change while the pipeline runs.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct DynamicConfig {
    #[serde(default)]
    pub resources: DynamicResources,
}

/// CPU and memory, the only fields that can change while the pipeline runs.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct DynamicResources {
    pub cpu_cores_min: Option<f64>,
    pub cpu_cores_max: Option<f64>,
    /// The minimum memory, such as `"4Gi"`. `memory_mb_min`, a number of
    /// megabytes, is a deprecated alias.
    #[serde(default, alias = "memory_mb_min", deserialize_with = "size_memory_min")]
    #[schema(value_type = Option<String>)]
    pub memory_min: Option<ConfigSize>,
    /// The maximum memory, such as `"16Gi"`. `memory_mb_max`, a number of
    /// megabytes, is a deprecated alias.
    #[serde(default, alias = "memory_mb_max", deserialize_with = "size_memory_max")]
    #[schema(value_type = Option<String>)]
    pub memory_max: Option<ConfigSize>,
}

#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
#[serde(default)]
pub struct ResourceConfig {
    /// The minimum number of CPU cores to reserve
    /// for an instance of this pipeline
    #[serde(deserialize_with = "crate::serde_via_value::deserialize")]
    pub cpu_cores_min: Option<f64>,

    /// The maximum number of CPU cores to reserve
    /// for an instance of this pipeline
    #[serde(deserialize_with = "crate::serde_via_value::deserialize")]
    pub cpu_cores_max: Option<f64>,

    /// The minimum memory to reserve for an instance of this pipeline, such
    /// as `"4Gi"`.
    ///
    /// Before release 0.367.0 this setting was `memory_mb_min`, a number of
    /// megabytes. That name is deprecated but still read.
    #[serde(
        alias = "memory_mb_min",
        deserialize_with = "size_memory_min",
        skip_serializing_if = "Option::is_none"
    )]
    #[schema(value_type = Option<String>)]
    pub memory_min: Option<ConfigSize>,

    /// The maximum memory to reserve for an instance of this pipeline, such
    /// as `"16Gi"`.
    ///
    /// Before release 0.367.0 this setting was `memory_mb_max`, a number of
    /// megabytes. That name is deprecated but still read.
    #[serde(
        alias = "memory_mb_max",
        deserialize_with = "size_memory_max",
        skip_serializing_if = "Option::is_none"
    )]
    #[schema(value_type = Option<String>)]
    pub memory_max: Option<ConfigSize>,

    /// The initial storage to reserve for an instance of this pipeline, such
    /// as `"100Gi"`. Set together with `storage_max` to enable storage
    /// autoscaling.
    ///
    /// Before release 0.367.0 this setting was `storage_mb_min`, a number of
    /// megabytes. That name is deprecated but still read.
    #[serde(
        alias = "storage_mb_min",
        deserialize_with = "size_storage_min",
        skip_serializing_if = "Option::is_none"
    )]
    #[schema(value_type = Option<String>)]
    pub storage_min: Option<ConfigSize>,

    /// The maximum storage for an instance of this pipeline, such as
    /// `"400Gi"`.
    ///
    /// Without `storage_min`, this much storage is reserved up front.
    ///
    /// With `storage_min`, storage starts there and autoscaling expands it up
    /// to this limit.
    ///
    /// Before release 0.367.0 this setting was `storage_mb_max`, a number of
    /// megabytes. That name is deprecated but still read.
    #[serde(
        alias = "storage_mb_max",
        deserialize_with = "size_storage_max",
        skip_serializing_if = "Option::is_none"
    )]
    #[schema(value_type = Option<String>)]
    pub storage_max: Option<ConfigSize>,

    /// Autoscaling policy for an instance of this pipeline.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub autoscaling: Option<AutoscalingConfig>,

    /// Storage class to use for an instance of this pipeline.
    /// The class determines storage performance such as IOPS and throughput.
    pub storage_class: Option<String>,

    /// Kubernetes volume attributes class to use for the storage of an
    /// instance of this pipeline. The class sets mutable storage parameters
    /// such as IOPS and throughput. Requires Kubernetes 1.34 or later (or
    /// the `VolumeAttributesClass` feature gate) and CSI driver support.
    /// A change takes effect on the next start, also for existing storage.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub volume_attributes_class: Option<String>,

    /// Kubernetes service account name to use for an instance of this pipeline.
    /// The account determines permissions and access controls.
    pub service_account_name: Option<String>,

    /// Kubernetes namespace to use for an instance of this pipeline.
    /// The namespace determines the scope of names for resources created
    /// for the pipeline.
    /// If not set, the pipeline will be deployed in the same namespace
    /// as the control-plane.
    // The type of this field should not be backward incompatibly changed, and its location in the
    // runtime configuration JSON (`runtime_config.resources.namespace`) should not be changed.
    pub namespace: Option<String>,
}

/// Autoscaling policy for an instance of a pipeline.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
#[serde(default)]
pub struct AutoscalingConfig {
    /// Storage autoscaling policy.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub storage: Option<StorageAutoscalingConfig>,
}

/// Storage autoscaling policy: expand storage from `storage_min` toward
/// `storage_max` as it fills up.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
#[serde(default)]
pub struct StorageAutoscalingConfig {
    /// Usage fraction that triggers expansion. Defaults to 0.8.
    #[serde(
        deserialize_with = "crate::serde_via_value::deserialize",
        skip_serializing_if = "Option::is_none"
    )]
    pub scale_threshold: Option<f64>,

    /// Expand storage when available space falls below this size, such as
    /// `"10Gi"`, even if usage is still under `scale_threshold`. Either
    /// condition triggers expansion. Unset by default.
    ///
    /// Before release 0.367.0 this setting was `scale_threshold_available_mb`,
    /// a number of megabytes. That name is deprecated but still read.
    #[serde(
        alias = "scale_threshold_available_mb",
        deserialize_with = "size_scale_threshold_available",
        skip_serializing_if = "Option::is_none"
    )]
    #[schema(value_type = Option<String>)]
    pub scale_threshold_available: Option<ConfigSize>,

    /// Expansion multiplier. Defaults to 2.0.
    #[serde(
        deserialize_with = "crate::serde_via_value::deserialize",
        skip_serializing_if = "Option::is_none"
    )]
    pub scale_factor: Option<f64>,
}

#[cfg(test)]
mod resource_config_tests {
    use super::{AutoscalingConfig, ResourceConfig, StorageAutoscalingConfig};
    use crate::size::ConfigSize;
    use serde_json::json;

    #[test]
    fn storage_autoscaling_round_trips_through_json() {
        let input = json!({
            "storage_min": "1G",
            "storage_max": "8G",
            "autoscaling": {
                "storage": {
                    "scale_threshold": 0.8,
                    "scale_threshold_available": "10G",
                    "scale_factor": 2.0
                }
            }
        });
        let config: ResourceConfig = serde_json::from_value(input).unwrap();
        assert_eq!(config.storage_min, Some(ConfigSize::from_mb(1000)));
        assert_eq!(config.storage_max, Some(ConfigSize::from_mb(8000)));
        assert_eq!(
            config.autoscaling,
            Some(AutoscalingConfig {
                storage: Some(StorageAutoscalingConfig {
                    scale_threshold: Some(0.8),
                    scale_threshold_available: Some(ConfigSize::from_mb(10000)),
                    scale_factor: Some(2.0),
                }),
            })
        );
        let output = serde_json::to_value(&config).unwrap();
        assert_eq!(output["storage_min"], json!("1G"));
        assert_eq!(
            output["autoscaling"]["storage"]["scale_threshold"],
            json!(0.8)
        );
        assert_eq!(
            output["autoscaling"]["storage"]["scale_threshold_available"],
            json!("10G")
        );
        assert_eq!(output["autoscaling"]["storage"]["scale_factor"], json!(2.0));
    }

    #[test]
    fn autoscaling_fields_default_to_none() {
        let config: ResourceConfig = serde_json::from_value(json!({})).unwrap();
        assert_eq!(config.storage_min, None);
        assert_eq!(config.autoscaling, None);

        // Unset autoscaling fields stay out of the serialized config so they
        // do not clutter configs of users who never touch them.
        let output = serde_json::to_value(&config).unwrap();
        assert!(output.get("storage_min").is_none());
        assert!(output.get("autoscaling").is_none());
        assert!(output.get("storage_max").is_none());

        // A partially set policy serializes only the fields the user set.
        let input = json!({ "autoscaling": { "storage": { "scale_threshold": 0.9 } } });
        let config: ResourceConfig = serde_json::from_value(input.clone()).unwrap();
        let output = serde_json::to_value(&config).unwrap();
        assert_eq!(output["autoscaling"], input["autoscaling"]);

        // A policy object with no storage section is accepted as-is.
        let config: ResourceConfig = serde_json::from_value(json!({ "autoscaling": {} })).unwrap();
        assert_eq!(config.autoscaling, Some(AutoscalingConfig::default()));
    }

    #[test]
    fn autoscaling_rejects_non_numeric_values() {
        let input = json!({ "autoscaling": { "storage": { "scale_threshold": "high" } } });
        assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
        let input = json!({ "autoscaling": { "storage": { "scale_threshold_available_mb": -1 } } });
        assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
        let input = json!({ "storage_mb_min": -1 });
        assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
    }
}

#[cfg(test)]
mod sync_config_tests {
    use super::SyncConfig;

    fn config(bucket: &str, read_bucket: Option<&str>) -> SyncConfig {
        SyncConfig {
            bucket: bucket.to_owned(),
            read_bucket: read_bucket.map(str::to_owned),
            ..Default::default()
        }
    }

    #[test]
    fn read_bucket_must_differ_from_bucket() {
        let err = config("ckpts/a", Some("ckpts/a")).validate().unwrap_err();
        assert!(err.contains("different locations"), "{err}");
    }

    #[test]
    fn read_bucket_must_use_the_same_object_store() {
        let err = config("gs://ckpts/a", Some("ckpts/b"))
            .validate()
            .unwrap_err();
        assert!(err.contains("same object store"), "{err}");
        let err = config("ckpts/a", Some("gs://ckpts/b"))
            .validate()
            .unwrap_err();
        assert!(err.contains("same object store"), "{err}");
    }

    #[test]
    fn matching_object_stores_are_accepted() {
        config("gs://ckpts/a", Some("gs://ckpts/b"))
            .validate()
            .unwrap();
        config("ckpts/a", Some("s3://ckpts/b")).validate().unwrap();
        config("gs://ckpts/a", None).validate().unwrap();
    }

    #[test]
    fn take_bucket_ownership_defaults_to_false() {
        let sync: SyncConfig = serde_json::from_str(r#"{"bucket": "ckpts/a"}"#).unwrap();
        assert!(!sync.take_bucket_ownership);

        let sync: SyncConfig =
            serde_json::from_str(r#"{"bucket": "ckpts/a", "take_bucket_ownership": true}"#)
                .unwrap();
        assert!(sync.take_bucket_ownership);
    }
}

#[cfg(test)]
mod transport_metadata_tests {
    use super::TransportConfig;
    use serde_json::json;

    fn nats_input(metadata: serde_json::Value) -> TransportConfig {
        serde_json::from_value(json!({
            "name": "nats_input",
            "config": {
                "connection_config": { "server_url": "nats://127.0.0.1:4222" },
                "stream_name": "orders",
                "consumer_config": { "deliver_policy": "All", "metadata": metadata },
            },
        }))
        .unwrap()
    }

    #[test]
    fn nats_input_exposes_consumer_metadata() {
        let mut transport = nats_input(json!({ "team": "ingest" }));
        let metadata = transport.transport_metadata_mut().unwrap();
        assert_eq!(metadata.get("team").map(String::as_str), Some("ingest"));

        metadata.insert("pipeline".to_string(), "orders_pipeline".to_string());
        let TransportConfig::NatsInput(config) = &transport else {
            unreachable!()
        };
        assert_eq!(
            config
                .consumer_config
                .metadata
                .get("pipeline")
                .map(String::as_str),
            Some("orders_pipeline"),
            "writes through the returned map must reach the consumer config"
        );
    }

    #[test]
    fn transports_without_metadata_return_none() {
        let mut transport: TransportConfig = serde_json::from_value(json!({
            "name": "file_input",
            "config": { "path": "/tmp/input.csv" },
        }))
        .unwrap();
        assert!(transport.transport_metadata_mut().is_none());
    }
}

#[cfg(test)]
mod local_file_uri_tests {
    use super::TransportConfig;
    use serde_json::json;

    #[test]
    fn local_file_uris() {
        let delta = |uri: &str| -> TransportConfig {
            serde_json::from_value(
                json!({"name": "delta_table_input", "config": {"uri": uri, "mode": "snapshot"}}),
            )
            .unwrap()
        };
        for uri in [
            "file:///etc",
            "FILE:/etc",
            "/etc",
            "./t",
            "",
            "c:/t",
            " file:///etc",
        ] {
            assert_eq!(delta(uri).local_file_uris(false), vec![("uri", uri)]);
        }
        for uri in [
            "s3://b/t",
            "gs://b/t",
            "az://c/t",
            "abfss://c@a/t",
            "uc://c.s.t",
        ] {
            assert!(delta(uri).local_file_uris(false).is_empty(), "{uri}");
        }
        // A reference is checked after resolution. Its resolved value can look like a reference.
        assert!(delta("${env:X}").local_file_uris(false).is_empty());
        assert_eq!(
            delta("${env:X}").local_file_uris(true),
            vec![("uri", "${env:X}")]
        );

        let iceberg: TransportConfig = serde_json::from_value(json!({"name": "iceberg_input",
            "config": {"mode": "snapshot", "metadata_location": "file:///t/m.json"}}))
        .unwrap();
        assert_eq!(
            iceberg.local_file_uris(false),
            vec![("metadata_location", "file:///t/m.json")]
        );
    }
}