khive-runtime 0.17.0

Composable Service API: entity/note CRUD, graph traversal, hybrid search, curation.
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
// Focused regression tests for the unsafe process probe (SAFETY: signal 0
// is an existence check with no side effects; see is_process_running).

#[test]
fn current_process_is_running() {
    // The current PID is always alive.
    let pid = std::process::id();
    assert!(
        is_process_running(pid),
        "current process {pid} should be detected as running"
    );
}

#[test]
fn pid_zero_is_not_running() {
    // PID 0 is the process group; kill(0, 0) sends to the group,
    // which we treat as invalid — the guard `pid <= 0` must block it.
    assert!(
        !is_process_running(0),
        "pid 0 must be rejected by the guard before the unsafe call"
    );
}

#[test]
fn very_large_pid_is_not_running() {
    // u32::MAX overflows i32 — try_from returns Err, guard returns false.
    assert!(
        !is_process_running(u32::MAX),
        "u32::MAX should fail i32 conversion and return false"
    );
}

// EPERM (process exists, no permission to signal it) must not be
// misread as "not running" during stale-daemon cleanup.

#[test]
fn classify_kill_result_zero_is_alive() {
    assert_eq!(classify_kill_result(0, 0), PidLiveness::Alive);
    assert!(classify_kill_result(0, 0).is_running());
}

#[test]
fn classify_kill_result_esrch_is_dead() {
    assert_eq!(classify_kill_result(-1, libc::ESRCH), PidLiveness::Dead);
    assert!(!classify_kill_result(-1, libc::ESRCH).is_running());
}

#[test]
fn classify_kill_result_eperm_is_permission_denied_and_counts_as_running() {
    assert_eq!(
        classify_kill_result(-1, libc::EPERM),
        PidLiveness::PermissionDenied
    );
    assert!(
        classify_kill_result(-1, libc::EPERM).is_running(),
        "EPERM must be unknown-safe: treated as running, never as a basis \
             for stale cleanup to unlink a live daemon's rendezvous files"
    );
}

#[test]
fn same_process_pid_requires_explicit_in_process_harness_opt_in() {
    let current = std::process::id();
    assert!(
        !pid_can_name_incumbent(current, current, false),
        "production startup must not trust a same-PID stale rendezvous"
    );
    assert!(
        pid_can_name_incumbent(current, current, true),
        "the in-process harness must let a live same-PID owner win"
    );
    // Keep the probe two away from `current` so the fixture preserves the
    // off-by-one regression check for adjacent PIDs; wrapping_add avoids
    // making the test overflow-sensitive at the u32 boundary.
    let distinct_probe_pid = current.wrapping_add(2);
    assert_ne!(
        distinct_probe_pid, current,
        "probe PID must differ from this process's PID"
    );
    assert!(
        pid_can_name_incumbent(distinct_probe_pid, current, false),
        "a distinct PID remains eligible under ordinary production rules"
    );
}

#[test]
fn pid_1_probe_is_running_regardless_of_permission_outcome() {
    // PID 1 (init/launchd) always exists. An unprivileged process gets
    // EPERM signaling it (never ESRCH); running as root would get 0
    // instead. Either way `is_process_running` must report true — this
    // is the live regression guard for EPERM being misread as dead;
    // `classify_kill_result` above is the pure-function unit coverage
    // for the same mapping, kept independent of process ownership so
    // it is never flaky in CI.
    assert!(
        is_process_running(1),
        "PID 1 always exists; EPERM must not read as dead"
    );
}

