rivet-cli 0.16.2

Rivet: PostgreSQL/MySQL/SQL Server → Parquet/CSV (local, S3, GCS, Azure). Crate name rivet-cli; binary rivet.
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
mod analysis;
pub(crate) mod cursor_expr;
mod doctor;
mod mssql;
mod mysql;
mod postgres;
mod schema_error;
pub mod type_report;

pub(crate) use analysis::chunk_sparsity_from_counts;
// Re-exported so the plan layer's strategy explainer can ground its "≥ threshold"
// narrative on the same constant `check`/`init` use, not a hard-coded copy.
pub(crate) use analysis::SMALL_TABLE_ROW_THRESHOLD;
#[cfg(test)]
use analysis::{
    build_suggestion, check_connection_limit, check_dense_surrogate_cost,
    check_parallel_memory_risk, check_sparse_range, compute_verdict, derive_strategy,
    recommend_parallelism, recommend_profile,
};
#[allow(unused_imports)]
pub use doctor::doctor;
// Reused at the run-time connect seam (src/pipeline/single.rs) so a failed
// `rivet run` carries the same category + remediation hint `rivet doctor` gives.
pub(crate) use doctor::{categorize_source_error, source_error_hint};
#[cfg(test)]
use postgres::{extract_scan_type, parse_pg_row_estimate};

use serde::Serialize;

use crate::config::{Config, ExportConfig, SourceType};
use crate::error::Result;
use crate::types::policy::TypePolicy;
use crate::types::target::{ExportTarget, TargetStatus};

/// Serializes lowercase ("efficient"/"acceptable"/"degraded"/"unsafe") so
/// `rivet check --json` consumers (CI gates, orchestrators) match on a stable,
/// case-insensitive token rather than the SHOUTING `Display` form used in the
/// human-readable table.
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum HealthVerdict {
    Efficient,
    Acceptable,
    Degraded,
    Unsafe,
}

impl std::fmt::Display for HealthVerdict {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Efficient => write!(f, "EFFICIENT"),
            Self::Acceptable => write!(f, "ACCEPTABLE"),
            Self::Degraded => write!(f, "DEGRADED"),
            Self::Unsafe => write!(f, "UNSAFE"),
        }
    }
}

pub(crate) struct ExportDiagnostic {
    pub export_name: String,
    pub strategy: String,
    pub mode: String,
    pub cursor_column: Option<String>,
    pub row_estimate: Option<i64>,
    /// Average bytes per row from catalog/plan stats (PG EXPLAIN `width`,
    /// MSSQL `dm_db_partition_stats` pages/row). `None` when unavailable
    /// (e.g. MySQL, with no trustworthy scan-free estimate). Feeds the
    /// oversized-chunk warning and is shown as the `Row width` line.
    pub avg_row_bytes: Option<i64>,
    pub cursor_min: Option<String>,
    pub cursor_max: Option<String>,
    pub scan_type: Option<String>,
    pub uses_index: bool,
    pub verdict: HealthVerdict,
    pub recommended_profile: &'static str,
    pub recommended_parallel: (u32, &'static str),
    pub warnings: Vec<analysis::Warning>,
    pub suggestion: Option<String>,
}

// Hand-rolled `Serialize` (rather than `#[derive]`) so the JSON shape stays
// fully under our control without touching the three engine construction sites:
//   - `recommended_parallel` (a raw `(u32, &str)`) becomes a self-describing
//     `{ "level": N, "reason": "…" }` object instead of a positional 2-array;
//   - a derived `capabilities` object ({uses_index, has_cursor, can_parallel})
//     is computed from the sibling fields at serialization time — no stored
//     field, no extra probe;
//   - `None` optionals are skipped to keep the object lean for CI consumers.
// `HealthVerdict` rides its own `#[derive(Serialize)]` (lowercase tokens).
impl Serialize for ExportDiagnostic {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeMap;

        #[derive(Serialize)]
        struct RecommendedParallel {
            level: u32,
            reason: &'static str,
        }
        #[derive(Serialize)]
        struct Capabilities {
            uses_index: bool,
            has_cursor: bool,
            can_parallel: bool,
        }

        let mut map = serializer.serialize_map(None)?;
        map.serialize_entry("export_name", &self.export_name)?;
        map.serialize_entry("strategy", &self.strategy)?;
        map.serialize_entry("mode", &self.mode)?;
        if let Some(v) = &self.cursor_column {
            map.serialize_entry("cursor_column", v)?;
        }
        if let Some(v) = &self.row_estimate {
            map.serialize_entry("row_estimate", v)?;
        }
        if let Some(v) = &self.avg_row_bytes {
            map.serialize_entry("avg_row_bytes", v)?;
        }
        if let Some(v) = &self.cursor_min {
            map.serialize_entry("cursor_min", v)?;
        }
        if let Some(v) = &self.cursor_max {
            map.serialize_entry("cursor_max", v)?;
        }
        if let Some(v) = &self.scan_type {
            map.serialize_entry("scan_type", v)?;
        }
        map.serialize_entry("uses_index", &self.uses_index)?;
        map.serialize_entry("verdict", &self.verdict)?;
        map.serialize_entry("recommended_profile", &self.recommended_profile)?;
        map.serialize_entry(
            "recommended_parallel",
            &RecommendedParallel {
                level: self.recommended_parallel.0,
                reason: self.recommended_parallel.1,
            },
        )?;
        map.serialize_entry("warnings", &self.warnings)?;
        if let Some(v) = &self.suggestion {
            map.serialize_entry("suggestion", v)?;
        }
        map.serialize_entry(
            "capabilities",
            &Capabilities {
                uses_index: self.uses_index,
                has_cursor: self.cursor_column.is_some(),
                can_parallel: self.recommended_parallel.0 > 1,
            },
        )?;
        map.end()
    }
}

/// Return the diagnostic for a single export without printing anything.
///
/// Used by `rivet plan` to capture preflight data into a `PlanArtifact`.
pub(crate) fn get_export_diagnostic(
    config: &Config,
    export: &ExportConfig,
) -> Result<ExportDiagnostic> {
    let url = config.source.resolve_url()?;
    let tls = config.source.tls.as_ref();
    crate::source::warn_if_tls_disabled(&config.source);
    match config.source.source_type {
        SourceType::Postgres => postgres::diagnose_export_pg(&url, tls, export),
        SourceType::Mysql => mysql::diagnose_export_mysql(&url, tls, export),
        SourceType::Mssql => mssql::diagnose_export_mssql(&url, tls, export),
    }
}

/// Dedup identity for a destination, shared by `check`'s credential probe
/// and `doctor`'s write probe. Must include every field that changes where
/// a probe lands — notably `path`, so two local destinations with different
/// paths are probed separately. Keeping one helper prevents the two call
/// sites from drifting apart (doctor's inline copy once omitted `path` and
/// silently skipped the second local destination).
fn destination_identity(d: &crate::config::DestinationConfig) -> String {
    format!(
        "{:?}:{}:{}:{}",
        d.destination_type,
        d.bucket.as_deref().unwrap_or("-"),
        d.endpoint.as_deref().unwrap_or("-"),
        d.path.as_deref().unwrap_or("-"),
    )
}

