khive-storage 0.5.0

Storage capability traits: SqlAccess, VectorStore, TextSearch. Zero implementations — only contracts.
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
//! Graph edge types: edges, filters, traversal configuration, and path results.

use std::fmt;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use uuid::Uuid;

use khive_types::EdgeRelation;

use super::BatchWriteSummary;

/// A type-safe link ID (wraps Uuid).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct LinkId(pub Uuid);

impl From<Uuid> for LinkId {
    fn from(u: Uuid) -> Self {
        Self(u)
    }
}

impl From<LinkId> for Uuid {
    fn from(l: LinkId) -> Uuid {
        l.0
    }
}

impl fmt::Display for LinkId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// Raw deserialization target for [`Edge`].
#[derive(Deserialize)]
struct EdgeRaw {
    id: LinkId,
    namespace: String,
    source_id: Uuid,
    target_id: Uuid,
    relation: EdgeRelation,
    weight: f64,
    created_at: DateTime<Utc>,
    updated_at: DateTime<Utc>,
    deleted_at: Option<DateTime<Utc>>,
    metadata: Option<Value>,
    target_backend: Option<String>,
}

impl TryFrom<EdgeRaw> for Edge {
    type Error = String;

    fn try_from(raw: EdgeRaw) -> Result<Self, Self::Error> {
        if !raw.weight.is_finite() {
            return Err(format!("Edge: weight must be finite, got {}", raw.weight));
        }
        if !(0.0..=1.0).contains(&raw.weight) {
            return Err(format!(
                "Edge: weight must be in [0.0, 1.0], got {}",
                raw.weight
            ));
        }
        Ok(Self {
            id: raw.id,
            namespace: raw.namespace,
            source_id: raw.source_id,
            target_id: raw.target_id,
            relation: raw.relation,
            weight: raw.weight,
            created_at: raw.created_at,
            updated_at: raw.updated_at,
            deleted_at: raw.deleted_at,
            metadata: raw.metadata,
            target_backend: raw.target_backend,
        })
    }
}

/// A directed edge in the graph. Deserialization rejects non-finite weights.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(try_from = "EdgeRaw")]
pub struct Edge {
    pub id: LinkId,
    pub namespace: String,
    pub source_id: Uuid,
    pub target_id: Uuid,
    pub relation: EdgeRelation,
    pub weight: f64,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub deleted_at: Option<DateTime<Utc>>,
    pub metadata: Option<Value>,
    pub target_backend: Option<String>,
}

/// A page of edges returned by keyset (seek) pagination, ordered by `id`
/// ascending — an indexed range scan against the `(namespace, id)` primary
/// key rather than an `OFFSET` skip. `next_after` is `Some(last_id)` when
/// more rows remain past this page.
#[derive(Clone, Debug, Default)]
pub struct EdgeSeekPage {
    pub items: Vec<Edge>,
    pub next_after: Option<Uuid>,
}

/// Edge traversal direction relative to the source node.
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum Direction {
    #[default]
    Out,
    In,
    Both,
}

/// An inclusive time window for filtering records by timestamp.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct TimeRange {
    pub start: Option<DateTime<Utc>>,
    pub end: Option<DateTime<Utc>>,
}

/// Filter to restrict a graph edge query to a matching subset.
///
/// Use [`validate`](EdgeFilter::validate) to check weight-bound invariants
/// before passing to a backend.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(try_from = "EdgeFilterRaw")]
pub struct EdgeFilter {
    pub ids: Vec<LinkId>,
    pub source_ids: Vec<Uuid>,
    pub target_ids: Vec<Uuid>,
    pub relations: Vec<EdgeRelation>,
    pub min_weight: Option<f64>,
    pub max_weight: Option<f64>,
    pub created_at: Option<TimeRange>,
}

/// Raw deserialization target for [`EdgeFilter`].
#[derive(Deserialize, Default)]
struct EdgeFilterRaw {
    #[serde(default)]
    ids: Vec<LinkId>,
    #[serde(default)]
    source_ids: Vec<Uuid>,
    #[serde(default)]
    target_ids: Vec<Uuid>,
    #[serde(default)]
    relations: Vec<EdgeRelation>,
    min_weight: Option<f64>,
    max_weight: Option<f64>,
    created_at: Option<TimeRange>,
}

