elinvar 0.1.0

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
//! Pure-Rust Gregorian calendar helpers for real-date evaluation in `accepts`,
//! `fuzz`, and `audit` (B48, N30).
//!
//! When a SQL schema uses `strftime('%Y-%m', ..., 'unixepoch')` or date shifts
//! (`'+16 years'`, `'+' || col || ' years'`), the solver abstracts `SqlDateFn`
//! as a monotone function. When evaluating concrete SQL scripts or dumps, this
//! module computes real calendar months/dates and populates `SqlDateFn` as an
//! exact monotone map over the sorted date order.

use std::collections::{BTreeMap, BTreeSet};

use elinvar_engine::logic::{Instance, Relation, Universe};

/// Converts days since 1970-01-01 to `(year, month 1..=12, day 1..=31)` in the
/// proleptic Gregorian calendar (Howard Hinnant's `civil_from_days`).
pub(crate) fn civil_from_days(z: i64) -> (i64, u32, u32) {
    let z = z + 719_468;
    let era = z.div_euclid(146_097);
    let doe = (z - era * 146_097) as u64;
    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
    let y = yoe as i64 + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let year = y + i64::from(m <= 2);
    (year, m as u32, d as u32)
}

/// Converts `(year, month 1..=12, day 1..=31)` to days since 1970-01-01.
pub(crate) fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
    let y = y - i64::from(m <= 2);
    let era = y.div_euclid(400);
    let yoe = (y - era * 400) as u64;
    let m_adj = if m > 2 { m - 3 } else { m + 9 } as u64;
    let doy = (153 * m_adj + 2) / 5 + u64::from(d) - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    era * 146_097 + doe as i64 - 719_468
}

/// Formats `(year, month, day)` according to a SQLite `strftime` format string.
pub(crate) fn format_ymd(y: i64, m: u32, d: u32, fmt: &str) -> String {
    let y_clamped = y.clamp(0, 9999);
    if fmt.contains("%d") {
        format!("{y_clamped:04}-{m:02}-{d:02}")
    } else if fmt.contains("%m") {
        format!("{y_clamped:04}-{m:02}")
    } else {
        format!("{y_clamped:04}")
    }
}

/// Formats a Unix timestamp (seconds since 1970-01-01 UTC) using `fmt`.
pub(crate) fn unix_to_date_str(ts: i64, fmt: &str) -> String {
    let days = ts.div_euclid(86_400);
    let (y, m, d) = civil_from_days(days);
    format_ymd(y, m, d, fmt)
}

/// Parses `"YYYY"`, `"YYYY-MM"`, or `"YYYY-MM-DD"` (ignoring any trailing time).
pub(crate) fn parse_date_ymd(s: &str) -> Option<(i64, u32, u32)> {
    let clean = s.trim().split(['T', ' ']).next()?;
    let mut parts = clean.split('-');
    let y: i64 = parts.next()?.parse().ok()?;
    let m: u32 = match parts.next() {
        Some(ms) => ms.parse().ok()?,
        None => 1,
    };
    let d: u32 = match parts.next() {
        Some(ds) => ds.parse().ok()?,
        None => 1,
    };
    if !(1..=12).contains(&m) || !(1..=31).contains(&d) {
        return None;
    }
    Some((y, m, d))
}

fn is_leap_year(y: i64) -> bool {
    (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0)
}

fn days_in_month(y: i64, m: u32) -> u32 {
    match m {
        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
        4 | 6 | 9 | 11 => 30,
        2 => {
            if is_leap_year(y) {
                29
            } else {
                28
            }
        }
        _ => 30,
    }
}

