haematite-cli 0.21.3

The haematite command: serve a store, its door and Studio, answer MCP, query with jq, and host the store's assistant seat
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
#[path = "library_support.rs"]
mod library;
use crate::serve::query::stages_tests_support as support;

use std::collections::BTreeSet;
use std::num::NonZeroU64;

use serde_json::{Value, json};

use crate::serve::protocol::{QueryRequest, Version};

use library::{Entry, load, render, run_entry};
use support::{Fixture, TestResult, patients, request, values};

const FOUR: NonZeroU64 = NonZeroU64::MIN.saturating_add(3);

#[test]
fn library_every_shipped_entry_runs_on_the_query_fixture_store() -> TestResult {
    let groups = load()?;
    let mut fixture = Fixture::new(None, &patients())?;
    let before = fixture.run(&request("patients | limit(4)", FOUR), &[])?;
    let earlier = before.get("selection").ok_or("missing fixture selection")?;
    fixture.vectors(&[[1.0, 0.0], [4.0, 0.0], [3.0, 0.0], [2.0, 0.0]])?;
    fixture.match_chain()?;
    let current = fixture.run(&request("patients | limit(4)", FOUR), &[])?;
    assert_ne!(
        earlier,
        current.get("selection").ok_or("missing head selection")?
    );
    let expected_groups = BTreeSet::from([
        "Reading one collection",
        "Choosing fields",
        "Filtering",
        "Ordering and bounding",
        "Counting",
        "Searching by meaning",
        "Reading an earlier version",
        "Grouping",
        "Matching relationships",
        "Executing labelled matches",
        "Percentiles",
        "Reranking",
        "Searching by text",
        "Shaping records",
        "Append time windows",
    ]);
    let mut seen_groups = BTreeSet::new();
    let mut names = BTreeSet::new();
    for group in &groups {
        assert!(
            seen_groups.insert(group.group.as_str()),
            "duplicate group {}",
            group.group
        );
        assert!(!group.entries.is_empty(), "empty group {}", group.group);
        for entry in &group.entries {
            assert!(
                names.insert(entry.name.as_str()),
                "duplicate entry {}",
                entry.name
            );
            let answer = run_entry(&fixture, entry, earlier)?;
            assert_eq!(
                values(&answer)?,
                expected(&entry.name)?,
                "entry {}",
                entry.name
            );
            assert!(
                answer
                    .get("next")
                    .ok_or("missing page continuation")?
                    .is_null(),
                "entry {} is incomplete",
                entry.name
            );
            check_version(entry, &answer, &render(entry, earlier)?, &fixture)?;
        }
    }
    assert_eq!(seen_groups, expected_groups);
    assert_eq!(
        names.len(),
        27,
        "every shipped entry must have a fixture expectation"
    );
    Ok(())
}

#[test]
fn library_two_collection_shape_has_exact_fixture_values() -> TestResult {
    let mut fixture = Fixture::new(None, &patients())?;
    let groups = load()?;
    let entry = groups
        .iter()
        .flat_map(|group| &group.entries)
        .find(|entry| entry.name == "Selected fields from two collections")
        .ok_or("missing two-collection shape entry")?;
    let expected = vec![
        json!({"name":"Bea"}),
        json!({"code":"4B"}),
        json!({"code":"3A"}),
    ];
    let answer = run_entry(&fixture, entry, &json!({"branch":"main"}))?;
    assert_eq!(values(&answer)?, expected);
    assert!(answer.get("next").ok_or("missing next")?.is_null());
    fixture.match_chain()?;
    let after = run_entry(&fixture, entry, &json!({"branch":"main"}))?;
    assert_eq!(values(&after)?, expected);
    assert!(after.get("next").ok_or("missing next")?.is_null());
    Ok(())
}

