1use std::collections::HashMap;
7use std::str::FromStr;
8
9use chrono::Utc;
10use serde::Serialize;
11use uuid::Uuid;
12
13#[cfg(test)]
14use khive_score::DeterministicScore;
15use khive_storage::entity::EntityTypeCounts;
16#[cfg(test)]
17use khive_storage::graph::{SymmetricEdgeUpdateOutcome, SymmetricEdgeUpdateRequest};
18use khive_storage::note::Note;
19#[cfg(test)]
20use khive_storage::types::DeleteMode;
21use khive_storage::types::{
22 DirectedNeighborHit, Direction, EdgeUpsertDisposition, EdgeUpsertRefusal, EdgeUpsertRequest,
23 EdgeUpsertResult, GraphPath, GuardedEdgeUpsertOutcome, LinkId, NeighborCursor, NeighborHit,
24 NeighborQuery, PageRequest, SqlStatement, SqlValue, TextFilter, TextQueryMode,
25 TextSearchRequest, TraversalRequest,
26};
27use khive_storage::{
28 Attachment, AttachmentSubstrate, Edge, EdgeRelation, Entity, EntityFilter, Event, EventFilter,
29 NewAttachment,
30};
31use khive_types::{EdgeEndpointRule, EndpointKind, EventKind, KhiveError, SubstrateKind};
32
33use khive_db::stores::entity::entity_upsert_statement;
34
35use khive_db::stores::graph::{
36 compose_graph_mutation_events, GraphMutationOutcome, GraphMutationPreconditions,
37 GraphMutationRequest,
38};
39
40use khive_db::stores::text::insert_document_statements;
41
42mod note_search;
43mod quarantine_note_retention;
44
45#[cfg(test)]
46mod batch_edge_tests;
47
48struct EdgeReadWindow {
49 outcomes: Vec<Option<RuntimeResult<Option<Edge>>>>,
50 groups: Vec<(khive_types::Namespace, Vec<usize>)>,
51}
52
53fn restore_reindex_failed(kind: &str, id: Uuid, error: RuntimeError) -> RuntimeError {
57 RuntimeError::Internal(format!(
58 "{kind} {id} is restored and text-indexed, but its embedding rebuild failed \
59 and will be retried by the next reindex: {error}"
60 ))
61}
62
63fn merge_tombstone_restore_refused(id: Uuid, kept_id: impl std::fmt::Display) -> RuntimeError {
64 KhiveError::conflict(format!(
65 "merge_tombstone: {id} was merged into {kept_id}; a merge tombstone is not restorable, query the kept id"
66 ))
67 .with_details(khive_types::Details::new_owned([
68 ("reason", "merge_tombstone".into()),
69 ("merged_into", kept_id.to_string()),
70 ]))
71 .into()
72}
73
74#[derive(Debug, PartialEq, Eq)]
76pub struct EntityStatsCounts {
77 pub entities: u64,
78 pub entities_by_type: Option<EntityTypeCounts>,
79}
80
81#[derive(Debug, Default, PartialEq, Eq)]
83pub struct EdgeStatsCounts {
84 pub edges: u64,
85 pub edges_by_relation: HashMap<String, u64>,
86 pub edges_by_endpoint_base: khive_storage::types::EdgeEndpointBaseCounts,
87}
88
89pub async fn entity_stats_counts(
92 store: &dyn khive_storage::EntityStore,
93 token: &NamespaceToken,
94) -> RuntimeResult<EntityStatsCounts> {
95 let namespaces: Vec<String> = token
96 .visible_namespaces()
97 .iter()
98 .map(|namespace| namespace.as_str().to_owned())
99 .collect();
100 match store.count_entities_by_type(&namespaces).await? {
101 Some(groups) => {
102 let entities = groups.iter().try_fold(0_u64, |total, (_, count)| {
103 total.checked_add(*count).ok_or_else(|| {
104 RuntimeError::Internal(
105 "entity type counts exceed the scalar count range".into(),
106 )
107 })
108 })?;
109 Ok(EntityStatsCounts {
110 entities,
111 entities_by_type: Some(groups),
112 })
113 }
114 None => {
115 let entities = store
116 .count_entities(
117 token.namespace().as_str(),
118 EntityFilter {
119 namespaces,
120 ..EntityFilter::default()
121 },
122 )
123 .await?;
124 Ok(EntityStatsCounts {
125 entities,
126 entities_by_type: None,
127 })
128 }
129 }
130}
131
132pub struct EntityClaimSpec {
135 pub id: Uuid,
136 pub kind: String,
137 pub entity_type: Option<String>,
138 pub name: String,
139 pub description: Option<String>,
140 pub properties: Option<serde_json::Value>,
141 pub tags: Vec<String>,
142 pub identity_tag: String,
143}
144
145fn live_merged_entity_refused(id: Uuid, kept_id: impl std::fmt::Display) -> RuntimeError {
146 KhiveError::conflict(format!(
147 "live_merged_entity: {id} is live but still carries merged_into {kept_id}; a row an \
148 earlier restore left live over its merge is not restorable, re-tombstone it or query the \
149 kept id"
150 ))
151 .with_details(khive_types::Details::new_owned([
152 ("reason", "live_merged_entity".into()),
153 ("merged_into", kept_id.to_string()),
154 ]))
155 .into()
156}
157
158fn restore_key_conflict(key: &str, holder: &Note) -> RuntimeError {
159 KhiveError::conflict(format!(
160 "restore_key_conflict: key {key:?} is already held by live note {}",
161 holder.id
162 ))
163 .with_details(khive_types::Details::new_owned([
164 ("reason", "restore_key_conflict".into()),
165 ("key", key.to_owned()),
166 ("existing_id", holder.id.to_string()),
167 ]))
168 .into()
169}
170
171use crate::atomic_plan::{
172 AddEntityPlan, AffectedRowGuard, PlanStatement, PostCommitEffect, UpdatePlan,
173};
174use crate::atomic_runner::{run_atomic_unit, AtomicOpFailure, AtomicOpPlan, AtomicRunOutcome};
175use crate::curation::{entity_fts_document, note_embedding_text_ref, note_fts_document};
176use crate::error::{GuardedWriteFailure, RuntimeError, RuntimeResult};
177use crate::runtime::{KhiveRuntime, NamespaceToken};
178
179#[derive(Clone, Debug, Serialize)]
182pub struct PostCommitDegradation {
183 pub stage: &'static str,
184 pub error: String,
185}
186
187impl PostCommitDegradation {
188 fn new(stage: &'static str, error: impl ToString) -> Self {
189 Self {
190 stage,
191 error: error.to_string(),
192 }
193 }
194}
195
196macro_rules! conditional_insert_stages {
198 ($($stage:ident => $label:literal),+ $(,)?) => {
199 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
205 pub enum ConditionalInsertStage {
206 $($stage,)+
207 }
208
209 impl ConditionalInsertStage {
210 pub const ALL: &'static [Self] = &[$(Self::$stage,)+];
212
213 pub const fn label(self) -> &'static str {
214 match self {
215 $(Self::$stage => $label,)+
216 }
217 }
218 }
219 };
220}
221
222conditional_insert_stages! {
223 FtsAcquisition => "fts_acquisition",
224 FtsUpsert => "fts_upsert",
225 Embedding => "embedding",
226 VectorAcquisition => "vector_acquisition",
227 VectorInsert => "vector_insert",
228}
229
230impl ConditionalInsertStage {
231 pub fn from_label(label: &str) -> Option<Self> {
232 Self::ALL
233 .iter()
234 .copied()
235 .find(|stage| stage.label() == label)
236 }
237}
238
239fn record_conditional_insert_degradation(
240 degradations: &mut Vec<PostCommitDegradation>,
241 id: Uuid,
242 stage: ConditionalInsertStage,
243 error: impl ToString,
244) {
245 record_post_commit_degradation(degradations, "try_create_note", id, stage.label(), error);
246}
247
248fn record_post_commit_degradation(
249 degradations: &mut Vec<PostCommitDegradation>,
250 operation: &'static str,
251 id: Uuid,
252 stage: &'static str,
253 error: impl ToString,
254) {
255 let degradation = PostCommitDegradation::new(stage, error);
256 tracing::warn!(%operation, %id, stage, error = %degradation.error,
257 "substrate mutation committed with post-commit degradation");
258 degradations.push(degradation);
259}
260
261pub(crate) fn legacy_post_commit_result<T>(
265 operation: &'static str,
266 id: Uuid,
267 value: T,
268 degradations: Vec<PostCommitDegradation>,
269) -> RuntimeResult<T> {
270 if degradations.is_empty() {
271 return Ok(value);
272 }
273 let failures = serde_json::Value::Array(
274 degradations
275 .iter()
276 .map(|failure| {
277 serde_json::json!({"stage": failure.stage, "error": failure.error.as_str()})
278 })
279 .collect(),
280 );
281 Err(KhiveError::internal(format!(
282 "{operation} committed record {id}, but post-commit work failed; do not retry the mutation; reconcile by record_id"
283 ))
284 .with_details(khive_types::Details::new_owned([
285 ("reason", "post_commit_degraded".to_string()),
286 ("operation", operation.to_string()),
287 ("record_id", id.to_string()),
288 ("committed", "true".to_string()),
289 ("retryable", "false".to_string()),
290 ("post_commit_degradations", failures.to_string()),
291 ]))
292 .into())
293}
294
295pub(crate) fn legacy_post_commit_result_with_embedding<T>(
296 operation: &'static str,
297 id: Uuid,
298 value: T,
299 embedding: crate::retrieval::EmbeddingTruncationReport,
300 degradations: Vec<PostCommitDegradation>,
301) -> RuntimeResult<T> {
302 if !embedding.any_truncated() {
303 return legacy_post_commit_result(operation, id, value, degradations);
304 }
305 let failures = serde_json::Value::Array(
306 degradations
307 .iter()
308 .map(|failure| {
309 serde_json::json!({"stage": failure.stage, "error": failure.error.as_str()})
310 })
311 .collect(),
312 );
313 Err(KhiveError::internal(format!(
314 "{operation} committed record {id}, but embedding input was truncated; do not retry the mutation; reconcile by record_id"
315 ))
316 .with_details(khive_types::Details::new_owned([
317 ("reason", "embedding_input_truncated".to_string()),
318 ("operation", operation.to_string()),
319 ("record_id", id.to_string()),
320 ("committed", "true".to_string()),
321 ("retryable", "false".to_string()),
322 (
323 "embedding_truncation_report",
324 serde_json::json!(embedding).to_string(),
325 ),
326 ("post_commit_degradations", failures.to_string()),
327 ]))
328 .into())
329}
330
331mod attachments;
332mod entity_aliases;
333pub(crate) use entity_aliases::{
334 apply_entity_alias_change, entity_updated_payload, unguarded as unguarded_alias_statements,
335};
336pub use entity_aliases::{validate_entity_alias, EntityAliasChange, EntityAliasReport};
337mod entity_bulk;
338mod entity_create;
339mod entity_key_add;
340pub use entity_key_add::{
341 entity_key_add_plans, EntityKeyAdd, ENTITY_KEY_ADD_HELD_LABEL, ENTITY_KEY_ADD_LIVE_LABEL,
342};
343mod entity_keys;
344pub(crate) use entity_keys::validate_entity_key;
345pub use entity_keys::{
346 entity_carries_create_payload, entity_key_conflict, keyed_replay_assertion_plan,
347 same_create_payload, KeyedEntityCreate, KeyedEntityReload, PendingEntityId,
348};
349mod entity_indexes;
350#[cfg(any(test, feature = "fault-injection"))]
351mod fault_injection;
352mod resolve_prefix_in;
353mod resolve_uuid_or_prefix;
354
355mod delete_restore;
356mod edge_query;
357mod graph_rules;
358mod identity_reads;
359mod link_ops;
360mod read_helpers;
361mod record_ops;
362mod traversal;
363
364use read_helpers::{
365 direction_sort_rank, drain_embed_join_set, normalize_symmetric_direction, note_snippet,
366 note_title, resolve_prefix_statement, salience_weighted_rank,
367};
368pub use read_helpers::{
369 hex_prefix_to_uuid_pattern, uuid_prefix_bounds, NoteSearchHit, NoteSearchOutcome, Resolved,
370};
371pub use record_ops::NoteCreateSpec;
372
373pub use edge_query::QueryResult;
374use graph_rules::{accepted_entity_relations_description, static_impossible_edge_pattern_warnings};
375pub use graph_rules::{
376 accepted_entity_relations_for_entities, accepted_pack_relations_for_entities,
377 allowed_pairs_for_relation_description, dependency_kind_inference_hint, merge_entry_metadata,
378};
379pub(crate) use graph_rules::{
380 canonical_edge_endpoint_kinds, canonical_edge_endpoints, merge_dependency_kind,
381 pack_rule_allows, validate_edge_metadata, validate_edge_weight,
382};
383#[cfg(test)]
384use link_ops::guarded_link_batch_failure;
385#[cfg(test)]
386use traversal::merge_traversal_paths_by_root;
387
388#[cfg(any(test, feature = "fault-injection"))]
389pub use fault_injection::{
390 arm_entity_compensation_fail_scoped, arm_fts_fail_many_partial_scoped,
391 arm_fts_fail_many_scoped, arm_fts_fail_scoped, arm_fts_search_fail,
392 arm_prefix_resolve_fail_scoped, arm_rollback_cleanup_fail, arm_vector_fail_after,
393 arm_vector_fail_scoped, FaultInjectionArm,
394};
395#[cfg(test)]
396use fault_injection::{arm_fault, FaultArmSet, LINK_FAIL_AFTER};
397#[cfg(any(test, feature = "fault-injection"))]
398use fault_injection::{
399 consume_fault, ENTITY_COMPENSATION_FAIL_NS, FTS_FAIL_MANY_NS, FTS_FAIL_MANY_PARTIAL_NS,
400 FTS_FAIL_NS, FTS_SEARCH_FAIL_NS, PREFIX_RESOLVE_FAIL_NS, ROLLBACK_CLEANUP_FAIL_NS,
401 VECTOR_FAIL_AFTER, VECTOR_FAIL_NS,
402};
403#[cfg(any(test, feature = "fault-injection"))]
404pub(crate) use fault_injection::{consume_fts_fail_fault, consume_vector_fail_fault};
405pub use resolve_prefix_in::PrefixScope;
406
407#[derive(Clone, Copy, Debug, Eq, PartialEq)]
414pub enum EdgeEndpointKind {
415 Entity,
416 Note,
417 Event,
418 Edge,
419}
420
421impl EdgeEndpointKind {
422 pub const fn name(self) -> &'static str {
424 match self {
425 Self::Entity => "entity",
426 Self::Note => "note",
427 Self::Event => "event",
428 Self::Edge => "edge",
429 }
430 }
431}
432
433fn resolved_pair(r: Option<&Resolved>) -> Option<(&'static str, &str, Option<&str>)> {
439 match r? {
440 Resolved::Entity(e) => Some(("entity", e.kind.as_str(), e.entity_type.as_deref())),
441 Resolved::Note(n) => Some(("note", n.kind.as_str(), None)),
442 Resolved::Event(_) => None,
443 Resolved::PackRecord { .. } => None,
444 }
445}
446
447pub use khive_types::{
448 base_entity_endpoint_rules, base_entity_rule_allows, endpoint_matches,
449 BASE_ENTITY_ENDPOINT_RULES,
450};
451
452impl KhiveRuntime {
453 #[allow(clippy::too_many_arguments)]
471 pub async fn create_note(
472 &self,
473 token: &NamespaceToken,
474 kind: &str,
475 name: Option<&str>,
476 content: &str,
477 salience: Option<f64>,
478 properties: Option<serde_json::Value>,
479 annotates: Vec<Uuid>,
480 ) -> RuntimeResult<Note> {
481 let (note, embedding, degradations, _) = self
482 .create_note_inner(
483 token, kind, name, content, None, salience, None, properties, annotates, None,
484 false, false,
485 )
486 .await?;
487 legacy_post_commit_result_with_embedding(
488 "create_note",
489 note.id,
490 note,
491 embedding,
492 degradations,
493 )
494 }
495
496 pub async fn create_web_receipt_note(
501 &self,
502 token: &NamespaceToken,
503 summary: &str,
504 request: serde_json::Value,
505 annotates: Vec<Uuid>,
506 ) -> RuntimeResult<Note> {
507 let properties = serde_json::json!({
508 "tags": ["web.receipt"],
509 "request": request,
510 });
511 let (note, _, degradations, _) = self
512 .create_note_inner(
513 token,
514 "observation",
515 None,
516 summary,
517 None,
518 None,
519 None,
520 Some(properties),
521 annotates,
522 None,
523 false,
524 true,
525 )
526 .await?;
527 legacy_post_commit_result("create_web_receipt_note", note.id, note, degradations)
528 }
529
530 #[allow(clippy::too_many_arguments)]
541 pub async fn create_note_with_embedding_content(
542 &self,
543 token: &NamespaceToken,
544 kind: &str,
545 name: Option<&str>,
546 content: &str,
547 embedding_content: Option<&str>,
548 salience: Option<f64>,
549 properties: Option<serde_json::Value>,
550 annotates: Vec<Uuid>,
551 ) -> RuntimeResult<Note> {
552 let (note, embedding, degradations, _) = self
553 .create_note_inner(
554 token,
555 kind,
556 name,
557 content,
558 embedding_content,
559 salience,
560 None,
561 properties,
562 annotates,
563 None,
564 false,
565 false,
566 )
567 .await?;
568 legacy_post_commit_result_with_embedding(
569 "create_note_with_embedding_content",
570 note.id,
571 note,
572 embedding,
573 degradations,
574 )
575 }
576
577 #[allow(clippy::too_many_arguments)]
578 pub async fn create_note_with_embedding_content_and_report(
579 &self,
580 token: &NamespaceToken,
581 kind: &str,
582 name: Option<&str>,
583 content: &str,
584 embedding_content: Option<&str>,
585 salience: Option<f64>,
586 properties: Option<serde_json::Value>,
587 annotates: Vec<Uuid>,
588 ) -> RuntimeResult<(Note, crate::retrieval::EmbeddingTruncationReport)> {
589 let (note, embedding, degradations, _) = self
590 .create_note_inner(
591 token,
592 kind,
593 name,
594 content,
595 embedding_content,
596 salience,
597 None,
598 properties,
599 annotates,
600 None,
601 false,
602 false,
603 )
604 .await?;
605 legacy_post_commit_result(
606 "create_note_with_embedding_content_and_report",
607 note.id,
608 (note, embedding),
609 degradations,
610 )
611 }
612
613 #[allow(clippy::too_many_arguments)]
615 pub async fn create_note_with_embedding_content_and_post_commit_report(
616 &self,
617 token: &NamespaceToken,
618 kind: &str,
619 name: Option<&str>,
620 content: &str,
621 embedding_content: Option<&str>,
622 salience: Option<f64>,
623 properties: Option<serde_json::Value>,
624 annotates: Vec<Uuid>,
625 ) -> RuntimeResult<(
626 Note,
627 crate::retrieval::EmbeddingTruncationReport,
628 Vec<PostCommitDegradation>,
629 )> {
630 let (note, embedding, degradations, _) = self
631 .create_note_inner(
632 token,
633 kind,
634 name,
635 content,
636 embedding_content,
637 salience,
638 None,
639 properties,
640 annotates,
641 None,
642 false,
643 false,
644 )
645 .await?;
646 Ok((note, embedding, degradations))
647 }
648
649 #[allow(clippy::too_many_arguments)]
653 pub async fn create_note_with_decay(
654 &self,
655 token: &NamespaceToken,
656 kind: &str,
657 name: Option<&str>,
658 content: &str,
659 salience: Option<f64>,
660 decay_factor: f64,
661 properties: Option<serde_json::Value>,
662 annotates: Vec<Uuid>,
663 ) -> RuntimeResult<Note> {
664 self.create_note_with_decay_for_embedding_model(
665 token,
666 kind,
667 name,
668 content,
669 salience,
670 decay_factor,
671 properties,
672 annotates,
673 None,
674 )
675 .await
676 }
677
678 #[allow(clippy::too_many_arguments)]
680 pub async fn create_note_with_decay_and_report(
681 &self,
682 token: &NamespaceToken,
683 kind: &str,
684 name: Option<&str>,
685 content: &str,
686 salience: Option<f64>,
687 decay_factor: f64,
688 properties: Option<serde_json::Value>,
689 annotates: Vec<Uuid>,
690 ) -> RuntimeResult<(Note, crate::retrieval::EmbeddingTruncationReport)> {
691 self.create_note_with_decay_for_embedding_model_and_report(
692 token,
693 kind,
694 name,
695 content,
696 salience,
697 decay_factor,
698 properties,
699 annotates,
700 None,
701 )
702 .await
703 }
704
705 #[allow(clippy::too_many_arguments)]
710 pub async fn create_note_with_decay_for_embedding_model(
711 &self,
712 token: &NamespaceToken,
713 kind: &str,
714 name: Option<&str>,
715 content: &str,
716 salience: Option<f64>,
717 decay_factor: f64,
718 properties: Option<serde_json::Value>,
719 annotates: Vec<Uuid>,
720 embedding_model: Option<&str>,
721 ) -> RuntimeResult<Note> {
722 let (note, embedding, degradations, _) = self
723 .create_note_inner(
724 token,
725 kind,
726 name,
727 content,
728 None,
729 salience,
730 Some(decay_factor),
731 properties,
732 annotates,
733 embedding_model,
734 false,
735 false,
736 )
737 .await?;
738 legacy_post_commit_result_with_embedding(
739 "create_note_with_decay_for_embedding_model",
740 note.id,
741 note,
742 embedding,
743 degradations,
744 )
745 }
746
747 #[allow(clippy::too_many_arguments)]
749 pub async fn create_note_with_decay_for_embedding_model_and_report(
750 &self,
751 token: &NamespaceToken,
752 kind: &str,
753 name: Option<&str>,
754 content: &str,
755 salience: Option<f64>,
756 decay_factor: f64,
757 properties: Option<serde_json::Value>,
758 annotates: Vec<Uuid>,
759 embedding_model: Option<&str>,
760 ) -> RuntimeResult<(Note, crate::retrieval::EmbeddingTruncationReport)> {
761 let (note, embedding, degradations, _) = self
762 .create_note_inner(
763 token,
764 kind,
765 name,
766 content,
767 None,
768 salience,
769 Some(decay_factor),
770 properties,
771 annotates,
772 embedding_model,
773 false,
774 false,
775 )
776 .await?;
777 legacy_post_commit_result(
778 "create_note_with_decay_for_embedding_model_and_report",
779 note.id,
780 (note, embedding),
781 degradations,
782 )
783 }
784
785 #[allow(clippy::too_many_arguments)]
789 pub async fn create_note_with_decay_for_embedding_model_with_visibility(
790 &self,
791 token: &NamespaceToken,
792 kind: &str,
793 name: Option<&str>,
794 content: &str,
795 salience: Option<f64>,
796 decay_factor: f64,
797 properties: Option<serde_json::Value>,
798 annotates: Vec<Uuid>,
799 embedding_model: Option<&str>,
800 ) -> RuntimeResult<(Note, Vec<(String, u64)>)> {
801 let (note, _, degradations, fences) = self
802 .create_note_inner(
803 token,
804 kind,
805 name,
806 content,
807 None,
808 salience,
809 Some(decay_factor),
810 properties,
811 annotates,
812 embedding_model,
813 true,
814 false,
815 )
816 .await?;
817 legacy_post_commit_result(
818 "create_note_with_decay_for_embedding_model_with_visibility",
819 note.id,
820 (note, fences),
821 degradations,
822 )
823 }
824
825 #[allow(clippy::too_many_arguments)]
829 pub async fn create_note_with_decay_for_embedding_model_with_visibility_and_report(
830 &self,
831 token: &NamespaceToken,
832 kind: &str,
833 name: Option<&str>,
834 content: &str,
835 salience: Option<f64>,
836 decay_factor: f64,
837 properties: Option<serde_json::Value>,
838 annotates: Vec<Uuid>,
839 embedding_model: Option<&str>,
840 ) -> RuntimeResult<(
841 Note,
842 Vec<(String, u64)>,
843 crate::retrieval::EmbeddingTruncationReport,
844 )> {
845 let (note, embedding, degradations, fences) = self
846 .create_note_inner(
847 token,
848 kind,
849 name,
850 content,
851 None,
852 salience,
853 Some(decay_factor),
854 properties,
855 annotates,
856 embedding_model,
857 true,
858 false,
859 )
860 .await?;
861 legacy_post_commit_result(
862 "create_note_with_decay_for_embedding_model_with_visibility_and_report",
863 note.id,
864 (note, fences, embedding),
865 degradations,
866 )
867 }
868
869 pub async fn try_create_note(
892 &self,
893 token: &NamespaceToken,
894 kind: &str,
895 name: Option<&str>,
896 content: &str,
897 properties: Option<serde_json::Value>,
898 ) -> RuntimeResult<Option<Note>> {
899 self.try_create_note_impl(token, kind, name, content, properties, false, None, None)
900 .await
901 }
902
903 #[allow(clippy::too_many_arguments)]
904 async fn try_create_note_impl(
905 &self,
906 token: &NamespaceToken,
907 kind: &str,
908 name: Option<&str>,
909 content: &str,
910 properties: Option<serde_json::Value>,
911 allow_transport_owned_message_properties: bool,
912 attachment: Option<NewAttachment>,
913 expires_after: Option<std::time::Duration>,
914 ) -> RuntimeResult<Option<Note>> {
915 self.validate_note_kind(kind)?;
916 crate::secret_gate::reject_reserved_secret_gate_property(properties.as_ref())?;
917 crate::secret_gate::check_note_fields_at(content, name, properties.as_ref(), "note")?;
918 if let Some(ref attachment) = attachment {
919 drop(self.attachments()?);
922 attachment.validate()?;
923 let blob_store = self.blob_store().ok_or_else(|| {
924 RuntimeError::Unconfigured(
925 "trusted ingest attachment requires an installed BlobStore".to_string(),
926 )
927 })?;
928 if !blob_store.exists(&attachment.content_ref).await? {
929 return Err(RuntimeError::InvalidInput(format!(
930 "trusted ingest attachment refers to an unpublished blob: {}",
931 attachment.content_ref
932 )));
933 }
934 }
935 if !allow_transport_owned_message_properties && kind == "message" {
936 if let Some(key) = properties
937 .as_ref()
938 .and_then(serde_json::Value::as_object)
939 .and_then(|supplied| {
940 crate::curation::kind_owned_properties("message")
941 .iter()
942 .copied()
943 .find(|key| supplied.contains_key(*key))
944 })
945 {
946 return Err(RuntimeError::InvalidInput(format!(
947 "`{key}` is transport-owned on a `message` note and cannot be supplied \
948 through `try_create_note`; only the trusted channel-ingest path may \
949 establish quarantine disposition and channel provenance"
950 )));
951 }
952 }
953
954 let ns = token.namespace().as_str();
955 let mut note = Note::new(ns, kind, content);
956 if let Some(retention) = expires_after {
957 let duration_us = i64::try_from(retention.as_micros()).map_err(|_| {
958 RuntimeError::InvalidInput(
959 "trusted ingest retention exceeds i64 microseconds".into(),
960 )
961 })?;
962 note.expires_at = Some(note.created_at.checked_add(duration_us).ok_or_else(|| {
963 RuntimeError::InvalidInput("trusted ingest expiry exceeds i64 microseconds".into())
964 })?);
965 }
966 if let Some(n) = name {
967 note = note.with_name(n);
968 }
969 if let Some(p) = properties {
970 note = note.with_properties(p);
971 }
972
973 let inserted = if let Some(attachment) = attachment {
980 self.raw_notes(token)?
981 .try_insert_note_with_attachments(
982 note.clone(),
983 vec![Attachment::from_new(
984 note.id,
985 AttachmentSubstrate::Note,
986 attachment,
987 note.created_at,
988 )],
989 )
990 .await?
991 } else {
992 self.raw_notes(token)?.try_insert_note(note.clone()).await?
993 };
994 if !inserted {
995 return Ok(None);
996 }
997
998 let mut degradations = Vec::new();
999 match self.text_for_notes(token) {
1000 Ok(fts) => {
1001 if let Err(error) = fts.upsert_document(note_fts_document(¬e)).await {
1002 record_conditional_insert_degradation(
1003 &mut degradations,
1004 note.id,
1005 ConditionalInsertStage::FtsUpsert,
1006 error,
1007 );
1008 }
1009 }
1010 Err(error) => record_conditional_insert_degradation(
1011 &mut degradations,
1012 note.id,
1013 ConditionalInsertStage::FtsAcquisition,
1014 error,
1015 ),
1016 }
1017
1018 let embed_model_names = self.embedding_models_for_note_kind(kind);
1019 for model_name in &embed_model_names {
1020 match self
1021 .embed_document_with_model_outcome_for_token(
1022 token,
1023 model_name,
1024 note_embedding_text_ref(¬e),
1025 )
1026 .await
1027 {
1028 Ok(outcome) => {
1029 if outcome.truncated {
1030 tracing::warn!(
1031 note_id = %note.id,
1032 model = %outcome.model_name,
1033 source_bytes = outcome.source_bytes,
1034 embedded_bytes = outcome.embedded_bytes,
1035 "try_create_note: embedding input truncated; full content stored unchanged"
1036 );
1037 }
1038 match self.vectors_for_model(token, model_name) {
1039 Ok(vs) => {
1040 if let Err(error) = vs
1041 .insert(
1042 note.id,
1043 SubstrateKind::Note,
1044 ns,
1045 "note.content",
1046 vec![outcome.vector],
1047 )
1048 .await
1049 {
1050 record_conditional_insert_degradation(
1051 &mut degradations,
1052 note.id,
1053 ConditionalInsertStage::VectorInsert,
1054 format!("model {model_name}: {error}"),
1055 );
1056 }
1057 }
1058 Err(error) => record_conditional_insert_degradation(
1059 &mut degradations,
1060 note.id,
1061 ConditionalInsertStage::VectorAcquisition,
1062 format!("model {model_name}: {error}"),
1063 ),
1064 }
1065 }
1066 Err(error) => record_conditional_insert_degradation(
1067 &mut degradations,
1068 note.id,
1069 ConditionalInsertStage::Embedding,
1070 format!("model {model_name}: {error}"),
1071 ),
1072 }
1073 }
1074
1075 legacy_post_commit_result("try_create_note", note.id, Some(note), degradations)
1076 }
1077
1078 #[allow(clippy::too_many_arguments)]
1082 async fn create_note_inner(
1083 &self,
1084 token: &NamespaceToken,
1085 kind: &str,
1086 name: Option<&str>,
1087 content: &str,
1088 embedding_content: Option<&str>,
1089 salience: Option<f64>,
1090 decay_factor: Option<f64>,
1091 properties: Option<serde_json::Value>,
1092 annotates: Vec<Uuid>,
1093 embedding_model: Option<&str>,
1094 capture_visibility: bool,
1095 web_receipt: bool,
1096 ) -> RuntimeResult<(
1097 Note,
1098 crate::retrieval::EmbeddingTruncationReport,
1099 Vec<PostCommitDegradation>,
1100 Vec<(String, u64)>,
1101 )> {
1102 self.validate_note_kind(kind)?;
1103 let mut properties = self.derive_note_write_properties(kind, token, properties)?;
1109 crate::secret_gate::reject_reserved_secret_gate_property(properties.as_ref())?;
1110 if web_receipt {
1111 let map = properties
1112 .as_mut()
1113 .and_then(serde_json::Value::as_object_mut)
1114 .expect("web receipt properties are constructed as an object");
1115 map.insert(
1116 crate::secret_gate::RESERVED_WEB_RECEIPT_KEY.to_string(),
1117 serde_json::Value::String(
1118 crate::secret_gate::WEB_RECEIPT_PROVENANCE_VALUE.to_string(),
1119 ),
1120 );
1121 }
1122 crate::secret_gate::check_note_fields_at(content, name, properties.as_ref(), "note")?;
1124 if let Some(ec) = embedding_content {
1130 if ec.is_empty() {
1131 return Err(RuntimeError::InvalidInput(
1132 "embedding_content must not be empty".into(),
1133 ));
1134 }
1135 if ec.len() >= content.len() || !content.starts_with(ec) {
1136 return Err(RuntimeError::InvalidInput(
1137 "embedding_content must be a proper prefix of content".into(),
1138 ));
1139 }
1140 crate::secret_gate::check_at(ec, "note", "embedding_content")?;
1141 }
1142 let ns = token.namespace().as_str();
1143
1144 for &target_id in &annotates {
1147 if !self.substrate_exists_by_id(token, target_id).await? {
1148 return Err(RuntimeError::NotFound(format!(
1149 "create_note annotates target {target_id} not found"
1150 )));
1151 }
1152 }
1153
1154 if let Some(s) = salience {
1157 if !s.is_finite() || !(0.0..=1.0).contains(&s) {
1158 return Err(RuntimeError::InvalidInput(format!(
1159 "salience must be a finite value in [0.0, 1.0]; got {s}"
1160 )));
1161 }
1162 }
1163 if let Some(d) = decay_factor {
1164 if !d.is_finite() || d < 0.0 {
1165 return Err(RuntimeError::InvalidInput(format!(
1166 "decay_factor must be a finite value >= 0.0; got {d}"
1167 )));
1168 }
1169 }
1170
1171 if let Some(model_name) = embedding_model {
1175 self.resolve_embedding_model(Some(model_name))?;
1176 }
1177
1178 let mut note = Note::new(ns, kind, content);
1179 if let Some(s) = salience {
1180 note = note.with_salience(s);
1181 }
1182 if let Some(df) = decay_factor {
1183 note = note.with_decay(df);
1184 }
1185 if let Some(n) = name {
1186 note = note.with_name(n);
1187 }
1188 if let Some(p) = properties {
1189 note = note.with_properties(p);
1190 }
1191 let notes = if web_receipt {
1192 self.raw_notes(token)?
1193 } else {
1194 self.notes(token)?
1195 };
1196 notes.upsert_note(note.clone()).await?;
1197
1198 let embed_model_names: Vec<String> = if let Some(m) = embedding_model {
1204 vec![m.to_string()]
1205 } else {
1206 self.embedding_models_for_note_kind(kind)
1207 };
1208
1209 {
1211 #[cfg(any(test, feature = "fault-injection"))]
1217 let fts_inject = consume_fault(&FTS_FAIL_NS, ns);
1218 #[cfg(not(any(test, feature = "fault-injection")))]
1219 let fts_inject = false;
1220 let fts_result: RuntimeResult<()> = if fts_inject {
1221 Err(RuntimeError::Internal("injected FTS failure".to_string()))
1222 } else {
1223 let statements =
1224 khive_db::stores::text::delete_document_statements("fts_notes", ns, note.id)
1225 .into_iter()
1226 .chain(khive_db::stores::text::insert_document_statements(
1227 "fts_notes",
1228 ¬e_fts_document(¬e),
1229 ))
1230 .collect();
1231 self.apply_note_index_revision(¬e, statements)
1232 .await
1233 .map(|_| ())
1234 };
1235
1236 if let Err(e) = fts_result {
1237 self.compensate_note_creation(¬e).await;
1238 return Err(e);
1239 }
1240 }
1241
1242 let canonical_embed_text = note_embedding_text_ref(¬e);
1252 let embed_text = embedding_content.unwrap_or(canonical_embed_text);
1253
1254 let mut embedding_report = crate::retrieval::EmbeddingTruncationReport::default();
1255 let mut vector_fences = Vec::with_capacity(embed_model_names.len());
1256 if embed_model_names.len() == 1 {
1257 let model_name = &embed_model_names[0];
1259 let vec_result = self
1260 .embed_document_with_model_outcome_for_token(token, model_name, embed_text)
1261 .await;
1262
1263 #[cfg(any(test, feature = "fault-injection"))]
1273 let vec_inject = {
1274 let ns_inject = consume_fault(&VECTOR_FAIL_NS, ns);
1275 let count_inject = VECTOR_FAIL_AFTER.with(|cell| match cell.get() {
1276 Some(0) => {
1277 cell.set(None);
1278 true
1279 }
1280 Some(n) => {
1281 cell.set(Some(n - 1));
1282 false
1283 }
1284 None => false,
1285 });
1286 ns_inject || count_inject
1287 };
1288 #[cfg(not(any(test, feature = "fault-injection")))]
1289 let vec_inject = false;
1290 let vec_result: RuntimeResult<crate::retrieval::DocumentEmbeddingOutcome> =
1291 if vec_inject {
1292 Err(RuntimeError::Internal(
1293 "injected vector failure".to_string(),
1294 ))
1295 } else {
1296 vec_result
1297 };
1298
1299 let single_model_result: RuntimeResult<()> = match vec_result {
1300 Ok(outcome) => {
1301 embedding_report.observe(&outcome);
1302 if capture_visibility {
1303 match self
1304 .publish_note_vector_revision_with_seq(
1305 token,
1306 ¬e,
1307 model_name,
1308 &outcome.vector,
1309 )
1310 .await
1311 {
1312 Ok(Some(seq)) => {
1313 vector_fences.push((model_name.clone(), seq));
1314 Ok(())
1315 }
1316 Ok(None) => Ok(()),
1317 Err(error) => Err(error),
1318 }
1319 } else {
1320 self.publish_note_vector_revision(token, ¬e, model_name, &outcome.vector)
1321 .await
1322 .map(|_| ())
1323 }
1324 }
1325 Err(e) => Err(e),
1326 };
1327 if let Err(e) = single_model_result {
1328 self.compensate_note_creation(¬e).await;
1329 return Err(e);
1330 }
1331 } else if !embed_model_names.is_empty() {
1332 let rt_clone = self.clone();
1335 let content_owned: std::sync::Arc<str> = std::sync::Arc::from(embed_text);
1338 let usage_ctx = crate::usage::current();
1339 let mut join_set = tokio::task::JoinSet::new();
1340 for (idx, model_name) in embed_model_names.iter().enumerate() {
1341 let rt = rt_clone.clone();
1342 let text = std::sync::Arc::clone(&content_owned);
1343 let name = model_name.clone();
1344 let ctx = usage_ctx.clone();
1345 let token = (*token).clone();
1346 join_set.spawn(crate::runtime::inherit_request_embedder_scope(async move {
1347 let fut = rt.embed_document_with_model_outcome_for_token(
1348 &token,
1349 &name,
1350 text.as_ref(),
1351 );
1352 let result = match ctx {
1353 Some(ctx) => crate::usage::scope(ctx, fut).await,
1354 None => fut.await,
1355 };
1356 (idx, result)
1357 }));
1358 }
1359 let outcomes = match drain_embed_join_set(join_set, embed_model_names.len()).await {
1363 Ok(outcomes) => outcomes,
1364 Err(e) => {
1365 self.compensate_note_creation(¬e).await;
1366 return Err(e);
1367 }
1368 };
1369 for (model_name, outcome) in embed_model_names.iter().zip(outcomes) {
1371 embedding_report.observe(&outcome);
1372 let insert_result = if capture_visibility {
1373 self.publish_note_vector_revision_with_seq(
1374 token,
1375 ¬e,
1376 model_name,
1377 &outcome.vector,
1378 )
1379 .await
1380 .map(|seq| {
1381 if let Some(seq) = seq {
1382 vector_fences.push((model_name.clone(), seq));
1383 }
1384 })
1385 } else {
1386 self.publish_note_vector_revision(token, ¬e, model_name, &outcome.vector)
1387 .await
1388 .map(|_| ())
1389 };
1390 if let Err(e) = insert_result {
1391 self.compensate_note_creation(¬e).await;
1392 return Err(e);
1393 }
1394 }
1395 }
1396
1397 let mut created_edges: Vec<Uuid> = Vec::with_capacity(annotates.len());
1402
1403 #[cfg(test)]
1406 let annotates_iter: Vec<(usize, Uuid)> = annotates
1407 .iter()
1408 .enumerate()
1409 .map(|(i, &id)| (i, id))
1410 .collect();
1411 #[cfg(test)]
1412 macro_rules! next_target {
1413 ($pair:expr) => {
1414 $pair.1
1415 };
1416 }
1417 #[cfg(not(test))]
1418 let annotates_iter: Vec<Uuid> = annotates.to_vec();
1419 #[cfg(not(test))]
1420 macro_rules! next_target {
1421 ($pair:expr) => {
1422 $pair
1423 };
1424 }
1425
1426 for pair in annotates_iter {
1427 let target_id = next_target!(pair);
1428
1429 #[cfg(test)]
1431 let injected_err: Option<RuntimeError> = {
1432 let call_idx = pair.0;
1433 LINK_FAIL_AFTER.with(|cell| {
1434 let n = cell.get();
1435 if n > 0 && call_idx + 1 == n {
1436 cell.set(0); Some(RuntimeError::Internal("injected link failure".to_string()))
1438 } else {
1439 None
1440 }
1441 })
1442 };
1443 #[cfg(not(test))]
1444 let injected_err: Option<RuntimeError> = None;
1445
1446 let link_result = if let Some(e) = injected_err {
1447 Err(e)
1448 } else {
1449 self.link(
1450 token,
1451 note.id,
1452 target_id,
1453 EdgeRelation::Annotates,
1454 1.0,
1455 None,
1456 )
1457 .await
1458 };
1459
1460 match link_result {
1461 Ok(edge) => created_edges.push(edge.id.into()),
1462 Err(e) => {
1463 let edge_ids = created_edges
1468 .iter()
1469 .map(Uuid::to_string)
1470 .collect::<Vec<_>>()
1471 .join(", ");
1472 match self.compensate_note_creation_with_edges(¬e).await {
1473 Ok(true) => return Err(e),
1474 Ok(false) => {
1475 return Err(RuntimeError::Internal(format!(
1476 "create_note: annotates link failed: {e}; note {} changed before \
1477 compensation, retaining its incident edges [{edge_ids}]",
1478 note.id
1479 )));
1480 }
1481 Err(cleanup_error) => {
1482 return Err(RuntimeError::Internal(format!(
1483 "create_note: annotates link failed: {e}; compensation failed \
1484 for note {} and retained edges [{edge_ids}]: {cleanup_error}; \
1485 note and edges remain for reconciliation",
1486 note.id
1487 )));
1488 }
1489 }
1490 }
1491 }
1492 }
1493
1494 let created_event = khive_storage::event::Event::new(
1499 note.namespace.clone(),
1500 "create",
1501 EventKind::NoteCreated,
1502 SubstrateKind::Note,
1503 "",
1504 )
1505 .with_target(note.id)
1506 .with_payload(serde_json::json!({
1507 "id": note.id,
1508 "namespace": note.namespace,
1509 "kind": note.kind,
1510 "salience": note.salience,
1511 }));
1512 let event_result = match self.events(token) {
1513 Ok(store) => store
1514 .append_event(created_event)
1515 .await
1516 .map_err(RuntimeError::from),
1517 Err(error) => Err(error),
1518 };
1519 let mut degradations = Vec::new();
1520 if let Err(error) = event_result {
1521 record_post_commit_degradation(
1522 &mut degradations,
1523 "create_note",
1524 note.id,
1525 "event_append",
1526 error,
1527 );
1528 }
1529
1530 vector_fences.sort_by(|a, b| a.0.cmp(&b.0));
1531 Ok((note, embedding_report, degradations, vector_fences))
1532 }
1533
1534 #[allow(clippy::too_many_arguments)]
1554 pub async fn search_notes(
1555 &self,
1556 token: &NamespaceToken,
1557 query_text: &str,
1558 query_vector: Option<Vec<f32>>,
1559 limit: u32,
1560 note_kind: Option<&str>,
1561 include_superseded: bool,
1562 tags_any: &[String],
1563 properties_filter: Option<&serde_json::Value>,
1564 ) -> RuntimeResult<Vec<NoteSearchHit>> {
1565 self.search_notes_with_text_mode(
1566 token,
1567 query_text,
1568 query_vector,
1569 limit,
1570 note_kind,
1571 include_superseded,
1572 tags_any,
1573 properties_filter,
1574 TextQueryMode::Plain,
1575 )
1576 .await
1577 }
1578
1579 #[allow(clippy::too_many_arguments)]
1581 pub async fn search_notes_with_text_mode(
1582 &self,
1583 token: &NamespaceToken,
1584 query_text: &str,
1585 query_vector: Option<Vec<f32>>,
1586 limit: u32,
1587 note_kind: Option<&str>,
1588 include_superseded: bool,
1589 tags_any: &[String],
1590 properties_filter: Option<&serde_json::Value>,
1591 text_mode: TextQueryMode,
1592 ) -> RuntimeResult<Vec<NoteSearchHit>> {
1593 let (hits, _note_status_dropped) = self
1594 .search_notes_with_text_mode_and_status(
1595 token,
1596 query_text,
1597 query_vector,
1598 limit,
1599 note_kind,
1600 include_superseded,
1601 tags_any,
1602 properties_filter,
1603 text_mode,
1604 khive_storage::note::NoteStatusSelector::Active,
1605 None,
1606 )
1607 .await?;
1608 Ok(hits)
1609 }
1610
1611 #[allow(clippy::too_many_arguments)]
1618 pub async fn search_notes_outcome(
1619 &self,
1620 token: &NamespaceToken,
1621 query_text: &str,
1622 limit: u32,
1623 note_kind: Option<&str>,
1624 include_superseded: bool,
1625 tags_any: &[String],
1626 properties_filter: Option<&serde_json::Value>,
1627 ) -> RuntimeResult<NoteSearchOutcome> {
1628 self.search_notes_outcome_with_text_mode(
1629 token,
1630 query_text,
1631 limit,
1632 note_kind,
1633 include_superseded,
1634 tags_any,
1635 properties_filter,
1636 TextQueryMode::Plain,
1637 )
1638 .await
1639 }
1640
1641 #[allow(clippy::too_many_arguments)]
1643 pub async fn search_notes_outcome_with_text_mode(
1644 &self,
1645 token: &NamespaceToken,
1646 query_text: &str,
1647 limit: u32,
1648 note_kind: Option<&str>,
1649 include_superseded: bool,
1650 tags_any: &[String],
1651 properties_filter: Option<&serde_json::Value>,
1652 text_mode: TextQueryMode,
1653 ) -> RuntimeResult<NoteSearchOutcome> {
1654 let (outcome, _note_status_dropped) = self
1655 .search_notes_outcome_with_text_mode_and_status(
1656 token,
1657 query_text,
1658 limit,
1659 note_kind,
1660 include_superseded,
1661 tags_any,
1662 properties_filter,
1663 text_mode,
1664 khive_storage::note::NoteStatusSelector::Active,
1665 None,
1666 )
1667 .await?;
1668 Ok(outcome)
1669 }
1670
1671 pub async fn restore_note(
1677 &self,
1678 token: &NamespaceToken,
1679 id: Uuid,
1680 ) -> RuntimeResult<Option<(Note, bool)>> {
1681 let Some(note) = self.notes(token)?.get_note_including_deleted(id).await? else {
1682 return Ok(None);
1683 };
1684 if note.namespace != token.namespace().as_str() {
1685 return Ok(None);
1686 }
1687 if note.deleted_at.is_none() {
1688 return Ok(Some((note, false)));
1689 }
1690 if let Some(key) = note.key.as_deref() {
1691 if let Some(holder) = self
1692 .notes(token)?
1693 .get_live_notes_by_key(¬e.namespace, key, Some(¬e.kind))
1694 .await?
1695 .into_iter()
1696 .find(|holder| holder.id != note.id)
1697 {
1698 return Err(restore_key_conflict(key, &holder));
1699 }
1700 }
1701 let updated_at =
1702 Utc::now()
1703 .timestamp_micros()
1704 .max(note.updated_at.checked_add(1).ok_or_else(|| {
1705 RuntimeError::Internal(format!(
1706 "note {id} updated_at is already at i64::MAX and cannot advance"
1707 ))
1708 })?);
1709 let mut params = vec![
1710 SqlValue::Text("active".into()),
1711 SqlValue::Integer(updated_at),
1712 SqlValue::Text(id.to_string()),
1713 SqlValue::Text(note.namespace.clone()),
1714 SqlValue::Text(note.kind.clone()),
1715 ];
1716 let key_clause = if let Some(key) = note.key.as_deref() {
1717 params.push(SqlValue::Text(key.to_owned()));
1718 format!(
1719 " AND (key IS NULL OR NOT EXISTS (SELECT 1 FROM notes live \
1720 WHERE live.namespace=?4 AND live.kind=?5 AND live.key=?{} \
1721 AND live.deleted_at IS NULL AND live.id != notes.id))",
1722 params.len()
1723 )
1724 } else {
1725 String::new()
1726 };
1727 let mut restored = note.clone();
1728 restored.status = "active".into();
1729 restored.deleted_at = None;
1730 restored.updated_at = updated_at;
1731 restored.version = restored
1732 .version
1733 .checked_add(1)
1734 .ok_or_else(|| RuntimeError::Internal(format!("note {id} version is exhausted")))?;
1735 let mut statements = vec![PlanStatement {
1736 statement: SqlStatement {
1737 sql: format!(
1738 "UPDATE notes SET status=?1, deleted_at=NULL, updated_at=?2 \
1739 WHERE id=?3 AND namespace=?4 AND kind=?5 AND deleted_at IS NOT NULL{key_clause}"
1740 ),
1741 params,
1742 label: Some("note-restore".into()),
1743 },
1744 guard: Some(AffectedRowGuard::exactly(1)),
1745 }];
1746 for statement in
1748 khive_db::stores::text::delete_document_statements("fts_notes", &restored.namespace, id)
1749 .into_iter()
1750 .chain(insert_document_statements(
1751 "fts_notes",
1752 ¬e_fts_document(&restored),
1753 ))
1754 {
1755 statements.push(PlanStatement {
1756 statement,
1757 guard: None,
1758 });
1759 }
1760 let plan = AtomicOpPlan::Update(Box::new(UpdatePlan {
1761 graph_effects: Vec::new(),
1762 target_id: id,
1763 statements,
1764 post_commit: PostCommitEffect::None,
1765 edge_natural_key: None,
1766 idempotent_noop: false,
1767 entity_guard: None,
1768 note_guard: None,
1769 note_vector_purge: None,
1770 note_embedding_inheritance: None,
1771 }));
1772 match run_atomic_unit(self.sql().as_ref(), vec![plan]).await {
1773 Ok(AtomicRunOutcome::Committed { .. }) => {
1774 #[cfg(any(test, feature = "fault-injection"))]
1775 if consume_fault(&FTS_FAIL_NS, &restored.namespace) {
1776 return Err(restore_reindex_failed(
1777 "note",
1778 id,
1779 RuntimeError::Internal("injected FTS failure".to_string()),
1780 ));
1781 }
1782 let reindexed = self.reindex_note_with_report(token, &restored).await;
1783 let report = reindexed.map_err(|e| restore_reindex_failed("note", id, e))?;
1784 let degradations = report.post_commit_degradations();
1785 legacy_post_commit_result("restore_note", id, Some((restored, true)), degradations)
1786 }
1787 Ok(AtomicRunOutcome::RolledBack {
1788 failure: AtomicOpFailure::GuardFailed { .. },
1789 ..
1790 }) => {
1791 if let Some(key) = note.key.as_deref() {
1792 if let Some(holder) = self
1793 .notes(token)?
1794 .get_live_notes_by_key(¬e.namespace, key, Some(¬e.kind))
1795 .await?
1796 .into_iter()
1797 .find(|holder| holder.id != note.id)
1798 {
1799 return Err(restore_key_conflict(key, &holder));
1800 }
1801 }
1802 Err(RuntimeError::NotFound(format!(
1803 "note {id} is no longer a caller-owned tombstone"
1804 )))
1805 }
1806 Ok(AtomicRunOutcome::RolledBack { failure, .. }) => Err(RuntimeError::Internal(
1807 format!("note restore rolled back: {failure:?}"),
1808 )),
1809 Err(error) => Err(RuntimeError::Storage(error.0)),
1810 }
1811 }
1812}
1813
1814#[derive(Clone, Debug)]
1817pub struct LinkSpec {
1818 pub namespace: Option<String>,
1819 pub source_id: Uuid,
1820 pub target_id: Uuid,
1821 pub relation: EdgeRelation,
1822 pub weight: f64,
1823 pub metadata: Option<serde_json::Value>,
1824 pub resurrect: bool,
1825}
1826
1827#[derive(Clone, Debug)]
1835pub struct EntityCreateSpec {
1836 pub kind: String,
1837 pub entity_type: Option<String>,
1838 pub name: String,
1839 pub description: Option<String>,
1840 pub properties: Option<serde_json::Value>,
1841 pub tags: Vec<String>,
1842 pub aliases: Vec<String>,
1845}
1846
1847#[cfg(test)]
1853#[path = "operations_tests.rs"]
1854mod tests;