#[tokio::test]
async fn stale_cleanup_preserves_live_incumbent_without_reachable_socket() {
    // No other test in this process may fork while this fixture briefly
    // owns a listener: a child that inherits it can keep the socket
    // reachable after this test drops its own descriptor.
    if crate::test_process::run_in_child() {
        return;
    }
    assert_eq!(
        std::env::var("KHIVE_RUNTIME_ISOLATED_TEST").ok().as_deref(),
        Some("daemon::tests::stale_cleanup_preserves_live_incumbent_without_reachable_socket"),
        "the stale-listener fixture must run alone in its child process"
    );
    for socket_exists in [false, true] {
        let dir = crate::test_process::private_tempdir_builder()
            .tempdir()
            .expect("tempdir");
        let sock = dir.path().join("khived.sock");
        let pid_file = dir.path().join("khived.pid");
        if socket_exists {
            let listener = std::os::unix::net::UnixListener::bind(&sock)
                .expect("bind socket before closing listener");
            drop(listener);
        }
        let identity = socket_identity(&sock);
        assert_eq!(identity.is_some(), socket_exists);
        let error = UnixStream::connect(&sock)
            .await
            .expect_err("incumbent must have no reachable listener");
        assert_eq!(
            error.kind(),
            if socket_exists {
                std::io::ErrorKind::ConnectionRefused
            } else {
                std::io::ErrorKind::NotFound
            }
        );
        let live_pid = std::process::id().to_string();
        let _pid_file_guard = write_pid_file_exclusive(&pid_file)
            .expect("claim and lock the live incumbent PID file");

        // Harness eligibility makes our own stable PID an incumbent;
        // ordinary same-PID rejection is covered separately above.
        assert!(
            matches!(
                cleanup_stale_daemon(&sock, &pid_file, true, "probe-test").await,
                Incumbent::Live(_) | Incumbent::Serving(_)
            ),
            "live incumbent must retain ownership with socket_exists={socket_exists}"
        );
        assert_eq!(
            std::fs::read_to_string(&pid_file).expect("live incumbent PID must survive"),
            live_pid
        );
        assert!(socket_identity(&sock) == identity);
    }
}

#[tokio::test]
async fn stale_cleanup_preserves_live_socket_without_usable_pid() {
    if crate::test_process::run_in_child() {
        return;
    }
    for pid_contents in [None, Some("not-a-pid"), Some("4294967295")] {
        let dir = crate::test_process::private_tempdir_builder()
            .tempdir()
            .expect("tempdir");
        let sock = dir.path().join("khived.sock");
        let pid_file = dir.path().join("khived.pid");
        let _listener = std::os::unix::net::UnixListener::bind(&sock).expect("bind listener");
        if let Some(contents) = pid_contents {
            std::fs::write(&pid_file, contents).expect("write PID fixture");
        }
        let identity = socket_identity(&sock).expect("socket identity");
        drop(UnixStream::connect(&sock).await.expect("listener baseline"));

        assert!(matches!(
            cleanup_stale_daemon(&sock, &pid_file, false, "probe-test").await,
            Incumbent::Unknown
        ));
        assert!(socket_identity(&sock) == Some(identity));
        drop(
            UnixStream::connect(&sock)
                .await
                .expect("listener survives cleanup"),
        );
        assert_eq!(
            std::fs::read_to_string(&pid_file).ok().as_deref(),
            pid_contents
        );
    }
}

#[tokio::test]
async fn stale_cleanup_reclaims_dead_socket_without_usable_pid() {
    if crate::test_process::run_in_child() {
        return;
    }
    for pid_contents in [None, Some("not-a-pid"), Some("4294967295")] {
        let dir = crate::test_process::private_tempdir_builder()
            .tempdir()
            .expect("tempdir");
        let sock = dir.path().join("khived.sock");
        let pid_file = dir.path().join("khived.pid");
        let listener = std::os::unix::net::UnixListener::bind(&sock).expect("bind socket");
        drop(listener);
        if let Some(contents) = pid_contents {
            std::fs::write(&pid_file, contents).expect("write PID fixture");
        }
        assert_eq!(
            UnixStream::connect(&sock)
                .await
                .expect_err("stale baseline")
                .kind(),
            std::io::ErrorKind::ConnectionRefused
        );

        assert!(matches!(
            cleanup_stale_daemon(&sock, &pid_file, false, "probe-test").await,
            Incumbent::Stale
        ));
        assert!(!pid_file.exists());
        let _replacement = std::os::unix::net::UnixListener::bind(&sock)
            .expect("stale socket path must be reusable");
    }
}

