khive-storage 0.21.0

Storage capability contracts and backend-neutral request context.
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
use super::*;

fn base_note() -> Note {
    Note::new("ns:test", "memory", "hello world")
}

#[test]
fn note_key_is_optional_and_unkeyed_wire_shape_is_unchanged() {
    let note = base_note();
    assert_eq!(note.key, None);
    let legacy = serde_json::to_value(&note).unwrap();
    assert!(legacy.get("key").is_none());
    assert_eq!(serde_json::from_value::<Note>(legacy).unwrap(), note);

    let mut keyed = note;
    keyed.key = Some("operation-1".to_string());
    let encoded = serde_json::to_value(&keyed).unwrap();
    assert_eq!(encoded["key"], "operation-1");
    assert_eq!(serde_json::from_value::<Note>(encoded).unwrap(), keyed);
}

// -- with_salience --

#[test]
fn with_salience_clamps_to_range() {
    let n = base_note().with_salience(1.5);
    assert_eq!(n.salience, Some(1.0));
    let n = base_note().with_salience(-0.1);
    assert_eq!(n.salience, Some(0.0));
    let n = base_note().with_salience(0.7);
    assert_eq!(n.salience, Some(0.7));
}

#[test]
fn with_salience_ignores_nan() {
    let n = base_note().with_salience(f64::NAN);
    assert_eq!(n.salience, None, "NaN must not set salience");
}

#[test]
fn with_salience_ignores_inf() {
    let n = base_note().with_salience(f64::INFINITY);
    assert_eq!(n.salience, None, "+Inf must not set salience");
    let n = base_note().with_salience(f64::NEG_INFINITY);
    assert_eq!(n.salience, None, "-Inf must not set salience");
}

// -- with_decay --

#[test]
fn with_decay_floors_at_zero() {
    let n = base_note().with_decay(-1.0);
    assert_eq!(n.decay_factor, Some(0.0));
    let n = base_note().with_decay(0.5);
    assert_eq!(n.decay_factor, Some(0.5));
}

#[test]
fn with_decay_ignores_nan() {
    let n = base_note().with_decay(f64::NAN);
    assert_eq!(n.decay_factor, None, "NaN must not set decay_factor");
}

#[test]
fn with_decay_ignores_inf() {
    let n = base_note().with_decay(f64::INFINITY);
    assert_eq!(n.decay_factor, None, "+Inf must not set decay_factor");
}

// -- try_with_salience --

#[test]
fn try_with_salience_accepts_valid_range() {
    let n = base_note().try_with_salience(0.0).unwrap();
    assert_eq!(n.salience, Some(0.0));
    let n = base_note().try_with_salience(1.0).unwrap();
    assert_eq!(n.salience, Some(1.0));
    let n = base_note().try_with_salience(0.85).unwrap();
    assert_eq!(n.salience, Some(0.85));
}

#[test]
fn try_with_salience_rejects_nan() {
    let err = base_note().try_with_salience(f64::NAN).unwrap_err();
    assert!(err.contains("finite"), "error must mention finite: {err}");
}

#[test]
fn try_with_salience_rejects_out_of_range() {
    let err = base_note().try_with_salience(1.1).unwrap_err();
    assert!(err.contains("1.0"), "error must mention bound: {err}");
    let err = base_note().try_with_salience(-0.01).unwrap_err();
    assert!(err.contains("0.0"), "error must mention bound: {err}");
}

// -- try_with_decay --

#[test]
fn try_with_decay_accepts_valid_values() {
    let n = base_note().try_with_decay(0.0).unwrap();
    assert_eq!(n.decay_factor, Some(0.0));
    let n = base_note().try_with_decay(2.5).unwrap();
    assert_eq!(n.decay_factor, Some(2.5));
}

#[test]
fn try_with_decay_rejects_nan() {
    let err = base_note().try_with_decay(f64::NAN).unwrap_err();
    assert!(err.contains("finite"), "error must mention finite: {err}");
}

#[test]
fn try_with_decay_rejects_negative() {
    let err = base_note().try_with_decay(-0.1).unwrap_err();
    assert!(err.contains("0.0"), "error must mention bound: {err}");
}

#[derive(Default)]
struct DefaultOnlyNoteStore {
    query_calls: std::sync::atomic::AtomicUsize,
    record_calls: std::sync::atomic::AtomicUsize,
}

impl DefaultOnlyNoteStore {
    fn query_call_count(&self) -> usize {
        self.query_calls.load(std::sync::atomic::Ordering::SeqCst)
    }
}