#[test]
fn library_pages_keep_response_roots_out_of_request_selection() -> TestResult {
    let fixture = Fixture::new(None, &patients())?;
    let before = fixture.run(&request("patients | limit(4)", FOUR), &[])?;
    let captured = before.get("selection").ok_or("missing page selection")?;
    let roots = captured
        .get("roots")
        .and_then(Value::as_array)
        .ok_or("missing captured roots")?;
    assert_eq!(roots.len(), 4);
    let entry = sample()?;
    let ask = render(&entry, captured)?;
    let selection = serde_json::to_value(&ask.selection)?;
    let fields: BTreeSet<_> = selection
        .as_object()
        .ok_or("request selection is not an object")?
        .keys()
        .map(String::as_str)
        .collect();
    assert_eq!(fields, BTreeSet::from(["branch", "version"]));
    let answer = run_entry(&fixture, &entry, captured)?;
    assert_eq!(
        answer
            .get("selection")
            .ok_or("missing repeated selection")?,
        captured
    );
    assert_eq!(values(&answer)?, patients());
    Ok(())
}

#[test]
fn library_a_misspelt_word_fails_and_names_the_entry() -> TestResult {
    let fixture = Fixture::new(None, &patients())?;
    let entry: Entry = serde_json::from_value(json!({
        "name": "Misspelt count",
        "sentence": "Count the records in one collection.",
        "query": "${collection} | coutn",
        "change": "Choose ${collection}.",
        "defaults": {"collection": "patients"}
    }))?;
    let failure = run_entry(&fixture, &entry, &json!({"branch":"main"}))
        .err()
        .ok_or("the library accepted a misspelt word")?;
    assert!(failure.to_string().contains("Misspelt count"), "{failure}");
    assert!(failure.to_string().contains("query_parse"), "{failure}");
    Ok(())
}

#[test]
fn library_a_missing_default_fails_and_names_the_entry_and_part() -> TestResult {
    let mut entry = sample()?;
    entry.defaults.clear();
    let failure = render(&entry, &json!({"branch":"main"}))
        .err()
        .ok_or("a placeholder without a default was inserted")?;
    assert!(failure.to_string().contains("All records"), "{failure}");
    assert!(failure.to_string().contains("collection"), "{failure}");
    Ok(())
}

#[test]
fn library_an_unclosed_placeholder_fails_and_names_the_entry() -> TestResult {
    let mut entry = sample()?;
    entry.query = "${collection".to_owned();
    let failure = render(&entry, &json!({"branch":"main"}))
        .err()
        .ok_or("an unclosed placeholder was inserted")?;
    assert!(failure.to_string().contains("All records"), "{failure}");
    assert!(failure.to_string().contains("unclosed"), "{failure}");
    Ok(())
}

#[test]
fn library_a_missing_captured_version_is_refused_without_using_the_head() -> TestResult {
    let groups = load()?;
    let entry = groups
        .iter()
        .flat_map(|group| &group.entries)
        .find(|entry| entry.name == "Records at an earlier version")
        .ok_or("missing earlier-version example")?;
    let failure = render(entry, &json!({"branch":"main"}))
        .err()
        .ok_or("a missing captured version became a head reading")?;
    assert!(failure.to_string().contains(&entry.name), "{failure}");
    assert!(
        failure.to_string().contains("selection.version"),
        "{failure}"
    );
    Ok(())
}

#[test]
fn library_a_store_refusal_fails_and_names_the_entry() -> TestResult {
    let mut fixture = Fixture::new(None, &patients())?;
    fixture.scan(NonZeroU64::MIN);
    let mut entry = sample()?;
    entry.query = "collection(${collection}) | count".to_owned();
    let failure = run_entry(&fixture, &entry, &json!({"branch":"main"}))
        .err()
        .ok_or("an incomplete count was accepted")?;
    assert!(failure.to_string().contains("All records"), "{failure}");
    assert!(
        failure.to_string().contains("query_scan_limit"),
        "{failure}"
    );
    Ok(())
}

