mentat_script 1.17.2

Backend-independent mino mentat.store/* scripting glue for Mentat
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
//! The Datomic-model test suite for the `mentat.store/*` scripting surface,
//! written once and run against every [`ScriptBackend`] (plan § 1.19).
//!
//! Each function takes a `&mut mino_rs::Interpreter` that already has the store
//! prims installed (via [`crate::install`]) over some backend. The `mentat`
//! crate and `pg_mentat` each build such an interpreter over their real
//! storage and call these; `crates/script/tests/model.rs` runs them against an
//! in-memory fake. One suite, three backends — so the two real backends stop
//! drifting.
//!
//! This module is compiled into the library (not gated) so downstream test
//! crates can depend on it without a dev-dependency dance; it pulls in nothing
//! but the interpreter it is handed.

use mino_rs::Interpreter;

/// Seed a store-installed interpreter with the schema and Alice, binding `c` to
/// the conn handle. Backend-agnostic: it only evals the shared script.
pub fn seed(it: &mut Interpreter) {
    it.eval("(def c (mentat.store/open))").expect("open");
    it.eval_to_string(
        "(mentat.store/transact c \
           [{:db/ident :person/name :db/valueType :db.type/string \
             :db/cardinality :db.cardinality/one}])",
    )
    .expect("schema transact");
    it.eval_to_string("(mentat.store/transact c [{:person/name \"Alice\"}])")
        .expect("data transact");
}

/// The eid of the person named `name`, as a scalar-query result string.
pub fn eid_of(it: &mut Interpreter, name: &str) -> String {
    it.eval_to_string(&format!(
        "(mentat.store/q (mentat.store/db c) '[:find ?e . :where [?e :person/name \"{name}\"]])"
    ))
    .expect("eid query")
}

/// The first synthetic tx id (Mentat's `TX0`); real basis ids exceed it.
pub const TX0: i64 = 0x1000_0000;

pub fn db_is_an_immutable_value_not_the_conn(it: &mut Interpreter) {
    seed(it);
    assert_eq!(it.eval_to_string("c").unwrap(), "1");
    let db = it.eval_to_string("(mentat.store/db c)").unwrap();
    assert!(db.contains(":mentat.store/db true"), "{db}");
    assert!(db.contains(":mentat.store/basis-tx"), "{db}");
    assert!(db.contains(":mentat.store/conn 1"), "{db}");
    assert_ne!(db, "1");
    let basis = it
        .eval_to_string("(:mentat.store/basis-tx (mentat.store/db c))")
        .unwrap();
    assert!(basis.parse::<i64>().unwrap() > TX0, "basis {basis}");
}

pub fn q_takes_a_db_value(it: &mut Interpreter) {
    seed(it);
    assert_eq!(
        it.eval_to_string(
            "(mentat.store/q (mentat.store/db c) '[:find ?n :where [?e :person/name ?n]])"
        )
        .unwrap(),
        "#{[\"Alice\"]}"
    );
    assert_eq!(
        it.eval_to_string("(mentat.store/q c '[:find ?n :where [?e :person/name ?n]])")
            .unwrap(),
        "#{[\"Alice\"]}"
    );
}

pub fn pull_returns_a_map(it: &mut Interpreter) {
    seed(it);
    let eid = eid_of(it, "Alice");
    let pulled = it
        .eval_to_string(&format!(
            "(mentat.store/pull (mentat.store/db c) {eid} [:person/name])"
        ))
        .unwrap();
    // A keyword-keyed map carrying the pulled value. (The exact map shape is
    // backend-specific — pg may include extra keys — so assert the content.)
    assert!(pulled.starts_with('{'), "pull -> map: {pulled}");
    assert!(pulled.contains(":person/name \"Alice\""), "pull: {pulled}");
}

pub fn entity_returns_an_entity_map(it: &mut Interpreter) {
    seed(it);
    let eid = eid_of(it, "Alice");
    let ent = it
        .eval_to_string(&format!("(mentat.store/entity (mentat.store/db c) {eid})"))
        .unwrap();
    assert!(ent.contains(&format!(":db/id {eid}")), "{ent}");
    assert!(ent.contains(":person/name \"Alice\""), "{ent}");
}

pub fn read_returns_the_scalar(it: &mut Interpreter) {
    seed(it);
    let eid = eid_of(it, "Alice");
    assert_eq!(
        it.eval_to_string(&format!(
            "(mentat.store/read (mentat.store/db c) {eid} :person/name)"
        ))
        .unwrap(),
        "\"Alice\""
    );
}

pub fn datoms_returns_tuples(it: &mut Interpreter) {
    seed(it);
    let ds = it
        .eval_to_string("(mentat.store/datoms (mentat.store/db c))")
        .unwrap();
    // A vector of tuples that includes the Alice name assertion's value. (The
    // attribute place is a keyword on SQLite and an entid on pg — a real
    // backend difference — so assert only the portable facts.)
    assert!(ds.starts_with('['), "datoms: {ds}");
    assert!(
        ds.contains("\"Alice\""),
        "datoms should include Alice: {ds}"
    );
}

pub fn with_is_speculative_and_does_not_commit(it: &mut Interpreter) {
    seed(it);
    let before = it
        .eval_to_string("(mentat.store/q c '[:find ?n :where [?e :person/name ?n]])")
        .unwrap();
    assert_eq!(before, "#{[\"Alice\"]}");
    let with_result = it
        .eval_to_string("(mentat.store/with (mentat.store/db c) [{:person/name \"Bob\"}])")
        .unwrap();
    assert!(
        with_result.contains(":mentat.store/db-after"),
        "{with_result}"
    );
    assert!(
        with_result.contains(":mentat.store/tx-report"),
        "{with_result}"
    );
    let basis_now: i64 = it
        .eval_to_string("(:mentat.store/basis-tx (mentat.store/db c))")
        .unwrap()
        .parse()
        .unwrap();
    let db_after_basis: i64 = it
        .eval_to_string(
            "(:mentat.store/basis-tx (:mentat.store/db-after \
               (mentat.store/with (mentat.store/db c) [{:person/name \"Bob\"}])))",
        )
        .unwrap()
        .parse()
        .unwrap();
    assert!(db_after_basis > basis_now, "{db_after_basis} > {basis_now}");
    let after = it
        .eval_to_string(
            "(mentat.store/q (mentat.store/db c) '[:find ?n :where [?e :person/name ?n]])",
        )
        .unwrap();
    assert_eq!(after, "#{[\"Alice\"]}", "with must not commit");
}

pub fn as_of_and_since_reflect_the_basis(it: &mut Interpreter) {
    seed(it);
    let basis_alice: i64 = it
        .eval_to_string("(:mentat.store/basis-tx (mentat.store/db c))")
        .unwrap()
        .parse()
        .unwrap();
    it.eval_to_string("(mentat.store/transact c [{:person/name \"Bob\"}])")
        .unwrap();
    let basis_bob: i64 = it
        .eval_to_string("(:mentat.store/basis-tx (mentat.store/db c))")
        .unwrap()
        .parse()
        .unwrap();
    assert!(basis_bob > basis_alice);

    let as_of_alice = it
        .eval_to_string(&format!(
            "(mentat.store/datoms (mentat.store/as-of (mentat.store/db c) {basis_alice}))"
        ))
        .unwrap();
    assert!(as_of_alice.contains("Alice"), "{as_of_alice}");
    assert!(!as_of_alice.contains("Bob"), "{as_of_alice}");

    let as_of_bob = it
        .eval_to_string(&format!(
            "(mentat.store/datoms (mentat.store/as-of (mentat.store/db c) {basis_bob}))"
        ))
        .unwrap();
    assert!(
        as_of_bob.contains("Alice") && as_of_bob.contains("Bob"),
        "{as_of_bob}"
    );

    let since_alice = it
        .eval_to_string(&format!(
            "(mentat.store/datoms (mentat.store/since (mentat.store/db c) {basis_alice}))"
        ))
        .unwrap();
    assert!(since_alice.contains("Bob"), "{since_alice}");
    assert!(!since_alice.contains("Alice"), "{since_alice}");

    let as_of_db = it
        .eval_to_string(&format!(
            "(mentat.store/as-of (mentat.store/db c) {basis_alice})"
        ))
        .unwrap();
    assert!(
        as_of_db.contains(&format!(":mentat.store/as-of {basis_alice}")),
        "{as_of_db}"
    );
    let since_db = it
        .eval_to_string(&format!(
            "(mentat.store/since (mentat.store/db c) {basis_alice})"
        ))
        .unwrap();
    assert!(
        since_db.contains(&format!(":mentat.store/since {basis_alice}")),
        "{since_db}"
    );
}

/// Issue #328: `q` against an as-of / since db value runs the query on that
/// basis (temporal Datalog), on every backend, instead of erroring.
pub fn q_runs_against_as_of_and_since(it: &mut Interpreter) {
    seed(it);
    let basis_alice: i64 = it
        .eval_to_string("(:mentat.store/basis-tx (mentat.store/db c))")
        .unwrap()
        .parse()
        .unwrap();
    it.eval_to_string("(mentat.store/transact c [{:person/name \"Bob\"}])")
        .unwrap();

    let names = "'[:find ?n :where [?e :person/name ?n]]";
    let now = it
        .eval_to_string(&format!("(mentat.store/q (mentat.store/db c) {names})"))
        .unwrap();
    assert!(now.contains("Alice") && now.contains("Bob"), "{now}");

    let then = it
        .eval_to_string(&format!(
            "(mentat.store/q (mentat.store/as-of (mentat.store/db c) {basis_alice}) {names})"
        ))
        .unwrap();
    assert_eq!(then, "#{[\"Alice\"]}", "as-of must hide later facts");

    // q with :in inputs works on a historical basis too.
    let with_in = it
        .eval_to_string(&format!(
            "(mentat.store/q (mentat.store/as-of (mentat.store/db c) {basis_alice}) \
             '[:find ?e :in $ ?n :where [?e :person/name ?n]] \"Bob\")"
        ))
        .unwrap();
    assert_eq!(
        with_in, "#{}",
        "Bob did not exist as of Alice's basis: {with_in}"
    );
}

pub fn tx_report_has_the_datomic_shape(it: &mut Interpreter) {
    seed(it);
    let report = it
        .eval_to_string("(mentat.store/transact c [{:person/name \"Carol\"}])")
        .unwrap();
    assert!(report.contains(":mentat.store/tx-id"), "{report}");
    assert!(report.contains(":mentat.store/tempids"), "{report}");
    assert!(report.contains(":mentat.store/db-after"), "{report}");
}

/// The inst/uuid VALUE BUILDERS emit values that round-trip through the mino
/// reader. Backend-independent (no interpreter needed).
pub fn inst_and_uuid_builders_round_trip_through_the_reader() {
    use mino_rs::printer::print_str;
    use mino_rs::reader::read_one;
    let uuid = crate::values::uuid_value("12345678-1234-5678-1234-567812345678");
    assert_eq!(
        print_str(&uuid),
        "#uuid \"12345678-1234-5678-1234-567812345678\""
    );
    let inst = crate::values::inst_value("2017-01-01T00:00:00Z");
    assert_eq!(
        print_str(&inst),
        "(clojure.instant/read-instant-date \"2017-01-01T00:00:00Z\")"
    );
    for v in [uuid, inst] {
        let (v2, _) = read_one(&print_str(&v)).unwrap();
        assert_eq!(print_str(&v), print_str(&v2));
    }
}

// ---------------------------------------------------------------------------
// :in inputs, history, cas / retractEntity (Datomic-like layer, 1.10).
// ---------------------------------------------------------------------------

/// `(q db query arg ...)`: Datomic's `:in $ ?x` with the args after the query.
/// A scalar input filters the value place. Runs on every backend (the fake
/// understands `:in $ ?x` and `:in $ [?x ...]` on one clause).
pub fn q_takes_in_inputs(it: &mut Interpreter) {
    seed(it);
    it.eval_to_string("(mentat.store/transact c [{:person/name \"Bob\"}])")
        .unwrap();
    assert_eq!(
        it.eval_to_string(
            "(mentat.store/q (mentat.store/db c) \
               '[:find ?n :in $ ?n :where [?e :person/name ?n]] \"Bob\")"
        )
        .unwrap(),
        "#{[\"Bob\"]}"
    );
    // A collection input binds any of its values.
    let both = it
        .eval_to_string(
            "(mentat.store/q (mentat.store/db c) \
               '[:find ?n :in $ [?n ...] :where [?e :person/name ?n]] [\"Alice\" \"Bob\" \"Zed\"])",
        )
        .unwrap();
    assert!(
        both.contains("\"Alice\"") && both.contains("\"Bob\"") && !both.contains("Zed"),
        "{both}"
    );
    // A missing input is an error, not a silently unbound variable.
    assert!(it
        .eval(
            "(mentat.store/q (mentat.store/db c) '[:find ?n :in $ ?n :where [?e :person/name ?n]])"
        )
        .is_err());
}

/// Seed people with ages, bound to `c`. Real engines only (the fake is a toy).
fn seed_people(it: &mut Interpreter) {
    it.eval("(def c (mentat.store/open))").expect("open");
    it.eval_to_string(
        "(mentat.store/transact c \
           [{:db/ident :person/name :db/valueType :db.type/string \
             :db/cardinality :db.cardinality/one :db/unique :db.unique/identity :db/index true} \
            {:db/ident :person/age :db/valueType :db.type/long :db/cardinality :db.cardinality/one} \
            {:db/ident :person/friend :db/valueType :db.type/ref :db/cardinality :db.cardinality/many}])",
    )
    .expect("schema");
    it.eval_to_string(
        "(mentat.store/transact c \
           [{:db/id \"a\" :person/name \"Alice\" :person/age 30 :person/friend \"b\"} \
            {:db/id \"b\" :person/name \"Bob\" :person/age 40}])",
    )
    .expect("people");
}

/// Mixed inputs on a real engine: a ref-typed scalar, a collection, and a
/// relation, bound by position; an entity-position integer is a ref.
pub fn q_mixed_inputs(it: &mut Interpreter) {
    seed_people(it);
    let bob = it
        .eval_to_string(
            "(mentat.store/q (mentat.store/db c) '[:find ?e . :where [?e :person/name \"Bob\"]])",
        )
        .unwrap();
    assert_eq!(
        it.eval_to_string(&format!(
            "(mentat.store/q (mentat.store/db c) \
               '[:find ?n . :in $ ?f [?a ...] :where [?e :person/friend ?f] [?e :person/age ?a] [?e :person/name ?n]] \
               {bob} [30 31])"
        ))
        .unwrap(),
        "\"Alice\""
    );
    let rel = it
        .eval_to_string(
            "(mentat.store/q (mentat.store/db c) \
               '[:find ?n :in $ [[?n ?a]] :where [?e :person/name ?n] [?e :person/age ?a]] \
               [[\"Alice\" 30] [\"Bob\" 41]])",
        )
        .unwrap();
    assert_eq!(rel, "#{[\"Alice\"]}");
}

/// The eid of a seeded person, as a number string.
fn person(it: &mut Interpreter, name: &str) -> String {
    it.eval_to_string(&format!(
        "(mentat.store/q (mentat.store/db c) '[:find ?e . :where [?e :person/name \"{name}\"]])"
    ))
    .unwrap()
}

/// History patterns: `[?e ?a ?v ?tx ?added]` sees retractions (`false`) and
/// assertions (`true`) across transactions.
pub fn history_patterns_see_added(it: &mut Interpreter) {
    seed_people(it);
    let alice = person(it, "Alice");
    it.eval_to_string(&format!(
        "(mentat.store/transact c [[:db/add {alice} :person/age 31]])"
    ))
    .unwrap();
    let h = it
        .eval_to_string(
            "(mentat.store/q (mentat.store/db c) \
               '[:find ?v ?added :where [?e :person/age ?v ?tx ?added] [?e :person/name \"Alice\"]])",
        )
        .unwrap();
    for want in ["[30 true]", "[30 false]", "[31 true]"] {
        assert!(h.contains(want), "history should contain {want}: {h}");
    }
}

/// `:db/cas` swaps only from the expected old value; `:db/retractEntity`
/// removes every datom of the entity AND every ref pointing at it (Datomic's
/// semantics; issue #326). Both accept a lookup ref `[:unique/attr v]` in the
/// entity place (issue #327).
pub fn cas_and_retract_entity(it: &mut Interpreter) {
    seed_people(it);
    let (alice, bob) = (person(it, "Alice"), person(it, "Bob"));
    let age = "(mentat.store/q (mentat.store/db c) \
               '[:find ?a . :where [?e :person/name \"Alice\"] [?e :person/age ?a]])";
    it.eval_to_string(&format!(
        "(mentat.store/transact c [[:db/cas {alice} :person/age 30 31]])"
    ))
    .expect("cas from the right value");
    assert_eq!(it.eval_to_string(age).unwrap(), "31");
    assert!(
        it.eval(&format!(
            "(mentat.store/transact c [[:db/cas {alice} :person/age 30 32]])"
        ))
        .is_err(),
        "cas from a stale value must fail"
    );
    assert_eq!(it.eval_to_string(age).unwrap(), "31");

    // A lookup ref names Alice in the entity place of cas.
    it.eval_to_string(
        "(mentat.store/transact c [[:db/cas [:person/name \"Alice\"] :person/age 31 32]])",
    )
    .expect("cas via a lookup ref");
    assert_eq!(it.eval_to_string(age).unwrap(), "32");

    // Alice -> :person/friend -> Bob is an inbound ref to Bob.
    let friends = "(mentat.store/q (mentat.store/db c) \
                   '[:find ?f . :where [?e :person/name \"Alice\"] [?e :person/friend ?f]])";
    assert_eq!(it.eval_to_string(friends).unwrap(), bob);

    // retractEntity via a lookup ref.
    it.eval_to_string("(mentat.store/transact c [[:db/retractEntity [:person/name \"Bob\"]]])")
        .expect("retractEntity via a lookup ref");
    assert_eq!(person(it, "Bob"), "nil");
    // Bob's own datoms are all gone:
    assert_eq!(
        it.eval_to_string(&format!(
            "(mentat.store/q (mentat.store/db c) '[:find ?a . :where [{bob} :person/age ?a]])"
        ))
        .unwrap(),
        "nil"
    );
    // ...and so is the ref TO him, while Alice herself remains.
    assert_eq!(
        it.eval_to_string(friends).unwrap(),
        "nil",
        "inbound ref retracted"
    );
    assert_eq!(person(it, "Alice"), alice);
}

/// User-defined transaction functions (issues #325, #333): an ident carrying
/// `:db/fn` (mino source of `(fn [db & args] ...)` returning tx-data) is
/// invoked as `[:my/fn arg ...]` inside a transaction, on every backend.
pub fn transaction_functions(it: &mut Interpreter) {
    seed_people(it);
    let age = |it: &mut Interpreter, who: &str| {
        it.eval_to_string(&format!(
            "(mentat.store/q (mentat.store/db c) \
               '[:find ?a . :where [?e :person/name \"{who}\"] [?e :person/age ?a]])"
        ))
        .unwrap()
    };

    // Install: a fn that reads the db (as of the start of the tx) with q and
    // returns a lookup-ref cas, so a stale call aborts.
    it.eval_to_string(
        "(mentat.store/transact c \
           [{:db/ident :person/birthday \
             :db/fn \"(fn [db who] \
                        (let [a (ffirst (mentat.store/q db \
                                  '[:find ?a :in $ ?n :where [?e :person/name ?n] [?e :person/age ?a]] \
                                  who))] \
                          [[:db/cas [:person/name who] :person/age a (inc a)]]))\"}])",
    )
    .expect("install :person/birthday");

    it.eval_to_string("(mentat.store/transact c [[:person/birthday \"Alice\"]])")
        .expect("invoke");
    assert_eq!(age(it, "Alice"), "31");

    // Spliced with other tx-data in the same transaction, and nested: a fn
    // that returns a call to another fn.
    it.eval_to_string(
        "(mentat.store/transact c \
           [{:db/ident :person/two-birthdays \
             :db/fn \"(fn [db who] [[:person/birthday who]])\"}])",
    )
    .expect("install nested fn");
    it.eval_to_string(
        "(mentat.store/transact c [[:person/two-birthdays \"Bob\"] {:person/name \"Carol\" :person/age 7}])",
    )
    .expect("nested invoke");
    assert_eq!(age(it, "Bob"), "41");
    assert_eq!(age(it, "Carol"), "7");

    // A fn that throws aborts the whole transaction, with the fn named.
    it.eval_to_string(
        "(mentat.store/transact c [{:db/ident :person/boom :db/fn \"(fn [db] (throw (ex-info \\\"nope\\\" {})))\"}])",
    )
    .expect("install :person/boom");
    let err = it
        .eval_to_string(
            "(mentat.store/transact c [[:person/boom] {:person/name \"Dan\" :person/age 1}])",
        )
        .expect_err("a throwing tx-fn aborts the tx");
    assert!(
        err.contains("txfn-error") && err.contains(":person/boom"),
        "{err}"
    );
    assert_eq!(age(it, "Dan"), "nil", "nothing from the aborted tx");

    // Self-recursion is bounded.
    it.eval_to_string(
        "(mentat.store/transact c [{:db/ident :person/forever :db/fn \"(fn [db] [[:person/forever]])\"}])",
    )
    .expect("install :person/forever");
    let err = it
        .eval_to_string("(mentat.store/transact c [[:person/forever]])")
        .expect_err("unbounded recursion");
    assert!(err.contains("txfn-depth"), "{err}");

    // Sandboxed: no host filesystem.
    it.eval_to_string(
        "(mentat.store/transact c [{:db/ident :person/escape :db/fn \"(fn [db] (slurp \\\"/etc/passwd\\\") [])\"}])",
    )
    .expect("install :person/escape");
    let err = it
        .eval_to_string("(mentat.store/transact c [[:person/escape]])")
        .expect_err("slurp must be unavailable");
    assert!(err.contains("txfn-error"), "{err}");
}