khive-db 0.20.0

SQLite storage backend: entities, edges, notes, events, FTS5, sqlite-vec vectors.
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
use super::*;
use std::sync::atomic::AtomicUsize;

/// A 100 ms lease deadline is only meaningful in the test's own lock
/// namespace; in the shared one it queues behind other tests' writers.
fn fixture_pool(path: &Path, volume_locks: &Path) -> ConnectionPool {
    ConnectionPool::new(PoolConfig {
        path: Some(path.to_path_buf()),
        volume_lock_dir: Some(volume_locks.to_path_buf()),
        write_queue_enabled: Some(false),
        disk_guard_config: Some(
            crate::DiskGuardEnvironment::default()
                .resolve(Some(0), Some(100))
                .unwrap(),
        ),
        ..PoolConfig::for_test()
    })
    .unwrap()
}

fn assert_identity_refusal<T>(result: Result<T, SqliteError>) {
    assert!(
        matches!(
            result,
            Err(SqliteError::CapacityUnavailable {
                phase: CapacityUnavailablePhase::Identity,
                ..
            })
        ),
        "ADMISSION_VOLUME_BINDING: a changed physical volume must be refused"
    );
}

#[test]
fn acquired_volume_cannot_be_replaced_before_capacity_probe() {
    let dir = tempfile::tempdir().unwrap();
    let pool = fixture_pool(
        &dir.path().join("lease-probe.db"),
        &dir.path().join("volume-locks"),
    );
    let admission = pool.write_admission();
    let captured = admission.captured_volume_for_test().unwrap();
    let lease = admission
        .acquire(crate::disk_guard::LeaseClass::Standalone)
        .unwrap()
        .expect("real volume lease");
    let probes = Arc::new(AtomicUsize::new(0));
    let seen = Arc::clone(&probes);
    admission.set_test_space_probe(move |_| {
        seen.fetch_add(1, Ordering::SeqCst);
        Ok(u64::MAX)
    });
    admission.set_test_current_volume(Some(captured.different_volume_for_test()));
    assert_identity_refusal(admission.check());
    assert_identity_refusal(admission.acquire(crate::disk_guard::LeaseClass::Standalone));
    assert_eq!(
        probes.load(Ordering::SeqCst),
        0,
        "wrong volume must not be probed"
    );
    admission.set_test_current_volume(None);
    admission.check().unwrap();
    assert_eq!(probes.load(Ordering::SeqCst), 1);
    drop(lease);
}

#[test]
fn volume_change_during_capacity_probe_refuses_the_sample() {
    let dir = tempfile::tempdir().unwrap();
    let pool = fixture_pool(
        &dir.path().join("probe-race.db"),
        &dir.path().join("volume-locks"),
    );
    let admission = pool.write_admission();
    let captured = admission.captured_volume_for_test().unwrap();
    let expected_probe_path = captured.probe_path().to_path_buf();
    let weak = Arc::downgrade(&admission);
    let probes = Arc::new(AtomicUsize::new(0));
    let seen = Arc::clone(&probes);
    admission.set_test_space_probe(move |path| {
        assert_eq!(path, expected_probe_path);
        seen.fetch_add(1, Ordering::SeqCst);
        weak.upgrade()
            .unwrap()
            .set_test_current_volume(Some(captured.different_volume_for_test()));
        Ok(u64::MAX)
    });
    let lease = admission
        .acquire(crate::disk_guard::LeaseClass::Standalone)
        .unwrap()
        .expect("real volume lease");
    assert_identity_refusal(admission.check());
    assert_eq!(
        probes.load(Ordering::SeqCst),
        1,
        "oracle changes identity inside the real probe seam"
    );
    admission.set_test_current_volume(None);
    drop(lease);
}

