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
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
// Copyright 2026 khive contributors. Licensed under Apache-2.0.
//
//! KG export / import — portable JSON archive for namespace-scoped knowledge graphs.
//!
//! Implements the v1 portability format described in ADR-010. Embeddings are
//! intentionally excluded: they are regenerable from the embedding model + text
//! and their inclusion would lock the format to a specific model.
//!
//! # Edge namespace enumeration
//!
//! `GraphStore::query_edges` has no namespace column — edges are linked to entities,
//! not namespaces. Export collects all entity IDs in the namespace first, then
//! queries edges where source_id is in that set. This covers every edge whose
//! source entity belongs to the namespace, which is the correct definition of
//! "edges in a namespace" for an export that preserves referential integrity.
use std::collections::HashSet;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use khive_storage::types::{EdgeFilter, LinkId, PageRequest};
use khive_storage::{EdgeRelation, EntityFilter};
use crate::error::{RuntimeError, RuntimeResult};
use crate::runtime::KhiveRuntime;
// ── Archive types ─────────────────────────────────────────────────────────────
/// Portable JSON archive of a namespace-scoped knowledge graph.
///
/// The `format` field is always `"khive-kg"`. The `version` field identifies
/// the serialization schema; parsers should reject unknown versions.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct KgArchive {
pub format: String,
pub version: String,
pub namespace: String,
pub exported_at: DateTime<Utc>,
pub entities: Vec<ExportedEntity>,
pub edges: Vec<ExportedEdge>,
}
/// An entity record in the portable archive.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ExportedEntity {
pub id: Uuid,
/// Pack-owned kind string (e.g. `"concept"`, `"person"`).
pub kind: String,
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub properties: Option<serde_json::Value>,
#[serde(default)]
pub tags: Vec<String>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
/// A directed edge record in the portable archive.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ExportedEdge {
/// Stable edge identity across export/import cycles (ADR-048 D1).
///
/// Old archives (pre-0.2) omit this field. `serde(default)` assigns a fresh
/// UUID on import so backward-compatible archives are accepted as-is.
#[serde(default = "Uuid::new_v4")]
pub edge_id: Uuid,
pub source: Uuid,
pub target: Uuid,
/// One of the 13 canonical relations defined in ADR-002.
pub relation: EdgeRelation,
pub weight: f64,
}
/// Outcome of a successful import operation.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ImportSummary {
pub entities_imported: usize,
pub edges_imported: usize,
/// Number of edges that were skipped because one or both endpoint UUIDs
/// were not found in the target namespace after entity import.
///
/// A non-zero value indicates the archive contained dangling edges (edges
/// referencing entities not present in the archive or the existing graph).
pub edges_skipped: usize,
}
// ── KhiveRuntime impl ─────────────────────────────────────────────────────────
impl KhiveRuntime {
/// Export all entities and edges in a namespace to a portable JSON archive.
///
/// Edge collection: all entity IDs in the namespace are gathered first;
/// `query_edges` is then called with those IDs as `source_ids`. This
/// captures every edge whose source entity belongs to the namespace.
pub async fn export_kg(&self, namespace: Option<&str>) -> RuntimeResult<KgArchive> {
let ns = self.ns(namespace).to_string();
// 1. Collect all entities in the namespace.
let entity_page = self
.entities(Some(&ns))?
.query_entities(
&ns,
EntityFilter::default(),
PageRequest {
offset: 0,
limit: u32::MAX,
},
)
.await?;
let entities: Vec<ExportedEntity> = entity_page
.items
.into_iter()
.map(|e| {
let created_at =
DateTime::from_timestamp_micros(e.created_at).unwrap_or_else(Utc::now);
let updated_at =
DateTime::from_timestamp_micros(e.updated_at).unwrap_or_else(Utc::now);
ExportedEntity {
id: e.id,
kind: e.kind.to_string(),
name: e.name,
description: e.description,
properties: e.properties,
tags: e.tags,
created_at,
updated_at,
}
})
.collect();
// 2. Collect edges whose source is any entity in this namespace.
let source_ids: Vec<Uuid> = entities.iter().map(|e| e.id).collect();
let edges = if source_ids.is_empty() {
Vec::new()
} else {
let filter = EdgeFilter {
source_ids: source_ids.clone(),
..Default::default()
};
let edge_page = self
.graph(Some(&ns))?
.query_edges(
filter,
Vec::new(),
PageRequest {
offset: 0,
limit: u32::MAX,
},
)
.await?;
let id_set: HashSet<Uuid> = source_ids.into_iter().collect();
edge_page
.items
.into_iter()
.filter(|e| id_set.contains(&e.source_id))
.map(|e| ExportedEdge {
edge_id: e.id.into(),
source: e.source_id,
target: e.target_id,
relation: e.relation,
weight: e.weight,
})
.collect()
};
Ok(KgArchive {
format: "khive-kg".to_string(),
version: "0.1".to_string(),
namespace: ns,
exported_at: Utc::now(),
entities,
edges,
})
}
/// Export to a JSON string (convenience wrapper around `export_kg`).
pub async fn export_kg_json(&self, namespace: Option<&str>) -> RuntimeResult<String> {
let archive = self.export_kg(namespace).await?;
serde_json::to_string(&archive).map_err(|e| RuntimeError::InvalidInput(e.to_string()))
}
/// Import an archive into `target_namespace`.
///
/// If `target_namespace` is `None`, the archive's own namespace is used.
///
/// - Entities: upserted by ID; existing records are overwritten.
/// - Edges: upserted; existing records are overwritten.
/// - Validation: `format != "khive-kg"` or unsupported version → `InvalidInput`.
/// Invalid edge relations are caught at JSON deserialization time.
pub async fn import_kg(
&self,
archive: &KgArchive,
target_namespace: Option<&str>,
) -> RuntimeResult<ImportSummary> {
// Format validation.
if archive.format != "khive-kg" {
return Err(RuntimeError::InvalidInput(format!(
"unsupported archive format {:?}; expected \"khive-kg\"",
archive.format
)));
}
if archive.version != "0.1" {
return Err(RuntimeError::InvalidInput(format!(
"unsupported archive version {:?}; supported: \"0.1\"",
archive.version
)));
}
let ns = target_namespace.unwrap_or(&archive.namespace).to_string();
// Import entities.
let store = self.entities(Some(&ns))?;
let mut entities_imported = 0usize;
for ee in &archive.entities {
let created_micros = ee.created_at.timestamp_micros();
let updated_micros = ee.updated_at.timestamp_micros();
let entity = khive_storage::entity::Entity {
id: ee.id,
namespace: ns.clone(),
kind: ee.kind.clone(),
name: ee.name.clone(),
description: ee.description.clone(),
properties: ee.properties.clone(),
tags: ee.tags.clone(),
created_at: created_micros,
updated_at: updated_micros,
deleted_at: None,
};
store.upsert_entity(entity.clone()).await?;
// Index into FTS5 (and vector store if a model is configured) so that
// imported entities are visible to hybrid_search immediately.
self.reindex_entity(Some(&ns), &entity).await?;
entities_imported += 1;
}
// Import edges — validate both endpoints before inserting.
//
// An untrusted archive may contain edges whose source or target UUIDs
// do not correspond to any entity in the target namespace. Inserting
// such edges would leave dangling references in the graph store. We
// therefore check each endpoint with `get_entity` (namespace-scoped,
// fail-closed) and skip any edge whose source or target is absent.
let graph = self.graph(Some(&ns))?;
let mut edges_imported = 0usize;
let mut edges_skipped = 0usize;
for ee in &archive.edges {
let source_ok = self.get_entity(Some(&ns), ee.source).await?.is_some();
if !source_ok {
tracing::warn!(
source = %ee.source,
target = %ee.target,
relation = ?ee.relation,
"import_kg: skipping edge — source entity not found in namespace {ns:?}"
);
edges_skipped += 1;
continue;
}
let target_ok = self.get_entity(Some(&ns), ee.target).await?.is_some();
if !target_ok {
tracing::warn!(
source = %ee.source,
target = %ee.target,
relation = ?ee.relation,
"import_kg: skipping edge — target entity not found in namespace {ns:?}"
);
edges_skipped += 1;
continue;
}
let edge = khive_storage::types::Edge {
id: LinkId::from(ee.edge_id),
source_id: ee.source,
target_id: ee.target,
relation: ee.relation,
weight: ee.weight,
created_at: Utc::now(),
metadata: None,
};
graph.upsert_edge(edge).await?;
edges_imported += 1;
}
Ok(ImportSummary {
entities_imported,
edges_imported,
edges_skipped,
})
}
/// Import from a JSON string (convenience wrapper around `import_kg`).
pub async fn import_kg_json(
&self,
json: &str,
target_namespace: Option<&str>,
) -> RuntimeResult<ImportSummary> {
let archive: KgArchive =
serde_json::from_str(json).map_err(|e| RuntimeError::InvalidInput(e.to_string()))?;
self.import_kg(&archive, target_namespace).await
}
}
// ── Tests ─────────────────────────────────────────────────────────────────────
#[cfg(test)]
mod tests {
use super::*;
use crate::runtime::KhiveRuntime;
use khive_storage::EdgeRelation;
async fn make_rt() -> KhiveRuntime {
KhiveRuntime::memory().expect("in-memory runtime")
}
/// 1. Roundtrip: 3 entities + 2 edges survive export → import on a fresh runtime.
#[tokio::test]
async fn roundtrip_entities_and_edges() {
let src = make_rt().await;
let e1 = src
.create_entity(
None,
"concept",
"FlashAttention",
Some("fast attention"),
None,
vec![],
)
.await
.unwrap();
let e2 = src
.create_entity(None, "concept", "FlashAttention-2", None, None, vec![])
.await
.unwrap();
let e3 = src
.create_entity(None, "person", "Tri Dao", None, None, vec!["author".into()])
.await
.unwrap();
src.link(None, e2.id, e1.id, EdgeRelation::Extends, 1.0)
.await
.unwrap();
src.link(None, e1.id, e3.id, EdgeRelation::IntroducedBy, 0.9)
.await
.unwrap();
let archive = src.export_kg(None).await.unwrap();
assert_eq!(archive.entities.len(), 3);
assert_eq!(archive.edges.len(), 2);
assert_eq!(archive.format, "khive-kg");
assert_eq!(archive.version, "0.1");
let dst = make_rt().await;
let summary = dst.import_kg(&archive, None).await.unwrap();
assert_eq!(summary.entities_imported, 3);
assert_eq!(summary.edges_imported, 2);
// Spot-check: the imported entity is retrievable.
let got = dst.get_entity(None, e1.id).await.unwrap();
assert!(got.is_some());
let got = got.unwrap();
assert_eq!(got.name, "FlashAttention");
assert_eq!(got.description.as_deref(), Some("fast attention"));
}
/// 2. JSON roundtrip: export_kg_json → import_kg_json produces equivalent state.
#[tokio::test]
async fn json_roundtrip() {
let src = make_rt().await;
let e1 = src
.create_entity(
None,
"concept",
"LoRA",
Some("low-rank adaptation"),
Some(serde_json::json!({"year": "2021"})),
vec!["fine-tuning".into()],
)
.await
.unwrap();
let e2 = src
.create_entity(None, "concept", "QLoRA", None, None, vec![])
.await
.unwrap();
src.link(None, e2.id, e1.id, EdgeRelation::VariantOf, 0.9)
.await
.unwrap();
let json_str = src.export_kg_json(None).await.unwrap();
assert!(json_str.contains("khive-kg"));
let dst = make_rt().await;
let summary = dst.import_kg_json(&json_str, None).await.unwrap();
assert_eq!(summary.entities_imported, 2);
assert_eq!(summary.edges_imported, 1);
let got = dst.get_entity(None, e1.id).await.unwrap().unwrap();
assert_eq!(got.tags, vec!["fine-tuning"]);
}
/// 3. Namespace targeting: export from namespace "a", import into namespace "b" on a
/// fresh runtime — entities land in "b", and the source runtime's "a" is unaffected.
///
/// Note: source and destination are separate runtimes (separate in-memory DBs).
/// Same-DB cross-namespace copy is not a portability use case — portability is about
/// moving graphs between instances, not between namespaces within one instance.
#[tokio::test]
async fn namespace_targeting() {
let src = make_rt().await;
src.create_entity(Some("a"), "concept", "Sinkhorn", None, None, vec![])
.await
.unwrap();
let archive = src.export_kg(Some("a")).await.unwrap();
assert_eq!(archive.namespace, "a");
// Import into a fresh runtime, targeting namespace "b".
let dst = make_rt().await;
let summary = dst.import_kg(&archive, Some("b")).await.unwrap();
assert_eq!(summary.entities_imported, 1);
// Entity is in "b" on the destination runtime.
let in_b = dst.list_entities(Some("b"), None, 100, 0).await.unwrap();
assert_eq!(in_b.len(), 1);
assert_eq!(in_b[0].name, "Sinkhorn");
// Namespace "a" on the source runtime is unchanged.
let in_a = src.list_entities(Some("a"), None, 100, 0).await.unwrap();
assert_eq!(in_a.len(), 1);
// Namespace "a" on the destination runtime has nothing (only "b" was written).
let dst_a = dst.list_entities(Some("a"), None, 100, 0).await.unwrap();
assert_eq!(dst_a.len(), 0);
}
/// 4. Format validation: wrong `format` field → InvalidInput.
#[tokio::test]
async fn format_validation_rejects_wrong_format() {
let rt = make_rt().await;
let bad = KgArchive {
format: "wrong".to_string(),
version: "0.1".to_string(),
namespace: "local".to_string(),
exported_at: Utc::now(),
entities: vec![],
edges: vec![],
};
let err = rt.import_kg(&bad, None).await.unwrap_err();
assert!(matches!(err, RuntimeError::InvalidInput(_)));
}
/// 5. Unsupported archive version → InvalidInput.
#[tokio::test]
async fn import_unsupported_archive_version_returns_error() {
let rt = make_rt().await;
let bad = KgArchive {
format: "khive-kg".to_string(),
version: "999.0".to_string(),
namespace: "local".to_string(),
exported_at: Utc::now(),
entities: vec![],
edges: vec![],
};
let err = rt.import_kg(&bad, None).await.unwrap_err();
assert!(
matches!(err, RuntimeError::InvalidInput(_)),
"expected InvalidInput, got {err:?}"
);
if let RuntimeError::InvalidInput(msg) = err {
assert!(
msg.contains("999.0"),
"error message should mention the unsupported version, got: {msg:?}"
);
}
}
/// 6. Invalid relation in archive → InvalidInput.
#[test]
fn invalid_relation_rejected_at_deserialize() {
let json = r#"{
"format":"khive-kg","version":"0.1","namespace":"local",
"exported_at":"2026-01-01T00:00:00Z",
"entities":[],
"edges":[{"edge_id":"00000000-0000-0000-0000-000000000099",
"source":"00000000-0000-0000-0000-000000000001",
"target":"00000000-0000-0000-0000-000000000002",
"relation":"related_to","weight":0.5}]
}"#;
let result: Result<KgArchive, _> = serde_json::from_str(json);
assert!(
result.is_err(),
"non-canonical relation should fail to deserialize"
);
}
// ── Dangling-edge validation tests (issue #28) ────────────────────────────
/// 6. Edge with dangling source (source UUID not in entity table) is skipped.
///
/// The archive has one entity + one edge whose source is a phantom UUID.
/// Import succeeds, entities_imported=1, edges_imported=0, edges_skipped=1.
#[tokio::test]
async fn import_edge_with_dangling_source_is_skipped() {
let phantom_source = Uuid::parse_str("deadbeef-dead-4ead-dead-deadbeefcafe").unwrap();
let rt = make_rt().await;
// Create an entity that will be the real target.
let real = rt
.create_entity(None, "concept", "Real", None, None, vec![])
.await
.unwrap();
// Build archive manually: one real entity, one edge with phantom source.
let archive = KgArchive {
format: "khive-kg".to_string(),
version: "0.1".to_string(),
namespace: "local".to_string(),
exported_at: Utc::now(),
entities: vec![ExportedEntity {
id: real.id,
kind: "concept".to_string(),
name: "Real".to_string(),
description: None,
properties: None,
tags: vec![],
created_at: Utc::now(),
updated_at: Utc::now(),
}],
edges: vec![ExportedEdge {
edge_id: Uuid::new_v4(),
source: phantom_source,
target: real.id,
relation: EdgeRelation::Extends,
weight: 1.0,
}],
};
let dst = make_rt().await;
let summary = dst.import_kg(&archive, None).await.unwrap();
assert_eq!(summary.entities_imported, 1);
assert_eq!(
summary.edges_imported, 0,
"dangling source must not be imported"
);
assert_eq!(
summary.edges_skipped, 1,
"dangling source must be counted as skipped"
);
}
/// 7. Edge with dangling target (target UUID not in entity table) is skipped.
///
/// The archive has one entity + one edge whose target is a phantom UUID.
/// Import succeeds, entities_imported=1, edges_imported=0, edges_skipped=1.
#[tokio::test]
async fn import_edge_with_dangling_target_is_skipped() {
let phantom_target = Uuid::parse_str("cafebabe-cafe-4abe-cafe-cafebabecafe").unwrap();
let rt = make_rt().await;
let real = rt
.create_entity(None, "concept", "Source", None, None, vec![])
.await
.unwrap();
let archive = KgArchive {
format: "khive-kg".to_string(),
version: "0.1".to_string(),
namespace: "local".to_string(),
exported_at: Utc::now(),
entities: vec![ExportedEntity {
id: real.id,
kind: "concept".to_string(),
name: "Source".to_string(),
description: None,
properties: None,
tags: vec![],
created_at: Utc::now(),
updated_at: Utc::now(),
}],
edges: vec![ExportedEdge {
edge_id: Uuid::new_v4(),
source: real.id,
target: phantom_target,
relation: EdgeRelation::DependsOn,
weight: 0.8,
}],
};
let dst = make_rt().await;
let summary = dst.import_kg(&archive, None).await.unwrap();
assert_eq!(summary.entities_imported, 1);
assert_eq!(
summary.edges_imported, 0,
"dangling target must not be imported"
);
assert_eq!(
summary.edges_skipped, 1,
"dangling target must be counted as skipped"
);
}
/// 8. Mixed batch: some valid edges and some dangling edges — correct counts reported.
///
/// Archive has 3 entities, 2 valid edges, and 1 dangling edge (phantom target).
/// Import succeeds with edges_imported=2, edges_skipped=1.
#[tokio::test]
async fn import_mixed_edges_reports_correct_counts() {
let phantom = Uuid::parse_str("11111111-1111-4111-8111-111111111111").unwrap();
let src = make_rt().await;
let a = src
.create_entity(None, "concept", "A", None, None, vec![])
.await
.unwrap();
let b = src
.create_entity(None, "concept", "B", None, None, vec![])
.await
.unwrap();
let c = src
.create_entity(None, "concept", "C", None, None, vec![])
.await
.unwrap();
// Build archive with 3 entities and 3 edges: 2 valid, 1 dangling.
let archive = KgArchive {
format: "khive-kg".to_string(),
version: "0.1".to_string(),
namespace: "local".to_string(),
exported_at: Utc::now(),
entities: vec![
ExportedEntity {
id: a.id,
kind: "concept".to_string(),
name: "A".to_string(),
description: None,
properties: None,
tags: vec![],
created_at: Utc::now(),
updated_at: Utc::now(),
},
ExportedEntity {
id: b.id,
kind: "concept".to_string(),
name: "B".to_string(),
description: None,
properties: None,
tags: vec![],
created_at: Utc::now(),
updated_at: Utc::now(),
},
ExportedEntity {
id: c.id,
kind: "concept".to_string(),
name: "C".to_string(),
description: None,
properties: None,
tags: vec![],
created_at: Utc::now(),
updated_at: Utc::now(),
},
],
edges: vec![
// Valid: A → B
ExportedEdge {
edge_id: Uuid::new_v4(),
source: a.id,
target: b.id,
relation: EdgeRelation::Extends,
weight: 1.0,
},
// Valid: B → C
ExportedEdge {
edge_id: Uuid::new_v4(),
source: b.id,
target: c.id,
relation: EdgeRelation::DependsOn,
weight: 0.9,
},
// Dangling: A → phantom
ExportedEdge {
edge_id: Uuid::new_v4(),
source: a.id,
target: phantom,
relation: EdgeRelation::Enables,
weight: 0.5,
},
],
};
let dst = make_rt().await;
let summary = dst.import_kg(&archive, None).await.unwrap();
assert_eq!(summary.entities_imported, 3);
assert_eq!(
summary.edges_imported, 2,
"only valid edges must be imported"
);
assert_eq!(
summary.edges_skipped, 1,
"one dangling edge must be reported"
);
}
/// 9. All-valid edges produce edges_skipped=0 (no regression on the happy path).
#[tokio::test]
async fn import_all_valid_edges_reports_zero_skipped() {
let src = make_rt().await;
let e1 = src
.create_entity(None, "concept", "E1", None, None, vec![])
.await
.unwrap();
let e2 = src
.create_entity(None, "concept", "E2", None, None, vec![])
.await
.unwrap();
src.link(None, e1.id, e2.id, EdgeRelation::VariantOf, 0.7)
.await
.unwrap();
let archive = src.export_kg(None).await.unwrap();
let dst = make_rt().await;
let summary = dst.import_kg(&archive, None).await.unwrap();
assert_eq!(summary.edges_imported, 1);
assert_eq!(
summary.edges_skipped, 0,
"no edges should be skipped when all endpoints exist"
);
}
// ── edge_id contract tests (ADR-048 D1) ──────────────────────────────────
/// 10. export_kg sets edge_id in the archive to the LinkId returned by link.
#[tokio::test]
async fn export_kg_preserves_edge_id() {
let rt = make_rt().await;
let a = rt
.create_entity(None, "concept", "Alpha", None, None, vec![])
.await
.unwrap();
let b = rt
.create_entity(None, "concept", "Beta", None, None, vec![])
.await
.unwrap();
let stored_edge = rt
.link(None, a.id, b.id, EdgeRelation::Extends, 1.0)
.await
.unwrap();
let stored_id: Uuid = stored_edge.id.into();
let archive = rt.export_kg(None).await.unwrap();
assert_eq!(archive.edges.len(), 1);
assert_eq!(
archive.edges[0].edge_id, stored_id,
"exported edge_id must equal the LinkId returned by link"
);
}
/// 11. import_kg writes the archive edge_id as the stored LinkId.
#[tokio::test]
async fn import_kg_persists_edge_id() {
let src = make_rt().await;
let a = src
.create_entity(None, "concept", "Alpha", None, None, vec![])
.await
.unwrap();
let b = src
.create_entity(None, "concept", "Beta", None, None, vec![])
.await
.unwrap();
let stored_edge = src
.link(None, a.id, b.id, EdgeRelation::Extends, 1.0)
.await
.unwrap();
let original_id: Uuid = stored_edge.id.into();
let archive = src.export_kg(None).await.unwrap();
let dst = make_rt().await;
dst.import_kg(&archive, None).await.unwrap();
// The imported edge must carry the same UUID as the original.
let imported_edge = dst.get_edge(None, original_id).await.unwrap();
assert!(
imported_edge.is_some(),
"imported edge must be retrievable by the original edge_id"
);
let imported_edge = imported_edge.unwrap();
assert_eq!(
Uuid::from(imported_edge.id),
original_id,
"stored edge id must equal the archive edge_id"
);
}
/// 12. Old archive (no edge_id field) deserializes, imports, and re-exports with the
/// same generated UUID — proving the generated ID survives the full round trip.
///
/// The fixture includes two entities so the edge is not skipped during import.
#[tokio::test]
async fn old_archive_missing_edge_id_round_trips() {
// Two entity UUIDs that will appear in both the fixture and the entity list.
let src_id = Uuid::parse_str("00000000-0000-0000-0000-000000000001").unwrap();
let tgt_id = Uuid::parse_str("00000000-0000-0000-0000-000000000002").unwrap();
// Simulate a pre-0.2 archive JSON where the edge lacks an edge_id field.
let json = format!(
r#"{{
"format": "khive-kg",
"version": "0.1",
"namespace": "local",
"exported_at": "2026-01-01T00:00:00Z",
"entities": [
{{"id":"{src_id}","kind":"concept","name":"SrcNode","created_at":"2026-01-01T00:00:00Z","updated_at":"2026-01-01T00:00:00Z"}},
{{"id":"{tgt_id}","kind":"concept","name":"TgtNode","created_at":"2026-01-01T00:00:00Z","updated_at":"2026-01-01T00:00:00Z"}}
],
"edges": [
{{
"source": "{src_id}",
"target": "{tgt_id}",
"relation": "extends",
"weight": 0.9
}}
]
}}"#
);
// Deserialize: serde(default) must assign a non-nil UUID.
let archive: KgArchive = serde_json::from_str(&json)
.expect("old archive without edge_id must deserialize successfully");
assert_eq!(archive.edges.len(), 1);
let generated_id = archive.edges[0].edge_id;
assert_ne!(
generated_id,
Uuid::nil(),
"missing edge_id in old archive must get a fresh non-nil UUID"
);
// Import into a fresh runtime and verify the generated ID is persisted.
let rt = make_rt().await;
let summary = rt.import_kg(&archive, None).await.unwrap();
assert_eq!(summary.entities_imported, 2);
assert_eq!(
summary.edges_imported, 1,
"edge must be imported when both endpoints exist"
);
let stored = rt.get_edge(None, generated_id).await.unwrap();
assert!(
stored.is_some(),
"imported edge must be retrievable by the generated edge_id"
);
assert_eq!(
Uuid::from(stored.unwrap().id),
generated_id,
"stored edge id must equal the generated edge_id"
);
// Re-export and verify the same UUID appears in the archive.
let re_archive = rt.export_kg(None).await.unwrap();
assert_eq!(re_archive.edges.len(), 1);
assert_eq!(
re_archive.edges[0].edge_id, generated_id,
"re-exported edge_id must equal the ID generated on first import"
);
}
/// 13. Explicit export → import → export equality: the edge_id is unchanged across
/// a full round trip when the source archive already contains an edge_id.
///
/// Verifies by (source, target, relation) key that re-export emits the original ID.
#[tokio::test]
async fn export_import_export_edge_id_equality() {
// Build a graph on the source runtime.
let src = make_rt().await;
let a = src
.create_entity(None, "concept", "NodeA", None, None, vec![])
.await
.unwrap();
let b = src
.create_entity(None, "concept", "NodeB", None, None, vec![])
.await
.unwrap();
let stored = src
.link(None, a.id, b.id, EdgeRelation::Extends, 1.0)
.await
.unwrap();
let original_edge_id: Uuid = stored.id.into();
// First export.
let archive1 = src.export_kg(None).await.unwrap();
assert_eq!(archive1.edges.len(), 1);
assert_eq!(
archive1.edges[0].edge_id, original_edge_id,
"first export must carry the stored edge_id"
);
// Import into a fresh runtime.
let dst = make_rt().await;
dst.import_kg(&archive1, None).await.unwrap();
// Second export from the destination runtime.
let archive2 = dst.export_kg(None).await.unwrap();
assert_eq!(archive2.edges.len(), 1);
// Find the edge by (source, target, relation) and assert the ID is unchanged.
let re_edge = archive2
.edges
.iter()
.find(|e| e.source == a.id && e.target == b.id && e.relation == EdgeRelation::Extends)
.expect(
"re-exported archive must contain the original edge by (source,target,relation)",
);
assert_eq!(
re_edge.edge_id, original_edge_id,
"edge_id must be identical across export → import → export"
);
}
}