/// One-line note for the "fail ✗ but rc 0" case: a column rendered `fail ✗`
/// for `--target` does NOT gate the exit code unless `--strict` is also passed
/// (that is the gate by design). Without this note an operator or CI reading
/// the glyph alone would wrongly assume a non-zero exit. Pure so the exact text
/// is unit-tested.
fn target_fail_note(n: usize, target_label: &str) -> String {
    let col = if n == 1 { "column" } else { "columns" };
    format!(
        "Note: {n} {col} FAIL {target_label} compatibility; exit code is gated only with --strict (currently exit 0)"
    )
}

/// Build one [`ExportDiagnostic`] per export via `diagnose`, collecting them (or
/// short-circuiting on the first error). Single-sources the connect → loop →
/// return contract every engine's `check_*` shares — only the per-export
/// `diagnose` call differs — so the deferred print-vs-collect decision lives in
/// one place rather than triplicated across postgres / mysql / mssql.
pub(super) fn collect_diagnostics<F>(
    exports: &[&ExportConfig],
    mut diagnose: F,
) -> Result<Vec<ExportDiagnostic>>
where
    F: FnMut(&ExportConfig) -> Result<ExportDiagnostic>,
{
    exports.iter().map(|&e| diagnose(e)).collect()
}

pub fn check(
    config_path: &str,
    export_name: Option<&str>,
    params: Option<&std::collections::HashMap<String, String>>,
    show_type_report: bool,
    strict: bool,
    json_output: bool,
    target: Option<ExportTarget>,
) -> Result<()> {
    let config = Config::load_with_params(config_path, params)?;

    let exports: Vec<&ExportConfig> = if let Some(name) = export_name {
        let e = config
            .exports
            .iter()
            .find(|e| e.name == name)
            .ok_or_else(|| anyhow::anyhow!("export '{}' not found in config", name))?;
        vec![e]
    } else {
        config.exports.iter().collect()
    };

    let url = config.source.resolve_url()?;
    let tls = config.source.tls.as_ref();
    // Surface the plaintext-transport warning at preflight time too —
    // operators should hear it from `rivet check` before they wait
    // through a full `rivet run` to learn the same thing. `Once` inside
    // the helper keeps emission to one line per process even when both
    // `check` and `run` flow through it.
    crate::source::warn_if_tls_disabled(&config.source);
    // Each engine connects once and returns one diagnostic per export without
    // printing. Rendering is decided here: TEXT (the per-export table) for the
    // default human path, or — under `--json` — the diagnostic is merged into
    // each export's type-report JSON object below (see the `if show_type_report`
    // block). `get_export_diagnostic` already proved the diag is computable
    // without printing; this is the multi-export variant of that path.
    let diagnostics: Vec<ExportDiagnostic> = match config.source.source_type {
        SourceType::Postgres => postgres::check_postgres(&url, tls, &exports)?,
        SourceType::Mysql => mysql::check_mysql(&url, tls, &exports)?,
        SourceType::Mssql => mssql::check_mssql(&url, tls, &exports)?,
    };
    if !json_output {
        for diag in &diagnostics {
            print_diagnostic(diag);
        }
    } else if !show_type_report {
        // `--json` WITHOUT a type report (the CLI forces `show_type_report` on
        // under `--json`, so this only fires if `check` is called directly with
        // `json_output=true, show_type_report=false`): there is no per-export
        // type-report object to nest the diagnostic into, so emit the diagnostic
        // alone — still NDJSON, one object per export per line. Keeps the
        // verdict from being silently dropped regardless of caller.
        for diag in &diagnostics {
            println!("{}", serde_json::to_string(diag)?);
        }
    }
    // Under `--json` WITH a type report, the diagnostics are emitted nested
    // inside each export's type-report object (the `show_type_report` block)
    // rather than as a standalone array — see the design note there. Built only
    // on the `--json` path (empty otherwise) since the TEXT path printed above.
    let diag_by_export: std::collections::HashMap<&str, &ExportDiagnostic> = if json_output {
        diagnostics
            .iter()
            .map(|d| (d.export_name.as_str(), d))
            .collect()
    } else {
        std::collections::HashMap::new()
    };

    // Destination credential-resolution preflight.  Until 0.7.6 `check` only
    // probed the source: a config with `AWS_ACCESS_KEY_ID` unset would pass
    // `rivet check` (rc=0) and then explode on `run`, while `rivet doctor`
    // caught it.  We don't issue a write-probe here (that is `doctor`'s job
    // and has side effects) — but we *do* call `create_destination`, which
    // resolves env vars / credentials_file existence at construction time.
    // Each unique destination is probed once per `check` to keep multi-export
    // configs cheap.
    let mut seen_destinations: std::collections::HashSet<String> = std::collections::HashSet::new();
    for export in &exports {
        let dest_key = destination_identity(&export.destination);
        if !seen_destinations.insert(dest_key) {
            continue;
        }
        let expanded = crate::plan::build::expand_destination_templates(
            export.destination.clone(),
            &export.name,
        );
        crate::destination::create_destination(&expanded).map_err(|e| {
            anyhow::anyhow!(
                "export '{}': destination preflight failed: {:#}",
                export.name,
                e
            )
        })?;
    }

    // Whether the check ends clean (no strict failure, no target-fail column).
    // Stays true for the default `rivet check` (no type report), so the "Next:
    // rivet run" pointer still fires.
    let mut clean = true;

    if show_type_report {
        let policy = if strict {
            TypePolicy::strict()
        } else {
            TypePolicy::warn_only()
        };

        let mut any_fatal = false;
        // Count hard target-FAIL columns (and remember which target) so that —
        // when --strict was NOT passed and the exit code is therefore 0 — we can
        // print a note. The "fail ✗" glyph in the table implies a hard failure,
        // but exit is gated only by --strict; without this note an operator or CI
        // reading the glyph alone would be misled into thinking rc != 0.
        let mut target_fail_cols = 0usize;
        let mut target_fail_label: Option<&'static str> = None;
        for export in &exports {
            let column_overrides =
                crate::plan::parse_column_overrides_pub(&export.columns, &export.name)?;
            // CLI `--target` wins; otherwise fall back to the per-export
            // `target:` from the config (slice #2a). A declared-but-unknown
            // target is a loud error — never silently ignored.
            if let Some(t) = export.target.as_deref()
                && crate::types::target::ExportTarget::parse(t).is_none()
            {
                anyhow::bail!(
                    "export '{}': unknown target '{t}' (expected: {})",
                    export.name,
                    crate::types::target::ExportTarget::valid_target_names()
                );
            }
            let eff_target = target.or_else(|| {
                export
                    .target
                    .as_deref()
                    .and_then(crate::types::target::ExportTarget::parse)
            });
            let config_dir = std::path::Path::new(config_path)
                .parent()
                .unwrap_or_else(|| std::path::Path::new("."));
            match type_report::collect_report(
                &config,
                export,
                &column_overrides,
                &policy,
                eff_target,
                config_dir,
                params,
            ) {
                Ok(report) => {
                    if report.has_fatal() {
                        any_fatal = true;
                    }
                    if let Some(t) = eff_target
                        && report.has_target_fail()
                    {
                        any_fatal = true;
                        target_fail_cols += report
                            .columns
                            .iter()
                            .filter(|c| c.target_status == Some(TargetStatus::Fail))
                            .count();
                        target_fail_label.get_or_insert(t.label());
                    }
                    if json_output {
                        // `--json` + `--type-report` interaction (DESIGN):
                        // emit BOTH, nested. Each export gets ONE JSON object
                        // (NDJSON, one per line, unchanged) keeping the
                        // top-level type-report keys (`export`/`columns`/
                        // `violations`) so existing consumers and the
                        // `check_json_flag_outputs_type_report_as_json` test
                        // stay green — and we attach the per-export DIAGNOSTIC
                        // verdict under a new `"diagnostic"` key. This is the
                        // least-surprising shape because `check --json` already
                        // emitted one type-report object per export; we simply
                        // enrich each with its verdict rather than printing a
                        // second, separate JSON value (which would break a
                        // single-`from_str` parse of stdout).
                        print_report_json_with_diagnostic(
                            &report,
                            diag_by_export.get(export.name.as_str()).copied(),
                        )?;
                    } else {
                        type_report::print_table(&report, eff_target);
                    }
                }
                Err(e) => {
                    log::warn!("type report for '{}' failed: {:#}", export.name, e);
                    // The type report could not be collected, but the diagnostic
                    // was. Under --json the verdict must still reach the
                    // consumer, so emit a diagnostic-only object (no `columns`/
                    // `violations`) rather than silently dropping this export.
                    if json_output
                        && let Some(diag) = diag_by_export.get(export.name.as_str()).copied()
                    {
                        println!("{}", serde_json::to_string(diag)?);
                    }
                }
            }
        }

        if strict && any_fatal {
            anyhow::bail!("strict mode: unsafe type mappings found (see report above)");
        } else if !strict && target_fail_cols > 0 && !json_output {
            // The table showed "fail ✗" but rc is 0 — say so explicitly. Skipped
            // under --json so NDJSON output stays one object per line.
            clean = false;
            println!();
            println!(
                "{}",
                target_fail_note(target_fail_cols, target_fail_label.unwrap_or("target"))
            );
        }
    }

    if !json_output {
        // Verdict legend — decode the EFFICIENT/ACCEPTABLE/DEGRADED/UNSAFE words
        // printed above and reassure that `check` is advisory: never blocks a run.
        println!();
        println!(
            "Verdicts: EFFICIENT > ACCEPTABLE > DEGRADED > UNSAFE — advisory only; the run is never blocked."
        );
        if clean {
            // Keep the ladder going to the final rung instead of ending cold.
            println!(
                "Looks good. Next: rivet run -c {config_path} --validate   # export, then verify row counts"
            );
        }
    }

    Ok(())
}