#[cfg(unix)]
#[test]
fn pooled_checkout_refuses_directory_replacement_on_the_same_volume() {
    let dir = tempfile::tempdir().unwrap();
    let original = dir.path().join("original");
    let retained = dir.path().join("retained");
    let replacement = dir.path().join("replacement");
    std::fs::create_dir(&original).unwrap();
    std::fs::create_dir(&replacement).unwrap();
    let path = original.join("database.db");
    let pool = fixture_pool(&path, &dir.path().join("volume-locks"));
    pool.writer()
        .unwrap()
        .conn()
        .execute_batch(
            "CREATE TABLE retained_row (id INTEGER); INSERT INTO retained_row VALUES (1)",
        )
        .unwrap();
    let other = Connection::open(replacement.join("database.db")).unwrap();
    other
        .execute_batch(
            "CREATE TABLE replacement_row (id INTEGER); INSERT INTO replacement_row VALUES (2)",
        )
        .unwrap();
    let before = VolumeIdentity::resolve(&path).unwrap();
    std::fs::rename(&original, &retained).unwrap();
    std::os::unix::fs::symlink(&replacement, &original).unwrap();
    assert_eq!(
        before,
        VolumeIdentity::resolve(&path).unwrap(),
        "fixture must keep the physical volume equal"
    );
    let writer = pool.writer();
    assert!(
        matches!(
            writer,
            Err(SqliteError::InvalidData(ref message))
                if message.contains("file identity changed")
        ),
        "POOLED_OPENED_FILE_BINDING: changed directory target must refuse checkout"
    );
    let bounded = pool.writer_until_for_admitted_operation(|| false);
    assert!(
        matches!(
            bounded,
            Err(SqliteError::InvalidData(ref message))
                if message.contains("file identity changed")
        ),
        "bounded checkout must preserve the same opened-file refusal"
    );
    std::fs::remove_file(&original).unwrap();
    std::fs::rename(&retained, &original).unwrap();
    assert_eq!(
        pool.writer()
            .unwrap()
            .conn()
            .query_row("SELECT id FROM retained_row", [], |row| row
                .get::<_, i64>(0))
            .unwrap(),
        1
    );
    assert_eq!(
        other
            .query_row("SELECT id FROM replacement_row", [], |row| row
                .get::<_, i64>(0))
            .unwrap(),
        2
    );
}

#[cfg(unix)]
#[test]
#[ignore = "needs a writable KHIVE_TEST_OTHER_VOLUME_DIR on a different physical volume"]
fn pooled_checkout_refuses_directory_redirect_to_another_physical_volume() {
    let dir = tempfile::tempdir().unwrap();
    let other_root =
        std::env::var_os("KHIVE_TEST_OTHER_VOLUME_DIR").expect("explicit second volume fixture");
    let source_volume = VolumeIdentity::resolve(dir.path()).unwrap();
    assert_ne!(
        source_volume,
        VolumeIdentity::resolve(Path::new(&other_root)).unwrap(),
        "fixture must be on a distinct physical volume"
    );
    let other_dir = tempfile::tempdir_in(&other_root).unwrap();
    let original = dir.path().join("original");
    let retained = dir.path().join("retained");
    std::fs::create_dir(&original).unwrap();
    let pool = fixture_pool(
        &original.join("database.db"),
        &dir.path().join("volume-locks"),
    );
    pool.writer()
        .unwrap()
        .conn()
        .execute_batch(
            "CREATE TABLE retained_row (id INTEGER); INSERT INTO retained_row VALUES (1)",
        )
        .unwrap();
    let other = Connection::open(other_dir.path().join("database.db")).unwrap();
    other
        .execute_batch(
            "CREATE TABLE replacement_row (id INTEGER); INSERT INTO replacement_row VALUES (2)",
        )
        .unwrap();
    std::fs::rename(&original, &retained).unwrap();
    std::os::unix::fs::symlink(other_dir.path(), &original).unwrap();
    assert_identity_refusal(pool.writer());
    std::fs::remove_file(&original).unwrap();
    std::fs::rename(&retained, &original).unwrap();
    assert_eq!(
        pool.writer()
            .unwrap()
            .conn()
            .query_row("SELECT id FROM retained_row", [], |row| row
                .get::<_, i64>(0))
            .unwrap(),
        1
    );
    assert_eq!(
        other
            .query_row("SELECT id FROM replacement_row", [], |row| row
                .get::<_, i64>(0))
            .unwrap(),
        2
    );
    println!("CROSS_VOLUME_DIRECTORY_REFUSAL_COMPLETE");
}