impl TryFrom<EdgeFilterRaw> for EdgeFilter {
    type Error = String;

    fn try_from(raw: EdgeFilterRaw) -> Result<Self, Self::Error> {
        let ef = Self {
            ids: raw.ids,
            source_ids: raw.source_ids,
            target_ids: raw.target_ids,
            relations: raw.relations,
            min_weight: raw.min_weight,
            max_weight: raw.max_weight,
            created_at: raw.created_at,
        };
        ef.validate()?;
        Ok(ef)
    }
}

impl EdgeFilter {
    /// Validate that weight bounds are finite, within [0.0, 1.0], and ordered correctly.
    /// Returns the first violation.
    pub fn validate(&self) -> Result<(), String> {
        if let Some(w) = self.min_weight {
            if !w.is_finite() {
                return Err(format!("EdgeFilter: min_weight is non-finite ({w})"));
            }
            if !(0.0..=1.0).contains(&w) {
                return Err(format!(
                    "EdgeFilter: min_weight must be in [0.0, 1.0], got {w}"
                ));
            }
        }
        if let Some(w) = self.max_weight {
            if !w.is_finite() {
                return Err(format!("EdgeFilter: max_weight is non-finite ({w})"));
            }
            if !(0.0..=1.0).contains(&w) {
                return Err(format!(
                    "EdgeFilter: max_weight must be in [0.0, 1.0], got {w}"
                ));
            }
        }
        if let (Some(lo), Some(hi)) = (self.min_weight, self.max_weight) {
            if lo > hi {
                return Err(format!("EdgeFilter: min_weight ({lo}) > max_weight ({hi})"));
            }
        }
        Ok(())
    }
}

/// Selects which edge attribute is used for sorting results.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum EdgeSortField {
    CreatedAt,
    Weight,
    Relation,
}

/// Ascending or descending sort order.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum SortDirection {
    Asc,
    Desc,
}

/// A sort specification pairing a field discriminant with a direction.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SortOrder<F> {
    pub field: F,
    pub direction: SortDirection,
}

/// Raw deserialization target for [`NeighborQuery`].
#[derive(Deserialize)]
struct NeighborQueryRaw {
    direction: Direction,
    relations: Option<Vec<EdgeRelation>>,
    limit: Option<u32>,
    min_weight: Option<f64>,
}

impl TryFrom<NeighborQueryRaw> for NeighborQuery {
    type Error = String;

    fn try_from(raw: NeighborQueryRaw) -> Result<Self, Self::Error> {
        if let Some(w) = raw.min_weight {
            if !w.is_finite() {
                return Err(format!("NeighborQuery: min_weight must be finite, got {w}"));
            }
            if !(0.0..=1.0).contains(&w) {
                return Err(format!(
                    "NeighborQuery: min_weight must be in [0.0, 1.0], got {w}"
                ));
            }
        }
        Ok(Self {
            direction: raw.direction,
            relations: raw.relations,
            limit: raw.limit,
            min_weight: raw.min_weight,
        })
    }
}

/// Parameters for a single-hop graph neighbor lookup. Deserialization rejects non-finite min_weight.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(try_from = "NeighborQueryRaw")]
pub struct NeighborQuery {
    pub direction: Direction,
    pub relations: Option<Vec<EdgeRelation>>,
    pub limit: Option<u32>,
    pub min_weight: Option<f64>,
}

/// One neighbor returned by a graph query.
///
/// Field naming (#148): on the JSON wire, the node identifier is serialized as
/// `id` (not `node_id`) so it matches the verb-wide identifier convention.
/// Internal Rust code still uses `.node_id` on the struct.
///
/// Enrichment (#162): `name` and `kind` are populated by the runtime layer
/// after the storage call returns. Storage `GraphStore` impls leave them
/// `None`; the runtime batch-fetches the entity rows and fills them in.
///
/// Optional enrichment: `entity_type` is populated by the runtime when the
/// caller passes `include_entity_type=true` to the `neighbors` verb. It is
/// absent from the wire when `None` so the default result shape is unchanged.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct NeighborHit {
    #[serde(rename = "id")]
    pub node_id: Uuid,
    pub edge_id: Uuid,
    pub relation: EdgeRelation,
    pub weight: f64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kind: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub entity_type: Option<String>,
}

