sql-splitter 1.18.0

High-performance CLI tool for splitting large SQL dump files into individual table files
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
//! The [`ModelCompiler`]: turns a complete model plus CLI options into an
//! immutable [`GenerationPlan`].
//!
//! Compilation is two concerns woven together:
//!
//! * **Selection** — `--tables`/`--exclude` globs choose the tables to
//!   generate; a selected table whose required parent was excluded is a
//!   `GEN-EXCLUDED-DEPENDENCY` error reporting the full dependency path.
//! * **Exact counts** — every selected table gets a single resolved integer
//!   row count. Roots resolve from their model count through the global
//!   `--scale`/`--rows` control, a per-table `--table-rows`/`--table-scale`
//!   override, and finally the `--max-rows` cap. Relationship children derive
//!   from their *final* parent count times the stored fan-out mean — the
//!   global control is never applied a second time — then take their own
//!   override and cap. Fractional targets are stochastically rounded on a
//!   stable per-table [`StreamId::rounding`] stream, so a run is reproducible.
//!
//! * **Ownership, types, and dependencies** — every column gets exactly one
//!   owner: an explicit generator, a table planner, a declared relationship, a
//!   database default, or the database itself (identity/serial, computed, or a
//!   bare integer primary key). Two owners claiming one column is a
//!   `GEN-COLUMN-OWNER-CONFLICT`; a column no rule or structural schema fact can
//!   supply is a `GEN-COLUMN-OWNER-MISSING`. Generators/modifiers are
//!   type-checked against their descriptor's accepted families, and the
//!   column/planner read→write graph is scanned for cycles
//!   (`GEN-COLUMN-CYCLE`), except a cycle a single planner owns end-to-end.
//!
//! Errors are gathered, not short-circuited: a model with a count conflict and
//! three excluded dependencies reports all four. Warnings (e.g. a `--max-rows`
//! cap) survive a successful compile via [`GenerationPlan::diagnostics`].

use std::cmp::Reverse;
use std::collections::{BTreeMap, BTreeSet, BinaryHeap};

use glob::Pattern;
use rand::RngExt;

use crate::diagnostic::{DiagnosticBag, Severity, SourceLocation};
use crate::parser::SqlDialect;
use crate::synthetic::model::{
    ChildDistribution, InferenceMode, ModifierConfig, PlannerConfig, RelationshipModel, RowsModel,
    SyntheticModel, TableModel, TableSeed, MAX_OUTPUT_BATCH_SIZE,
};
use crate::synthetic::schema::{PortableColumn, PortableTable, SqlTypeFamily};

use super::plan::{
    ColumnOwner, CompiledOutput, CompiledRelationship, ExecutionPhase, FamilyPhase, GenerationPlan,
    PlanEstimates, PlannedColumn, PlannedTable, RelationshipDistribution, ResolvedTableSeed,
};
use super::registry::{
    ColumnScope, CompileContext, CompiledModifier, CompiledPlanner, ExtensionRegistry,
};
use super::seed::{SeedRoot, StreamId};

/// A single per-table count override from the CLI (`--table-rows` or
/// `--table-scale`).
#[derive(Debug, Clone, PartialEq)]
pub struct TableCountOverride {
    /// The table the override targets.
    pub table: String,
    /// Whether it pins an absolute count or a table-local scale.
    pub kind: TableCountKind,
}

/// The two shapes of a per-table count override.
#[derive(Debug, Clone, PartialEq)]
pub enum TableCountKind {
    /// `--table-rows`: an absolute row count that is never re-scaled.
    Rows(u64),
    /// `--table-scale`: a table-local scale that replaces the global control
    /// on a root, or multiplies the derived count on a child.
    Scale(f64),
}

impl TableCountOverride {
    /// A `--table-rows` override pinning `table` to an absolute count.
    pub fn rows(table: impl Into<String>, rows: u64) -> Self {
        Self {
            table: table.into(),
            kind: TableCountKind::Rows(rows),
        }
    }

    /// A `--table-scale` override applying `scale` to `table`.
    pub fn scale(table: impl Into<String>, scale: f64) -> Self {
        Self {
            table: table.into(),
            kind: TableCountKind::Scale(scale),
        }
    }
}

/// The CLI-supplied knobs a compile honors, mapping one-to-one onto the
/// generation command's count and selection flags.
#[derive(Debug, Clone, Default)]
pub struct CompileOptions {
    /// Run root seed (`--seed`); overrides the model's `seed`.
    pub seed: Option<u64>,
    /// Global multiplicative scale (`--scale`); conflicts with `rows`.
    pub scale: Option<f64>,
    /// Global absolute root count (`--rows`); conflicts with `scale`.
    pub rows: Option<u64>,
    /// Upper bound applied to every table last (`--max-rows`).
    pub max_rows: Option<u64>,
    /// Per-table count overrides (`--table-rows`/`--table-scale`).
    pub table_rows: Vec<TableCountOverride>,
    /// Table-selection globs (`--tables`); empty selects every table.
    pub tables: Vec<String>,
    /// Table-exclusion globs (`--exclude`).
    pub exclude: Vec<String>,
    /// The exact in-memory byte budget for each correlated family's buffered
    /// child rows (`--family-budget`). `None` uses a large default; a small
    /// value forces the family spill path. Byte-for-byte output is independent
    /// of this budget — only where child rows are held changes.
    pub family_budget_bytes: Option<u64>,
}

/// The default per-family in-memory budget when none is pinned.
const DEFAULT_FAMILY_BUDGET_BYTES: u64 = 64 * 1024 * 1024;

/// Compiles a [`SyntheticModel`] into a [`GenerationPlan`].
///
/// Holds the [`ExtensionRegistry`] used to resolve column generators and
/// planners while compiling structure, counts, ownership, and dependencies.
pub struct ModelCompiler {
    registry: ExtensionRegistry,
}

impl ModelCompiler {
    /// A compiler backed by an explicit registry.
    pub fn new(registry: ExtensionRegistry) -> Self {
        Self { registry }
    }

    /// A compiler backed by [`ExtensionRegistry::standard`].
    pub fn standard() -> Self {
        Self::new(ExtensionRegistry::standard())
    }

    /// The registry this compiler resolves operators against.
    pub fn registry(&self) -> &ExtensionRegistry {
        &self.registry
    }

    /// Compile `model` under `options`, gathering every independent error
    /// before returning `Err`. On success, warnings survive in
    /// [`GenerationPlan::diagnostics`].
    pub fn compile(
        &self,
        model: SyntheticModel,
        options: CompileOptions,
    ) -> Result<GenerationPlan, DiagnosticBag> {
        let mut bag = DiagnosticBag::default();

        if let Some(source) = &model.source {
            if source.dialect.parse::<SqlDialect>().is_err() {
                bag.error(
                    crate::diagnostic::codes::DIALECT_INVALID.code,
                    "source.dialect",
                    format!(
                        "unsupported source dialect `{}`; expected mysql, postgres, sqlite, or mssql",
                        source.dialect
                    ),
                );
            }
        }
        if let Some(dialect) = &model.output.dialect {
            if dialect.parse::<SqlDialect>().is_err() {
                bag.error(
                    crate::diagnostic::codes::DIALECT_INVALID.code,
                    "output.dialect",
                    format!(
                        "unsupported output dialect `{dialect}`; expected mysql, postgres, sqlite, or mssql"
                    ),
                );
            }
        }
        if let Some(batch_size) = model.output.batch_size {
            if batch_size == 0 || batch_size > MAX_OUTPUT_BATCH_SIZE {
                bag.error(
                    crate::diagnostic::codes::OUTPUT_BATCH_SIZE.code,
                    "output.batch_size",
                    format!(
                        "output batch size must be between 1 and {MAX_OUTPUT_BATCH_SIZE} (got {batch_size})"
                    ),
                );
            }
        }

        if options.scale.is_some() && options.rows.is_some() {
            bag.error(
                crate::diagnostic::codes::COUNT_CONTROL_CONFLICT.code,
                "options",
                "`--scale` and `--rows` are mutually exclusive global row controls",
            );
        }
        if let Some(scale) = options.scale {
            // A negative or non-finite global scale would silently floor every
            // table to zero rows; reject it instead.
            if !scale.is_finite() || scale < 0.0 {
                bag.error(
                    crate::diagnostic::codes::TABLE_SCALE_INVALID.code,
                    "options",
                    format!("`--scale` must be a finite, non-negative number (got {scale})"),
                );
            }
        }

        let overrides = self.collect_table_overrides(&options, &mut bag);
        let selected = self.select_tables(&model, &options, &mut bag);
        // Ordering edges (`All`) include every foreign key so a present parent is
        // still generated before its child; only *required* edges (non-null FKs,
        // relation.children parents, polymorphic targets) make an excluded
        // dependency a hard `GEN-EXCLUDED-DEPENDENCY`. A nullable FK to an
        // excluded table is detached (with a warning) in `plan_table` instead.
        let all_parents = parent_edges(&model, EdgeKind::All);
        let required = parent_edges(&model, EdgeKind::Required);
        self.report_excluded_dependencies(&selected, &required, &mut bag);
        // Preserve original DDL byte-for-byte only when the ENTIRE source schema
        // survives selection; once any table is excluded, every retained table is
        // rendered from its normalized schema (see `plan_table`).
        let schema_changed = selected.len() < model.tables.len();

        // Resolve an omitted model seed once per compilation so every inherited
        // table shares one fresh run root. Explicit `seed: null` tables draw
        // their own independent roots in `resolve_seed` below.
        let root_seed = options.seed.or(model.seed).unwrap_or_else(rand::random);
        let rounding_root = SeedRoot::new(root_seed);
        let (mut order, mut cyclic) = topo_order(&selected, &all_parents);
        if !cyclic.is_empty() {
            // A cycle under the full edge set may consist only of nullable
            // foreign keys, which do not constrain generation order (values index
            // into the parent key domain, and the FK can be NULL/deferred at
            // load). Retry using only *required* edges — non-null FKs,
            // relation.children parents, polymorphic targets. If that graph is
            // acyclic, the cycle was purely nullable FKs: order by required edges
            // and warn that the cyclic tables are not parent-before-child.
            let (required_order, required_cyclic) = topo_order(&selected, &required);
            if required_cyclic.is_empty() {
                order = required_order;
                cyclic = Vec::new();
                bag.warning(
                    crate::diagnostic::codes::FOREIGN_KEY_CYCLE.code,
                    "tables",
                    "nullable foreign keys form a dependency cycle; the cyclic tables cannot all be ordered parent-before-child in the output",
                );
            }
        }
        if !cyclic.is_empty() {
            // A cycle remains among required dependencies: either mutual
            // relation.children counts (each table's count derives from a parent
            // that ultimately derives from it, which would silently yield zero
            // rows) or a non-null foreign-key cycle. Neither can be resolved in a
            // single ordered pass.
            bag.error(
                crate::diagnostic::codes::ROWS_CYCLE.code,
                "tables",
                format!(
                    "required dependencies (non-null foreign keys or relation.children row counts) form a cycle among tables: {}; each derives from a parent that ultimately derives from it",
                    cyclic.join(", ")
                ),
            );
        }

        let family_ctx = self.collect_family_facts(&model, &mut bag);
        let family_budget_bytes = options
            .family_budget_bytes
            .unwrap_or(DEFAULT_FAMILY_BUDGET_BYTES);

        let mut resolved: BTreeMap<String, u64> = BTreeMap::new();
        let mut tables: Vec<PlannedTable> = Vec::with_capacity(order.len());

        for name in &order {
            let table = &model.tables[name];
            let count = self.resolve_count(
                &model,
                name,
                table,
                &options,
                overrides.get(name),
                rounding_root,
                &resolved,
                &mut bag,
            );
            resolved.insert(name.clone(), count);
            tables.push(self.plan_table(
                &model,
                name,
                table,
                count,
                root_seed,
                model.defaults.inference,
                &family_ctx,
                &resolved,
                &selected,
                !schema_changed,
                options.max_rows,
                &mut bag,
            ));
        }

        let phases = build_phases(&order, &family_ctx, family_budget_bytes, &mut bag);

        let estimates = PlanEstimates {
            total_rows: resolved.values().copied().fold(0u64, u64::saturating_add),
            ..PlanEstimates::default()
        };

        if bag.has_errors() {
            return Err(bag);
        }

        // Drain warnings so they reach the CLI/JSON report even though the
        // compile succeeded. (A merge, when wired ahead of the compiler, feeds
        // its warning-only bag through this same channel.)
        let diagnostics = bag
            .diagnostics
            .into_iter()
            .filter(|diagnostic| diagnostic.severity == Severity::Warning)
            .collect();

        Ok(GenerationPlan {
            input_dialect: model
                .source
                .as_ref()
                .and_then(|source| source.dialect.parse().ok()),
            output: compile_output(&model),
            tables,
            phases,
            diagnostics,
            estimates,
            family_budget_bytes,
        })
    }