/// Applies a SQLite calendar shift (`+N years`, `+N months`, `+N days`) to a
/// date string and formats the result with `fmt`.
pub(crate) fn shift_date_str(s: &str, amount: i64, unit: &str, fmt: &str) -> Option<String> {
    let (y, m, d) = parse_date_ymd(s)?;
    let (ny, nm, nd) = match unit {
        "years" | "year" => {
            let ny = y.saturating_add(amount);
            let max_d = days_in_month(ny, m);
            // SQLite rolls Feb 29 + 1 year forward to Mar 1.
            if d > max_d {
                let overflow = d - max_d;
                let (ry, rm, rd) =
                    civil_from_days(days_from_civil(ny, m, max_d) + i64::from(overflow));
                (ry, rm, rd)
            } else {
                (ny, m, d)
            }
        }
        "months" | "month" => {
            let total = y
                .saturating_mul(12)
                .saturating_add(i64::from(m - 1))
                .saturating_add(amount);
            let ny = total.div_euclid(12);
            let nm = (total.rem_euclid(12) + 1) as u32;
            let max_d = days_in_month(ny, nm);
            if d > max_d {
                let overflow = d - max_d;
                let (ry, rm, rd) =
                    civil_from_days(days_from_civil(ny, nm, max_d) + i64::from(overflow));
                (ry, rm, rd)
            } else {
                (ny, nm, d)
            }
        }
        _ => {
            let days = days_from_civil(y, m, d).saturating_add(amount);
            civil_from_days(days)
        }
    };
    Some(format_ymd(ny, nm, nd, fmt))
}

/// Top sentinel date guaranteed to sort strictly after every real date.
pub(crate) fn max_sentinel_date(fmt: &str) -> String {
    if fmt.contains("%d") {
        "9999-12-31".to_string()
    } else if fmt.contains("%m") {
        "9999-12".to_string()
    } else {
        "9999".to_string()
    }
}

/// Bottom sentinel date guaranteed to sort strictly before every real date.
pub(crate) fn min_sentinel_date(fmt: &str) -> String {
    if fmt.contains("%d") {
        "0000-01-01".to_string()
    } else if fmt.contains("%m") {
        "0000-01".to_string()
    } else {
        "0000".to_string()
    }
}

/// Maps `target` to the index of the smallest date in sorted `dates` that is
/// `>= target` (and strictly `> base_idx` when `strict_gt` is true), clamped to
/// `dates.len() - 1`.
fn ceil_date_idx(dates: &[String], target: &str, base_idx: usize, strict_gt: bool) -> usize {
    if dates.is_empty() {
        return 0;
    }
    let last = dates.len() - 1;
    let start = if strict_gt {
        (base_idx + 1).min(last)
    } else {
        0
    };
    for (i, d) in dates.iter().enumerate().skip(start) {
        if d.as_str() >= target {
            return i;
        }
    }
    last
}

/// Maps `target` to the index of the largest date in sorted `dates` that is
/// `<= target` (and strictly `< base_idx` when `strict_lt` is true), clamped to `0`.
fn floor_date_idx(dates: &[String], target: &str, base_idx: usize, strict_lt: bool) -> usize {
    if dates.is_empty() {
        return 0;
    }
    let end = if strict_lt {
        base_idx.saturating_sub(1)
    } else {
        dates.len() - 1
    };
    for i in (0..=end).rev() {
        if dates[i].as_str() <= target {
            return i;
        }
    }
    0
}

/// Finds the ordered date signature name from `SqlDateFn`'s fields (`to_date_*` / `add_*`).
pub(crate) fn detect_date_sig_from_relations(
    relations: &[Relation],
    field_range_sig: &BTreeMap<String, String>,
) -> Option<String> {
    if !relations.iter().any(|r| r.name() == "SqlDateFn") {
        return None;
    }
    for rel in relations {
        let name = rel.name();
        let short = name.rsplit('.').next().unwrap_or(name);
        if (short.starts_with("to_date_") || short.starts_with("add_"))
            && (rel.arity() == 3 || rel.arity() == 4)
            && let Some(ran) = field_range_sig.get(name)
        {
            return Some(ran.clone());
        }
    }
    None
}

/// Returns true for synthetic `SqlDateFn` solver axioms/multiplicity facts
/// that [`populate_sql_date_fn`] satisfies by construction (B54).
pub(crate) fn is_synthetic_date_fn_rule(rule_name: &str) -> bool {
    if rule_name == "fact SqlDateFn_monotone" {
        return true;
    }
    if let Some(rest) = rule_name.strip_prefix("field ") {
        let short = rest.rsplit('.').next().unwrap_or(rest);
        return short.starts_with("to_date_") || short.starts_with("add_");
    }
    false
}