/// A [`NeighborHit`] tagged with the direction it was found in, relative to
/// the queried node. Returned by [`crate::GraphStore::neighbors_both_directions`],
/// which fetches both directions in a single `UNION ALL` query instead of two
/// separate direction-scoped calls — the tag lets a caller (e.g. the `context`
/// verb) label each hit `outgoing`/`incoming` without paying for the second
/// query. Only `Direction::Out` and `Direction::In` are ever populated here.
#[derive(Clone, Debug)]
pub struct DirectedNeighborHit {
    pub hit: NeighborHit,
    pub direction: Direction,
}

/// Raw deserialization target for [`TraversalOptions`].
#[derive(Deserialize)]
struct TraversalOptionsRaw {
    max_depth: usize,
    direction: Direction,
    relations: Option<Vec<EdgeRelation>>,
    min_weight: Option<f64>,
    limit: Option<u32>,
}

impl TryFrom<TraversalOptionsRaw> for TraversalOptions {
    type Error = String;

    fn try_from(raw: TraversalOptionsRaw) -> Result<Self, Self::Error> {
        if let Some(w) = raw.min_weight {
            if !w.is_finite() {
                return Err(format!(
                    "TraversalOptions: min_weight must be finite, got {w}"
                ));
            }
            if !(0.0..=1.0).contains(&w) {
                return Err(format!(
                    "TraversalOptions: min_weight must be in [0.0, 1.0], got {w}"
                ));
            }
        }
        if raw.max_depth > i64::MAX as usize {
            return Err(format!(
                "TraversalOptions: max_depth must be <= i64::MAX, got {}",
                raw.max_depth
            ));
        }
        Ok(Self {
            max_depth: raw.max_depth,
            direction: raw.direction,
            relations: raw.relations,
            min_weight: raw.min_weight,
            limit: raw.limit,
        })
    }
}

/// BFS traversal configuration controlling depth, direction, and edge filters.
/// Deserialization rejects non-finite min_weight.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(try_from = "TraversalOptionsRaw")]
pub struct TraversalOptions {
    pub max_depth: usize,
    pub direction: Direction,
    pub relations: Option<Vec<EdgeRelation>>,
    pub min_weight: Option<f64>,
    pub limit: Option<u32>,
}

impl Default for TraversalOptions {
    fn default() -> Self {
        Self {
            max_depth: 3,
            direction: Direction::Out,
            relations: None,
            min_weight: None,
            limit: None,
        }
    }
}

impl TraversalOptions {
    /// Create traversal options with the given maximum depth.
    pub fn new(max_depth: usize) -> Self {
        Self {
            max_depth,
            ..Default::default()
        }
    }

    /// Set the traversal direction.
    pub fn with_direction(mut self, d: Direction) -> Self {
        self.direction = d;
        self
    }
}

/// Raw deserialization target for [`TraversalRequest`].
#[derive(Deserialize)]
struct TraversalRequestRaw {
    roots: Vec<Uuid>,
    options: TraversalOptionsRaw,
    include_roots: bool,
    #[serde(default)]
    include_properties: bool,
}

impl TryFrom<TraversalRequestRaw> for TraversalRequest {
    type Error = String;

    fn try_from(raw: TraversalRequestRaw) -> Result<Self, Self::Error> {
        Ok(Self {
            roots: raw.roots,
            options: TraversalOptions::try_from(raw.options)?,
            include_roots: raw.include_roots,
            include_properties: raw.include_properties,
        })
    }
}