    /// Fold the flat `--table-rows`/`--table-scale` list into a per-table
    /// view, reporting `--table-rows` + `--table-scale` on the same table as
    /// `GEN-TABLE-COUNT-CONFLICT`.
    fn collect_table_overrides(
        &self,
        options: &CompileOptions,
        bag: &mut DiagnosticBag,
    ) -> BTreeMap<String, TableOverride> {
        let mut map: BTreeMap<String, TableOverride> = BTreeMap::new();
        for over in &options.table_rows {
            let entry = map.entry(over.table.clone()).or_default();
            match over.kind {
                TableCountKind::Rows(rows) => entry.rows = Some(rows),
                TableCountKind::Scale(scale) => entry.scale = Some(scale),
            }
        }
        for (table, over) in &map {
            if over.rows.is_some() && over.scale.is_some() {
                bag.error(
                    crate::diagnostic::codes::TABLE_COUNT_CONFLICT.code,
                    format!("tables.{table}"),
                    format!(
                        "table `{table}` has both `--table-rows` and `--table-scale`; they are mutually exclusive"
                    ),
                );
            }
        }
        map
    }

    /// Apply the `--tables`/`--exclude` globs to choose the generated set.
    fn select_tables(
        &self,
        model: &SyntheticModel,
        options: &CompileOptions,
        bag: &mut DiagnosticBag,
    ) -> BTreeSet<String> {
        let includes = compile_globs(&options.tables, bag);
        let excludes = compile_globs(&options.exclude, bag);
        model
            .tables
            .keys()
            .filter(|name| {
                let included =
                    includes.is_empty() || includes.iter().any(|pattern| pattern.matches(name));
                let excluded = excludes.iter().any(|pattern| pattern.matches(name));
                included && !excluded
            })
            .cloned()
            .collect()
    }

    /// Report, for each selected table, any required dependency that is not in
    /// the selected set — with the full path from the table to the excluded
    /// dependency. Never re-adds an excluded table.
    fn report_excluded_dependencies(
        &self,
        selected: &BTreeSet<String>,
        parents: &BTreeMap<String, BTreeSet<String>>,
        bag: &mut DiagnosticBag,
    ) {
        for start in selected {
            let mut reported: BTreeSet<String> = BTreeSet::new();
            let mut visited: BTreeSet<String> = BTreeSet::new();
            let mut stack: Vec<Vec<String>> = vec![vec![start.clone()]];
            while let Some(path) = stack.pop() {
                let node = path.last().expect("path is never empty");
                let Some(node_parents) = parents.get(node) else {
                    continue;
                };
                for parent in node_parents {
                    let mut extended = path.clone();
                    extended.push(parent.clone());
                    if selected.contains(parent) {
                        if visited.insert(parent.clone()) {
                            stack.push(extended);
                        }
                    } else if reported.insert(parent.clone()) {
                        bag.error(
                            crate::diagnostic::codes::EXCLUDED_DEPENDENCY.code,
                            format!("tables.{start}"),
                            format!(
                                "table `{start}` requires excluded table `{parent}` via dependency path {}",
                                extended.join(" -> ")
                            ),
                        );
                    }
                }
            }
        }
    }