#[tokio::test]
async fn default_key_assignment_refuses_instead_of_emulating_a_write() {
    let store = DefaultOnlyNoteStore::default();
    let result = store
        .assign_note_key_if_unset(Uuid::new_v4(), "key", "local")
        .await;
    assert!(matches!(
        result,
        Err(crate::StorageError::Unsupported { .. })
    ));
    assert_eq!(
        store.record_calls.load(std::sync::atomic::Ordering::SeqCst),
        0
    );
}

fn unsupported<T>(operation: &'static str) -> StorageResult<T> {
    Err(crate::StorageError::Unsupported {
        capability: crate::StorageCapability::Notes,
        operation: operation.into(),
        message: "test double does not implement this operation".into(),
    })
}

#[async_trait]
impl NoteStore for DefaultOnlyNoteStore {
    async fn upsert_note(&self, _note: Note) -> StorageResult<()> {
        self.record_calls
            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        unsupported("upsert_note")
    }

    async fn upsert_notes(&self, _notes: Vec<Note>) -> StorageResult<BatchWriteSummary> {
        self.record_calls
            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        unsupported("upsert_notes")
    }

    async fn get_note(&self, _id: Uuid) -> StorageResult<Option<Note>> {
        self.record_calls
            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        unsupported("get_note")
    }

    async fn get_note_including_deleted(&self, _id: Uuid) -> StorageResult<Option<Note>> {
        self.record_calls
            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        unsupported("get_note_including_deleted")
    }

    async fn delete_note(&self, _id: Uuid, _mode: DeleteMode) -> StorageResult<bool> {
        unsupported("delete_note")
    }

    async fn update_note_properties(
        &self,
        _id: Uuid,
        _properties: Option<Value>,
        _updated_at: i64,
    ) -> StorageResult<bool> {
        unsupported("update_note_properties")
    }

    async fn set_note_property(
        &self,
        _id: Uuid,
        _key: &str,
        _value: Value,
        _updated_at: i64,
    ) -> StorageResult<bool> {
        unsupported("set_note_property")
    }

    async fn try_patch_note_property(
        &self,
        _id: Uuid,
        _namespace: &str,
        _filter: &NoteFilter,
        _json_path: &str,
        _value: Value,
        _updated_at: i64,
    ) -> StorageResult<bool> {
        unsupported("try_patch_note_property")
    }

    async fn query_notes(
        &self,
        _namespace: &str,
        _kind: Option<&str>,
        _page: PageRequest,
    ) -> StorageResult<Page<Note>> {
        self.query_calls
            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        Ok(Page {
            items: Vec::new(),
            total: Some(0),
        })
    }

    async fn query_notes_filtered(
        &self,
        _namespace: &str,
        _filter: &NoteFilter,
        _page: PageRequest,
    ) -> StorageResult<Page<Note>> {
        self.query_calls
            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        Ok(Page {
            items: Vec::new(),
            total: Some(0),
        })
    }

    async fn query_notes_filtered_bounded(
        &self,
        _namespace: &str,
        _filter: &NoteFilter,
        _max_rows: u32,
    ) -> StorageResult<Vec<Note>> {
        unsupported("query_notes_filtered_bounded")
    }

    async fn count_notes(&self, _namespace: &str, _kind: Option<&str>) -> StorageResult<u64> {
        unsupported("count_notes")
    }

    async fn try_insert_note(&self, _note: Note) -> StorageResult<bool> {
        unsupported("try_insert_note")
    }
}

#[tokio::test]
async fn default_partial_property_patch_is_fail_closed_without_read_or_upsert() {
    let store = DefaultOnlyNoteStore::default();
    let patch = NotePropertyPatch {
        preconditions: Vec::new(),
        set: [("delivered".into(), Value::Bool(true))].into(),
        extend_expires_at: Some(123),
        updated_at: 42,
    };
    let result = store
        .try_patch_note_properties(Uuid::new_v4(), "ns:test", "message", &patch)
        .await;
    assert!(
        matches!(
            result,
            Err(crate::StorageError::Unsupported {
                capability: crate::StorageCapability::Notes,
                ref operation,
                ..
            }) if operation == "try_patch_note_properties"
        ),
        "inherited partial patch must fail closed, got {result:?}"
    );
    assert_eq!(
        store.record_calls.load(std::sync::atomic::Ordering::SeqCst),
        0
    );
    assert_eq!(store.query_call_count(), 0);
}

