haematite-cli 0.21.0

The haematite command: serve a store, its door and Studio, answer MCP, query with jq, and host the store's assistant seat
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
use std::io;
use std::num::{NonZeroU32, NonZeroUsize};
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{self, TryRecvError};
use std::time::Duration;

use haematite::db::DatabaseConfig;
use haematite::store::NodeCacheBudget;
use serde_json::{Value, json, value::RawValue};

use super::{ToolResult, dispatch};
use crate::mcp::{rpc, stdio, types};
use crate::serve::{frame, protocol, service::Service, storage::Storage};

type TestResult = Result<(), Box<dyn std::error::Error>>;
const CAP: NonZeroU32 = NonZeroU32::MIN.saturating_add(1_048_575);
const ROWS: NonZeroU32 = NonZeroU32::MIN.saturating_add(63);

pub(super) struct Fixture {
    pub(super) sender: stdio::NativeSender,
    service: Arc<Service>,
    socket: PathBuf,
    stop: mpsc::Sender<()>,
    task: std::thread::JoinHandle<io::Result<()>>,
    calls: Arc<AtomicUsize>,
    directory: tempfile::TempDir,
}

impl Fixture {
    pub(super) fn start() -> Result<Self, Box<dyn std::error::Error>> {
        let directory = tempfile::tempdir()?;
        let storage = Storage::create(
            DatabaseConfig {
                data_dir: directory.path().join("database"),
                shard_count: 1,
                distributed: None,
                executor_threads: Some(1),
                node_cache_budget: Some(NodeCacheBudget::Unlimited),
                retention: haematite::Retention::KeepAll,
            },
            NodeCacheBudget::Unlimited,
            fixture_long_wait_interval(),
        )?;
        let service = Arc::new(Service::new(storage, ROWS)?);
        let socket = directory.path().join("service.sock");
        let listener = UnixListener::bind(&socket)?;
        let (stop, stopped) = mpsc::channel();
        let calls = Arc::new(AtomicUsize::new(0));
        let served = Arc::clone(&service);
        let requested = Arc::clone(&calls);
        let task = std::thread::spawn(move || {
            loop {
                let (mut stream, _) = listener.accept()?;
                match stopped.try_recv() {
                    Ok(()) | Err(TryRecvError::Disconnected) => return Ok(()),
                    Err(TryRecvError::Empty) => {}
                }
                while let Some(bytes) = frame::read(&mut stream, CAP)? {
                    let request: protocol::Request =
                        serde_json::from_slice(&bytes).map_err(io::Error::other)?;
                    let response = if matches!(&request.operation, protocol::Operation::Hello(_)) {
                        // The store's hello (BUSYSHARDNODEADLINE-001 Amendment 17):
                        // its version, the typed receipt capability, its limits.
                        json!({"id":request.id,"result":{
                            "protocol":protocol::PROTOCOL,
                            "capabilities":[protocol::RECEIPT_CAPABILITY],
                            "max_frame":CAP,"max_page":ROWS,
                        }})
                    } else {
                        requested.fetch_add(1, Ordering::SeqCst);
                        let budget = NonZeroUsize::new(1_048_576)
                            .ok_or_else(|| io::Error::other("fixture budget is zero"))?;
                        match served.dispatch_text(request.operation, budget) {
                            Ok(raw) => json!({"id":request.id,"result":raw}),
                            Err(refusal) => json!({"id":request.id,"error":refusal}),
                        }
                    };
                    frame::write(
                        &mut stream,
                        &serde_json::to_vec(&response).map_err(io::Error::other)?,
                        CAP,
                    )?;
                }
            }
        });
        let sender = stdio::NativeSender::new(socket.clone(), Duration::from_secs(1));
        Ok(Self {
            sender,
            service,
            socket,
            stop,
            task,
            calls,
            directory,
        })
    }

    pub(super) fn current(&self) -> Result<protocol::Version, Box<dyn std::error::Error>> {
        let answer =
            self.service
                .dispatch(protocol::Operation::StoreStats(protocol::StoreRead {
                    selection: protocol::Selection {
                        branch: "main".to_owned(),
                        version: None,
                    },
                }))?;
        Ok(serde_json::from_value(
            answer["selection"]["version"].clone(),
        )?)
    }

    pub(super) fn requests(&self) -> usize {
        self.calls.load(Ordering::SeqCst)
    }

    pub(super) fn mutate(
        &self,
        branch: &str,
        request_id: &str,
        change: protocol::Change,
    ) -> Result<protocol::Version, Box<dyn std::error::Error>> {
        let capture =
            self.service
                .dispatch(protocol::Operation::StoreStats(protocol::StoreRead {
                    selection: protocol::Selection {
                        branch: branch.to_owned(),
                        version: None,
                    },
                }))?;
        let answer = self
            .service
            .dispatch(protocol::Operation::Mutate(protocol::Mutation {
                request_id: request_id.to_owned(),
                branch: branch.to_owned(),
                expected: serde_json::from_value(capture["selection"]["version"].clone())?,
                change,
            }))?;
        Ok(serde_json::from_value(answer["version"].clone())?)
    }