#[tokio::test]
async fn stale_cleanup_preserves_non_socket_path() {
    let dir = crate::test_process::private_tempdir_builder()
        .tempdir()
        .expect("tempdir");
    let sock = dir.path().join("khived.sock");
    let pid_file = dir.path().join("khived.pid");
    std::fs::write(&sock, "not a socket").expect("write non-socket fixture");

    assert!(matches!(
        cleanup_stale_daemon(&sock, &pid_file, false, "probe-test").await,
        Incumbent::Unknown
    ));
    assert_eq!(std::fs::read_to_string(&sock).unwrap(), "not a socket");
}

#[tokio::test]
async fn stale_cleanup_preserves_socket_when_pid_cannot_be_read() {
    if crate::test_process::run_in_child() {
        return;
    }
    let dir = crate::test_process::private_tempdir_builder()
        .tempdir()
        .expect("tempdir");
    let sock = dir.path().join("khived.sock");
    let pid_file = dir.path().join("khived.pid");
    let _listener = std::os::unix::net::UnixListener::bind(&sock).expect("bind listener");
    std::fs::create_dir(&pid_file).expect("make unreadable-as-file PID fixture");
    assert!(std::fs::read_to_string(&pid_file).is_err());
    let identity = socket_identity(&sock).expect("socket identity");
    drop(UnixStream::connect(&sock).await.expect("listener baseline"));

    assert!(matches!(
        cleanup_stale_daemon(&sock, &pid_file, false, "probe-test").await,
        Incumbent::Unknown
    ));
    assert!(socket_identity(&sock) == Some(identity));
    drop(
        UnixStream::connect(&sock)
            .await
            .expect("listener survives cleanup"),
    );
}

#[test]
fn stale_cleanup_rejects_fifo_pid_without_waiting_for_writer() {
    use std::os::unix::ffi::OsStrExt;
    use std::os::unix::fs::FileTypeExt;

    if crate::test_process::run_in_child() {
        return;
    }
    let dir = crate::test_process::private_tempdir_builder()
        .tempdir()
        .expect("tempdir");
    let sock = dir.path().join("khived.sock");
    let pid_file = dir.path().join("khived.pid");
    let path = std::ffi::CString::new(pid_file.as_os_str().as_bytes()).expect("FIFO path");
    // SAFETY: path is a live NUL-terminated string for the duration of this call.
    assert_eq!(unsafe { libc::mkfifo(path.as_ptr(), 0o600) }, 0);
    assert!(std::fs::symlink_metadata(&pid_file)
        .expect("FIFO metadata")
        .file_type()
        .is_fifo());
    let (sender, receiver) = std::sync::mpsc::sync_channel(1);
    std::thread::spawn(move || {
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("runtime");
        let refused = matches!(
            runtime.block_on(cleanup_stale_daemon(&sock, &pid_file, false, "probe-test")),
            Incumbent::Unknown
        );
        let _ = sender.send(refused);
    });
    assert!(receiver
        .recv_timeout(std::time::Duration::from_secs(5))
        .expect("FIFO cleanup must not wait for a writer"));
}

#[tokio::test]
async fn stale_cleanup_refuses_symlink_and_oversized_pid() {
    use std::os::unix::fs::symlink;

    let dir = crate::test_process::private_tempdir_builder()
        .tempdir()
        .expect("tempdir");
    let sock = dir.path().join("khived.sock");
    let pid_file = dir.path().join("khived.pid");
    let target = dir.path().join("target");
    std::fs::write(&target, "4294967295").expect("target PID");
    symlink(&target, &pid_file).expect("PID symlink");
    assert!(matches!(
        cleanup_stale_daemon(&sock, &pid_file, false, "probe-test").await,
        Incumbent::Unknown
    ));
    assert!(std::fs::symlink_metadata(&pid_file)
        .expect("PID symlink retained")
        .file_type()
        .is_symlink());
    std::fs::remove_file(&pid_file).expect("remove fixture symlink");
    std::fs::write(&pid_file, "0".repeat(4097)).expect("oversized PID");
    assert!(matches!(
        cleanup_stale_daemon(&sock, &pid_file, false, "probe-test").await,
        Incumbent::Unknown
    ));
    assert_eq!(
        std::fs::metadata(&pid_file).expect("PID retained").len(),
        4097
    );
}