    /// Resolve one table's exact row count, appending any diagnostics.
    #[allow(clippy::too_many_arguments)]
    fn resolve_count(
        &self,
        model: &SyntheticModel,
        name: &str,
        table: &TableModel,
        options: &CompileOptions,
        over: Option<&TableOverride>,
        rounding_root: SeedRoot,
        resolved: &BTreeMap<String, u64>,
        bag: &mut DiagnosticBag,
    ) -> u64 {
        match &table.rows {
            RowsModel::RelationChildren {
                parent,
                distribution,
                ..
            } => self.resolve_child_count(
                name,
                parent,
                distribution,
                options,
                over,
                rounding_root,
                resolved,
                bag,
            ),
            rows => self.resolve_root_count(model, name, rows, options, over, rounding_root, bag),
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn resolve_root_count(
        &self,
        model: &SyntheticModel,
        name: &str,
        rows: &RowsModel,
        options: &CompileOptions,
        over: Option<&TableOverride>,
        rounding_root: SeedRoot,
        bag: &mut DiagnosticBag,
    ) -> u64 {
        if matches!(rows, RowsModel::Observed { .. }) && !has_observed_provenance(model, name) {
            bag.error(
                crate::diagnostic::codes::ROWS_OBSERVED_MISSING.code,
                format!("tables.{name}.rows"),
                format!(
                    "table `{name}` uses `rows.kind: observed` but the model has no attached source or profile to resolve the observed count from"
                ),
            );
        }

        let base = declared_count(rows).unwrap_or(0) as f64;

        // Global control (scale XOR rows); conflict already reported upstream.
        let mut target = match (options.scale, options.rows) {
            (Some(scale), _) => base * scale,
            (None, Some(rows)) => rows as f64,
            (None, None) => base,
        };

        // Root per-table override: absolute rows win outright; a table-scale
        // replaces the global control and re-scales the untouched base.
        match over.map(TableOverride::effective) {
            Some(EffectiveOverride::Rows(rows)) => target = rows as f64,
            Some(EffectiveOverride::Scale(scale)) => target = base * scale,
            None | Some(EffectiveOverride::Conflict) => {}
        }

        let count = stochastic_round(target, rounding_root, name);
        apply_max_rows(count, options.max_rows, name, bag)
    }

    #[allow(clippy::too_many_arguments)]
    fn resolve_child_count(
        &self,
        name: &str,
        parent: &str,
        distribution: &ChildDistribution,
        options: &CompileOptions,
        over: Option<&TableOverride>,
        rounding_root: SeedRoot,
        resolved: &BTreeMap<String, u64>,
        bag: &mut DiagnosticBag,
    ) -> u64 {
        // A missing parent means it was excluded/cyclic; that error is already
        // recorded, so resolve to zero and let the compile fail.
        let Some(&parent_count) = resolved.get(parent) else {
            return 0;
        };
        let (mean, min, _max) = distribution_bounds(distribution);

        // Children derive from the FINAL parent count and stored fan-out; the
        // global control is deliberately NOT reapplied (no double-scale).
        let derived = parent_count as f64 * mean;
        let target = match over.map(TableOverride::effective) {
            Some(EffectiveOverride::Rows(rows)) => rows as f64,
            Some(EffectiveOverride::Scale(scale)) => derived * scale,
            None | Some(EffectiveOverride::Conflict) => derived,
        };

        let count = stochastic_round(target, rounding_root, name);
        let count = apply_max_rows(count, options.max_rows, name, bag);

        let minimum = (parent_count as f64 * min).ceil() as u64;
        if count < minimum {
            bag.error(
                crate::diagnostic::codes::CHILD_COUNT_IMPOSSIBLE.code,
                format!("tables.{name}.rows"),
                format!(
                    "table `{name}` resolves to {count} rows, but its {parent_count} parents in `{parent}` each require at least {min} child(ren) ({minimum} total)"
                ),
            );
        }
        count
    }

    /// Build a [`PlannedTable`]: resolve seed and relationships, compile every
    /// declared planner, assign exactly one owner to each column, type-check
    /// generators/modifiers, and report read/write dependency cycles. All
    /// diagnostics are appended to `bag`.
    #[allow(clippy::too_many_arguments)]
    fn plan_table(
        &self,
        model: &SyntheticModel,
        name: &str,
        table: &TableModel,
        rows: u64,
        root_seed: u64,
        inference: InferenceMode,
        family_ctx: &FamilyContext,
        resolved: &BTreeMap<String, u64>,
        selected: &BTreeSet<String>,
        preserve_raw: bool,
        max_rows: Option<u64>,
        bag: &mut DiagnosticBag,
    ) -> PlannedTable {
        let seed = resolve_seed(&table.seed, root_seed);
        let compile_seed = seed_root_of(&seed);
        // Reject a table that declares the same column name more than once — a
        // schema authoring error that otherwise surfaces as a confusing
        // owner-missing error or a bare DEFAULT at render time.
        let mut seen_columns: BTreeSet<&str> = BTreeSet::new();
        for column in &table.schema.columns {
            if !seen_columns.insert(column.name.as_str()) {
                bag.error(
                    crate::diagnostic::codes::DUPLICATE_COLUMN.code,
                    format!("tables.{name}.schema.columns"),
                    format!(
                        "table `{name}` declares column `{}` more than once",
                        column.name
                    ),
                );
            }
        }
        self.validate_column_operator_arguments(name, table, bag);
        let mut relationships: Vec<CompiledRelationship> = table
            .relationships
            .iter()
            .map(compile_relationship)
            .collect();
        // Foreign keys declared only in the portable schema (the common shape
        // for FKs recovered from a parsed dump) are compiled too, so the engine
        // can assign their values. A generation relationship on the same columns
        // wins, since it can carry an explicit assignment distribution.
        for schema_rel in &table.schema.relationships {
            if relationships
                .iter()
                .any(|existing| existing.columns == schema_rel.columns)
            {
                continue;
            }
            relationships.push(CompiledRelationship {
                name: schema_rel.name.clone(),
                columns: schema_rel.columns.clone(),
                parent_table: schema_rel.referenced_table.clone(),
                parent_columns: schema_rel.referenced_columns.clone(),
                distribution: RelationshipDistribution::default(),
                null_permille: 0,
            });
        }
        fold_foreign_key_generators(name, table, &mut relationships, bag);

        // Detach any compiled relationship whose parent table was excluded, so
        // the output never references an absent table. A required (non-null) FK
        // to an excluded table already produced a `GEN-EXCLUDED-DEPENDENCY`
        // error; a nullable one is deliberately detachable, so warn (and let
        // `--strict` promote it) rather than fail.
        relationships.retain(|relationship| {
            if selected.contains(&relationship.parent_table) {
                return true;
            }
            if !fk_columns_all_non_null(table, &relationship.columns) {
                bag.warning(
                    crate::diagnostic::codes::DETACHED_DEPENDENCY.code,
                    format!("tables.{name}"),
                    format!(
                        "optional relationship `{}` on table `{name}` references excluded table `{}`; its foreign key is detached and omitted from the rendered DDL",
                        relationship.name.as_deref().unwrap_or("(unnamed)"),
                        relationship.parent_table
                    ),
                );
            }
            false
        });

        for relationship in &relationships {
            let parent_is_empty = resolved
                .get(&relationship.parent_table)
                .is_some_and(|count| *count == 0);
            if rows > 0 && parent_is_empty && !fk_columns_all_nullable(table, &relationship.columns)
            {
                bag.error(
                    crate::diagnostic::codes::FOREIGN_KEY_UNRESOLVED.code,
                    format!("tables.{name}.relationships"),
                    format!(
                        "table `{name}` resolves to {rows} row(s), but required relationship `{}` targets empty parent table `{}`",
                        relationship.name.as_deref().unwrap_or("(unnamed)"),
                        relationship.parent_table
                    ),
                );
            }
        }

        let planners = self.compile_planners(
            model,
            name,
            table,
            compile_seed,
            family_ctx,
            resolved,
            rows,
            max_rows,
            bag,
        );
        let claims = collect_claims(table, &planners);

        let columns: Vec<PlannedColumn> = table
            .schema
            .columns
            .iter()
            .map(|column| {
                let owner = self.resolve_owner(
                    name,
                    table,
                    column,
                    claims.get(&column.name).map(Vec::as_slice).unwrap_or(&[]),
                    &planners,
                    family_ctx,
                    compile_seed,
                    inference,
                    bag,
                );
                let modifiers =
                    self.compile_modifiers(name, table, column, &owner, compile_seed, bag);
                PlannedColumn {
                    schema: column.clone(),
                    owner,
                    modifiers,
                }
            })
            .collect();

        report_dependency_cycles(name, table, &columns, &planners, bag);
        let eval_order = column_eval_order(table, &columns);

        // On a successful compile every planner resolved and compiled, so this
        // filter keeps them all in declaration order and a `ColumnOwner::
        // Planner`'s `planner_index` stays valid. If any planner failed, the
        // bag holds an error and the plan is discarded before it is observed.
        let compiled_planners = planners.into_iter().filter_map(|p| p.compiled).collect();

        // The normalized portable schema the renderer sees: drop every foreign
        // key to an absent table, and any index that references an object that no
        // longer exists (columns are never dropped here, so the index guard is a
        // no-op today but keeps the invariant explicit). Clear the raw
        // `create_statement` whenever the schema set changed, so a filtered run
        // renders normalized DDL instead of stale original DDL.
        let present_columns: BTreeSet<&str> = table
            .schema
            .columns
            .iter()
            .map(|c| c.name.as_str())
            .collect();
        let mut schema = table.schema.clone();
        schema
            .relationships
            .retain(|relationship| selected.contains(&relationship.referenced_table));
        schema.indexes.retain(|index| {
            index
                .columns
                .iter()
                .all(|c| present_columns.contains(c.as_str()))
        });
        if !preserve_raw {
            schema.create_statement = None;
        }

        PlannedTable {
            name: name.to_string(),
            rows,
            schema,
            seed,
            columns,
            relationships,
            planners: compiled_planners,
            eval_order,
        }
    }

    /// Resolve and compile every declared planner, collecting `GEN-PLANNER-*`
    /// diagnostics and the read/write column sets each planner declares.
    #[allow(clippy::too_many_arguments)]
    fn compile_planners(
        &self,
        model: &SyntheticModel,
        table_name: &str,
        table: &TableModel,
        seed: SeedRoot,
        family_ctx: &FamilyContext,
        resolved: &BTreeMap<String, u64>,
        parent_rows: u64,
        max_rows: Option<u64>,
        bag: &mut DiagnosticBag,
    ) -> Vec<PlannerInfo> {
        let relationship_names = relationship_names(table);
        // Cross-table FK-side planners (junction/tenant/polymorphic) reference
        // OTHER tables' keys but the planner only sees its own table at compile.
        // The compiler has the whole model plus the resolved counts (parents
        // precede children in dependency order), so it injects the referenced
        // tables' resolved counts and dense key recipes as facts — the same
        // pattern the family planner uses, driven off the `cross_table`
        // capability rather than any specific `kind`.
        let relation_facts = build_relation_facts(model, table, resolved);
        table
            .planners
            .iter()
            .enumerate()
            .map(|(index, config)| {
                let path = format!("tables.{table_name}.planners[{index}]");
                let Some(factory) = self.registry.planner(&config.kind) else {
                    bag.error(
                        crate::diagnostic::codes::PLANNER_UNKNOWN.code,
                        path,
                        format!("no planner registered for kind `{}`", config.kind),
                    );
                    return PlannerInfo::unresolved(&config.kind);
                };
                let descriptor = factory.descriptor();
                validate_operator_arguments(
                    &config.args,
                    descriptor.arguments,
                    &path,
                    "planner",
                    &config.kind,
                    bag,
                );
                // A cross-table family planner (`children:`) carries its
                // relationship on the *child* table; the compiler injected the
                // child facts to validate it there, so skip the same-table
                // relationship check that would otherwise falsely reject it.
                let is_family = config.args.contains_key("children");
                let is_cross_table = descriptor.cross_table;
                let injected;
                let config = if let Some(facts) =
                    family_ctx.facts.get(&(table_name.to_string(), index))
                {
                    let mut cloned = config.clone();
                    let mut facts = facts.clone();
                    if let (Some(max_rows), serde_yaml_ng::Value::Mapping(mapping)) =
                        (max_rows, &mut facts)
                    {
                        mapping.insert("child_row_limit".into(), max_rows.into());
                    }
                    if let serde_yaml_ng::Value::Mapping(mapping) = &mut facts {
                        mapping.insert("parent_rows".into(), parent_rows.into());
                    }
                    cloned.args.insert(
                        super::planners::order_family::FAMILY_FACTS_KEY.to_string(),
                        facts,
                    );
                    injected = cloned;
                    &injected
                } else if !is_family
                    && (is_cross_table || config.args.contains_key("relationship"))
                {
                    // A planner that references another table's (or its own
                    // self-FK) key domain by relationship name: inject the
                    // resolved parent counts and dense key recipes so it can
                    // produce valid keys. This covers the FK-side cross-table
                    // planners (junction/tenant/polymorphic) and the same-table
                    // `hierarchy.tree`, which derives its emitted parent_id key
                    // from the referenced primary key's generator.
                    let mut cloned = config.clone();
                    cloned.args.insert(
                        super::planners::structural::RELATION_FACTS_KEY.to_string(),
                        relation_facts.clone(),
                    );
                    injected = cloned;
                    &injected
                } else {
                    config
                };
                let writes = match descriptor.writes {
                    ColumnScope::Configured => configured_columns(config, &["columns", "writes"]),
                    _ => Vec::new(),
                };
                let reads = match descriptor.reads {
                    ColumnScope::Configured => configured_columns(config, &["reads"]),
                    _ => Vec::new(),
                };

                if !is_family {
                    if let Some(referenced) = string_arg(config, "relationship") {
                        if !relationship_names.iter().any(|n| n == referenced) {
                            bag.error(
                                crate::diagnostic::codes::RELATIONSHIP_UNKNOWN.code,
                                format!("{path}.relationship"),
                                format!(
                                    "planner `{}` references relationship `{referenced}`, which is not declared on table `{table_name}`",
                                    config.kind
                                ),
                            );
                        }
                    }
                }

                let context = CompileContext::for_table(&table.schema, seed, &path);
                let compiled = match factory.compile(config, &context) {
                    Ok(compiled) => Some(compiled),
                    Err(errors) => {
                        bag.diagnostics.extend(errors.diagnostics);
                        None
                    }
                };

                PlannerInfo {
                    kind: descriptor.kind.to_string(),
                    writes,
                    reads,
                    compiled,
                }
            })
            .collect()
    }

    /// Validate descriptor-owned generator/modifier keys before ownership
    /// resolution. This includes relationship marker generators that the
    /// engine consumes structurally instead of compiling as value operators.
    fn validate_column_operator_arguments(
        &self,
        table_name: &str,
        table: &TableModel,
        bag: &mut DiagnosticBag,
    ) {
        for (column_name, rule) in &table.columns {
            if let Some(config) = &rule.generator {
                if let Some(factory) = self.registry.generator(&config.kind) {
                    validate_operator_arguments(
                        &config.args,
                        factory.descriptor().arguments,
                        &format!("tables.{table_name}.columns.{column_name}.generator"),
                        "generator",
                        &config.kind,
                        bag,
                    );
                }
            }
            for (index, config) in rule.modifiers.iter().enumerate() {
                if let Some(factory) = self.registry.modifier(&config.kind) {
                    validate_operator_arguments(
                        &config.args,
                        factory.descriptor().arguments,
                        &format!("tables.{table_name}.columns.{column_name}.modifiers[{index}]"),
                        "modifier",
                        &config.kind,
                        bag,
                    );
                }
            }
        }
    }

    /// Assign the single owner for `column`, given its recorded claimants.
    #[allow(clippy::too_many_arguments)]
    fn resolve_owner(
        &self,
        table_name: &str,
        table: &TableModel,
        column: &PortableColumn,
        claimants: &[Claim],
        planners: &[PlannerInfo],
        family_ctx: &FamilyContext,
        seed: SeedRoot,
        inference: InferenceMode,
        bag: &mut DiagnosticBag,
    ) -> ColumnOwner {
        if claimants.len() > 1 {
            let diagnostic = bag.error(
                crate::diagnostic::codes::COLUMN_OWNER_CONFLICT.code,
                format!("tables.{table_name}.columns.{}", column.name),
                format!(
                    "tables.{table_name}.columns.{} is produced by more than one owner",
                    column.name
                ),
            );
            diagnostic.related = claimants
                .iter()
                .map(|claim| SourceLocation {
                    path: claim.path.clone(),
                    description: claim.description.clone(),
                })
                .collect();
            diagnostic.help = Some(format!(
                "keep a single owner for `{}`: remove the column generator or drop it from the planner mapping",
                column.name
            ));
            return ColumnOwner::GeneratedByDatabase;
        }

        if let Some(claim) = claimants.first() {
            return match &claim.source {
                ClaimSource::Generator => {
                    self.compile_generator(table_name, table, column, seed, bag)
                }
                ClaimSource::Planner { index } => ColumnOwner::Planner {
                    kind: planners[*index].kind.clone(),
                    planner_index: *index,
                },
            };
        }

        // A cross-table family planner (declared on another table) may own this
        // column; that ownership was recorded when its parent table was planned.
        if let Some(external) = family_ctx
            .external_owners
            .get(&(table_name.to_string(), column.name.clone()))
        {
            return ColumnOwner::FamilyChild {
                planner_kind: external.planner_kind.clone(),
            };
        }

        self.infer_structural_owner(table_name, table, column, inference, seed, bag)
    }

    /// Resolve, type-check, and compile the explicit generator on `column`.
    fn compile_generator(
        &self,
        table_name: &str,
        table: &TableModel,
        column: &PortableColumn,
        seed: SeedRoot,
        bag: &mut DiagnosticBag,
    ) -> ColumnOwner {
        let path = format!("tables.{table_name}.columns.{}.generator", column.name);
        let config = table.columns[&column.name]
            .generator
            .as_ref()
            .expect("generator claim implies a generator rule");
        self.compile_generator_config(table, column, config, path, seed, bag)
    }

    /// Look up, type-check, and compile `config` into a generator owner for
    /// `column`, attaching unknown-kind and type-mismatch diagnostics to `path`.
    /// Shared by the explicit-generator path and schema inference.
    fn compile_generator_config(
        &self,
        table: &TableModel,
        column: &PortableColumn,
        config: &crate::synthetic::model::GeneratorConfig,
        path: String,
        seed: SeedRoot,
        bag: &mut DiagnosticBag,
    ) -> ColumnOwner {
        let Some(factory) = self.registry.generator(&config.kind) else {
            bag.error(
                crate::diagnostic::codes::GENERATOR_UNKNOWN.code,
                path,
                format!("no generator registered for kind `{}`", config.kind),
            );
            return ColumnOwner::GeneratedByDatabase;
        };
        let descriptor = factory.descriptor();

        if !descriptor.accepts.contains(&column.family) {
            bag.error(
                crate::diagnostic::codes::GENERATOR_TYPE.code,
                path,
                format!(
                    "generator `{}` cannot produce column `{}` of type family {:?}",
                    config.kind, column.name, column.family
                ),
            );
            return ColumnOwner::GeneratedByDatabase;
        }

        let context = CompileContext::for_column(&table.schema, column, seed, &path);
        match factory.compile(config, &context) {
            Ok(compiled) => ColumnOwner::Generator {
                kind: descriptor.kind.to_string(),
                compiled,
            },
            Err(errors) => {
                bag.diagnostics.extend(errors.diagnostics);
                ColumnOwner::GeneratedByDatabase
            }
        }
    }

    /// Owner for a column with no generator and no planner claim, from
    /// structural schema facts alone (no data observation). A column that no
    /// structural rule can supply is `GEN-COLUMN-OWNER-MISSING`.
    fn infer_structural_owner(
        &self,
        table_name: &str,
        table: &TableModel,
        column: &PortableColumn,
        inference: InferenceMode,
        seed: SeedRoot,
        bag: &mut DiagnosticBag,
    ) -> ColumnOwner {
        // HARD schema facts — genuine database-supplied values, honored in BOTH
        // `disabled` and `schema` modes because they are declared in the DDL,
        // not inferred by convention.
        if column.generated || column.identity {
            return ColumnOwner::GeneratedByDatabase;
        }
        if foreign_key_columns(table).contains(&column.name) {
            return ColumnOwner::Relationship {
                relationship: relationship_of(table, &column.name),
            };
        }
        if column.default_sql.is_some() {
            return ColumnOwner::DatabaseDefault;
        }

        // CONVENTION — a bare integer primary key (no identity/serial flag, no
        // explicit owner) is treated as a database sequence. This is inference,
        // not a declared fact, so it runs ONLY under `schema` mode; under
        // `disabled` every generated column needs an explicit owner, so a bare
        // PK falls through to `GEN-COLUMN-OWNER-MISSING`.
        //
        // `GeneratedByDatabase` here means "the DB fills it", but a plain integer
        // PK has no sequence to fill from. Schema inference currently classifies
        // it this way without attaching the registered `sequence` generator, so
        // rendered output relies on database behavior for the value.
        if matches!(inference, InferenceMode::Schema)
            && column.primary_key
            && matches!(
                column.family,
                SqlTypeFamily::Integer | SqlTypeFamily::BigInteger
            )
        {
            return ColumnOwner::GeneratedByDatabase;
        }

        // Nothing structural applies. Under `schema` inference, derive a
        // generator from the column's name and declared type (email ->
        // internet.email, created_at -> datetime, a plain text column ->
        // string, ...) using the same name/type heuristics the profiler applies
        // at schema depth. The type fallback is the guaranteed floor, so this
        // never leaves a column unowned. Under `disabled` inference every
        // generated column needs an explicit owner, so the column is reported
        // as `GEN-COLUMN-OWNER-MISSING`.
        match inference {
            InferenceMode::Schema => {
                let config =
                    crate::profile::heuristics::schema_inferred_generator(&table.schema, column);
                let path = format!(
                    "tables.{table_name}.columns.{}.generator[inferred]",
                    column.name
                );
                self.compile_generator_config(table, column, &config, path, seed, bag)
            }
            InferenceMode::Disabled => {
                bag.error(
                    crate::diagnostic::codes::COLUMN_OWNER_MISSING.code,
                    format!("tables.{table_name}.columns.{}", column.name),
                    format!(
                        "column `{}` on table `{table_name}` has no generator, planner, relationship, or database default to produce its value",
                        column.name
                    ),
                );
                ColumnOwner::GeneratedByDatabase
            }
        }
    }

    /// Type-check every modifier declared on `column`, and compile the pipeline
    /// into runnable operators (in declared order) for a generator-owned column
    /// so the engine can apply it after generation.
    ///
    /// Modifiers are compiled only for [`ColumnOwner::Generator`] columns: a
    /// `DatabaseDefault`/`GeneratedByDatabase`/`Relationship`/`Planner` column
    /// does not run a per-column generator pipeline (its value is a database
    /// placeholder, a materialized key, or planner-coordinated). Type-checking
    /// still runs for every column so a misapplied modifier is reported
    /// regardless of owner.
    fn compile_modifiers(
        &self,
        table_name: &str,
        table: &TableModel,
        column: &PortableColumn,
        owner: &ColumnOwner,
        seed: SeedRoot,
        bag: &mut DiagnosticBag,
    ) -> Vec<Box<dyn CompiledModifier>> {
        // A column inferred under `schema` mode has no explicit rule in the
        // model; treat it as one with no declared modifiers so its generator
        // still reaches `enforce_key_uniqueness` (an inferred key column must
        // still be deduplicated).
        let empty_rule;
        let rule = match table.columns.get(&column.name) {
            Some(rule) => rule,
            None => {
                empty_rule = crate::synthetic::model::ColumnRule {
                    semantic: None,
                    generator: None,
                    modifiers: Vec::new(),
                };
                &empty_rule
            }
        };
        let is_generator = matches!(owner, ColumnOwner::Generator { .. });
        let mut compiled: Vec<Box<dyn CompiledModifier>> = Vec::new();
        for (index, modifier) in rule.modifiers.iter().enumerate() {
            let path = format!(
                "tables.{table_name}.columns.{}.modifiers[{index}]",
                column.name
            );
            let Some(factory) = self.registry.modifier(&modifier.kind) else {
                bag.error(
                    crate::diagnostic::codes::MODIFIER_UNKNOWN.code,
                    path,
                    format!("no modifier registered for kind `{}`", modifier.kind),
                );
                continue;
            };
            if !factory.descriptor().accepts.contains(&column.family) {
                bag.error(
                    crate::diagnostic::codes::MODIFIER_TYPE.code,
                    path,
                    format!(
                        "modifier `{}` cannot transform column `{}` of type family {:?}",
                        modifier.kind, column.name, column.family
                    ),
                );
                continue;
            }
            if !is_generator {
                continue;
            }
            let context = CompileContext::for_column(&table.schema, column, seed, &path);
            match factory.compile(modifier, &context) {
                Ok(operator) => compiled.push(operator),
                Err(errors) => bag.diagnostics.extend(errors.diagnostics),
            }
        }

        self.enforce_key_uniqueness(
            table_name,
            table,
            column,
            owner,
            rule,
            seed,
            &mut compiled,
            bag,
        );

        compiled
    }

    /// Guarantee a single-column primary/unique key is unique BY CONSTRUCTION:
    /// auto-attach a `unique` modifier (with `on_exhaustion: error`) to a
    /// generator-owned key column whose generator is not already inherently
    /// unique. A `sequence`/`Dense` generator is unique by construction and a
    /// `uuid` collision is astronomically negligible, so both are left alone;
    /// `monotonic` (a row-indexed sequence with no key recipe) is treated as
    /// inherently unique too. Everything else (`string`, `pattern`, `choice`,
    /// semantic text, …) could collide on a key column, so it gets the modifier
    /// — which either de-duplicates the value or fails loudly, never silently
    /// emitting a duplicate key. A user-declared `unique` modifier is honored as
    /// is and never doubled. Composite (multi-column) keys are deliberately not
    /// enforced here (per-column dedup cannot guarantee composite uniqueness).
    #[allow(clippy::too_many_arguments)]
    fn enforce_key_uniqueness(
        &self,
        table_name: &str,
        table: &TableModel,
        column: &PortableColumn,
        owner: &ColumnOwner,
        rule: &crate::synthetic::model::ColumnRule,
        seed: SeedRoot,
        compiled: &mut Vec<Box<dyn CompiledModifier>>,
        bag: &mut DiagnosticBag,
    ) {
        let ColumnOwner::Generator {
            compiled: generator,
            ..
        } = owner
        else {
            return;
        };
        if !is_single_column_key(&table.schema, column) {
            return;
        }
        if generator.is_inherently_unique() {
            return;
        }
        // A user-declared `unique` modifier already enforces distinctness (with
        // whatever `on_exhaustion` they chose); do not add a second one.
        if rule
            .modifiers
            .iter()
            .any(|modifier| modifier.kind == "unique")
        {
            return;
        }
        let Some(factory) = self.registry.modifier("unique") else {
            return;
        };
        let path = format!(
            "tables.{table_name}.columns.{}.modifiers[auto-unique]",
            column.name
        );
        let config = ModifierConfig {
            kind: "unique".to_string(),
            args: [(
                "on_exhaustion".to_string(),
                serde_yaml_ng::Value::from("error"),
            )]
            .into_iter()
            .collect(),
        };
        let context = CompileContext::for_column(&table.schema, column, seed, &path);
        match factory.compile(&config, &context) {
            Ok(operator) => compiled.push(operator),
            Err(errors) => bag.diagnostics.extend(errors.diagnostics),
        }
    }
}

/// Reject keys the registered descriptor does not publish. Factories remain
/// responsible for required arguments and value semantics; this common pass
/// only closes the permissive flattened-map gap shared by every operator kind.
fn validate_operator_arguments(
    args: &BTreeMap<String, serde_yaml_ng::Value>,
    expected: &[super::registry::ArgumentSpec],
    path: &str,
    operator_type: &str,
    kind: &str,
    bag: &mut DiagnosticBag,
) {
    for argument in args.keys() {
        if expected.iter().any(|spec| spec.name == argument) {
            continue;
        }
        let diagnostic = bag.error(
            crate::diagnostic::codes::OPERATOR_UNKNOWN_ARGUMENT.code,
            format!("{path}.{argument}"),
            format!("{operator_type} `{kind}` does not accept argument `{argument}`"),
        );
        if !expected.is_empty() {
            diagnostic.help = Some(format!(
                "supported arguments: {}",
                expected
                    .iter()
                    .map(|spec| spec.name)
                    .collect::<Vec<_>>()
                    .join(", ")
            ));
        }
    }
}

/// The union of every column that participates in the table's primary key,
/// from both the table-level `primary_key` list and column-level flags.
fn primary_key_columns(table: &PortableTable) -> BTreeSet<&str> {
    let mut columns: BTreeSet<&str> = table.primary_key.iter().map(String::as_str).collect();
    columns.extend(
        table
            .columns
            .iter()
            .filter(|column| column.primary_key)
            .map(|column| column.name.as_str()),
    );
    columns
}

/// Whether `column` is enforced-unique by a SINGLE-COLUMN key: it is the sole
/// primary-key column, or it carries a one-column UNIQUE constraint (a
/// column-level `unique` flag, a single-column unique constraint, or a
/// single-column unique index). Composite keys (2+ columns) are excluded — per
/// column deduplication cannot guarantee composite uniqueness.
fn is_single_column_key(table: &PortableTable, column: &PortableColumn) -> bool {
    let primary = primary_key_columns(table);
    if primary.len() == 1 && primary.contains(column.name.as_str()) {
        return true;
    }
    if column.unique {
        return true;
    }
    let single = |columns: &[String]| columns.len() == 1 && columns[0] == column.name;
    table
        .unique_constraints
        .iter()
        .any(|constraint| single(&constraint.columns))
        || table
            .indexes
            .iter()
            .any(|index| index.unique && single(&index.columns))
}

/// The per-table override view folded from the flat CLI list.
#[derive(Debug, Default, Clone, Copy)]
struct TableOverride {
    rows: Option<u64>,
    scale: Option<f64>,
}

/// The override actually applied once conflicts are accounted for.
enum EffectiveOverride {
    Rows(u64),
    Scale(f64),
    Conflict,
}

impl TableOverride {
    fn effective(&self) -> EffectiveOverride {
        match (self.rows, self.scale) {
            (Some(_), Some(_)) => EffectiveOverride::Conflict,
            (Some(rows), None) => EffectiveOverride::Rows(rows),
            (None, Some(scale)) => EffectiveOverride::Scale(scale),
            (None, None) => EffectiveOverride::Conflict,
        }
    }
}

/// Cap `count` at `max_rows` (the last step of count resolution), emitting a
/// surviving warning when the cap actually reduces the count.
fn apply_max_rows(count: u64, max_rows: Option<u64>, name: &str, bag: &mut DiagnosticBag) -> u64 {
    match max_rows {
        Some(max) if count > max => {
            bag.warning(
                crate::diagnostic::codes::MAX_ROWS_CAPPED.code,
                format!("tables.{name}.rows"),
                format!("table `{name}` row count capped from {count} to {max} by `--max-rows`"),
            );
            max
        }
        _ => count,
    }
}

/// Stochastically round `value` to an integer on the table's stable
/// `rows.rounding` stream: round up with probability equal to the fraction.
fn stochastic_round(value: f64, root: SeedRoot, table: &str) -> u64 {
    if value <= 0.0 {
        return 0;
    }
    let floor = value.floor();
    let fraction = value - floor;
    let mut count = floor as u64;
    if fraction > 0.0 {
        let mut rng = root.stream(StreamId::rounding(table));
        if rng.random::<f64>() < fraction {
            count += 1;
        }
    }
    count
}

/// The declared row count for the count-carrying `RowsModel` variants;
/// `relation.children` carries no standalone count (it derives from a parent).
fn declared_count(rows: &RowsModel) -> Option<u64> {
    match rows {
        RowsModel::Fixed { count }
        | RowsModel::Observed { count }
        | RowsModel::Scale { count, .. } => Some(*count),
        RowsModel::RelationChildren { .. } => None,
    }
}

/// The kind name of a child fan-out distribution, so a family planner can honor
/// its *shape* (not just its bounds) when drawing per-order line counts.
fn distribution_kind(distribution: &ChildDistribution) -> &'static str {
    match distribution {
        ChildDistribution::Observed { .. } => "observed",
        ChildDistribution::Fixed { .. } => "fixed",
        ChildDistribution::Uniform { .. } => "uniform",
        ChildDistribution::Poisson { .. } => "poisson",
        ChildDistribution::Histogram { .. } => "histogram",
    }
}

/// The `(mean, min, max)` fan-out bounds of any child distribution.
fn distribution_bounds(distribution: &ChildDistribution) -> (f64, f64, f64) {
    match distribution {
        ChildDistribution::Observed { mean, min, max }
        | ChildDistribution::Fixed { mean, min, max }
        | ChildDistribution::Uniform { mean, min, max }
        | ChildDistribution::Poisson { mean, min, max }
        | ChildDistribution::Histogram { mean, min, max } => (*mean, *min, *max),
    }
}

/// Whether an `observed` row count has a source or profile to resolve from.
fn has_observed_provenance(model: &SyntheticModel, table: &str) -> bool {
    model.source.is_some()
        || model
            .profiles
            .keys()
            .filter_map(|key| key.split_once('.'))
            .any(|(profiled_table, _)| profiled_table == table)
}

/// Which parent edges [`parent_edges`] collects.
#[derive(Clone, Copy, PartialEq, Eq)]
enum EdgeKind {
    /// Every ordering edge: relation.children parents, polymorphic targets, and
    /// every foreign key regardless of nullability.
    All,
    /// Only edges whose absence is fatal: relation.children parents, polymorphic
    /// targets, and non-null foreign keys. A nullable FK is detachable, so it is
    /// not required.
    Required,
}

/// Whether every column of a foreign key is declared `NOT NULL`; a nullable
/// component makes the whole relationship optional (detachable). An unknown
/// column is treated conservatively as required.
fn fk_columns_all_non_null(table: &TableModel, columns: &[String]) -> bool {
    columns.iter().all(|column| {
        table
            .schema
            .columns
            .iter()
            .find(|candidate| &candidate.name == column)
            .map(|candidate| !candidate.nullable)
            .unwrap_or(true)
    })
}

/// Whether every column of a foreign key can represent the all-NULL composite
/// used when its parent domain is empty. Unknown columns are not nullable.
fn fk_columns_all_nullable(table: &TableModel, columns: &[String]) -> bool {
    columns.iter().all(|column| {
        table
            .schema
            .columns
            .iter()
            .find(|candidate| &candidate.name == column)
            .is_some_and(|candidate| candidate.nullable)
    })
}

/// Parent edges per table for the requested [`EdgeKind`]: the `relation.children`
/// parent plus every declared relationship's referenced table (generation
/// relationships and portable-schema foreign keys). Under [`EdgeKind::Required`]
/// a nullable foreign key is omitted, since it may be detached rather than
/// forcing its parent to be retained.
fn parent_edges(model: &SyntheticModel, kind: EdgeKind) -> BTreeMap<String, BTreeSet<String>> {
    model
        .tables
        .iter()
        .map(|(name, table)| {
            let generation = table
                .relationships
                .iter()
                .map(|relationship| (relationship.references.table.clone(), &relationship.columns));
            let schema =
                table.schema.relationships.iter().map(|relationship| {
                    (relationship.referenced_table.clone(), &relationship.columns)
                });
            let mut parents: BTreeSet<String> = BTreeSet::new();
            for (parent, columns) in generation.chain(schema) {
                if kind == EdgeKind::All || fk_columns_all_non_null(table, columns) {
                    parents.insert(parent);
                }
            }
            if let RowsModel::RelationChildren { parent, .. } = &table.rows {
                parents.insert(parent.clone());
            }
            // A polymorphic planner references its target tables by name (with no
            // `relationships:` entry), so those targets are ordering dependencies
            // too: their counts must be resolved before this table is planned.
            for planner in &table.planners {
                if let Some(serde_yaml_ng::Value::Sequence(items)) = planner.args.get("targets") {
                    for item in items {
                        if let Some(target) =
                            item.get("table").and_then(serde_yaml_ng::Value::as_str)
                        {
                            parents.insert(target.to_string());
                        }
                    }
                }
            }
            // A table never depends on itself for ordering purposes.
            parents.remove(name);
            (name.clone(), parents)
        })
        .collect()
}

/// Topologically order the selected tables, parents before children, using
/// only edges between selected tables. Deterministic via sorted `BTreeMap`s.
///
/// Returns `(order, cyclic)`: `order` is the tables that could be sequenced
/// parents-first, and `cyclic` is any tables trapped in a mutual dependency
/// cycle (in name order). The caller turns a non-empty `cyclic` into a
/// `GEN-ROWS-CYCLE` error rather than resolving those tables to zero rows.
fn topo_order(
    selected: &BTreeSet<String>,
    parents: &BTreeMap<String, BTreeSet<String>>,
) -> (Vec<String>, Vec<String>) {
    let mut in_degree: BTreeMap<String, usize> = BTreeMap::new();
    let mut children: BTreeMap<String, Vec<String>> = BTreeMap::new();
    for name in selected {
        let selected_parents: Vec<&String> = parents
            .get(name)
            .into_iter()
            .flatten()
            .filter(|parent| selected.contains(*parent))
            .collect();
        in_degree.insert(name.clone(), selected_parents.len());
        for parent in selected_parents {
            children
                .entry(parent.clone())
                .or_default()
                .push(name.clone());
        }
    }

    // Ready tables are drained smallest-name-first. The queue is kept sorted
    // descending and popped from the back so the emitted order is stable and
    // alphabetical within each dependency level.
    let mut queue: Vec<String> = in_degree
        .iter()
        .filter(|(_, &degree)| degree == 0)
        .map(|(name, _)| name.clone())
        .collect();
    queue.sort();
    queue.reverse();
    let mut order: Vec<String> = Vec::with_capacity(selected.len());
    while let Some(name) = queue.pop() {
        order.push(name.clone());
        if let Some(kids) = children.get(&name) {
            for kid in kids {
                let degree = in_degree.get_mut(kid).expect("child has an in-degree");
                *degree -= 1;
                if *degree == 0 {
                    queue.push(kid.clone());
                }
            }
        }
        queue.sort();
        queue.reverse();
    }

    // Any selected table the Kahn drain never reached is trapped in a cycle.
    let cyclic: Vec<String> = selected
        .iter()
        .filter(|name| !order.contains(name))
        .cloned()
        .collect();
    (order, cyclic)
}

/// A declared planner after resolution: its resolved kind, the column sets it
/// reads and writes, and its compiled form (absent if resolution or compile
/// failed — the corresponding diagnostic is already recorded).
struct PlannerInfo {
    kind: String,
    writes: Vec<String>,
    reads: Vec<String>,
    compiled: Option<Box<dyn CompiledPlanner>>,
}

impl PlannerInfo {
    /// A planner whose kind did not resolve in the registry.
    fn unresolved(kind: &str) -> Self {
        Self {
            kind: kind.to_string(),
            writes: Vec::new(),
            reads: Vec::new(),
            compiled: None,
        }
    }
}

/// One recorded claim of ownership over a column, for conflict reporting.
struct Claim {
    source: ClaimSource,
    path: String,
    description: Option<String>,
}

/// Who a [`Claim`] comes from.
enum ClaimSource {
    /// The column's own explicit generator rule.
    Generator,
    /// A planner, by its index in the table's compiled planner list.
    Planner { index: usize },
}

/// Record every ownership claim over each column: an explicit generator plus
/// each planner that names the column in its `columns`/`writes` set. A column
/// with more than one claim is a `GEN-COLUMN-OWNER-CONFLICT`.
fn collect_claims(table: &TableModel, planners: &[PlannerInfo]) -> BTreeMap<String, Vec<Claim>> {
    let mut claims: BTreeMap<String, Vec<Claim>> = BTreeMap::new();
    for (name, rule) in &table.columns {
        if rule.generator.is_some() {
            claims.entry(name.clone()).or_default().push(Claim {
                source: ClaimSource::Generator,
                path: format!("columns.{name}.generator"),
                description: None,
            });
        }
    }
    for (index, planner) in planners.iter().enumerate() {
        // A single planner claims each column once, even if it lists the column
        // under more than one config key (`columns` and `writes`); otherwise it
        // would falsely conflict with itself.
        let mut claimed: BTreeSet<&str> = BTreeSet::new();
        for column in &planner.writes {
            if !claimed.insert(column.as_str()) {
                continue;
            }
            claims.entry(column.clone()).or_default().push(Claim {
                source: ClaimSource::Planner { index },
                path: format!("planners[{index}]"),
                description: Some(planner.kind.clone()),
            });
        }
    }
    claims
}

/// The column names a planner config names under any of `keys`. Each key's
/// value may be a sequence of names or a mapping whose values are names (the
/// `role: column` planner mapping shape).
fn configured_columns(config: &PlannerConfig, keys: &[&str]) -> Vec<String> {
    let mut columns = Vec::new();
    for key in keys {
        match config.args.get(*key) {
            Some(serde_yaml_ng::Value::Sequence(items)) => columns.extend(
                items
                    .iter()
                    .filter_map(serde_yaml_ng::Value::as_str)
                    .map(str::to_string),
            ),
            Some(serde_yaml_ng::Value::Mapping(map)) => columns.extend(
                map.values()
                    .filter_map(serde_yaml_ng::Value::as_str)
                    .map(str::to_string),
            ),
            _ => {}
        }
    }
    columns
}

/// A single string-valued planner argument, if present.
fn string_arg<'a>(config: &'a PlannerConfig, key: &str) -> Option<&'a str> {
    config.args.get(key).and_then(serde_yaml_ng::Value::as_str)
}