/// Collects all concrete dates needed in the date order for `SqlDateFn`:
/// - Unix timestamps converted to date strings for every `to_date_<src>` field,
/// - Shifted date strings for every concrete row date and every `SqlDateShift`,
/// - Bottom/top sentinels (`0000-01` / `9999-12`) so monotonicity axioms hold everywhere.
pub(crate) fn expand_date_domain(
    fmt: &str,
    date_shifts: &[elinvar_als::SqlDateShift],
    src_unix_values: &[i64],
    int_values: &BTreeSet<i64>,
    ord_shift_values: &BTreeMap<String, Vec<i64>>,
    base_dates: &mut BTreeSet<String>,
) {
    // B54: only shift actual date-string column values (`row_dates`), not the
    // converted Unix-epoch timestamps, so `add_Int` stays tiny and fast.
    let row_dates: Vec<String> = base_dates.iter().cloned().collect();

    // 1. Convert all source Unix timestamps to date strings.
    for &ts in src_unix_values {
        base_dates.insert(unix_to_date_str(ts, fmt));
    }

    // 2. Apply every configured shift to every known row date so comparisons
    //    between actual rows and shifted dates hit exact values in the order.
    let shift_sources: Vec<String> = if row_dates.is_empty() {
        base_dates.iter().cloned().collect()
    } else {
        row_dates
    };
    for sh in date_shifts {
        if let Some(amt) = sh.amount {
            for d in &shift_sources {
                if let Some(shifted) = shift_date_str(d, amt, &sh.unit, fmt) {
                    base_dates.insert(shifted);
                }
            }
        } else if sh.field == "add_Int" {
            for d in &shift_sources {
                for &n in int_values {
                    if n != 0
                        && n.abs() <= 36_600
                        && let Some(shifted) = shift_date_str(d, n, &sh.unit, fmt)
                    {
                        base_dates.insert(shifted);
                    }
                }
            }
        } else if let Some(ord_sig) = sh.field.strip_prefix("add_")
            && let Some(nums) = ord_shift_values.get(ord_sig)
        {
            for d in &shift_sources {
                for &n in nums {
                    if n != 0
                        && n.abs() <= 36_600
                        && let Some(shifted) = shift_date_str(d, n, &sh.unit, fmt)
                    {
                        base_dates.insert(shifted);
                    }
                }
            }
        }
    }

    // 3. Always add sentinels so `add_pos` can clamp at `last` and `add_neg` at `first`.
    base_dates.insert(max_sentinel_date(fmt));
    let has_neg = date_shifts
        .iter()
        .any(|s| s.field.starts_with("add_neg") || s.field == "add_Int");
    if has_neg {
        base_dates.insert(min_sentinel_date(fmt));
    }
    if base_dates.len() == 1 {
        // Ensure at least two dates so `first < last` when `add_pos` exists.
        base_dates.insert(min_sentinel_date(fmt));
    }
}

