khive-runtime 0.13.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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
use super::*;
use async_trait::async_trait;
use lattice_embed::{EmbedError, EmbeddingModel, EmbeddingService, MAX_TEXT_BYTES};
use std::sync::{Arc, Mutex};

use khive_types::Namespace;

use crate::embedder_registry::EmbedderProvider;

const NAN_MODEL: &str = "atomic-message-nan-model";
const NAN_DIMS: usize = 4;

struct NanService;
#[async_trait]
impl EmbeddingService for NanService {
    async fn embed(
        &self,
        texts: &[String],
        _model: EmbeddingModel,
    ) -> Result<Vec<Vec<f32>>, EmbedError> {
        Ok(texts.iter().map(|_| vec![f32::NAN; NAN_DIMS]).collect())
    }
    fn supports_model(&self, _model: EmbeddingModel) -> bool {
        true
    }
    fn name(&self) -> &'static str {
        NAN_MODEL
    }
}
struct NanProvider;
#[async_trait]
impl EmbedderProvider for NanProvider {
    fn name(&self) -> &str {
        NAN_MODEL
    }
    fn dimensions(&self) -> usize {
        NAN_DIMS
    }
    async fn build(&self) -> RuntimeResult<std::sync::Arc<dyn EmbeddingService>> {
        Ok(std::sync::Arc::new(NanService))
    }
}

struct TruncationService;
#[async_trait]
impl EmbeddingService for TruncationService {
    async fn embed(
        &self,
        texts: &[String],
        _model: EmbeddingModel,
    ) -> Result<Vec<Vec<f32>>, EmbedError> {
        Ok(texts
            .iter()
            .map(|_| vec![0.5; EmbeddingModel::MultilingualE5Base.dimensions()])
            .collect())
    }
    fn supports_model(&self, _model: EmbeddingModel) -> bool {
        true
    }
    fn name(&self) -> &'static str {
        "multilingual-e5-base"
    }
}

struct TruncationProvider;
#[async_trait]
impl EmbedderProvider for TruncationProvider {
    fn name(&self) -> &str {
        "multilingual-e5-base"
    }
    fn dimensions(&self) -> usize {
        EmbeddingModel::MultilingualE5Base.dimensions()
    }
    async fn build(&self) -> RuntimeResult<std::sync::Arc<dyn EmbeddingService>> {
        Ok(std::sync::Arc::new(TruncationService))
    }
}

const DEDUP_DIMS: usize = 4;

struct DedupService {
    name: &'static str,
}

#[async_trait]
impl EmbeddingService for DedupService {
    async fn embed(
        &self,
        texts: &[String],
        _model: EmbeddingModel,
    ) -> Result<Vec<Vec<f32>>, EmbedError> {
        Ok(texts.iter().map(|_| vec![0.25; DEDUP_DIMS]).collect())
    }

    fn supports_model(&self, _model: EmbeddingModel) -> bool {
        true
    }

    fn name(&self) -> &'static str {
        self.name
    }
}

struct DedupProvider {
    name: &'static str,
}

#[async_trait]
impl EmbedderProvider for DedupProvider {
    fn name(&self) -> &str {
        self.name
    }

    fn dimensions(&self) -> usize {
        DEDUP_DIMS
    }

    async fn build(&self) -> RuntimeResult<std::sync::Arc<dyn EmbeddingService>> {
        Ok(std::sync::Arc::new(DedupService { name: self.name }))
    }
}

struct BatchCountingService {
    name: &'static str,
    calls: Arc<Mutex<Vec<Vec<String>>>>,
}

#[async_trait]
impl EmbeddingService for BatchCountingService {
    async fn embed(
        &self,
        texts: &[String],
        _model: EmbeddingModel,
    ) -> Result<Vec<Vec<f32>>, EmbedError> {
        self.calls.lock().unwrap().push(texts.to_vec());
        Ok(texts.iter().map(|_| vec![0.25; DEDUP_DIMS]).collect())
    }

    fn supports_model(&self, _model: EmbeddingModel) -> bool {
        true
    }

    fn name(&self) -> &'static str {
        self.name
    }
}

struct BatchCountingProvider {
    name: &'static str,
    calls: Arc<Mutex<Vec<Vec<String>>>>,
}