#[tokio::test]
#[ignore = "requires an unprivileged UID and a local filesystem with read-only flock support"]
async fn stale_cleanup_handles_read_only_pid_when_exclusive_lock_is_supported() {
    use std::os::unix::fs::PermissionsExt;
    use std::os::unix::io::AsRawFd;

    let dir = crate::test_process::private_tempdir_builder()
        .tempdir()
        .expect("tempdir");
    let sock = dir.path().join("khived.sock");
    let pid_file = dir.path().join("khived.pid");
    let stale_listener = std::os::unix::net::UnixListener::bind(&sock).expect("bind socket");
    drop(stale_listener);
    assert_eq!(
        UnixStream::connect(&sock)
            .await
            .expect_err("stale socket baseline")
            .kind(),
        std::io::ErrorKind::ConnectionRefused
    );
    std::fs::write(&pid_file, "4294967295").expect("stale PID");
    std::fs::set_permissions(&pid_file, std::fs::Permissions::from_mode(0o400))
        .expect("read-only PID permissions");
    let write_error = std::fs::OpenOptions::new()
        .write(true)
        .open(&pid_file)
        .expect_err("fixture must run without permission to write the PID file");
    assert_eq!(write_error.kind(), std::io::ErrorKind::PermissionDenied);

    let held = std::fs::File::open(&pid_file).expect("open read-only PID");
    // SAFETY: held owns a live descriptor; flock does not retain this pointer.
    assert_eq!(
        unsafe { libc::flock(held.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
        0
    );
    assert!(matches!(
        cleanup_stale_daemon(&sock, &pid_file, false, "probe-test").await,
        Incumbent::Unknown
    ));
    assert!(sock.exists() && pid_file.exists());
    drop(held);
    assert!(matches!(
        cleanup_stale_daemon(&sock, &pid_file, false, "probe-test").await,
        Incumbent::Stale
    ));
    assert!(!pid_file.exists());

    let _listener = std::os::unix::net::UnixListener::bind(&sock).expect("bind replacement");
    std::fs::write(&pid_file, "4294967295").expect("stale PID beside listener");
    std::fs::set_permissions(&pid_file, std::fs::Permissions::from_mode(0o400))
        .expect("read-only PID permissions");
    let identity = socket_identity(&sock).expect("socket identity");
    drop(UnixStream::connect(&sock).await.expect("listener baseline"));
    assert!(matches!(
        cleanup_stale_daemon(&sock, &pid_file, false, "probe-test").await,
        Incumbent::Unknown
    ));
    assert!(socket_identity(&sock) == Some(identity));
    drop(
        UnixStream::connect(&sock)
            .await
            .expect("listener survives cleanup"),
    );
}

#[tokio::test]
#[serial]
async fn live_foreign_pid_does_not_block_daemon_startup() {
    if crate::test_process::run_in_child() {
        return;
    }

    let dir = crate::test_process::private_tempdir_builder()
        .tempdir()
        .expect("tempdir");
    let sock = dir.path().join("khived.sock");
    let pid_file = dir.path().join("khived.pid");
    std::env::set_var("KHIVE_SOCKET", &sock);
    std::env::set_var("KHIVE_PID", &pid_file);
    std::env::set_var("KHIVE_LOCK", dir.path().join("khived.recovery.lock"));

    let stale_listener =
        std::os::unix::net::UnixListener::bind(&sock).expect("create stale socket path");
    drop(stale_listener);

    let mut foreign = std::process::Command::new("/bin/sleep")
        .arg("30")
        .spawn()
        .expect("spawn live unrelated process");
    std::fs::write(&pid_file, foreign.id().to_string()).expect("write unrelated PID");

    let dispatcher = MockDispatch {
        namespace: "local".to_string(),
        config_id: "foreign-pid-start-test".to_string(),
        dispatch_calls: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
        pool: None,
        dispatch_err: None,
    };
    let daemon = tokio::spawn(run_daemon_in_process_test(dispatcher));
    let connected = tokio::time::timeout(std::time::Duration::from_secs(5), async {
        loop {
            if let Ok(stream) = UnixStream::connect(&sock).await {
                break Some(stream);
            }
            if daemon.is_finished() {
                break None;
            }
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        }
    })
    .await;

    let response = if let Ok(Some(mut stream)) = connected {
        let mut request = base_request_frame("foreign-pid-start-test");
        request.probe_only = true;
        let payload = serde_json::to_vec(&request).expect("encode probe request");
        tokio::time::timeout(std::time::Duration::from_secs(1), async {
            write_frame(&mut stream, &payload).await.ok()?;
            let raw = read_frame(&mut stream).await.ok()?;
            serde_json::from_slice::<DaemonResponseFrame>(&raw).ok()
        })
        .await
        .ok()
        .flatten()
    } else {
        None
    };
    let foreign_survived_start = foreign
        .try_wait()
        .expect("query unrelated process state")
        .is_none();

    daemon.abort();
    let _ = daemon.await;
    let _ = foreign.kill();
    let _ = foreign.wait();
    std::env::remove_var("KHIVE_SOCKET");
    std::env::remove_var("KHIVE_PID");
    std::env::remove_var("KHIVE_LOCK");

    assert!(
        response.is_some_and(|response| {
            response.ok && response.served_config_id.as_deref() == Some("foreign-pid-start-test")
        }),
        "daemon must start and answer its identity probe"
    );
    assert!(
        foreign_survived_start,
        "starting khived must leave the unrelated live process running"
    );
}

#[tokio::test]
#[serial]
async fn second_start_refuses_while_pid_file_is_locked_before_bind() {
    if crate::test_process::run_in_child() {
        return;
    }

    let dir = crate::test_process::private_tempdir_builder()
        .tempdir()
        .expect("tempdir");
    let sock = dir.path().join("khived.sock");
    let pid_file = dir.path().join("khived.pid");
    std::env::set_var("KHIVE_SOCKET", &sock);
    std::env::set_var("KHIVE_PID", &pid_file);
    std::env::set_var("KHIVE_LOCK", dir.path().join("khived.recovery.lock"));

    let _incumbent_startup_guard = write_pid_file_exclusive(&pid_file)
        .expect("incumbent claims and locks its PID file before binding");
    let dispatcher = MockDispatch {
        namespace: "local".to_string(),
        config_id: "startup-lock-test".to_string(),
        dispatch_calls: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
        pool: None,
        dispatch_err: None,
    };
    let second = tokio::time::timeout(
        std::time::Duration::from_secs(1),
        run_daemon_in_process_test(dispatcher),
    )
    .await;
    let refused = matches!(second, Ok(Err(_)));
    let pid_file_survived = pid_file.exists();
    let socket_was_not_bound = !sock.exists();

    std::env::remove_var("KHIVE_SOCKET");
    std::env::remove_var("KHIVE_PID");
    std::env::remove_var("KHIVE_LOCK");

    assert!(
        refused,
        "a second start must refuse while an incumbent holds its pre-bind PID lock"
    );
    assert!(
        pid_file_survived,
        "the incumbent PID file must remain in place"
    );
    assert!(
        socket_was_not_bound,
        "the second start must not bind the socket"
    );
}

#[test]
fn env_truthy_recognises_set_values() {
    assert!(!env_truthy("__KHIVE_TEST_ABSENT_VAR_XYZ__"));

    // env_truthy with a live value — set and unset atomically to avoid
    // cross-test pollution (not parallel-safe without serial_test, but these
    // are fast unit tests and the variable name is unique).
    let key = "__KHIVE_TEST_TRUTHY_ABC__";
    std::env::set_var(key, "1");
    assert!(env_truthy(key));
    std::env::set_var(key, "false");
    assert!(!env_truthy(key));
    std::env::set_var(key, "0");
    assert!(!env_truthy(key));
    std::env::remove_var(key);
}