elinvar 0.1.2

Find the holes in a design before you build it: a relational model finder, its command line, and an MCP server
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
//! `elinvar discover`: discover and prove common schema invariants via
//! k-induction, reporting each proved invariant in plain English together with
//! the triggers and rules it rests on (N27, B42, B43, W21).

use crate::cli::verbs::{Output, error_output};
use elinvar_als::{SqlColInfo, SqlImportOptions};
use elinvar_engine::sat::Budget;
use elinvar_engine::{Verdict, story_brief};
use serde_json::json;
use std::collections::{BTreeMap, BTreeSet};
use std::time::{Duration, Instant};

/// Default per-candidate conflict budget so `discover` stays responsive.
const DEFAULT_DISCOVER_CONFLICTS: u64 = 200_000;
/// Cap on conflict budget spent extracting the unsat core for one proved invariant.
const EXPLAIN_CAP_CONFLICTS: u64 = 50_000;

/// Options for `elinvar discover` (N27).
#[derive(Clone, Debug)]
pub struct DiscoverOptions {
    /// Optional `--tables` slice (discover invariants only on these tables).
    pub tables: Vec<String>,
    /// With `--tables`, include tables pointing into the slice via FKs.
    pub with_referencing: bool,
    /// Optional sidecar `.als` rules/helpers.
    pub extra_als: Option<String>,
    /// Scope per top-level signature (default 3).
    pub scope: usize,
    /// Optional per-candidate conflict budget.
    pub budget: Option<u64>,
    /// Optional wall-clock time limit in milliseconds for the whole run.
    pub timeout_ms: Option<u64>,
    /// Print rejected candidates and their counterexamples in text output (W21).
    pub show_rejected: bool,
}

impl Default for DiscoverOptions {
    fn default() -> Self {
        Self {
            tables: Vec::new(),
            with_referencing: false,
            extra_als: None,
            scope: 3,
            budget: None,
            timeout_ms: None,
            show_rejected: false,
        }
    }
}

#[derive(Clone, Debug)]
struct Candidate {
    name: String,
    table: String,
    column: Option<String>,
    /// Optional secondary key columns for `at_most_one_open`.
    key_columns: Vec<String>,
    kind: &'static str,
    sentence: String,
    formula: String,
}

fn looks_like_end_marker(col_name: &str) -> bool {
    let low = col_name.to_ascii_lowercase();
    [
        "ended",
        "closed",
        "revoked",
        "deleted",
        "archived",
        "completed",
        "cancelled",
        "canceled",
        "expired",
        "removed",
        "finished",
        "stopped",
    ]
    .iter()
    .any(|kw| low.contains(kw))
}