/// A graph traversal request from a set of root nodes.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(try_from = "TraversalRequestRaw")]
pub struct TraversalRequest {
    pub roots: Vec<Uuid>,
    pub options: TraversalOptions,
    pub include_roots: bool,
    /// When `true`, `enrich_path_nodes` populates the `properties` map on each
    /// `PathNode`. Default `false`; the wire shape is unchanged when absent.
    #[serde(default)]
    pub include_properties: bool,
}

/// One node along a traversal path.
///
/// Field naming (#148): JSON wire serialization is `id`. Enrichment (#162):
/// `name`/`kind` are filled by the runtime layer after the storage call.
///
/// Optional enrichment: `properties` is populated by the runtime when the
/// caller passes `include_properties=true` to the `traverse` verb. It is
/// absent from the wire when `None` so the default result shape is unchanged.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PathNode {
    #[serde(rename = "id")]
    pub node_id: Uuid,
    pub via_edge: Option<Uuid>,
    pub depth: usize,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kind: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub properties: Option<Value>,
}

/// A complete traversal path from one root node to its reachable descendants.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GraphPath {
    pub root_id: Uuid,
    pub nodes: Vec<PathNode>,
    pub total_weight: f64,
}

/// Which of a would-be edge's two endpoints were missing when a guarded
/// write's in-transaction existence check refused it (#769). Produced by
/// the guard's own commit-time probe, not a
/// post-hoc read after the write already failed, so a concurrent
/// hard-delete landing after the guard ran cannot make this outcome lie
/// about which endpoint was actually missing at write time.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct MissingEndpoints {
    pub source: bool,
    pub target: bool,
}

impl MissingEndpoints {
    /// True if at least one endpoint was reported missing.
    pub fn any(&self) -> bool {
        self.source || self.target
    }
}

/// Outcome of [`crate::GraphStore::upsert_edge_guarded`], determined entirely
/// inside the guard's own storage transaction.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum GuardedWriteOutcome {
    /// The edge was inserted or updated; both endpoints existed at write time.
    Written,
    /// The write was refused; `MissingEndpoints` names which endpoint(s) were
    /// gone at write time.
    Refused(MissingEndpoints),
}

/// Which batch entry a guarded batch write refused on, and why, determined
/// inside the same in-transaction pre-check that aborted the batch.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GuardedBatchRefusal {
    /// Index of the first batch entry whose endpoint(s) were missing.
    pub entry_index: usize,
    pub missing: MissingEndpoints,
}

/// Outcome of [`crate::GraphStore::upsert_edges_guarded`]. `refused` is
/// `Some` exactly when `summary.affected == 0` after a guard refusal;
/// `None` when every edge in the batch was written.
#[derive(Clone, Debug)]
pub struct GuardedBatchOutcome {
    pub summary: BatchWriteSummary,
    pub refused: Option<GuardedBatchRefusal>,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn traversal_options_default_max_depth_is_three() {
        assert_eq!(TraversalOptions::default().max_depth, 3);
    }

    /// STORAGE-AUD-003 / #485: max_depth > i64::MAX must be rejected by serde
    /// deserialization instead of silently narrowing to a negative i64 at the
    /// SQLite traversal boundary.
    #[test]
    #[cfg(target_pointer_width = "64")]
    fn traverse_max_depth_over_i64max_rejected() {
        let raw = serde_json::json!({
            "max_depth": (i64::MAX as u64) + 1,
            "direction": "out",
            "relations": null,
            "min_weight": null,
            "limit": null,
        });
        let result: Result<TraversalOptions, _> = serde_json::from_value(raw);
        assert!(
            result.is_err(),
            "max_depth > i64::MAX must be rejected, got {result:?}"
        );
    }

    #[test]
    #[cfg(target_pointer_width = "64")]
    fn traverse_max_depth_at_i64max_accepted() {
        let raw = serde_json::json!({
            "max_depth": i64::MAX as u64,
            "direction": "out",
            "relations": null,
            "min_weight": null,
            "limit": null,
        });
        let result: Result<TraversalOptions, _> = serde_json::from_value(raw);
        assert!(result.is_ok(), "max_depth == i64::MAX must be accepted");
    }
}