1use std::collections::{BTreeSet, HashMap, HashSet};
4
5use khive_storage::types::SqlRow;
6use khive_storage::{Entity, SqlStatement, SqlValue};
7use khive_types::pack::pack_registry_tag;
8use khive_types::ImportKindPolicy;
9use serde::{Deserialize, Serialize};
10use uuid::Uuid;
11
12use super::names::{
13 archive_name_writes, import_key_conflict, key_holder, key_holder_statement, ArchiveNameWrites,
14};
15use super::{ExportedEdge, ExportedEntity, ImportValidation, KgArchive};
16use crate::atomic_plan::PostCommitEffect;
17use crate::atomic_prepare::{
18 apply_post_commit_effects_with_report, canonical_refuse_registry_tags,
19 prepare_import_entity_record, prepare_update_entity_record, validate_import_entity_record,
20};
21use crate::atomic_runner::{
22 apply_plan_preserving_storage, run_prepared_atomic_unit, AtomicOpPlan, PlanExecutionFailure,
23 PreparedAtomicError, PreparedAtomicOp, PreparedAtomicOutcome,
24};
25use crate::curation::EntityPatch;
26use crate::operations::{canonical_edge_endpoints, Resolved};
27use crate::{KhiveRuntime, NamespaceToken, RuntimeError, RuntimeResult};
28
29const MAX_IMPORT_RECORDS: usize = 10_000;
31const MAX_IMPORT_BYTES: usize = 64 * 1024 * 1024;
32
33#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
34#[serde(rename_all = "snake_case")]
35pub enum ImportConflictMode {
36 #[default]
37 Error,
38 Skip,
39 Update,
40}
41
42#[derive(Clone, Copy, Debug, Default)]
44pub struct ImportOptions {
45 pub on_conflict: ImportConflictMode,
46 pub force: bool,
47 pub dry_run: bool,
48}
49
50#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
52#[serde(rename_all = "snake_case")]
53pub enum ImportPolicySkipCause {
54 ExistingEdge,
55 SkippedRecord,
56 MissingSource,
57 MissingTarget,
58 EndpointContract,
59}
60
61#[derive(Clone, Debug, Serialize, Deserialize)]
62pub struct ImportPolicySkippedEdge {
63 pub edge_id: Uuid,
64 pub source: Uuid,
65 pub target: Uuid,
66 pub relation: khive_storage::EdgeRelation,
67 pub cause: ImportPolicySkipCause,
68 #[serde(default, skip_serializing_if = "Option::is_none")]
69 pub error: Option<String>,
70}
71
72#[derive(Clone, Debug, Default, Serialize, Deserialize)]
73pub struct ImportConflictSummary {
74 pub entities_imported: usize,
75 pub entities_inserted: usize,
76 pub entities_updated: usize,
77 pub entities_skipped: usize,
78 #[serde(default, skip_serializing_if = "is_zero_count")]
79 pub entities_registry_skipped: usize,
80 #[serde(default, skip_serializing_if = "is_zero_count")]
83 pub entities_key_conflict_skipped: usize,
84 pub edges_imported: usize,
85 pub edges_inserted: usize,
86 pub edges_updated: usize,
87 pub edges_skipped: usize,
88 #[serde(default, skip_serializing_if = "is_zero_count")]
89 pub edges_registry_skipped: usize,
90 #[serde(default, skip_serializing_if = "Vec::is_empty")]
91 pub skipped_edges: Vec<ImportPolicySkippedEdge>,
92 #[serde(default)]
93 pub embedding_truncation: crate::retrieval::EmbeddingTruncationReport,
94}
95
96fn is_zero_count(count: &usize) -> bool {
97 *count == 0
98}
99
100struct Probe {
101 statement: SqlStatement,
102 expected: serde_json::Value,
103}
104
105enum ImportEndpoint {
106 Record(Box<Resolved>),
107 Edge,
108}
109
110impl ImportEndpoint {
111 fn record(&self) -> Option<&Resolved> {
112 match self {
113 Self::Record(record) => Some(record.as_ref()),
114 Self::Edge => None,
115 }
116 }
117}
118
119struct PreparedImport {
120 probes: Vec<Probe>,
121 entities: Vec<AtomicOpPlan>,
122 edges: Vec<SqlStatement>,
123 summary: ImportConflictSummary,
124}
125
126fn invalid(message: impl Into<String>) -> RuntimeError {
127 RuntimeError::InvalidInput(message.into())
128}
129
130fn archive_entity(record: &ExportedEntity, namespace: &str) -> Entity {
131 Entity {
132 entity_type: record.entity_type.clone(),
133 description: record.description.clone(),
134 properties: record.properties.clone().filter(|value| !value.is_null()),
135 tags: record.tags.clone(),
136 ..Entity::minimal(
137 record.id,
138 namespace,
139 &record.kind,
140 &record.name,
141 record.created_at.timestamp_micros(),
142 record.updated_at.timestamp_micros(),
143 )
144 }
145}
146
147fn is_registry_archive_entity(record: &ExportedEntity) -> bool {
148 record
149 .tags
150 .iter()
151 .any(|tag| pack_registry_tag(tag).is_some())
152}
153
154fn archive_patch(record: &ExportedEntity) -> EntityPatch {
155 EntityPatch {
156 name: Some(record.name.clone()),
157 description: record.description.clone().map(Some),
158 entity_type: record.entity_type.clone().map(Some),
159 properties: record.properties.clone().filter(|value| !value.is_null()),
160 tags: (!record.tags.is_empty()).then(|| record.tags.clone()),
161 }
162}
163
164fn append_name_writes(
168 plan: &mut AtomicOpPlan,
169 writes: ArchiveNameWrites,
170 reindex: bool,
171) -> RuntimeResult<()> {
172 if writes.statements.is_empty() {
173 return Ok(());
174 }
175 match plan {
176 AtomicOpPlan::AddEntity(add) => add.statements.extend(writes.statements),
177 AtomicOpPlan::Update(update) => {
178 update.statements.extend(writes.statements);
179 if reindex {
180 update.post_commit = PostCommitEffect::ReindexEntity {
181 entity_id: update.target_id,
182 };
183 }
184 }
185 _ => {
186 return Err(RuntimeError::Internal(
187 "archive entity plan writes no entity row".into(),
188 ))
189 }
190 }
191 Ok(())
192}
193
194fn identity_statement(id: Uuid) -> SqlStatement {
195 SqlStatement::new(
196 include_str!("../../sql/canonical_identity_exists.sql"),
197 vec![SqlValue::Text(id.to_string())],
198 )
199 .labelled("import-id-collision")
200}
201
202fn identity_state_statement(id: Uuid) -> SqlStatement {
203 SqlStatement::new(
204 include_str!("../../sql/import-endpoint-state.sql"),
205 vec![SqlValue::Text(id.to_string())],
206 )
207 .labelled("import-endpoint-state")
208}
209
210fn entity_statement(id: Uuid) -> SqlStatement {
211 SqlStatement::new(
212 include_str!("../../sql/import-entity-state.sql"),
213 vec![SqlValue::Text(id.to_string())],
214 )
215 .labelled("import-entity-state")
216}
217
218fn edge_statement(id: Uuid) -> SqlStatement {
219 SqlStatement::new(
220 include_str!("../../sql/import-edge-state.sql"),
221 vec![SqlValue::Text(id.to_string())],
222 )
223 .labelled("import-edge-state")
224}
225
226fn key_statement(namespace: &str, record: &ExportedEdge) -> SqlStatement {
227 let (source, target) = canonical_edge_endpoints(record.relation, record.source, record.target);
228 SqlStatement::new(
229 include_str!("../../sql/import-edge-key.sql"),
230 vec![
231 SqlValue::Text(namespace.to_owned()),
232 SqlValue::Text(source.to_string()),
233 SqlValue::Text(target.to_string()),
234 SqlValue::Text(record.relation.to_string()),
235 ],
236 )
237 .labelled("import-edge-key")
238}
239
240async fn read_probe(
241 runtime: &KhiveRuntime,
242 statement: SqlStatement,
243) -> RuntimeResult<(Probe, Vec<SqlRow>)> {
244 let rows = {
246 let mut reader = runtime.sql().reader().await?;
247 reader.query_all(statement.clone()).await?
248 };
249 let expected = serde_json::to_value(&rows)
250 .map_err(|error| RuntimeError::Internal(format!("encode import precondition: {error}")))?;
251 Ok((
252 Probe {
253 statement,
254 expected,
255 },
256 rows,
257 ))
258}
259
260async fn read_endpoint(
261 runtime: &KhiveRuntime,
262 token: &NamespaceToken,
263 id: Uuid,
264 probes: &mut Vec<Probe>,
265) -> RuntimeResult<Option<ImportEndpoint>> {
266 let (probe, _) = read_probe(runtime, identity_state_statement(id)).await?;
269 probes.push(probe);
270 if let Some(record) = runtime.resolve_edge_endpoint(token, id).await? {
271 return Ok(Some(ImportEndpoint::Record(Box::new(record))));
272 }
273 Ok(runtime
274 .get_edge(token, id)
275 .await?
276 .map(|_| ImportEndpoint::Edge))
277}
278
279fn validate_endpoints(
280 runtime: &KhiveRuntime,
281 edge: &ExportedEdge,
282 source: &ImportEndpoint,
283 target: &ImportEndpoint,
284 rules: &[khive_types::EdgeEndpointRule],
285) -> RuntimeResult<()> {
286 if edge.relation == khive_storage::EdgeRelation::Annotates
289 && matches!(source.record(), Some(Resolved::Note(_)))
290 && matches!(target, ImportEndpoint::Edge)
291 {
292 if edge.source == edge.target {
293 return Err(invalid(
294 "self-loop edges are not allowed: source_id and target_id must be different",
295 ));
296 }
297 return Ok(());
298 }
299 if matches!(source, ImportEndpoint::Edge) || matches!(target, ImportEndpoint::Edge) {
300 return Err(invalid(format!(
301 "archive edge {}: a stored edge is only a valid annotates target from a note",
302 edge.edge_id
303 )));
304 }
305 runtime.validate_link_endpoints_by_resolved_with_rules(
306 edge.source,
307 edge.target,
308 edge.relation,
309 source.record(),
310 target.record(),
311 rules,
312 )
313}
314
315fn skipped(
316 record: &ExportedEdge,
317 cause: ImportPolicySkipCause,
318 error: Option<String>,
319) -> ImportPolicySkippedEdge {
320 ImportPolicySkippedEdge {
321 edge_id: record.edge_id,
322 source: record.source,
323 target: record.target,
324 relation: record.relation,
325 cause,
326 error,
327 }
328}
329
330impl KhiveRuntime {
331 pub fn validate_kg_import_options(
334 &self,
335 archive: &KgArchive,
336 token: &NamespaceToken,
337 policy: ImportKindPolicy,
338 ) -> RuntimeResult<ImportValidation> {
339 let count = archive
340 .entities
341 .len()
342 .checked_add(archive.edges.len())
343 .ok_or_else(|| invalid("import record count overflow"))?;
344 if count > MAX_IMPORT_RECORDS {
345 return Err(invalid(format!(
346 "import has {count} records; maximum is {MAX_IMPORT_RECORDS}"
347 )));
348 }
349 struct Budget(usize);
350 impl std::io::Write for Budget {
351 fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
352 self.0 = self
353 .0
354 .checked_add(bytes.len())
355 .filter(|size| *size <= MAX_IMPORT_BYTES)
356 .ok_or_else(|| {
357 std::io::Error::new(
358 std::io::ErrorKind::InvalidInput,
359 "archive exceeds 64 MiB import limit",
360 )
361 })?;
362 Ok(bytes.len())
363 }
364 fn flush(&mut self) -> std::io::Result<()> {
365 Ok(())
366 }
367 }
368 serde_json::to_writer(Budget(0), archive)
369 .map_err(|error| invalid(format!("import archive budget: {error}")))?;
370 let validation = self.validate_kg_import(archive, policy)?;
371 let mut ids = HashSet::new();
372 for record in &archive.entities {
373 if !ids.insert(record.id) {
374 return Err(invalid(format!(
375 "duplicate archive entity UUID {}",
376 record.id
377 )));
378 }
379 if is_registry_archive_entity(record) {
380 continue;
381 }
382 validate_import_entity_record(
383 self,
384 token,
385 &archive_entity(record, token.namespace().as_str()),
386 policy,
387 )?;
388 }
389 Ok(validation)
390 }
391
392 pub async fn import_kg_with_options(
396 &self,
397 archive: &KgArchive,
398 token: &NamespaceToken,
399 policy: ImportKindPolicy,
400 options: ImportOptions,
401 ) -> RuntimeResult<ImportConflictSummary> {
402 let validation = self.validate_kg_import_options(archive, token, policy)?;
403 let prepared = self.prepare_import(archive, token, policy, options).await?;
404 if options.dry_run {
405 return Ok(prepared.summary);
406 }
407 for kind in validation.unknown_entity_kinds {
408 tracing::warn!(target: "khive.import.schema",
409 kind = %crate::secret_gate::bounded_masked_log_text(&kind),
410 "preserving unknown entity kind during explicit import");
411 }
412 self.apply_prepared_import(token, prepared).await
413 }
414
415 async fn apply_prepared_import(
416 &self,
417 token: &NamespaceToken,
418 prepared: PreparedImport,
419 ) -> RuntimeResult<ImportConflictSummary> {
420 self.entities(token)?;
422 self.graph(token)?;
423 self.text(token)?;
424 self.events(token)?;
425 let op: PreparedAtomicOp<ImportConflictSummary, RuntimeError> = Box::new(move |writer| {
426 Box::pin(async move {
427 for probe in prepared.probes {
430 let rows = writer.query_all(probe.statement).await?;
431 let actual = serde_json::to_value(rows).map_err(|error| {
432 PreparedAtomicError::Refused {
433 failure: RuntimeError::Internal(format!(
434 "encode import precondition: {error}"
435 )),
436 message: "import precondition encoding failed".into(),
437 }
438 })?;
439 if actual != probe.expected {
440 return Err(PreparedAtomicError::Refused {
441 failure: invalid(
442 "import destination changed during preflight; retry the import",
443 ),
444 message: "import destination changed during preflight".into(),
445 });
446 }
447 }
448 let mut effects = Vec::<PostCommitEffect>::new();
449 for plan in prepared.entities {
450 match apply_plan_preserving_storage(writer, &plan, false).await {
451 Ok(applied) => effects.extend(applied.effect),
452 Err(PlanExecutionFailure::Storage { source, .. }) => {
453 return Err(PreparedAtomicError::Storage(source))
454 }
455 Err(PlanExecutionFailure::Operation(failure)) => {
456 return Err(PreparedAtomicError::Refused {
457 failure: invalid(format!(
458 "import entity precondition failed: {failure:?}"
459 )),
460 message: "import entity precondition failed".into(),
461 });
462 }
463 }
464 }
465 for statement in prepared.edges {
466 if writer.execute(statement).await? != 1 {
467 return Err(PreparedAtomicError::Refused {
468 failure: invalid("import edge precondition failed"),
469 message: "import edge precondition failed".into(),
470 });
471 }
472 }
473 Ok((prepared.summary, effects))
474 })
475 });
476 let access = self.sql();
477 match run_prepared_atomic_unit(access.as_ref(), op).await? {
478 PreparedAtomicOutcome::RolledBack(error) => Err(error),
479 PreparedAtomicOutcome::Committed {
480 mut value,
481 post_commit,
482 } => {
483 for outcome in
484 apply_post_commit_effects_with_report(self, token, post_commit).await?
485 {
486 value.embedding_truncation.merge(outcome.truncation);
487 }
488 Ok(value)
489 }
490 }
491 }
492
493 async fn prepare_import(
494 &self,
495 archive: &KgArchive,
496 token: &NamespaceToken,
497 policy: ImportKindPolicy,
498 options: ImportOptions,
499 ) -> RuntimeResult<PreparedImport> {
500 let namespace = token.namespace().as_str();
501 let mut result = PreparedImport {
502 probes: Vec::new(),
503 entities: Vec::new(),
504 edges: Vec::new(),
505 summary: ImportConflictSummary::default(),
506 };
507 let mut endpoints = HashMap::<Uuid, Option<ImportEndpoint>>::new();
508 let mut skipped_records = HashSet::new();
509 let mut registry_entities = HashSet::new();
510 let mut written_entities = HashSet::new();
511 for record in &archive.entities {
512 if is_registry_archive_entity(record) {
513 result.summary.entities_skipped += 1;
514 result.summary.entities_registry_skipped += 1;
515 registry_entities.insert(record.id);
516 skipped_records.insert(record.id);
517 continue;
518 }
519 let (probe, rows) = read_probe(self, entity_statement(record.id)).await?;
520 if rows.len() > 1 {
521 return Err(invalid(format!("entity UUID {} is ambiguous", record.id)));
522 }
523 result.probes.push(probe);
524 let (identity_probe, identities) =
525 read_probe(self, identity_statement(record.id)).await?;
526 result.probes.push(identity_probe);
527 let identity_exists = !identities.is_empty();
528 if identity_exists && options.on_conflict == ImportConflictMode::Error {
529 return Err(invalid(format!(
530 "archive entity UUID {} already exists",
531 record.id
532 )));
533 }
534 if identity_exists && options.on_conflict == ImportConflictMode::Skip {
535 result.summary.entities_skipped += 1;
536 skipped_records.insert(record.id);
537 continue;
538 }
539 if identity_exists && options.on_conflict == ImportConflictMode::Update {
540 let (probe, identities) =
543 read_probe(self, identity_state_statement(record.id)).await?;
544 result.probes.push(probe);
545 if rows.is_empty()
546 || identities
547 .iter()
548 .any(|row| row.text("substrate") != Ok("entity"))
549 {
550 return Err(invalid(format!(
551 "archive entity UUID {} is held by a different record substrate",
552 record.id
553 )));
554 }
555 }
556 let mut named = BTreeSet::new();
561 let mut taken = None;
562 for key in &record.keys {
563 let (probe, holders) =
564 read_probe(self, key_holder_statement(namespace, &record.kind, key)).await?;
565 result.probes.push(probe);
566 match key_holder(&holders)? {
567 Some(holder) if holder == record.id => {
568 named.insert(key.as_str());
569 }
570 Some(_) => {
571 taken = Some(key);
572 break;
573 }
574 None => {}
575 }
576 }
577 if let Some(key) = taken {
578 if options.on_conflict == ImportConflictMode::Skip {
579 result.summary.entities_skipped += 1;
580 result.summary.entities_key_conflict_skipped += 1;
581 skipped_records.insert(record.id);
582 continue;
583 }
584 return Err(import_key_conflict(record.id, &record.kind, key));
585 }
586 let entity = if rows.is_empty() {
587 let mut entity = archive_entity(record, namespace);
588 let writes =
589 archive_name_writes(&mut entity, &record.keys, &record.aliases, &named);
590 let mut plan = prepare_import_entity_record(self, token, entity.clone(), policy)?;
591 append_name_writes(&mut plan, writes, true)?;
592 result.entities.push(plan);
593 result.summary.entities_inserted += 1;
594 entity
595 } else {
596 let current = self
597 .entities(token)?
598 .get_entity(record.id)
599 .await?
600 .filter(|entity| entity.namespace == namespace && entity.deleted_at.is_none())
601 .ok_or_else(|| {
602 invalid(format!(
603 "entity {} cannot be updated in the destination namespace",
604 record.id
605 ))
606 })?;
607 canonical_refuse_registry_tags(¤t.tags, "update")?;
610 if current.kind != record.kind {
611 return Err(invalid(format!(
612 "archive entity {} kind differs from the stored kind",
613 record.id
614 )));
615 }
616 let (mut entity, mut plan) = prepare_update_entity_record(
617 self,
618 token,
619 record.id,
620 archive_patch(record),
621 &crate::EntityAliasChange::default().keeping_old_name(true),
626 Some(current.version),
627 )
628 .await?;
629 let before = entity.aliases.clone();
631 let writes =
632 archive_name_writes(&mut entity, &record.keys, &record.aliases, &named);
633 let reindex = entity.aliases != before;
634 append_name_writes(&mut plan, writes, reindex)?;
635 result.entities.push(plan);
636 result.summary.entities_updated += 1;
637 entity
638 };
639 written_entities.insert(record.id);
640 endpoints.insert(
641 record.id,
642 Some(ImportEndpoint::Record(Box::new(Resolved::Entity(entity)))),
643 );
644 }
645 let rules = self.pack_edge_rules();
646 let mut edge_identities = HashMap::new();
647 for record in &archive.edges {
648 if registry_entities.contains(&record.source)
649 || registry_entities.contains(&record.target)
650 || edge_identities.contains_key(&record.edge_id)
651 {
652 continue;
653 }
654 let (probe, identities) = read_probe(self, identity_statement(record.edge_id)).await?;
655 result.probes.push(probe);
656 let identity_exists = !identities.is_empty();
657 edge_identities.insert(record.edge_id, identity_exists);
658 if identity_exists && options.on_conflict == ImportConflictMode::Skip {
659 skipped_records.insert(record.edge_id);
660 }
661 }
662 let mut edge_ids = HashSet::new();
663 let mut edge_keys = HashSet::new();
664 for record in &archive.edges {
665 if registry_entities.contains(&record.source)
666 || registry_entities.contains(&record.target)
667 {
668 result.summary.edges_registry_skipped += 1;
669 result.summary.skipped_edges.push(skipped(
670 record,
671 ImportPolicySkipCause::SkippedRecord,
672 None,
673 ));
674 continue;
675 }
676 let identity_exists = edge_identities[&record.edge_id];
677 let (probe, stored_ids) = read_probe(self, edge_statement(record.edge_id)).await?;
678 if stored_ids.len() > 1 {
679 return Err(invalid(format!(
680 "edge UUID {} is ambiguous",
681 record.edge_id
682 )));
683 }
684 result.probes.push(probe);
685 let (key_probe, key_rows) = read_probe(self, key_statement(namespace, record)).await?;
686 result.probes.push(key_probe);
687 if key_rows.iter().any(|row| {
688 row.text("id")
689 .map_or(true, |id| id != record.edge_id.to_string())
690 }) {
691 return Err(invalid(format!(
692 "archive edge {} triple is held by another stored UUID",
693 record.edge_id
694 )));
695 }
696 if identity_exists && options.on_conflict == ImportConflictMode::Error {
697 return Err(invalid(format!(
698 "archive edge UUID {} already exists",
699 record.edge_id
700 )));
701 }
702 let current_edge =
705 if identity_exists && options.on_conflict == ImportConflictMode::Update {
706 let (probe, identities) =
707 read_probe(self, identity_state_statement(record.edge_id)).await?;
708 result.probes.push(probe);
709 if stored_ids.is_empty()
710 || identities
711 .iter()
712 .any(|row| row.text("substrate") != Ok("edge"))
713 {
714 return Err(invalid(format!(
715 "archive edge UUID {} is held by a different record substrate",
716 record.edge_id
717 )));
718 }
719 let current = self
720 .get_edge_including_deleted(token, record.edge_id)
721 .await?
722 .filter(|edge| edge.namespace == namespace && edge.deleted_at.is_none())
723 .ok_or_else(|| {
724 invalid(format!(
725 "edge {} cannot be updated in the destination namespace",
726 record.edge_id
727 ))
728 })?;
729 let (source, target) =
730 canonical_edge_endpoints(record.relation, record.source, record.target);
731 if current.source_id != source || current.target_id != target {
732 return Err(invalid(format!(
733 "archive edge {} endpoints differ from stored endpoints",
734 record.edge_id
735 )));
736 }
737 Some(current)
738 } else {
739 None
740 };
741 if skipped_records.contains(&record.source) || skipped_records.contains(&record.target)
742 {
743 result.summary.skipped_edges.push(skipped(
744 record,
745 ImportPolicySkipCause::SkippedRecord,
746 None,
747 ));
748 continue;
749 }
750 if identity_exists && options.on_conflict == ImportConflictMode::Skip {
751 result.summary.skipped_edges.push(skipped(
752 record,
753 ImportPolicySkipCause::ExistingEdge,
754 None,
755 ));
756 continue;
757 }
758 for id in [record.source, record.target] {
759 if let std::collections::hash_map::Entry::Vacant(entry) = endpoints.entry(id) {
760 entry.insert(read_endpoint(self, token, id, &mut result.probes).await?);
761 }
762 }
763 let source = endpoints.get(&record.source).and_then(Option::as_ref);
764 let target = endpoints.get(&record.target).and_then(Option::as_ref);
765 let refusal = match (source, target) {
766 (None, _) => Some((
767 ImportPolicySkipCause::MissingSource,
768 format!("link source {} not found", record.source),
769 )),
770 (Some(_), None) => Some((
771 ImportPolicySkipCause::MissingTarget,
772 format!("link target {} not found", record.target),
773 )),
774 (Some(source), Some(target)) => {
775 match validate_endpoints(self, record, source, target, &rules) {
776 Ok(()) => None,
777 Err(
778 error @ (RuntimeError::InvalidInput(_) | RuntimeError::NotFound(_)),
779 ) => Some((ImportPolicySkipCause::EndpointContract, error.to_string())),
780 Err(error) => return Err(error),
781 }
782 }
783 };
784 if let Some((cause, error)) = refusal {
785 if !options.force {
786 return Err(invalid(format!("archive edge {}: {error}", record.edge_id)));
787 }
788 result.summary.skipped_edges.push(skipped(
789 record,
790 cause,
791 (cause == ImportPolicySkipCause::EndpointContract).then_some(error),
792 ));
793 continue;
794 }
795 let (source_id, target_id) =
796 canonical_edge_endpoints(record.relation, record.source, record.target);
797 if written_entities.contains(&record.edge_id) {
801 return Err(invalid(format!(
802 "archive UUID {} is used by both an entity and an edge",
803 record.edge_id
804 )));
805 }
806 if !edge_ids.insert(record.edge_id) {
807 return Err(invalid(format!(
808 "duplicate archive edge UUID {}",
809 record.edge_id
810 )));
811 }
812 if !edge_keys.insert((source_id, target_id, record.relation)) {
813 return Err(invalid(format!(
814 "duplicate archive edge triple at {}",
815 record.edge_id
816 )));
817 }
818 let mut edge = khive_storage::Edge {
819 id: record.edge_id.into(),
820 namespace: namespace.to_owned(),
821 source_id,
822 target_id,
823 relation: record.relation,
824 weight: record.weight,
825 created_at: record.created_at,
826 updated_at: record.updated_at,
827 deleted_at: None,
828 metadata: record.properties.clone().filter(|value| !value.is_null()),
829 target_backend: None,
830 };
831 if stored_ids.is_empty() {
832 result.edges.push(
833 khive_db::stores::graph::edge_insert_only_guarded_by_endpoints_statement(&edge),
834 );
835 result.summary.edges_inserted += 1;
836 } else {
837 let current = current_edge.ok_or_else(|| {
838 RuntimeError::Internal("missing prepared edge preimage".into())
839 })?;
840 edge.created_at = current.created_at;
841 edge.target_backend = current.target_backend.clone();
842 edge.metadata = edge.metadata.or_else(|| current.metadata.clone());
843 let minimum = current
844 .updated_at
845 .timestamp_micros()
846 .checked_add(1)
847 .ok_or_else(|| invalid("stored edge revision cannot advance"))?;
848 edge.updated_at = chrono::DateTime::from_timestamp_micros(
849 chrono::Utc::now().timestamp_micros().max(minimum),
850 )
851 .ok_or_else(|| invalid("edge update timestamp is out of range"))?;
852 result.edges.push(
853 khive_db::stores::graph::edge_replace_if_unchanged_statement(
854 &edge,
855 current.updated_at,
856 current.deleted_at,
857 ),
858 );
859 result.summary.edges_updated += 1;
860 }
861 }
862 result.summary.entities_imported =
863 result.summary.entities_inserted + result.summary.entities_updated;
864 result.summary.edges_imported =
865 result.summary.edges_inserted + result.summary.edges_updated;
866 result.summary.edges_skipped = result.summary.skipped_edges.len();
867 Ok(result)
868 }
869}
870
871#[cfg(test)]
872#[path = "conflicts_tests.rs"]
873mod tests;