fn generate_candidates(imp: &elinvar_als::SqlImport, target_tables: &[String]) -> Vec<Candidate> {
    let mut out = Vec::new();
    let mut next_id = 0usize;
    let mut push = |table: &str,
                    column: Option<String>,
                    key_columns: Vec<String>,
                    kind: &'static str,
                    sentence: String,
                    formula: String| {
        let name = format!("__discover_{next_id}");
        next_id += 1;
        out.push(Candidate {
            name,
            table: table.to_string(),
            column,
            key_columns,
            kind,
            sentence,
            formula,
        });
    };

    // Index incoming FKs: target_table_lower -> Vec<(child_table_sql, child_alloy, fk_col_sql, fk_col_alloy)>
    let mut incoming_fks: BTreeMap<String, Vec<(String, String, String, String)>> = BTreeMap::new();
    for ((child_low, fk_col_low), target) in &imp.fk_targets {
        let Some(child_sql) = imp
            .tables
            .iter()
            .find(|t| t.eq_ignore_ascii_case(child_low))
        else {
            continue;
        };
        let Some(child_alloy) = imp.sql_to_alloy_table.get(child_sql) else {
            continue;
        };
        let Some(child_cols) = imp.table_columns.get(child_sql) else {
            continue;
        };
        let Some(fk_col) = child_cols
            .iter()
            .find(|c| c.sql_name.eq_ignore_ascii_case(fk_col_low))
        else {
            continue;
        };
        incoming_fks
            .entry(target.target_table.to_ascii_lowercase())
            .or_default()
            .push((
                child_sql.clone(),
                child_alloy.clone(),
                fk_col.sql_name.clone(),
                fk_col.alloy_name.clone(),
            ));
    }

    for table in target_tables {
        let Some(a_sig) = imp.sql_to_alloy_table.get(table) else {
            continue;
        };
        let cols: &[SqlColInfo] = imp
            .table_columns
            .get(table)
            .map(Vec::as_slice)
            .unwrap_or(&[]);
        let t_low = table.to_ascii_lowercase();
        let pk_count = cols.iter().filter(|c| c.primary_key).count();

        // 1. Dead insert (table is always empty).
        push(
            table,
            None,
            Vec::new(),
            "never_populated",
            format!("Table `{table}` never holds any rows (inserts are always blocked)."),
            format!("always (no {a_sig})"),
        );

        // 2. Append-only (rows are never deleted).
        push(
            table,
            None,
            Vec::new(),
            "never_deleted",
            format!("A row of `{table}` is never deleted."),
            format!("always (all r: {a_sig} | r in {a_sig}')"),
        );

        // 3. Delete protection by referencing child tables.
        if let Some(refs) = incoming_fks.get(&t_low) {
            for (child_sql, child_alloy, fk_sql, fk_alloy) in refs {
                push(
                    table,
                    None,
                    Vec::new(),
                    "protected_by_reference",
                    format!(
                        "A row of `{table}` is never deleted while referenced by `{child_sql}.{fk_sql}`."
                    ),
                    format!(
                        "always (all p: {a_sig} | (some c: {child_alloy} | c.{fk_alloy} = p) implies p in {a_sig}')"
                    ),
                );
            }
        }

        // 4. Per-column invariants.
        for c in cols {
            let ca = &c.alloy_name;
            let cs = &c.sql_name;
            let c_low = cs.to_ascii_lowercase();
            let is_fk = imp.fk_targets.contains_key(&(t_low.clone(), c_low));

            if !c.not_null {
                push(
                    table,
                    Some(cs.clone()),
                    Vec::new(),
                    "always_present",
                    format!("`{table}.{cs}` is always present (never NULL)."),
                    format!("always (all r: {a_sig} | some r.{ca})"),
                );
            }

            push(
                table,
                Some(cs.clone()),
                Vec::new(),
                "immutable",
                format!("`{table}.{cs}` never changes after insert."),
                format!("always (all r: {a_sig} | r in {a_sig}' implies (r.{ca})' = r.{ca})"),
            );

            if !c.not_null {
                push(
                    table,
                    Some(cs.clone()),
                    Vec::new(),
                    "immutable_once_set",
                    format!("`{table}.{cs}` never changes once set."),
                    format!(
                        "always (all r: {a_sig} | (r in {a_sig}' and some r.{ca}) implies (r.{ca})' = r.{ca})"
                    ),
                );
                push(
                    table,
                    Some(cs.clone()),
                    Vec::new(),
                    "never_cleared",
                    format!("`{table}.{cs}` is set once and never cleared."),
                    format!(
                        "always (all r: {a_sig} | (r in {a_sig}' and some r.{ca}) implies some (r.{ca})')"
                    ),
                );
            }

            if c.is_alloy_int && !c.primary_key && !is_fk {
                push(
                    table,
                    Some(cs.clone()),
                    Vec::new(),
                    "non_decreasing",
                    format!("`{table}.{cs}` never decreases."),
                    format!(
                        "always (all r: {a_sig} | (r in {a_sig}' and some r.{ca} and some (r.{ca})') implies int[(r.{ca})'] >= int[r.{ca}])"
                    ),
                );
            }

            if !(pk_count == 1 && c.primary_key) {
                push(
                    table,
                    Some(cs.clone()),
                    Vec::new(),
                    "unique",
                    format!("`{table}.{cs}` is unique across live rows."),
                    format!(
                        "always (all disj r1, r2: {a_sig} | (some r1.{ca} and some r2.{ca}) implies r1.{ca} != r2.{ca})"
                    ),
                );
            }
        }

        // 5. At most one active/open row per key (B43):
        //    First emit exact candidates for every partial unique index on this table
        //    (including composite keys like `(room, who)` with `WHERE ended IS NULL`),
        //    then add single-column key heuristics for nullable marker columns.
        let mut seen_open: BTreeSet<(Vec<String>, String)> = BTreeSet::new();
        for pu in &imp.partial_unique_indexes {
            if !pu.table.eq_ignore_ascii_case(table) {
                continue;
            }
            let Some(m_info) = cols
                .iter()
                .find(|c| c.sql_name.eq_ignore_ascii_case(&pu.null_col))
            else {
                continue;
            };
            let mut k_infos = Vec::new();
            for kname in &pu.cols {
                if let Some(ki) = cols.iter().find(|c| c.sql_name.eq_ignore_ascii_case(kname)) {
                    k_infos.push(ki);
                }
            }
            if k_infos.len() != pu.cols.len() || k_infos.is_empty() {
                continue;
            }
            let key_names: Vec<String> = k_infos.iter().map(|k| k.sql_name.clone()).collect();
            let dedup_key = (
                key_names.iter().map(|s| s.to_ascii_lowercase()).collect(),
                m_info.sql_name.to_ascii_lowercase(),
            );
            if !seen_open.insert(dedup_key) {
                continue;
            }
            let mut conds = vec![
                format!("no r1.{}", m_info.alloy_name),
                format!("no r2.{}", m_info.alloy_name),
            ];
            for k in &k_infos {
                conds.push(format!("some r1.{}", k.alloy_name));
                conds.push(format!("r1.{} = r2.{}", k.alloy_name, k.alloy_name));
            }
            let key_desc = if key_names.len() == 1 {
                format!("`{}`", key_names[0])
            } else {
                format!("`({})`", key_names.join(", "))
            };
            push(
                table,
                Some(m_info.sql_name.clone()),
                key_names,
                "at_most_one_open",
                format!(
                    "At most one row of `{table}` per {key_desc} has `{}` unset.",
                    m_info.sql_name
                ),
                format!(
                    "always (all disj r1, r2: {a_sig} | not ({}))",
                    conds.join(" and ")
                ),
            );
        }

        let marker_cols: Vec<&SqlColInfo> = cols
            .iter()
            .filter(|c| !c.not_null && (cols.len() <= 6 || looks_like_end_marker(&c.sql_name)))
            .collect();
        let key_cols: Vec<&SqlColInfo> = cols
            .iter()
            .filter(|c| !(pk_count == 1 && c.primary_key) && !c.unique)
            .collect();
        for m in &marker_cols {
            for k in &key_cols {
                if m.sql_name == k.sql_name {
                    continue;
                }
                let dedup_key = (
                    vec![k.sql_name.to_ascii_lowercase()],
                    m.sql_name.to_ascii_lowercase(),
                );
                if !seen_open.insert(dedup_key) {
                    continue;
                }
                push(
                    table,
                    Some(m.sql_name.clone()),
                    vec![k.sql_name.clone()],
                    "at_most_one_open",
                    format!(
                        "At most one row of `{table}` per `{}` has `{}` unset.",
                        k.sql_name, m.sql_name
                    ),
                    format!(
                        "always (all disj r1, r2: {a_sig} | not (no r1.{} and no r2.{} and some r1.{} and r1.{} = r2.{}))",
                        m.alloy_name, m.alloy_name, k.alloy_name, k.alloy_name, k.alloy_name
                    ),
                );
            }
        }
    }

    out
}

