haematite-cli 0.21.7

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
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
#![forbid(unsafe_code)]
#![cfg(unix)]

#[path = "../../haematite/tests/common/runtime_options.rs"]
mod runtime_options;

use runtime_options::runtime_options;

use std::error::Error;
use std::io::Write;
use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt};
use std::path::{Path, PathBuf};

use haematite::branch::history::{Key, Row, SERVICE_BRANCH, ShardRoot};
use haematite::branch::{
    CommitDurability, CommitRequest, Kind, RefRecord, RefStore, Registry, create_branch_with_kind,
    current_timestamp, fork_from_with_kind, open, remove,
};
use haematite::db::branches::BranchDatabase;
use haematite::db::vacuum::CANONICAL_REFS_DIR;
use haematite::db::{Database, DatabaseConfig};
use haematite::private_mode::{file_read_bytes, reset_file_read_bytes};
use haematite::store::{NodeCacheBudget, file_opens, reset_file_opens};
use haematite::tree::Hash;
use haematite::wal::Recovery;
use haematite_cli::serve::protocol::{Selection, Version};
use haematite_cli::serve::storage::Storage;

type TestResult<T = ()> = Result<T, Box<dyn Error>>;

const SHARDS: usize = 2;
const LARGE: u64 = 20;
const SMALL: u64 = 2;
const LEGACY_SMALL: u64 = 32;
const LEGACY_LARGE: u64 = LEGACY_SMALL * 10;
const MAIN: &str = "@haem/branch/main";
// Configuration, the service preflight, two installed branch records and
// each shard's tiny WAL, checkpoint, empty node and framing prefixes fit
// within this fixed budget, without history nodes.
const OPEN_BYTES: u64 = 64 * 1024;

struct Fixture {
    directory: tempfile::TempDir,
    old: Version,
    predecessor: Version,
    current: Version,
    roots: Vec<(usize, Hash)>,
}

fn record(refs: &RefStore, name: &str) -> TestResult<RefRecord> {
    refs.get(name)
        .cloned()
        .ok_or_else(|| format!("reference missing: {name}").into())
}

fn row(record: &RefRecord, sequence: u64) -> Row {
    Row {
        key: Key {
            branch: Hash::of(b"main"),
            generation: record.created,
            sequence,
        },
        timestamp: record.timestamp,
        shards: record
            .shards
            .iter()
            .map(|shard| ShardRoot {
                shard_id: shard.shard_id,
                root: shard.head,
            })
            .collect(),
    }
}

fn seed_history(
    writer: &mut BranchDatabase,
    refs: &mut RefStore,
    registry: &Registry,
    records: (&RefRecord, &RefRecord),
    versions: u64,
) -> TestResult<u64> {
    let (previous, live) = records;
    let service = open(SERVICE_BRANCH, refs, registry)?;
    let old_count = versions
        .checked_sub(1)
        .ok_or("fixture needs a predecessor")?;
    let mut per_shard = [0_u64; SHARDS];
    let template = row(previous, 0);
    let value = template.encode_value()?;
    let kept = row(live, 0);
    let key = kept.key.encode();
    let kept_shard = writer.shard_for(&key);
    // The smallest fixture still puts history in both physical shards.
    let first_sequence = (0..1024)
        .find(|sequence| {
            let key = Key {
                sequence: *sequence,
                ..template.key
            }
            .encode();
            writer.shard_for(&key) != kept_shard
        })
        .ok_or("fixture cannot find history for the other shard")?;
    for offset in 0..old_count {
        let sequence = first_sequence + offset;
        let key = Key {
            sequence,
            ..template.key
        }
        .encode();
        let shard = writer.shard_for(&key);
        service.put(shard, key, &value)?;
        per_shard[shard] += 1;
    }
    service.put(kept_shard, key, kept.encode_value()?)?;
    per_shard[kept_shard] += 1;
    // This checks the fixture covers both shards.
    // A changed key selection must not silently leave a shard empty.
    assert!(per_shard.iter().all(|count| *count > 0));
    // One batch materialises the history; no commit follows each offered row.
    writer.commit(
        &service,
        registry,
        CommitRequest {
            durability: CommitDurability::Durable { refs },
            extra_parents: &[],
            timestamp: current_timestamp(),
        },
    )?;
    assert_eq!(record(refs, SERVICE_BRANCH)?.seq, 1);
    Ok(first_sequence)
}