#[test]
fn nested_checkout_on_one_thread_fails_at_once_naming_both_sites() {
    let dir = tempfile::tempdir().unwrap();
    let pool = ConnectionPool::new(PoolConfig {
        path: Some(dir.path().join("reentry.db")),
        write_queue_enabled: Some(false),
        disk_guard_config: Some(
            crate::DiskGuardEnvironment::default()
                .resolve(Some(0), Some(5_000))
                .unwrap(),
        ),
        ..PoolConfig::for_test()
    })
    .unwrap();
    let held = pool.writer().unwrap();
    let started = Instant::now();
    let nested = [
        pool.writer().err().expect("nested checkout is refused"),
        pool.autocommit_write_unit()
            .err()
            .expect("nested write unit is refused"),
    ];
    assert!(
        started.elapsed() < Duration::from_secs(1),
        "re-entry waited {:?} of a 5 s lease deadline",
        started.elapsed()
    );
    for error in nested {
        let (holder_site, requester_site) = match &error {
            SqliteError::VolumeLeaseReentry {
                holder_site,
                requester_site,
            } => (holder_site.clone(), requester_site.clone()),
            other => panic!("re-entry must not read as lock contention: {other}"),
        };
        assert!(holder_site.contains(file!()), "{holder_site}");
        assert!(requester_site.contains(file!()), "{requester_site}");
        assert_ne!(holder_site, requester_site);
    }
    drop(held);
    pool.writer().expect("the lease is free after the holder");
}

fn admission_with_probe(
    dir: &Path,
    database: &str,
    available: u64,
    lock_dir: &Path,
) -> WriteAdmission {
    let admission = WriteAdmission::new(
        Some(dir.join(database)),
        0,
        DEFAULT_DISK_GUARD_DEADLINE_MS,
        Some(lock_dir.to_path_buf()),
    )
    .unwrap();
    admission.set_test_space_probe(move |_| Ok(available));
    admission
}

#[test]
fn zero_reserve_still_compares_operation_headroom() {
    let dir = tempfile::tempdir().unwrap();
    let locks = dir.path().join("locks");
    let admission = admission_with_probe(dir.path(), "headroom.db", 1_000, &locks);
    assert!(matches!(
        admission.check_with_headroom(1_000),
        Err(SqliteError::CapacityFloor {
            available_bytes: 1_000,
            floor_bytes: 0,
            required_headroom_bytes: 1_000,
            ..
        })
    ));
    assert!(matches!(
        admission.check_with_headroom(u64::MAX),
        Err(SqliteError::CapacityFloor { .. })
    ));
    admission
        .check_with_headroom(999)
        .expect("one byte above the headroom is admitted");
}

#[test]
fn zero_reserve_without_headroom_admits_any_space() {
    let dir = tempfile::tempdir().unwrap();
    let locks = dir.path().join("locks");
    let admission = admission_with_probe(dir.path(), "no-headroom.db", 0, &locks);
    admission.check().expect("no floor term and no headroom");
    admission.check_with_headroom(0).unwrap();
}

#[test]
fn missing_vacuum_estimate_refuses_even_under_a_zero_reserve() {
    let dir = tempfile::tempdir().unwrap();
    let locks = dir.path().join("locks");
    // The database file does not exist, so its copy-sized headroom cannot be
    // estimated, and plenty of space must not turn that into an admission.
    let admission = admission_with_probe(dir.path(), "never-created.db", u64::MAX, &locks);
    assert!(matches!(
        admission.check_for_vacuum(),
        Err(SqliteError::CapacityUnavailable {
            phase: CapacityUnavailablePhase::Probe,
            ..
        })
    ));
    admission
        .check()
        .expect("an ordinary write is not asked for the estimate");
}