fn append_candidates(
    base_model: &str,
    extra_als: Option<&str>,
    candidates: &[Candidate],
    scope: usize,
) -> String {
    let mut combined = base_model.to_string();
    if let Some(extra) = extra_als
        && !extra.trim().is_empty()
    {
        combined.push('\n');
        combined.push_str(extra);
        combined.push('\n');
    }
    for c in candidates {
        combined.push_str(&format!(
            "\nassert {} {{ {} }}\ncheck {} for {}\n",
            c.name, c.formula, c.name, scope
        ));
    }
    combined
}

/// Discovers and proves schema invariants by k-induction (N27, B42, B43, W21).
pub fn discover(
    file: &str,
    sql_text: &str,
    opts: &DiscoverOptions,
    on_progress: Option<&dyn Fn(&str)>,
) -> Output {
    let deadline = opts
        .timeout_ms
        .map(|ms| Instant::now() + Duration::from_millis(ms));
    let imp = match elinvar_als::import_sql_with(
        file,
        sql_text,
        &SqlImportOptions::new()
            .temporal(true)
            .from_empty(true)
            .tables(opts.tables.clone())
            .with_referencing(opts.with_referencing),
    ) {
        Ok(i) => i,
        Err(errors) => return error_output("discover", errors),
    };

    // B42: build a matching model WITHOUT `fact StartEmpty` so unsat-core
    // explanation of inductively proved invariants attributes them to the
    // real triggers/constraints rather than the empty initial state.
    let imp_no_empty = match elinvar_als::import_sql_with(
        file,
        sql_text,
        &SqlImportOptions::new()
            .temporal(true)
            .from_empty(false)
            .tables(opts.tables.clone())
            .with_referencing(opts.with_referencing),
    ) {
        Ok(i) => i,
        Err(errors) => return error_output("discover", errors),
    };

    let target_tables: Vec<String> = if opts.tables.is_empty() {
        imp.tables.clone()
    } else {
        imp.tables
            .iter()
            .filter(|t| opts.tables.iter().any(|req| req.eq_ignore_ascii_case(t)))
            .cloned()
            .collect()
    };

    let candidates = generate_candidates(&imp, &target_tables);
    let combined = append_candidates(
        &imp.model,
        opts.extra_als.as_deref(),
        &candidates,
        opts.scope,
    );
    let combined_no_empty = append_candidates(
        &imp_no_empty.model,
        opts.extra_als.as_deref(),
        &candidates,
        opts.scope,
    );

    let read_opts = elinvar_als::ReadOptions::default().default_bitwidth(imp.bitwidth);
    let model = match elinvar_als::read_with(file, &combined, read_opts) {
        Ok(m) => m,
        Err(errors) => return error_output("discover", errors),
    };
    let explain_model = match elinvar_als::read_with(file, &combined_no_empty, read_opts) {
        Ok(m) => m,
        Err(errors) => return error_output("discover", errors),
    };

    let spec_by_name: BTreeMap<&str, &elinvar_als::CommandSpec> = model
        .commands
        .iter()
        .filter(|c| c.check)
        .map(|c| (c.name.as_str(), c))
        .collect();
    let explain_spec_by_name: BTreeMap<&str, &elinvar_als::CommandSpec> = explain_model
        .commands
        .iter()
        .filter(|c| c.check)
        .map(|c| (c.name.as_str(), c))
        .collect();

    let per_cand_conflicts = opts.budget.unwrap_or(DEFAULT_DISCOVER_CONFLICTS);

    if let Some(cb) = on_progress {
        cb(&format!(
            "discover {file}: checking {} candidate(s) across {} table(s)",
            candidates.len(),
            target_tables.len()
        ));
    }

    // Evaluates one candidate and extracts its minimal rule core when proved.
    let eval_candidate = |cand: &Candidate| -> (
        Option<Verdict>,
        Option<serde_json::Value>,
        Option<serde_json::Value>,
    ) {
        let Some(&spec) = spec_by_name.get(cand.name.as_str()) else {
            return (None, None, None);
        };
        let mut cand_budget = Budget::conflicts(per_cand_conflicts);
        if let Some(d) = deadline {
            let Some(rem) = d.checked_duration_since(Instant::now()) else {
                return (Some(Verdict::Unknown), None, None);
            };
            cand_budget = cand_budget.with_time(rem);
        }

        // W23: when `--show-rejected` is off (the default), run k-induction
        // directly without falling back to bounded trace checking or shrinking
        // counterexamples for rejected candidates. When `--show-rejected` is
        // on, keep bounded `steps(3)` fallback so rejected candidates carry
        // short shrunk counterexamples (W21).
        let (verdict, rejected_rep) = if opts.show_rejected {
            let rep = model
                .command(spec)
                .scope(opts.scope)
                .steps(3)
                .by_induction(1)
                .budget(cand_budget)
                .report();
            (rep.verdict, Some(rep))
        } else {
            let v = match model
                .command(spec)
                .scope(opts.scope)
                .steps(2)
                .budget(cand_budget)
                .prove_by_induction(1)
            {
                Ok(Some(out)) => Some(out.verdict),
                Ok(None) if deadline.is_some_and(|d| Instant::now() >= d) => Some(Verdict::Unknown),
                Ok(None) => None,
                // AGENTS.md law 14: a candidate the solver could not judge is
                // unsettled, not rejected.
                Err(_) => Some(Verdict::Unknown),
            };
            (v, None)
        };

        match verdict {
            Some(Verdict::Proved) => {
                // B42/W23: extract the minimal unsat core WITHOUT `fact StartEmpty`
                // at scope <= 2 first (2 rows suffice for all unary/binary checks
                // and uniqueness invariants while running much faster than scope 3).
                let mut explain_budget =
                    Budget::conflicts(per_cand_conflicts.min(EXPLAIN_CAP_CONFLICTS));
                let mut explain_expired = false;
                if let Some(d) = deadline {
                    if let Some(rem) = d.checked_duration_since(Instant::now())
                        && !rem.is_zero()
                    {
                        explain_budget = explain_budget.with_time(rem.min(Duration::from_secs(3)));
                    } else {
                        explain_expired = true;
                    }
                }
                let explain_scope = opts.scope.clamp(1, 2);
                let rules = if explain_expired {
                    Vec::new()
                } else if cand.kind != "never_populated"
                    && let Some(&exp_spec) = explain_spec_by_name.get(cand.name.as_str())
                    && let Ok(Some(core)) = explain_model
                        .command(exp_spec)
                        .scope(explain_scope)
                        .steps(2)
                        .budget(explain_budget)
                        .explain_holds()
                {
                    core.used
                } else if let Some(d) = deadline {
                    if let Some(rem) = d.checked_duration_since(Instant::now())
                        && !rem.is_zero()
                    {
                        let fb_budget =
                            Budget::conflicts(per_cand_conflicts.min(EXPLAIN_CAP_CONFLICTS))
                                .with_time(rem.min(Duration::from_secs(3)));
                        model
                            .command(spec)
                            .scope(explain_scope)
                            .steps(2)
                            .budget(fb_budget)
                            .explain_holds()
                            .ok()
                            .flatten()
                            .map(|core| core.used)
                            .unwrap_or_default()
                    } else {
                        Vec::new()
                    }
                } else {
                    model
                        .command(spec)
                        .scope(explain_scope)
                        .steps(2)
                        .budget(explain_budget)
                        .explain_holds()
                        .ok()
                        .flatten()
                        .map(|core| core.used)
                        .unwrap_or_default()
                };
                (
                    verdict,
                    Some(json!({
                        "table": cand.table,
                        "column": cand.column,
                        "kind": cand.kind,
                        "sentence": cand.sentence,
                        "formula": cand.formula,
                        "rules": rules,
                    })),
                    None,
                )
            }
            Some(Verdict::Unknown) => (verdict, None, None),
            Some(Verdict::Counterexample) if opts.show_rejected => {
                let cx = rejected_rep.as_ref().map(story_brief);
                (
                    verdict,
                    None,
                    Some(json!({
                        "table": cand.table,
                        "column": cand.column,
                        "kind": cand.kind,
                        "sentence": cand.sentence,
                        "formula": cand.formula,
                        "reason": "counterexample",
                        "counterexample": cx,
                    })),
                )
            }
            _ => {
                let rej = if opts.show_rejected {
                    let note = rejected_rep.and_then(|r| r.note);
                    Some(json!({
                        "table": cand.table,
                        "column": cand.column,
                        "kind": cand.kind,
                        "sentence": cand.sentence,
                        "formula": cand.formula,
                        "reason": "not_inductive",
                        "counterexample": note,
                    }))
                } else {
                    None
                };
                (verdict, None, rej)
            }
        }
    };

    // Per-candidate outcome slots indexed by original candidate order (Law 16:
    // deterministic output order regardless of worker scheduling).
    #[derive(Default)]
    struct CandSlot {
        checked: bool,
        unfinished: bool,
        proved: Option<serde_json::Value>,
        rejected: Option<serde_json::Value>,
    }

    let workers = std::thread::available_parallelism()
        .map(usize::from)
        .unwrap_or(1)
        .clamp(1, if deadline.is_some() { 4 } else { 8 });

    // Phase 1: check `never_populated` across all target tables in parallel so
    // dead tables skip all remaining candidates cleanly.
    let dead_indices: Vec<usize> = candidates
        .iter()
        .enumerate()
        .filter(|(_, c)| c.kind == "never_populated")
        .map(|(i, _)| i)
        .collect();
    let slots: Vec<std::sync::Mutex<CandSlot>> = (0..candidates.len())
        .map(|_| std::sync::Mutex::new(CandSlot::default()))
        .collect();
    let dead_tables_mu: std::sync::Mutex<BTreeSet<String>> = std::sync::Mutex::new(BTreeSet::new());

    if !dead_indices.is_empty() {
        let next = std::sync::atomic::AtomicUsize::new(0);
        let n_threads = workers.min(dead_indices.len());
        std::thread::scope(|s| {
            for _ in 0..n_threads {
                let work = || {
                    loop {
                        let k = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                        if k >= dead_indices.len() {
                            break;
                        }
                        let idx = dead_indices[k];
                        let cand = &candidates[idx];
                        if deadline.is_some_and(|d| Instant::now() >= d) {
                            if let Ok(mut sl) = slots[idx].lock() {
                                sl.checked = true;
                                sl.unfinished = true;
                            }
                            continue;
                        }
                        let (verdict, prov, rej) = eval_candidate(cand);
                        if verdict == Some(Verdict::Proved)
                            && let Ok(mut dt) = dead_tables_mu.lock()
                        {
                            dt.insert(cand.table.clone());
                        }
                        if let Ok(mut sl) = slots[idx].lock() {
                            sl.checked = true;
                            sl.unfinished = verdict == Some(Verdict::Unknown);
                            sl.proved = prov;
                            sl.rejected = rej;
                        }
                    }
                };
                // A worker that cannot get the large stack runs on a default one.
                if crate::cli::model_thread().spawn_scoped(s, work).is_err() {
                    s.spawn(work);
                }
            }
        });
    }
    let dead_tables = dead_tables_mu.into_inner().unwrap_or_default();

    // Phase 2: partition remaining candidates on live tables into independent
    // subsumption chains (per table delete-chain, per (table, col) mutation-chain,
    // per (table, col) unique+open-chain) and execute chains in parallel (W25).
    let mut chains: BTreeMap<(String, u8, String), Vec<usize>> = BTreeMap::new();
    for (idx, cand) in candidates.iter().enumerate() {
        if cand.kind == "never_populated" || dead_tables.contains(&cand.table) {
            continue;
        }
        let key = match cand.kind {
            "never_deleted" | "protected_by_reference" => (cand.table.clone(), 0u8, String::new()),
            "always_present" => (
                cand.table.clone(),
                1u8,
                cand.column.clone().unwrap_or_default(),
            ),
            "immutable" | "immutable_once_set" | "never_cleared" | "non_decreasing" => (
                cand.table.clone(),
                2u8,
                cand.column.clone().unwrap_or_default(),
            ),
            "unique" => (
                cand.table.clone(),
                3u8,
                cand.column.clone().unwrap_or_default(),
            ),
            "at_most_one_open" => {
                if cand.key_columns.len() == 1 {
                    (cand.table.clone(), 3u8, cand.key_columns[0].clone())
                } else {
                    (cand.table.clone(), 4u8, format!("{idx}"))
                }
            }
            _ => (cand.table.clone(), 5u8, format!("{idx}")),
        };
        chains.entry(key).or_default().push(idx);
    }
    let chain_list: Vec<Vec<usize>> = chains.into_values().collect();
    if !chain_list.is_empty() {
        let next = std::sync::atomic::AtomicUsize::new(0);
        let n_threads = workers.min(chain_list.len());
        std::thread::scope(|s| {
            for _ in 0..n_threads {
                let work = || {
                    loop {
                        let k = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                        if k >= chain_list.len() {
                            break;
                        }
                        let mut never_deleted = false;
                        let mut immutable = false;
                        let mut immutable_once = false;
                        let mut unique = false;
                        for &idx in &chain_list[k] {
                            let cand = &candidates[idx];
                            if deadline.is_some_and(|d| Instant::now() >= d) {
                                if let Ok(mut sl) = slots[idx].lock() {
                                    sl.checked = true;
                                    sl.unfinished = true;
                                }
                                continue;
                            }
                            if cand.kind == "protected_by_reference" && never_deleted {
                                continue;
                            }
                            if matches!(
                                cand.kind,
                                "immutable_once_set" | "never_cleared" | "non_decreasing"
                            ) && immutable
                            {
                                continue;
                            }
                            if matches!(cand.kind, "never_cleared" | "non_decreasing")
                                && immutable_once
                            {
                                continue;
                            }
                            if cand.kind == "at_most_one_open"
                                && cand.key_columns.len() == 1
                                && unique
                            {
                                continue;
                            }
                            let (verdict, prov, rej) = eval_candidate(cand);
                            if verdict == Some(Verdict::Proved) {
                                match cand.kind {
                                    "never_deleted" => never_deleted = true,
                                    "immutable" => immutable = true,
                                    "immutable_once_set" => immutable_once = true,
                                    "unique" => unique = true,
                                    _ => {}
                                }
                            }
                            if let Ok(mut sl) = slots[idx].lock() {
                                sl.checked = true;
                                sl.unfinished = verdict == Some(Verdict::Unknown);
                                sl.proved = prov;
                                sl.rejected = rej;
                            }
                        }
                    }
                };
                // A worker that cannot get the large stack runs on a default one.
                if crate::cli::model_thread().spawn_scoped(s, work).is_err() {
                    s.spawn(work);
                }
            }
        });
    }

    let mut proved = Vec::new();
    let mut rejected = Vec::new();
    let mut candidates_checked = 0usize;
    let mut candidates_unfinished = 0usize;
    for sl_mu in slots {
        let sl = sl_mu.into_inner().unwrap_or_default();
        if sl.checked {
            candidates_checked += 1;
        }
        if sl.unfinished {
            candidates_unfinished += 1;
        }
        if let Some(p) = sl.proved {
            proved.push(p);
        }
        if let Some(r) = sl.rejected {
            rejected.push(r);
        }
    }

    let unread_rules = imp.skipped.len();
    let mut story = format!(
        "discover: proved {} invariant(s) across {} table(s) (scope {}; checked {candidates_checked} candidate(s))\n",
        proved.len(),
        target_tables.len(),
        opts.scope
    );
    if unread_rules > 0 {
        story.push_str(&format!(
            "  note: {unread_rules} rule(s) of the schema were not read; invariants depending on them may not appear\n"
        ));
    }
    if candidates_unfinished > 0 {
        story.push_str(&format!(
            "  note: {candidates_unfinished} candidate(s) did not finish: budget, timeout, or an error\n"
        ));
    }

    for table in &target_tables {
        let items: Vec<&serde_json::Value> = proved
            .iter()
            .filter(|v| v["table"].as_str() == Some(table.as_str()))
            .collect();
        if items.is_empty() {
            continue;
        }
        story.push_str(&format!("\n{table}:\n"));
        for item in items {
            let sent = item["sentence"].as_str().unwrap_or("");
            story.push_str(&format!("  - {sent}\n"));
            if let Some(rules) = item["rules"].as_array()
                && !rules.is_empty()
            {
                let names: Vec<&str> = rules.iter().filter_map(serde_json::Value::as_str).collect();
                story.push_str(&format!("    rests on: {}\n", names.join(", ")));
            }
        }
    }

    if opts.show_rejected && !rejected.is_empty() {
        story.push_str("\nnot proved:\n");
        for item in &rejected {
            let sent = item["sentence"].as_str().unwrap_or("");
            let reason = item["reason"].as_str().unwrap_or("");
            story.push_str(&format!("  - [{reason}] {sent}\n"));
            if let Some(cx) = item["counterexample"].as_str() {
                for line in cx.lines().take(12) {
                    if !line.trim().is_empty() {
                        story.push_str(&format!("      {line}\n"));
                    }
                }
            }
        }
    }

    let status = if candidates_unfinished > 0 { 2 } else { 0 };
    Output {
        json: json!({
            "elinvar": 1,
            "command": "discover",
            "tables": target_tables,
            "scope": opts.scope,
            "candidates_checked": candidates_checked,
            "candidates_unfinished": candidates_unfinished,
            "unread_rules": unread_rules,
            "invariants": proved,
            "rejected": rejected,
            "story": story,
        }),
        text: story,
        status,
    }
}