/// Populates all `SqlDateFn` relations (`to_date_*`, `add_pos*`, `add_neg*`,
/// `add_Int`, `add_<ord>`) in `fixed` using real Gregorian calendar arithmetic.
#[allow(clippy::too_many_arguments)]
pub(crate) fn populate_sql_date_fn(
    fixed: &mut Instance,
    u: &Universe,
    relations: &[Relation],
    fn_atom: &str,
    fmt: &str,
    date_shifts: &[elinvar_als::SqlDateShift],
    date_strings: &[String],
    date_atoms: &[String],
    ord_int_values: &BTreeMap<String, Vec<(String, i64)>>,
    int_atom_pairs: &[(String, i64)],
) -> Result<(), elinvar_engine::logic::Error> {
    if date_strings.is_empty() || date_atoms.is_empty() {
        return Ok(());
    }
    let shift_by_field: BTreeMap<&str, &elinvar_als::SqlDateShift> =
        date_shifts.iter().map(|s| (s.field.as_str(), s)).collect();

    for rel in relations {
        if rel.is_changing() || (rel.arity() != 3 && rel.arity() != 4) {
            continue;
        }
        let rname = rel.name();
        let short = rname.rsplit('.').next().unwrap_or(rname);

        if let Some(src_sig) = short.strip_prefix("to_date_")
            && rel.arity() == 3
        {
            let mut triples: Vec<(String, String, String)> = Vec::new();
            let pairs: Vec<(String, i64)> = if src_sig == "Int" {
                int_atom_pairs.to_vec()
            } else {
                ord_int_values.get(src_sig).cloned().unwrap_or_default()
            };
            for (src_atom, ts) in pairs {
                let dstr = unix_to_date_str(ts, fmt);
                let idx = ceil_date_idx(date_strings, &dstr, 0, false);
                triples.push((fn_atom.to_string(), src_atom, date_atoms[idx].clone()));
            }
            let slices: Vec<[&str; 3]> = triples
                .iter()
                .map(|(a, b, c)| [a.as_str(), b.as_str(), c.as_str()])
                .collect();
            let refs: Vec<&[&str]> = slices.iter().map(|t| t.as_slice()).collect();
            let ts = u.tuple_set(3, &refs)?;
            fixed.set(rel, ts)?;
        } else if (short == "add_pos" || short.starts_with("add_pos_")) && rel.arity() == 3 {
            let (amt, unit) = shift_by_field
                .get(short)
                .map(|s| (s.amount.unwrap_or(1).max(1), s.unit.as_str()))
                .unwrap_or((1, "years"));
            let mut triples: Vec<(String, String, String)> = Vec::new();
            for (i, dstr) in date_strings.iter().enumerate() {
                let target_idx = match shift_date_str(dstr, amt, unit, fmt) {
                    Some(shifted) => ceil_date_idx(date_strings, &shifted, i, true),
                    None => (i + 1).min(date_atoms.len() - 1),
                };
                triples.push((
                    fn_atom.to_string(),
                    date_atoms[i].clone(),
                    date_atoms[target_idx].clone(),
                ));
            }
            let slices: Vec<[&str; 3]> = triples
                .iter()
                .map(|(a, b, c)| [a.as_str(), b.as_str(), c.as_str()])
                .collect();
            let refs: Vec<&[&str]> = slices.iter().map(|t| t.as_slice()).collect();
            let ts = u.tuple_set(3, &refs)?;
            fixed.set(rel, ts)?;
        } else if (short == "add_neg" || short.starts_with("add_neg_")) && rel.arity() == 3 {
            let (amt, unit) = shift_by_field
                .get(short)
                .map(|s| (s.amount.unwrap_or(-1).min(-1), s.unit.as_str()))
                .unwrap_or((-1, "years"));
            let mut triples: Vec<(String, String, String)> = Vec::new();
            for (i, dstr) in date_strings.iter().enumerate() {
                let target_idx = match shift_date_str(dstr, amt, unit, fmt) {
                    Some(shifted) => floor_date_idx(date_strings, &shifted, i, true),
                    None => i.saturating_sub(1),
                };
                triples.push((
                    fn_atom.to_string(),
                    date_atoms[i].clone(),
                    date_atoms[target_idx].clone(),
                ));
            }
            let slices: Vec<[&str; 3]> = triples
                .iter()
                .map(|(a, b, c)| [a.as_str(), b.as_str(), c.as_str()])
                .collect();
            let refs: Vec<&[&str]> = slices.iter().map(|t| t.as_slice()).collect();
            let ts = u.tuple_set(3, &refs)?;
            fixed.set(rel, ts)?;
        } else if short == "add_Int" && rel.arity() == 4 {
            let unit = shift_by_field
                .get(short)
                .map(|s| s.unit.as_str())
                .unwrap_or("years");
            let mut quads: Vec<(String, String, String, String)> = Vec::new();
            for (i, dstr) in date_strings.iter().enumerate() {
                for (int_atom, n) in int_atom_pairs {
                    let target_idx = if *n == 0 {
                        i
                    } else if *n > 0 {
                        match shift_date_str(dstr, *n, unit, fmt) {
                            Some(shifted) => ceil_date_idx(date_strings, &shifted, i, true),
                            None => (i + 1).min(date_atoms.len() - 1),
                        }
                    } else {
                        match shift_date_str(dstr, *n, unit, fmt) {
                            Some(shifted) => floor_date_idx(date_strings, &shifted, i, true),
                            None => i.saturating_sub(1),
                        }
                    };
                    quads.push((
                        fn_atom.to_string(),
                        date_atoms[i].clone(),
                        int_atom.clone(),
                        date_atoms[target_idx].clone(),
                    ));
                }
            }
            let slices: Vec<[&str; 4]> = quads
                .iter()
                .map(|(a, b, c, d)| [a.as_str(), b.as_str(), c.as_str(), d.as_str()])
                .collect();
            let refs: Vec<&[&str]> = slices.iter().map(|t| t.as_slice()).collect();
            let ts = u.tuple_set(4, &refs)?;
            fixed.set(rel, ts)?;
        } else if let Some(ord_sig) = short.strip_prefix("add_")
            && rel.arity() == 4
        {
            let unit = shift_by_field
                .get(short)
                .map(|s| s.unit.as_str())
                .unwrap_or("years");
            let ord_pairs = ord_int_values.get(ord_sig).cloned().unwrap_or_default();
            let mut quads: Vec<(String, String, String, String)> = Vec::new();
            for (i, dstr) in date_strings.iter().enumerate() {
                for (ord_atom, n) in &ord_pairs {
                    let target_idx = if *n == 0 {
                        i
                    } else if *n > 0 {
                        match shift_date_str(dstr, *n, unit, fmt) {
                            Some(shifted) => ceil_date_idx(date_strings, &shifted, i, true),
                            None => (i + 1).min(date_atoms.len() - 1),
                        }
                    } else {
                        match shift_date_str(dstr, *n, unit, fmt) {
                            Some(shifted) => floor_date_idx(date_strings, &shifted, i, true),
                            None => i.saturating_sub(1),
                        }
                    };
                    quads.push((
                        fn_atom.to_string(),
                        date_atoms[i].clone(),
                        ord_atom.clone(),
                        date_atoms[target_idx].clone(),
                    ));
                }
            }
            let slices: Vec<[&str; 4]> = quads
                .iter()
                .map(|(a, b, c, d)| [a.as_str(), b.as_str(), c.as_str(), d.as_str()])
                .collect();
            let refs: Vec<&[&str]> = slices.iter().map(|t| t.as_slice()).collect();
            let ts = u.tuple_set(4, &refs)?;
            fixed.set(rel, ts)?;
        }
    }
    Ok(())
}

