1use super::*;
4use crate::secret_gate_finalizer::entity_admission::{
5 prepare_entity_admission, EntityAdmission, EntityEntryPoint,
6};
7use crate::EntityCandidateMutation;
8use khive_db::stores::attachment::attachment_upsert_statement;
9use khive_db::stores::entity::{entity_key_claim_statement, ENTITY_KEY_CLAIM_LABEL};
10use khive_storage::{BoxFuture, SqlWriter, StorageResult};
11
12pub(super) enum EntityCreateWrite {
15 Written(
16 Box<Entity>,
17 crate::retrieval::EmbeddingTruncationReport,
18 Vec<PostCommitDegradation>,
19 ),
20 KeyHeld,
23}
24
25impl EntityCreateWrite {
26 pub(super) fn into_written(
27 self,
28 ) -> RuntimeResult<(
29 Entity,
30 crate::retrieval::EmbeddingTruncationReport,
31 Vec<PostCommitDegradation>,
32 )> {
33 match self {
34 Self::Written(entity, report, degradations) => Ok((*entity, report, degradations)),
35 Self::KeyHeld => Err(RuntimeError::Internal(
36 "an unkeyed entity create reported a held key".into(),
37 )),
38 }
39 }
40}
41
42fn claimed_entity_create_event(entity: &Entity) -> Event {
43 let mut event = Event::new(
44 entity.namespace.clone(),
45 "create",
46 EventKind::EntityCreated,
47 SubstrateKind::Entity,
48 "",
49 )
50 .with_target(entity.id)
51 .with_payload(serde_json::json!({
52 "id": entity.id,
53 "namespace": &entity.namespace,
54 "kind": &entity.kind,
55 }));
56 let event_seed = Uuid::new_v5(&Uuid::NAMESPACE_URL, b"khive:claimed-entity-create:v1");
57 let mut event_key = Vec::with_capacity(24);
58 event_key.extend_from_slice(entity.id.as_bytes());
59 event_key.extend_from_slice(&entity.created_at.to_be_bytes());
60 event.id = Uuid::new_v5(&event_seed, &event_key);
61 event
62}
63
64impl KhiveRuntime {
65 pub async fn create_workspace_document_with_cursor<F>(
67 &self,
68 registry: &crate::VerbRegistry,
69 token: &crate::NamespaceToken,
70 document: (&str, &str),
71 source: (&str, &str, &str),
72 previous: Option<khive_types::Id128>,
73 cursor: F,
74 ) -> crate::RuntimeResult<(khive_types::Id128, crate::RuntimeResult<()>)>
75 where
76 F: for<'w> FnOnce(
77 &'w mut dyn SqlWriter,
78 khive_types::Id128,
79 ) -> BoxFuture<'w, StorageResult<()>>
80 + Send
81 + 'static,
82 {
83 use crate::atomic_prepare::apply_post_commit_effects;
84 use crate::atomic_runner::PreparedAtomicError::{Refused, Storage};
85 use crate::atomic_runner::{
86 apply_plan_preserving_storage, run_prepared_atomic_unit, AtomicOpFailure, AtomicOpPlan,
87 PlanExecutionFailure, PreparedAtomicOp, PreparedAtomicOutcome,
88 };
89 use crate::canonical_apply::prepare_canonical_changeset;
90 use khive_changeset::{
91 ChangeSet, CreateOp, CreateTarget, EntityCreateFields, Envelope, LinkOp, Op,
92 };
93 use khive_storage::{SqlStatement, StorageError, WriterTaskRequestState};
94 use khive_types::{EdgeRelation, EntityKind, Id128, PropertyValue, Timestamp};
95 use std::mem::take;
96 use std::sync::{Arc, Mutex};
97 if self.backend_id().as_str() != crate::config::BackendId::MAIN {
98 return Err(RuntimeError::InvalidInput(format!(
99 "workspace mirror requires main backend; assigned backend: {}",
100 self.backend_id()
101 )));
102 }
103 let staged_at = u64::try_from(chrono::Utc::now().timestamp_micros())
104 .map(Timestamp::from_micros)
105 .map_err(|_| {
106 RuntimeError::Internal("workspace staging time precedes Unix epoch".into())
107 })?;
108 let id = Id128::from_bytes(*Uuid::new_v4().as_bytes());
109 let properties = [
110 ("source_uri".into(), PropertyValue::String(source.0.into())),
111 ("source_type".into(), PropertyValue::String(source.1.into())),
112 ("checksum".into(), PropertyValue::String(source.2.into())),
113 ]
114 .into_iter()
115 .collect();
116 let mut ops = vec![Op::Create(CreateOp {
117 id,
118 namespace: token.namespace().clone(),
119 target: CreateTarget::Entity(EntityCreateFields {
120 entity_kind: EntityKind::Document,
121 entity_type: None,
122 name: document.0.into(),
123 description: Some(document.1.into()),
124 properties,
125 tags: Vec::new(),
126 key: None,
127 aliases: vec![],
128 }),
129 })];
130 if let Some(previous) = previous {
131 ops.push(Op::Link(LinkOp {
132 id: Id128::from_bytes(*Uuid::new_v4().as_bytes()),
133 namespace: token.namespace().clone(),
134 source: id,
135 target: previous,
136 relation: EdgeRelation::Supersedes,
137 weight: 1.0,
138 properties: Default::default(),
139 }));
140 }
141 let changeset = ChangeSet::new(
142 Envelope::new("workspace.mirror", "deterministic", staged_at),
143 ops,
144 );
145 let plans = prepare_canonical_changeset(self, registry, token, &changeset).await?;
146 let handles = Arc::new(Mutex::new(Vec::<crate::EntityFinalizationPlan>::new()));
147 let attempted = Arc::clone(&handles);
148 let prepared: PreparedAtomicOp<(), (usize, AtomicOpFailure)> = Box::new(move |writer| {
149 Box::pin(async move {
150 let mut effects = Vec::new();
151 for (index, plan) in plans.into_iter().enumerate() {
152 let savepoint = format!("adr099_atomic_op_{index}");
153 writer
154 .execute(SqlStatement::new(format!("SAVEPOINT {savepoint}"), vec![]))
155 .await?;
156 let materialized = match plan {
157 AtomicOpPlan::Canonical(canonical) => {
158 crate::canonical_apply::materialize(writer, &canonical).await
159 }
160 plan => Ok(plan),
161 };
162 let applied = match materialized {
163 Ok(plan) => {
164 if let AtomicOpPlan::FinalizeEntity(finalizer) = &plan {
165 attempted
166 .lock()
167 .expect("workspace finalizer lock poisoned")
168 .push(finalizer.for_settlement());
169 }
170 apply_plan_preserving_storage(writer, &plan, false).await
171 }
172 Err(failure) => Err(PlanExecutionFailure::Operation(failure)),
173 };
174 match applied {
175 Ok(applied) => {
176 writer
177 .execute(SqlStatement::new(format!("RELEASE {savepoint}"), vec![]))
178 .await?;
179 if let Some(effect) = applied.effect {
180 effects.push(effect);
181 }
182 }
183 Err(failure) => {
184 let _ = writer
185 .execute(SqlStatement::new(
186 format!("ROLLBACK TO {savepoint}"),
187 vec![],
188 ))
189 .await;
190 let _ = writer
191 .execute(SqlStatement::new(format!("RELEASE {savepoint}"), vec![]))
192 .await;
193 return Err(match failure {
194 PlanExecutionFailure::Storage { source, .. } => Storage(source),
195 PlanExecutionFailure::Operation(failure) => Refused {
196 failure: (index, failure),
197 message: format!("workspace atomic unit aborted at op {index}"),
198 },
199 });
200 }
201 }
202 }
203 cursor(writer, id).await.map_err(Storage)?;
204 Ok(((), effects))
205 })
206 });
207 let access = self.sql();
208 let outcome = run_prepared_atomic_unit(access.as_ref(), prepared).await;
209 let handles = take(&mut *handles.lock().expect("workspace finalizer lock poisoned"));
210 match outcome {
211 Ok(PreparedAtomicOutcome::Committed { post_commit, .. }) => {
212 for plan in handles {
213 plan.finish_commit();
214 }
215 let effects = apply_post_commit_effects(self, token, post_commit).await;
216 Ok((id, effects))
217 }
218 Ok(PreparedAtomicOutcome::RolledBack((index, failure))) => {
219 let mut native_source = None;
220 for plan in handles {
221 if let Some(source) = plan.finish_rollback(access.as_ref()).await {
222 native_source = Some(source);
223 }
224 }
225 if let Some(source) = native_source {
226 return Err(RuntimeError::Storage(
227 StorageError::WriterTaskRequestFailed {
228 request_state: WriterTaskRequestState::TransactionRolledBack,
229 source: Box::new(source),
230 },
231 ));
232 }
233 Err(RuntimeError::Internal(format!(
234 "workspace atomic unit rolled back at op {index}: {failure:?}"
235 )))
236 }
237 Err(error) => {
238 if matches!(
239 &error,
240 StorageError::WriterTaskRequestFailed {
241 request_state: WriterTaskRequestState::TransactionRolledBack,
242 ..
243 }
244 ) {
245 for plan in handles {
246 let _ = plan.finish_rollback(access.as_ref()).await;
247 }
248 }
249 Err(RuntimeError::Storage(error))
250 }
251 }
252 }
253
254 pub async fn claim_entity_if_absent(
257 &self,
258 token: &NamespaceToken,
259 spec: EntityClaimSpec,
260 ) -> RuntimeResult<(Entity, bool)> {
261 self.validate_entity_kind(&spec.kind)?;
262 let entity_type =
263 self.validate_entity_type_for_kind(&spec.kind, spec.entity_type.as_deref())?;
264 crate::secret_gate::reject_reserved_secret_gate_property(spec.properties.as_ref())?;
265
266 let mut proposed = Entity::new(token.namespace().as_str(), &spec.kind, &spec.name);
267 proposed.id = spec.id;
268 proposed.entity_type = entity_type.clone();
269 proposed.description = spec.description;
270 proposed.properties = spec.properties;
271 proposed.tags = spec.tags;
272
273 let admission = prepare_entity_admission(token, EntityEntryPoint::Claim, proposed)?;
274 let store = self.entities(token)?;
275 let (inserted, indexes_committed) = match admission {
276 EntityAdmission::Legacy(candidate) => {
277 proposed = candidate;
278 (
279 store.insert_entity_if_absent(proposed.clone()).await?,
280 false,
281 )
282 }
283 EntityAdmission::Exempt(prepared) => {
284 proposed = prepared.entity().clone();
285 let (mut required, _) = self
286 .prepare_admitted_entity_indexes(token, &proposed, &[], true)
287 .await?;
288 let _ = self.events(token)?;
289 let event = crate::EventAttribution::from_token(token)
290 .stamp(claimed_entity_create_event(&proposed));
291 required.extend(
292 khive_db::stores::event::event_insert_statements(&event)
293 .map_err(|error| RuntimeError::Internal(error.to_string()))?
294 .into_iter()
295 .map(|statement| PlanStatement {
296 statement,
297 guard: Some(AffectedRowGuard::exactly(1)),
298 }),
299 );
300 let plan = prepared.into_plan(
301 EntityCandidateMutation::CreateIfAbsent,
302 required,
303 PostCommitEffect::None,
304 )?;
305 match run_atomic_unit(
306 self.sql().as_ref(),
307 vec![AtomicOpPlan::FinalizeEntity(Box::new(plan))],
308 )
309 .await
310 {
311 Ok(AtomicRunOutcome::Committed { .. }) => (true, true),
312 Ok(AtomicRunOutcome::RolledBack {
313 failure: crate::atomic_runner::AtomicOpFailure::GuardFailed { .. },
314 ..
315 }) => (false, false),
316 Ok(AtomicRunOutcome::RolledBack { failure, .. }) => {
317 return Err(RuntimeError::Internal(format!(
318 "entity claim finalization rolled back: {failure:?}"
319 )));
320 }
321 Err(error) => return Err(RuntimeError::Storage(error.0)),
322 }
323 }
324 };
325 let entity = if inserted {
326 proposed
327 } else {
328 store
329 .get_entity_including_deleted(spec.id)
330 .await?
331 .ok_or_else(|| {
332 RuntimeError::Internal(format!(
333 "entity claim {} lost but the winning row is missing",
334 spec.id
335 ))
336 })?
337 };
338 if entity.deleted_at.is_some() {
339 return Err(RuntimeError::InvalidInput(format!(
340 "entity claim {} is soft-deleted; restore it explicitly",
341 entity.id
342 )));
343 }
344 if entity.namespace != token.namespace().as_str()
345 || entity.kind != spec.kind
346 || entity.entity_type.as_deref() != entity_type.as_deref()
347 || !entity.name.eq_ignore_ascii_case(&spec.name)
348 || !entity
349 .tags
350 .iter()
351 .any(|tag| tag.eq_ignore_ascii_case(&spec.identity_tag))
352 {
353 return Err(RuntimeError::InvalidInput(format!(
354 "entity claim {} belongs to a different record",
355 entity.id
356 )));
357 }
358
359 if !indexes_committed {
360 self.ensure_claimed_entity_create_event(token, &entity)
361 .await?;
362 self.reindex_claimed_entity(token, &entity).await?;
363 }
364 Ok((entity, inserted))
365 }
366
367 pub async fn ensure_claimed_entity_create_event(
370 &self,
371 token: &NamespaceToken,
372 entity: &Entity,
373 ) -> RuntimeResult<()> {
374 if entity.namespace != token.namespace().as_str() || entity.deleted_at.is_some() {
375 return Err(RuntimeError::InvalidInput(format!(
376 "entity {} is not a live row in the write namespace",
377 entity.id
378 )));
379 }
380 let events = self.events(token).map_err(|error| {
381 RuntimeError::Internal(format!(
382 "entity {} persists but its create event store is unavailable: {error}",
383 entity.id
384 ))
385 })?;
386 let filter = EventFilter {
387 target_id: Some(entity.id),
388 kinds: vec![EventKind::EntityCreated],
389 verbs: vec!["create".into()],
390 substrates: vec![SubstrateKind::Entity],
391 after: Some(entity.created_at.saturating_sub(1)),
392 ..EventFilter::default()
393 };
394 let page = PageRequest {
395 offset: 0,
396 limit: 1,
397 };
398 if !events
399 .query_events(filter.clone(), page.clone())
400 .await?
401 .items
402 .is_empty()
403 {
404 return Ok(());
405 }
406
407 let event = claimed_entity_create_event(entity);
408 if let Err(error) = events.append_event(event).await {
409 if events.query_events(filter, page).await?.items.is_empty() {
410 return Err(RuntimeError::Internal(format!(
411 "entity {} persists but its create event failed: {error}",
412 entity.id
413 )));
414 }
415 }
416 Ok(())
417 }
418
419 pub async fn reindex_claimed_entity(
422 &self,
423 token: &NamespaceToken,
424 entity: &Entity,
425 ) -> RuntimeResult<()> {
426 if entity.namespace != token.namespace().as_str() || entity.deleted_at.is_some() {
427 return Err(RuntimeError::InvalidInput(format!(
428 "entity {} is not a live row in the write namespace",
429 entity.id
430 )));
431 }
432 let doc = entity_fts_document(entity);
433 let embed_body = doc.body.clone();
434 #[cfg(any(test, feature = "fault-injection"))]
435 let fts_inject = consume_fault(&FTS_FAIL_NS, &entity.namespace);
436 #[cfg(not(any(test, feature = "fault-injection")))]
437 let fts_inject = false;
438 let fts_result = if fts_inject {
439 Err(RuntimeError::Internal("injected FTS failure".into()))
440 } else {
441 match self.text(token) {
442 Ok(_) => {
443 let statements = khive_db::stores::text::delete_document_statements(
444 "fts_entities",
445 &entity.namespace,
446 entity.id,
447 )
448 .into_iter()
449 .chain(khive_db::stores::text::insert_document_statements(
450 "fts_entities",
451 &doc,
452 ))
453 .collect();
454 self.apply_entity_index_revision(entity, statements).await
455 }
456 Err(error) => Err(error),
457 }
458 };
459 let published = fts_result.map_err(|error| {
460 RuntimeError::Internal(format!(
461 "entity {} persists but its text index failed: {error}",
462 entity.id
463 ))
464 })?;
465 if !published {
466 return Err(RuntimeError::Internal(format!(
467 "entity {} persists but changed concurrently before text index publication; retry against the current row",
468 entity.id
469 )));
470 }
471
472 for model_name in self.registered_embedding_model_names() {
473 let outcome = self
474 .embed_document_with_model_outcome_for_token(token, &model_name, &embed_body)
475 .await
476 .map_err(|error| {
477 RuntimeError::Internal(format!(
478 "entity {} persists but model {model_name} embedding failed: {error}",
479 entity.id
480 ))
481 })?;
482 #[cfg(any(test, feature = "fault-injection"))]
483 let vector_inject = consume_fault(&VECTOR_FAIL_NS, &entity.namespace);
484 #[cfg(not(any(test, feature = "fault-injection")))]
485 let vector_inject = false;
486 if vector_inject {
487 return Err(RuntimeError::Internal(format!(
488 "entity {} persists but model {model_name} vector indexing failed: injected vector failure",
489 entity.id
490 )));
491 }
492 let published = self
493 .publish_entity_vector_revision(token, entity, &model_name, &outcome.vector)
494 .await
495 .map_err(|error| {
496 RuntimeError::Internal(format!(
497 "entity {} persists but model {model_name} vector indexing failed: {error}",
498 entity.id
499 ))
500 })?;
501 if !published {
502 return Err(RuntimeError::Internal(format!(
503 "entity {} persists but changed concurrently before model {model_name} vector publication; retry against the current row",
504 entity.id
505 )));
506 }
507 }
508 Ok(())
509 }
510
511 #[allow(clippy::too_many_arguments)]
522 #[cfg(test)]
523 pub(crate) async fn create_entity(
524 &self,
525 token: &NamespaceToken,
526 kind: &str,
527 entity_type: Option<&str>,
528 name: &str,
529 description: Option<&str>,
530 properties: Option<serde_json::Value>,
531 tags: Vec<String>,
532 ) -> RuntimeResult<Entity> {
533 let (entity, _, degradations) = self
534 .create_entity_with_embedding_report_inner(
535 token,
536 kind,
537 entity_type,
538 name,
539 description,
540 properties,
541 tags,
542 Vec::new(),
543 None,
544 &EntityAliasChange::default(),
545 )
546 .await?
547 .into_written()?;
548 legacy_post_commit_result("create_entity", entity.id, entity, degradations)
549 }
550
551 #[allow(clippy::too_many_arguments)]
564 pub async fn create_entity_with_attachments(
565 &self,
566 token: &NamespaceToken,
567 kind: &str,
568 entity_type: Option<&str>,
569 name: &str,
570 description: Option<&str>,
571 properties: Option<serde_json::Value>,
572 tags: Vec<String>,
573 attachments: Vec<NewAttachment>,
574 ) -> RuntimeResult<Entity> {
575 let (entity, embedding, degradations) = self
576 .create_entity_with_attachments_inner(
577 token,
578 kind,
579 entity_type,
580 name,
581 description,
582 properties,
583 tags,
584 attachments,
585 )
586 .await?;
587 legacy_post_commit_result_with_embedding(
588 "create_entity_with_attachments",
589 entity.id,
590 entity,
591 embedding,
592 degradations,
593 )
594 }
595
596 #[allow(clippy::too_many_arguments)]
598 pub async fn create_entity_with_attachments_and_report(
599 &self,
600 token: &NamespaceToken,
601 kind: &str,
602 entity_type: Option<&str>,
603 name: &str,
604 description: Option<&str>,
605 properties: Option<serde_json::Value>,
606 tags: Vec<String>,
607 attachments: Vec<NewAttachment>,
608 ) -> RuntimeResult<(Entity, crate::retrieval::EmbeddingTruncationReport)> {
609 let (entity, embedding, degradations) = self
610 .create_entity_with_attachments_inner(
611 token,
612 kind,
613 entity_type,
614 name,
615 description,
616 properties,
617 tags,
618 attachments,
619 )
620 .await?;
621 legacy_post_commit_result(
622 "create_entity_with_attachments_and_report",
623 entity.id,
624 (entity, embedding),
625 degradations,
626 )
627 }
628
629 #[allow(clippy::too_many_arguments)]
630 async fn create_entity_with_attachments_inner(
631 &self,
632 token: &NamespaceToken,
633 kind: &str,
634 entity_type: Option<&str>,
635 name: &str,
636 description: Option<&str>,
637 properties: Option<serde_json::Value>,
638 tags: Vec<String>,
639 attachments: Vec<NewAttachment>,
640 ) -> RuntimeResult<(
641 Entity,
642 crate::retrieval::EmbeddingTruncationReport,
643 Vec<PostCommitDegradation>,
644 )> {
645 drop(self.attachments()?);
649 let blob_store = self.blob_store().ok_or_else(|| {
650 RuntimeError::Unconfigured(
651 "create_entity_with_attachments requires an installed BlobStore".to_string(),
652 )
653 })?;
654 let mut roles = std::collections::HashSet::with_capacity(attachments.len());
655 for attachment in &attachments {
656 attachment.validate()?;
657 if !roles.insert(attachment.role.as_str()) {
658 return Err(RuntimeError::InvalidInput(format!(
659 "duplicate attachment role {:?}",
660 attachment.role
661 )));
662 }
663 }
664 for attachment in &attachments {
665 if !blob_store.exists(&attachment.content_ref).await? {
666 return Err(RuntimeError::InvalidInput(format!(
667 "create_entity_with_attachments requires a published blob; no object exists for {}",
668 attachment.content_ref
669 )));
670 }
671 }
672 let validated_type = self.validate_entity_type_for_kind(kind, entity_type)?;
673 let (entity, embedding, degradations) = self
674 .create_entity_with_embedding_report_inner(
675 token,
676 kind,
677 validated_type.as_deref(),
678 name,
679 description,
680 properties,
681 tags,
682 attachments,
683 None,
684 &EntityAliasChange::default(),
685 )
686 .await?
687 .into_written()?;
688 Ok((entity, embedding, degradations))
689 }
690
691 #[allow(clippy::too_many_arguments)]
692 pub async fn create_entity_with_embedding_report(
693 &self,
694 token: &NamespaceToken,
695 kind: &str,
696 entity_type: Option<&str>,
697 name: &str,
698 description: Option<&str>,
699 properties: Option<serde_json::Value>,
700 tags: Vec<String>,
701 ) -> RuntimeResult<(Entity, crate::retrieval::EmbeddingTruncationReport)> {
702 let (entity, embedding, degradations) = self
703 .create_entity_with_embedding_report_inner(
704 token,
705 kind,
706 entity_type,
707 name,
708 description,
709 properties,
710 tags,
711 Vec::new(),
712 None,
713 &EntityAliasChange::default(),
714 )
715 .await?
716 .into_written()?;
717 legacy_post_commit_result(
718 "create_entity_with_embedding_report",
719 entity.id,
720 (entity, embedding),
721 degradations,
722 )
723 }
724
725 #[allow(clippy::too_many_arguments)]
730 pub async fn create_entity_with_post_commit_report(
731 &self,
732 token: &NamespaceToken,
733 kind: &str,
734 entity_type: Option<&str>,
735 name: &str,
736 description: Option<&str>,
737 properties: Option<serde_json::Value>,
738 tags: Vec<String>,
739 aliases: &EntityAliasChange,
740 ) -> RuntimeResult<(
741 Entity,
742 crate::retrieval::EmbeddingTruncationReport,
743 Vec<PostCommitDegradation>,
744 )> {
745 self.create_entity_with_embedding_report_inner(
746 token,
747 kind,
748 entity_type,
749 name,
750 description,
751 properties,
752 tags,
753 Vec::new(),
754 None,
755 aliases,
756 )
757 .await?
758 .into_written()
759 }
760
761 #[allow(clippy::too_many_arguments)]
762 pub(super) async fn create_entity_with_embedding_report_inner(
763 &self,
764 token: &NamespaceToken,
765 kind: &str,
766 entity_type: Option<&str>,
767 name: &str,
768 description: Option<&str>,
769 properties: Option<serde_json::Value>,
770 tags: Vec<String>,
771 attachments: Vec<NewAttachment>,
772 key: Option<&str>,
773 aliases: &EntityAliasChange,
774 ) -> RuntimeResult<EntityCreateWrite> {
775 self.validate_entity_kind(kind)?;
776 crate::secret_gate::reject_reserved_secret_gate_property(properties.as_ref())?;
777 let ns = token.namespace().as_str();
778 let mut entity = Entity::new(ns, kind, name).with_entity_type(entity_type);
779 if let Some(d) = description {
780 entity = entity.with_description(d);
781 }
782 if let Some(p) = properties {
783 entity = entity.with_properties(p);
784 }
785 if !tags.is_empty() {
786 entity = entity.with_tags(tags);
787 }
788 let projected_content_ref = attachments
789 .iter()
790 .find(|attachment| attachment.role == "content")
791 .map(|attachment| attachment.content_ref.to_string());
792 let attachment_rows: Vec<Attachment> = attachments
793 .into_iter()
794 .map(|attachment| {
795 Attachment::from_new(
796 entity.id,
797 AttachmentSubstrate::Entity,
798 attachment,
799 entity.created_at,
800 )
801 })
802 .collect();
803 entity.content_ref = projected_content_ref.clone();
804 let created_at = entity.created_at;
808 let (_, alias_statements, _) = super::entity_aliases::apply_entity_alias_change(
809 &mut entity,
810 aliases,
811 created_at,
812 None,
813 );
814 let key_claim =
818 key.map(|key| entity_key_claim_statement(ns, kind, key, entity.id, entity.created_at));
819 entity = match prepare_entity_admission(token, EntityEntryPoint::Create, entity)? {
820 EntityAdmission::Legacy(candidate) => candidate,
821 EntityAdmission::Exempt(prepared) => {
822 let entity = prepared.entity().clone();
823 let (mut required, report) = self
824 .prepare_admitted_entity_indexes(token, &entity, &attachment_rows, true)
825 .await?;
826 if let Some(claim) = key_claim {
827 required.insert(
828 0,
829 PlanStatement {
830 statement: claim,
831 guard: Some(AffectedRowGuard::exactly(1)),
832 },
833 );
834 }
835 required.extend(super::entity_aliases::unguarded(alias_statements));
836 let plan = prepared.into_plan(
837 EntityCandidateMutation::CreateIfAbsent,
838 required,
839 PostCommitEffect::None,
840 )?;
841 match run_atomic_unit(
842 self.sql().as_ref(),
843 vec![AtomicOpPlan::FinalizeEntity(Box::new(plan))],
844 )
845 .await
846 {
847 Ok(AtomicRunOutcome::Committed { .. }) => {
848 let degradations = self.record_created_entity_event(token, &entity).await;
849 return Ok(EntityCreateWrite::Written(
850 Box::new(entity),
851 report,
852 degradations,
853 ));
854 }
855 Ok(AtomicRunOutcome::RolledBack { failure, .. }) => {
856 if let Some(key) = key {
860 let holder = self
861 .entities(token)?
862 .get_entity_by_key(ns, kind, key)
863 .await?;
864 if holder.is_some_and(|holder| holder.id != entity.id) {
865 return Ok(EntityCreateWrite::KeyHeld);
866 }
867 }
868 return Err(RuntimeError::Internal(format!(
869 "entity finalization rolled back: {failure:?}"
870 )));
871 }
872 Err(error) => return Err(RuntimeError::Storage(error.0)),
873 }
874 }
875 };
876 if key_claim.is_none() && alias_statements.is_empty() {
877 self.entities(token)?
878 .upsert_entity_with_attachments(entity.clone(), attachment_rows)
879 .await?;
880 } else {
881 drop(self.entities(token)?);
882 let mut statements: Vec<PlanStatement> = key_claim
883 .into_iter()
884 .map(|claim| PlanStatement {
885 statement: claim,
886 guard: Some(AffectedRowGuard::exactly(1)),
887 })
888 .collect();
889 statements.push(PlanStatement {
890 statement: entity_upsert_statement(&entity),
891 guard: Some(AffectedRowGuard::exactly(1)),
892 });
893 for attachment in &attachment_rows {
894 statements.push(PlanStatement {
895 statement: attachment_upsert_statement(attachment)?,
896 guard: None,
897 });
898 }
899 statements.extend(super::entity_aliases::unguarded(alias_statements));
900 let plan = AddEntityPlan {
901 entity_id: entity.id,
902 statements,
903 post_commit: PostCommitEffect::None,
904 };
905 match run_atomic_unit(self.sql().as_ref(), vec![AtomicOpPlan::AddEntity(plan)]).await {
906 Ok(AtomicRunOutcome::Committed { .. }) => {}
907 Ok(AtomicRunOutcome::RolledBack {
908 failure:
909 AtomicOpFailure::GuardFailed {
910 statement_label: Some(label),
911 ..
912 },
913 ..
914 }) if label == ENTITY_KEY_CLAIM_LABEL => {
915 return Ok(EntityCreateWrite::KeyHeld);
916 }
917 Ok(AtomicRunOutcome::RolledBack { failure, .. }) => {
918 return Err(RuntimeError::Internal(format!(
919 "entity create rolled back: {failure:?}"
920 )));
921 }
922 Err(error) => return Err(RuntimeError::Storage(error.0)),
923 }
924 }
925 entity.content_ref = projected_content_ref;
926
927 let doc = entity_fts_document(&entity);
928 let embed_body = doc.body.clone();
929
930 {
932 #[cfg(any(test, feature = "fault-injection"))]
933 let fts_inject = consume_fault(&FTS_FAIL_NS, ns);
934 #[cfg(not(any(test, feature = "fault-injection")))]
935 let fts_inject = false;
936 let fts_result: RuntimeResult<()> = if fts_inject {
937 Err(RuntimeError::Internal("injected FTS failure".to_string()))
938 } else {
939 match self.text(token) {
940 Ok(fts) => fts.upsert_document(doc).await.map_err(RuntimeError::from),
941 Err(e) => Err(e),
942 }
943 };
944 if let Err(e) = fts_result {
945 let cleanup_errors = self
946 .compensate_entity_create(token, entity.id, ns, &[])
947 .await;
948 return Err(Self::entity_create_failure(entity.id, e, cleanup_errors));
949 }
950 }
951
952 let embed_model_names = {
955 let names = self.registered_embedding_model_names();
956 if names.is_empty() {
957 vec![]
958 } else {
959 names
960 }
961 };
962
963 let mut embedding_report = crate::retrieval::EmbeddingTruncationReport::default();
964 if embed_model_names.len() == 1 {
965 let model_name = &embed_model_names[0];
966 let vec_result = self
967 .embed_document_with_model_outcome_for_token(token, model_name, &embed_body)
968 .await;
969
970 #[cfg(any(test, feature = "fault-injection"))]
971 let vec_inject = consume_fault(&VECTOR_FAIL_NS, ns);
972 #[cfg(not(any(test, feature = "fault-injection")))]
973 let vec_inject = false;
974 let vec_result: RuntimeResult<crate::retrieval::DocumentEmbeddingOutcome> =
975 if vec_inject {
976 Err(RuntimeError::Internal(
977 "injected vector failure".to_string(),
978 ))
979 } else {
980 vec_result
981 };
982
983 let single_result: RuntimeResult<()> = match vec_result {
984 Ok(outcome) => {
985 embedding_report.observe(&outcome);
986 match self.vectors_for_model(token, model_name) {
987 Ok(vs) => vs
988 .insert(
989 entity.id,
990 SubstrateKind::Entity,
991 ns,
992 "entity.body",
993 vec![outcome.vector],
994 )
995 .await
996 .map_err(RuntimeError::from),
997 Err(e) => Err(e),
998 }
999 }
1000 Err(e) => Err(e),
1001 };
1002 if let Err(e) = single_result {
1003 let cleanup_errors = self
1004 .compensate_entity_create(
1005 token,
1006 entity.id,
1007 ns,
1008 std::slice::from_ref(model_name),
1009 )
1010 .await;
1011 return Err(Self::entity_create_failure(entity.id, e, cleanup_errors));
1012 }
1013 } else if !embed_model_names.is_empty() {
1014 let rt_clone = self.clone();
1017 let body_owned = embed_body.clone();
1018 let usage_ctx = crate::usage::current();
1019 let mut join_set = tokio::task::JoinSet::new();
1020 for (idx, model_name) in embed_model_names.iter().enumerate() {
1021 let rt = rt_clone.clone();
1022 let text = body_owned.clone();
1023 let name = model_name.clone();
1024 let ctx = usage_ctx.clone();
1025 let token = (*token).clone();
1026 join_set.spawn(crate::runtime::inherit_request_embedder_scope(async move {
1027 let fut = rt.embed_document_with_model_outcome_for_token(&token, &name, &text);
1028 let result = match ctx {
1029 Some(ctx) => crate::usage::scope(ctx, fut).await,
1030 None => fut.await,
1031 };
1032 (idx, result)
1033 }));
1034 }
1035 let outcomes = match drain_embed_join_set(join_set, embed_model_names.len()).await {
1039 Ok(outcomes) => outcomes,
1040 Err(e) => {
1041 let cleanup_errors = self
1042 .compensate_entity_create(token, entity.id, ns, &[])
1043 .await;
1044 return Err(Self::entity_create_failure(entity.id, e, cleanup_errors));
1045 }
1046 };
1047 let mut inserted_models: Vec<String> = Vec::with_capacity(embed_model_names.len());
1049 for (model_name, outcome) in embed_model_names.iter().zip(outcomes) {
1050 embedding_report.observe(&outcome);
1051 #[cfg(any(test, feature = "fault-injection"))]
1053 let count_inject = VECTOR_FAIL_AFTER.with(|cell| match cell.get() {
1054 Some(0) => {
1055 cell.set(None);
1056 true
1057 }
1058 Some(n) => {
1059 cell.set(Some(n - 1));
1060 false
1061 }
1062 None => false,
1063 });
1064 #[cfg(not(any(test, feature = "fault-injection")))]
1065 let count_inject = false;
1066
1067 let insert_result = if count_inject {
1068 Err(RuntimeError::Internal(
1069 "injected vector insert failure".to_string(),
1070 ))
1071 } else {
1072 match self.vectors_for_model(token, model_name) {
1073 Ok(vs) => vs
1074 .insert(
1075 entity.id,
1076 SubstrateKind::Entity,
1077 ns,
1078 "entity.body",
1079 vec![outcome.vector],
1080 )
1081 .await
1082 .map_err(RuntimeError::from),
1083 Err(e) => Err(e),
1084 }
1085 };
1086 if let Err(e) = insert_result {
1087 let mut cleanup_models = inserted_models.clone();
1090 cleanup_models.push(model_name.clone());
1091 let cleanup_errors = self
1092 .compensate_entity_create(token, entity.id, ns, &cleanup_models)
1093 .await;
1094 return Err(Self::entity_create_failure(entity.id, e, cleanup_errors));
1095 }
1096 inserted_models.push(model_name.clone());
1097 }
1098 }
1099
1100 let degradations = self.record_created_entity_event(token, &entity).await;
1101 Ok(EntityCreateWrite::Written(
1102 Box::new(entity),
1103 embedding_report,
1104 degradations,
1105 ))
1106 }
1107
1108 async fn record_created_entity_event(
1109 &self,
1110 token: &NamespaceToken,
1111 entity: &Entity,
1112 ) -> Vec<PostCommitDegradation> {
1113 let created_event = khive_storage::event::Event::new(
1120 entity.namespace.clone(),
1121 "create",
1122 EventKind::EntityCreated,
1123 SubstrateKind::Entity,
1124 "",
1125 )
1126 .with_target(entity.id)
1127 .with_payload(serde_json::json!({
1128 "id": entity.id,
1129 "namespace": entity.namespace,
1130 "kind": entity.kind,
1131 }));
1132 let event_result = match self.events(token) {
1133 Ok(store) => store
1134 .append_event(created_event)
1135 .await
1136 .map_err(RuntimeError::from),
1137 Err(error) => Err(error),
1138 };
1139 let mut degradations = Vec::new();
1140 if let Err(error) = event_result {
1141 record_post_commit_degradation(
1142 &mut degradations,
1143 "create_entity",
1144 entity.id,
1145 "event_append",
1146 error,
1147 );
1148 }
1149
1150 degradations
1151 }
1152}