fn build(versions: u64) -> TestResult<Fixture> {
    if !matches!(versions, LARGE | SMALL) {
        return Err("fixture size must be one of the two declared cases".into());
    }
    build_versions(versions, None)
}

fn build_versions(versions: u64, stamps: Option<[u64; 3]>) -> TestResult<Fixture> {
    let directory = tempfile::tempdir()?;
    let data = directory.path().join("database");
    let database = Database::create(
        DatabaseConfig {
            data_dir: data.clone(),
            shard_count: SHARDS,
            distributed: None,
            executor_threads: Some(SHARDS),
            node_cache_budget: Some(NodeCacheBudget::Unlimited),
            retention: haematite::Retention::KeepAll,
        },
        runtime_options(),
    )?;
    let mut writer = BranchDatabase::new(database, NodeCacheBudget::Unlimited)?;
    let mut refs = RefStore::open(data.join(CANONICAL_REFS_DIR))?;
    let registry = Registry::new();
    let service = create_branch_with_kind(
        SERVICE_BRANCH,
        writer.base_roots()?,
        Kind::Namespace,
        &mut refs,
        &registry,
        stamps.map_or_else(current_timestamp, |[service, _, _]| service),
    )?;
    let previous_branch = fork_from_with_kind(
        &service,
        MAIN,
        Kind::Work,
        &mut refs,
        &registry,
        stamps.map_or_else(current_timestamp, |[_, previous, _]| previous),
    )?;
    let previous = record(&refs, MAIN)?;
    drop(previous_branch);
    assert!(remove(MAIN, &mut refs)?.is_some());
    let main = fork_from_with_kind(
        &service,
        MAIN,
        Kind::Work,
        &mut refs,
        &registry,
        stamps.map_or_else(current_timestamp, |[_, _, current]| current),
    )?;
    let live = record(&refs, MAIN)?;
    assert_ne!(live.created, previous.created);
    let old_sequence = seed_history(
        &mut writer,
        &mut refs,
        &registry,
        (&previous, &live),
        versions,
    )?;
    let key = b"fixture/live";
    main.put(writer.shard_for(key), key, b"current")?;
    writer.commit(
        &main,
        &registry,
        CommitRequest {
            durability: CommitDurability::Durable { refs: &mut refs },
            extra_parents: &[],
            timestamp: current_timestamp(),
        },
    )?;
    let current = record(&refs, MAIN)?;
    assert_eq!(current.seq, 1);
    assert_eq!(refs.list_prefix("@haem/history/").count(), 0);
    Ok(Fixture {
        directory,
        old: Version {
            generation: previous.created,
            sequence: old_sequence,
        },
        predecessor: Version {
            generation: live.created,
            sequence: 0,
        },
        current: Version {
            generation: current.created,
            sequence: current.seq,
        },
        roots: previous
            .shards
            .iter()
            .map(|shard| (shard.shard_id, shard.head))
            .collect(),
    })
}

fn check_open(fixture: &Fixture) -> TestResult {
    let data = fixture.directory.path().join("database");
    // The fixture is written under KeepAll, so its first open moves it to
    // reclaim (STOR-003 H1a) and owes a startup pass whose mark reads the
    // history tree. Both happen once in a store's life: move it, run that
    // pass to rest by its progress answers, and count the open after it.
    drop(Storage::open(
        &data,
        NodeCacheBudget::Unlimited,
        long_wait_interval(),
    )?);
    let moved = Database::open(&data, runtime_options())?;
    moved.quiesce_reclaim()?;
    drop(moved);
    // 6H (NB1): each counted open is logged by its call site and thread, and
    // printed when the count is wrong.
    haematite::private_mode::log_file_opens(true);
    reset_file_opens();
    reset_file_read_bytes();
    let storage = Storage::open(&data, NodeCacheBudget::Unlimited, long_wait_interval())?;
    let opened = file_opens();
    let log = haematite::private_mode::file_open_log();
    haematite::private_mode::log_file_opens(false);
    let bytes = file_read_bytes();
    // Fourteen fixed opens: five configuration reads, one writer lock,
    // one service-record preflight, three FORMAT reads, two root-source
    // records and two records loaded under the writer lock.
    // The preflight refuses an unserved store before retention can change;
    // its record is not reused as writable state. The fifth configuration
    // read is under the lock, so startup uses the current configuration.
    // Six per shard: migration probe, WAL recovery, tail reconciliation,
    // append framing, empty base node and index checkpoint.
    // This rows-only store has no legacy history files, snapshot registry or
    // reclaim resume record, and its startup pass has already settled.
    // Directory opens/listing, metadata calls and cache hits are not counted.
    assert_eq!(opened, 14 + 6 * u64::try_from(SHARDS)?, "{log:#?}");
    assert!(bytes > 0);
    assert!(bytes < OPEN_BYTES, "open read {bytes} bytes");
    let captured = storage.capture(&Selection {
        branch: "main".to_owned(),
        version: Some(fixture.old),
    })?;
    assert_eq!(captured.version, fixture.old);
    assert_eq!(
        captured
            .shards
            .iter()
            .map(|shard| (shard.shard_id, shard.head))
            .collect::<Vec<_>>(),
        fixture.roots
    );
    let page = storage.catalogue().history("main", None, 2)?;
    assert_eq!(
        page.iter()
            .map(|captured| captured.version)
            .collect::<Vec<_>>(),
        [fixture.predecessor, fixture.current]
    );
    assert_eq!(
        page[0]
            .shards
            .iter()
            .map(|shard| (shard.shard_id, shard.head))
            .collect::<Vec<_>>(),
        fixture.roots
    );
    Ok(())
}