/// Every declared relationship name on a table, from both the generation
/// relationships and the portable schema's foreign keys.
fn relationship_names(table: &TableModel) -> Vec<String> {
    table
        .relationships
        .iter()
        .filter_map(|relationship| relationship.name.clone())
        .chain(
            table
                .schema
                .relationships
                .iter()
                .filter_map(|relationship| relationship.name.clone()),
        )
        .collect()
}

/// Every column that participates in a declared foreign key, from both the
/// generation relationships and the portable schema.
fn foreign_key_columns(table: &TableModel) -> BTreeSet<String> {
    table
        .relationships
        .iter()
        .flat_map(|relationship| relationship.columns.iter().cloned())
        .chain(
            table
                .schema
                .relationships
                .iter()
                .flat_map(|relationship| relationship.columns.iter().cloned()),
        )
        .collect()
}

/// The name of the first relationship that covers `column`, if any.
fn relationship_of(table: &TableModel, column: &str) -> Option<String> {
    table
        .relationships
        .iter()
        .find(|relationship| relationship.columns.iter().any(|c| c == column))
        .and_then(|relationship| relationship.name.clone())
        .or_else(|| {
            table
                .schema
                .relationships
                .iter()
                .find(|relationship| relationship.columns.iter().any(|c| c == column))
                .and_then(|relationship| relationship.name.clone())
        })
}