/// Populates `SqlOrdFn` constant-offset shift relations (`add_<sig>_pos_<N>` /
/// `add_<sig>_neg_<N>`) with exact 64-bit integer addition/subtraction (B61).
pub(crate) fn populate_sql_ord_fn(
    fixed: &mut elinvar_engine::logic::Instance,
    u: &elinvar_engine::logic::Universe,
    relations: &[elinvar_engine::logic::Relation],
    fn_atom: &str,
    ord_shifts: &[elinvar_als::SqlOrdShift],
    ord_int_values: &BTreeMap<String, Vec<(String, i64)>>,
) -> Result<(), elinvar_engine::logic::Error> {
    for sh in ord_shifts {
        let Some(rel) = relations.iter().find(|r| {
            !r.is_changing()
                && r.arity() == 3
                && r.name().rsplit('.').next() == Some(sh.field.as_str())
        }) else {
            continue;
        };
        let pairs = ord_int_values
            .get(&sh.ordered_sig)
            .map(Vec::as_slice)
            .unwrap_or(&[]);
        if pairs.is_empty() {
            // B67: still bind an empty tuple set when the table using this
            // ordered domain has 0 rows so the evaluator never sees an unbound relation.
            let empty = u.tuple_set(3, &[])?;
            fixed.set(rel, empty)?;
            continue;
        }
        let mut triples: Vec<(String, String, String)> = Vec::with_capacity(pairs.len());
        for (atom, v) in pairs {
            let target = v.saturating_add(sh.delta);
            let target_atom = if sh.delta > 0 {
                pairs
                    .iter()
                    .find(|(_, tv)| *tv >= target)
                    .or_else(|| pairs.last())
                    .map(|(ta, _)| ta.clone())
                    .expect("non-empty pairs")
            } else {
                pairs
                    .iter()
                    .rev()
                    .find(|(_, tv)| *tv <= target)
                    .or_else(|| pairs.first())
                    .map(|(ta, _)| ta.clone())
                    .expect("non-empty pairs")
            };
            triples.push((fn_atom.to_string(), atom.clone(), target_atom));
        }
        let slices: Vec<[&str; 3]> = triples
            .iter()
            .map(|(a, b, c)| [a.as_str(), b.as_str(), c.as_str()])
            .collect();
        let refs: Vec<&[&str]> = slices.iter().map(|t| t.as_slice()).collect();
        let ts = u.tuple_set(3, &refs)?;
        fixed.set(rel, ts)?;
    }
    Ok(())
}