/// Emit one export's `--json` line: the type report (`export`/`columns`/
/// `violations`/…) with the per-export DIAGNOSTIC verdict attached under a new
/// `"diagnostic"` key. NDJSON — exactly one JSON object, terminated by a
/// newline, so a multi-export config prints one parseable object per line
/// (preserving the prior `check --json` type-report wire shape, now enriched).
///
/// `diag` is `None` only if the diagnostic could not be paired by export name
/// (it always can in practice); in that case the type report is emitted as
/// before, so the worst case is a missing `diagnostic` key, never a panic.
fn print_report_json_with_diagnostic(
    report: &type_report::ExportTypeReport,
    diag: Option<&ExportDiagnostic>,
) -> Result<()> {
    let mut value = serde_json::to_value(report)?;
    if let (Some(obj), Some(diag)) = (value.as_object_mut(), diag) {
        obj.insert("diagnostic".to_string(), serde_json::to_value(diag)?);
    }
    println!("{}", serde_json::to_string(&value)?);
    Ok(())
}

fn print_diagnostic(diag: &ExportDiagnostic) {
    println!();
    println!("Export: {}", diag.export_name);
    println!("  Strategy:     {}", diag.strategy);
    println!("  Mode:         {}", diag.mode);
    if let Some(est) = diag.row_estimate {
        if est >= 1_000_000 {
            println!("  Row estimate: ~{}M", est / 1_000_000);
        } else if est >= 1_000 {
            println!("  Row estimate: ~{}K", est / 1_000);
        } else {
            println!("  Row estimate: ~{}", est);
        }
    }
    if let Some(w) = diag.avg_row_bytes {
        println!("  Row width:    ~{} bytes", w);
    }
    if let (Some(min_v), Some(max_v)) = (&diag.cursor_min, &diag.cursor_max) {
        println!("  Cursor range: {} .. {}", min_v, max_v);
    }
    if let Some(col) = &diag.cursor_column {
        println!("  Cursor col:   {}", col);
    }
    // Plain-language access path instead of a raw EXPLAIN node dump
    // (`Result (cost=0.00..0.01 rows=1 width=36)`). Keyed off the authoritative
    // `uses_index` bool, gated on `scan_type.is_some()` so engines without an
    // EXPLAIN probe (MSSQL) stay silent.
    if diag.scan_type.is_some() {
        let access = if diag.uses_index {
            "index scan (the cursor/chunk column is indexed)"
        } else {
            "full table scan (no index on the read path)"
        };
        println!("  Access:       {access}");
    }
    println!("  Verdict:      {}", diag.verdict);
    println!(
        "  Recommended:  tuning.profile: {}",
        diag.recommended_profile
    );
    let (par_level, par_reason) = diag.recommended_parallel;
    if par_level > 1 {
        println!("  Recommended:  parallel: {} ({})", par_level, par_reason);
    } else {
        println!("  Parallelism:  {} ({})", par_level, par_reason);
    }
    for w in &diag.warnings {
        println!("  Warning:      [{}] {}", w.severity.label(), w.message);
    }
    if let Some(suggestion) = &diag.suggestion {
        println!("  Suggestion:   {}", suggestion);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{DestinationConfig, DestinationType, ExportConfig, ExportMode, FormatType};
    use doctor::{
        categorize_dest_error, categorize_source_error, destination_error_hint, source_error_hint,
    };
    use serde_json::Value;

    fn make_export(name: &str, mode: ExportMode, cursor: Option<&str>) -> ExportConfig {
        // Baseline from the canonical test fixture; override only the fields
        // these preflight tests vary (mode, cursor, CSV format, query, dest).
        ExportConfig {
            mode,
            cursor_column: cursor.map(|s| s.to_string()),
            query: Some("SELECT * FROM t".to_string()),
            format: FormatType::Csv,
            destination: DestinationConfig {
                destination_type: DestinationType::Local,
                path: Some("./out".to_string()),
                ..Default::default()
            },
            ..crate::config::sample_export(name)
        }
    }

    /// A representative incremental diagnostic for the `--json` serialization
    /// tests: a cursor column (so `has_cursor` is true), an index (so
    /// `uses_index` is true), a >1 parallel recommendation (so `can_parallel`
    /// is true), and a couple of warnings.
    fn sample_diagnostic(name: &str) -> ExportDiagnostic {
        ExportDiagnostic {
            export_name: name.to_string(),
            strategy: "incremental(updated_at)".to_string(),
            mode: "incremental".to_string(),
            cursor_column: Some("updated_at".to_string()),
            row_estimate: Some(1_234_567),
            avg_row_bytes: Some(96),
            cursor_min: Some("2020-01-01".to_string()),
            cursor_max: Some("2024-01-01".to_string()),
            scan_type: Some("Index Scan".to_string()),
            uses_index: true,
            verdict: HealthVerdict::Degraded,
            recommended_profile: "safe",
            recommended_parallel: (4, "large indexed dataset"),
            warnings: vec![
                analysis::Warning::new(analysis::Severity::Medium, "Sparse key range".to_string()),
                analysis::Warning::new(analysis::Severity::High, "memory risk".to_string()),
            ],
            suggestion: Some("create an index".to_string()),
        }
    }

    // ── `rivet check --json`: the per-export DIAGNOSTIC verdict as JSON ───────

    #[test]
    fn diagnostic_json_has_lowercase_verdict_and_core_fields() {
        let diag = sample_diagnostic("orders");
        let v: serde_json::Value =
            serde_json::from_str(&serde_json::to_string(&diag).unwrap()).unwrap();

        // Verdict serializes to a stable lowercase token (not the SHOUTING
        // Display form), so CI can match on it case-sensitively.
        assert_eq!(v["verdict"], "degraded", "got: {v}");
        assert_eq!(v["strategy"], "incremental(updated_at)", "got: {v}");
        assert_eq!(v["mode"], "incremental", "got: {v}");
        assert_eq!(v["recommended_profile"], "safe", "got: {v}");
        assert!(v["warnings"].is_array(), "warnings must be an array: {v}");
        assert_eq!(v["warnings"].as_array().unwrap().len(), 2, "got: {v}");
        // Each warning is a `{ severity, message }` object (per-warning severity).
        assert_eq!(v["warnings"][0]["severity"], "medium", "got: {v}");
        assert_eq!(v["warnings"][0]["message"], "Sparse key range", "got: {v}");
        assert_eq!(v["warnings"][1]["severity"], "high", "got: {v}");
        assert_eq!(v["export_name"], "orders", "got: {v}");
    }

    #[test]
    fn diagnostic_json_verdict_tokens_are_all_lowercase() {
        for (verdict, token) in [
            (HealthVerdict::Efficient, "efficient"),
            (HealthVerdict::Acceptable, "acceptable"),
            (HealthVerdict::Degraded, "degraded"),
            (HealthVerdict::Unsafe, "unsafe"),
        ] {
            let mut diag = sample_diagnostic("t");
            diag.verdict = verdict;
            let v: serde_json::Value =
                serde_json::from_str(&serde_json::to_string(&diag).unwrap()).unwrap();
            assert_eq!(v["verdict"], token, "verdict must lowercase to {token}");
        }
    }

    #[test]
    fn diagnostic_json_recommended_parallel_is_named_object_not_tuple() {
        // The raw `(u32, &str)` must NOT leak as a positional 2-array; consumers
        // read `recommended_parallel.level` / `.reason`.
        let diag = sample_diagnostic("t");
        let v: serde_json::Value =
            serde_json::from_str(&serde_json::to_string(&diag).unwrap()).unwrap();
        assert!(
            v["recommended_parallel"].is_object(),
            "recommended_parallel must be an object, got: {}",
            v["recommended_parallel"]
        );
        assert_eq!(v["recommended_parallel"]["level"], 4, "got: {v}");
        assert_eq!(
            v["recommended_parallel"]["reason"], "large indexed dataset",
            "got: {v}"
        );
    }

    #[test]
    fn diagnostic_json_capabilities_are_derived_from_fields() {
        let diag = sample_diagnostic("t");
        let v: serde_json::Value =
            serde_json::from_str(&serde_json::to_string(&diag).unwrap()).unwrap();
        let caps = &v["capabilities"];
        assert_eq!(caps["uses_index"], true, "got: {caps}");
        assert_eq!(caps["has_cursor"], true, "got: {caps}");
        assert_eq!(caps["can_parallel"], true, "got: {caps}");
    }

    #[test]
    fn diagnostic_json_capabilities_flip_with_fields() {
        // A non-cursor, no-index, single-worker diagnostic flips all three.
        let mut diag = sample_diagnostic("t");
        diag.cursor_column = None;
        diag.uses_index = false;
        diag.recommended_parallel = (1, "small dataset");
        let v: serde_json::Value =
            serde_json::from_str(&serde_json::to_string(&diag).unwrap()).unwrap();
        let caps = &v["capabilities"];
        assert_eq!(caps["uses_index"], false, "got: {caps}");
        assert_eq!(caps["has_cursor"], false, "got: {caps}");
        assert_eq!(caps["can_parallel"], false, "got: {caps}");
    }

    #[test]
    fn diagnostic_json_skips_none_optionals() {
        // `None` optionals are omitted (not `null`) to keep the object lean.
        let mut diag = sample_diagnostic("t");
        diag.suggestion = None;
        diag.scan_type = None;
        let v: serde_json::Value =
            serde_json::from_str(&serde_json::to_string(&diag).unwrap()).unwrap();
        let obj = v.as_object().unwrap();
        assert!(!obj.contains_key("suggestion"), "None must be omitted: {v}");
        assert!(!obj.contains_key("scan_type"), "None must be omitted: {v}");
    }

    /// Build the same `Value` `print_report_json_with_diagnostic` prints, so the
    /// merged shape is asserted without capturing stdout.
    fn merged_check_json(report: &type_report::ExportTypeReport, diag: &ExportDiagnostic) -> Value {
        let mut value = serde_json::to_value(report).unwrap();
        value.as_object_mut().unwrap().insert(
            "diagnostic".to_string(),
            serde_json::to_value(diag).unwrap(),
        );
        value
    }

    fn empty_report(export: &str) -> type_report::ExportTypeReport {
        type_report::ExportTypeReport {
            export: export.to_string(),
            columns: Vec::new(),
            violations: Vec::new(),
            target_failures: false,
            recovery_sql: None,
        }
    }

    #[test]
    fn check_json_merges_diagnostic_into_type_report_object() {
        // The `--json` + `--type-report` interaction: ONE object per export
        // keeping the type-report keys (`export`/`columns`/`violations`) — so
        // the existing `check_json_flag_outputs_type_report_as_json` contract
        // holds — PLUS a nested `diagnostic` carrying the verdict.
        let report = empty_report("orders");
        let diag = sample_diagnostic("orders");
        let v = merged_check_json(&report, &diag);

        // Pre-existing type-report keys still at the root.
        assert_eq!(v["export"], "orders", "got: {v}");
        assert!(v["columns"].is_array(), "columns at root: {v}");
        assert!(v["violations"].is_array(), "violations at root: {v}");

        // The diagnostic is nested and carries the verdict + advice.
        let d = &v["diagnostic"];
        assert_eq!(d["verdict"], "degraded", "got: {d}");
        assert_eq!(d["strategy"], "incremental(updated_at)", "got: {d}");
        assert_eq!(d["mode"], "incremental", "got: {d}");
        assert_eq!(d["recommended_profile"], "safe", "got: {d}");
        assert!(d["warnings"].is_array(), "warnings array: {d}");
        assert_eq!(d["capabilities"]["has_cursor"], true, "got: {d}");
    }

    #[test]
    fn check_json_object_is_a_single_parseable_line() {
        // NDJSON: serializing yields exactly one JSON value with no trailing
        // data, so `serde_json::from_str(line.trim())` (as the live test does)
        // parses it whole.
        let report = empty_report("orders");
        let diag = sample_diagnostic("orders");
        let line = serde_json::to_string(&merged_check_json(&report, &diag)).unwrap();
        assert!(!line.contains('\n'), "one object per line: {line}");
        let parsed: Value = serde_json::from_str(line.trim()).expect("must parse whole");
        assert_eq!(parsed["export"], "orders");
    }

    // ── L8: 'fail ✗' note when --target FAILs but --strict was not passed ─────
    // The glyph implies a hard failure; exit is gated only by --strict. The note
    // tells an operator/CI the exit is 0 so the glyph doesn't mislead.
    #[test]
    fn target_fail_note_names_count_target_and_strict_gate() {
        let note = target_fail_note(2, "bigquery");
        assert!(note.contains("2 columns FAIL"), "got: {note}");
        assert!(note.contains("bigquery"), "got: {note}");
        assert!(note.contains("--strict"), "got: {note}");
        assert!(note.contains("exit 0"), "got: {note}");
    }

    #[test]
    fn target_fail_note_singular_for_one_column() {
        let note = target_fail_note(1, "duckdb");
        assert!(note.contains("1 column FAIL"), "got: {note}");
        assert!(!note.contains("1 columns"), "should be singular: {note}");
    }

    #[test]
    fn verdict_small_indexed_with_cursor_is_efficient() {
        let v = compute_verdict(Some(500_000), true, true, None, 1);
        assert!(matches!(v, HealthVerdict::Efficient), "got: {v}");
    }

    #[test]
    fn verdict_large_indexed_with_cursor_is_acceptable() {
        let v = compute_verdict(Some(20_000_000), true, true, None, 1);
        assert!(matches!(v, HealthVerdict::Acceptable), "got: {v}");
    }

    #[test]
    fn verdict_no_index_no_cursor_is_degraded() {
        let v = compute_verdict(Some(500_000), false, false, None, 1);
        assert!(matches!(v, HealthVerdict::Degraded), "got: {v}");
    }

    #[test]
    fn verdict_huge_no_index_is_unsafe() {
        let v = compute_verdict(Some(100_000_000), false, false, None, 1);
        assert!(matches!(v, HealthVerdict::Unsafe), "got: {v}");
    }

    #[test]
    fn parse_pg_row_estimate_from_sort_plan() {
        let plan = "Sort  (cost=12345.67..12456.78 rows=1000455 width=50)\n  ->  Seq Scan on orders  (cost=0.00..8765.43 rows=1000455 width=50)";
        assert_eq!(parse_pg_row_estimate(plan), Some(1_000_455));
    }

    #[test]
    fn parse_pg_row_estimate_from_index_scan() {
        let plan =
            "Index Scan using idx_updated on orders  (cost=0.42..81676.36 rows=500000 width=50)";
        assert_eq!(parse_pg_row_estimate(plan), Some(500_000));
    }

    #[test]
    fn extract_scan_type_detects_seq_scan() {
        let plan = "Sort  (cost=...)\n  ->  Seq Scan on users  (cost=...)";
        let st = extract_scan_type(plan);
        assert!(st.contains("Seq Scan"), "expected Seq Scan, got: {st}");
    }

    #[test]
    fn extract_scan_type_detects_index_scan() {
        let plan = "Index Scan using users_pkey on users  (cost=0.42..123.45 rows=100 width=50)";
        let st = extract_scan_type(plan);
        assert!(st.contains("Index Scan"), "expected Index Scan, got: {st}");
    }

    #[test]
    fn suggestion_for_efficient_verdict_is_none() {
        let e = make_export("t", ExportMode::Full, None);
        let s = build_suggestion(&HealthVerdict::Efficient, Some(1000), true, &e);
        assert!(
            s.is_none(),
            "efficient verdict should produce no suggestion"
        );
    }

    #[test]
    fn suggestion_for_degraded_verdict_recommends_safe_profile() {
        let e = make_export("t", ExportMode::Full, None);
        let s = build_suggestion(&HealthVerdict::Degraded, Some(500_000), false, &e);
        let msg = s.expect("degraded verdict should produce a suggestion");
        assert!(
            msg.contains("safe"),
            "suggestion should recommend safe profile, got: {msg}"
        );
    }

    fn src_err(msg: &str) -> &'static str {
        categorize_source_error(&anyhow::anyhow!("{}", msg))
    }

    #[test]
    fn source_password_rejected_is_auth_error() {
        assert_eq!(
            src_err("password authentication failed for user \"rivet\""),
            "auth error"
        );
    }

    #[test]
    fn source_authentication_failed_is_auth_error() {
        assert_eq!(src_err("FATAL: authentication failed"), "auth error");
    }

    #[test]
    fn source_access_denied_is_auth_error() {
        assert_eq!(
            src_err("Access denied for user 'rivet'@'localhost'"),
            "auth error"
        );
    }

    #[test]
    fn source_connection_refused_is_connectivity() {
        assert_eq!(
            src_err("connection refused (os error 61)"),
            "connectivity error"
        );
    }

    #[test]
    fn source_timed_out_is_connectivity() {
        assert_eq!(src_err("connection timed out"), "connectivity error");
    }

    #[test]
    fn source_dns_translate_host_is_connectivity() {
        assert_eq!(
            src_err("could not translate host name \"db.bad\" to address"),
            "connectivity error"
        );
    }

    #[test]
    fn source_name_not_known_is_connectivity() {
        assert_eq!(src_err("Name or service not known"), "connectivity error");
    }

    #[test]
    fn source_unknown_error_is_generic() {
        assert_eq!(src_err("something totally unexpected"), "error");
    }

    fn dest_config(dtype: DestinationType) -> DestinationConfig {
        DestinationConfig {
            destination_type: dtype,
            bucket: Some("b".to_string()),
            ..Default::default()
        }
    }

    fn dest_err(msg: &str, dtype: DestinationType) -> &'static str {
        let cfg = dest_config(dtype);
        categorize_dest_error(&anyhow::anyhow!("{}", msg), &cfg)
    }

    fn local_dest(path: &str) -> DestinationConfig {
        DestinationConfig {
            destination_type: DestinationType::Local,
            path: Some(path.to_string()),
            ..Default::default()
        }
    }

    // Regression (doctor-dedup): doctor's inline dedup key omitted `path`,
    // so two local destinations with different paths collapsed to one entry
    // and the second was never write-probed. The shared identity must keep
    // them distinct.
    #[test]
    fn destination_identity_distinguishes_local_paths() {
        assert_ne!(
            destination_identity(&local_dest("/tmp/a")),
            destination_identity(&local_dest("/tmp/b")),
        );
    }

    #[test]
    fn destination_identity_collapses_identical_local_destinations() {
        assert_eq!(
            destination_identity(&local_dest("/tmp/a")),
            destination_identity(&local_dest("/tmp/a")),
        );
    }

    #[test]
    fn destination_identity_distinguishes_buckets() {
        let a = DestinationConfig {
            bucket: Some("bucket-a".to_string()),
            ..dest_config(DestinationType::S3)
        };
        let b = DestinationConfig {
            bucket: Some("bucket-b".to_string()),
            ..dest_config(DestinationType::S3)
        };
        assert_ne!(destination_identity(&a), destination_identity(&b));
    }

    // Same bucket name on different endpoints (e.g. AWS vs MinIO) is two
    // distinct destinations and must be probed separately.
    #[test]
    fn destination_identity_distinguishes_endpoints_for_same_bucket() {
        let aws = dest_config(DestinationType::S3);
        let minio = DestinationConfig {
            endpoint: Some("http://localhost:9000".to_string()),
            ..dest_config(DestinationType::S3)
        };
        assert_ne!(destination_identity(&aws), destination_identity(&minio));
    }

    #[test]
    fn dest_credential_loading_is_auth_error() {
        assert_eq!(
            dest_err(
                "loading credential to sign http request",
                DestinationType::Gcs
            ),
            "auth error"
        );
    }

    #[test]
    fn dest_permission_denied_is_auth_error() {
        assert_eq!(
            dest_err("permission denied on resource bucket", DestinationType::S3),
            "auth error"
        );
    }

    #[test]
    fn dest_forbidden_is_auth_error() {
        assert_eq!(
            dest_err("403 Forbidden", DestinationType::Gcs),
            "auth error"
        );
    }

    #[test]
    fn dest_unauthorized_is_auth_error() {
        assert_eq!(
            dest_err("401 Unauthorized", DestinationType::S3),
            "auth error"
        );
    }

    #[test]
    fn dest_invalid_grant_is_auth_error() {
        assert_eq!(
            dest_err(
                "invalid_grant: token has been revoked",
                DestinationType::Gcs
            ),
            "auth error"
        );
    }

    #[test]
    fn dest_nosuchbucket_s3_is_bucket_not_found() {
        assert_eq!(
            dest_err(
                "NoSuchBucket: the specified bucket does not exist",
                DestinationType::S3
            ),
            "bucket not found"
        );
    }

    #[test]
    fn dest_not_found_gcs_is_bucket_not_found() {
        assert_eq!(
            dest_err("bucket not found (404)", DestinationType::Gcs),
            "bucket not found"
        );
    }

    #[test]
    fn dest_not_found_local_is_path_not_found() {
        assert_eq!(
            dest_err("path not found: /tmp/missing", DestinationType::Local),
            "path not found"
        );
    }

    #[test]
    fn dest_connection_refused_is_connectivity() {
        assert_eq!(
            dest_err("connection refused to endpoint", DestinationType::S3),
            "connectivity error"
        );
    }

    #[test]
    fn dest_dns_error_is_connectivity() {
        assert_eq!(
            dest_err("dns error: failed to lookup address", DestinationType::S3),
            "connectivity error"
        );
    }

    #[test]
    fn dest_timed_out_is_connectivity() {
        assert_eq!(
            dest_err("request timed out after 30s", DestinationType::Gcs),
            "connectivity error"
        );
    }

    #[test]
    fn dest_unknown_error_is_generic() {
        assert_eq!(
            dest_err("something else entirely", DestinationType::S3),
            "error"
        );
    }

    #[test]
    fn strategy_full_scan() {
        let e = make_export("t", ExportMode::Full, None);
        assert_eq!(derive_strategy(&e), "full-scan");
    }

    #[test]
    fn strategy_full_parallel() {
        let mut e = make_export("t", ExportMode::Full, None);
        e.parallel = 4;
        assert_eq!(derive_strategy(&e), "full-parallel(4)");
    }

    #[test]
    fn strategy_incremental() {
        let e = make_export("t", ExportMode::Incremental, Some("updated_at"));
        assert_eq!(derive_strategy(&e), "incremental(updated_at)");
    }

    #[test]
    fn strategy_chunked() {
        let mut e = make_export("t", ExportMode::Chunked, None);
        e.chunk_column = Some("id".to_string());
        e.chunk_size = 50_000;
        assert_eq!(derive_strategy(&e), "chunked(id, size=50000)");
    }

    #[test]
    fn strategy_chunked_parallel() {
        let mut e = make_export("t", ExportMode::Chunked, None);
        e.chunk_column = Some("id".to_string());
        e.chunk_size = 50_000;
        e.parallel = 3;
        assert_eq!(derive_strategy(&e), "chunked-parallel(id, size=50000, p=3)");
    }

    #[test]
    fn strategy_time_window() {
        let mut e = make_export("t", ExportMode::TimeWindow, None);
        e.time_column = Some("created_at".to_string());
        e.days_window = Some(7);
        assert_eq!(derive_strategy(&e), "time-window(created_at, 7d)");
    }

    #[test]
    fn profile_small_indexed_is_fast() {
        let e = make_export("t", ExportMode::Full, None);
        assert_eq!(recommend_profile(Some(500_000), true, &e), "fast");
    }

    #[test]
    fn profile_medium_indexed_is_balanced() {
        let e = make_export("t", ExportMode::Full, None);
        assert_eq!(recommend_profile(Some(5_000_000), true, &e), "balanced");
    }

    #[test]
    fn profile_large_indexed_is_safe() {
        let e = make_export("t", ExportMode::Full, None);
        assert_eq!(recommend_profile(Some(50_000_000), true, &e), "safe");
    }

    #[test]
    fn profile_small_no_index_is_balanced() {
        let e = make_export("t", ExportMode::Full, None);
        assert_eq!(recommend_profile(Some(50_000), false, &e), "balanced");
    }

    #[test]
    fn profile_small_no_index_parallel_is_safe() {
        let mut e = make_export("t", ExportMode::Full, None);
        e.parallel = 4;
        assert_eq!(recommend_profile(Some(50_000), false, &e), "safe");
    }

    #[test]
    fn profile_medium_no_index_is_balanced() {
        let e = make_export("t", ExportMode::Full, None);
        assert_eq!(recommend_profile(Some(500_000), false, &e), "balanced");
    }

    #[test]
    fn profile_large_no_index_is_safe() {
        let e = make_export("t", ExportMode::Full, None);
        assert_eq!(recommend_profile(Some(5_000_000), false, &e), "safe");
    }

    #[test]
    fn sparse_range_warning_when_very_sparse() {
        let mut e = make_export("t", ExportMode::Chunked, None);
        e.chunk_column = Some("id".to_string());
        e.chunk_size = 100_000;
        let w = check_sparse_range(&e, Some(100_000), Some("1"), Some("10000000"));
        assert!(w.is_some(), "should warn about sparse range");
        let msg = w.unwrap();
        assert!(msg.contains("Sparse key range"), "got: {msg}");
        assert!(msg.contains("empty"), "got: {msg}");
    }

    #[test]
    fn sparse_range_no_warning_when_dense() {
        let mut e = make_export("t", ExportMode::Chunked, None);
        e.chunk_column = Some("id".to_string());
        e.chunk_size = 100_000;
        let w = check_sparse_range(&e, Some(100_000), Some("1"), Some("100000"));
        assert!(w.is_none(), "should not warn for dense range");
    }

    #[test]
    fn sparse_range_skipped_when_chunk_dense() {
        let mut e = make_export("t", ExportMode::Chunked, None);
        e.chunk_column = Some("id".to_string());
        e.chunk_dense = true;
        e.chunk_size = 100_000;
        let w = check_sparse_range(&e, Some(100_000), Some("1"), Some("10000000"));
        assert!(
            w.is_none(),
            "chunk_dense uses ordinals, not physical id span"
        );
    }

    #[test]
    fn dense_surrogate_warning_when_chunk_dense_builtin() {
        let mut e = make_export("t", ExportMode::Chunked, None);
        e.chunk_column = Some("id".to_string());
        e.chunk_dense = true;
        e.query = Some("SELECT id FROM orders".to_string());
        let w = check_dense_surrogate_cost(&e);
        assert!(w.is_some(), "should warn about built-in ROW_NUMBER cost");
        assert!(w.unwrap().contains("global sort"));
    }

    #[test]
    fn sparse_range_not_triggered_for_non_chunked() {
        let e = make_export("t", ExportMode::Full, None);
        let w = check_sparse_range(&e, Some(100), Some("1"), Some("1000000"));
        assert!(w.is_none(), "should not warn for non-chunked mode");
    }

    #[test]
    fn dense_surrogate_warning_with_row_number() {
        let mut e = make_export("t", ExportMode::Chunked, None);
        e.chunk_column = Some("rn".to_string());
        e.query = Some("SELECT *, ROW_NUMBER() OVER (ORDER BY id) AS rn FROM orders".to_string());
        let w = check_dense_surrogate_cost(&e);
        assert!(w.is_some(), "should warn about ROW_NUMBER cost");
        assert!(w.unwrap().contains("global sort"));
    }

    #[test]
    fn no_dense_surrogate_warning_without_row_number() {
        let mut e = make_export("t", ExportMode::Chunked, None);
        e.chunk_column = Some("id".to_string());
        e.query = Some("SELECT * FROM orders".to_string());
        let w = check_dense_surrogate_cost(&e);
        assert!(w.is_none());
    }

    #[test]
    fn no_dense_surrogate_warning_for_non_chunked() {
        let mut e = make_export("t", ExportMode::Full, None);
        e.query = Some("SELECT ROW_NUMBER() OVER () AS rn FROM t".to_string());
        let w = check_dense_surrogate_cost(&e);
        assert!(w.is_none(), "should not warn for non-chunked mode");
    }

    #[test]
    fn parallel_memory_warning_large_dataset() {
        let mut e = make_export("t", ExportMode::Chunked, None);
        e.parallel = 4;
        let w = check_parallel_memory_risk(&e, Some(10_000_000));
        assert!(w.is_some(), "should warn about memory risk");
        let msg = w.unwrap();
        assert!(msg.contains("Parallel=4"), "got: {msg}");
        assert!(msg.contains("memory"), "got: {msg}");
    }

    #[test]
    fn no_parallel_memory_warning_small_dataset() {
        let mut e = make_export("t", ExportMode::Chunked, None);
        e.parallel = 4;
        let w = check_parallel_memory_risk(&e, Some(1_000));
        assert!(w.is_none(), "should not warn for small dataset");
    }

    #[test]
    fn no_parallel_memory_warning_single_worker() {
        let e = make_export("t", ExportMode::Full, None);
        let w = check_parallel_memory_risk(&e, Some(100_000_000));
        assert!(w.is_none(), "should not warn when parallel=1");
    }

    #[test]
    fn suggestion_degraded_full_recommends_incremental() {
        let e = make_export("t", ExportMode::Full, None);
        let s = build_suggestion(&HealthVerdict::Degraded, Some(500_000), false, &e).unwrap();
        assert!(s.contains("incremental"), "got: {s}");
    }

    #[test]
    fn suggestion_degraded_chunked_recommends_index() {
        let mut e = make_export("t", ExportMode::Chunked, None);
        e.chunk_column = Some("id".to_string());
        let s = build_suggestion(&HealthVerdict::Degraded, Some(500_000), false, &e).unwrap();
        assert!(s.contains("index on 'id'"), "got: {s}");
    }

    #[test]
    fn suggestion_degraded_time_window_recommends_index() {
        let mut e = make_export("t", ExportMode::TimeWindow, None);
        e.time_column = Some("created_at".to_string());
        e.days_window = Some(7);
        let s = build_suggestion(&HealthVerdict::Degraded, Some(500_000), false, &e).unwrap();
        assert!(s.contains("index on 'created_at'"), "got: {s}");
    }

    #[test]
    fn suggestion_unsafe_full_recommends_incremental() {
        let e = make_export("t", ExportMode::Full, None);
        let s = build_suggestion(&HealthVerdict::Unsafe, Some(100_000_000), false, &e).unwrap();
        assert!(s.contains("incremental"), "got: {s}");
    }

    #[test]
    fn suggestion_unsafe_chunked_recommends_index_and_parallel() {
        let mut e = make_export("t", ExportMode::Chunked, None);
        e.chunk_column = Some("id".to_string());
        let s = build_suggestion(&HealthVerdict::Unsafe, Some(100_000_000), false, &e).unwrap();
        assert!(s.contains("index on 'id'"), "got: {s}");
        assert!(s.contains("parallel"), "got: {s}");
    }

    #[test]
    fn suggestion_unsafe_incremental_recommends_index_on_cursor() {
        let e = make_export("t", ExportMode::Incremental, Some("updated_at"));
        let s = build_suggestion(&HealthVerdict::Unsafe, Some(100_000_000), false, &e).unwrap();
        assert!(s.contains("index on 'updated_at'"), "got: {s}");
    }

    #[test]
    fn suggestion_acceptable_large_full_recommends_incremental() {
        let e = make_export("t", ExportMode::Full, None);
        let s = build_suggestion(&HealthVerdict::Acceptable, Some(20_000_000), true, &e).unwrap();
        assert!(s.contains("incremental"), "got: {s}");
    }

    #[test]
    fn parallel_only_for_chunked_mode() {
        let e = make_export("t", ExportMode::Full, None);
        let (level, _) = recommend_parallelism(&e, Some(1_000_000), true);
        assert_eq!(level, 1, "non-chunked mode should recommend 1");
    }

    #[test]
    fn parallel_small_dataset_is_one() {
        let mut e = make_export("t", ExportMode::Chunked, None);
        e.chunk_column = Some("id".to_string());
        let (level, _) = recommend_parallelism(&e, Some(10_000), true);
        assert_eq!(level, 1, "small dataset should recommend 1");
    }

    #[test]
    fn parallel_moderate_indexed_is_two() {
        let mut e = make_export("t", ExportMode::Chunked, None);
        e.chunk_column = Some("id".to_string());
        let (level, _) = recommend_parallelism(&e, Some(200_000), true);
        assert_eq!(level, 2, "moderate indexed dataset should recommend 2");
    }

    #[test]
    fn parallel_large_indexed_is_four() {
        let mut e = make_export("t", ExportMode::Chunked, None);
        e.chunk_column = Some("id".to_string());
        let (level, _) = recommend_parallelism(&e, Some(2_000_000), true);
        assert_eq!(level, 4, "large indexed dataset should recommend 4");
    }

    #[test]
    fn parallel_no_index_large_is_one() {
        let mut e = make_export("t", ExportMode::Chunked, None);
        e.chunk_column = Some("id".to_string());
        let (level, reason) = recommend_parallelism(&e, Some(10_000_000), false);
        assert_eq!(level, 1, "no index + large should recommend 1");
        assert!(reason.contains("no index"), "got: {reason}");
    }

    #[test]
    fn parallel_no_index_moderate_is_conservative() {
        let mut e = make_export("t", ExportMode::Chunked, None);
        e.chunk_column = Some("id".to_string());
        let (level, _) = recommend_parallelism(&e, Some(200_000), false);
        assert_eq!(
            level, 2,
            "no index + moderate should recommend 2 (conservative)"
        );
    }

    #[test]
    fn suggestion_acceptable_large_chunked_recommends_parallel() {
        let mut e = make_export("t", ExportMode::Chunked, None);
        e.chunk_column = Some("id".to_string());
        let s = build_suggestion(&HealthVerdict::Acceptable, Some(20_000_000), true, &e).unwrap();
        assert!(s.contains("parallel"), "got: {s}");
    }

    #[test]
    fn connection_limit_warn_when_parallel_meets_max() {
        let w = check_connection_limit(20, Some(20));
        assert!(w.is_some(), "should warn when parallel == max_connections");
        let msg = w.unwrap();
        assert!(msg.contains("max_connections=20"), "got: {msg}");
        assert!(msg.contains("parallel=20"), "got: {msg}");
    }

    #[test]
    fn connection_limit_warn_when_parallel_exceeds_max() {
        let w = check_connection_limit(100, Some(20));
        assert!(w.is_some(), "should warn when parallel > max_connections");
        let msg = w.unwrap();
        assert!(msg.contains("max_connections=20"), "got: {msg}");
    }

    #[test]
    fn connection_limit_no_warn_when_parallel_below_max() {
        let w = check_connection_limit(4, Some(100));
        assert!(
            w.is_none(),
            "should not warn when parallel << max_connections"
        );
    }

    #[test]
    fn connection_limit_no_warn_when_parallel_is_one() {
        let w = check_connection_limit(1, Some(5));
        assert!(
            w.is_none(),
            "single worker never triggers connection warning"
        );
    }

    #[test]
    fn connection_limit_skipped_note_when_max_unknown_and_parallel_gt_one() {
        let w = check_connection_limit(100, None);
        assert!(w.is_some(), "should note that check was skipped");
        let msg = w.unwrap();
        assert!(msg.contains("skipped"), "got: {msg}");
    }

    #[test]
    fn connection_limit_no_note_when_max_unknown_and_parallel_is_one() {
        let w = check_connection_limit(1, None);
        assert!(
            w.is_none(),
            "single worker never triggers connection warning"
        );
    }

    #[test]
    fn connection_limit_suggests_headroom() {
        let w = check_connection_limit(25, Some(20)).unwrap();
        // Suggested safe max should be max_connections - 3 = 17
        assert!(
            w.contains("17"),
            "should suggest leaving headroom, got: {w}"
        );
    }

    // ── v0.7.4: actionable hints next to categorised errors ───────────

    fn src_hint(msg: &str, st: SourceType) -> Option<&'static str> {
        let err = anyhow::anyhow!("{}", msg);
        let cat = categorize_source_error(&err);
        source_error_hint(cat, &err, &st)
    }

    fn dest_hint(msg: &str, dt: DestinationType) -> Option<&'static str> {
        let err = anyhow::anyhow!("{}", msg);
        let dest = DestinationConfig {
            destination_type: dt,
            bucket: Some("b".into()),
            ..Default::default()
        };
        let cat = categorize_dest_error(&err, &dest);
        destination_error_hint(cat, &dest)
    }

    #[test]
    fn source_tls_handshake_returns_pg_specific_tls_hint() {
        let h = src_hint("TLS handshake failed", SourceType::Postgres).expect("hint");
        assert!(h.contains("tls.mode") && h.contains("ca_file"), "got: {h}");
    }

    #[test]
    fn source_tls_handshake_returns_mysql_specific_tls_hint() {
        let h = src_hint("certificate verify failed", SourceType::Mysql).expect("hint");
        assert!(h.contains("tls.mode"), "got: {h}");
    }

    #[test]
    fn source_auth_error_postgres_mentions_pg_hba() {
        let h = src_hint("password authentication failed", SourceType::Postgres).expect("hint");
        assert!(h.contains("pg_hba") && h.contains("SELECT"), "got: {h}");
    }

    #[test]
    fn source_auth_error_mysql_mentions_grant() {
        let h = src_hint(
            "Access denied for user 'rivet'@'localhost'",
            SourceType::Mysql,
        )
        .expect("hint");
        assert!(h.contains("GRANT") && h.contains("FLUSH"), "got: {h}");
    }

    #[test]
    fn source_connectivity_error_mentions_bastion_and_network() {
        let h = src_hint("connection refused", SourceType::Postgres).expect("hint");
        assert!(h.contains("bastion") || h.contains("VPN"), "got: {h}");
    }

    #[test]
    fn source_unknown_error_returns_no_hint() {
        // Generic "error" category should yield no hint — better to
        // print the raw driver message than to mislead.
        let h = src_hint("totally unexpected", SourceType::Postgres);
        assert!(h.is_none(), "unknown errors should not produce a hint");
    }

    #[test]
    fn dest_s3_auth_error_names_concrete_actions() {
        let h = dest_hint("permission denied", DestinationType::S3).expect("hint");
        assert!(
            h.contains("s3:PutObject") && h.contains("cloud-permissions"),
            "got: {h}"
        );
    }

    #[test]
    fn dest_gcs_auth_error_names_concrete_actions() {
        let h = dest_hint("403 Forbidden", DestinationType::Gcs).expect("hint");
        assert!(
            h.contains("storage.objects") && h.contains("cloud-permissions"),
            "got: {h}"
        );
    }

    #[test]
    fn categorize_dest_error_sas_expired_message_returns_sas_expired_category() {
        // Guard the load-bearing ordering in categorize_dest_error: the
        // "sas expired" early-return must fire before the generic "token"
        // branch, or destination_error_hint produces the wrong hint.
        // This test pins the *category string*, not just the final hint text.
        let err = anyhow::anyhow!(
            "Azure SAS token already expired (se=2024-01-01T00:00:00Z). Generate a new SAS and re-export."
        );
        let dest = DestinationConfig {
            destination_type: DestinationType::Azure,
            bucket: Some("c".into()),
            ..Default::default()
        };
        let cat = categorize_dest_error(&err, &dest);
        assert_eq!(
            cat, "sas expired",
            "expired-SAS error must categorise as 'sas expired', not '{cat}' — ordering in categorize_dest_error is load-bearing"
        );
    }

    #[test]
    fn dest_azure_sas_expired_returns_regenerate_hint() {
        // The Azure preflight (v0.7.4) bails with "expired (se=…)" —
        // the hint must steer the operator to `az storage container
        // generate-sas` not "your IAM role is broken".
        let h = dest_hint(
            "Azure SAS token already expired (se=2024-01-01T00:00:00Z)",
            DestinationType::Azure,
        )
        .expect("hint");
        assert!(
            h.contains("generate-sas") && h.contains("AZURE_STORAGE_SAS_TOKEN"),
            "got: {h}"
        );
    }

    #[test]
    fn dest_s3_bucket_not_found_says_no_auto_create() {
        let h = dest_hint("NoSuchBucket", DestinationType::S3).expect("hint");
        assert!(
            h.contains("does NOT auto-create") && h.contains("aws s3 mb"),
            "got: {h}"
        );
    }

    #[test]
    fn dest_s3_connectivity_error_warns_about_region_mismatch() {
        let h = dest_hint("dns error", DestinationType::S3).expect("hint");
        assert!(h.contains("region") || h.contains("endpoint"), "got: {h}");
    }
}