#[cfg(unix)]
#[test]
fn write_unit_volume_checks_read_the_existing_database_without_resolving_its_path() {
    let dir = tempfile::tempdir().unwrap();
    let locks = dir.path().join("locks");
    std::fs::write(dir.path().join("present.db"), []).unwrap();
    let admission = admission_with_probe(dir.path(), "present.db", u64::MAX, &locks);
    let before = crate::disk_guard::resolves_on_this_thread();
    for _ in 0..10 {
        admission.check().unwrap();
        let lease = admission
            .acquire(crate::disk_guard::LeaseClass::Standalone)
            .unwrap()
            .expect("real volume lease");
        drop(lease);
        admission.volume_identity().unwrap();
    }
    assert_eq!(
        crate::disk_guard::resolves_on_this_thread() - before,
        0,
        "an existing database answers the volume check with one stat"
    );

    // Control: a database file that does not exist yet still takes the full
    // resolve, once per check, on this same counter.
    let absent = admission_with_probe(dir.path(), "absent.db", u64::MAX, &locks);
    let before = crate::disk_guard::resolves_on_this_thread();
    absent.check().unwrap();
    assert_eq!(crate::disk_guard::resolves_on_this_thread() - before, 2);
}

/// Holds of at least half a second recorded under `class` so far. Other tests
/// record into the same process-wide histograms, but none hold a lease that
/// long, so a delta here is this test's own lease.
fn long_holds(class: crate::disk_guard::LeaseClass) -> u64 {
    let holds = crate::disk_guard::lease_hold_snapshot().expect("lease holds available");
    let (_, histogram) = holds
        .iter()
        .find(|(recorded, _)| *recorded == class)
        .expect("every class is reported");
    histogram.buckets[11..].iter().sum::<u64>() + histogram.overflow_count
}

#[test]
fn a_held_lease_records_its_hold_under_its_class() {
    use crate::disk_guard::LeaseClass;
    let dir = tempfile::tempdir().unwrap();
    let pool = fixture_pool(
        &dir.path().join("lease-hold.db"),
        &dir.path().join("volume-locks"),
    );
    let before = long_holds(LeaseClass::Standalone);
    let lease = pool
        .write_admission()
        .acquire(LeaseClass::Standalone)
        .unwrap()
        .expect("real volume lease");
    std::thread::sleep(Duration::from_millis(600));
    assert_eq!(
        long_holds(LeaseClass::Standalone),
        before,
        "a hold is recorded at release, not while held"
    );
    drop(lease);
    assert!(
        long_holds(LeaseClass::Standalone) > before,
        "a 600 ms standalone hold must be recorded under standalone"
    );
}

#[test]
fn a_class_scope_overrides_the_acquisition_site_class() {
    use crate::disk_guard::{effective_class, lease_class_scope, LeaseClass};
    assert_eq!(effective_class(LeaseClass::Pooled), LeaseClass::Pooled);
    let dir = tempfile::tempdir().unwrap();
    let pool = fixture_pool(
        &dir.path().join("lease-scope.db"),
        &dir.path().join("volume-locks"),
    );
    let before = long_holds(LeaseClass::Migration);
    {
        let _outer = lease_class_scope(LeaseClass::Migration);
        {
            let _inner = lease_class_scope(LeaseClass::Maintenance);
            assert_eq!(effective_class(LeaseClass::Pooled), LeaseClass::Maintenance);
        }
        assert_eq!(effective_class(LeaseClass::Pooled), LeaseClass::Migration);
        let lease = pool
            .write_admission()
            .acquire(LeaseClass::Standalone)
            .unwrap()
            .expect("real volume lease");
        std::thread::sleep(Duration::from_millis(600));
        drop(lease);
    }
    assert_eq!(effective_class(LeaseClass::Pooled), LeaseClass::Pooled);
    assert!(
        long_holds(LeaseClass::Migration) > before,
        "a lease taken inside a migration scope is recorded as migration"
    );
}