#[test]
fn library_a_worker_refusal_fails_and_names_the_entry() -> TestResult {
    let mut fixture = Fixture::new(None, &patients())?;
    fixture.no_worker();
    let failure = run_entry(&fixture, &sample()?, &json!({"branch":"main"}))
        .err()
        .ok_or("an absent worker was accepted")?;
    assert!(failure.to_string().contains("All records"), "{failure}");
    assert!(
        failure.to_string().contains("query_engine_unavailable"),
        "{failure}"
    );
    Ok(())
}

#[test]
fn library_pages_keep_the_fixture_continuation() -> TestResult {
    let fixture = Fixture::new(None, &patients())?;
    let mut ask = render(&sample()?, &json!({"branch":"main"}))?;
    ask.page.rows = NonZeroU64::MIN;
    let answer = fixture.run(&ask, &[])?;
    let next = answer
        .get("next")
        .and_then(Value::as_str)
        .ok_or("missing continuation")?;
    let token = crate::serve::query::Continuation::decode(next, &fixture.seal)?;
    assert_eq!(token.branch, "main");
    assert_eq!(token.resume.pending.collection, "patients");
    assert_eq!(values(&answer)?, vec![patients()[0].clone()]);
    ask.continuation = Some(next.to_owned());
    let second = fixture.run(&ask, &[])?;
    assert_eq!(values(&second)?, vec![patients()[1].clone()]);
    assert_eq!(second.get("selection"), answer.get("selection"));
    Ok(())
}

fn sample() -> Result<Entry, Box<dyn std::error::Error>> {
    Ok(serde_json::from_value(json!({
        "name": "All records",
        "sentence": "Read every record in one collection.",
        "query": "collection(${collection})",
        "change": "Choose ${collection}.",
        "defaults": {"collection": "\"patients\""}
    }))?)
}

fn expected(name: &str) -> Result<Vec<Value>, Box<dyn std::error::Error>> {
    let documents = patients();
    match name {
        "Labelled patients" => Ok(documents
            .into_iter()
            .map(|record| json!({"c": record}))
            .collect()),
        "Patients admitted to wards"
        | "Wards admitting patients"
        | "Bound relationship records" => Ok(vec![json!({
            "c": documents[0], "w": {"ward":"4B", "code":"4B"}
        })]),
        "Patients with ward nurses" => Ok(vec![json!({
            "c": documents[0], "w": {"ward":"4B", "code":"4B"}, "n": {"name":"Nia"}
        })]),
        "Bound labelled records" => Ok(documents
            .into_iter()
            .take(2)
            .map(|record| json!({"c": record}))
            .collect()),
        "All records"
        | "Records at an earlier version"
        | "Records in a version window"
        | "Records in an instant window" => Ok(documents),
        "Names" => Ok(vec![json!("Ada"), json!("Bea"), json!("Cy"), json!("Dee")]),
        "Records in one ward"
        | "Records containing text"
        | "Text in one field"
        | "Whole field text" => Ok(vec![
            documents[0].clone(),
            documents[2].clone(),
            documents[3].clone(),
        ]),
        "Newest records" | "Similar records" => {
            Ok(vec![documents[1].clone(), documents[2].clone()])
        }
        "Similar records after text" => Ok(vec![documents[2].clone(), documents[3].clone()]),
        "Records without text" => Ok(vec![documents[1].clone()]),
        "First records" => Ok(vec![documents[0].clone(), documents[1].clone()]),
        "Count records" | "Nearest-rank percentile" => Ok(vec![json!(4)]),
        "Reranked records" => Ok(vec![documents[1].clone(), documents[2].clone()]),
        "Selected fields" | "Selected collection fields" => Ok(vec![
            json!({"name":"Ada", "ward":"4B"}),
            json!({"name":"Bea", "ward":"3A"}),
            json!({"name":"Cy", "ward":"4B"}),
            json!({"name":"Dee", "ward":"4B"}),
        ]),
        "Selected fields from two collections" => Ok(vec![
            json!({"name":"Bea"}),
            json!({"code":"4B"}),
            json!({"code":"3A"}),
        ]),
        "Records by ward" => Ok(vec![
            json!({"key":"3A","count":1,"values":[documents[1]]}),
            json!({"key":"4B","count":3,"values":[
                documents[0], documents[2], documents[3]
            ]}),
        ]),
        other => Err(format!("entry {other} has no fixture expectation").into()),
    }
}