#[test]
fn clean_open_counts_every_regular_file_open_independently_of_kept_versions() -> TestResult {
    let large = build(LARGE)?;
    let small = build(SMALL)?;
    check_open(&large)?;
    check_open(&small)?;
    Ok(())
}

fn legacy_record_bytes(record: &RefRecord) -> TestResult<Vec<u8>> {
    let mut bytes = b"HBR1".to_vec();
    bytes.extend_from_slice(&u64::try_from(record.name.len())?.to_le_bytes());
    bytes.extend_from_slice(record.name.as_bytes());
    for value in [
        record.created,
        record.seq,
        record.timestamp,
        u64::try_from(record.shards.len())?,
    ] {
        bytes.extend_from_slice(&value.to_le_bytes());
    }
    for shard in &record.shards {
        bytes.extend_from_slice(&u64::try_from(shard.shard_id)?.to_le_bytes());
        bytes.extend_from_slice(shard.fork_anchor.as_bytes());
        bytes.extend_from_slice(shard.head.as_bytes());
    }
    bytes.extend_from_slice(&u64::try_from(record.parents.len())?.to_le_bytes());
    for parent in &record.parents {
        bytes.extend_from_slice(parent.as_bytes());
    }
    Ok(bytes)
}

fn build_legacy(versions: u64) -> TestResult<Fixture> {
    if !matches!(versions, LEGACY_SMALL | LEGACY_LARGE) {
        return Err("legacy fixture size must be one of the two declared cases".into());
    }
    let fixture = build_versions(
        versions.checked_add(1).ok_or("fixture size overflow")?,
        Some([10, 20, 30]),
    )?;
    let refs_dir = fixture
        .directory
        .path()
        .join("database")
        .join(CANONICAL_REFS_DIR);
    assert!(!refs_dir.join("FORMAT").exists());
    for offset in 0..versions {
        let sequence = fixture
            .old
            .sequence
            .checked_add(offset)
            .ok_or("legacy history sequence overflow")?;
        let name = format!(
            "@haem/history/{}/{}/{sequence:020}",
            Hash::of(b"main"),
            fixture.old.generation,
        );
        let reference = RefRecord {
            name: name.clone(),
            created: fixture.old.generation,
            kind: Kind::Work,
            namespace_lineage: None,
            seq: sequence,
            timestamp: fixture.old.generation,
            shards: fixture
                .roots
                .iter()
                .map(|(shard_id, root)| haematite::branch::ShardRef {
                    shard_id: *shard_id,
                    fork_anchor: *root,
                    head: *root,
                })
                .collect(),
            parents: Vec::new(),
        };
        let digest = Hash::of(name.as_bytes()).to_string();
        let prefix = digest.get(..32).ok_or("reference hash is too short")?;
        let mut file = std::fs::OpenOptions::new()
            .create_new(true)
            .write(true)
            .mode(0o600)
            .open(refs_dir.join(format!("{prefix}.ref")))?;
        file.write_all(&legacy_record_bytes(&reference)?)?;
    }
    std::fs::File::open(&refs_dir)?.sync_all()?;
    let refs = RefStore::open(&refs_dir)?;
    assert_eq!(
        u64::try_from(refs.list_prefix("@haem/history/").count())?,
        versions,
    );
    Ok(fixture)
}

struct OpenCost {
    files: u64,
    bytes: u64,
    wal_file_bytes: [u64; SHARDS],
}