#[async_trait]
impl EmbedderProvider for BatchCountingProvider {
    fn name(&self) -> &str {
        self.name
    }

    fn dimensions(&self) -> usize {
        DEDUP_DIMS
    }

    async fn build(&self) -> RuntimeResult<Arc<dyn EmbeddingService>> {
        Ok(Arc::new(BatchCountingService {
            name: self.name,
            calls: Arc::clone(&self.calls),
        }))
    }
}

#[tokio::test]
async fn heterogeneous_notes_batch_models_with_one_schema_writer() {
    let runtime = KhiveRuntime::memory().unwrap();
    let token = runtime
        .authorize(Namespace::parse("batch-notes").unwrap())
        .unwrap();
    let names = ["batch-notes-a", "batch-notes-b"];
    let mut counters = Vec::new();
    for name in names {
        let calls = Arc::new(Mutex::new(Vec::new()));
        runtime.register_embedder(BatchCountingProvider {
            name,
            calls: Arc::clone(&calls),
        });
        runtime.embedder_with_token(&token, name).await.unwrap();
        counters.push(calls);
    }
    let inputs = [
        ("first", "shared text", true, 0.2),
        ("second", "shared text", true, 0.4),
        ("third", "different text", true, 0.6),
        ("disabled", "shared text", false, 0.8),
    ];
    let requests = inputs
        .iter()
        .map(|&(key, content, embed, salience)| AtomicNoteRequest {
            spec: AtomicNoteSpec {
                token: &token,
                id: None,
                kind: "observation",
                name: None,
                content,
                properties: Some(serde_json::json!({"key": key})),
            },
            options: AtomicNoteOptions {
                key: Some(key),
                salience: Some(salience),
                embed: Some(embed),
                ..Default::default()
            },
        })
        .collect();
    let before = runtime.backend().pool().writer_acquisition_snapshot();
    let prepared = prepare_atomic_note_requests(&runtime, requests)
        .await
        .unwrap();
    let after = runtime.backend().pool().writer_acquisition_snapshot();
    assert_eq!(after.acquisitions - before.acquisitions, 1);
    for calls in &counters {
        assert_eq!(
            *calls.lock().unwrap(),
            vec![vec!["shared text".to_owned(), "different text".to_owned()]],
        );
    }
    for (note, &(key, content, _, salience)) in prepared.notes.iter().zip(&inputs) {
        assert_eq!(note.key.as_deref(), Some(key));
        assert_eq!(note.content, content);
        assert_eq!(note.salience, Some(salience));
        assert_eq!(note.properties.as_ref().unwrap()["key"], key);
    }
    assert!(matches!(
        crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), prepared.plans)
            .await
            .unwrap(),
        AtomicRunOutcome::Committed { .. }
    ));
    for name in names {
        assert_eq!(
            runtime
                .vectors_for_model(&token, name)
                .unwrap()
                .count()
                .await
                .unwrap(),
            3,
            "disabled notes must not inherit a sibling's shared vector",
        );
    }
}

#[tokio::test]
async fn atomic_note_batch_chunks_only_above_provider_limit() {
    let runtime = KhiveRuntime::memory().unwrap();
    let token = runtime.authorize(Namespace::local()).unwrap();
    let calls = Arc::new(Mutex::new(Vec::new()));
    runtime.register_embedder(BatchCountingProvider {
        name: "batch-notes-large",
        calls: Arc::clone(&calls),
    });
    let contents: Vec<_> = (0..=lattice_embed::DEFAULT_MAX_BATCH_SIZE)
        .map(|index| format!("distinct document {index}"))
        .collect();
    let specs = contents
        .iter()
        .map(|content| AtomicNoteSpec {
            token: &token,
            id: None,
            kind: "observation",
            name: None,
            content,
            properties: None,
        })
        .collect();
    let prepared = prepare_atomic_notes(&runtime, specs, AtomicNoteOptions::default())
        .await
        .unwrap();
    assert_eq!(prepared.notes.len(), contents.len());
    let calls = calls.lock().unwrap();
    assert_eq!(calls.len(), 2);
    assert_eq!(calls[0].len(), lattice_embed::DEFAULT_MAX_BATCH_SIZE);
    assert_eq!(calls[1].len(), 1);
    assert_eq!(calls.concat(), contents);
}