fn check_version(
    entry: &Entry,
    answer: &Value,
    asked: &QueryRequest,
    fixture: &Fixture,
) -> TestResult {
    let Some(version) = asked.selection.version else {
        return Ok(());
    };
    let actual = answer
        .get("selection")
        .and_then(|selection| selection.get("version"))
        .ok_or("missing page version")?;
    assert_eq!(
        serde_json::from_value::<Version>(actual.clone())?,
        version,
        "entry {} read a different version",
        entry.name
    );
    for row in answer
        .get("rows")
        .and_then(Value::as_array)
        .ok_or("missing rows")?
    {
        let origin = row.get("origin").ok_or("missing origin")?;
        let collection = origin
            .get("collection")
            .and_then(Value::as_str)
            .ok_or("missing origin collection")?;
        let id = origin
            .get("id")
            .and_then(Value::as_str)
            .ok_or("missing origin id")?;
        let written = fixture
            .written
            .get(&format!("{collection}/{id}"))
            .ok_or("origin record was never written")?;
        assert_eq!(
            origin.get("version").ok_or("missing origin version")?,
            &serde_json::to_value(written)?,
            "entry {} origin moved",
            entry.name
        );
    }
    Ok(())
}

#[test]
fn library_two_hop_chain_runs_to_exact_nonempty_fixture_values() -> TestResult {
    let groups = load()?;
    let entry = groups
        .iter()
        .flat_map(|group| &group.entries)
        .find(|entry| entry.name == "Patients with ward nurses")
        .ok_or("two-hop library entry missing")?;
    let mut fixture = Fixture::new(None, &patients())?;
    fixture.match_chain()?;
    let answer = run_entry(&fixture, entry, &json!({"branch":"main"}))?;
    assert_eq!(
        values(&answer)?,
        vec![json!({
            "c": patients()[0], "w": {"ward":"4B", "code":"4B"}, "n": {"name":"Nia"}
        })]
    );
    assert!(answer.get("next").ok_or("continuation missing")?.is_null());
    Ok(())
}

#[test]
fn library_relationship_entries_return_no_rows_without_fixture_edges() -> TestResult {
    let groups = load()?;
    let fixture = Fixture::new(None, &patients())?;
    for name in [
        "Patients admitted to wards",
        "Wards admitting patients",
        "Bound relationship records",
    ] {
        let entry = groups
            .iter()
            .flat_map(|group| &group.entries)
            .find(|entry| entry.name == name)
            .ok_or("relationship entry missing")?;
        let answer = run_entry(&fixture, entry, &json!({"branch":"main"}))?;
        assert_eq!(values(&answer)?, Vec::<Value>::new(), "{name}");
        assert!(answer.get("next").ok_or("continuation missing")?.is_null());
    }
    Ok(())
}

#[test]
fn library_inverted_and_whole_field_searches_have_exact_fixture_results() -> TestResult {
    let fixture = Fixture::new(None, &patients())?;
    let groups = load()?;
    for (name, expected) in [
        ("Records without text", vec![patients()[1].clone()]),
        (
            "Whole field text",
            vec![
                patients()[0].clone(),
                patients()[2].clone(),
                patients()[3].clone(),
            ],
        ),
    ] {
        let entry = groups
            .iter()
            .flat_map(|group| &group.entries)
            .find(|entry| entry.name == name)
            .ok_or("missing new rg library entry")?;
        let answer = run_entry(&fixture, entry, &json!({"branch":"main"}))?;
        assert_eq!(values(&answer)?, expected, "{name}");
        assert!(answer.get("next").ok_or("missing next")?.is_null());
    }
    Ok(())
}