/// The concrete [`SeedRoot`] a resolved seed compiles operators against.
fn seed_root_of(seed: &ResolvedTableSeed) -> SeedRoot {
    match seed {
        ResolvedTableSeed::Inherited(root)
        | ResolvedTableSeed::Fixed(root)
        | ResolvedTableSeed::Random(root) => *root,
    }
}

/// A node in a table's column/planner dependency graph.
#[derive(Clone, PartialEq, Eq)]
enum DepNode {
    Column(String),
    Planner(usize),
}

/// Build the read/write dependency graph and report each strongly connected
/// component that forms a real cycle as `GEN-COLUMN-CYCLE` — unless a single
/// registered planner owns every column in it (the planner resolves those
/// values jointly).
fn report_dependency_cycles(
    table_name: &str,
    table: &TableModel,
    columns: &[PlannedColumn],
    planners: &[PlannerInfo],
    bag: &mut DiagnosticBag,
) {
    let mut nodes: Vec<DepNode> = columns
        .iter()
        .map(|column| DepNode::Column(column.schema.name.clone()))
        .collect();
    nodes.extend((0..planners.len()).map(DepNode::Planner));

    let index_of = |node: &DepNode| nodes.iter().position(|candidate| candidate == node);
    let mut edges: Vec<Vec<usize>> = vec![Vec::new(); nodes.len()];
    let add_edge = |from: &DepNode, to: &DepNode, edges: &mut Vec<Vec<usize>>| {
        if let (Some(from), Some(to)) = (index_of(from), index_of(to)) {
            edges[from].push(to);
        }
    };

    // A generator that reads sibling columns depends on them: read -> column.
    for planned in columns {
        if matches!(planned.owner, ColumnOwner::Generator { .. }) {
            for read in generator_reads(table, &planned.schema.name) {
                add_edge(
                    &DepNode::Column(read),
                    &DepNode::Column(planned.schema.name.clone()),
                    &mut edges,
                );
            }
        }
    }
    // A planner depends on the columns it reads and produces the ones it
    // writes: read -> planner -> write.
    for (index, planner) in planners.iter().enumerate() {
        for read in &planner.reads {
            add_edge(
                &DepNode::Column(read.clone()),
                &DepNode::Planner(index),
                &mut edges,
            );
        }
        for write in &planner.writes {
            add_edge(
                &DepNode::Planner(index),
                &DepNode::Column(write.clone()),
                &mut edges,
            );
        }
    }

    for component in strongly_connected_components(&edges) {
        let self_loop = component.len() == 1 && edges[component[0]].contains(&component[0]);
        if component.len() <= 1 && !self_loop {
            continue;
        }
        let cycle_columns: Vec<String> = component
            .iter()
            .filter_map(|&node| match &nodes[node] {
                DepNode::Column(name) => Some(name.clone()),
                DepNode::Planner(_) => None,
            })
            .collect();
        if owned_by_single_planner(&cycle_columns, columns) {
            continue;
        }
        bag.error(
            crate::diagnostic::codes::COLUMN_CYCLE.code,
            format!("tables.{table_name}.columns"),
            format!(
                "columns on table `{table_name}` form a read/write dependency cycle: {}",
                cycle_columns.join(", ")
            ),
        );
    }
}