#[tokio::test]
async fn default_snapshot_count_is_fail_closed_without_query_fallback() {
    let store = DefaultOnlyNoteStore::default();
    let result = store
        .count_notes_filtered_in_snapshot(
            "ns:test",
            &[NoteFilter::default(), NoteFilter::default()],
        )
        .await;

    assert!(
        matches!(
            result,
            Err(crate::StorageError::Unsupported { ref operation, .. })
                if operation == "count_notes_filtered_in_snapshot"
        ),
        "inherited snapshot count must fail closed, got {result:?}"
    );
    assert_eq!(
        store.query_call_count(),
        0,
        "inherited snapshot count must not fall back to independent queries"
    );
}

#[tokio::test]
async fn count_free_page_default_is_fail_closed_without_exact_query_fallback() {
    let store = DefaultOnlyNoteStore::default();
    let result = store
        .query_notes_filtered_count_free("ns:test", &NoteFilter::default(), PageRequest::default())
        .await;

    assert!(
        matches!(
            result,
            Err(crate::StorageError::Unsupported { ref operation, .. })
                if operation == "query_notes_filtered_count_free"
        ),
        "inherited count-free query must fail closed, got {result:?}"
    );
    assert_eq!(
        store.query_call_count(),
        0,
        "count-free default must not invoke the exact-count page"
    );
}

#[tokio::test]
async fn unfiltered_count_free_page_default_is_fail_closed_without_exact_query_fallback() {
    let store = DefaultOnlyNoteStore::default();
    let result = store
        .query_notes_count_free("ns:test", Some("message"), PageRequest::default())
        .await;

    assert!(
        matches!(
            result,
            Err(crate::StorageError::Unsupported { ref operation, .. })
                if operation == "query_notes_count_free"
        ),
        "inherited count-free query must fail closed, got {result:?}"
    );
    assert_eq!(
        store.query_call_count(),
        0,
        "count-free default must not invoke the exact-count page"
    );
}

#[tokio::test]
async fn bounded_snapshot_count_default_is_fail_closed_without_query_fallback() {
    let store = DefaultOnlyNoteStore::default();
    let result = store
        .count_notes_filtered_bounded_in_snapshot(
            "ns:test",
            &[NoteFilter::default(), NoteFilter::default()],
            1_000,
        )
        .await;

    assert!(
        matches!(
            result,
            Err(crate::StorageError::Unsupported { ref operation, .. })
                if operation == "count_notes_filtered_bounded_in_snapshot"
        ),
        "inherited bounded snapshot count must fail closed, got {result:?}"
    );
    assert_eq!(
        store.query_call_count(),
        0,
        "bounded snapshot count must not compose independent page queries"
    );
}

#[test]
fn key_limit_counts_utf8_bytes_and_rejects_nul() {
    assert!(note_key_is_valid(""));
    assert!(note_key_is_valid(&"é".repeat(256)));
    assert!(!note_key_is_valid(&"a".repeat(513)));
    assert!(!note_key_is_valid("before\0after"));
}

#[tokio::test]
async fn default_key_assignment_refuses_secrets_before_any_backend_call() {
    let store = DefaultOnlyNoteStore::default();
    let key = format!("ghp_{}", "A".repeat(40));
    let result = store
        .assign_note_key_if_unset(Uuid::new_v4(), &key, "local")
        .await;
    assert!(
        matches!(&result, Err(crate::StorageError::SecretDetected { .. })),
        "default assignment must report its own secret refusal: {result:?}"
    );
    assert_eq!(
        store.record_calls.load(std::sync::atomic::Ordering::SeqCst),
        0
    );
    assert_eq!(
        store.query_calls.load(std::sync::atomic::Ordering::SeqCst),
        0
    );
    assert!(
        note_key_is_valid(&key),
        "legacy read selectors remain shape-only"
    );
    for valid in ["", "Xk9mZ2vQpLrT8nJwYuAeHfBsDcGiONvM1"] {
        assert!(
            validate_note_key_for_store(valid, "assign_note_key_if_unset").is_ok(),
            "ordinary raw keys must not acquire a synthetic credential label"
        );
    }
    for invalid in ["x".repeat(513), "prefix\0suffix".into()] {
        assert!(matches!(
            validate_note_key_for_store(&invalid, "assign_note_key_if_unset"),
            Err(crate::StorageError::InvalidInput { .. })
        ));
    }
}