    pub(super) fn fork(&self, name: &str) -> TestResult {
        self.mutate(
            "main",
            &format!("fork-{name}"),
            protocol::Change::Fork(protocol::Fork {
                name: name.to_owned(),
                from: self.current()?,
            }),
        )?;
        Ok(())
    }

    fn call(
        &mut self,
        name: &str,
        mut fields: Value,
    ) -> Result<ToolResult, Box<dyn std::error::Error>> {
        let expected = self.current()?;
        let object = fields
            .as_object_mut()
            .ok_or_else(|| io::Error::other("input must be an object"))?;
        object.insert(
            "request_id".to_owned(),
            Value::String(format!("request-{name}")),
        );
        object.insert("branch".to_owned(), Value::String("main".to_owned()));
        object.insert("expected".to_owned(), serde_json::to_value(expected)?);
        let call = rpc::ToolCall {
            metadata: None,
            name: name.to_owned(),
            arguments: serde_json::value::to_raw_value(&fields)?,
        };
        let before = self.calls.load(Ordering::SeqCst);
        let result = dispatch(&mut self.sender, &call)?;
        assert_eq!(self.calls.load(Ordering::SeqCst), before + 1);
        Ok(result)
    }

    pub(super) fn seed(&self) -> TestResult {
        for change in [
            protocol::Change::Collection(protocol::CollectionWrite {
                collection: "records".to_owned(),
                schema: None,
            }),
            protocol::Change::PutMany(protocol::DocumentImport {
                collection: "records".to_owned(),
                documents: vec![
                    protocol::ImportedDocument {
                        document_id: "a".to_owned(),
                        document: RawValue::from_string(r#"{"n":1}"#.to_owned())?,
                    },
                    protocol::ImportedDocument {
                        document_id: "b".to_owned(),
                        document: RawValue::from_string(r#"{"n":2}"#.to_owned())?,
                    },
                ],
            }),
            protocol::Change::RelationPut(protocol::Relation {
                relation: "links".to_owned(),
                from_collection: "records".to_owned(),
                to_collection: "records".to_owned(),
                cardinality: protocol::Cardinality::ManyToMany,
            }),
        ] {
            self.service
                .dispatch(protocol::Operation::Mutate(protocol::Mutation {
                    request_id: format!("seed-{}", self.current()?.sequence),
                    branch: "main".to_owned(),
                    expected: self.current()?,
                    change,
                }))?;
        }
        Ok(())
    }

    pub(super) fn finish(self) -> TestResult {
        drop(self.sender);
        self.stop.send(())?;
        drop(UnixStream::connect(&self.socket)?);
        self.task
            .join()
            .map_err(|_| io::Error::other("fixture service task panicked"))??;
        drop(self.service);
        self.directory.close()?;
        Ok(())
    }
}

fn successful(result: &ToolResult, name: &str) -> TestResult {
    assert!(!result.is_error, "{}", result.structured_content.get());
    let schema = crate::mcp::schema::tools()
        .into_iter()
        .find(|tool| tool.name == name)
        .ok_or_else(|| io::Error::other("tool schema missing"))?;
    let validator = jsonschema::validator_for(schema.output_schema.as_value())?;
    let output: Value = serde_json::from_str(result.structured_content.get())?;
    validator
        .validate(&output)
        .map_err(|error| io::Error::other(error.to_string()))?;
    Ok(())
}

#[test]
fn define_collection_uses_one_served_mutation_and_typed_output() -> TestResult {
    let mut fixture = Fixture::start()?;
    let result = fixture.call(
        "define_collection",
        json!({"collection":"records","schema":null}),
    )?;
    successful(&result, "define_collection")?;
    let answer =
        fixture
            .service
            .dispatch(protocol::Operation::Collections(protocol::CollectionPage {
                selection: protocol::Selection {
                    branch: "main".to_owned(),
                    version: None,
                },
                after: None,
                limit: ROWS,
            }))?;
    assert_eq!(answer["entries"][0]["name"], "records");
    fixture.finish()
}

#[test]
fn put_records_is_atomic_and_keeps_raw_number_spelling() -> TestResult {
    let mut fixture = Fixture::start()?;
    fixture.seed()?;
    let raw: Box<RawValue> =
        serde_json::from_str(r#"{"n":1e2,"identity":18446744073709551616001}"#)?;
    let expected = serde_json::to_string(&fixture.current()?)?;
    let arguments = format!(
        r#"{{"request_id":"request-put_records","branch":"main","expected":{expected},"collection":"records","records":[{{"document_id":"large","document":{}}},{{"document_id":"second","document":{{"n":3}}}}]}}"#,
        raw.get(),
    );
    let call = rpc::ToolCall {
        metadata: None,
        name: "put_records".to_owned(),
        arguments: RawValue::from_string(arguments)?,
    };
    let before = fixture.requests();
    let result = dispatch(&mut fixture.sender, &call)?;
    assert_eq!(fixture.requests(), before + 1);
    successful(&result, "put_records")?;
    let answer = fixture
        .service
        .dispatch(protocol::Operation::Get(protocol::DocumentRead {
            selection: protocol::Selection {
                branch: "main".to_owned(),
                version: None,
            },
            collection: "records".to_owned(),
            document_id: "large".to_owned(),
        }))?;
    assert_eq!(
        answer["document"]["raw_json"],
        r#"{"n":1e2,"identity":18446744073709551616001}"#
    );
    let second = fixture
        .service
        .dispatch(protocol::Operation::Get(protocol::DocumentRead {
            selection: protocol::Selection {
                branch: "main".to_owned(),
                version: None,
            },
            collection: "records".to_owned(),
            document_id: "second".to_owned(),
        }))?;
    assert_eq!(second["document"]["raw_json"], r#"{"n":3}"#);
    fixture.finish()
}

#[test]
fn delete_record_uses_served_delete_and_returns_the_receipt_version() -> TestResult {
    let mut fixture = Fixture::start()?;
    fixture.seed()?;
    let result = fixture.call(
        "delete_record",
        json!({"record":{"collection":"records","document_id":"a"}}),
    )?;
    successful(&result, "delete_record")?;
    let output: types::DeleteRecordOutput = serde_json::from_str(result.structured_content.get())?;
    assert_eq!(output.version.0, fixture.current()?);
    let answer = fixture
        .service
        .dispatch(protocol::Operation::Get(protocol::DocumentRead {
            selection: protocol::Selection {
                branch: "main".to_owned(),
                version: None,
            },
            collection: "records".to_owned(),
            document_id: "a".to_owned(),
        }))?;
    assert!(answer["document"].is_null());
    fixture.finish()
}

fn endpoints() -> Value {
    json!({"relation":"links","from":{"collection":"records","document_id":"a"},"to":{"collection":"records","document_id":"b"}})
}

#[test]
fn link_records_passes_both_endpoints_and_properties_to_the_service() -> TestResult {
    let mut fixture = Fixture::start()?;
    fixture.seed()?;
    let mut fields = endpoints();
    fields["properties"] = json!({"label":"edge"});
    let result = fixture.call("link_records", fields)?;
    successful(&result, "link_records")?;
    let answer = fixture
        .service
        .dispatch(protocol::Operation::EdgesOut(protocol::EdgePage {
            selection: protocol::Selection {
                branch: "main".to_owned(),
                version: None,
            },
            node: protocol::Node {
                collection: "records".to_owned(),
                document_id: "a".to_owned(),
            },
            relation: None,
            after: None,
            limit: ROWS,
        }))?;
    assert_eq!(answer["edges"][0]["properties"]["label"], "edge");
    assert_eq!(answer["edges"][0]["from"]["document_id"], "a");
    assert_eq!(answer["edges"][0]["to"]["document_id"], "b");
    fixture.finish()
}

#[test]
fn unlink_records_removes_only_the_named_served_edge() -> TestResult {
    let mut fixture = Fixture::start()?;
    fixture.seed()?;
    for destination in ["a", "b"] {
        fixture
            .service
            .dispatch(protocol::Operation::Mutate(protocol::Mutation {
                request_id: format!("seed-edge-{destination}"),
                branch: "main".to_owned(),
                expected: fixture.current()?,
                change: protocol::Change::EdgePut(protocol::Edge {
                    relation: "links".to_owned(),
                    from: protocol::Node {
                        collection: "records".to_owned(),
                        document_id: "a".to_owned(),
                    },
                    to: protocol::Node {
                        collection: "records".to_owned(),
                        document_id: destination.to_owned(),
                    },
                    properties: json!({}),
                }),
            }))?;
    }
    let result = fixture.call("unlink_records", endpoints())?;
    successful(&result, "unlink_records")?;
    let answer = fixture
        .service
        .dispatch(protocol::Operation::EdgesOut(protocol::EdgePage {
            selection: protocol::Selection {
                branch: "main".to_owned(),
                version: None,
            },
            node: protocol::Node {
                collection: "records".to_owned(),
                document_id: "a".to_owned(),
            },
            relation: None,
            after: None,
            limit: ROWS,
        }))?;
    assert_eq!(answer["edges"].as_array().map(Vec::len), Some(1));
    assert_eq!(answer["edges"][0]["to"]["document_id"], "a");
    fixture.finish()
}

#[test]
fn create_branch_uses_the_selected_from_version_and_reports_destination() -> TestResult {
    let mut fixture = Fixture::start()?;
    fixture.seed()?;
    let from = fixture.current()?;
    let result = fixture.call("create_branch", json!({"name":"feature","from":from}))?;
    successful(&result, "create_branch")?;
    let output: types::CreateBranchOutput = serde_json::from_str(result.structured_content.get())?;
    assert_eq!(output.branch, "feature");
    assert_eq!(output.request_id, "request-create_branch");
    let answer =
        fixture
            .service
            .dispatch(protocol::Operation::Collections(protocol::CollectionPage {
                selection: protocol::Selection {
                    branch: "feature".to_owned(),
                    version: Some(output.version.0),
                },
                after: None,
                limit: ROWS,
            }))?;
    assert_eq!(answer["entries"][0]["name"], "records");
    fixture.finish()
}

const fn fixture_long_wait_interval() -> std::time::Duration {
    std::time::Duration::from_secs(1)
}