Skip to main content

khive_runtime/portability/
conflicts.rs

1//! Explicit CLI import policies. Legacy library entry points remain in the parent module.
2
3use std::collections::{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::{ExportedEdge, ExportedEntity, ImportValidation, KgArchive};
13use crate::atomic_plan::PostCommitEffect;
14use crate::atomic_prepare::{
15    apply_post_commit_effects_with_report, canonical_refuse_registry_tags,
16    prepare_import_entity_record, prepare_update_entity_record, validate_import_entity_record,
17};
18use crate::atomic_runner::{
19    apply_plan_preserving_storage, run_prepared_atomic_unit, AtomicOpPlan, PlanExecutionFailure,
20    PreparedAtomicError, PreparedAtomicOp, PreparedAtomicOutcome,
21};
22use crate::curation::EntityPatch;
23use crate::operations::{canonical_edge_endpoints, Resolved};
24use crate::{KhiveRuntime, NamespaceToken, RuntimeError, RuntimeResult};
25
26// Bound both the number of synchronous writer operations and their materialized input.
27const MAX_IMPORT_RECORDS: usize = 10_000;
28const MAX_IMPORT_BYTES: usize = 64 * 1024 * 1024;
29
30#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
31#[serde(rename_all = "snake_case")]
32pub enum ImportConflictMode {
33    #[default]
34    Error,
35    Skip,
36    Update,
37}
38
39/// Opt-in CLI behavior; this does not change `import_kg` or its JSON/policy wrappers.
40#[derive(Clone, Copy, Debug, Default)]
41pub struct ImportOptions {
42    pub on_conflict: ImportConflictMode,
43    pub force: bool,
44    pub dry_run: bool,
45}
46
47/// Reasons in the policy-aware report, separate from the legacy closed skip enum.
48#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
49#[serde(rename_all = "snake_case")]
50pub enum ImportPolicySkipCause {
51    ExistingEdge,
52    SkippedRecord,
53    MissingSource,
54    MissingTarget,
55    EndpointContract,
56}
57
58#[derive(Clone, Debug, Serialize, Deserialize)]
59pub struct ImportPolicySkippedEdge {
60    pub edge_id: Uuid,
61    pub source: Uuid,
62    pub target: Uuid,
63    pub relation: khive_storage::EdgeRelation,
64    pub cause: ImportPolicySkipCause,
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub error: Option<String>,
67}
68
69#[derive(Clone, Debug, Default, Serialize, Deserialize)]
70pub struct ImportConflictSummary {
71    pub entities_imported: usize,
72    pub entities_inserted: usize,
73    pub entities_updated: usize,
74    pub entities_skipped: usize,
75    #[serde(default, skip_serializing_if = "is_zero_count")]
76    pub entities_registry_skipped: usize,
77    pub edges_imported: usize,
78    pub edges_inserted: usize,
79    pub edges_updated: usize,
80    pub edges_skipped: usize,
81    #[serde(default, skip_serializing_if = "is_zero_count")]
82    pub edges_registry_skipped: usize,
83    #[serde(default, skip_serializing_if = "Vec::is_empty")]
84    pub skipped_edges: Vec<ImportPolicySkippedEdge>,
85    #[serde(default)]
86    pub embedding_truncation: crate::retrieval::EmbeddingTruncationReport,
87}
88
89fn is_zero_count(count: &usize) -> bool {
90    *count == 0
91}
92
93struct Probe {
94    statement: SqlStatement,
95    expected: serde_json::Value,
96}
97
98enum ImportEndpoint {
99    Record(Box<Resolved>),
100    Edge,
101}
102
103impl ImportEndpoint {
104    fn record(&self) -> Option<&Resolved> {
105        match self {
106            Self::Record(record) => Some(record.as_ref()),
107            Self::Edge => None,
108        }
109    }
110}
111
112struct PreparedImport {
113    probes: Vec<Probe>,
114    entities: Vec<AtomicOpPlan>,
115    edges: Vec<SqlStatement>,
116    summary: ImportConflictSummary,
117}
118
119fn invalid(message: impl Into<String>) -> RuntimeError {
120    RuntimeError::InvalidInput(message.into())
121}
122
123fn archive_entity(record: &ExportedEntity, namespace: &str) -> Entity {
124    Entity {
125        entity_type: record.entity_type.clone(),
126        description: record.description.clone(),
127        properties: record.properties.clone().filter(|value| !value.is_null()),
128        tags: record.tags.clone(),
129        ..Entity::minimal(
130            record.id,
131            namespace,
132            &record.kind,
133            &record.name,
134            record.created_at.timestamp_micros(),
135            record.updated_at.timestamp_micros(),
136        )
137    }
138}
139
140fn is_registry_archive_entity(record: &ExportedEntity) -> bool {
141    record
142        .tags
143        .iter()
144        .any(|tag| pack_registry_tag(tag).is_some())
145}
146
147fn archive_patch(record: &ExportedEntity) -> EntityPatch {
148    EntityPatch {
149        name: Some(record.name.clone()),
150        description: record.description.clone().map(Some),
151        entity_type: record.entity_type.clone().map(Some),
152        properties: record.properties.clone().filter(|value| !value.is_null()),
153        tags: (!record.tags.is_empty()).then(|| record.tags.clone()),
154    }
155}
156
157fn identity_statement(id: Uuid) -> SqlStatement {
158    SqlStatement::new(
159        include_str!("../../sql/canonical_identity_exists.sql"),
160        vec![SqlValue::Text(id.to_string())],
161    )
162    .labelled("import-id-collision")
163}
164
165fn identity_state_statement(id: Uuid) -> SqlStatement {
166    SqlStatement::new(
167        include_str!("../../sql/import-endpoint-state.sql"),
168        vec![SqlValue::Text(id.to_string())],
169    )
170    .labelled("import-endpoint-state")
171}
172
173fn entity_statement(id: Uuid) -> SqlStatement {
174    SqlStatement::new(
175        include_str!("../../sql/import-entity-state.sql"),
176        vec![SqlValue::Text(id.to_string())],
177    )
178    .labelled("import-entity-state")
179}
180
181fn edge_statement(id: Uuid) -> SqlStatement {
182    SqlStatement::new(
183        include_str!("../../sql/import-edge-state.sql"),
184        vec![SqlValue::Text(id.to_string())],
185    )
186    .labelled("import-edge-state")
187}
188
189fn key_statement(namespace: &str, record: &ExportedEdge) -> SqlStatement {
190    let (source, target) = canonical_edge_endpoints(record.relation, record.source, record.target);
191    SqlStatement::new(
192        include_str!("../../sql/import-edge-key.sql"),
193        vec![
194            SqlValue::Text(namespace.to_owned()),
195            SqlValue::Text(source.to_string()),
196            SqlValue::Text(target.to_string()),
197            SqlValue::Text(record.relation.to_string()),
198        ],
199    )
200    .labelled("import-edge-key")
201}
202
203async fn read_probe(
204    runtime: &KhiveRuntime,
205    statement: SqlStatement,
206) -> RuntimeResult<(Probe, Vec<SqlRow>)> {
207    // Release the checkout before any hook/plan preparation or subsequent await.
208    let rows = {
209        let mut reader = runtime.sql().reader().await?;
210        reader.query_all(statement.clone()).await?
211    };
212    let expected = serde_json::to_value(&rows)
213        .map_err(|error| RuntimeError::Internal(format!("encode import precondition: {error}")))?;
214    Ok((
215        Probe {
216            statement,
217            expected,
218        },
219        rows,
220    ))
221}
222
223async fn read_endpoint(
224    runtime: &KhiveRuntime,
225    token: &NamespaceToken,
226    id: Uuid,
227    probes: &mut Vec<Probe>,
228) -> RuntimeResult<Option<ImportEndpoint>> {
229    // Capture all substrate candidates, including absence and higher-precedence
230    // identities, before canonical by-ID resolution (entity, note, event, edge).
231    let (probe, _) = read_probe(runtime, identity_state_statement(id)).await?;
232    probes.push(probe);
233    if let Some(record) = runtime.resolve_edge_endpoint(token, id).await? {
234        return Ok(Some(ImportEndpoint::Record(Box::new(record))));
235    }
236    Ok(runtime
237        .get_edge(token, id)
238        .await?
239        .map(|_| ImportEndpoint::Edge))
240}
241
242fn validate_endpoints(
243    runtime: &KhiveRuntime,
244    edge: &ExportedEdge,
245    source: &ImportEndpoint,
246    target: &ImportEndpoint,
247    rules: &[khive_types::EdgeEndpointRule],
248) -> RuntimeResult<()> {
249    // Resolved deliberately has no Edge variant. The canonical annotates rule
250    // also admits an existing live edge as a target; never impersonate a record.
251    if edge.relation == khive_storage::EdgeRelation::Annotates
252        && matches!(source.record(), Some(Resolved::Note(_)))
253        && matches!(target, ImportEndpoint::Edge)
254    {
255        if edge.source == edge.target {
256            return Err(invalid(
257                "self-loop edges are not allowed: source_id and target_id must be different",
258            ));
259        }
260        return Ok(());
261    }
262    if matches!(source, ImportEndpoint::Edge) || matches!(target, ImportEndpoint::Edge) {
263        return Err(invalid(format!(
264            "archive edge {}: a stored edge is only a valid annotates target from a note",
265            edge.edge_id
266        )));
267    }
268    runtime.validate_link_endpoints_by_resolved_with_rules(
269        edge.source,
270        edge.target,
271        edge.relation,
272        source.record(),
273        target.record(),
274        rules,
275    )
276}
277
278fn skipped(
279    record: &ExportedEdge,
280    cause: ImportPolicySkipCause,
281    error: Option<String>,
282) -> ImportPolicySkippedEdge {
283    ImportPolicySkippedEdge {
284        edge_id: record.edge_id,
285        source: record.source,
286        target: record.target,
287        relation: record.relation,
288        cause,
289        error,
290    }
291}
292
293impl KhiveRuntime {
294    /// Validate policy-aware input before opening the destination. Imports admit at most
295    /// 10,000 records and 64 MiB of serialized archive data per atomic unit.
296    pub fn validate_kg_import_options(
297        &self,
298        archive: &KgArchive,
299        token: &NamespaceToken,
300        policy: ImportKindPolicy,
301    ) -> RuntimeResult<ImportValidation> {
302        let count = archive
303            .entities
304            .len()
305            .checked_add(archive.edges.len())
306            .ok_or_else(|| invalid("import record count overflow"))?;
307        if count > MAX_IMPORT_RECORDS {
308            return Err(invalid(format!(
309                "import has {count} records; maximum is {MAX_IMPORT_RECORDS}"
310            )));
311        }
312        struct Budget(usize);
313        impl std::io::Write for Budget {
314            fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
315                self.0 = self
316                    .0
317                    .checked_add(bytes.len())
318                    .filter(|size| *size <= MAX_IMPORT_BYTES)
319                    .ok_or_else(|| {
320                        std::io::Error::new(
321                            std::io::ErrorKind::InvalidInput,
322                            "archive exceeds 64 MiB import limit",
323                        )
324                    })?;
325                Ok(bytes.len())
326            }
327            fn flush(&mut self) -> std::io::Result<()> {
328                Ok(())
329            }
330        }
331        serde_json::to_writer(Budget(0), archive)
332            .map_err(|error| invalid(format!("import archive budget: {error}")))?;
333        let validation = self.validate_kg_import(archive, policy)?;
334        let mut ids = HashSet::new();
335        for record in &archive.entities {
336            if !ids.insert(record.id) {
337                return Err(invalid(format!(
338                    "duplicate archive entity UUID {}",
339                    record.id
340                )));
341            }
342            if is_registry_archive_entity(record) {
343                continue;
344            }
345            validate_import_entity_record(
346                self,
347                token,
348                &archive_entity(record, token.namespace().as_str()),
349                policy,
350            )?;
351        }
352        Ok(validation)
353    }
354
355    /// Apply explicit conflict modes after complete preflight. All row changes share one
356    /// existing storage owner; ordinary entity reindexing runs only after commit. Preview
357    /// uses the same prepared outcomes but never acquires a writer or executes effects.
358    pub async fn import_kg_with_options(
359        &self,
360        archive: &KgArchive,
361        token: &NamespaceToken,
362        policy: ImportKindPolicy,
363        options: ImportOptions,
364    ) -> RuntimeResult<ImportConflictSummary> {
365        let validation = self.validate_kg_import_options(archive, token, policy)?;
366        let prepared = self.prepare_import(archive, token, policy, options).await?;
367        if options.dry_run {
368            return Ok(prepared.summary);
369        }
370        for kind in validation.unknown_entity_kinds {
371            tracing::warn!(target: "khive.import.schema",
372                kind = %crate::secret_gate::bounded_masked_log_text(&kind),
373                "preserving unknown entity kind during explicit import");
374        }
375        self.apply_prepared_import(token, prepared).await
376    }
377
378    async fn apply_prepared_import(
379        &self,
380        token: &NamespaceToken,
381        prepared: PreparedImport,
382    ) -> RuntimeResult<ImportConflictSummary> {
383        // Store constructors/table preparation are outside the suspend-free owner.
384        self.entities(token)?;
385        self.graph(token)?;
386        self.text(token)?;
387        self.events(token)?;
388        let op: PreparedAtomicOp<ImportConflictSummary, RuntimeError> = Box::new(move |writer| {
389            Box::pin(async move {
390                // Revalidate every identity, endpoint and natural-key observation BEFORE DML.
391                // A changed destination is a retryable refusal, never a stale overwrite/skip count.
392                for probe in prepared.probes {
393                    let rows = writer.query_all(probe.statement).await?;
394                    let actual = serde_json::to_value(rows).map_err(|error| {
395                        PreparedAtomicError::Refused {
396                            failure: RuntimeError::Internal(format!(
397                                "encode import precondition: {error}"
398                            )),
399                            message: "import precondition encoding failed".into(),
400                        }
401                    })?;
402                    if actual != probe.expected {
403                        return Err(PreparedAtomicError::Refused {
404                            failure: invalid(
405                                "import destination changed during preflight; retry the import",
406                            ),
407                            message: "import destination changed during preflight".into(),
408                        });
409                    }
410                }
411                let mut effects = Vec::<PostCommitEffect>::new();
412                for plan in prepared.entities {
413                    match apply_plan_preserving_storage(writer, &plan, false).await {
414                        Ok(applied) => effects.extend(applied.effect),
415                        Err(PlanExecutionFailure::Storage { source, .. }) => {
416                            return Err(PreparedAtomicError::Storage(source))
417                        }
418                        Err(PlanExecutionFailure::Operation(failure)) => {
419                            return Err(PreparedAtomicError::Refused {
420                                failure: invalid(format!(
421                                    "import entity precondition failed: {failure:?}"
422                                )),
423                                message: "import entity precondition failed".into(),
424                            });
425                        }
426                    }
427                }
428                for statement in prepared.edges {
429                    if writer.execute(statement).await? != 1 {
430                        return Err(PreparedAtomicError::Refused {
431                            failure: invalid("import edge precondition failed"),
432                            message: "import edge precondition failed".into(),
433                        });
434                    }
435                }
436                Ok((prepared.summary, effects))
437            })
438        });
439        let access = self.sql();
440        match run_prepared_atomic_unit(access.as_ref(), op).await? {
441            PreparedAtomicOutcome::RolledBack(error) => Err(error),
442            PreparedAtomicOutcome::Committed {
443                mut value,
444                post_commit,
445            } => {
446                for outcome in
447                    apply_post_commit_effects_with_report(self, token, post_commit).await?
448                {
449                    value.embedding_truncation.merge(outcome.truncation);
450                }
451                Ok(value)
452            }
453        }
454    }
455
456    async fn prepare_import(
457        &self,
458        archive: &KgArchive,
459        token: &NamespaceToken,
460        policy: ImportKindPolicy,
461        options: ImportOptions,
462    ) -> RuntimeResult<PreparedImport> {
463        let namespace = token.namespace().as_str();
464        let mut result = PreparedImport {
465            probes: Vec::new(),
466            entities: Vec::new(),
467            edges: Vec::new(),
468            summary: ImportConflictSummary::default(),
469        };
470        let mut endpoints = HashMap::<Uuid, Option<ImportEndpoint>>::new();
471        let mut skipped_records = HashSet::new();
472        let mut registry_entities = HashSet::new();
473        let mut written_entities = HashSet::new();
474        for record in &archive.entities {
475            if is_registry_archive_entity(record) {
476                result.summary.entities_skipped += 1;
477                result.summary.entities_registry_skipped += 1;
478                registry_entities.insert(record.id);
479                skipped_records.insert(record.id);
480                continue;
481            }
482            let (probe, rows) = read_probe(self, entity_statement(record.id)).await?;
483            if rows.len() > 1 {
484                return Err(invalid(format!("entity UUID {} is ambiguous", record.id)));
485            }
486            result.probes.push(probe);
487            let (identity_probe, identities) =
488                read_probe(self, identity_statement(record.id)).await?;
489            result.probes.push(identity_probe);
490            let identity_exists = !identities.is_empty();
491            if identity_exists && options.on_conflict == ImportConflictMode::Error {
492                return Err(invalid(format!(
493                    "archive entity UUID {} already exists",
494                    record.id
495                )));
496            }
497            if identity_exists && options.on_conflict == ImportConflictMode::Skip {
498                result.summary.entities_skipped += 1;
499                skipped_records.insert(record.id);
500                continue;
501            }
502            if identity_exists && options.on_conflict == ImportConflictMode::Update {
503                // LIMIT 1 establishes existence, but cannot reveal a second substrate.
504                // Retain every identity row so revalidation also detects a later collision.
505                let (probe, identities) =
506                    read_probe(self, identity_state_statement(record.id)).await?;
507                result.probes.push(probe);
508                if rows.is_empty()
509                    || identities
510                        .iter()
511                        .any(|row| row.text("substrate") != Ok("entity"))
512                {
513                    return Err(invalid(format!(
514                        "archive entity UUID {} is held by a different record substrate",
515                        record.id
516                    )));
517                }
518            }
519            let entity = if rows.is_empty() {
520                let entity = archive_entity(record, namespace);
521                result.entities.push(prepare_import_entity_record(
522                    self,
523                    token,
524                    entity.clone(),
525                    policy,
526                )?);
527                result.summary.entities_inserted += 1;
528                entity
529            } else {
530                let current = self
531                    .entities(token)?
532                    .get_entity(record.id)
533                    .await?
534                    .filter(|entity| entity.namespace == namespace && entity.deleted_at.is_none())
535                    .ok_or_else(|| {
536                        invalid(format!(
537                            "entity {} cannot be updated in the destination namespace",
538                            record.id
539                        ))
540                    })?;
541                // The archive's tags cannot attest ownership of the stored row.
542                // Refuse before a patch can replace its properties or tags.
543                canonical_refuse_registry_tags(&current.tags, "update")?;
544                if current.kind != record.kind {
545                    return Err(invalid(format!(
546                        "archive entity {} kind differs from the stored kind",
547                        record.id
548                    )));
549                }
550                let (entity, plan) = prepare_update_entity_record(
551                    self,
552                    token,
553                    record.id,
554                    archive_patch(record),
555                    Some(current.version),
556                )
557                .await?;
558                result.entities.push(plan);
559                result.summary.entities_updated += 1;
560                entity
561            };
562            written_entities.insert(record.id);
563            endpoints.insert(
564                record.id,
565                Some(ImportEndpoint::Record(Box::new(Resolved::Entity(entity)))),
566            );
567        }
568        let rules = self.pack_edge_rules();
569        let mut edge_identities = HashMap::new();
570        for record in &archive.edges {
571            if registry_entities.contains(&record.source)
572                || registry_entities.contains(&record.target)
573                || edge_identities.contains_key(&record.edge_id)
574            {
575                continue;
576            }
577            let (probe, identities) = read_probe(self, identity_statement(record.edge_id)).await?;
578            result.probes.push(probe);
579            let identity_exists = !identities.is_empty();
580            edge_identities.insert(record.edge_id, identity_exists);
581            if identity_exists && options.on_conflict == ImportConflictMode::Skip {
582                skipped_records.insert(record.edge_id);
583            }
584        }
585        let mut edge_ids = HashSet::new();
586        let mut edge_keys = HashSet::new();
587        for record in &archive.edges {
588            if registry_entities.contains(&record.source)
589                || registry_entities.contains(&record.target)
590            {
591                result.summary.edges_registry_skipped += 1;
592                result.summary.skipped_edges.push(skipped(
593                    record,
594                    ImportPolicySkipCause::SkippedRecord,
595                    None,
596                ));
597                continue;
598            }
599            let identity_exists = edge_identities[&record.edge_id];
600            let (probe, stored_ids) = read_probe(self, edge_statement(record.edge_id)).await?;
601            if stored_ids.len() > 1 {
602                return Err(invalid(format!(
603                    "edge UUID {} is ambiguous",
604                    record.edge_id
605                )));
606            }
607            result.probes.push(probe);
608            let (key_probe, key_rows) = read_probe(self, key_statement(namespace, record)).await?;
609            result.probes.push(key_probe);
610            if key_rows.iter().any(|row| {
611                row.text("id")
612                    .map_or(true, |id| id != record.edge_id.to_string())
613            }) {
614                return Err(invalid(format!(
615                    "archive edge {} triple is held by another stored UUID",
616                    record.edge_id
617                )));
618            }
619            if identity_exists && options.on_conflict == ImportConflictMode::Error {
620                return Err(invalid(format!(
621                    "archive edge UUID {} already exists",
622                    record.edge_id
623                )));
624            }
625            // Force cannot hide a stored-identity/endpoint mismatch by turning it
626            // into an endpoint skip. Validate the immutable identity first.
627            let current_edge =
628                if identity_exists && options.on_conflict == ImportConflictMode::Update {
629                    let (probe, identities) =
630                        read_probe(self, identity_state_statement(record.edge_id)).await?;
631                    result.probes.push(probe);
632                    if stored_ids.is_empty()
633                        || identities
634                            .iter()
635                            .any(|row| row.text("substrate") != Ok("edge"))
636                    {
637                        return Err(invalid(format!(
638                            "archive edge UUID {} is held by a different record substrate",
639                            record.edge_id
640                        )));
641                    }
642                    let current = self
643                        .get_edge_including_deleted(token, record.edge_id)
644                        .await?
645                        .filter(|edge| edge.namespace == namespace && edge.deleted_at.is_none())
646                        .ok_or_else(|| {
647                            invalid(format!(
648                                "edge {} cannot be updated in the destination namespace",
649                                record.edge_id
650                            ))
651                        })?;
652                    let (source, target) =
653                        canonical_edge_endpoints(record.relation, record.source, record.target);
654                    if current.source_id != source || current.target_id != target {
655                        return Err(invalid(format!(
656                            "archive edge {} endpoints differ from stored endpoints",
657                            record.edge_id
658                        )));
659                    }
660                    Some(current)
661                } else {
662                    None
663                };
664            if skipped_records.contains(&record.source) || skipped_records.contains(&record.target)
665            {
666                result.summary.skipped_edges.push(skipped(
667                    record,
668                    ImportPolicySkipCause::SkippedRecord,
669                    None,
670                ));
671                continue;
672            }
673            if identity_exists && options.on_conflict == ImportConflictMode::Skip {
674                result.summary.skipped_edges.push(skipped(
675                    record,
676                    ImportPolicySkipCause::ExistingEdge,
677                    None,
678                ));
679                continue;
680            }
681            for id in [record.source, record.target] {
682                if let std::collections::hash_map::Entry::Vacant(entry) = endpoints.entry(id) {
683                    entry.insert(read_endpoint(self, token, id, &mut result.probes).await?);
684                }
685            }
686            let source = endpoints.get(&record.source).and_then(Option::as_ref);
687            let target = endpoints.get(&record.target).and_then(Option::as_ref);
688            let refusal = match (source, target) {
689                (None, _) => Some((
690                    ImportPolicySkipCause::MissingSource,
691                    format!("link source {} not found", record.source),
692                )),
693                (Some(_), None) => Some((
694                    ImportPolicySkipCause::MissingTarget,
695                    format!("link target {} not found", record.target),
696                )),
697                (Some(source), Some(target)) => {
698                    match validate_endpoints(self, record, source, target, &rules) {
699                        Ok(()) => None,
700                        Err(
701                            error @ (RuntimeError::InvalidInput(_) | RuntimeError::NotFound(_)),
702                        ) => Some((ImportPolicySkipCause::EndpointContract, error.to_string())),
703                        Err(error) => return Err(error),
704                    }
705                }
706            };
707            if let Some((cause, error)) = refusal {
708                if !options.force {
709                    return Err(invalid(format!("archive edge {}: {error}", record.edge_id)));
710                }
711                result.summary.skipped_edges.push(skipped(
712                    record,
713                    cause,
714                    (cause == ImportPolicySkipCause::EndpointContract).then_some(error),
715                ));
716                continue;
717            }
718            let (source_id, target_id) =
719                canonical_edge_endpoints(record.relation, record.source, record.target);
720            // Repeated refused/skipped edges retain one report per input item. For
721            // edges that would be written, reject duplicate identities and tuples
722            // before the owner starts so no plan can overwrite another input row.
723            if written_entities.contains(&record.edge_id) {
724                return Err(invalid(format!(
725                    "archive UUID {} is used by both an entity and an edge",
726                    record.edge_id
727                )));
728            }
729            if !edge_ids.insert(record.edge_id) {
730                return Err(invalid(format!(
731                    "duplicate archive edge UUID {}",
732                    record.edge_id
733                )));
734            }
735            if !edge_keys.insert((source_id, target_id, record.relation)) {
736                return Err(invalid(format!(
737                    "duplicate archive edge triple at {}",
738                    record.edge_id
739                )));
740            }
741            let mut edge = khive_storage::Edge {
742                id: record.edge_id.into(),
743                namespace: namespace.to_owned(),
744                source_id,
745                target_id,
746                relation: record.relation,
747                weight: record.weight,
748                created_at: record.created_at,
749                updated_at: record.updated_at,
750                deleted_at: None,
751                metadata: record.properties.clone().filter(|value| !value.is_null()),
752                target_backend: None,
753            };
754            if stored_ids.is_empty() {
755                result.edges.push(
756                    khive_db::stores::graph::edge_insert_only_guarded_by_endpoints_statement(&edge),
757                );
758                result.summary.edges_inserted += 1;
759            } else {
760                let current = current_edge.ok_or_else(|| {
761                    RuntimeError::Internal("missing prepared edge preimage".into())
762                })?;
763                edge.created_at = current.created_at;
764                edge.target_backend = current.target_backend.clone();
765                edge.metadata = edge.metadata.or_else(|| current.metadata.clone());
766                let minimum = current
767                    .updated_at
768                    .timestamp_micros()
769                    .checked_add(1)
770                    .ok_or_else(|| invalid("stored edge revision cannot advance"))?;
771                edge.updated_at = chrono::DateTime::from_timestamp_micros(
772                    chrono::Utc::now().timestamp_micros().max(minimum),
773                )
774                .ok_or_else(|| invalid("edge update timestamp is out of range"))?;
775                result.edges.push(
776                    khive_db::stores::graph::edge_replace_if_unchanged_statement(
777                        &edge,
778                        current.updated_at,
779                        current.deleted_at,
780                    ),
781                );
782                result.summary.edges_updated += 1;
783            }
784        }
785        result.summary.entities_imported =
786            result.summary.entities_inserted + result.summary.entities_updated;
787        result.summary.edges_imported =
788            result.summary.edges_inserted + result.summary.edges_updated;
789        result.summary.edges_skipped = result.summary.skipped_edges.len();
790        Ok(result)
791    }
792}
793
794#[cfg(test)]
795#[path = "conflicts_tests.rs"]
796mod tests;