/// The order in which the engine evaluates generator-owned columns within a
/// row: a topological sort of the column read graph (an edge `source -> reader`
/// for every sibling a generator reads), tie-broken by schema position so an
/// acyclic model with no cross-column reads keeps its declared order exactly.
///
/// Non-generator columns carry no read constraints — the engine fills them
/// before the generator pass — so they float to their schema position. Any
/// columns trapped in a cycle (which [`report_dependency_cycles`] already
/// rejects, save the single-planner-owned exception) are appended in schema
/// order, so the result is always a total permutation of `0..columns.len()`.
fn column_eval_order(table: &TableModel, columns: &[PlannedColumn]) -> Vec<usize> {
    let n = columns.len();
    let index_of: BTreeMap<&str, usize> = columns
        .iter()
        .enumerate()
        .map(|(index, column)| (column.schema.name.as_str(), index))
        .collect();

    let mut successors: Vec<Vec<usize>> = vec![Vec::new(); n];
    let mut in_degree = vec![0usize; n];
    for (reader, column) in columns.iter().enumerate() {
        if !matches!(column.owner, ColumnOwner::Generator { .. }) {
            continue;
        }
        for read in generator_reads(table, &column.schema.name) {
            if let Some(&source) = index_of.get(read.as_str()) {
                if source != reader {
                    successors[source].push(reader);
                    in_degree[reader] += 1;
                }
            }
        }
    }

    // Kahn's algorithm; the min-heap yields the lowest ready index first, so
    // independent columns emerge in schema order.
    let mut ready: BinaryHeap<Reverse<usize>> = (0..n)
        .filter(|&index| in_degree[index] == 0)
        .map(Reverse)
        .collect();
    let mut order = Vec::with_capacity(n);
    while let Some(Reverse(node)) = ready.pop() {
        order.push(node);
        for &next in &successors[node] {
            in_degree[next] -= 1;
            if in_degree[next] == 0 {
                ready.push(Reverse(next));
            }
        }
    }

    // Cyclic remnants (already a reported error) get a deterministic slot so the
    // permutation stays total and the engine never panics on a missing index.
    if order.len() < n {
        let mut placed = vec![false; n];
        for &node in &order {
            placed[node] = true;
        }
        for (node, &is_placed) in placed.iter().enumerate() {
            if !is_placed {
                order.push(node);
            }
        }
    }
    order
}

/// The sibling columns a compiled column generator reads on the same row. This
/// is the single source of truth for column read edges, feeding both cycle
/// detection ([`report_dependency_cycles`]) and the row-evaluation topological
/// order ([`column_eval_order`]).
///
/// Reads come from two places: an explicit `reads:` sequence (any generator may
/// declare one, meaningful when the descriptor declares `reads: Configured`),
/// plus the implicit sibling reads baked into specific built-in kinds — `copy`,
/// `slug`, `before`, and `after` read their `source`, and `template` reads each
/// `{ field: ... }`. These built-ins have no aliases, so matching the primary
/// kind is exact.
/// Duplicate names are collapsed so a repeated edge cannot skew the toposort's
/// in-degree accounting.
fn generator_reads(table: &TableModel, column: &str) -> Vec<String> {
    let Some(config) = table
        .columns
        .get(column)
        .and_then(|rule| rule.generator.as_ref())
    else {
        return Vec::new();
    };

    let mut reads = Vec::new();
    let mut push = |name: &str| {
        let name = name.to_string();
        if !reads.contains(&name) {
            reads.push(name);
        }
    };

    if let Some(serde_yaml_ng::Value::Sequence(items)) = config.args.get("reads") {
        for name in items.iter().filter_map(serde_yaml_ng::Value::as_str) {
            push(name);
        }
    }

    match config.kind.as_str() {
        "copy" | "slug" | "before" | "after" => {
            if let Some(source) = config
                .args
                .get("source")
                .and_then(serde_yaml_ng::Value::as_str)
            {
                push(source);
            }
        }
        "template" => {
            if let Some(serde_yaml_ng::Value::Sequence(parts)) = config.args.get("parts") {
                for part in parts {
                    if let Some(field) = part.get("field").and_then(serde_yaml_ng::Value::as_str) {
                        push(field);
                    }
                }
            }
        }
        _ => {}
    }

    reads
}

