1use serde_json::Value;
20use uuid::Uuid;
21
22use khive_storage::types::SqlValue;
23use khive_storage::{AttachmentSubstrate, EdgeRelation, SqlStatement};
24use khive_types::{EventKind, SubstrateKind};
25
26use crate::atomic_plan::{
27 AddEntityPlan, AddNotePlan, AffectedRowGuard, DeletePlan, EdgeNaturalKey, LinkPlan, MergePlan,
28 PlanStatement, PostCommitEffect, UpdatePlan,
29};
30use crate::atomic_runner::AtomicOpPlan;
31use crate::atomic_runner::CommittedPostCommitEffects;
32use crate::curation::{entity_fts_document, note_fts_document};
33use crate::error::{RuntimeError, RuntimeResult};
34use crate::operations::{
35 canonical_edge_endpoints, merge_dependency_kind, validate_edge_metadata, validate_edge_weight,
36 Resolved,
37};
38use crate::runtime::{KhiveRuntime, NamespaceToken};
39
40use khive_db::stores::attachment::delete_record_attachments_statement;
41use khive_db::stores::entity::{
42 entity_hard_delete_statement, entity_replace_if_unchanged_statement,
43 entity_soft_delete_statement, entity_upsert_statement,
44};
45use khive_db::stores::event::event_insert_statements;
46use khive_db::stores::event::hard_delete_lineage_warning_statements;
47use khive_db::stores::graph::{
48 edge_hard_delete_statement, edge_insert_guarded_by_endpoints_statement,
49 edge_replace_if_unchanged_statement, edge_soft_delete_statement,
50 edge_symmetric_absorb_or_update_inplace_statement, edge_symmetric_delete_if_conflict_statement,
51 purge_incident_edges_statement,
52};
53use khive_db::stores::note::{
54 note_hard_delete_statement, note_replace_if_unchanged_statement, note_soft_delete_statement,
55 note_upsert_statement,
56};
57use khive_db::stores::text::insert_document_statement;
58
59fn obj(args: &Value) -> RuntimeResult<&serde_json::Map<String, Value>> {
64 args.as_object()
65 .ok_or_else(|| RuntimeError::InvalidInput("op args must be a JSON object".into()))
66}
67
68fn require_str<'a>(args: &'a Value, key: &str) -> RuntimeResult<&'a str> {
69 obj(args)?
70 .get(key)
71 .and_then(|v| v.as_str())
72 .ok_or_else(|| RuntimeError::InvalidInput(format!("missing required field {key:?}")))
73}
74
75fn require_uuid(args: &Value, key: &str) -> RuntimeResult<Uuid> {
76 let raw = require_str(args, key)?;
77 Uuid::parse_str(raw)
78 .map_err(|_| RuntimeError::InvalidInput(format!("{key} must be a full UUID; got {raw:?}")))
79}
80
81fn optional_str<'a>(args: &'a Value, key: &str) -> Option<&'a str> {
82 obj(args).ok()?.get(key).and_then(|v| v.as_str())
83}
84
85fn optional_create_string(args: &Value, key: &str) -> RuntimeResult<Option<String>> {
86 match obj(args)?.get(key) {
87 None | Some(Value::Null) => Ok(None),
88 Some(Value::String(value)) => Ok(Some(value.clone())),
89 Some(other) => Err(RuntimeError::InvalidInput(format!(
90 "{key} must be a string or null, got: {other}"
91 ))),
92 }
93}
94
95fn optional_entity_type_patch(args: &Value, key: &str) -> RuntimeResult<Option<Option<String>>> {
102 match obj(args)?.get(key) {
103 None => Ok(None),
104 Some(Value::Null) => Ok(Some(None)),
105 Some(Value::String(value)) => Ok(Some(Some(value.clone()))),
106 Some(other) => Err(RuntimeError::InvalidInput(format!(
107 "{key} must be a string or null, got: {other}"
108 ))),
109 }
110}
111
112fn optional_string_patch(args: &Value, key: &str) -> RuntimeResult<Option<Option<String>>> {
126 match obj(args)?.get(key) {
127 None | Some(Value::Null) => Ok(None),
128 Some(Value::String(s)) => Ok(Some(Some(s.clone()))),
129 Some(other) => Err(RuntimeError::InvalidInput(format!(
130 "{key} must be a string or null, got: {other}"
131 ))),
132 }
133}
134
135fn entity_name_patch(args: &Value) -> RuntimeResult<Option<String>> {
146 match obj(args)?.get("name") {
147 None | Some(Value::Null) => Ok(None),
148 Some(Value::String(s)) => Ok(Some(s.clone())),
149 Some(other) => Err(RuntimeError::InvalidInput(format!(
150 "name must be a string, got: {other}"
151 ))),
152 }
153}
154
155fn optional_properties(args: &Value, key: &str) -> RuntimeResult<Option<Value>> {
164 match obj(args)?.get(key) {
165 None | Some(Value::Null) => Ok(None),
166 Some(v) => Ok(Some(v.clone())),
167 }
168}
169
170fn optional_tags(args: &Value) -> RuntimeResult<Option<Vec<String>>> {
177 match obj(args)?.get("tags") {
178 None | Some(Value::Null) => Ok(None),
179 Some(Value::Array(items)) => {
180 let mut tags = Vec::with_capacity(items.len());
181 for item in items {
182 let s = item.as_str().ok_or_else(|| {
183 RuntimeError::InvalidInput("tags must be an array of strings".into())
184 })?;
185 tags.push(s.to_string());
186 }
187 Ok(Some(tags))
188 }
189 Some(_) => Err(RuntimeError::InvalidInput(
190 "tags must be an array of strings".into(),
191 )),
192 }
193}
194
195fn optional_f64(args: &Value, key: &str) -> RuntimeResult<Option<f64>> {
196 match obj(args)?.get(key) {
197 None => Ok(None),
198 Some(Value::Null) => Ok(None),
199 Some(v) => v
200 .as_f64()
201 .map(Some)
202 .ok_or_else(|| RuntimeError::InvalidInput(format!("{key} must be a number"))),
203 }
204}
205
206fn optional_f64_patch(args: &Value, key: &str) -> RuntimeResult<Option<Option<f64>>> {
212 match obj(args)?.get(key) {
213 None => Ok(None),
214 Some(Value::Null) => Ok(Some(None)),
215 Some(v) => v
216 .as_f64()
217 .map(|f| Some(Some(f)))
218 .ok_or_else(|| RuntimeError::InvalidInput(format!("{key} must be a number"))),
219 }
220}
221
222fn vector_table_names(runtime: &KhiveRuntime) -> Vec<String> {
227 runtime
228 .registered_embedding_model_names()
229 .iter()
230 .map(|name| format!("vec_{}", crate::config::sanitize_key(name)))
231 .collect()
232}
233
234fn purge_index_row_statement(
238 table: &str,
239 namespace: &str,
240 subject_id: Uuid,
241 label: &str,
242) -> PlanStatement {
243 PlanStatement {
244 statement: SqlStatement {
245 sql: format!("DELETE FROM {table} WHERE namespace = ?1 AND subject_id = ?2"),
246 params: vec![
247 SqlValue::Text(namespace.to_string()),
248 SqlValue::Text(subject_id.to_string()),
249 ],
250 label: Some(label.to_string()),
251 },
252 guard: None,
253 }
254}
255
256fn log_vector_row_delete_statement(
257 table: &str,
258 namespace: &str,
259 subject_id: Uuid,
260 label: &str,
261) -> PlanStatement {
262 PlanStatement {
263 statement: SqlStatement {
264 sql: format!(
265 "INSERT INTO ann_write_log \
266 (namespace, embedding_model, kind, field, subject_id, op) \
267 SELECT namespace, embedding_model, kind, field, subject_id, 'delete' \
268 FROM {table} WHERE namespace = ?1 AND subject_id = ?2"
269 ),
270 params: vec![
271 SqlValue::Text(namespace.to_string()),
272 SqlValue::Text(subject_id.to_string()),
273 ],
274 label: Some(label.to_string()),
275 },
276 guard: None,
277 }
278}
279
280async fn vector_table_exists(runtime: &KhiveRuntime, table: &str) -> RuntimeResult<bool> {
285 let mut reader = runtime
286 .sql()
287 .reader()
288 .await
289 .map_err(RuntimeError::Storage)?;
290 let row = reader
291 .query_scalar(SqlStatement {
292 sql: "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?1".to_string(),
293 params: vec![SqlValue::Text(table.to_string())],
294 label: Some("atomic-delete-vec-table-exists".to_string()),
295 })
296 .await
297 .map_err(RuntimeError::Storage)?;
298 Ok(row.is_some())
299}
300
301async fn push_index_purge_statements(
317 runtime: &KhiveRuntime,
318 statements: &mut Vec<PlanStatement>,
319 fts_table: &str,
320 namespace: &str,
321 subject_id: Uuid,
322 label_prefix: &str,
323) -> RuntimeResult<()> {
324 statements.push(purge_index_row_statement(
325 fts_table,
326 namespace,
327 subject_id,
328 &format!("{label_prefix}-purge-fts"),
329 ));
330 for vec_table in vector_table_names(runtime) {
331 if vector_table_exists(runtime, &vec_table).await? {
332 statements.push(log_vector_row_delete_statement(
333 &vec_table,
334 namespace,
335 subject_id,
336 &format!("{label_prefix}-log-delete-vec-{vec_table}"),
337 ));
338 statements.push(purge_index_row_statement(
339 &vec_table,
340 namespace,
341 subject_id,
342 &format!("{label_prefix}-purge-vec-{vec_table}"),
343 ));
344 }
345 }
346 Ok(())
347}
348
349fn event_append_statements(
365 namespace: &str,
366 verb: &str,
367 kind: EventKind,
368 substrate: SubstrateKind,
369 target_id: Uuid,
370 payload: Value,
371) -> RuntimeResult<Vec<PlanStatement>> {
372 let event = khive_storage::event::Event::new(namespace.to_string(), verb, kind, substrate, "")
373 .with_target(target_id)
374 .with_payload(payload);
375 let statements = event_insert_statements(&event)
376 .map_err(|e| RuntimeError::Internal(format!("event_insert_statements: {e}")))?;
377 Ok(statements
378 .into_iter()
379 .map(|statement| PlanStatement {
380 statement,
381 guard: None,
382 })
383 .collect())
384}
385
386pub async fn prepare_op(
396 runtime: &KhiveRuntime,
397 token: &NamespaceToken,
398 tool: &str,
399 args: &Value,
400) -> RuntimeResult<AtomicOpPlan> {
401 match tool {
402 "update" => prepare_update(runtime, token, args, None).await,
411 "delete" => prepare_delete(runtime, token, args, None).await,
420 "link" => prepare_link(runtime, token, args).await,
421 "merge" => prepare_merge(runtime, token, args).await,
422 "propose" | "review" | "withdraw" => prepare_governance_unimplemented(tool),
423 other => Err(RuntimeError::InvalidInput(format!(
424 "{other:?} has no atomic_prepare::prepare_op implementation; the CLI \
425 admissibility check should have rejected this before prepare"
426 ))),
427 }
428}
429
430fn prepare_governance_unimplemented(tool: &str) -> RuntimeResult<AtomicOpPlan> {
431 Err(RuntimeError::InvalidInput(format!(
432 "{tool:?} is on the ADR-099 v1 admissible verb list but has no --atomic \
433 prepare/apply implementation yet: its lifecycle (ADR-046) is an \
434 event-sourced changeset-interpreter over a dedicated `proposals_open` \
435 table, not a small guarded-DML plan — a faithful non-stub atomic \
436 prepare for it is tracked as ADR-099 follow-up work, not implemented \
437 in slice B3. No write was attempted."
438 )))
439}
440
441pub async fn prepare_add_entity(
451 runtime: &KhiveRuntime,
452 token: &NamespaceToken,
453 args: &Value,
454) -> RuntimeResult<AtomicOpPlan> {
455 let kind = require_str(args, "kind")?;
456 let name = require_str(args, "name")?;
457 runtime.validate_entity_kind(kind)?;
458 if name.trim().is_empty() {
459 return Err(RuntimeError::InvalidInput(
460 "name must not be empty".to_string(),
461 ));
462 }
463
464 let description = optional_create_string(args, "description")?;
465 let properties = optional_properties(args, "properties")?;
466 let tags = optional_tags(args)?.unwrap_or_default();
467
468 crate::secret_gate::check(name)?;
469 if let Some(ref d) = description {
470 crate::secret_gate::check(d)?;
471 }
472 if let Some(ref p) = properties {
473 crate::secret_gate::check_json(p)?;
474 }
475 crate::secret_gate::check_tags(&tags)?;
476 crate::secret_gate::reject_reserved_secret_gate_property(properties.as_ref())?;
477
478 let ns = token.namespace().as_str();
479 let mut entity = khive_storage::Entity::new(ns, kind, name);
480 if let Some(d) = description {
481 entity = entity.with_description(d);
482 }
483 if let Some(p) = properties {
484 entity = entity.with_properties(p);
485 }
486 if !tags.is_empty() {
487 entity = entity.with_tags(tags);
488 }
489
490 let statements = vec![
491 PlanStatement {
492 statement: entity_upsert_statement(&entity),
493 guard: Some(AffectedRowGuard::exactly(1)),
494 },
495 PlanStatement {
496 statement: insert_document_statement("fts_entities", &entity_fts_document(&entity)),
497 guard: None,
498 },
499 ];
500
501 Ok(AtomicOpPlan::AddEntity(AddEntityPlan {
502 entity_id: entity.id,
503 statements,
504 post_commit: PostCommitEffect::ReindexEntity {
505 entity_id: entity.id,
506 },
507 }))
508}
509
510pub async fn prepare_add_note(
516 runtime: &KhiveRuntime,
517 token: &NamespaceToken,
518 args: &Value,
519) -> RuntimeResult<AtomicOpPlan> {
520 let kind = require_str(args, "kind")?;
521 let content = require_str(args, "content")?;
522 runtime.validate_note_kind(kind)?;
523
524 let name = optional_create_string(args, "name")?;
525 let properties = optional_properties(args, "properties")?;
526 let properties = runtime.derive_note_write_properties(kind, token, properties)?;
532
533 crate::secret_gate::check(content)?;
534 if let Some(ref n) = name {
535 crate::secret_gate::check(n)?;
536 }
537 if let Some(ref p) = properties {
538 crate::secret_gate::check_json(p)?;
539 }
540 crate::secret_gate::reject_reserved_secret_gate_property(properties.as_ref())?;
541
542 let ns = token.namespace().as_str();
543 let mut note = khive_storage::note::Note::new(ns, kind, content);
544 if let Some(n) = name {
545 note = note.with_name(n);
546 }
547 if let Some(p) = properties {
548 note = note.with_properties(p);
549 }
550
551 let statements = vec![
552 PlanStatement {
553 statement: note_upsert_statement(¬e),
554 guard: Some(AffectedRowGuard::exactly(1)),
555 },
556 PlanStatement {
557 statement: insert_document_statement("fts_notes", ¬e_fts_document(¬e)),
558 guard: None,
559 },
560 ];
561
562 Ok(AtomicOpPlan::AddNote(AddNotePlan {
563 note_id: note.id,
564 statements,
565 post_commit: PostCommitEffect::ReindexNote { note_id: note.id },
566 }))
567}
568
569fn reject_inapplicable_update_fields(args: &Value, substrate: &str) -> RuntimeResult<()> {
584 let o = obj(args)?;
585 let present = |k: &str| o.get(k).is_some_and(|v| !v.is_null());
586 let (bad_field, valid): (Option<&str>, &str) = match substrate {
587 "entity" => {
588 let bad = if present("content") {
589 Some("content")
590 } else if present("salience") {
591 Some("salience")
592 } else if present("decay_factor") {
593 Some("decay_factor")
594 } else if present("relation") {
595 Some("relation")
596 } else if present("weight") {
597 Some("weight")
598 } else {
599 None
600 };
601 (bad, "name, description, tags, properties, entity_type")
602 }
603 "note" => {
604 let bad = if present("description") {
605 Some("description")
606 } else if present("tags") {
607 Some("tags")
608 } else if present("relation") {
609 Some("relation")
610 } else if present("weight") {
611 Some("weight")
612 } else if o.contains_key("entity_type") {
613 Some("entity_type")
616 } else {
617 None
618 };
619 (bad, "name, content, salience, decay_factor, properties")
620 }
621 "edge" => {
627 let bad = if present("name") {
628 Some("name")
629 } else if present("description") {
630 Some("description")
631 } else if present("content") {
632 Some("content")
633 } else if present("tags") {
634 Some("tags")
635 } else if present("salience") {
636 Some("salience")
637 } else if present("decay_factor") {
638 Some("decay_factor")
639 } else if o.contains_key("entity_type") {
640 Some("entity_type")
643 } else {
644 None
645 };
646 (bad, "relation, weight, properties")
647 }
648 _ => (None, ""),
649 };
650 if let Some(field) = bad_field {
651 let substrate_label = match substrate {
652 "entity" => "an entity",
653 "note" => "a note",
654 "edge" => "an edge",
655 other => other,
656 };
657 return Err(RuntimeError::InvalidInput(format!(
658 "field '{field}' is not valid for {substrate_label}; valid fields: {valid}"
659 )));
660 }
661 Ok(())
662}
663
664pub enum AtomicUpdateKind {
674 Entity { specific: Option<String> },
675 Note { specific: Option<String> },
676 Edge,
677}
678
679pub fn validate_note_update_expected_kind(
684 note: &khive_storage::note::Note,
685 expected_kind: &Option<AtomicUpdateKind>,
686) -> RuntimeResult<()> {
687 let id = note.id;
688 match expected_kind {
689 None => Ok(()),
690 Some(AtomicUpdateKind::Note {
691 specific: Some(expected),
692 }) if ¬e.kind != expected => Err(RuntimeError::NotFound(format!("note {id}"))),
693 Some(AtomicUpdateKind::Note { .. }) => Ok(()),
694 Some(AtomicUpdateKind::Entity { .. }) => {
695 Err(RuntimeError::NotFound(format!("entity {id}")))
696 }
697 Some(AtomicUpdateKind::Edge) => Err(RuntimeError::NotFound(format!("edge {id}"))),
698 }
699}
700
701async fn prepare_note_update_plan_from_snapshot(
702 runtime: &KhiveRuntime,
703 token: &NamespaceToken,
704 args: &Value,
705 expected_kind: &Option<AtomicUpdateKind>,
706 note: khive_storage::note::Note,
707) -> RuntimeResult<AtomicOpPlan> {
708 let id = require_uuid(args, "id")?;
709 if note.id != id {
710 return Err(RuntimeError::NotFound(format!("note {id}")));
711 }
712 validate_note_update_expected_kind(¬e, expected_kind)?;
713
714 reject_inapplicable_update_fields(args, "note")?;
715 let name = optional_string_patch(args, "name")?;
716 let content = optional_str(args, "content").map(str::to_string);
717 let properties = optional_properties(args, "properties")?;
718 let salience = optional_f64_patch(args, "salience")?;
719 let decay_factor = optional_f64_patch(args, "decay_factor")?;
720 let expected_updated_at = note.updated_at;
721 let expected_deleted_at = note.deleted_at;
722
723 let (note, text_changed) = runtime
724 .prepare_update_note_from_snapshot(
725 token,
726 note,
727 crate::curation::NotePatch::new(name, content, salience, decay_factor, properties),
728 )
729 .await?;
730
731 let post_commit = if text_changed {
732 PostCommitEffect::ReindexNote { note_id: id }
733 } else {
734 PostCommitEffect::None
735 };
736 Ok(AtomicOpPlan::Update(UpdatePlan {
737 target_id: id,
738 statements: vec![PlanStatement {
739 statement: note_replace_if_unchanged_statement(
740 ¬e,
741 expected_updated_at,
742 expected_deleted_at,
743 ),
744 guard: Some(AffectedRowGuard::exactly(1)),
745 }],
746 post_commit,
747 edge_natural_key: None,
748 }))
749}
750
751pub async fn prepare_update_from_note_snapshot(
755 runtime: &KhiveRuntime,
756 token: &NamespaceToken,
757 args: &Value,
758 expected_kind: Option<AtomicUpdateKind>,
759 note: khive_storage::note::Note,
760) -> RuntimeResult<AtomicOpPlan> {
761 if obj(args)?.get("entity_kind").is_some_and(|v| !v.is_null()) {
762 return Err(RuntimeError::InvalidInput(
763 "entity_kind is immutable; to change kind, delete then re-create the entity, \
764 or use merge() if this is a deduplication correction"
765 .into(),
766 ));
767 }
768 let current = runtime
769 .notes(token)?
770 .get_note(note.id)
771 .await?
772 .ok_or_else(|| RuntimeError::NotFound(format!("note {}", note.id)))?;
773 if current != note {
774 return Err(crate::curation::stale_note_snapshot_error(note.id));
775 }
776 prepare_note_update_plan_from_snapshot(runtime, token, args, &expected_kind, note).await
777}
778
779pub async fn prepare_update(
787 runtime: &KhiveRuntime,
788 token: &NamespaceToken,
789 args: &Value,
790 expected_kind: Option<AtomicUpdateKind>,
791) -> RuntimeResult<AtomicOpPlan> {
792 let id = require_uuid(args, "id")?;
793
794 if obj(args)?.get("entity_kind").is_some_and(|v| !v.is_null()) {
798 return Err(RuntimeError::InvalidInput(
799 "entity_kind is immutable; to change kind, delete then re-create the entity, \
800 or use merge() if this is a deduplication correction"
801 .into(),
802 ));
803 }
804
805 match runtime.resolve_by_id(token, id).await? {
806 Some(Resolved::Entity(entity)) => {
807 match &expected_kind {
808 None => {}
809 Some(AtomicUpdateKind::Entity {
810 specific: Some(expected),
811 }) if &entity.kind != expected => {
812 return Err(RuntimeError::NotFound(format!("entity {id}")));
813 }
814 Some(AtomicUpdateKind::Entity { .. }) => {}
815 Some(AtomicUpdateKind::Note { .. }) => {
816 return Err(RuntimeError::NotFound(format!("note {id}")));
817 }
818 Some(AtomicUpdateKind::Edge) => {
819 return Err(RuntimeError::NotFound(format!("edge {id}")));
820 }
821 }
822 reject_inapplicable_update_fields(args, "entity")?;
830 let name = entity_name_patch(args)?;
831 let description = optional_string_patch(args, "description")?;
832 let properties = optional_properties(args, "properties")?;
833 let tags = optional_tags(args)?;
834 let entity_type = optional_entity_type_patch(args, "entity_type")?;
835
836 prepare_update_entity_plan(
837 runtime,
838 token,
839 id,
840 crate::curation::EntityPatch {
841 name,
842 description,
843 properties,
844 tags,
845 entity_type,
846 },
847 )
848 .await
849 }
850 Some(Resolved::Note(note)) => {
851 prepare_note_update_plan_from_snapshot(runtime, token, args, &expected_kind, note).await
856 }
857 Some(_) => Err(RuntimeError::InvalidInput(format!(
858 "update target {id} must be an entity, note, or edge"
859 ))),
860 None => match &expected_kind {
867 Some(AtomicUpdateKind::Entity { .. }) => {
868 Err(RuntimeError::NotFound(format!("entity/note {id}")))
869 }
870 Some(AtomicUpdateKind::Note { .. }) => {
871 Err(RuntimeError::NotFound(format!("entity/note {id}")))
872 }
873 Some(AtomicUpdateKind::Edge) | None => match runtime.get_edge(token, id).await? {
874 Some(edge) => prepare_update_edge(runtime, id, edge, args).await,
875 None => Err(RuntimeError::NotFound(format!("entity/note/edge {id}"))),
876 },
877 },
878 }
879}
880
881pub async fn prepare_update_entity_plan(
885 runtime: &KhiveRuntime,
886 token: &NamespaceToken,
887 id: Uuid,
888 patch: crate::curation::EntityPatch,
889) -> RuntimeResult<AtomicOpPlan> {
890 let (entity, reindex_required, changed_fields, expected_updated_at, expected_deleted_at) =
891 runtime.prepare_update_entity(token, id, patch).await?;
892 let mut statements = vec![PlanStatement {
893 statement: entity_replace_if_unchanged_statement(
894 &entity,
895 expected_updated_at,
896 expected_deleted_at,
897 ),
898 guard: Some(AffectedRowGuard::exactly(1)),
899 }];
900 statements.extend(event_append_statements(
901 &entity.namespace,
902 "update",
903 EventKind::EntityUpdated,
904 SubstrateKind::Entity,
905 id,
906 serde_json::json!({
907 "id": id,
908 "namespace": entity.namespace,
909 "changed_fields": changed_fields,
910 }),
911 )?);
912 let post_commit = if reindex_required {
913 PostCommitEffect::ReindexEntity { entity_id: id }
914 } else {
915 PostCommitEffect::None
916 };
917 Ok(AtomicOpPlan::Update(UpdatePlan {
918 target_id: id,
919 statements,
920 post_commit,
921 edge_natural_key: None,
922 }))
923}
924
925async fn prepare_update_edge(
945 runtime: &KhiveRuntime,
946 id: Uuid,
947 mut edge: khive_storage::types::Edge,
948 args: &Value,
949) -> RuntimeResult<AtomicOpPlan> {
950 reject_inapplicable_update_fields(args, "edge")?;
951
952 let expected_updated_at = edge.updated_at;
953 let expected_deleted_at = edge.deleted_at;
954
955 let relation_raw = optional_str(args, "relation");
956 let weight = optional_f64(args, "weight")?;
957 let properties = optional_properties(args, "properties")?;
958
959 if let Some(ref p) = properties {
960 crate::secret_gate::check_json(p)?;
961 }
962 crate::secret_gate::reject_reserved_secret_gate_property(properties.as_ref())?;
963
964 let namespace = edge.namespace.clone();
965 let record_tok = NamespaceToken::for_namespace(
966 khive_types::Namespace::parse(&namespace)
967 .map_err(|e| RuntimeError::Internal(format!("edge namespace invalid: {e}")))?,
968 );
969
970 let mut changed_fields: Vec<&'static str> = Vec::new();
971 if let Some(raw) = relation_raw {
972 let relation = parse_edge_relation(raw)?;
973 runtime
974 .validate_edge_relation_endpoints(&record_tok, edge.source_id, edge.target_id, relation)
975 .await?;
976 edge.relation = relation;
977 changed_fields.push("relation");
978 }
979 if let Some(w) = weight {
980 if !w.is_finite() || !(0.0..=1.0).contains(&w) {
981 return Err(RuntimeError::InvalidInput(format!(
982 "edge weight must be a finite value in [0.0, 1.0]; got {w}"
983 )));
984 }
985 edge.weight = w;
986 changed_fields.push("weight");
987 }
988 if let Some(p) = properties {
989 edge.metadata = Some(p);
990 changed_fields.push("properties");
991 }
992
993 let (canon_src, canon_tgt) =
994 canonical_edge_endpoints(edge.relation, edge.source_id, edge.target_id);
995 let now = chrono::Utc::now();
996
997 let mut statements: Vec<PlanStatement> = Vec::new();
998 let mut edge_natural_key: Option<EdgeNaturalKey> = None;
999
1000 if edge.relation.is_symmetric() {
1001 let metadata_str = edge
1011 .metadata
1012 .as_ref()
1013 .map(|v| serde_json::to_string(v).unwrap_or_default());
1014
1015 let minimum_updated_at_micros = expected_updated_at
1020 .timestamp_micros()
1021 .checked_add(1)
1022 .ok_or_else(|| {
1023 RuntimeError::Internal(format!(
1024 "edge {id} updated_at is already at i64::MAX and cannot advance"
1025 ))
1026 })?;
1027 let symmetric_updated_at_micros = now.timestamp_micros().max(minimum_updated_at_micros);
1028 let expected_deleted_at_micros = expected_deleted_at.map(|v| v.timestamp_micros());
1029
1030 statements.push(PlanStatement {
1031 statement: edge_symmetric_delete_if_conflict_statement(
1032 &namespace,
1033 id,
1034 canon_src,
1035 canon_tgt,
1036 edge.relation,
1037 expected_updated_at.timestamp_micros(),
1038 expected_deleted_at_micros,
1039 ),
1040 guard: Some(AffectedRowGuard {
1041 expected_min: 0,
1042 expected_max: Some(1),
1043 }),
1044 });
1045 statements.push(PlanStatement {
1046 statement: edge_symmetric_absorb_or_update_inplace_statement(
1047 &namespace,
1048 id,
1049 canon_src,
1050 canon_tgt,
1051 edge.relation,
1052 edge.weight,
1053 symmetric_updated_at_micros,
1054 metadata_str.as_deref(),
1055 edge.target_backend.as_deref(),
1056 expected_updated_at.timestamp_micros(),
1057 expected_deleted_at_micros,
1058 ),
1059 guard: Some(AffectedRowGuard::exactly(1)),
1060 });
1061
1062 edge_natural_key = Some(EdgeNaturalKey {
1067 namespace: namespace.clone(),
1068 canon_source_id: canon_src,
1069 canon_target_id: canon_tgt,
1070 relation: edge.relation,
1071 });
1072 } else {
1073 let minimum_updated_at_micros = expected_updated_at
1084 .timestamp_micros()
1085 .checked_add(1)
1086 .ok_or_else(|| {
1087 RuntimeError::Internal(format!(
1088 "edge {id} updated_at is already at i64::MAX and cannot advance"
1089 ))
1090 })?;
1091 let now_micros = now.timestamp_micros().max(minimum_updated_at_micros);
1092 edge.updated_at = chrono::DateTime::from_timestamp_micros(now_micros).ok_or_else(|| {
1093 RuntimeError::Internal(format!(
1094 "edge {id}: computed updated_at {now_micros} is not a valid timestamp"
1095 ))
1096 })?;
1097 statements.push(PlanStatement {
1098 statement: edge_replace_if_unchanged_statement(
1099 &edge,
1100 expected_updated_at,
1101 expected_deleted_at,
1102 ),
1103 guard: Some(AffectedRowGuard::exactly(1)),
1104 });
1105 }
1106
1107 statements.extend(event_append_statements(
1112 &namespace,
1113 "update",
1114 EventKind::EdgeUpdated,
1115 SubstrateKind::Entity,
1116 id,
1117 serde_json::json!({"id": id, "namespace": namespace, "changed_fields": changed_fields}),
1118 )?);
1119
1120 Ok(AtomicOpPlan::Update(UpdatePlan {
1121 target_id: id,
1122 statements,
1123 post_commit: PostCommitEffect::None,
1124 edge_natural_key,
1125 }))
1126}
1127
1128pub enum AtomicDeleteKind {
1145 Entity { specific: Option<String> },
1146 Note { specific: Option<String> },
1147 Edge,
1148}
1149
1150pub async fn prepare_delete(
1156 runtime: &KhiveRuntime,
1157 token: &NamespaceToken,
1158 args: &Value,
1159 expected_kind: Option<AtomicDeleteKind>,
1160) -> RuntimeResult<AtomicOpPlan> {
1161 let id = require_uuid(args, "id")?;
1162 let actor = format!("{}:{}", token.actor().kind, token.actor().id);
1163 let hard = obj(args)?
1164 .get("hard")
1165 .and_then(|v| v.as_bool())
1166 .unwrap_or(false);
1167
1168 let resolved = if hard {
1174 runtime.resolve_by_id_including_deleted(token, id).await?
1175 } else {
1176 runtime.resolve_by_id(token, id).await?
1177 };
1178
1179 match resolved {
1180 Some(Resolved::Entity(entity)) => {
1181 match &expected_kind {
1182 None => {}
1183 Some(AtomicDeleteKind::Entity {
1184 specific: Some(expected),
1185 }) if &entity.kind != expected => {
1186 return Err(RuntimeError::NotFound(format!("{expected} {id}")));
1187 }
1188 Some(AtomicDeleteKind::Entity { .. }) => {}
1189 Some(AtomicDeleteKind::Note { .. }) => {
1190 return Err(RuntimeError::NotFound(format!("note {id}")));
1191 }
1192 Some(AtomicDeleteKind::Edge) => {
1193 return Err(RuntimeError::NotFound(format!("edge {id}")));
1194 }
1195 }
1196 let namespace = entity.namespace.clone();
1197 let mut statements = if hard {
1202 vec![
1203 PlanStatement {
1204 statement: delete_record_attachments_statement(
1205 id,
1206 AttachmentSubstrate::Entity,
1207 ),
1208 guard: None,
1209 },
1210 PlanStatement {
1211 statement: entity_hard_delete_statement(id),
1212 guard: Some(AffectedRowGuard::exactly(1)),
1213 },
1214 ]
1215 } else {
1216 let deleted_at = chrono::Utc::now().timestamp_micros();
1217 vec![PlanStatement {
1218 statement: entity_soft_delete_statement(id, deleted_at),
1219 guard: Some(AffectedRowGuard::exactly(1)),
1220 }]
1221 };
1222 if hard {
1223 statements.extend(
1224 hard_delete_lineage_warning_statements(
1225 &namespace,
1226 &actor,
1227 id,
1228 SubstrateKind::Entity,
1229 )
1230 .into_iter()
1231 .map(|statement| PlanStatement {
1232 statement,
1233 guard: None,
1234 }),
1235 );
1236 statements.push(PlanStatement {
1239 statement: purge_incident_edges_statement(id),
1240 guard: None,
1241 });
1242 }
1243 push_index_purge_statements(
1248 runtime,
1249 &mut statements,
1250 "fts_entities",
1251 &namespace,
1252 id,
1253 "atomic-delete-entity",
1254 )
1255 .await?;
1256 statements.extend(event_append_statements(
1262 &namespace,
1263 "delete",
1264 EventKind::EntityDeleted,
1265 SubstrateKind::Entity,
1266 id,
1267 serde_json::json!({"id": id, "namespace": namespace, "hard": hard}),
1268 )?);
1269 Ok(AtomicOpPlan::Delete(DeletePlan {
1270 target_id: id,
1271 statements,
1272 post_commit: PostCommitEffect::None,
1273 }))
1274 }
1275 Some(Resolved::Note(note)) => {
1276 match &expected_kind {
1277 None => {}
1278 Some(AtomicDeleteKind::Note {
1279 specific: Some(expected),
1280 }) if ¬e.kind != expected => {
1281 return Err(RuntimeError::NotFound(format!("{expected} {id}")));
1282 }
1283 Some(AtomicDeleteKind::Note { .. }) => {}
1284 Some(AtomicDeleteKind::Entity { .. }) => {
1285 return Err(RuntimeError::NotFound(format!("entity {id}")));
1286 }
1287 Some(AtomicDeleteKind::Edge) => {
1288 return Err(RuntimeError::NotFound(format!("edge {id}")));
1289 }
1290 }
1291 let namespace = note.namespace.clone();
1292 let mut statements = if hard {
1296 vec![
1297 PlanStatement {
1298 statement: delete_record_attachments_statement(
1299 id,
1300 AttachmentSubstrate::Note,
1301 ),
1302 guard: None,
1303 },
1304 PlanStatement {
1305 statement: note_hard_delete_statement(id),
1306 guard: Some(AffectedRowGuard::exactly(1)),
1307 },
1308 ]
1309 } else {
1310 let deleted_at = chrono::Utc::now().timestamp_micros();
1311 vec![PlanStatement {
1312 statement: note_soft_delete_statement(id, deleted_at),
1313 guard: Some(AffectedRowGuard::exactly(1)),
1314 }]
1315 };
1316 if hard {
1317 statements.extend(
1318 hard_delete_lineage_warning_statements(
1319 &namespace,
1320 &actor,
1321 id,
1322 SubstrateKind::Note,
1323 )
1324 .into_iter()
1325 .map(|statement| PlanStatement {
1326 statement,
1327 guard: None,
1328 }),
1329 );
1330 statements.push(PlanStatement {
1331 statement: purge_incident_edges_statement(id),
1332 guard: None,
1333 });
1334 }
1335 push_index_purge_statements(
1340 runtime,
1341 &mut statements,
1342 "fts_notes",
1343 &namespace,
1344 id,
1345 "atomic-delete-note",
1346 )
1347 .await?;
1348 statements.extend(event_append_statements(
1352 &namespace,
1353 "delete",
1354 EventKind::NoteDeleted,
1355 SubstrateKind::Note,
1356 id,
1357 serde_json::json!({"id": id, "namespace": namespace, "hard": hard}),
1358 )?);
1359 Ok(AtomicOpPlan::Delete(DeletePlan {
1360 target_id: id,
1361 statements,
1362 post_commit: PostCommitEffect::NoteDeleted {
1367 note_id: id,
1368 kind: note.kind.clone(),
1369 },
1370 }))
1371 }
1372 Some(_) => Err(RuntimeError::InvalidInput(format!(
1373 "delete target {id} must be an entity, note, or edge"
1374 ))),
1375 None => match &expected_kind {
1379 Some(AtomicDeleteKind::Entity { .. }) => {
1380 Err(RuntimeError::NotFound(format!("entity/note {id}")))
1381 }
1382 Some(AtomicDeleteKind::Note { .. }) => {
1383 Err(RuntimeError::NotFound(format!("entity/note {id}")))
1384 }
1385 Some(AtomicDeleteKind::Edge) | None => {
1386 let edge = if hard {
1387 runtime.get_edge_including_deleted(token, id).await?
1388 } else {
1389 runtime.get_edge(token, id).await?
1390 };
1391 match edge {
1392 Some(edge) => prepare_delete_edge(id, edge, hard, &actor).await,
1393 None => Err(RuntimeError::NotFound(format!("entity/note/edge {id}"))),
1394 }
1395 }
1396 },
1397 }
1398}
1399
1400async fn prepare_delete_edge(
1409 id: Uuid,
1410 edge: khive_storage::types::Edge,
1411 hard: bool,
1412 actor: &str,
1413) -> RuntimeResult<AtomicOpPlan> {
1414 let namespace = edge.namespace.clone();
1415 let mut statements: Vec<PlanStatement> = Vec::new();
1416
1417 if hard {
1418 statements.extend(
1419 hard_delete_lineage_warning_statements(&namespace, actor, id, SubstrateKind::Entity)
1420 .into_iter()
1421 .map(|statement| PlanStatement {
1422 statement,
1423 guard: None,
1424 }),
1425 );
1426 statements.push(PlanStatement {
1431 statement: purge_incident_edges_statement(id),
1432 guard: None,
1433 });
1434 statements.push(PlanStatement {
1435 statement: edge_hard_delete_statement(id),
1436 guard: Some(AffectedRowGuard::exactly(1)),
1437 });
1438 } else {
1439 let now = chrono::Utc::now().timestamp_micros();
1440 statements.push(PlanStatement {
1441 statement: edge_soft_delete_statement(id, now),
1442 guard: Some(AffectedRowGuard::exactly(1)),
1443 });
1444 }
1445
1446 statements.extend(event_append_statements(
1447 &namespace,
1448 "delete",
1449 EventKind::EdgeDeleted,
1450 SubstrateKind::Entity,
1451 id,
1452 serde_json::json!({"id": id, "namespace": namespace, "hard": hard}),
1453 )?);
1454
1455 Ok(AtomicOpPlan::Delete(DeletePlan {
1456 target_id: id,
1457 statements,
1458 post_commit: PostCommitEffect::None,
1459 }))
1460}
1461
1462fn parse_edge_relation(raw: &str) -> RuntimeResult<EdgeRelation> {
1467 raw.parse::<EdgeRelation>()
1468 .map_err(|e| RuntimeError::InvalidInput(format!("unknown edge relation {raw:?}: {e}")))
1469}
1470
1471async fn prepare_link(
1472 runtime: &KhiveRuntime,
1473 token: &NamespaceToken,
1474 args: &Value,
1475) -> RuntimeResult<AtomicOpPlan> {
1476 let source_id = require_uuid(args, "source_id")?;
1477 let target_id = require_uuid(args, "target_id")?;
1478 let relation = parse_edge_relation(require_str(args, "relation")?)?;
1479 let weight = optional_f64(args, "weight")?.unwrap_or(1.0);
1480 let metadata = obj(args)?.get("metadata").cloned();
1481
1482 let mut metadata = crate::merge_entry_metadata(
1488 metadata,
1489 optional_str(args, "dependency_kind").map(String::from),
1490 )?;
1491
1492 validate_edge_weight(weight)?;
1493 runtime
1494 .validate_edge_relation_endpoints(token, source_id, target_id, relation)
1495 .await?;
1496
1497 let (canon_source, canon_target) = canonical_edge_endpoints(relation, source_id, target_id);
1498
1499 if relation == EdgeRelation::DependsOn {
1506 metadata = match (
1507 runtime.resolve_edge_endpoint(token, canon_source).await?,
1508 runtime.resolve_edge_endpoint(token, canon_target).await?,
1509 ) {
1510 (Some(Resolved::Entity(src_e)), Some(Resolved::Entity(tgt_e))) => {
1511 merge_dependency_kind(&src_e.kind, &tgt_e.kind, metadata)
1512 }
1513 _ => metadata,
1514 };
1515 }
1516
1517 validate_edge_metadata(relation, metadata.as_ref())?;
1518 let edge_id = Uuid::new_v4();
1519 let namespace = token.namespace().as_str().to_string();
1520 let now = chrono::Utc::now().timestamp_micros();
1521 let metadata_str = metadata.map(|m| serde_json::to_string(&m).unwrap_or_default());
1522
1523 let statement = edge_insert_guarded_by_endpoints_statement(
1536 &namespace,
1537 edge_id,
1538 canon_source,
1539 canon_target,
1540 relation,
1541 weight,
1542 now,
1543 metadata_str.as_deref(),
1544 );
1545
1546 Ok(AtomicOpPlan::Link(LinkPlan {
1547 source_id: canon_source,
1548 target_id: canon_target,
1549 statement: PlanStatement {
1550 statement,
1551 guard: Some(AffectedRowGuard::exactly(1)),
1552 },
1553 }))
1554}
1555
1556async fn prepare_merge(
1570 runtime: &KhiveRuntime,
1571 token: &NamespaceToken,
1572 args: &Value,
1573) -> RuntimeResult<AtomicOpPlan> {
1574 let into_id = require_uuid(args, "into_id")?;
1575 let from_id = require_uuid(args, "from_id")?;
1576 if into_id == from_id {
1577 return Err(RuntimeError::InvalidInput(
1578 "cannot merge an entity into itself".into(),
1579 ));
1580 }
1581
1582 let entities = runtime.entities(token)?;
1583 entities
1584 .get_entity(into_id)
1585 .await?
1586 .ok_or_else(|| RuntimeError::NotFound(format!("entity {into_id}")))?;
1587 entities
1588 .get_entity(from_id)
1589 .await?
1590 .ok_or_else(|| RuntimeError::NotFound(format!("entity {from_id}")))?;
1591
1592 let now = chrono::Utc::now().timestamp_micros();
1593 let rewires = vec![
1594 crate::atomic_plan::PlanPredicate {
1595 description: "source_id = :from".to_string(),
1596 statement: SqlStatement {
1597 sql: "UPDATE graph_edges SET source_id = ?1, updated_at = ?2 WHERE source_id = ?3"
1598 .to_string(),
1599 params: vec![
1600 SqlValue::Text(into_id.to_string()),
1601 SqlValue::Integer(now),
1602 SqlValue::Text(from_id.to_string()),
1603 ],
1604 label: Some("atomic-merge-rewire-source".to_string()),
1605 },
1606 },
1607 crate::atomic_plan::PlanPredicate {
1608 description: "target_id = :from".to_string(),
1609 statement: SqlStatement {
1610 sql: "UPDATE graph_edges SET target_id = ?1, updated_at = ?2 WHERE target_id = ?3"
1611 .to_string(),
1612 params: vec![
1613 SqlValue::Text(into_id.to_string()),
1614 SqlValue::Integer(now),
1615 SqlValue::Text(from_id.to_string()),
1616 ],
1617 label: Some("atomic-merge-rewire-target".to_string()),
1618 },
1619 },
1620 ];
1621 let lifecycle = vec![PlanStatement {
1622 statement: SqlStatement {
1623 sql: "UPDATE entities SET deleted_at = ?1, merged_into = ?2 \
1624 WHERE id = ?3 AND deleted_at IS NULL"
1625 .to_string(),
1626 params: vec![
1627 SqlValue::Integer(now),
1628 SqlValue::Text(into_id.to_string()),
1629 SqlValue::Text(from_id.to_string()),
1630 ],
1631 label: Some("atomic-merge-tombstone-from-entity".to_string()),
1632 },
1633 guard: Some(AffectedRowGuard::exactly(1)),
1634 }];
1635
1636 Ok(AtomicOpPlan::Merge(MergePlan {
1637 into_id,
1638 from_id,
1639 rewires,
1640 lifecycle,
1641 }))
1642}
1643
1644#[derive(Clone, Debug, PartialEq, Eq)]
1654pub struct PostCommitEmbeddingOutcome {
1655 pub effect: PostCommitEffect,
1657 pub truncation: crate::retrieval::EmbeddingTruncationReport,
1659}
1660
1661pub async fn apply_post_commit_effects(
1663 runtime: &KhiveRuntime,
1664 token: &NamespaceToken,
1665 effects: CommittedPostCommitEffects,
1666) -> RuntimeResult<()> {
1667 apply_post_commit_effects_with_report(runtime, token, effects)
1668 .await
1669 .map(|_| ())
1670}
1671
1672pub async fn apply_post_commit_effects_with_report(
1679 runtime: &KhiveRuntime,
1680 token: &NamespaceToken,
1681 effects: CommittedPostCommitEffects,
1682) -> RuntimeResult<Vec<PostCommitEmbeddingOutcome>> {
1683 let mut embedding_outcomes = Vec::new();
1684 for effect in effects.into_effects() {
1685 match effect {
1686 PostCommitEffect::None => {}
1687 PostCommitEffect::ReindexEntity { entity_id } => {
1688 if let Some(entity) = runtime.entities(token)?.get_entity(entity_id).await? {
1689 let truncation = runtime.reindex_entity(token, &entity).await?;
1690 embedding_outcomes.push(PostCommitEmbeddingOutcome {
1691 effect: PostCommitEffect::ReindexEntity { entity_id },
1692 truncation,
1693 });
1694 }
1695 }
1696 PostCommitEffect::ReindexNote { note_id } => {
1697 if let Some(note) = runtime.notes(token)?.get_note(note_id).await? {
1698 let truncation = runtime.reindex_note(token, ¬e).await?;
1699 embedding_outcomes.push(PostCommitEmbeddingOutcome {
1700 effect: PostCommitEffect::ReindexNote { note_id },
1701 truncation,
1702 });
1703 runtime.fire_note_mutation_hook(¬e.kind, note.id).await;
1711 }
1712 }
1713 PostCommitEffect::NoteDeleted { note_id, kind } => {
1714 runtime.fire_note_mutation_hook(&kind, note_id).await;
1723 }
1724 PostCommitEffect::GtdAudit { .. } => {
1725 }
1733 }
1734 }
1735 Ok(embedding_outcomes)
1736}
1737
1738#[cfg(test)]
1739mod tests {
1740 use super::*;
1741
1742 use async_trait::async_trait;
1743 use lattice_embed::{EmbedError, EmbeddingModel, EmbeddingService, MAX_TEXT_BYTES};
1744 use serde_json::json;
1745
1746 use khive_types::Namespace;
1747
1748 use crate::embedder_registry::EmbedderProvider;
1749 use crate::runtime::RuntimeConfig;
1750
1751 const STUB_MODEL: &str = "stub-adr099-b3";
1752 const STUB_DIMS: usize = 4;
1753
1754 struct StubService;
1755
1756 #[async_trait]
1757 impl EmbeddingService for StubService {
1758 async fn embed(
1759 &self,
1760 texts: &[String],
1761 _model: EmbeddingModel,
1762 ) -> Result<Vec<Vec<f32>>, EmbedError> {
1763 Ok(texts.iter().map(|_| vec![0.5_f32; STUB_DIMS]).collect())
1764 }
1765
1766 fn supports_model(&self, _model: EmbeddingModel) -> bool {
1767 true
1768 }
1769
1770 fn name(&self) -> &'static str {
1771 STUB_MODEL
1772 }
1773 }
1774
1775 struct StubProvider;
1776
1777 #[async_trait]
1778 impl EmbedderProvider for StubProvider {
1779 fn name(&self) -> &str {
1780 STUB_MODEL
1781 }
1782
1783 fn dimensions(&self) -> usize {
1784 STUB_DIMS
1785 }
1786
1787 async fn build(&self) -> RuntimeResult<std::sync::Arc<dyn EmbeddingService>> {
1788 Ok(std::sync::Arc::new(StubService))
1789 }
1790 }
1791
1792 fn scratch_runtime() -> KhiveRuntime {
1793 let dir = tempfile::tempdir().expect("tempdir");
1794 let path = dir.path().join("atomic_prepare_reindex.db");
1795 let rt = KhiveRuntime::new(RuntimeConfig {
1796 db_path: Some(path),
1797 embedding_model: None,
1798 additional_embedding_models: vec![],
1799 ..RuntimeConfig::default()
1800 })
1801 .expect("runtime");
1802 std::mem::forget(dir);
1803 rt
1804 }
1805
1806 #[tokio::test]
1814 async fn atomic_update_entity_rejects_note_only_field_salience() {
1815 let runtime = scratch_runtime();
1816 let token = runtime
1817 .authorize(Namespace::parse("local").expect("ns"))
1818 .expect("authorize");
1819 let entity = khive_storage::Entity::new("local", "concept", "GapFourEntity");
1820 let entity_id = entity.id;
1821 runtime
1822 .entities(&token)
1823 .expect("entities store")
1824 .upsert_entity(entity)
1825 .await
1826 .expect("seed entity");
1827
1828 let err = prepare_update(
1829 &runtime,
1830 &token,
1831 &json!({"id": entity_id.to_string(), "salience": 0.9}),
1832 None,
1833 )
1834 .await
1835 .expect_err("salience on an entity must be rejected, not silently accepted");
1836 assert!(
1837 matches!(err, RuntimeError::InvalidInput(ref msg) if msg.contains("salience") && msg.contains("not valid for an entity")),
1838 "expected an InvalidInput naming the offending field, got: {err:?}"
1839 );
1840
1841 let plan = prepare_update(
1843 &runtime,
1844 &token,
1845 &json!({
1846 "id": entity_id.to_string(),
1847 "name": "GapFourEntity-renamed",
1848 "description": "updated description",
1849 "tags": ["a", "b"],
1850 }),
1851 None,
1852 )
1853 .await
1854 .expect("a valid entity field set must still be accepted");
1855 let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
1856 .await
1857 .expect("seam call ok");
1858 assert!(matches!(
1859 outcome,
1860 crate::atomic_runner::AtomicRunOutcome::Committed { .. }
1861 ));
1862 let entity = runtime
1863 .get_entity(&token, entity_id)
1864 .await
1865 .expect("get_entity");
1866 assert_eq!(entity.name, "GapFourEntity-renamed");
1867 }
1868
1869 #[tokio::test]
1870 async fn atomic_update_entity_type_persists_patch_and_schedules_reindex() {
1871 let runtime = scratch_runtime();
1872 runtime.install_entity_type_validator(std::sync::Arc::new(|kind, entity_type| {
1873 let Some(raw) = entity_type else {
1874 return Ok(None);
1875 };
1876 let normalized = raw.trim().to_ascii_lowercase();
1877 if kind == "concept" && normalized == "algorithm" {
1878 Ok(Some(normalized))
1879 } else {
1880 Err(RuntimeError::InvalidInput(format!(
1881 "unknown entity_type {raw:?} for {kind:?}; valid: algorithm"
1882 )))
1883 }
1884 }));
1885 let token = runtime
1886 .authorize(Namespace::parse("local").expect("ns"))
1887 .expect("authorize");
1888 let mut entity = khive_storage::Entity::new("local", "concept", "AtomicHistorical");
1889 entity.description = Some("keep description".to_string());
1890 entity.properties = Some(json!({"type": "algorithm", "keep": true}));
1891 entity.tags = vec!["keep-tag".to_string()];
1892 let entity_id = entity.id;
1893 runtime
1894 .entities(&token)
1895 .expect("entities store")
1896 .upsert_entity(entity)
1897 .await
1898 .expect("seed entity");
1899
1900 let plan = prepare_update(
1901 &runtime,
1902 &token,
1903 &json!({"id": entity_id.to_string(), "entity_type": " Algorithm "}),
1904 None,
1905 )
1906 .await
1907 .expect("atomic prepare must accept a registered entity_type");
1908 let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
1909 .await
1910 .expect("atomic update must run");
1911 let post_commit = match outcome {
1912 crate::atomic_runner::AtomicRunOutcome::Committed { post_commit } => post_commit,
1913 other => panic!("expected Committed, got {other:?}"),
1914 };
1915 assert_eq!(
1916 post_commit.as_slice(),
1917 &[PostCommitEffect::ReindexEntity { entity_id }],
1918 "entity_type patch must schedule the normal entity reindex path"
1919 );
1920
1921 let updated = runtime
1922 .get_entity(&token, entity_id)
1923 .await
1924 .expect("read updated entity");
1925 assert_eq!(updated.entity_type.as_deref(), Some("algorithm"));
1926 assert_eq!(updated.name, "AtomicHistorical");
1927 assert_eq!(updated.description.as_deref(), Some("keep description"));
1928 assert_eq!(
1929 updated.properties,
1930 Some(json!({"type": "algorithm", "keep": true}))
1931 );
1932 assert_eq!(updated.tags, vec!["keep-tag"]);
1933 }
1934
1935 #[tokio::test]
1939 async fn atomic_update_note_rejects_entity_only_field_description() {
1940 let runtime = scratch_runtime();
1941 let token = runtime
1942 .authorize(Namespace::parse("local").expect("ns"))
1943 .expect("authorize");
1944 let mut note = khive_storage::note::Note::new("local", "observation", "gap-4 note content");
1945 note.name = Some("gap-four-note".to_string());
1946 let note_id = note.id;
1947 runtime
1948 .notes(&token)
1949 .expect("notes store")
1950 .upsert_note(note)
1951 .await
1952 .expect("seed note");
1953
1954 let err = prepare_update(
1955 &runtime,
1956 &token,
1957 &json!({"id": note_id.to_string(), "description": "entities have descriptions, notes don't"}),
1958 None,
1959 )
1960 .await
1961 .expect_err("description on a note must be rejected, not silently accepted");
1962 assert!(
1963 matches!(err, RuntimeError::InvalidInput(ref msg) if msg.contains("description") && msg.contains("not valid for a note")),
1964 "expected an InvalidInput naming the offending field, got: {err:?}"
1965 );
1966
1967 let plan = prepare_update(
1969 &runtime,
1970 &token,
1971 &json!({"id": note_id.to_string(), "content": "gap-4 note content, revised"}),
1972 None,
1973 )
1974 .await
1975 .expect("a valid note field must still be accepted");
1976 let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
1977 .await
1978 .expect("seam call ok");
1979 assert!(matches!(
1980 outcome,
1981 crate::atomic_runner::AtomicRunOutcome::Committed { .. }
1982 ));
1983 }
1984
1985 #[tokio::test]
1990 async fn atomic_update_note_content_is_fts_and_vector_reindexed_post_commit() {
1991 let runtime = scratch_runtime();
1992 runtime.register_embedder(StubProvider);
1993 let token = runtime
1994 .authorize(Namespace::parse("local").expect("ns"))
1995 .expect("authorize");
1996
1997 let mut note = khive_storage::note::Note::new("local", "observation", "original content");
1998 note.name = Some("reindex-target".to_string());
1999 let note_id = note.id;
2000 runtime
2001 .notes(&token)
2002 .expect("notes store")
2003 .upsert_note(note)
2004 .await
2005 .expect("seed note");
2006
2007 let vec_store = runtime
2009 .vectors_for_model(&token, STUB_MODEL)
2010 .expect("vec store");
2011 assert_eq!(vec_store.count().await.expect("count before"), 0);
2012
2013 let updated_content = format!("freshly-updated-content-xyz{}", "x".repeat(MAX_TEXT_BYTES));
2014 let plan = prepare_update(
2015 &runtime,
2016 &token,
2017 &json!({"id": note_id.to_string(), "content": updated_content}),
2018 None,
2019 )
2020 .await
2021 .expect("prepare update");
2022
2023 let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
2024 .await
2025 .expect("seam call ok");
2026 let post_commit = match outcome {
2027 crate::atomic_runner::AtomicRunOutcome::Committed { post_commit } => post_commit,
2028 other => panic!("expected Committed, got {other:?}"),
2029 };
2030 assert_eq!(
2031 post_commit.as_slice(),
2032 &[PostCommitEffect::ReindexNote { note_id }],
2033 "content change must schedule exactly one ReindexNote post-commit effect"
2034 );
2035
2036 let embedding_outcomes =
2037 apply_post_commit_effects_with_report(&runtime, &token, post_commit)
2038 .await
2039 .expect("apply post-commit effects");
2040 assert_eq!(embedding_outcomes.len(), 1);
2041 assert_eq!(
2042 embedding_outcomes[0].effect,
2043 PostCommitEffect::ReindexNote { note_id }
2044 );
2045 assert_eq!(embedding_outcomes[0].truncation.truncated, 1);
2046 assert!(embedding_outcomes[0].truncation.discarded_bytes > 0);
2047
2048 let doc = runtime
2050 .text_for_notes(&token)
2051 .expect("text store")
2052 .get_document("local", note_id)
2053 .await
2054 .expect("get_document")
2055 .expect("document must be indexed after post-commit reindex");
2056 assert!(
2057 doc.body.contains("freshly-updated-content-xyz"),
2058 "FTS body must reflect the committed content: {:?}",
2059 doc.body
2060 );
2061
2062 assert_eq!(
2064 vec_store.count().await.expect("count after"),
2065 1,
2066 "post-commit reindex must have inserted a vector row for the stub model"
2067 );
2068 }
2069
2070 #[tokio::test]
2082 async fn atomic_note_update_and_delete_post_commit_effects_execute_exactly_once() {
2083 let runtime = scratch_runtime();
2084 let token = runtime
2085 .authorize(Namespace::parse("local").expect("ns"))
2086 .expect("authorize");
2087
2088 let fired: std::sync::Arc<std::sync::Mutex<Vec<(String, uuid::Uuid)>>> =
2089 std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
2090 let fired_for_hook = fired.clone();
2091 runtime.install_note_mutation_hook(std::sync::Arc::new(
2092 move |kind: String, id: uuid::Uuid| {
2093 let fired = fired_for_hook.clone();
2094 Box::pin(async move {
2095 fired.lock().expect("lock").push((kind, id));
2096 })
2097 },
2098 ));
2099
2100 let mut note = khive_storage::note::Note::new("local", "observation", "hook-update-target");
2102 note.name = Some("hook-update-target".to_string());
2103 let update_note_id = note.id;
2104 runtime
2105 .notes(&token)
2106 .expect("notes store")
2107 .upsert_note(note)
2108 .await
2109 .expect("seed update-target note");
2110
2111 let plan = prepare_update(
2112 &runtime,
2113 &token,
2114 &json!({"id": update_note_id.to_string(), "content": "hook-update-target, revised"}),
2115 None,
2116 )
2117 .await
2118 .expect("prepare update");
2119 let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
2120 .await
2121 .expect("seam call ok");
2122 let post_commit = match outcome {
2123 crate::atomic_runner::AtomicRunOutcome::Committed { post_commit } => post_commit,
2124 other => panic!("expected Committed, got {other:?}"),
2125 };
2126 apply_post_commit_effects(&runtime, &token, post_commit)
2127 .await
2128 .expect("apply post-commit effects (update)");
2129
2130 let mut del_note =
2133 khive_storage::note::Note::new("local", "observation", "hook-delete-target");
2134 del_note.name = Some("hook-delete-target".to_string());
2135 let delete_note_id = del_note.id;
2136 runtime
2137 .notes(&token)
2138 .expect("notes store")
2139 .upsert_note(del_note)
2140 .await
2141 .expect("seed delete-target note");
2142
2143 let plan = prepare_delete(
2144 &runtime,
2145 &token,
2146 &json!({"id": delete_note_id.to_string(), "hard": false}),
2147 None,
2148 )
2149 .await
2150 .expect("prepare delete");
2151 let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
2152 .await
2153 .expect("seam call ok");
2154 let post_commit = match outcome {
2155 crate::atomic_runner::AtomicRunOutcome::Committed { post_commit } => post_commit,
2156 other => panic!("expected Committed, got {other:?}"),
2157 };
2158 assert_eq!(
2159 post_commit.as_slice(),
2160 &[PostCommitEffect::NoteDeleted {
2161 note_id: delete_note_id,
2162 kind: "observation".to_string(),
2163 }],
2164 "a committed note delete must schedule exactly one NoteDeleted post-commit effect"
2165 );
2166 apply_post_commit_effects(&runtime, &token, post_commit)
2167 .await
2168 .expect("apply post-commit effects (delete)");
2169
2170 assert_eq!(
2171 *fired.lock().expect("lock"),
2172 vec![
2173 ("observation".to_string(), update_note_id),
2174 ("observation".to_string(), delete_note_id),
2175 ],
2176 "each committed token must execute its note-mutation effect exactly once"
2177 );
2178 }
2179
2180 #[tokio::test]
2184 async fn atomic_delete_note_purges_fts_and_vector_indexes_soft_and_hard() {
2185 let runtime = scratch_runtime();
2186 runtime.register_embedder(StubProvider);
2187 let token = runtime
2188 .authorize(Namespace::parse("local").expect("ns"))
2189 .expect("authorize");
2190
2191 for hard in [false, true] {
2192 let mut note =
2193 khive_storage::note::Note::new("local", "observation", "purge-target content");
2194 note.name = Some(format!("purge-target-hard-{hard}"));
2195 let note_id = note.id;
2196 runtime
2197 .notes(&token)
2198 .expect("notes store")
2199 .upsert_note(note.clone())
2200 .await
2201 .expect("seed note");
2202 runtime
2203 .reindex_note(&token, ¬e)
2204 .await
2205 .expect("seed index rows");
2206
2207 let vec_store = runtime
2208 .vectors_for_model(&token, STUB_MODEL)
2209 .expect("vec store");
2210 assert_eq!(
2211 vec_store.count().await.expect("count before"),
2212 1,
2213 "seeded note must have a vector row before delete (hard={hard})"
2214 );
2215 assert!(
2216 runtime
2217 .text_for_notes(&token)
2218 .expect("text store")
2219 .get_document("local", note_id)
2220 .await
2221 .expect("get_document")
2222 .is_some(),
2223 "seeded note must have an FTS row before delete (hard={hard})"
2224 );
2225
2226 let plan = prepare_delete(
2227 &runtime,
2228 &token,
2229 &json!({"id": note_id.to_string(), "hard": hard}),
2230 None,
2231 )
2232 .await
2233 .expect("prepare delete");
2234 let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
2235 .await
2236 .expect("seam call ok");
2237 assert!(
2238 matches!(
2239 outcome,
2240 crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2241 ),
2242 "expected commit (hard={hard}): {outcome:?}"
2243 );
2244
2245 assert!(
2246 runtime
2247 .text_for_notes(&token)
2248 .expect("text store")
2249 .get_document("local", note_id)
2250 .await
2251 .expect("get_document")
2252 .is_none(),
2253 "FTS row must be purged after atomic delete (hard={hard})"
2254 );
2255 assert_eq!(
2256 vec_store.count().await.expect("count after"),
2257 0,
2258 "vector row must be purged after atomic delete (hard={hard})"
2259 );
2260 }
2261 }
2262
2263 #[tokio::test]
2267 async fn atomic_delete_entity_purges_fts_and_vector_indexes_soft_and_hard() {
2268 let runtime = scratch_runtime();
2269 runtime.register_embedder(StubProvider);
2270 let token = runtime
2271 .authorize(Namespace::parse("local").expect("ns"))
2272 .expect("authorize");
2273
2274 for hard in [false, true] {
2275 let entity =
2276 khive_storage::Entity::new("local", "concept", format!("purge-target-hard-{hard}"));
2277 let entity_id = entity.id;
2278 runtime
2279 .entities(&token)
2280 .expect("entities store")
2281 .upsert_entity(entity.clone())
2282 .await
2283 .expect("seed entity");
2284 runtime
2285 .reindex_entity(&token, &entity)
2286 .await
2287 .expect("seed index rows");
2288
2289 let vec_store = runtime
2290 .vectors_for_model(&token, STUB_MODEL)
2291 .expect("vec store");
2292 assert_eq!(
2293 vec_store.count().await.expect("count before"),
2294 1,
2295 "seeded entity must have a vector row before delete (hard={hard})"
2296 );
2297 assert!(
2298 runtime
2299 .text(&token)
2300 .expect("text store")
2301 .get_document("local", entity_id)
2302 .await
2303 .expect("get_document")
2304 .is_some(),
2305 "seeded entity must have an FTS row before delete (hard={hard})"
2306 );
2307
2308 let plan = prepare_delete(
2309 &runtime,
2310 &token,
2311 &json!({"id": entity_id.to_string(), "hard": hard}),
2312 None,
2313 )
2314 .await
2315 .expect("prepare delete");
2316 let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
2317 .await
2318 .expect("seam call ok");
2319 assert!(
2320 matches!(
2321 outcome,
2322 crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2323 ),
2324 "expected commit (hard={hard}): {outcome:?}"
2325 );
2326
2327 assert!(
2328 runtime
2329 .text(&token)
2330 .expect("text store")
2331 .get_document("local", entity_id)
2332 .await
2333 .expect("get_document")
2334 .is_none(),
2335 "FTS row must be purged after atomic delete (hard={hard})"
2336 );
2337 assert_eq!(
2338 vec_store.count().await.expect("count after"),
2339 0,
2340 "vector row must be purged after atomic delete (hard={hard})"
2341 );
2342 }
2343 }
2344
2345 #[tokio::test]
2346 async fn atomic_delete_entity_and_note_logs_vector_delete_rows() {
2347 let runtime = scratch_runtime();
2348 runtime.register_embedder(StubProvider);
2349 let token = runtime
2350 .authorize(Namespace::parse("local").expect("ns"))
2351 .expect("authorize");
2352
2353 let entity = khive_storage::Entity::new("local", "concept", "ann-delete-entity");
2354 let entity_id = entity.id;
2355 runtime
2356 .entities(&token)
2357 .expect("entities store")
2358 .upsert_entity(entity.clone())
2359 .await
2360 .expect("seed entity");
2361 runtime
2362 .reindex_entity(&token, &entity)
2363 .await
2364 .expect("seed entity vector row");
2365 let note = khive_storage::note::Note::new("local", "observation", "ann-delete-note");
2366 let note_id = note.id;
2367 runtime
2368 .notes(&token)
2369 .expect("notes store")
2370 .upsert_note(note.clone())
2371 .await
2372 .expect("seed note");
2373 runtime
2374 .reindex_note(&token, ¬e)
2375 .await
2376 .expect("seed note vector row");
2377
2378 for id in [entity_id, note_id] {
2379 let plan = prepare_delete(&runtime, &token, &json!({"id": id.to_string()}), None)
2380 .await
2381 .expect("prepare delete");
2382 let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
2383 .await
2384 .expect("seam call ok");
2385 assert!(matches!(
2386 outcome,
2387 crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2388 ));
2389 }
2390
2391 let mut reader = runtime.sql().reader().await.expect("sql reader");
2392 let count = reader
2393 .query_scalar(SqlStatement {
2394 sql: "SELECT COUNT(*) FROM ann_write_log \
2395 WHERE namespace = 'local' AND embedding_model = ?1 AND op = 'delete' \
2396 AND ((kind = 'entity' AND field = 'entity.body' AND subject_id = ?2) \
2397 OR (kind = 'note' AND field = 'note.content' AND subject_id = ?3))"
2398 .to_string(),
2399 params: vec![
2400 SqlValue::Text(STUB_MODEL.to_string()),
2401 SqlValue::Text(entity_id.to_string()),
2402 SqlValue::Text(note_id.to_string()),
2403 ],
2404 label: Some("test-atomic-delete-ann-write-log".to_string()),
2405 })
2406 .await
2407 .expect("query ANN write log");
2408 assert!(matches!(count, Some(SqlValue::Integer(2))));
2409 }
2410
2411 #[tokio::test]
2415 async fn atomic_link_symmetric_rejection_preserves_requested_pair() {
2416 let runtime = scratch_runtime();
2417 let token = runtime
2418 .authorize(Namespace::parse("local").expect("ns"))
2419 .expect("authorize");
2420 let entities = runtime.entities(&token).expect("entities store");
2421 let concept_id =
2422 Uuid::parse_str("ffffffff-ffff-ffff-ffff-ffffffffffff").expect("high UUID");
2423 let project_id = Uuid::nil();
2424 assert!(project_id < concept_id, "test must exercise UUID reversal");
2425
2426 let mut concept = khive_storage::Entity::new("local", "concept", "Concept source");
2427 concept.id = concept_id;
2428 let mut project = khive_storage::Entity::new("local", "project", "Project target");
2429 project.id = project_id;
2430 entities.upsert_entity(concept).await.expect("seed concept");
2431 entities.upsert_entity(project).await.expect("seed project");
2432
2433 let error = prepare_link(
2434 &runtime,
2435 &token,
2436 &json!({
2437 "source_id": concept_id.to_string(),
2438 "target_id": project_id.to_string(),
2439 "relation": "competes_with",
2440 }),
2441 )
2442 .await
2443 .expect_err("atomic link must reject concept competes_with project");
2444 let message = error.to_string();
2445 assert!(
2446 message.contains(
2447 "currently legal relations for concept -> project under the loaded endpoint rules: none"
2448 ),
2449 "atomic validation must diagnose caller order before persistence canonicalization; got: {message}"
2450 );
2451 assert!(
2452 !message.contains("currently legal relations for project -> concept"),
2453 "atomic validation must not diagnose the UUID-canonical reverse pair; got: {message}"
2454 );
2455 }
2456
2457 #[tokio::test]
2463 async fn atomic_link_persists_explicit_dependency_kind_and_infers_when_absent() {
2464 let runtime = scratch_runtime();
2465 let token = runtime
2466 .authorize(Namespace::parse("local").expect("ns"))
2467 .expect("authorize");
2468 let entities = runtime.entities(&token).expect("entities store");
2469
2470 fn metadata_json(plan: &AtomicOpPlan) -> String {
2471 let link_plan = match plan {
2472 AtomicOpPlan::Link(p) => p,
2473 other => panic!("expected an AtomicOpPlan::Link, got {other:?}"),
2474 };
2475 match link_plan.statement.statement.params.last() {
2476 Some(SqlValue::Text(s)) => s.clone(),
2477 other => panic!("expected the metadata param to be SqlValue::Text, got {other:?}"),
2478 }
2479 }
2480
2481 {
2483 let svc = khive_storage::Entity::new("local", "service", "SvcA");
2484 let proj = khive_storage::Entity::new("local", "project", "ProjB");
2485 let (svc_id, proj_id) = (svc.id, proj.id);
2486 entities.upsert_entity(svc).await.expect("seed svc");
2487 entities.upsert_entity(proj).await.expect("seed proj");
2488
2489 let plan = prepare_link(
2490 &runtime,
2491 &token,
2492 &json!({
2493 "source_id": svc_id.to_string(),
2494 "target_id": proj_id.to_string(),
2495 "relation": "depends_on",
2496 "dependency_kind": "artifact",
2497 }),
2498 )
2499 .await
2500 .expect("prepare link");
2501 let json_str = metadata_json(&plan);
2502 assert!(
2503 json_str.contains(r#""dependency_kind":"artifact""#),
2504 "explicit dependency_kind param must persist: {json_str}"
2505 );
2506 }
2507
2508 {
2511 let svc_a = khive_storage::Entity::new("local", "service", "SvcC");
2512 let svc_b = khive_storage::Entity::new("local", "service", "SvcD");
2513 let (a_id, b_id) = (svc_a.id, svc_b.id);
2514 entities.upsert_entity(svc_a).await.expect("seed svc a");
2515 entities.upsert_entity(svc_b).await.expect("seed svc b");
2516
2517 let plan = prepare_link(
2518 &runtime,
2519 &token,
2520 &json!({
2521 "source_id": a_id.to_string(),
2522 "target_id": b_id.to_string(),
2523 "relation": "depends_on",
2524 }),
2525 )
2526 .await
2527 .expect("prepare link");
2528 let json_str = metadata_json(&plan);
2529 assert!(
2530 json_str.contains(r#""dependency_kind":"runtime""#),
2531 "inferred dependency_kind for (service, service) must persist: {json_str}"
2532 );
2533 }
2534 }
2535
2536 async fn probe_edge_natural_key(
2541 runtime: &KhiveRuntime,
2542 namespace: &str,
2543 source_id: Uuid,
2544 target_id: Uuid,
2545 relation: &str,
2546 ) -> (usize, Option<f64>, Option<String>, Option<i64>) {
2547 let mut reader = runtime.sql().reader().await.expect("reader");
2548 let rows = reader
2549 .query_all(SqlStatement {
2550 sql: "SELECT weight, metadata, deleted_at FROM graph_edges \
2551 WHERE namespace = ?1 AND source_id = ?2 AND target_id = ?3 AND relation = ?4"
2552 .to_string(),
2553 params: vec![
2554 SqlValue::Text(namespace.to_string()),
2555 SqlValue::Text(source_id.to_string()),
2556 SqlValue::Text(target_id.to_string()),
2557 SqlValue::Text(relation.to_string()),
2558 ],
2559 label: Some("test-probe-edge-natural-key".to_string()),
2560 })
2561 .await
2562 .expect("probe edge natural key");
2563 let count = rows.len();
2564 let Some(row) = rows.into_iter().next() else {
2565 return (count, None, None, None);
2566 };
2567 let weight = match row.get("weight") {
2568 Some(SqlValue::Float(f)) => Some(*f),
2569 Some(SqlValue::Integer(i)) => Some(*i as f64),
2570 _ => None,
2571 };
2572 let metadata = match row.get("metadata") {
2573 Some(SqlValue::Text(s)) => Some(s.clone()),
2574 _ => None,
2575 };
2576 let deleted_at = match row.get("deleted_at") {
2577 Some(SqlValue::Integer(i)) => Some(*i),
2578 _ => None,
2579 };
2580 (count, weight, metadata, deleted_at)
2581 }
2582
2583 #[tokio::test]
2589 async fn atomic_link_of_already_linked_triple_upserts_weight_and_metadata() {
2590 let runtime = scratch_runtime();
2591 let token = runtime
2592 .authorize(Namespace::parse("local").expect("ns"))
2593 .expect("authorize");
2594 let entities = runtime.entities(&token).expect("entities store");
2595
2596 let a = khive_storage::Entity::new("local", "concept", "GapTwoA");
2597 let b = khive_storage::Entity::new("local", "concept", "GapTwoB");
2598 let (a_id, b_id) = (a.id, b.id);
2599 entities.upsert_entity(a).await.expect("seed a");
2600 entities.upsert_entity(b).await.expect("seed b");
2601
2602 let plan1 = prepare_link(
2604 &runtime,
2605 &token,
2606 &json!({
2607 "source_id": a_id.to_string(),
2608 "target_id": b_id.to_string(),
2609 "relation": "extends",
2610 "weight": 0.5,
2611 }),
2612 )
2613 .await
2614 .expect("prepare first link");
2615 let outcome1 = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan1])
2616 .await
2617 .expect("seam call ok");
2618 assert!(
2619 matches!(
2620 outcome1,
2621 crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2622 ),
2623 "fresh link must commit: {outcome1:?}"
2624 );
2625 let (count, weight, _metadata, deleted_at) =
2626 probe_edge_natural_key(&runtime, "local", a_id, b_id, "extends").await;
2627 assert_eq!(count, 1, "exactly one edge row after the fresh link");
2628 assert_eq!(weight, Some(0.5));
2629 assert!(deleted_at.is_none());
2630
2631 let plan2 = prepare_link(
2635 &runtime,
2636 &token,
2637 &json!({
2638 "source_id": a_id.to_string(),
2639 "target_id": b_id.to_string(),
2640 "relation": "extends",
2641 "weight": 0.9,
2642 "metadata": {"note": "relinked"},
2643 }),
2644 )
2645 .await
2646 .expect("prepare second link");
2647 let outcome2 = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan2])
2648 .await
2649 .expect("seam call ok");
2650 assert!(
2651 matches!(
2652 outcome2,
2653 crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2654 ),
2655 "re-link of an already-linked triple must upsert, not roll back: {outcome2:?}"
2656 );
2657 let (count, weight, metadata, deleted_at) =
2658 probe_edge_natural_key(&runtime, "local", a_id, b_id, "extends").await;
2659 assert_eq!(
2660 count, 1,
2661 "the natural-key UNIQUE constraint must still hold exactly one row (upsert, not a second insert)"
2662 );
2663 assert_eq!(weight, Some(0.9), "weight must be updated to the new value");
2664 assert!(
2665 metadata
2666 .as_deref()
2667 .is_some_and(|m| m.contains(r#""note":"relinked""#)),
2668 "metadata must be updated to the new value: {metadata:?}"
2669 );
2670 assert!(deleted_at.is_none());
2671 }
2672
2673 #[tokio::test]
2677 async fn atomic_link_of_soft_deleted_triple_resurrects_it() {
2678 let runtime = scratch_runtime();
2679 let token = runtime
2680 .authorize(Namespace::parse("local").expect("ns"))
2681 .expect("authorize");
2682 let entities = runtime.entities(&token).expect("entities store");
2683
2684 let a = khive_storage::Entity::new("local", "concept", "GapTwoResurrectA");
2685 let b = khive_storage::Entity::new("local", "concept", "GapTwoResurrectB");
2686 let (a_id, b_id) = (a.id, b.id);
2687 entities.upsert_entity(a).await.expect("seed a");
2688 entities.upsert_entity(b).await.expect("seed b");
2689
2690 let plan = prepare_link(
2691 &runtime,
2692 &token,
2693 &json!({
2694 "source_id": a_id.to_string(),
2695 "target_id": b_id.to_string(),
2696 "relation": "extends",
2697 }),
2698 )
2699 .await
2700 .expect("prepare link");
2701 let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
2702 .await
2703 .expect("seam call ok");
2704 assert!(matches!(
2705 outcome,
2706 crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2707 ));
2708
2709 {
2712 let mut writer = runtime.sql().writer().await.expect("writer");
2713 let affected = writer
2714 .execute(SqlStatement {
2715 sql: "UPDATE graph_edges SET deleted_at = ?1 \
2716 WHERE namespace = ?2 AND source_id = ?3 AND target_id = ?4 AND relation = ?5"
2717 .to_string(),
2718 params: vec![
2719 SqlValue::Integer(chrono::Utc::now().timestamp_micros()),
2720 SqlValue::Text("local".to_string()),
2721 SqlValue::Text(a_id.to_string()),
2722 SqlValue::Text(b_id.to_string()),
2723 SqlValue::Text("extends".to_string()),
2724 ],
2725 label: Some("test-soft-delete-edge".to_string()),
2726 })
2727 .await
2728 .expect("soft delete edge");
2729 assert_eq!(affected, 1, "soft-delete must touch exactly the seeded row");
2730 }
2731 let (_, _, _, deleted_at) =
2732 probe_edge_natural_key(&runtime, "local", a_id, b_id, "extends").await;
2733 assert!(
2734 deleted_at.is_some(),
2735 "row must be soft-deleted before the resurrect attempt"
2736 );
2737
2738 let plan_relink = prepare_link(
2741 &runtime,
2742 &token,
2743 &json!({
2744 "source_id": a_id.to_string(),
2745 "target_id": b_id.to_string(),
2746 "relation": "extends",
2747 "weight": 0.75,
2748 }),
2749 )
2750 .await
2751 .expect("prepare resurrecting link");
2752 let outcome_relink =
2753 crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan_relink])
2754 .await
2755 .expect("seam call ok");
2756 assert!(
2757 matches!(
2758 outcome_relink,
2759 crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2760 ),
2761 "re-linking a soft-deleted triple must resurrect it, not roll back: {outcome_relink:?}"
2762 );
2763 let (count, weight, _, deleted_at) =
2764 probe_edge_natural_key(&runtime, "local", a_id, b_id, "extends").await;
2765 assert_eq!(count, 1);
2766 assert_eq!(weight, Some(0.75));
2767 assert!(
2768 deleted_at.is_none(),
2769 "re-link must resurrect the soft-deleted row (deleted_at -> NULL)"
2770 );
2771 }
2772
2773 #[tokio::test]
2781 async fn atomic_delete_succeeds_when_vec_table_never_created() {
2782 let runtime = scratch_runtime();
2783 runtime.register_embedder(StubProvider);
2784 let token = runtime
2785 .authorize(Namespace::parse("local").expect("ns"))
2786 .expect("authorize");
2787
2788 let entity = khive_storage::Entity::new("local", "concept", "no-vec-table-entity");
2792 let entity_id = entity.id;
2793 runtime
2794 .entities(&token)
2795 .expect("entities store")
2796 .upsert_entity(entity)
2797 .await
2798 .expect("seed entity");
2799
2800 let mut note = khive_storage::note::Note::new("local", "observation", "no-vec-table-note");
2801 note.name = Some("no-vec-table-note".to_string());
2802 let note_id = note.id;
2803 runtime
2804 .notes(&token)
2805 .expect("notes store")
2806 .upsert_note(note)
2807 .await
2808 .expect("seed note");
2809
2810 for (id, kind) in [(entity_id, "entity"), (note_id, "note")] {
2811 let plan = prepare_delete(&runtime, &token, &json!({"id": id.to_string()}), None)
2812 .await
2813 .unwrap_or_else(|e| panic!("prepare delete ({kind}) must not fail: {e}"));
2814 let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
2815 .await
2816 .unwrap_or_else(|e| {
2817 panic!("atomic delete ({kind}) must not hit `no such table`: {e}")
2818 });
2819 assert!(
2820 matches!(
2821 outcome,
2822 crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2823 ),
2824 "expected a clean commit ({kind}): {outcome:?}"
2825 );
2826 }
2827
2828 assert!(
2829 runtime
2830 .get_entity_including_deleted(&token, entity_id)
2831 .await
2832 .expect("get entity")
2833 .expect("entity row still present (soft delete)")
2834 .deleted_at
2835 .is_some(),
2836 "entity must be soft-deleted"
2837 );
2838 assert!(
2839 runtime
2840 .get_note_including_deleted(&token, note_id)
2841 .await
2842 .expect("get note")
2843 .expect("note row still present (soft delete)")
2844 .deleted_at
2845 .is_some(),
2846 "note must be soft-deleted"
2847 );
2848 }
2849
2850 #[tokio::test]
2856 async fn atomic_hard_delete_purges_already_soft_deleted_entity_and_note() {
2857 let runtime = scratch_runtime();
2858 runtime.register_embedder(StubProvider);
2859 let token = runtime
2860 .authorize(Namespace::parse("local").expect("ns"))
2861 .expect("authorize");
2862
2863 let entity =
2864 khive_storage::Entity::new("local", "concept", "tombstoned-entity-hard-delete");
2865 let entity_id = entity.id;
2866 runtime
2867 .entities(&token)
2868 .expect("entities store")
2869 .upsert_entity(entity.clone())
2870 .await
2871 .expect("seed entity");
2872 runtime
2873 .reindex_entity(&token, &entity)
2874 .await
2875 .expect("seed index rows");
2876
2877 let mut note =
2878 khive_storage::note::Note::new("local", "observation", "tombstoned-note-hard-delete");
2879 note.name = Some("tombstoned-note-hard-delete".to_string());
2880 let note_id = note.id;
2881 runtime
2882 .notes(&token)
2883 .expect("notes store")
2884 .upsert_note(note.clone())
2885 .await
2886 .expect("seed note");
2887 runtime
2888 .reindex_note(&token, ¬e)
2889 .await
2890 .expect("seed index rows");
2891
2892 for id in [entity_id, note_id] {
2895 let plan = prepare_delete(&runtime, &token, &json!({"id": id.to_string()}), None)
2896 .await
2897 .expect("prepare soft delete");
2898 let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
2899 .await
2900 .expect("soft delete commit");
2901 assert!(matches!(
2902 outcome,
2903 crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2904 ));
2905 }
2906 assert!(
2907 runtime
2908 .get_entity_including_deleted(&token, entity_id)
2909 .await
2910 .expect("get entity")
2911 .expect("entity present")
2912 .deleted_at
2913 .is_some(),
2914 "entity must be soft-deleted before the hard-delete attempt"
2915 );
2916 assert!(
2917 runtime
2918 .get_note_including_deleted(&token, note_id)
2919 .await
2920 .expect("get note")
2921 .expect("note present")
2922 .deleted_at
2923 .is_some(),
2924 "note must be soft-deleted before the hard-delete attempt"
2925 );
2926
2927 for (id, kind) in [(entity_id, "entity"), (note_id, "note")] {
2929 let plan = prepare_delete(
2930 &runtime,
2931 &token,
2932 &json!({"id": id.to_string(), "hard": true}),
2933 None,
2934 )
2935 .await
2936 .unwrap_or_else(|e| {
2937 panic!(
2938 "prepare hard delete ({kind}) of an already-soft-deleted record \
2939 must resolve it: {e}"
2940 )
2941 });
2942 let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
2943 .await
2944 .unwrap_or_else(|e| panic!("hard delete ({kind}) commit failed: {e}"));
2945 assert!(
2946 matches!(
2947 outcome,
2948 crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2949 ),
2950 "expected a clean hard-delete commit ({kind}): {outcome:?}"
2951 );
2952 }
2953
2954 assert!(
2955 runtime
2956 .get_entity_including_deleted(&token, entity_id)
2957 .await
2958 .expect("get entity")
2959 .is_none(),
2960 "entity row must be fully purged after hard delete"
2961 );
2962 assert!(
2963 runtime
2964 .get_note_including_deleted(&token, note_id)
2965 .await
2966 .expect("get note")
2967 .is_none(),
2968 "note row must be fully purged after hard delete"
2969 );
2970 assert!(
2971 runtime
2972 .text(&token)
2973 .expect("text store")
2974 .get_document("local", entity_id)
2975 .await
2976 .expect("get_document")
2977 .is_none(),
2978 "entity FTS row must be purged after hard delete"
2979 );
2980 assert!(
2981 runtime
2982 .text_for_notes(&token)
2983 .expect("text store")
2984 .get_document("local", note_id)
2985 .await
2986 .expect("get_document")
2987 .is_none(),
2988 "note FTS row must be purged after hard delete"
2989 );
2990 let vec_store = runtime
2991 .vectors_for_model(&token, STUB_MODEL)
2992 .expect("vec store");
2993 assert_eq!(
2994 vec_store.count().await.expect("count after"),
2995 0,
2996 "vector rows for both records must be purged after hard delete"
2997 );
2998 }
2999
3000 async fn events_for_target(
3008 runtime: &KhiveRuntime,
3009 token: &NamespaceToken,
3010 target_id: Uuid,
3011 kind: EventKind,
3012 ) -> Vec<khive_storage::Event> {
3013 let event_store = runtime.events(token).expect("event store");
3014 let filter = khive_storage::EventFilter {
3015 kinds: vec![kind],
3016 ..Default::default()
3017 };
3018 let page = event_store
3019 .query_events(filter, khive_storage::types::PageRequest::default())
3020 .await
3021 .expect("query_events");
3022 page.items
3023 .into_iter()
3024 .filter(|e| e.target_id == Some(target_id))
3025 .collect()
3026 }
3027
3028 #[tokio::test]
3033 async fn atomic_update_entity_appends_entity_updated_event() {
3034 let runtime = scratch_runtime();
3035 let token = runtime
3036 .authorize(Namespace::parse("local").expect("ns"))
3037 .expect("authorize");
3038 let entity = khive_storage::Entity::new("local", "concept", "gap1-entity");
3039 let entity_id = entity.id;
3040 runtime
3041 .entities(&token)
3042 .expect("entities store")
3043 .upsert_entity(entity)
3044 .await
3045 .expect("seed entity");
3046
3047 let plan = prepare_update(
3048 &runtime,
3049 &token,
3050 &json!({"id": entity_id.to_string(), "name": "gap1-entity-renamed"}),
3051 None,
3052 )
3053 .await
3054 .expect("prepare update");
3055 let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
3056 .await
3057 .expect("seam call ok");
3058 assert!(matches!(
3059 outcome,
3060 crate::atomic_runner::AtomicRunOutcome::Committed { .. }
3061 ));
3062
3063 let events = events_for_target(&runtime, &token, entity_id, EventKind::EntityUpdated).await;
3064 assert_eq!(
3065 events.len(),
3066 1,
3067 "expected exactly one EntityUpdated event for {entity_id}"
3068 );
3069 assert_eq!(events[0].namespace, "local");
3070 assert_eq!(events[0].payload["id"], json!(entity_id.to_string()));
3071 assert_eq!(
3072 events[0].payload["changed_fields"],
3073 json!(["name"]),
3074 "changed_fields must name exactly the patched fields"
3075 );
3076 }
3077
3078 #[tokio::test]
3082 async fn atomic_delete_entity_appends_entity_deleted_event_soft_and_hard() {
3083 let runtime = scratch_runtime();
3084 let token = runtime
3085 .authorize(Namespace::parse("local").expect("ns"))
3086 .expect("authorize");
3087
3088 for hard in [false, true] {
3089 let entity =
3090 khive_storage::Entity::new("local", "concept", format!("gap1-entity-hard-{hard}"));
3091 let entity_id = entity.id;
3092 runtime
3093 .entities(&token)
3094 .expect("entities store")
3095 .upsert_entity(entity)
3096 .await
3097 .expect("seed entity");
3098
3099 let args = if hard {
3100 json!({"id": entity_id.to_string(), "hard": true})
3101 } else {
3102 json!({"id": entity_id.to_string()})
3103 };
3104 let plan = prepare_delete(&runtime, &token, &args, None)
3105 .await
3106 .unwrap_or_else(|e| panic!("prepare delete (hard={hard}): {e}"));
3107 let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
3108 .await
3109 .unwrap_or_else(|e| panic!("delete commit (hard={hard}): {e}"));
3110 assert!(
3111 matches!(
3112 outcome,
3113 crate::atomic_runner::AtomicRunOutcome::Committed { .. }
3114 ),
3115 "expected a clean delete commit (hard={hard}): {outcome:?}"
3116 );
3117
3118 let events =
3119 events_for_target(&runtime, &token, entity_id, EventKind::EntityDeleted).await;
3120 assert_eq!(
3121 events.len(),
3122 1,
3123 "expected exactly one EntityDeleted event for {entity_id} (hard={hard})"
3124 );
3125 assert_eq!(events[0].payload["hard"], json!(hard));
3126 }
3127 }
3128
3129 #[tokio::test]
3130 async fn atomic_hard_delete_emits_lineage_warning_in_commit_unit() {
3131 let runtime = scratch_runtime();
3132 let token = NamespaceToken::mint_authorized(
3133 Namespace::local(),
3134 crate::ActorRef::new("agent", "atomic-lineage-deleter"),
3135 );
3136 let doomed = khive_storage::Entity::new("local", "document", "atomic-doomed");
3137 let source = khive_storage::Entity::new("local", "artifact", "atomic-source");
3138 let doomed_id = doomed.id;
3139 runtime
3140 .entities(&token)
3141 .expect("entities store")
3142 .upsert_entity(doomed)
3143 .await
3144 .expect("seed doomed entity");
3145 runtime
3146 .entities(&token)
3147 .expect("entities store")
3148 .upsert_entity(source.clone())
3149 .await
3150 .expect("seed source entity");
3151 runtime
3152 .link(
3153 &token,
3154 source.id,
3155 doomed_id,
3156 EdgeRelation::DerivedFrom,
3157 1.0,
3158 None,
3159 )
3160 .await
3161 .expect("seed protected edge");
3162
3163 let plan = prepare_delete(
3164 &runtime,
3165 &token,
3166 &json!({"id": doomed_id.to_string(), "hard": true}),
3167 None,
3168 )
3169 .await
3170 .expect("prepare hard delete");
3171 let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
3172 .await
3173 .expect("delete commit");
3174 assert!(matches!(
3175 outcome,
3176 crate::atomic_runner::AtomicRunOutcome::Committed { .. }
3177 ));
3178
3179 let warnings = events_for_target(&runtime, &token, doomed_id, EventKind::Audit).await;
3180 assert_eq!(warnings.len(), 1);
3181 assert_eq!(warnings[0].actor, "agent:atomic-lineage-deleter");
3182 assert_eq!(warnings[0].payload["relation"], "derived_from");
3183 assert_eq!(warnings[0].payload["warning"], "provenance_loss");
3184 }
3185
3186 #[tokio::test]
3190 async fn atomic_delete_note_appends_note_deleted_event_soft_and_hard() {
3191 let runtime = scratch_runtime();
3192 let token = runtime
3193 .authorize(Namespace::parse("local").expect("ns"))
3194 .expect("authorize");
3195
3196 for hard in [false, true] {
3197 let mut note = khive_storage::note::Note::new(
3198 "local",
3199 "observation",
3200 format!("gap1-note-content-hard-{hard}"),
3201 );
3202 note.name = Some(format!("gap1-note-hard-{hard}"));
3203 let note_id = note.id;
3204 runtime
3205 .notes(&token)
3206 .expect("notes store")
3207 .upsert_note(note)
3208 .await
3209 .expect("seed note");
3210
3211 let args = if hard {
3212 json!({"id": note_id.to_string(), "hard": true})
3213 } else {
3214 json!({"id": note_id.to_string()})
3215 };
3216 let plan = prepare_delete(&runtime, &token, &args, None)
3217 .await
3218 .unwrap_or_else(|e| panic!("prepare delete (hard={hard}): {e}"));
3219 let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
3220 .await
3221 .unwrap_or_else(|e| panic!("delete commit (hard={hard}): {e}"));
3222 assert!(
3223 matches!(
3224 outcome,
3225 crate::atomic_runner::AtomicRunOutcome::Committed { .. }
3226 ),
3227 "expected a clean delete commit (hard={hard}): {outcome:?}"
3228 );
3229
3230 let events = events_for_target(&runtime, &token, note_id, EventKind::NoteDeleted).await;
3231 assert_eq!(
3232 events.len(),
3233 1,
3234 "expected exactly one NoteDeleted event for {note_id} (hard={hard})"
3235 );
3236 assert_eq!(events[0].payload["hard"], json!(hard));
3237 }
3238 }
3239
3240 #[tokio::test]
3247 async fn atomic_update_edge_patches_weight_and_appends_edge_updated_event() {
3248 let runtime = scratch_runtime();
3249 let token = runtime
3250 .authorize(Namespace::parse("local").expect("ns"))
3251 .expect("authorize");
3252 let entities = runtime.entities(&token).expect("entities store");
3253 let a = khive_storage::Entity::new("local", "concept", "GapEdgeA");
3254 let b = khive_storage::Entity::new("local", "concept", "GapEdgeB");
3255 let (a_id, b_id) = (a.id, b.id);
3256 entities.upsert_entity(a).await.expect("seed a");
3257 entities.upsert_entity(b).await.expect("seed b");
3258
3259 let edge = runtime
3260 .link(&token, a_id, b_id, EdgeRelation::Extends, 0.4, None)
3261 .await
3262 .expect("seed edge");
3263 let edge_id = Uuid::from(edge.id);
3264
3265 let plan = prepare_update(
3266 &runtime,
3267 &token,
3268 &json!({"id": edge_id.to_string(), "weight": 0.75}),
3269 None,
3270 )
3271 .await
3272 .expect("prepare update edge");
3273 let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
3274 .await
3275 .expect("seam call ok");
3276 assert!(
3277 matches!(
3278 outcome,
3279 crate::atomic_runner::AtomicRunOutcome::Committed { .. }
3280 ),
3281 "expected a clean edge update commit: {outcome:?}"
3282 );
3283
3284 let updated = runtime
3285 .get_edge(&token, edge_id)
3286 .await
3287 .expect("get_edge")
3288 .expect("edge still present");
3289 assert_eq!(updated.weight, 0.75, "weight patch must persist");
3290 assert_eq!(updated.relation, EdgeRelation::Extends);
3291
3292 let events = events_for_target(&runtime, &token, edge_id, EventKind::EdgeUpdated).await;
3293 assert_eq!(
3294 events.len(),
3295 1,
3296 "expected exactly one EdgeUpdated event for {edge_id}"
3297 );
3298 assert_eq!(
3299 events[0].payload["changed_fields"],
3300 json!(["weight"]),
3301 "changed_fields must name exactly the patched field"
3302 );
3303 }
3304
3305 #[tokio::test]
3309 async fn atomic_update_edge_rejects_reserved_secret_gate_property() {
3310 let runtime = scratch_runtime();
3311 let token = runtime
3312 .authorize(Namespace::parse("local").expect("ns"))
3313 .expect("authorize");
3314 let entities = runtime.entities(&token).expect("entities store");
3315 let a = khive_storage::Entity::new("local", "concept", "ReservedEdgeA");
3316 let b = khive_storage::Entity::new("local", "concept", "ReservedEdgeB");
3317 let (a_id, b_id) = (a.id, b.id);
3318 entities.upsert_entity(a).await.expect("seed a");
3319 entities.upsert_entity(b).await.expect("seed b");
3320
3321 let edge = runtime
3322 .link(&token, a_id, b_id, EdgeRelation::Extends, 0.4, None)
3323 .await
3324 .expect("seed edge");
3325 let edge_id = Uuid::from(edge.id);
3326
3327 let err = prepare_update(
3328 &runtime,
3329 &token,
3330 &json!({
3331 "id": edge_id.to_string(),
3332 "properties": {"khive:secret_gate": "exempted:content-sha256-manifest-v1"},
3333 }),
3334 None,
3335 )
3336 .await
3337 .expect_err("a caller-supplied reserved key on edge metadata must be rejected");
3338 assert!(
3339 matches!(err, RuntimeError::InvalidInput(ref msg) if msg.contains("khive:secret_gate") && msg.contains("runtime-owned")),
3340 "expected a reservation rejection, got: {err:?}"
3341 );
3342
3343 let unchanged = runtime
3344 .get_edge(&token, edge_id)
3345 .await
3346 .expect("get_edge")
3347 .expect("edge still present");
3348 assert!(
3349 unchanged.metadata.is_none(),
3350 "rejected edge update must leave metadata untouched"
3351 );
3352 }
3353
3354 #[tokio::test]
3364 async fn atomic_update_edge_symmetric_conflict_absorbs_into_surviving_row() {
3365 let runtime = scratch_runtime();
3366 let token = runtime
3367 .authorize(Namespace::parse("local").expect("ns"))
3368 .expect("authorize");
3369 let entities = runtime.entities(&token).expect("entities store");
3370 let a = khive_storage::Entity::new("local", "concept", "GapEdgeSymA");
3371 let b = khive_storage::Entity::new("local", "concept", "GapEdgeSymB");
3372 let (a_id, b_id) = (a.id, b.id);
3373 entities.upsert_entity(a).await.expect("seed a");
3374 entities.upsert_entity(b).await.expect("seed b");
3375
3376 let requested_edge = runtime
3378 .link(&token, a_id, b_id, EdgeRelation::Extends, 0.2, None)
3379 .await
3380 .expect("seed requested edge");
3381 let requested_id = Uuid::from(requested_edge.id);
3382
3383 let canonical_edge = runtime
3386 .link(&token, a_id, b_id, EdgeRelation::CompetesWith, 0.6, None)
3387 .await
3388 .expect("seed canonical edge");
3389 let canonical_id = Uuid::from(canonical_edge.id);
3390 assert_ne!(requested_id, canonical_id);
3391
3392 let plan = prepare_update(
3393 &runtime,
3394 &token,
3395 &json!({"id": requested_id.to_string(), "relation": "competes_with", "weight": 0.9}),
3396 None,
3397 )
3398 .await
3399 .expect("prepare update edge (symmetric conflict)");
3400 let (canon_src, canon_tgt) =
3407 canonical_edge_endpoints(EdgeRelation::CompetesWith, a_id, b_id);
3408 match &plan {
3409 AtomicOpPlan::Update(p) => {
3410 assert_eq!(p.target_id, requested_id);
3411 let key = p
3412 .edge_natural_key
3413 .as_ref()
3414 .expect("symmetric edge update must carry edge_natural_key");
3415 assert_eq!(key.canon_source_id, canon_src);
3416 assert_eq!(key.canon_target_id, canon_tgt);
3417 assert_eq!(key.relation, EdgeRelation::CompetesWith);
3418 }
3419 other => panic!("expected an Update plan, got {other:?}"),
3420 }
3421
3422 let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
3423 .await
3424 .expect("seam call ok");
3425 assert!(
3426 matches!(
3427 outcome,
3428 crate::atomic_runner::AtomicRunOutcome::Committed { .. }
3429 ),
3430 "expected a clean symmetric-conflict-absorption commit: {outcome:?}"
3431 );
3432
3433 let requested_after = runtime
3435 .get_edge_including_deleted(&token, requested_id)
3436 .await
3437 .expect("get_edge_including_deleted");
3438 assert!(
3439 requested_after.is_none(),
3440 "the non-canonical requested row must be deleted, not just tombstoned"
3441 );
3442
3443 let surviving = runtime
3447 .get_edge(&token, canonical_id)
3448 .await
3449 .expect("get_edge")
3450 .expect("surviving canonical row must remain");
3451 assert_eq!(
3452 surviving.weight, 0.6,
3453 "survivor weight must not be overwritten by the discarded edge's patch"
3454 );
3455 assert_eq!(surviving.relation, EdgeRelation::CompetesWith);
3456
3457 let events =
3461 events_for_target(&runtime, &token, requested_id, EventKind::EdgeUpdated).await;
3462 assert_eq!(events.len(), 1);
3463 }
3464
3465 #[tokio::test]
3478 async fn atomic_entity_update_plan_stale_revision_rolls_back_unit() {
3479 let runtime = scratch_runtime();
3480 let token = runtime
3481 .authorize(Namespace::parse("local").expect("ns"))
3482 .expect("authorize");
3483 let entity = runtime
3484 .create_entity(
3485 &token,
3486 "concept",
3487 None,
3488 "StaleEntityPlanTarget",
3489 None,
3490 Some(json!({"a": 0})),
3491 vec![],
3492 )
3493 .await
3494 .expect("seed entity");
3495 let id = entity.id;
3496
3497 let plan = prepare_update(
3500 &runtime,
3501 &token,
3502 &json!({"id": id.to_string(), "description": "from the stale plan"}),
3503 None,
3504 )
3505 .await
3506 .expect("prepare update entity plan");
3507
3508 let (planned_replacement, plan_target_id, plan_expected, plan_expected_deleted) = {
3515 let statements = match &plan {
3516 AtomicOpPlan::Update(p) => p.statements.clone(),
3517 other => panic!("expected an Update plan, got {other:?}"),
3518 };
3519 let cas = statements
3524 .iter()
3525 .find(|s| s.statement.label.as_deref() == Some("entity-replace-if-unchanged"))
3526 .expect("the plan must carry the guarded entity replacement");
3527 let read = |i: usize| match &cas.statement.params[i] {
3528 SqlValue::Integer(v) => *v,
3529 other => panic!("param {i} must be an integer revision, got {other:?}"),
3530 };
3531 let read_marker = |i: usize| match &cas.statement.params[i] {
3532 SqlValue::Null => None,
3533 SqlValue::Integer(v) => Some(*v),
3534 other => panic!("param {i} must be a deletion marker, got {other:?}"),
3535 };
3536 let read_text = |i: usize| match &cas.statement.params[i] {
3537 SqlValue::Text(v) => v.clone(),
3538 other => panic!("param {i} must be a text id, got {other:?}"),
3539 };
3540 (read(7), read_text(11), read(12), read_marker(13))
3541 };
3542 assert_eq!(
3548 plan_target_id,
3549 id.to_string(),
3550 "fixture premise: the plan's `?12` must be the row under test, otherwise \
3551 `id = ?12` refuses on identity and the rollback stops being attributable to \
3552 the expected-revision guard"
3553 );
3554
3555 runtime
3558 .update_entity(
3559 &token,
3560 id,
3561 crate::curation::EntityPatch {
3562 name: Some("ConcurrentWriterWon".to_string()),
3563 ..Default::default()
3564 },
3565 )
3566 .await
3567 .expect("concurrent writer update");
3568
3569 let stored_pinned = planned_replacement - 1;
3580 assert_ne!(
3581 stored_pinned, plan_expected,
3582 "fixture premise: the pinned revision must differ from the plan's expected \
3583 revision, otherwise `updated_at = ?13` would MATCH and nothing would refuse \
3584 the plan"
3585 );
3586 {
3587 let mut writer = runtime.sql().writer().await.expect("writer");
3588 let affected = writer
3589 .execute(SqlStatement {
3590 sql: "UPDATE entities SET updated_at = ?1 WHERE id = ?2".to_string(),
3591 params: vec![
3592 SqlValue::Integer(stored_pinned),
3593 SqlValue::Text(id.to_string()),
3594 ],
3595 label: Some("test-pin-stored-revision".to_string()),
3596 })
3597 .await
3598 .expect("pin the stored revision");
3599 assert_eq!(affected, 1, "the pin must touch exactly the seeded row");
3600 }
3601 assert!(
3602 planned_replacement > stored_pinned,
3603 "fixture premise: the plan's replacement must still strictly advance past the \
3604 stored revision, otherwise `?8 > updated_at` would refuse and this stops being \
3605 a test of the expected-revision guard"
3606 );
3607 {
3613 let stored = runtime
3614 .get_entity_including_deleted(&token, id)
3615 .await
3616 .expect("read the stored row")
3617 .expect("the seeded row is present before the plan runs");
3618 assert_eq!(
3619 stored.updated_at, stored_pinned,
3620 "fixture premise: the pin must be what the guard reads, so the stored \
3621 revision is the pinned value and nothing re-advanced it"
3622 );
3623 assert_eq!(
3624 stored.deleted_at, plan_expected_deleted,
3625 "fixture premise: the stored deletion marker must MATCH the plan's `?14`, \
3626 otherwise `deleted_at IS ?14` refuses too and this stops being a test of \
3627 the expected-revision guard alone"
3628 );
3629 }
3630
3631 let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
3632 .await
3633 .expect("the seam call itself must not error; the unit rolls back cleanly");
3634 match outcome {
3635 crate::atomic_runner::AtomicRunOutcome::RolledBack {
3636 failed_op_index,
3637 failure,
3638 } => {
3639 assert_eq!(
3640 failed_op_index, 0,
3641 "the sole op's guard must be the one that fails"
3642 );
3643 assert_eq!(
3650 failure,
3651 crate::atomic_runner::AtomicOpFailure::GuardFailed {
3652 statement_label: Some("entity-replace-if-unchanged".to_string()),
3653 expected: crate::atomic_plan::AffectedRowGuard::exactly(1),
3654 observed: 0,
3655 },
3656 "the guarded entity replacement must be the statement whose guard refused"
3657 );
3658 }
3659 other => panic!(
3660 "a stale entity plan must roll back, not silently overwrite the concurrent \
3661 writer's change: {other:?}"
3662 ),
3663 }
3664
3665 let after = runtime.get_entity(&token, id).await.expect("get_entity");
3666 assert_eq!(
3667 after.name, "ConcurrentWriterWon",
3668 "the concurrent writer's committed name must survive the rolled-back stale plan"
3669 );
3670 assert_eq!(
3671 after.description, None,
3672 "the stale plan's description patch must NOT have landed"
3673 );
3674 }
3675
3676 #[tokio::test]
3681 async fn atomic_edge_update_plan_stale_revision_rolls_back_unit() {
3682 let runtime = scratch_runtime();
3683 let token = runtime
3684 .authorize(Namespace::parse("local").expect("ns"))
3685 .expect("authorize");
3686 let entities = runtime.entities(&token).expect("entities store");
3687 let a = khive_storage::Entity::new("local", "concept", "StaleEdgePlanA");
3688 let b = khive_storage::Entity::new("local", "concept", "StaleEdgePlanB");
3689 let (a_id, b_id) = (a.id, b.id);
3690 entities.upsert_entity(a).await.expect("seed a");
3691 entities.upsert_entity(b).await.expect("seed b");
3692
3693 let edge = runtime
3694 .link(&token, a_id, b_id, EdgeRelation::Extends, 0.2, None)
3695 .await
3696 .expect("seed edge");
3697 let edge_id = Uuid::from(edge.id);
3698
3699 let plan = prepare_update(
3702 &runtime,
3703 &token,
3704 &json!({"id": edge_id.to_string(), "properties": {"note": "from the stale plan"}}),
3705 None,
3706 )
3707 .await
3708 .expect("prepare update edge plan");
3709
3710 let (planned_replacement, plan_target_id, plan_expected, plan_expected_deleted) = {
3717 let statements = match &plan {
3718 AtomicOpPlan::Update(p) => p.statements.clone(),
3719 other => panic!("expected an Update plan, got {other:?}"),
3720 };
3721 let cas = statements
3725 .iter()
3726 .find(|s| s.statement.label.as_deref() == Some("edge-replace-if-unchanged"))
3727 .expect("the plan must carry the guarded edge replacement");
3728 let read = |i: usize| match &cas.statement.params[i] {
3729 SqlValue::Integer(v) => *v,
3730 other => panic!("param {i} must be an integer revision, got {other:?}"),
3731 };
3732 let read_marker = |i: usize| match &cas.statement.params[i] {
3733 SqlValue::Null => None,
3734 SqlValue::Integer(v) => Some(*v),
3735 other => panic!("param {i} must be a deletion marker, got {other:?}"),
3736 };
3737 let read_text = |i: usize| match &cas.statement.params[i] {
3738 SqlValue::Text(v) => v.clone(),
3739 other => panic!("param {i} must be a text id, got {other:?}"),
3740 };
3741 (read(5), read_text(9), read(10), read_marker(11))
3742 };
3743 assert_eq!(
3747 plan_target_id,
3748 edge_id.to_string(),
3749 "fixture premise: the plan's `?10` must be the edge under test, otherwise \
3750 `id = ?10` refuses on identity and the rollback stops being attributable to \
3751 the expected-revision guard"
3752 );
3753
3754 runtime
3757 .update_edge(
3758 &token,
3759 edge_id,
3760 crate::curation::EdgePatch {
3761 weight: Some(0.75),
3762 ..Default::default()
3763 },
3764 )
3765 .await
3766 .expect("concurrent writer update");
3767
3768 let stored_pinned = planned_replacement - 1;
3776 assert_ne!(
3777 stored_pinned, plan_expected,
3778 "fixture premise: the pinned revision must differ from the plan's expected \
3779 revision, otherwise `updated_at = ?11` would MATCH and nothing would refuse \
3780 the plan"
3781 );
3782 {
3783 let mut writer = runtime.sql().writer().await.expect("writer");
3784 let affected = writer
3785 .execute(SqlStatement {
3786 sql: "UPDATE graph_edges SET updated_at = ?1 WHERE id = ?2".to_string(),
3787 params: vec![
3788 SqlValue::Integer(stored_pinned),
3789 SqlValue::Text(edge_id.to_string()),
3790 ],
3791 label: Some("test-pin-stored-revision".to_string()),
3792 })
3793 .await
3794 .expect("pin the stored revision");
3795 assert_eq!(affected, 1, "the pin must touch exactly the seeded edge");
3796 }
3797 assert!(
3798 planned_replacement > stored_pinned,
3799 "fixture premise: the plan's replacement must still strictly advance past the \
3800 stored revision, otherwise `?6 > updated_at` would refuse and this stops being \
3801 a test of the expected-revision guard"
3802 );
3803 {
3807 let stored = runtime
3808 .get_edge_including_deleted(&token, edge_id)
3809 .await
3810 .expect("read the stored edge")
3811 .expect("the seeded edge is present before the plan runs");
3812 assert_eq!(
3813 stored.updated_at.timestamp_micros(),
3814 stored_pinned,
3815 "fixture premise: the pin must be what the guard reads, so the stored \
3816 revision is the pinned value and nothing re-advanced it"
3817 );
3818 assert_eq!(
3819 stored.deleted_at.map(|d| d.timestamp_micros()),
3820 plan_expected_deleted,
3821 "fixture premise: the stored deletion marker must MATCH the plan's `?12`, \
3822 otherwise `deleted_at IS ?12` refuses too and this stops being a test of \
3823 the expected-revision guard alone"
3824 );
3825 }
3826
3827 let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
3828 .await
3829 .expect("the seam call itself must not error; the unit rolls back cleanly");
3830 match outcome {
3831 crate::atomic_runner::AtomicRunOutcome::RolledBack {
3832 failed_op_index,
3833 failure,
3834 } => {
3835 assert_eq!(
3836 failed_op_index, 0,
3837 "the sole op's guard must be the one that fails"
3838 );
3839 assert_eq!(
3841 failure,
3842 crate::atomic_runner::AtomicOpFailure::GuardFailed {
3843 statement_label: Some("edge-replace-if-unchanged".to_string()),
3844 expected: crate::atomic_plan::AffectedRowGuard::exactly(1),
3845 observed: 0,
3846 },
3847 "the guarded edge replacement must be the statement whose guard refused"
3848 );
3849 }
3850 other => panic!(
3851 "a stale edge plan must roll back, not silently overwrite the concurrent \
3852 writer's change: {other:?}"
3853 ),
3854 }
3855
3856 let after = runtime
3857 .get_edge(&token, edge_id)
3858 .await
3859 .expect("get_edge")
3860 .expect("edge still exists");
3861 assert!(
3862 (after.weight - 0.75).abs() < 0.001,
3863 "the concurrent writer's committed weight must survive the rolled-back stale plan: {after:?}"
3864 );
3865 assert!(
3866 after.metadata.is_none(),
3867 "the stale plan's properties patch must NOT have landed: {after:?}"
3868 );
3869 }
3870
3871 #[tokio::test]
3876 async fn atomic_update_edge_symmetric_conflict_does_not_resurrect_tombstoned_survivor() {
3877 let runtime = scratch_runtime();
3878 let token = runtime
3879 .authorize(Namespace::parse("local").expect("ns"))
3880 .expect("authorize");
3881 let entities = runtime.entities(&token).expect("entities store");
3882 let a = khive_storage::Entity::new("local", "concept", "GapEdgeSymTombA");
3883 let b = khive_storage::Entity::new("local", "concept", "GapEdgeSymTombB");
3884 let (a_id, b_id) = (a.id, b.id);
3885 entities.upsert_entity(a).await.expect("seed a");
3886 entities.upsert_entity(b).await.expect("seed b");
3887
3888 let requested_edge = runtime
3889 .link(&token, a_id, b_id, EdgeRelation::Extends, 0.2, None)
3890 .await
3891 .expect("seed requested edge");
3892 let requested_id = Uuid::from(requested_edge.id);
3893
3894 let canonical_edge = runtime
3895 .link(&token, a_id, b_id, EdgeRelation::CompetesWith, 0.6, None)
3896 .await
3897 .expect("seed canonical edge");
3898 let canonical_id = Uuid::from(canonical_edge.id);
3899 runtime
3900 .delete_edge(&token, canonical_id, false)
3901 .await
3902 .expect("soft-delete canonical edge");
3903
3904 let plan = prepare_update(
3905 &runtime,
3906 &token,
3907 &json!({"id": requested_id.to_string(), "relation": "competes_with", "weight": 0.9}),
3908 None,
3909 )
3910 .await
3911 .expect("prepare update edge (symmetric conflict over tombstone)");
3912
3913 let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
3914 .await
3915 .expect("seam call ok");
3916 assert!(
3917 matches!(
3918 outcome,
3919 crate::atomic_runner::AtomicRunOutcome::Committed { .. }
3920 ),
3921 "expected a clean symmetric-conflict-absorption commit: {outcome:?}"
3922 );
3923
3924 let requested_after = runtime
3925 .get_edge_including_deleted(&token, requested_id)
3926 .await
3927 .expect("get_edge_including_deleted");
3928 assert!(
3929 requested_after.is_none(),
3930 "the non-canonical requested row must be deleted, not just tombstoned"
3931 );
3932
3933 let canonical_after = runtime
3934 .get_edge(&token, canonical_id)
3935 .await
3936 .expect("get_edge");
3937 assert!(
3938 canonical_after.is_none(),
3939 "a tombstoned survivor must not be resurrected by a conflicting update"
3940 );
3941 }
3942
3943 #[tokio::test]
3955 async fn atomic_update_edge_symmetric_same_unit_delete_race_aborts_the_unit() {
3956 let runtime = scratch_runtime();
3957 let token = runtime
3958 .authorize(Namespace::parse("local").expect("ns"))
3959 .expect("authorize");
3960 let entities = runtime.entities(&token).expect("entities store");
3961 let a = khive_storage::Entity::new("local", "concept", "GapEdgeRaceA");
3962 let b = khive_storage::Entity::new("local", "concept", "GapEdgeRaceB");
3963 let (a_id, b_id) = (a.id, b.id);
3964 entities.upsert_entity(a).await.expect("seed a");
3965 entities.upsert_entity(b).await.expect("seed b");
3966
3967 let requested_edge = runtime
3969 .link(&token, a_id, b_id, EdgeRelation::Extends, 0.2, None)
3970 .await
3971 .expect("seed requested edge");
3972 let requested_id = Uuid::from(requested_edge.id);
3973
3974 let canonical_edge = runtime
3977 .link(&token, a_id, b_id, EdgeRelation::CompetesWith, 0.6, None)
3978 .await
3979 .expect("seed canonical edge");
3980 let canonical_id = Uuid::from(canonical_edge.id);
3981
3982 let delete_plan = prepare_delete(
3983 &runtime,
3984 &token,
3985 &json!({"id": requested_id.to_string(), "hard": true}),
3986 None,
3987 )
3988 .await
3989 .expect("prepare delete edge");
3990 let update_plan = prepare_update(
3991 &runtime,
3992 &token,
3993 &json!({"id": requested_id.to_string(), "relation": "competes_with", "weight": 0.9}),
3994 None,
3995 )
3996 .await
3997 .expect("prepare update edge (both prepares run before either commits)");
3998
3999 let outcome = crate::atomic_runner::run_atomic_unit(
4000 runtime.sql().as_ref(),
4001 vec![delete_plan, update_plan],
4002 )
4003 .await
4004 .expect("the seam call itself must not error — the unit rolls back cleanly");
4005 match outcome {
4006 crate::atomic_runner::AtomicRunOutcome::RolledBack {
4007 failed_op_index, ..
4008 } => {
4009 assert_eq!(
4010 failed_op_index, 1,
4011 "op 1 (the update) must be the one whose guard fails"
4012 );
4013 }
4014 other => panic!("expected the whole unit to roll back, got {other:?}"),
4015 }
4016
4017 let requested_after = runtime
4019 .get_edge(&token, requested_id)
4020 .await
4021 .expect("get_edge");
4022 assert!(
4023 requested_after.is_some(),
4024 "delete(X) must have rolled back along with the failed update"
4025 );
4026 let canonical_after = runtime
4028 .get_edge(&token, canonical_id)
4029 .await
4030 .expect("get_edge")
4031 .expect("canonical row must still be present");
4032 assert_eq!(
4033 canonical_after.weight, 0.6,
4034 "the pre-existing canonical row must never have been touched by the aborted update"
4035 );
4036 }
4037
4038 #[tokio::test]
4049 async fn atomic_update_edge_symmetric_absorption_plan_stale_revision_rolls_back_unit() {
4050 let runtime = scratch_runtime();
4051 let token = runtime
4052 .authorize(Namespace::parse("local").expect("ns"))
4053 .expect("authorize");
4054 let entities = runtime.entities(&token).expect("entities store");
4055 let a = khive_storage::Entity::new("local", "concept", "StaleAbsorbA");
4056 let b = khive_storage::Entity::new("local", "concept", "StaleAbsorbB");
4057 let (a_id, b_id) = (a.id, b.id);
4058 entities.upsert_entity(a).await.expect("seed a");
4059 entities.upsert_entity(b).await.expect("seed b");
4060
4061 let canonical_edge = runtime
4063 .link(&token, a_id, b_id, EdgeRelation::CompetesWith, 0.6, None)
4064 .await
4065 .expect("seed canonical edge");
4066 let canonical_id = Uuid::from(canonical_edge.id);
4067
4068 let requested_edge = runtime
4070 .link(&token, a_id, b_id, EdgeRelation::Extends, 0.2, None)
4071 .await
4072 .expect("seed requested edge");
4073 let requested_id = Uuid::from(requested_edge.id);
4074
4075 let plan = prepare_update(
4078 &runtime,
4079 &token,
4080 &json!({"id": requested_id.to_string(), "relation": "competes_with", "weight": 0.9}),
4081 None,
4082 )
4083 .await
4084 .expect("prepare update edge (symmetric absorption)");
4085
4086 let concurrent = runtime
4091 .update_edge(
4092 &token,
4093 requested_id,
4094 crate::curation::EdgePatch {
4095 weight: Some(0.77),
4096 ..Default::default()
4097 },
4098 )
4099 .await
4100 .expect("concurrent writer update");
4101 assert!((concurrent.weight - 0.77).abs() < 1e-9);
4102
4103 let (absorb_replacement, absorb_expected, absorb_expected_deleted, absorb_ns, absorb_id) = {
4113 let statements = match &plan {
4114 AtomicOpPlan::Update(p) => p.statements.clone(),
4115 other => panic!("expected an Update plan, got {other:?}"),
4116 };
4117 let s = statements
4118 .iter()
4119 .find(|st| {
4120 st.statement.label.as_deref() == Some("edge-symmetric-absorb-or-update-inplace")
4121 })
4122 .expect("the plan must carry the guarded symmetric in-place absorb");
4123 let int = |i: usize| match &s.statement.params[i] {
4124 SqlValue::Integer(v) => *v,
4125 other => panic!("param {i} must be an integer revision, got {other:?}"),
4126 };
4127 let marker = |i: usize| match &s.statement.params[i] {
4128 SqlValue::Null => None,
4129 SqlValue::Integer(v) => Some(*v),
4130 other => panic!("param {i} must be a deletion marker, got {other:?}"),
4131 };
4132 let txt = |i: usize| match &s.statement.params[i] {
4133 SqlValue::Text(v) => v.clone(),
4134 other => panic!("param {i} must be text, got {other:?}"),
4135 };
4136 (int(6), int(9), marker(10), txt(0), txt(1))
4137 };
4138 let stored_pinned = absorb_replacement - 1;
4139 assert_ne!(
4140 stored_pinned, absorb_expected,
4141 "fixture premise: the pinned revision must differ from the plan's `?10`, otherwise \
4142 `updated_at = ?10` would MATCH and nothing would refuse the in-place arm (and the \
4143 guarded delete's `updated_at = ?6`, bound to the same value, would MATCH too and \
4144 fire, leaving `changes() = 1` and selecting the absorbed arm instead)"
4145 );
4146 {
4147 let mut writer = runtime.sql().writer().await.expect("writer");
4148 let affected = writer
4149 .execute(SqlStatement {
4150 sql: "UPDATE graph_edges SET updated_at = ?1 WHERE id = ?2".to_string(),
4151 params: vec![
4152 SqlValue::Integer(stored_pinned),
4153 SqlValue::Text(requested_id.to_string()),
4154 ],
4155 label: Some("test-pin-stored-revision".to_string()),
4156 })
4157 .await
4158 .expect("pin the stored revision");
4159 assert_eq!(affected, 1, "the pin must touch exactly the requested edge");
4160 }
4161 assert!(
4162 absorb_replacement > stored_pinned,
4163 "fixture premise: the plan's `?7` must still strictly advance past the stored \
4164 revision, otherwise `?7 > updated_at` refuses too and the refusal stops being \
4165 attributable to `updated_at = ?10`"
4166 );
4167
4168 {
4192 let statements = match &plan {
4193 AtomicOpPlan::Update(p) => p.statements.clone(),
4194 other => panic!("expected an Update plan, got {other:?}"),
4195 };
4196 let del = statements
4198 .iter()
4199 .find(|s| s.statement.label.as_deref() == Some("edge-symmetric-delete-if-conflict"))
4200 .expect("the plan must carry the guarded symmetric delete");
4201 let text = |i: usize| match &del.statement.params[i] {
4202 SqlValue::Text(v) => v.clone(),
4203 other => panic!("param {i} must be text, got {other:?}"),
4204 };
4205 let plan_expected_updated = match &del.statement.params[5] {
4206 SqlValue::Integer(v) => *v,
4207 other => panic!("param 5 must be the expected revision, got {other:?}"),
4208 };
4209 let plan_expected_deleted = match &del.statement.params[6] {
4210 SqlValue::Null => None,
4211 SqlValue::Integer(v) => Some(*v),
4212 other => panic!("param 6 must be a deletion marker, got {other:?}"),
4213 };
4214
4215 assert_eq!(
4223 text(0),
4224 "local",
4225 "fixture premise: the delete's `?1` must be the namespace the row lives in, \
4226 otherwise `namespace = ?1` refuses on its own"
4227 );
4228 assert_eq!(
4229 text(1),
4230 requested_id.to_string(),
4231 "fixture premise: the delete's `?2` must be the edge under test, otherwise \
4232 `id = ?2` refuses on identity and the delete never attempted the requested row"
4233 );
4234
4235 let requested_now = runtime
4236 .get_edge_including_deleted(&token, requested_id)
4237 .await
4238 .expect("read the requested edge")
4239 .expect("the requested edge is present before the plan runs");
4240 assert_ne!(
4241 requested_now.updated_at.timestamp_micros(),
4242 plan_expected_updated,
4243 "fixture premise: the concurrent writer must actually have moved the \
4244 revision past the plan's `?6`, otherwise nothing refuses the delete"
4245 );
4246 assert_eq!(
4247 requested_now.deleted_at.map(|d| d.timestamp_micros()),
4248 plan_expected_deleted,
4249 "fixture premise: the stored deletion marker must MATCH the plan's `?7`, \
4250 otherwise `deleted_at IS ?7` refuses too and the refusal is not \
4251 attributable to the revision guard"
4252 );
4253
4254 assert_ne!(
4263 canonical_id, requested_id,
4264 "fixture premise: the survivor must be a DIFFERENT row, since the EXISTS \
4265 arm excludes the requested id"
4266 );
4267 let survivors = {
4268 let mut reader = runtime.sql().reader().await.expect("sql reader");
4269 reader
4270 .query_scalar(SqlStatement {
4271 sql: "SELECT count(*) FROM graph_edges \
4272 WHERE namespace = ?1 AND source_id = ?3 AND target_id = ?4 \
4273 AND relation = ?5 AND id != ?2"
4274 .to_string(),
4275 params: del.statement.params[0..5].to_vec(),
4276 label: Some("test-survivor-exists-premise".to_string()),
4277 })
4278 .await
4279 .expect("run the plan's own EXISTS predicate")
4280 };
4281 let survivors = match survivors {
4282 Some(SqlValue::Integer(n)) => n,
4283 other => panic!("count(*) must come back as an integer, got {other:?}"),
4284 };
4285 assert_eq!(
4286 survivors,
4287 1,
4288 "fixture premise: exactly one survivor must satisfy the plan's own EXISTS \
4289 predicate (namespace {}, source {}, target {}, relation {}, id != {}), \
4290 otherwise the delete refuses on the survivor arm and the refusal is not \
4291 attributable to the revision guard",
4292 text(0),
4293 text(2),
4294 text(3),
4295 text(4),
4296 text(1),
4297 );
4298 }
4299
4300 assert_eq!(
4304 absorb_ns, "local",
4305 "fixture premise: the plan's `?1` must be the namespace the row lives in, \
4306 otherwise the outer `namespace = ?1` refuses on its own"
4307 );
4308 assert_eq!(
4309 absorb_id,
4310 requested_id.to_string(),
4311 "fixture premise: the plan's `?2` must be the edge under test, otherwise the \
4312 in-place arm's `id = ?2` refuses on identity"
4313 );
4314 {
4315 let stored = runtime
4316 .get_edge_including_deleted(&token, requested_id)
4317 .await
4318 .expect("read the requested edge")
4319 .expect("the requested edge is present before the plan runs");
4320 assert_eq!(
4321 stored.updated_at.timestamp_micros(),
4322 stored_pinned,
4323 "fixture premise: the pin must be what the guard reads at DML time, so the \
4324 stored revision is the pinned value and nothing re-advanced it"
4325 );
4326 assert_eq!(
4327 stored.deleted_at.map(|d| d.timestamp_micros()),
4328 absorb_expected_deleted,
4329 "fixture premise: the stored deletion marker must MATCH the plan's `?11`, \
4330 otherwise `deleted_at IS ?11` refuses too and the refusal stops being \
4331 attributable to `updated_at = ?10`"
4332 );
4333 }
4334
4335 let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
4336 .await
4337 .expect("the seam call itself must not error; the unit rolls back cleanly");
4338 match outcome {
4339 crate::atomic_runner::AtomicRunOutcome::RolledBack {
4340 failed_op_index,
4341 failure,
4342 } => {
4343 assert_eq!(
4344 failed_op_index, 0,
4345 "the sole op's guard must be the one that fails"
4346 );
4347 assert_eq!(
4355 failure,
4356 crate::atomic_runner::AtomicOpFailure::GuardFailed {
4357 statement_label: Some(
4358 "edge-symmetric-absorb-or-update-inplace".to_string()
4359 ),
4360 expected: crate::atomic_plan::AffectedRowGuard::exactly(1),
4361 observed: 0,
4362 },
4363 "the guarded in-place absorb must be the statement whose guard refused"
4364 );
4365 }
4366 other => panic!(
4367 "a stale absorption plan must roll back, not silently absorb E into the \
4368 survivor and discard the concurrent writer's change: {other:?}"
4369 ),
4370 }
4371
4372 let requested_after = runtime
4373 .get_edge(&token, requested_id)
4374 .await
4375 .expect("get_edge")
4376 .expect("E must still exist after the rolled-back absorption");
4377 assert_eq!(
4378 requested_after.relation,
4379 EdgeRelation::Extends,
4380 "E must be untouched by the rolled-back absorption: {requested_after:?}"
4381 );
4382 assert!(
4383 (requested_after.weight - 0.77).abs() < 1e-9,
4384 "the concurrent writer's committed weight must survive the rolled-back plan: \
4385 {requested_after:?}"
4386 );
4387
4388 let canonical_after = runtime
4389 .get_edge(&token, canonical_id)
4390 .await
4391 .expect("get_edge")
4392 .expect("S must still exist after the rolled-back absorption");
4393 assert_eq!(
4394 canonical_after.weight, 0.6,
4395 "the survivor must never have been touched by the aborted absorption"
4396 );
4397 }
4398
4399 #[tokio::test]
4404 async fn atomic_update_edge_rejects_entity_only_field_name() {
4405 let runtime = scratch_runtime();
4406 let token = runtime
4407 .authorize(Namespace::parse("local").expect("ns"))
4408 .expect("authorize");
4409 let entities = runtime.entities(&token).expect("entities store");
4410 let a = khive_storage::Entity::new("local", "concept", "GapEdgeRejectA");
4411 let b = khive_storage::Entity::new("local", "concept", "GapEdgeRejectB");
4412 let (a_id, b_id) = (a.id, b.id);
4413 entities.upsert_entity(a).await.expect("seed a");
4414 entities.upsert_entity(b).await.expect("seed b");
4415 let edge = runtime
4416 .link(&token, a_id, b_id, EdgeRelation::Extends, 0.5, None)
4417 .await
4418 .expect("seed edge");
4419 let edge_id = Uuid::from(edge.id);
4420
4421 let err = prepare_update(
4422 &runtime,
4423 &token,
4424 &json!({"id": edge_id.to_string(), "name": "not-a-valid-edge-field"}),
4425 None,
4426 )
4427 .await
4428 .expect_err("edge update with an entity-only field must be rejected");
4429 let message = err.to_string();
4430 assert!(
4431 message.contains("name") && message.contains("edge"),
4432 "error must name the offending field and the substrate: {message}"
4433 );
4434 }
4435
4436 #[tokio::test]
4441 async fn atomic_delete_edge_soft_and_hard_appends_edge_deleted_event() {
4442 let runtime = scratch_runtime();
4443 let token = runtime
4444 .authorize(Namespace::parse("local").expect("ns"))
4445 .expect("authorize");
4446
4447 for hard in [false, true] {
4448 let entities = runtime.entities(&token).expect("entities store");
4449 let a = khive_storage::Entity::new("local", "concept", format!("GapEdgeDelA{hard}"));
4450 let b = khive_storage::Entity::new("local", "concept", format!("GapEdgeDelB{hard}"));
4451 let (a_id, b_id) = (a.id, b.id);
4452 entities.upsert_entity(a).await.expect("seed a");
4453 entities.upsert_entity(b).await.expect("seed b");
4454 let edge = runtime
4455 .link(&token, a_id, b_id, EdgeRelation::Extends, 0.5, None)
4456 .await
4457 .expect("seed edge");
4458 let edge_id = Uuid::from(edge.id);
4459
4460 let args = if hard {
4461 json!({"id": edge_id.to_string(), "hard": true})
4462 } else {
4463 json!({"id": edge_id.to_string()})
4464 };
4465 let plan = prepare_delete(&runtime, &token, &args, None)
4466 .await
4467 .unwrap_or_else(|e| panic!("prepare delete edge (hard={hard}): {e}"));
4468 let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
4469 .await
4470 .unwrap_or_else(|e| panic!("edge delete commit (hard={hard}): {e}"));
4471 assert!(
4472 matches!(
4473 outcome,
4474 crate::atomic_runner::AtomicRunOutcome::Committed { .. }
4475 ),
4476 "expected a clean edge delete commit (hard={hard}): {outcome:?}"
4477 );
4478
4479 let after = runtime
4480 .get_edge_including_deleted(&token, edge_id)
4481 .await
4482 .expect("get_edge_including_deleted");
4483 if hard {
4484 assert!(after.is_none(), "hard delete must purge the row entirely");
4485 } else {
4486 assert!(
4487 after.as_ref().is_some_and(|e| e.deleted_at.is_some()),
4488 "soft delete must tombstone, not purge"
4489 );
4490 }
4491
4492 let events = events_for_target(&runtime, &token, edge_id, EventKind::EdgeDeleted).await;
4493 assert_eq!(
4494 events.len(),
4495 1,
4496 "expected exactly one EdgeDeleted event for {edge_id} (hard={hard})"
4497 );
4498 assert_eq!(events[0].payload["hard"], json!(hard));
4499 }
4500 }
4501
4502 #[tokio::test]
4506 async fn atomic_update_note_appends_no_event() {
4507 let runtime = scratch_runtime();
4508 let token = runtime
4509 .authorize(Namespace::parse("local").expect("ns"))
4510 .expect("authorize");
4511 let mut note = khive_storage::note::Note::new("local", "observation", "gap1-note-noevent");
4512 note.name = Some("gap1-note-noevent".to_string());
4513 let note_id = note.id;
4514 runtime
4515 .notes(&token)
4516 .expect("notes store")
4517 .upsert_note(note)
4518 .await
4519 .expect("seed note");
4520
4521 let plan = prepare_update(
4522 &runtime,
4523 &token,
4524 &json!({"id": note_id.to_string(), "content": "gap1-note-noevent, revised"}),
4525 None,
4526 )
4527 .await
4528 .expect("prepare update");
4529 let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
4530 .await
4531 .expect("seam call ok");
4532 assert!(matches!(
4533 outcome,
4534 crate::atomic_runner::AtomicRunOutcome::Committed { .. }
4535 ));
4536
4537 let event_store = runtime.events(&token).expect("event store");
4538 let page = event_store
4539 .query_events(
4540 khive_storage::EventFilter::default(),
4541 khive_storage::types::PageRequest::default(),
4542 )
4543 .await
4544 .expect("query_events");
4545 assert!(
4546 page.items.iter().all(|e| e.target_id != Some(note_id)),
4547 "update_note must append no event; found: {:?}",
4548 page.items
4549 .iter()
4550 .filter(|e| e.target_id == Some(note_id))
4551 .collect::<Vec<_>>()
4552 );
4553 }
4554
4555 #[tokio::test]
4558 async fn atomic_link_appends_no_event() {
4559 let runtime = scratch_runtime();
4560 let token = runtime
4561 .authorize(Namespace::parse("local").expect("ns"))
4562 .expect("authorize");
4563 let source = khive_storage::Entity::new("local", "concept", "gap1-link-source");
4564 let target = khive_storage::Entity::new("local", "concept", "gap1-link-target");
4565 let (source_id, target_id) = (source.id, target.id);
4566 runtime
4567 .entities(&token)
4568 .expect("entities store")
4569 .upsert_entity(source)
4570 .await
4571 .expect("seed source");
4572 runtime
4573 .entities(&token)
4574 .expect("entities store")
4575 .upsert_entity(target)
4576 .await
4577 .expect("seed target");
4578
4579 let plan = prepare_link(
4580 &runtime,
4581 &token,
4582 &json!({
4583 "source_id": source_id.to_string(),
4584 "target_id": target_id.to_string(),
4585 "relation": "extends",
4586 }),
4587 )
4588 .await
4589 .expect("prepare link");
4590 let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
4591 .await
4592 .expect("seam call ok");
4593 assert!(matches!(
4594 outcome,
4595 crate::atomic_runner::AtomicRunOutcome::Committed { .. }
4596 ));
4597
4598 let event_store = runtime.events(&token).expect("event store");
4599 let page = event_store
4600 .query_events(
4601 khive_storage::EventFilter::default(),
4602 khive_storage::types::PageRequest::default(),
4603 )
4604 .await
4605 .expect("query_events");
4606 assert!(
4607 page.items.is_empty(),
4608 "link must append no event; found: {:?}",
4609 page.items
4610 );
4611 }
4612
4613 #[tokio::test]
4618 async fn prepare_add_entity_rejects_whitespace_only_name() {
4619 let runtime = scratch_runtime();
4620 let token = runtime
4621 .authorize(Namespace::parse("local").expect("ns"))
4622 .expect("authorize");
4623
4624 let err = prepare_add_entity(&runtime, &token, &json!({"kind": "concept", "name": " "}))
4625 .await
4626 .expect_err("whitespace-only entity name must fail prepare");
4627
4628 assert!(matches!(
4629 err,
4630 RuntimeError::InvalidInput(message) if message.contains("name must not be empty")
4631 ));
4632 }
4633
4634 #[tokio::test]
4635 async fn prepare_add_entity_rejects_non_string_description() {
4636 let runtime = scratch_runtime();
4637 let token = runtime
4638 .authorize(Namespace::parse("local").expect("ns"))
4639 .expect("authorize");
4640
4641 let err = prepare_add_entity(
4642 &runtime,
4643 &token,
4644 &json!({"kind": "concept", "name": "Valid", "description": 42}),
4645 )
4646 .await
4647 .expect_err("non-string entity description must fail prepare");
4648
4649 assert!(matches!(
4650 err,
4651 RuntimeError::InvalidInput(message)
4652 if message.contains("description must be a string or null")
4653 ));
4654 }
4655
4656 #[tokio::test]
4657 async fn prepare_add_note_rejects_non_string_name() {
4658 let runtime = scratch_runtime();
4659 let token = runtime
4660 .authorize(Namespace::parse("local").expect("ns"))
4661 .expect("authorize");
4662
4663 let err = prepare_add_note(
4664 &runtime,
4665 &token,
4666 &json!({"kind": "observation", "content": "Valid", "name": 42}),
4667 )
4668 .await
4669 .expect_err("non-string note name must fail prepare");
4670
4671 assert!(matches!(
4672 err,
4673 RuntimeError::InvalidInput(message) if message.contains("name must be a string or null")
4674 ));
4675 }
4676
4677 #[tokio::test]
4682 async fn prepare_add_entity_rejects_reserved_secret_gate_property() {
4683 let runtime = scratch_runtime();
4684 let token = runtime
4685 .authorize(Namespace::parse("local").expect("ns"))
4686 .expect("authorize");
4687
4688 let err = prepare_add_entity(
4689 &runtime,
4690 &token,
4691 &json!({
4692 "kind": "concept",
4693 "name": "ReservedKeyEntity",
4694 "properties": {"khive:secret_gate": "exempted:content-sha256-manifest-v1"},
4695 }),
4696 )
4697 .await
4698 .expect_err("a caller-supplied reserved key on a new entity must be rejected");
4699 assert!(
4700 matches!(err, RuntimeError::InvalidInput(ref msg) if msg.contains("khive:secret_gate") && msg.contains("runtime-owned")),
4701 "expected a reservation rejection, got: {err:?}"
4702 );
4703 }
4704
4705 #[tokio::test]
4708 async fn prepare_add_note_rejects_reserved_secret_gate_property() {
4709 let runtime = scratch_runtime();
4710 let token = runtime
4711 .authorize(Namespace::parse("local").expect("ns"))
4712 .expect("authorize");
4713
4714 let err = prepare_add_note(
4715 &runtime,
4716 &token,
4717 &json!({
4718 "kind": "observation",
4719 "content": "a note carrying a reserved property key",
4720 "properties": {"khive:secret_gate": "exempted:content-sha256-manifest-v1"},
4721 }),
4722 )
4723 .await
4724 .expect_err("a caller-supplied reserved key on a new note must be rejected");
4725 assert!(
4726 matches!(err, RuntimeError::InvalidInput(ref msg) if msg.contains("khive:secret_gate") && msg.contains("runtime-owned")),
4727 "expected a reservation rejection, got: {err:?}"
4728 );
4729 }
4730
4731 #[tokio::test]
4732 async fn atomic_proposal_vectors_materialize_only_after_successful_commit() {
4733 let runtime = scratch_runtime();
4734 runtime.register_embedder(StubProvider);
4735 let token = runtime
4736 .authorize(Namespace::parse("local").expect("ns"))
4737 .expect("authorize");
4738 let vec_store = runtime
4739 .vectors_for_model(&token, STUB_MODEL)
4740 .expect("vec store");
4741 let entities = runtime.entities(&token).expect("entities store");
4742 let a = khive_storage::Entity::new("local", "concept", "ProposalPlanLinkA");
4743 let b = khive_storage::Entity::new("local", "concept", "ProposalPlanLinkB");
4744 let (a_id, b_id) = (a.id, b.id);
4745 entities.upsert_entity(a).await.expect("seed a");
4746 entities.upsert_entity(b).await.expect("seed b");
4747
4748 let add_entity_plan = prepare_add_entity(
4749 &runtime,
4750 &token,
4751 &json!({"kind": "concept", "name": "ProposalPlanNewEntity", "description": "created atomically"}),
4752 )
4753 .await
4754 .expect("prepare add_entity");
4755 let link_plan = prepare_link(
4756 &runtime,
4757 &token,
4758 &json!({"source_id": a_id.to_string(), "target_id": b_id.to_string(), "relation": "extends"}),
4759 )
4760 .await
4761 .expect("prepare link");
4762 let add_note_plan = prepare_add_note(
4763 &runtime,
4764 &token,
4765 &json!({"kind": "observation", "content": "created atomically alongside the entity"}),
4766 )
4767 .await
4768 .expect("prepare add_note");
4769
4770 let entity_id = match &add_entity_plan {
4771 AtomicOpPlan::AddEntity(p) => p.entity_id,
4772 other => panic!("expected an AddEntity plan, got {other:?}"),
4773 };
4774 let note_id = match &add_note_plan {
4775 AtomicOpPlan::AddNote(p) => p.note_id,
4776 other => panic!("expected an AddNote plan, got {other:?}"),
4777 };
4778
4779 let outcome = crate::atomic_runner::run_atomic_unit(
4780 runtime.sql().as_ref(),
4781 vec![add_entity_plan, link_plan, add_note_plan],
4782 )
4783 .await
4784 .expect("seam call ok");
4785 let post_commit = match outcome {
4786 crate::atomic_runner::AtomicRunOutcome::Committed { post_commit } => post_commit,
4787 other => panic!("expected the whole unit to commit: {other:?}"),
4788 };
4789 assert_eq!(
4790 post_commit.as_slice(),
4791 &[
4792 PostCommitEffect::ReindexEntity { entity_id },
4793 PostCommitEffect::ReindexNote { note_id },
4794 ],
4795 "prepare-derived effects must reach the committed token unchanged"
4796 );
4797 assert_eq!(
4798 vec_store.count().await.expect("count before effects"),
4799 0,
4800 "commit returns deferred effects without materializing vectors"
4801 );
4802 let entity = runtime
4803 .entities(&token)
4804 .expect("entities store")
4805 .get_entity(entity_id)
4806 .await
4807 .expect("get_entity")
4808 .expect("entity must exist after commit");
4809 assert_eq!(entity.name, "ProposalPlanNewEntity");
4810 assert!(
4811 runtime
4812 .text(&token)
4813 .expect("text store")
4814 .get_document("local", entity_id)
4815 .await
4816 .expect("get_document")
4817 .is_some(),
4818 "entity's FTS document must exist after commit"
4819 );
4820
4821 let (edge_count, _, _, edge_deleted_at) =
4822 probe_edge_natural_key(&runtime, "local", a_id, b_id, "extends").await;
4823 assert_eq!(
4824 edge_count, 1,
4825 "the edge must be committed alongside the entity/note"
4826 );
4827 assert!(edge_deleted_at.is_none());
4828
4829 let note = runtime
4830 .notes(&token)
4831 .expect("notes store")
4832 .get_note(note_id)
4833 .await
4834 .expect("get_note")
4835 .expect("note must exist after commit");
4836 assert_eq!(note.content, "created atomically alongside the entity");
4837 assert!(
4838 runtime
4839 .text_for_notes(&token)
4840 .expect("text store")
4841 .get_document("local", note_id)
4842 .await
4843 .expect("get_document")
4844 .is_some(),
4845 "note's FTS document must exist after commit"
4846 );
4847
4848 apply_post_commit_effects(&runtime, &token, post_commit)
4849 .await
4850 .expect("apply post-commit effects");
4851
4852 assert_eq!(
4853 vec_store.count().await.expect("count after"),
4854 2,
4855 "post-commit reindex must have embedded both the new entity and the new note"
4856 );
4857 }
4858
4859 #[tokio::test]
4860 async fn atomic_proposal_abort_leaves_zero_vector_rows() {
4861 let runtime = scratch_runtime();
4862 runtime.register_embedder(StubProvider);
4863 let token = runtime
4864 .authorize(Namespace::parse("local").expect("ns"))
4865 .expect("authorize");
4866 let vec_store = runtime
4867 .vectors_for_model(&token, STUB_MODEL)
4868 .expect("vec store");
4869 let entities = runtime.entities(&token).expect("entities store");
4870 let a = khive_storage::Entity::new("local", "concept", "ProposalPlanRollbackA");
4871 let x = khive_storage::Entity::new("local", "concept", "ProposalPlanRollbackX");
4872 let (a_id, x_id) = (a.id, x.id);
4873 entities.upsert_entity(a).await.expect("seed a");
4874 entities.upsert_entity(x.clone()).await.expect("seed x");
4875
4876 let add_entity_plan = prepare_add_entity(
4877 &runtime,
4878 &token,
4879 &json!({"kind": "concept", "name": "ProposalPlanRollbackNewEntity"}),
4880 )
4881 .await
4882 .expect("prepare add_entity");
4883 let add_note_plan = prepare_add_note(
4884 &runtime,
4885 &token,
4886 &json!({"kind": "observation", "content": "must not survive the rollback"}),
4887 )
4888 .await
4889 .expect("prepare add_note");
4890 let delete_plan = prepare_delete(
4891 &runtime,
4892 &token,
4893 &json!({"id": x_id.to_string(), "hard": true}),
4894 None,
4895 )
4896 .await
4897 .expect("prepare delete x");
4898 let link_plan = prepare_link(
4901 &runtime,
4902 &token,
4903 &json!({"source_id": a_id.to_string(), "target_id": x_id.to_string(), "relation": "extends"}),
4904 )
4905 .await
4906 .expect("prepare link (endpoint still exists at prepare time)");
4907
4908 let entity_id = match &add_entity_plan {
4909 AtomicOpPlan::AddEntity(p) => p.entity_id,
4910 other => panic!("expected an AddEntity plan, got {other:?}"),
4911 };
4912 let note_id = match &add_note_plan {
4913 AtomicOpPlan::AddNote(p) => p.note_id,
4914 other => panic!("expected an AddNote plan, got {other:?}"),
4915 };
4916
4917 let outcome = crate::atomic_runner::run_atomic_unit(
4918 runtime.sql().as_ref(),
4919 vec![add_entity_plan, add_note_plan, delete_plan, link_plan],
4920 )
4921 .await
4922 .expect("the seam call itself must not error; the unit rolls back cleanly");
4923 match outcome {
4924 crate::atomic_runner::AtomicRunOutcome::RolledBack {
4925 failed_op_index, ..
4926 } => {
4927 assert_eq!(
4928 failed_op_index, 3,
4929 "the trailing link (index 3) must be the op whose guard fails"
4930 );
4931 }
4932 other => panic!("expected the whole unit to roll back, got {other:?}"),
4933 }
4934
4935 assert_eq!(
4936 vec_store
4937 .count()
4938 .await
4939 .expect("vector count after rollback"),
4940 0,
4941 "a rolled-back atomic apply must not materialize vectors"
4942 );
4943
4944 assert!(
4945 runtime
4946 .get_entity_including_deleted(&token, entity_id)
4947 .await
4948 .expect("get_entity_including_deleted")
4949 .is_none(),
4950 "the new entity must leave zero trace after rollback"
4951 );
4952 assert!(
4953 runtime
4954 .text(&token)
4955 .expect("text store")
4956 .get_document("local", entity_id)
4957 .await
4958 .expect("get_document")
4959 .is_none(),
4960 "the new entity's FTS document must leave zero trace after rollback"
4961 );
4962 assert!(
4963 runtime
4964 .get_note_including_deleted(&token, note_id)
4965 .await
4966 .expect("get_note_including_deleted")
4967 .is_none(),
4968 "the new note must leave zero trace after rollback"
4969 );
4970 assert!(
4971 runtime
4972 .text_for_notes(&token)
4973 .expect("text store")
4974 .get_document("local", note_id)
4975 .await
4976 .expect("get_document")
4977 .is_none(),
4978 "the new note's FTS document must leave zero trace after rollback"
4979 );
4980
4981 let x_after = runtime
4982 .get_entity_including_deleted(&token, x_id)
4983 .await
4984 .expect("get_entity_including_deleted")
4985 .expect("x must still be present because its delete rolled back too");
4986 assert!(
4987 x_after.deleted_at.is_none(),
4988 "x's delete must have rolled back along with the failed link"
4989 );
4990
4991 let (edge_count, _, _, _) =
4992 probe_edge_natural_key(&runtime, "local", a_id, x_id, "extends").await;
4993 assert_eq!(edge_count, 0, "no edge may have been committed");
4994 }
4995
4996 #[tokio::test]
5000 async fn atomic_update_entity_type_null_clears_stored_type() {
5001 let runtime = scratch_runtime();
5002 runtime.install_entity_type_validator(std::sync::Arc::new(|kind, entity_type| {
5003 let Some(raw) = entity_type else {
5004 return Ok(None);
5005 };
5006 let normalized = raw.trim().to_ascii_lowercase();
5007 if kind == "concept" && normalized == "algorithm" {
5008 Ok(Some(normalized))
5009 } else {
5010 Err(RuntimeError::InvalidInput(format!(
5011 "unknown entity_type {raw:?} for {kind:?}; valid: algorithm"
5012 )))
5013 }
5014 }));
5015 let token = runtime
5016 .authorize(Namespace::parse("local").expect("ns"))
5017 .expect("authorize");
5018 let mut entity = khive_storage::Entity::new("local", "concept", "AtomicNullClear");
5019 entity.entity_type = Some("algorithm".to_string());
5020 let entity_id = entity.id;
5021 runtime
5022 .entities(&token)
5023 .expect("entities store")
5024 .upsert_entity(entity)
5025 .await
5026 .expect("seed entity");
5027
5028 let plan = prepare_update(
5029 &runtime,
5030 &token,
5031 &json!({"id": entity_id.to_string(), "entity_type": null}),
5032 None,
5033 )
5034 .await
5035 .expect("atomic prepare must accept entity_type: null");
5036 let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
5037 .await
5038 .expect("atomic update must run");
5039 let post_commit = match outcome {
5040 crate::atomic_runner::AtomicRunOutcome::Committed { post_commit } => post_commit,
5041 other => panic!("expected Committed, got {other:?}"),
5042 };
5043 assert_eq!(
5044 post_commit.as_slice(),
5045 &[PostCommitEffect::ReindexEntity { entity_id }],
5046 "a type clear that differs from the prior value must reindex"
5047 );
5048
5049 let updated = runtime
5050 .get_entity(&token, entity_id)
5051 .await
5052 .expect("read updated entity");
5053 assert_eq!(
5054 updated.entity_type, None,
5055 "entity_type: null must clear the stored type"
5056 );
5057 assert_eq!(updated.name, "AtomicNullClear");
5058 }
5059
5060 #[tokio::test]
5064 async fn atomic_update_null_entity_type_rejected_for_note_and_edge() {
5065 let runtime = scratch_runtime();
5066 let token = runtime
5067 .authorize(Namespace::parse("local").expect("ns"))
5068 .expect("authorize");
5069 let note = runtime
5070 .create_note(
5071 &token,
5072 "observation",
5073 None,
5074 "note body for entity_type guard",
5075 Some(0.5),
5076 None,
5077 vec![],
5078 )
5079 .await
5080 .expect("create note");
5081
5082 let note_err = prepare_update(
5083 &runtime,
5084 &token,
5085 &json!({"id": note.id.to_string(), "entity_type": null}),
5086 Some(crate::atomic_prepare::AtomicUpdateKind::Note { specific: None }),
5087 )
5088 .await
5089 .expect_err("entity_type: null on a note must be rejected");
5090 assert!(
5091 matches!(note_err, RuntimeError::InvalidInput(ref msg) if msg.contains("entity_type") && msg.contains("not valid for a note")),
5092 "expected an InvalidInput naming entity_type for a note, got: {note_err:?}"
5093 );
5094
5095 let source = khive_storage::Entity::new("local", "concept", "AtomicNullTypeEdgeSource");
5096 let target = khive_storage::Entity::new("local", "concept", "AtomicNullTypeEdgeTarget");
5097 let source_id = source.id;
5098 let target_id = target.id;
5099 runtime
5100 .entities(&token)
5101 .expect("entities store")
5102 .upsert_entity(source)
5103 .await
5104 .expect("seed source");
5105 runtime
5106 .entities(&token)
5107 .expect("entities store")
5108 .upsert_entity(target)
5109 .await
5110 .expect("seed target");
5111 let edge = runtime
5112 .link(
5113 &token,
5114 source_id,
5115 target_id,
5116 "supports".parse().expect("relation"),
5117 0.5,
5118 None,
5119 )
5120 .await
5121 .expect("create edge");
5122
5123 let edge_err = prepare_update(
5124 &runtime,
5125 &token,
5126 &json!({"id": edge.id.to_string(), "entity_type": null}),
5127 Some(crate::atomic_prepare::AtomicUpdateKind::Edge),
5128 )
5129 .await
5130 .expect_err("entity_type: null on an edge must be rejected");
5131 assert!(
5132 matches!(edge_err, RuntimeError::InvalidInput(ref msg) if msg.contains("entity_type") && msg.contains("not valid for an edge")),
5133 "expected an InvalidInput naming entity_type for an edge, got: {edge_err:?}"
5134 );
5135 }
5136}