/// A minimal note-write validator standing in for a pack's real one (e.g.
/// `khive-pack-comm`'s `derive_message_identity`): unconditionally stamps
/// `from_actor` with the caller's token-derived actor id, discarding
/// whatever the caller's own `properties` named for that key.
fn stamp_from_actor(
    _kind: &str,
    actor_id: &str,
    properties: Option<Value>,
) -> RuntimeResult<Option<Value>> {
    let mut props = match properties {
        Some(Value::Object(map)) => map,
        _ => serde_json::Map::new(),
    };
    props.insert(
        "from_actor".to_string(),
        Value::String(actor_id.to_string()),
    );
    Ok(Some(Value::Object(props)))
}

async fn fts_row_count(runtime: &KhiveRuntime, namespace: &str) -> i64 {
    let mut reader = runtime.sql().reader().await.expect("sql reader");
    match reader
        .query_scalar(SqlStatement {
            sql: "SELECT COUNT(*) FROM fts_notes WHERE namespace = ?1".to_string(),
            params: vec![SqlValue::Text(namespace.to_string())],
            label: None,
        })
        .await
        .expect("fts count query")
    {
        Some(SqlValue::Integer(n)) => n,
        other => panic!("unexpected fts count result: {other:?}"),
    }
}

async fn ann_write_log_count(runtime: &KhiveRuntime, namespace: &str, model: &str) -> i64 {
    let mut reader = runtime.sql().reader().await.expect("sql reader");
    match reader
        .query_scalar(SqlStatement {
            sql: "SELECT COUNT(*) FROM ann_write_log \
                      WHERE namespace = ?1 AND embedding_model = ?2"
                .to_string(),
            params: vec![
                SqlValue::Text(namespace.to_string()),
                SqlValue::Text(model.to_string()),
            ],
            label: None,
        })
        .await
        .expect("ann_write_log count query")
    {
        Some(SqlValue::Integer(n)) => n,
        other => panic!("unexpected ann_write_log count result: {other:?}"),
    }
}

/// A custom embedding provider returning NaN must be rejected BEFORE any
/// plan is built — same validation `VectorStore::insert` performs on the
/// canonical `create_note_inner` path. No note row, FTS document, vector
/// row, or `ann_write_log` row may be committed.
#[tokio::test]
async fn create_notes_atomic_rejects_non_finite_embedding_before_any_write() {
    let runtime = KhiveRuntime::memory().expect("in-memory runtime");
    runtime.register_embedder(NanProvider);
    let ns = "atomic-message-nan-test";
    let token = runtime
        .authorize(Namespace::parse(ns).unwrap())
        .expect("authorize");

    let result = create_notes_atomic(
        &runtime,
        vec![AtomicNoteSpec {
            token: &token,
            id: None,
            kind: "observation",
            name: None,
            content: "nan embedding content",
            properties: None,
        }],
    )
    .await;

    assert!(
        result.is_err(),
        "a non-finite embedding must be rejected; got {result:?}"
    );

    let alive = runtime
        .list_notes(&token, Some("observation"), 100, 0)
        .await
        .expect("list_notes")
        .into_iter()
        .filter(|n| n.deleted_at.is_none())
        .count();
    assert_eq!(
        alive, 0,
        "no note row may be committed when an embedding is non-finite"
    );

    assert_eq!(
        fts_row_count(&runtime, ns).await,
        0,
        "no FTS document may be committed when an embedding is non-finite"
    );

    let vs = runtime
        .vectors_for_model(&token, NAN_MODEL)
        .expect("vec store");
    assert_eq!(
        vs.count().await.expect("count"),
        0,
        "no vector row may be committed when an embedding is non-finite"
    );

    assert_eq!(
        ann_write_log_count(&runtime, ns, NAN_MODEL).await,
        0,
        "no ann_write_log row may be committed when an embedding is non-finite"
    );
}