/// Whether every column in a cycle is owned by one and the same planner.
fn owned_by_single_planner(cycle_columns: &[String], columns: &[PlannedColumn]) -> bool {
    let mut planner: Option<usize> = None;
    for name in cycle_columns {
        let owner = columns
            .iter()
            .find(|planned| &planned.schema.name == name)
            .map(|planned| &planned.owner);
        match owner {
            Some(ColumnOwner::Planner { planner_index, .. }) => {
                if planner.is_some_and(|existing| existing != *planner_index) {
                    return false;
                }
                planner = Some(*planner_index);
            }
            _ => return false,
        }
    }
    planner.is_some()
}

/// Tarjan's strongly connected components over an adjacency list. Returns one
/// vector of node indices per component.
fn strongly_connected_components(edges: &[Vec<usize>]) -> Vec<Vec<usize>> {
    struct State<'a> {
        edges: &'a [Vec<usize>],
        index: usize,
        indices: Vec<Option<usize>>,
        low: Vec<usize>,
        on_stack: Vec<bool>,
        stack: Vec<usize>,
        components: Vec<Vec<usize>>,
    }

    fn connect(state: &mut State, v: usize) {
        state.indices[v] = Some(state.index);
        state.low[v] = state.index;
        state.index += 1;
        state.stack.push(v);
        state.on_stack[v] = true;

        for &w in &state.edges[v] {
            match state.indices[w] {
                None => {
                    connect(state, w);
                    state.low[v] = state.low[v].min(state.low[w]);
                }
                Some(w_index) if state.on_stack[w] => {
                    state.low[v] = state.low[v].min(w_index);
                }
                Some(_) => {}
            }
        }

        if state.low[v] == state.indices[v].expect("v was assigned an index") {
            let mut component = Vec::new();
            while let Some(w) = state.stack.pop() {
                state.on_stack[w] = false;
                component.push(w);
                if w == v {
                    break;
                }
            }
            state.components.push(component);
        }
    }

    let n = edges.len();
    let mut state = State {
        edges,
        index: 0,
        indices: vec![None; n],
        low: vec![0; n],
        on_stack: vec![false; n],
        stack: Vec::new(),
        components: Vec::new(),
    };
    for v in 0..n {
        if state.indices[v].is_none() {
            connect(&mut state, v);
        }
    }
    state.components
}

// --- Cross-table family (commerce.order_family) -----------------------------

/// The child-facts a parent-scoped family planner cannot see on its own,
/// gathered by the compiler (which has the whole model) and injected into the
/// planner config, plus the child-column ownership the family planner asserts
/// across the table boundary.
#[derive(Default)]
struct FamilyContext {
    /// `(parent_table, planner_index)` → injected child facts.
    facts: BTreeMap<(String, usize), serde_yaml_ng::Value>,
    /// `(child_table, child_column)` → the family planner that owns it.
    external_owners: BTreeMap<(String, String), ExternalChildOwner>,
    /// Every discovered parent→child family membership.
    families: Vec<FamilyMembership>,
}

/// A child column owned by a family planner declared on another table.
struct ExternalChildOwner {
    planner_kind: String,
}

/// One discovered parent/child family, used to emit the [`ExecutionPhase::Family`].
struct FamilyMembership {
    parent: String,
    child: String,
}

/// Whether a planner participates in the cross-table family child-spool pre-pass:
/// its descriptor advertises the `cross_table` capability AND it declares a
/// `children:` table (it produces that child's rows alongside its own). This is
/// driven off the registered capability rather than any specific planner `kind`,
/// so a new family planner joins the pre-pass by setting `cross_table` and
/// declaring `children`. Cross-table planners that only *reference* other tables
/// (junction/tenant/polymorphic FK-side planners) set `cross_table` too but do
/// not declare `children`, so they receive parent-key facts in
/// [`ModelCompiler::inject_relation_facts`] instead of spooling children here.
fn is_family_producer(registry: &ExtensionRegistry, config: &PlannerConfig) -> bool {
    registry
        .planner(&config.kind)
        .is_some_and(|factory| factory.descriptor().cross_table)
        && config.args.contains_key("children")
}

impl ModelCompiler {
    /// Scan the model for cross-table family planners, validate the child-side
    /// facts each one cannot see (child existence and ownership conflicts on the
    /// child columns it claims), and gather the facts to inject plus the child
    /// column ownership the planner asserts. The parent-side and remaining
    /// child-side validation runs in the planner's own `compile`.
    ///
    /// Which planners take part is decided by the [`is_family_producer`]
    /// capability check, not a hardcoded `kind`.
    fn collect_family_facts(
        &self,
        model: &SyntheticModel,
        bag: &mut DiagnosticBag,
    ) -> FamilyContext {
        collect_family_facts(&self.registry, model, bag)
    }
}

fn collect_family_facts(
    registry: &ExtensionRegistry,
    model: &SyntheticModel,
    bag: &mut DiagnosticBag,
) -> FamilyContext {
    let mut ctx = FamilyContext::default();
    for (parent_name, table) in &model.tables {
        for (index, config) in table.planners.iter().enumerate() {
            if !is_family_producer(registry, config) {
                continue;
            }
            let child_name = config.args.get("children").and_then(|v| v.as_str());
            let child = child_name.and_then(|name| model.tables.get(name).map(|t| (name, t)));

            let mut facts = serde_yaml_ng::Mapping::new();
            facts.insert("child_found".into(), (child.is_some()).into());

            if let Some((child_name, child_model)) = child {
                let mut columns = serde_yaml_ng::Mapping::new();
                for column in &child_model.schema.columns {
                    columns.insert(
                        column.name.clone().into(),
                        column.source_type.clone().into(),
                    );
                }
                facts.insert(
                    "child_columns".into(),
                    serde_yaml_ng::Value::Mapping(columns),
                );

                if let RowsModel::RelationChildren { distribution, .. } = &child_model.rows {
                    let (mean, min, max) = distribution_bounds(distribution);
                    facts.insert("dist_kind".into(), distribution_kind(distribution).into());
                    facts.insert("dist_mean".into(), mean.into());
                    facts.insert("dist_min".into(), min.into());
                    facts.insert("dist_max".into(), max.into());
                }

                let rel_name = config.args.get("relationship").and_then(|v| v.as_str());
                let rel_on_child = rel_name.is_some_and(|name| {
                    child_relationship_references(child_model, name, parent_name)
                });
                facts.insert("rel_on_child".into(), rel_on_child.into());

                // Record ownership of every child column the planner maps, and
                // report a conflict with any competing generator on the child.
                if let Some(serde_yaml_ng::Value::Mapping(mapping)) =
                    config.args.get("child_columns")
                {
                    for column_name in mapping.values().filter_map(|v| v.as_str()) {
                        let exists = child_model
                            .schema
                            .columns
                            .iter()
                            .any(|column| column.name == column_name);
                        if !exists {
                            continue;
                        }
                        let has_generator = child_model
                            .columns
                            .get(column_name)
                            .is_some_and(|rule| rule.generator.is_some());
                        if has_generator {
                            bag.error(
                                crate::diagnostic::codes::COLUMN_OWNER_CONFLICT.code,
                                format!("tables.{child_name}.columns.{column_name}"),
                                format!(
                                    "column `{column_name}` on table `{child_name}` is produced by both its own generator and the `commerce.order_family` planner on table `{parent_name}`"
                                ),
                            );
                        }
                        ctx.external_owners.insert(
                            (child_name.to_string(), column_name.to_string()),
                            ExternalChildOwner {
                                planner_kind: config.kind.clone(),
                            },
                        );
                    }
                }

                if ctx.families.iter().any(|f| f.child == child_name) {
                    // A child produced by two family planners would be emitted
                    // twice (a Family phase per parent). Reject the ambiguity.
                    bag.error(
                        crate::diagnostic::codes::COLUMN_OWNER_CONFLICT.code,
                        format!("tables.{child_name}"),
                        format!(
                            "child table `{child_name}` is claimed as a family child by more than one parent; a family child must have a single producing parent"
                        ),
                    );
                } else {
                    ctx.families.push(FamilyMembership {
                        parent: parent_name.clone(),
                        child: child_name.to_string(),
                    });
                }
            }

            ctx.facts.insert(
                (parent_name.clone(), index),
                serde_yaml_ng::Value::Mapping(facts),
            );
        }
    }
    ctx
}

/// The dense integer key recipe `(start, step)` a parent column materializes as
/// — row `n`'s key is `start + n * step`. Mirrors the engine's
/// [`super::engine`] key-domain rules: a `sequence` generator carries its own
/// `start`/`step`, and a bare integer primary key (no generator, not
/// identity/generated) is the database sequence `1, 2, …`. Any other column
/// (a UUID, a text key, a non-key) has no dense integer recipe and returns
/// `None`, so an FK-side cross-table planner referencing it can reject the
/// incompatible key at compile time.
/// Parse a YAML value as an `i128`, matching the `sequence` generator's own
/// `parse_i128`: a Number (widening beyond i64 via f64), or a numeric String.
fn yaml_to_i128(value: &serde_yaml_ng::Value) -> Option<i128> {
    match value {
        serde_yaml_ng::Value::Number(n) => n
            .as_i64()
            .map(i128::from)
            .or_else(|| n.as_f64().map(|f| f as i128)),
        serde_yaml_ng::Value::String(s) => s.trim().parse::<i128>().ok(),
        _ => None,
    }
}

fn dense_key_recipe(table: &TableModel, column: &str) -> Option<(i128, i128)> {
    if let Some(rule) = table.columns.get(column) {
        if let Some(generator) = &rule.generator {
            if generator.kind == "sequence" {
                // Parse with the same semantics the `sequence` generator itself
                // uses (accepting string- and float-form values), so the FK-side
                // recipe matches the keys the generator actually emits. Using
                // `as_i64` here returned None for e.g. `start: "1000"` and fell
                // back to 0, producing dangling foreign keys.
                let start = generator
                    .args
                    .get("start")
                    .and_then(yaml_to_i128)
                    .unwrap_or(0);
                let step = generator
                    .args
                    .get("step")
                    .and_then(yaml_to_i128)
                    .unwrap_or(1);
                return Some((start, step));
            }
            // Any other explicit generator is not a dense integer key.
            return None;
        }
    }
    let column = table.schema.columns.iter().find(|c| c.name == column)?;
    // A bare integer primary key OR an identity integer primary key is a
    // database sequence rendered as `1..=count` — the engine's FK key-domain
    // path (`build_key_domains`) treats both the same, so cross-table planners
    // must accept both as the dense recipe `(1, 1)` too. (A `generated`/computed
    // column has no such closed form.)
    if column.primary_key
        && !column.generated
        && matches!(
            column.family,
            SqlTypeFamily::Integer | SqlTypeFamily::BigInteger
        )
    {
        return Some((1, 1));
    }
    None
}