fn wal_path(data: &Path, shard: usize) -> PathBuf {
    data.join(format!("shard-{shard}")).join("shard.wal")
}

fn wal_lengths(data: &Path) -> TestResult<[u64; SHARDS]> {
    let mut lengths = [0; SHARDS];
    for (shard, length) in lengths.iter_mut().enumerate() {
        *length = std::fs::metadata(wal_path(data, shard))?.len();
    }
    Ok(lengths)
}

fn first_open_cost(fixture: &Fixture) -> TestResult<OpenCost> {
    let data = fixture.directory.path().join("database");
    let wal_file_bytes = wal_lengths(&data)?;
    reset_file_opens();
    reset_file_read_bytes();
    let storage = Storage::open(&data, NodeCacheBudget::Unlimited, long_wait_interval())?;
    let cost = OpenCost {
        files: file_opens(),
        bytes: file_read_bytes(),
        wal_file_bytes,
    };
    drop(storage);
    Ok(cost)
}

fn sum_bytes(bytes: &[u64]) -> TestResult<u64> {
    bytes
        .iter()
        .try_fold(0_u64, |sum, count| sum.checked_add(*count))
        .ok_or_else(|| "fixture byte count overflow".into())
}

fn print_open_cost(versions: u64, phase: &str, cost: &OpenCost) -> TestResult {
    let wal_file_bytes = sum_bytes(&cost.wal_file_bytes)?;
    println!(
        "BOUND_MEASURE legacy_refs={versions} phase={phase} file_opens={} bytes_read={} \
         wal_file_bytes={wal_file_bytes} wal_file_bytes_by_shard={:?}",
        cost.files, cost.bytes, cost.wal_file_bytes,
    );
    Ok(())
}

fn copy_fixture_directory(source: &Path, destination: &Path) -> TestResult {
    std::fs::DirBuilder::new().mode(0o700).create(destination)?;
    for entry in std::fs::read_dir(source)? {
        let entry = entry?;
        let kind = entry.file_type()?;
        let copied = destination.join(entry.file_name());
        if kind.is_dir() {
            copy_fixture_directory(&entry.path(), &copied)?;
        } else if kind.is_file() {
            std::fs::copy(entry.path(), copied)?;
        } else {
            return Err("fixture copy contains a nonregular entry".into());
        }
    }
    Ok(())
}

fn recovery_probe(fixture: &Fixture, versions: u64) -> TestResult {
    let directory = tempfile::tempdir()?;
    let data = directory.path().join("database");
    copy_fixture_directory(&fixture.directory.path().join("database"), &data)?;
    let wal_file_bytes = wal_lengths(&data)?;
    let mut probe_bytes = [0; SHARDS];
    for (shard, bytes) in probe_bytes.iter_mut().enumerate() {
        let recovered = Recovery::open(wal_path(&data, shard))?.recover_unverified()?;
        *bytes = recovered.bytes_read();
    }
    println!(
        "BOUND_MEASURE legacy_refs={versions} phase=recovery_probe wal_file_bytes={} \
         wal_file_bytes_by_shard={wal_file_bytes:?} \
         recovery_probe_bytes_read (not served-open)={} \
         recovery_probe_bytes_read_by_shard (not served-open)={probe_bytes:?}",
        sum_bytes(&wal_file_bytes)?,
        sum_bytes(&probe_bytes)?,
    );
    Ok(())
}

#[test]
fn legacy_refs_startup_counts_and_wal_probe() -> TestResult {
    let small = build_legacy(LEGACY_SMALL)?;
    let small_first = first_open_cost(&small)?;
    let small_reopen = first_open_cost(&small)?;
    let large = build_legacy(LEGACY_LARGE)?;
    let large_first = first_open_cost(&large)?;
    let large_reopen = first_open_cost(&large)?;
    print_open_cost(LEGACY_SMALL, "first_open", &small_first)?;
    print_open_cost(LEGACY_SMALL, "reopen", &small_reopen)?;
    print_open_cost(LEGACY_LARGE, "first_open", &large_first)?;
    print_open_cost(LEGACY_LARGE, "reopen", &large_reopen)?;
    recovery_probe(&small, LEGACY_SMALL)?;
    recovery_probe(&large, LEGACY_LARGE)?;
    Ok(())
}

const fn long_wait_interval() -> std::time::Duration {
    const LONG_WAIT_INTERVAL: std::time::Duration = std::time::Duration::from_secs(1);
    LONG_WAIT_INTERVAL
}