#[tokio::test]
async fn create_notes_atomic_rejects_reserved_secret_gate_key() {
    let runtime = KhiveRuntime::memory().expect("in-memory runtime");
    let ns = "atomic-message-reserved-key-test";
    let token = runtime
        .authorize(Namespace::parse(ns).unwrap())
        .expect("authorize");

    let result = create_notes_atomic(
        &runtime,
        vec![AtomicNoteSpec {
            token: &token,
            id: None,
            kind: "observation",
            name: None,
            content: "atomic message reservation target",
            properties: Some(
                serde_json::json!({"khive:secret_gate": "exempted:content-sha256-manifest-v1"}),
            ),
        }],
    )
    .await;

    let err = result.expect_err("caller-supplied reserved key must be rejected");
    assert!(
        matches!(err, RuntimeError::InvalidInput(ref msg) if msg.contains("khive:secret_gate")),
        "unexpected error: {err:?}"
    );

    let alive = runtime
        .list_notes(&token, Some("observation"), 100, 0)
        .await
        .expect("list_notes")
        .into_iter()
        .filter(|n| n.deleted_at.is_none())
        .count();
    assert_eq!(
        alive, 0,
        "no note row may be committed on reservation rejection"
    );
}

#[tokio::test]
async fn create_notes_atomic_with_report_preserves_truncation_outcome() {
    let runtime = KhiveRuntime::memory().expect("in-memory runtime");
    runtime.register_embedder(TruncationProvider);
    let token = runtime
        .authorize(Namespace::parse("atomic-message-truncation-test").unwrap())
        .expect("authorize");
    let content = "x".repeat(MAX_TEXT_BYTES);

    let (notes, report) = create_notes_atomic_with_report(
        &runtime,
        vec![AtomicNoteSpec {
            token: &token,
            id: None,
            kind: "observation",
            name: None,
            content: &content,
            properties: None,
        }],
    )
    .await
    .expect("atomic note write");

    assert_eq!(notes.len(), 1);
    assert_eq!(report.truncated, 1);
    assert_eq!(
        report.discarded_bytes,
        "passage: ".len() as u64,
        "E5 document-prefix reservation must be reflected in the returned report"
    );
}

#[tokio::test]
async fn create_notes_atomic_reuses_identical_content_once_per_model() {
    let runtime = KhiveRuntime::memory().expect("in-memory runtime");
    for name in ["atomic-dedup-model-a", "atomic-dedup-model-b"] {
        runtime.register_embedder(DedupProvider { name });
    }
    let outbound_token = runtime
        .authorize(Namespace::parse("atomic-dedup-outbound").unwrap())
        .expect("authorize outbound");
    let inbound_token = runtime
        .authorize(Namespace::parse("atomic-dedup-inbound").unwrap())
        .expect("authorize inbound");
    let content = "byte-identical outbound and inbound message content";

    let usage = crate::usage::UsageContext::new();
    let notes = crate::usage::scope(usage.clone(), async {
        create_notes_atomic(
            &runtime,
            vec![
                AtomicNoteSpec {
                    token: &outbound_token,
                    id: None,
                    kind: "observation",
                    name: Some("shared subject"),
                    content,
                    properties: Some(serde_json::json!({"direction": "outbound"})),
                },
                AtomicNoteSpec {
                    token: &inbound_token,
                    id: None,
                    kind: "observation",
                    name: Some("shared subject"),
                    content,
                    properties: Some(serde_json::json!({"direction": "inbound"})),
                },
            ],
        )
        .await
    })
    .await
    .expect("atomic note pair");

    assert_eq!(notes.len(), 2);
    assert_eq!(notes[0].content, content);
    assert_eq!(notes[1].content, content);
    assert_eq!(
        usage.snapshot()["embed_calls"],
        2,
        "two identical notes across two models must issue one embed per model"
    );
    for model in ["atomic-dedup-model-a", "atomic-dedup-model-b"] {
        for (direction, token) in [("outbound", &outbound_token), ("inbound", &inbound_token)] {
            assert_eq!(
                runtime
                    .vectors_for_model(token, model)
                    .expect("vector store")
                    .count()
                    .await
                    .expect("vector count"),
                1,
                "the {direction} note must retain its vector row for {model}"
            );
        }
    }
}