/// Build the `__relation_facts` payload injected into an FK-side cross-table
/// planner: for every relationship the child declares, the resolved parent
/// count and dense key recipe; and for every model table, its resolved count
/// and the dense recipe of each of its columns (so a polymorphic planner can
/// resolve a target table referenced only by name). Counts come from the
/// already-resolved parents, which precede the child in dependency order.
fn build_relation_facts(
    model: &SyntheticModel,
    table: &TableModel,
    resolved: &BTreeMap<String, u64>,
) -> serde_yaml_ng::Value {
    use serde_yaml_ng::{Mapping, Value};

    let recipe_map = |recipe: Option<(i128, i128)>| -> Mapping {
        let mut m = Mapping::new();
        match recipe {
            Some((start, step)) => {
                m.insert("dense".into(), true.into());
                m.insert("start".into(), (start as i64).into());
                m.insert("step".into(), (step as i64).into());
            }
            None => {
                m.insert("dense".into(), false.into());
            }
        }
        m
    };

    let mut relationships = Mapping::new();
    let generation = table.relationships.iter().map(|rel| {
        (
            rel.name.clone(),
            rel.references.table.clone(),
            rel.references.columns.clone(),
        )
    });
    let schema = table.schema.relationships.iter().map(|rel| {
        (
            rel.name.clone(),
            rel.referenced_table.clone(),
            rel.referenced_columns.clone(),
        )
    });
    for (name, parent_table, parent_columns) in generation.chain(schema) {
        let Some(name) = name else { continue };
        let parent_column = parent_columns.first().cloned().unwrap_or_default();
        let recipe = model
            .tables
            .get(&parent_table)
            .and_then(|parent| dense_key_recipe(parent, &parent_column));
        let mut entry = recipe_map(recipe);
        entry.insert("parent_table".into(), parent_table.clone().into());
        entry.insert("parent_column".into(), parent_column.into());
        entry.insert(
            "count".into(),
            resolved.get(&parent_table).copied().unwrap_or(0).into(),
        );
        relationships.insert(name.into(), Value::Mapping(entry));
    }

    let mut tables = Mapping::new();
    for (name, target) in &model.tables {
        let count = resolved.get(name).copied().unwrap_or(0);
        let mut keys = Mapping::new();
        for column in &target.schema.columns {
            if let Some(recipe) = dense_key_recipe(target, &column.name) {
                let mut key_entry = recipe_map(Some(recipe));
                // Carry the owning table's row count on each key entry so a
                // polymorphic target resolved by column name still knows its
                // domain size.
                key_entry.insert("count".into(), count.into());
                keys.insert(column.name.clone().into(), Value::Mapping(key_entry));
            }
        }
        let mut entry = Mapping::new();
        entry.insert("count".into(), count.into());
        entry.insert("keys".into(), Value::Mapping(keys));
        // The primary-key column: an explicit table-level PK, else a column
        // flagged `primary_key` (the common single-column-PK shape).
        let primary_key = target.schema.primary_key.first().cloned().or_else(|| {
            target
                .schema
                .columns
                .iter()
                .find(|column| column.primary_key)
                .map(|column| column.name.clone())
        });
        if let Some(primary_key) = primary_key {
            entry.insert("primary_key".into(), primary_key.into());
        }
        tables.insert(name.clone().into(), Value::Mapping(entry));
    }

    let mut root = Mapping::new();
    root.insert("relationships".into(), Value::Mapping(relationships));
    root.insert("tables".into(), Value::Mapping(tables));
    // The child's own resolved count (it is inserted into `resolved` before this
    // table is planned), so a junction planner can reject a row count that
    // exceeds the number of distinct parent pairs.
    root.insert(
        "self_count".into(),
        resolved
            .get(&table.schema.name)
            .copied()
            .unwrap_or(0)
            .into(),
    );
    Value::Mapping(root)
}

/// Whether `child` declares a relationship named `name` that references
/// `parent`, via either a generation relationship or a portable-schema foreign
/// key. A name that resolves to a relationship referencing a *different* table
/// (or is absent) does not count — the family FK must bind the child to its
/// parent.
fn child_relationship_references(child: &TableModel, name: &str, parent: &str) -> bool {
    let generation = child.relationships.iter().any(|relationship| {
        relationship.name.as_deref() == Some(name) && relationship.references.table == parent
    });
    let schema = child.schema.relationships.iter().any(|relationship| {
        relationship.name.as_deref() == Some(name) && relationship.referenced_table == parent
    });
    generation || schema
}

/// Build the execution phases: a family parent and its child collapse into one
/// [`ExecutionPhase::Family`] (the child's own `Table` phase is omitted, since it
/// is generated inside the family), and every other table stays a `Table` phase.
fn build_phases(
    order: &[String],
    family_ctx: &FamilyContext,
    budget_bytes: u64,
    bag: &mut DiagnosticBag,
) -> Vec<ExecutionPhase> {
    let ordered: BTreeSet<&str> = order.iter().map(String::as_str).collect();
    let child_tables: BTreeSet<&str> = family_ctx
        .families
        .iter()
        .map(|family| family.child.as_str())
        .collect();
    let mut phases = Vec::with_capacity(order.len());
    for name in order {
        if child_tables.contains(name.as_str()) {
            continue;
        }
        match family_ctx
            .families
            .iter()
            .find(|family| &family.parent == name)
        {
            // Only pair the parent with its child when the child is actually
            // generated; otherwise the family phase would name an ungenerated
            // table (and mis-route its spooled rows).
            Some(family) if ordered.contains(family.child.as_str()) => {
                phases.push(ExecutionPhase::Family(FamilyPhase {
                    name: name.clone(),
                    tables: vec![name.clone(), family.child.clone()],
                    budget_bytes,
                }));
            }
            Some(family) => {
                bag.warning(
                    crate::diagnostic::codes::DETACHED_DEPENDENCY.code,
                    format!("tables.{name}.planners"),
                    format!(
                        "family child `{}` of `{name}` was excluded; generating `{name}` without its correlated child rows",
                        family.child
                    ),
                );
                phases.push(ExecutionPhase::Table(name.clone()));
            }
            None => phases.push(ExecutionPhase::Table(name.clone())),
        }
    }
    phases
}

/// Capture a declared relationship's referential shape and value-assignment
/// distribution. The generation engine executes the per-row parent assignment.
fn compile_relationship(relationship: &RelationshipModel) -> CompiledRelationship {
    CompiledRelationship {
        name: relationship.name.clone(),
        columns: relationship.columns.clone(),
        parent_table: relationship.references.table.clone(),
        parent_columns: relationship.references.columns.clone(),
        distribution: parse_distribution(relationship.distribution.as_deref()),
        null_permille: 0,
    }
}

/// Parse a relationship's assignment distribution name. An absent or
/// unrecognized name falls back to [`RelationshipDistribution::Uniform`].
fn parse_distribution(name: Option<&str>) -> RelationshipDistribution {
    match name {
        Some("sequential") => RelationshipDistribution::Sequential,
        Some("weighted") => RelationshipDistribution::Weighted,
        Some("observed") => RelationshipDistribution::Observed,
        _ => RelationshipDistribution::Uniform,
    }
}

/// Fold the arguments of any explicit `relation.foreign_key` /
/// `relation.composite_key` column generator into the matching relationship, so
/// an inferred FK (owner `Relationship`) and an explicit FK generator (owner
/// `Generator`) converge on the same compiled relationship the engine executes.
/// Recognizes `distribution` (a name) and `null_rate` (a `0.0..=1.0` fraction).
/// An FK generator whose column no relationship covers is a
/// `GEN-FOREIGN-KEY-UNRESOLVED` error: it would otherwise render `DEFAULT`
/// silently at run time.
fn fold_foreign_key_generators(
    table_name: &str,
    table: &TableModel,
    relationships: &mut [CompiledRelationship],
    bag: &mut DiagnosticBag,
) {
    for (column, rule) in &table.columns {
        let Some(generator) = &rule.generator else {
            continue;
        };
        if generator.kind != "relation.foreign_key" && generator.kind != "relation.composite_key" {
            continue;
        }
        let Some(relationship) = relationships
            .iter_mut()
            .find(|relationship| relationship.columns.iter().any(|c| c == column))
        else {
            bag.error(
                crate::diagnostic::codes::FOREIGN_KEY_UNRESOLVED.code,
                format!("tables.{table_name}.columns.{column}.generator"),
                format!(
                    "column `{column}` on table `{table_name}` uses generator `{}` but no relationship declares it as a foreign key; declare a `relationships:` entry covering it",
                    generator.kind
                ),
            );
            continue;
        };
        if let Some(name) = generator.args.get("distribution").and_then(|v| v.as_str()) {
            relationship.distribution = parse_distribution(Some(name));
        }
        if let Some(rate) = generator.args.get("null_rate").and_then(|v| v.as_f64()) {
            relationship.null_permille = (rate.clamp(0.0, 1.0) * 1000.0).round() as u16;
        }
    }
}

/// Resolve a table's seed against the run's root seed.
fn resolve_seed(seed: &TableSeed, root_seed: u64) -> ResolvedTableSeed {
    match seed {
        TableSeed::Inherit => ResolvedTableSeed::Inherited(SeedRoot::new(root_seed)),
        TableSeed::Random => ResolvedTableSeed::Random(SeedRoot::new(rand::random())),
        TableSeed::Fixed(seed) => ResolvedTableSeed::Fixed(SeedRoot::new(*seed)),
    }
}

/// Carry the model's `output:` block into the plan, parsing the render dialect.
fn compile_output(model: &SyntheticModel) -> CompiledOutput {
    CompiledOutput {
        dialect: model.output.dialect.as_ref().and_then(|d| d.parse().ok()),
        mode: model.output.mode,
        inserts: model.output.inserts,
        batch_size: model.output.batch_size,
    }
}

/// Compile a list of glob strings once, reporting `GEN-INVALID-GLOB` for any
/// that fail to parse.
fn compile_globs(patterns: &[String], bag: &mut DiagnosticBag) -> Vec<Pattern> {
    patterns
        .iter()
        .filter_map(|pattern| match Pattern::new(pattern) {
            Ok(compiled) => Some(compiled),
            Err(error) => {
                bag.error(
                    crate::diagnostic::codes::INVALID_GLOB.code,
                    "options",
                    format!("invalid table glob `{pattern}`: {error}"),
                );
                None
            }
        })
        .collect()
}