/// Calling `create_notes_atomic` twice with the SAME caller-supplied id
/// (different content each time) must leave exactly one FTS document for
/// that id, reflecting the latest content — not an append of two
/// documents (the note row is already an upsert; the FTS half must match).
#[tokio::test]
async fn version_create_notes_atomic_upserts_fts_document_for_reused_note_id() {
    let runtime = KhiveRuntime::memory().expect("in-memory runtime");
    let ns = "atomic-message-fts-upsert-test";
    let token = runtime
        .authorize(Namespace::parse(ns).unwrap())
        .expect("authorize");
    let id = Uuid::new_v4();

    let first = create_notes_atomic(
        &runtime,
        vec![AtomicNoteSpec {
            token: &token,
            id: Some(id),
            kind: "observation",
            name: None,
            content: "first content",
            properties: None,
        }],
    )
    .await
    .expect("first write with supplied id");
    assert_eq!(first[0].version, 1);

    let second = create_notes_atomic(
        &runtime,
        vec![AtomicNoteSpec {
            token: &token,
            id: Some(id),
            kind: "observation",
            name: None,
            content: "second content replacing the first",
            properties: None,
        }],
    )
    .await
    .expect("second write reusing the same id");
    assert_eq!(second[0].version, 2);
    assert_eq!(
        runtime
            .notes(&token)
            .unwrap()
            .get_note(id)
            .await
            .unwrap()
            .unwrap()
            .version,
        2
    );
    let repeated = create_notes_atomic(
        &runtime,
        (0..2)
            .map(|_| AtomicNoteSpec {
                token: &token,
                id: Some(id),
                kind: "observation",
                name: None,
                content: "second content replacing the first",
                properties: None,
            })
            .collect(),
    )
    .await
    .expect("equal-value upserts in the same batch");
    assert_eq!(
        repeated.iter().map(|note| note.version).collect::<Vec<_>>(),
        vec![3, 4]
    );
    assert_eq!(
        runtime
            .notes(&token)
            .unwrap()
            .get_note(id)
            .await
            .unwrap()
            .unwrap()
            .version,
        4
    );

    assert_eq!(
        fts_row_count(&runtime, ns).await,
        1,
        "exactly one FTS document may exist for the reused id"
    );

    let text = runtime.text_for_notes(&token).expect("text store");
    let doc = text
        .get_document(ns, id)
        .await
        .expect("get_document")
        .expect("document exists for the reused id");
    assert!(
        doc.body.contains("second content"),
        "the surviving FTS document must reflect the latest content; got {:?}",
        doc.body
    );
}

/// ADR-124 regression: `create_notes_atomic_with_report` must run
/// `derive_note_write_properties` per spec, the same as every other
/// note-write site (`operations.rs`'s create funnel,
/// `atomic_prepare::prepare_add_note`). A caller holding a valid token
/// for one actor must not be able to plant an arbitrary `from_actor` (or
/// any other owner-established property) via `AtomicNoteSpec::properties`
/// — the installed validator's derived value must win.
///
/// This test fails if the `derive_note_write_properties` call in
/// `create_notes_atomic_with_report`'s spec loop is removed: verified by
/// deleting that call in a scratch copy of this file and re-running —
/// the assertion below turns red because the stored `from_actor` reverts
/// to the forged `"forged-actor"` value instead of the token's actor id.
#[tokio::test]
async fn create_notes_atomic_derives_from_actor_overwriting_a_forged_value() {
    let runtime = KhiveRuntime::memory().expect("in-memory runtime");
    runtime.install_note_write_validator(std::sync::Arc::new(stamp_from_actor));
    let ns = "atomic-message-identity-guard-test";
    let token = runtime
        .authorize(Namespace::parse(ns).unwrap())
        .expect("authorize");
    let true_actor = token.actor().id.clone();

    let notes = create_notes_atomic(
        &runtime,
        vec![AtomicNoteSpec {
            token: &token,
            id: None,
            kind: "observation",
            name: None,
            content: "atomic writer identity guard probe",
            properties: Some(serde_json::json!({"from_actor": "forged-actor"})),
        }],
    )
    .await
    .expect("atomic note write must succeed — the guard derives, it does not refuse");

    assert_eq!(notes.len(), 1);
    assert_eq!(
        notes[0]
            .properties
            .as_ref()
            .and_then(|p| p.get("from_actor"))
            .and_then(|v| v.as_str()),
        Some(true_actor.as_str()),
        "the atomic writer must store the token-derived from_actor, not the \
             caller-supplied forged value"
    );
}