Skip to main content

khive_runtime/curation/
entity_curation.rs

1#[cfg(test)]
2use super::race_seam;
3use super::{
4    entity_fts_document, map_merge_entity_storage_error, merge_entity_sql, merge_properties,
5    stale_entity_snapshot_error, Any, AtomicUnitOp, ContentMergeStrategy, EmbeddingModelPlan,
6    Entity, EntityDedupMergePolicy, EntityMergeValidation, EntityPatch, EventAttribution,
7    EventKind, HashMap, KhiveRuntime, MergeEventContext, MergeSqlError, MergeSummary,
8    MergeTxLimits, NamespaceToken, RuntimeError, RuntimeResult, RuntimeWriteOperation,
9    SqlStatement, SqlValue, SqliteError, SubstrateKind, Uuid, Value,
10};
11
12use super::entity_pending_index::EntityUpdateReport;
13use crate::secret_gate_finalizer::entity_admission::{
14    EntityAdmission, OrdinaryEntityUpdateContext,
15};
16use crate::EntityCandidateMutation;
17
18#[derive(Clone, Copy)]
19enum EntityUpdateRoute<'a> {
20    ReservationOnly,
21    OrdinaryConstructor(&'a OrdinaryEntityUpdateContext),
22}
23
24struct PreparedEntityUpdate {
25    entity: Entity,
26    reindex_required: bool,
27    changed_fields: Vec<&'static str>,
28    expected_updated_at: i64,
29    expected_deleted_at: Option<i64>,
30    original: Entity,
31}
32
33impl KhiveRuntime {
34    pub(crate) async fn validate_canonical_entity_patch(
35        &self,
36        token: &NamespaceToken,
37        current: &Entity,
38        mut patch: EntityPatch,
39    ) -> RuntimeResult<EntityPatch> {
40        crate::atomic_prepare::canonical_refuse_registry_tags(&current.tags, "update")?;
41        if let Some(name) = &patch.name {
42            if name.trim().is_empty() {
43                return Err(RuntimeError::InvalidInput("name must not be empty".into()));
44            }
45            crate::secret_gate::check_at(name, "entity", "name")?;
46        }
47        if let Some(Some(description)) = &patch.description {
48            crate::secret_gate::check_at(description, "entity", "description")?;
49        }
50        if let Some(properties) = &patch.properties {
51            crate::secret_gate::check_json_at(properties, "entity", "properties")?;
52        }
53        if let Some(tags) = &patch.tags {
54            crate::atomic_prepare::canonical_refuse_registry_tags(tags, "update")?;
55            crate::secret_gate::check_tags_at(tags, "entity", "tags")?;
56        }
57        if let Some(Some(entity_type)) = &patch.entity_type {
58            patch.entity_type =
59                Some(self.validate_entity_type_for_kind(&current.kind, Some(entity_type))?);
60        }
61        // ADR-115 §4 against the prepared row: the writer repeats this against the row it
62        // meets, which also decides whether a stored reserved value carries.
63        if let Some(properties) = &patch.properties {
64            crate::secret_gate::strip_reserved_echo(
65                &mut properties.clone(),
66                current.properties.as_ref(),
67            )?;
68        }
69        let mut projected = current.clone();
70        Self::apply_entity_patch_fields(&mut projected, patch.clone(), &[], true);
71        if let Some(hook) = self.entity_kind_hook(&current.kind) {
72            hook.validate_entity_update(self, token, &projected, projected.properties.as_ref())
73                .await?;
74        }
75        Ok(patch)
76    }
77
78    pub(crate) fn apply_entity_patch_fields(
79        entity: &mut Entity,
80        patch: EntityPatch,
81        remove_properties: &[&str],
82        replace_properties: bool,
83    ) -> (bool, Vec<&'static str>) {
84        let mut reindex_required = false;
85        let mut changed_fields: Vec<&'static str> = Vec::new();
86
87        if let Some(name) = patch.name {
88            reindex_required |= entity.name != name;
89            entity.name = name;
90            changed_fields.push("name");
91        }
92        if let Some(desc_patch) = patch.description {
93            reindex_required |= entity.description != desc_patch;
94            entity.description = desc_patch;
95            changed_fields.push("description");
96        }
97        if let Some(props) = patch.properties {
98            if replace_properties {
99                entity.properties = Some(props);
100            } else {
101                let (merged, _) = merge_properties(
102                    &entity.properties,
103                    &Some(props),
104                    EntityDedupMergePolicy::PreferFrom,
105                );
106                entity.properties = merged;
107            }
108            changed_fields.push("properties");
109        }
110        if let Some(Value::Object(properties)) = entity.properties.as_mut() {
111            let mut removed = false;
112            for key in remove_properties {
113                removed |= properties.remove(*key).is_some();
114            }
115            if removed && !changed_fields.contains(&"properties") {
116                changed_fields.push("properties");
117            }
118        }
119        if let Some(tags) = patch.tags {
120            entity.tags = tags;
121            changed_fields.push("tags");
122        }
123        if let Some(entity_type) = patch.entity_type {
124            reindex_required |= entity.entity_type != entity_type;
125            entity.entity_type = entity_type;
126            changed_fields.push("entity_type");
127        }
128
129        (reindex_required, changed_fields)
130    }
131
132    /// Patch-style entity update.
133    ///
134    /// Only fields set to `Some(_)` are changed. Re-indexes FTS5 (and vectors if configured)
135    /// when `name`, `description`, or `entity_type` changes; skips re-indexing for
136    /// property/tag-only patches.
137    ///
138    /// Returns `RuntimeError::NotFound` if the entity does not exist or belongs to a different
139    /// namespace. Namespace isolation is enforced at the runtime layer.
140    /// Computes the patched `Entity`, `reindex_required`, and `changed_fields` without
141    /// writing anything, so both the normal write path and the atomic-prepare path
142    /// share one source of truth for what a patched entity looks like.
143    /// `remove_properties` names top-level property keys dropped after the
144    /// patch's properties merge in; runtime-owned keys cannot be removed.
145    #[cfg(test)]
146    pub(crate) async fn prepare_update_entity(
147        &self,
148        token: &NamespaceToken,
149        id: Uuid,
150        patch: EntityPatch,
151        remove_properties: &[&str],
152    ) -> RuntimeResult<(Entity, bool, Vec<&'static str>, i64, Option<i64>)> {
153        self.prepare_guarded_entity_update(token, id, patch, None, remove_properties)
154            .await
155    }
156
157    /// [`Self::prepare_update_entity`] that also returns the name the row had
158    /// when this update read it, so a rename can keep it (ADR-221 section 3).
159    #[allow(clippy::type_complexity)]
160    pub(crate) async fn prepare_update_entity_with_previous_name(
161        &self,
162        token: &NamespaceToken,
163        id: Uuid,
164        patch: EntityPatch,
165        remove_properties: &[&str],
166    ) -> RuntimeResult<((Entity, bool, Vec<&'static str>, i64, Option<i64>), String)> {
167        let prepared = self
168            .prepare_entity_update_for_route(
169                token,
170                id,
171                patch,
172                None,
173                remove_properties,
174                EntityUpdateRoute::ReservationOnly,
175            )
176            .await?;
177        Ok((
178            (
179                prepared.entity,
180                prepared.reindex_required,
181                prepared.changed_fields,
182                prepared.expected_updated_at,
183                prepared.expected_deleted_at,
184            ),
185            prepared.original.name,
186        ))
187    }
188
189    async fn prepare_guarded_entity_update(
190        &self,
191        token: &NamespaceToken,
192        id: Uuid,
193        patch: EntityPatch,
194        expected: Option<&Entity>,
195        remove_properties: &[&str],
196    ) -> RuntimeResult<(Entity, bool, Vec<&'static str>, i64, Option<i64>)> {
197        let prepared = self
198            .prepare_entity_update_for_route(
199                token,
200                id,
201                patch,
202                expected,
203                remove_properties,
204                EntityUpdateRoute::ReservationOnly,
205            )
206            .await?;
207        Ok((
208            prepared.entity,
209            prepared.reindex_required,
210            prepared.changed_fields,
211            prepared.expected_updated_at,
212            prepared.expected_deleted_at,
213        ))
214    }
215
216    async fn prepare_entity_update_for_route(
217        &self,
218        token: &NamespaceToken,
219        id: Uuid,
220        patch: EntityPatch,
221        expected: Option<&Entity>,
222        remove_properties: &[&str],
223        route: EntityUpdateRoute<'_>,
224    ) -> RuntimeResult<PreparedEntityUpdate> {
225        crate::secret_gate::reject_reserved_secret_gate_property(patch.properties.as_ref())?;
226        if !remove_properties.is_empty() {
227            let removals = Value::Object(
228                remove_properties
229                    .iter()
230                    .map(|key| ((*key).to_string(), Value::Null))
231                    .collect(),
232            );
233            crate::secret_gate::reject_reserved_secret_gate_property(Some(&removals))?;
234        }
235        if matches!(route, EntityUpdateRoute::ReservationOnly) {
236            if let Some(ref name) = patch.name {
237                crate::secret_gate::check_at(name, "entity", "name")?;
238            }
239            if let Some(Some(ref desc)) = patch.description {
240                crate::secret_gate::check_at(desc, "entity", "description")?;
241            }
242            if let Some(ref props) = patch.properties {
243                crate::secret_gate::check_json_at(props, "entity", "properties")?;
244            }
245            if let Some(ref tags) = patch.tags {
246                crate::secret_gate::check_tags_at(tags, "entity", "tags")?;
247            }
248        } else if let EntityUpdateRoute::OrdinaryConstructor(context) = route {
249            context.check_patch(
250                patch.name.as_deref(),
251                patch
252                    .description
253                    .as_ref()
254                    .and_then(|value| value.as_deref()),
255                patch.properties.as_ref(),
256                patch.tags.as_deref(),
257            )?;
258        }
259        let store = self.entities(token)?;
260        let mut entity = store.get_entity(id).await?.ok_or_else(|| {
261            if expected.is_some() {
262                stale_entity_snapshot_error(id)
263            } else {
264                RuntimeError::NotFound(format!("entity {id}"))
265            }
266        })?;
267        if let Some(expected) = expected {
268            let actual = serde_json::to_value(&entity)
269                .map_err(|error| RuntimeError::Internal(error.to_string()))?;
270            let expected = serde_json::to_value(expected)
271                .map_err(|error| RuntimeError::Internal(error.to_string()))?;
272            if actual != expected {
273                return Err(stale_entity_snapshot_error(id));
274            }
275        }
276        let original = entity.clone();
277        let expected_updated_at = entity.updated_at;
278        let expected_deleted_at = entity.deleted_at;
279        #[cfg(test)]
280        race_seam::pause_after_read().await;
281
282        // ADR-014 tri-state: outer `None` = unchanged; `Some(None)` = explicit
283        // clear (no vocabulary validation — there is no value to validate);
284        // `Some(Some(raw))` = set, validated and normalized.
285        let validated_entity_type = match &patch.entity_type {
286            Some(None) => Some(None),
287            Some(Some(raw)) => Some(Some(
288                self.validate_entity_type_for_kind(&entity.kind, Some(raw))?
289                    .expect("set branch always yields a normalized value"),
290            )),
291            None => None,
292        };
293
294        let patch = EntityPatch {
295            entity_type: validated_entity_type,
296            ..patch
297        };
298        let (reindex_required, changed_fields) =
299            Self::apply_entity_patch_fields(&mut entity, patch, remove_properties, false);
300
301        // A patch may carry properties from the stored row into the full
302        // replacement. Validate the final object, including that carry.
303        crate::secret_gate::reject_reserved_secret_gate_property(entity.properties.as_ref())?;
304
305        if expected.is_some() && changed_fields.is_empty() {
306            return Ok(PreparedEntityUpdate {
307                entity,
308                reindex_required,
309                changed_fields,
310                expected_updated_at,
311                expected_deleted_at,
312                original,
313            });
314        }
315
316        // #2943: `entity.properties`, `entity.entity_type`, and `entity.tags`
317        // are all final here — the owning pack's KindHook, if any, validates
318        // the resulting record, mirroring `prepare_note_update_hook` on the
319        // note side. `Ok(())` when no pack registered a hook for this entity
320        // kind (the trait default, or the runtime-layer aggregate was never
321        // installed). Placed after the no-op early return above so a
322        // genuinely unchanged guarded update never re-runs the hook for
323        // nothing; only `updated_at` remains to be bumped after this point.
324        if let Some(hook) = self.entity_kind_hook(&entity.kind) {
325            hook.validate_entity_update(self, token, &entity, entity.properties.as_ref())
326                .await?;
327        }
328
329        // `updated_at` is also the optimistic-concurrency revision for
330        // full-entity replacement. Make it strictly advance even when two
331        // operations land inside one clock microsecond. Saturation is not a
332        // valid fallback: reusing i64::MAX would make the CAS accept a write
333        // without advancing its revision.
334        let minimum_updated_at = expected_updated_at.checked_add(1).ok_or_else(|| {
335            RuntimeError::Internal(format!(
336                "entity {id} updated_at is already at i64::MAX and cannot advance"
337            ))
338        })?;
339        entity.updated_at = chrono::Utc::now()
340            .timestamp_micros()
341            .max(minimum_updated_at);
342        Ok(PreparedEntityUpdate {
343            entity,
344            reindex_required,
345            changed_fields,
346            expected_updated_at,
347            expected_deleted_at,
348            original,
349        })
350    }
351
352    #[cfg(test)]
353    pub(crate) async fn update_entity(
354        &self,
355        token: &NamespaceToken,
356        id: Uuid,
357        patch: EntityPatch,
358    ) -> RuntimeResult<Entity> {
359        Ok(self
360            .update_entity_with_embedding_report(token, id, patch)
361            .await?
362            .0)
363    }
364
365    pub async fn update_entity_with_embedding_report(
366        &self,
367        token: &NamespaceToken,
368        id: Uuid,
369        patch: EntityPatch,
370    ) -> RuntimeResult<(Entity, crate::retrieval::EmbeddingTruncationReport)> {
371        self.update_entity_with_expected_version_and_embedding_report(token, id, patch, None)
372            .await
373    }
374
375    /// Entity update with an optional caller revision, checked inside the writer transaction.
376    pub async fn update_entity_with_expected_version_and_embedding_report(
377        &self,
378        token: &NamespaceToken,
379        id: Uuid,
380        patch: EntityPatch,
381        expected_version: Option<i64>,
382    ) -> RuntimeResult<(Entity, crate::retrieval::EmbeddingTruncationReport)> {
383        let (entity, report) = self
384            .update_entity_with_index_report(token, id, patch, expected_version)
385            .await?;
386        report.into_legacy(entity)
387    }
388
389    /// Apply an entity patch and report committed but unfinished index targets.
390    ///
391    /// A rename through this call keeps no `rename` alias: packs use it for
392    /// names they derive themselves, such as a placeholder replaced by the
393    /// real name. The `update` verb keeps the old name through
394    /// [`Self::update_entity_with_aliases_and_index_report`] (ADR-221
395    /// section 3).
396    pub async fn update_entity_with_index_report(
397        &self,
398        token: &NamespaceToken,
399        id: Uuid,
400        patch: EntityPatch,
401        expected_version: Option<i64>,
402    ) -> RuntimeResult<(Entity, EntityUpdateReport)> {
403        self.update_entity_with_removals_and_index_report(
404            token,
405            id,
406            patch,
407            &[],
408            expected_version,
409            &crate::EntityAliasChange::default().keeping_old_name(false),
410        )
411        .await
412    }
413
414    /// [`Self::update_entity_with_index_report`] that also applies `aliases`
415    /// to the entity's caller-origin aliases (ADR-221 section 2), in the
416    /// transaction that writes the patch. An alias change reindexes the
417    /// entity as a name change does. The report's `aliases` lists what the
418    /// change asked for and did not do.
419    pub async fn update_entity_with_aliases_and_index_report(
420        &self,
421        token: &NamespaceToken,
422        id: Uuid,
423        patch: EntityPatch,
424        aliases: &crate::EntityAliasChange,
425        expected_version: Option<i64>,
426    ) -> RuntimeResult<(Entity, EntityUpdateReport)> {
427        self.update_entity_with_removals_and_index_report(
428            token,
429            id,
430            patch,
431            &[],
432            expected_version,
433            aliases,
434        )
435        .await
436    }
437
438    /// [`Self::update_entity_with_index_report`] that also removes the named
439    /// top-level property keys after the patch's properties merge in.
440    /// Runtime-owned keys cannot be removed.
441    pub(crate) async fn update_entity_with_removals_and_index_report(
442        &self,
443        token: &NamespaceToken,
444        id: Uuid,
445        patch: EntityPatch,
446        remove_properties: &[&str],
447        expected_version: Option<i64>,
448        aliases: &crate::EntityAliasChange,
449    ) -> RuntimeResult<(Entity, EntityUpdateReport)> {
450        crate::entity_write::validate_expected_version(expected_version)?;
451        let alias_only = patch.is_empty() && remove_properties.is_empty() && !aliases.is_empty();
452        let admission = OrdinaryEntityUpdateContext::capture(token);
453        let PreparedEntityUpdate {
454            mut entity,
455            mut reindex_required,
456            mut changed_fields,
457            expected_updated_at,
458            expected_deleted_at,
459            original,
460        } = self
461            .prepare_entity_update_for_route(
462                token,
463                id,
464                patch,
465                None,
466                remove_properties,
467                EntityUpdateRoute::OrdinaryConstructor(&admission),
468            )
469            .await?;
470        // ADR-221 section 2: the alias change lands on the row whose name is
471        // final, before admission, so the indexed body carries it.
472        let updated_at = entity.updated_at;
473        let previous_name = original.name.clone();
474        let (aliases_changed, alias_statements, alias_report) =
475            crate::operations::apply_entity_alias_change(
476                &mut entity,
477                aliases,
478                updated_at,
479                Some(&previous_name),
480            );
481        if aliases_changed {
482            reindex_required = true;
483            changed_fields.push("aliases");
484        }
485        // An update that asks only for alias changes and changes none writes
486        // nothing: the version, updated_at and the event log stay as they
487        // are, and the answer still lists what was not stored or removed.
488        if alias_only
489            && !aliases_changed
490            && expected_version.is_none_or(|expected| expected == original.version)
491        {
492            let mut report = EntityUpdateReport::complete(
493                crate::retrieval::EmbeddingTruncationReport::default(),
494                false,
495            );
496            report.aliases = alias_report;
497            return Ok((original, report));
498        }
499        let entity = match admission.admit(token, entity)? {
500            EntityAdmission::Legacy(entity) => entity,
501            EntityAdmission::Exempt(prepared) => {
502                use crate::atomic_plan::PostCommitEffect;
503                use crate::atomic_runner::{
504                    run_atomic_unit, AtomicOpFailure, AtomicOpPlan, AtomicRunOutcome,
505                };
506                let mut entity = prepared.entity().clone();
507                let next_version = original
508                    .version
509                    .checked_add(1)
510                    .ok_or_else(|| RuntimeError::InvalidInput("entity version overflow".into()))?;
511                let (mut required, report) = self
512                    .prepare_admitted_entity_indexes(token, &entity, &[], reindex_required)
513                    .await?;
514                required.extend(crate::operations::unguarded_alias_statements(
515                    alias_statements,
516                ));
517                required.extend(crate::atomic_prepare::event_append_statements(
518                    token,
519                    &entity.namespace,
520                    "update",
521                    EventKind::EntityUpdated,
522                    SubstrateKind::Entity,
523                    entity.id,
524                    crate::operations::entity_updated_payload(
525                        &entity,
526                        &changed_fields,
527                        Some(&previous_name),
528                    ),
529                )?);
530                let plan = prepared.into_plan(
531                    EntityCandidateMutation::ReplaceIfUnchanged {
532                        expected: original,
533                        expected_version,
534                    },
535                    required,
536                    PostCommitEffect::None,
537                )?;
538                match run_atomic_unit(
539                    self.sql().as_ref(),
540                    vec![AtomicOpPlan::FinalizeEntity(Box::new(plan))],
541                )
542                .await
543                {
544                    Ok(AtomicRunOutcome::Committed { .. }) => {
545                        entity.version = next_version;
546                        let mut report = EntityUpdateReport::complete(report, reindex_required);
547                        report.aliases = alias_report;
548                        return Ok((entity, report));
549                    }
550                    Ok(AtomicRunOutcome::RolledBack {
551                        failure: AtomicOpFailure::EntityConflict(conflict),
552                        ..
553                    }) => {
554                        return Err(conflict.into_error().into());
555                    }
556                    Ok(AtomicRunOutcome::RolledBack {
557                        failure: AtomicOpFailure::GuardFailed { .. },
558                        ..
559                    }) => {
560                        return Err(stale_entity_snapshot_error(id));
561                    }
562                    Ok(AtomicRunOutcome::RolledBack { failure, .. }) => {
563                        return Err(RuntimeError::Internal(format!(
564                            "entity update finalization rolled back: {failure:?}"
565                        )));
566                    }
567                    Err(error) => return Err(RuntimeError::Storage(error.0)),
568                }
569            }
570        };
571
572        let (entity, mut report) = self
573            .persist_prepared_entity_update(
574                token,
575                entity,
576                reindex_required,
577                changed_fields,
578                expected_updated_at,
579                expected_deleted_at,
580                expected_version,
581                alias_statements,
582                Some(previous_name),
583            )
584            .await?;
585        report.aliases = alias_report;
586        Ok((entity, report))
587    }
588
589    /// Apply an admin patch only if the entity still matches the full read snapshot.
590    /// Property removals apply after the normal merge and preserve all other keys.
591    /// Missing keys alone are a no-op; reserved runtime-owned keys cannot be removed.
592    /// A changed, deleted, or missing entity returns a conflict without writing.
593    /// A bounded embedding returns a non-retryable error with the committed ID
594    /// and truncation report; use the report-aware variant to retain the record.
595    pub async fn update_entity_if_unchanged(
596        &self,
597        token: &NamespaceToken,
598        expected: &Entity,
599        patch: EntityPatch,
600        remove_properties: &[&str],
601    ) -> RuntimeResult<Entity> {
602        let (entity, embedding) = self
603            .update_entity_if_unchanged_with_embedding_report(
604                token,
605                expected,
606                patch,
607                remove_properties,
608            )
609            .await?;
610        crate::operations::legacy_post_commit_result_with_embedding(
611            "update_entity_if_unchanged",
612            entity.id,
613            entity,
614            embedding,
615            Vec::new(),
616        )
617    }
618
619    /// Apply a guarded admin patch with one event in the same writer transaction.
620    /// The token stamps the required event's namespace, actor and operation;
621    /// callers supply its semantic kind, target and payload. An unchanged patch
622    /// appends nothing. A failed append rolls back the replacement. Existing
623    /// post-commit index and generic update-event reporting remains unchanged.
624    pub async fn update_entity_if_unchanged_with_required_event(
625        &self,
626        token: &NamespaceToken,
627        expected: &Entity,
628        patch: EntityPatch,
629        remove_properties: &[&str],
630        required_event: khive_storage::Event,
631    ) -> RuntimeResult<Entity> {
632        let (entity, embedding) = self
633            .update_entity_if_unchanged_with_optional_event(
634                token,
635                expected,
636                patch,
637                remove_properties,
638                Some(required_event),
639            )
640            .await?;
641        crate::operations::legacy_post_commit_result_with_embedding(
642            "update_entity_if_unchanged",
643            entity.id,
644            entity,
645            embedding,
646            Vec::new(),
647        )
648    }
649
650    /// Apply a guarded admin patch and retain embedding truncation accounting.
651    pub async fn update_entity_if_unchanged_with_embedding_report(
652        &self,
653        token: &NamespaceToken,
654        expected: &Entity,
655        patch: EntityPatch,
656        remove_properties: &[&str],
657    ) -> RuntimeResult<(Entity, crate::retrieval::EmbeddingTruncationReport)> {
658        self.update_entity_if_unchanged_with_optional_event(
659            token,
660            expected,
661            patch,
662            remove_properties,
663            None,
664        )
665        .await
666    }
667
668    async fn update_entity_if_unchanged_with_optional_event(
669        &self,
670        token: &NamespaceToken,
671        expected: &Entity,
672        patch: EntityPatch,
673        remove_properties: &[&str],
674        required_event: Option<khive_storage::Event>,
675    ) -> RuntimeResult<(Entity, crate::retrieval::EmbeddingTruncationReport)> {
676        let (
677            mut entity,
678            mut reindex_required,
679            mut changed_fields,
680            expected_updated_at,
681            expected_deleted_at,
682        ) = self
683            .prepare_guarded_entity_update(
684                token,
685                expected.id,
686                patch,
687                Some(expected),
688                remove_properties,
689            )
690            .await?;
691        // ADR-221 section 3 holds on this route too: a rename keeps the old
692        // name as a `rename` alias and drops an alias equal to the new name.
693        let updated_at = entity.updated_at;
694        let (aliases_changed, alias_statements, _) = crate::operations::apply_entity_alias_change(
695            &mut entity,
696            &crate::EntityAliasChange::default(),
697            updated_at,
698            Some(&expected.name),
699        );
700        if aliases_changed {
701            reindex_required = true;
702            changed_fields.push("aliases");
703        }
704        if changed_fields.is_empty() {
705            return Ok((
706                entity,
707                crate::retrieval::EmbeddingTruncationReport::default(),
708            ));
709        }
710        let (entity, report) = self
711            .persist_prepared_entity_update_with_required_event(
712                token,
713                entity,
714                reindex_required,
715                changed_fields,
716                expected_updated_at,
717                expected_deleted_at,
718                None,
719                required_event,
720                alias_statements,
721                Some(expected.name.clone()),
722            )
723            .await?;
724        report.into_legacy(entity)
725    }
726
727    #[allow(clippy::too_many_arguments)]
728    pub(super) async fn persist_prepared_entity_update(
729        &self,
730        token: &NamespaceToken,
731        entity: Entity,
732        reindex_required: bool,
733        changed_fields: Vec<&'static str>,
734        expected_updated_at: i64,
735        expected_deleted_at: Option<i64>,
736        expected_version: Option<i64>,
737        alias_statements: Vec<khive_storage::types::SqlStatement>,
738        previous_name: Option<String>,
739    ) -> RuntimeResult<(Entity, EntityUpdateReport)> {
740        self.persist_prepared_entity_update_with_required_event(
741            token,
742            entity,
743            reindex_required,
744            changed_fields,
745            expected_updated_at,
746            expected_deleted_at,
747            expected_version,
748            None,
749            alias_statements,
750            previous_name,
751        )
752        .await
753    }
754
755    #[allow(clippy::too_many_arguments)]
756    async fn persist_prepared_entity_update_with_required_event(
757        &self,
758        token: &NamespaceToken,
759        mut entity: Entity,
760        reindex_required: bool,
761        changed_fields: Vec<&'static str>,
762        expected_updated_at: i64,
763        expected_deleted_at: Option<i64>,
764        expected_version: Option<i64>,
765        required_event: Option<khive_storage::Event>,
766        alias_statements: Vec<khive_storage::types::SqlStatement>,
767        previous_name: Option<String>,
768    ) -> RuntimeResult<(Entity, EntityUpdateReport)> {
769        // This final whole-object replacement must reserve the complete
770        // candidate, even if a future caller bypasses the patch preparer.
771        crate::secret_gate::reject_reserved_secret_gate_property(entity.properties.as_ref())?;
772        let id = entity.id;
773        let _ = self.entities(token)?;
774        let next_version = entity
775            .version
776            .checked_add(1)
777            .ok_or_else(|| RuntimeError::InvalidInput("entity version overflow".into()))?;
778        use crate::atomic_plan::{AffectedRowGuard, PlanStatement, PostCommitEffect, UpdatePlan};
779        use crate::atomic_runner::{
780            apply_plan_preserving_storage, run_prepared_atomic_unit, AtomicOpFailure, AtomicOpPlan,
781            PlanExecutionFailure, PreparedAtomicError, PreparedAtomicOp, PreparedAtomicOutcome,
782        };
783        // One immutable metadata snapshot, captured before writer admission.
784        let models = if reindex_required {
785            self.entity_index_model_snapshot()?
786        } else {
787            Vec::new()
788        };
789        let mut statements = vec![PlanStatement {
790            statement: khive_db::stores::entity::entity_replace_if_unchanged_statement(
791                &entity,
792                expected_updated_at,
793                expected_deleted_at,
794            ),
795            guard: Some(AffectedRowGuard::exactly(1)),
796        }];
797        statements.extend(crate::operations::unguarded_alias_statements(
798            alias_statements,
799        ));
800        if let Some(event) = required_event {
801            let event = EventAttribution::from_token(token).stamp(event);
802            statements.extend(
803                khive_db::stores::event::event_insert_statements(&event)
804                    .map_err(|error| {
805                        RuntimeError::Internal(format!("required entity event: {error}"))
806                    })?
807                    .into_iter()
808                    .map(|statement| PlanStatement {
809                        statement,
810                        guard: None,
811                    }),
812            );
813        }
814        let plan = UpdatePlan {
815            target_id: id,
816            statements,
817            post_commit: PostCommitEffect::None,
818            edge_natural_key: None,
819            idempotent_noop: false,
820            entity_guard: expected_version.map(|expected_version| {
821                crate::entity_write::EntityWriteGuard {
822                    id,
823                    expected_version,
824                }
825            }),
826            note_guard: None,
827            note_vector_purge: None,
828            note_embedding_inheritance: None,
829            graph_effects: Vec::new(),
830        };
831        let captured_models = models.clone();
832        let generation = Uuid::new_v4();
833        let pending_at = chrono::Utc::now().timestamp_micros();
834        let namespace = entity.namespace.clone();
835        let op: PreparedAtomicOp<
836            Option<khive_db::pending_index::PendingEntityIndex>,
837            AtomicOpFailure,
838        > = Box::new(move |writer| {
839            Box::pin(async move {
840                let plan = AtomicOpPlan::Update(Box::new(plan));
841                match apply_plan_preserving_storage(writer, &plan, false).await {
842                    Ok(_) => {}
843                    Err(PlanExecutionFailure::Operation(failure)) => {
844                        return Err(PreparedAtomicError::Refused {
845                            message: "entity update guard refused".into(),
846                            failure,
847                        });
848                    }
849                    Err(PlanExecutionFailure::Storage { source, .. }) => {
850                        return Err(PreparedAtomicError::Storage(source));
851                    }
852                }
853                let pending = if reindex_required {
854                    Some(
855                        khive_db::pending_index::enqueue(
856                            writer,
857                            id,
858                            &namespace,
859                            next_version,
860                            &captured_models,
861                            generation,
862                            pending_at,
863                        )
864                        .await?,
865                    )
866                } else {
867                    None
868                };
869                Ok((pending, Vec::new()))
870            })
871        });
872        let pending = match run_prepared_atomic_unit(self.sql().as_ref(), op).await {
873            Ok(PreparedAtomicOutcome::Committed { value, .. }) => {
874                entity.version = next_version;
875                value
876            }
877            Ok(PreparedAtomicOutcome::RolledBack(AtomicOpFailure::EntityConflict(conflict))) => {
878                return Err(conflict.into_error().into());
879            }
880            Ok(PreparedAtomicOutcome::RolledBack(AtomicOpFailure::GuardFailed { .. })) => {
881                return Err(stale_entity_snapshot_error(id));
882            }
883            Ok(PreparedAtomicOutcome::RolledBack(failure)) => {
884                return Err(RuntimeError::Internal(format!(
885                    "entity update rolled back: {failure:?}"
886                )));
887            }
888            // Preserve the storage owner's unknown-outcome classification unchanged.
889            Err(error) => return Err(RuntimeError::Storage(error)),
890        };
891
892        let event_result: RuntimeResult<()> = async {
893            let event_token =
894                token.with_namespace(crate::Namespace::parse(&entity.namespace).map_err(
895                    |error| RuntimeError::Internal(format!("entity namespace invalid: {error}")),
896                )?);
897            let event_store = self.events(&event_token)?;
898            let event = khive_storage::event::Event::new(
899                entity.namespace.clone(),
900                "update",
901                EventKind::EntityUpdated,
902                SubstrateKind::Entity,
903                "",
904            )
905            .with_target(entity.id)
906            .with_payload(crate::operations::entity_updated_payload(
907                &entity,
908                &changed_fields,
909                previous_name.as_deref(),
910            ));
911            event_store
912                .append_event(event)
913                .await
914                .map(|_| ())
915                .map_err(RuntimeError::Storage)
916        }
917        .await;
918
919        let mut report = match pending {
920            Some(pending) => {
921                self.publish_pending_entity_indexes(token, &entity, &pending, &models)
922                    .await
923            }
924            None => EntityUpdateReport::complete(
925                crate::retrieval::EmbeddingTruncationReport::default(),
926                false,
927            ),
928        };
929        if event_result.is_err() {
930            report
931                .post_commit_degradations
932                .push(crate::PostCommitDegradation {
933                    stage: "event_append",
934                    error: "entity committed; event append did not return a confirmed success"
935                        .into(),
936                });
937        }
938        Ok((entity, report))
939    }
940
941    /// Merge `from_id` into `into_id`.
942    ///
943    /// All edges incident to `from_id` are rewired to `into_id`. Self-loops that would
944    /// result from the rewire are dropped. Properties and tags are merged per `strategy`.
945    /// `from_id` is tombstoned with merge provenance and removed from indexes. Returns a summary.
946    ///
947    /// If `dry_run` is true, computes and returns the planned summary without mutating any rows.
948    ///
949    /// Atomic: all SQL (entity reads/writes, edge rewires, FTS updates, vec-index
950    /// delete, merge event with destructive edge preimages) runs on one pool
951    /// connection inside one `BEGIN IMMEDIATE` transaction via
952    /// `merge_entity_sql`. If embedding vectors are configured, the vector re-insert for
953    /// `into_id` is performed after the transaction (requires async embedding computation).
954    pub async fn merge_entity(
955        &self,
956        token: &NamespaceToken,
957        into_id: Uuid,
958        from_id: Uuid,
959        strategy: EntityDedupMergePolicy,
960        content_strategy: ContentMergeStrategy,
961        dry_run: bool,
962    ) -> RuntimeResult<MergeSummary> {
963        self.merge_entity_with_reason(
964            token,
965            into_id,
966            from_id,
967            strategy,
968            content_strategy,
969            dry_run,
970            None,
971        )
972        .await
973    }
974
975    /// Merge `from_id` into `into_id` and include an optional reason in the audit event.
976    // REASON: these arguments mirror the merge verb's policy, content strategy,
977    // dry-run, and audit-reason fields; a builder would only move that surface.
978    #[allow(clippy::too_many_arguments)]
979    pub async fn merge_entity_with_reason(
980        &self,
981        token: &NamespaceToken,
982        into_id: Uuid,
983        from_id: Uuid,
984        strategy: EntityDedupMergePolicy,
985        content_strategy: ContentMergeStrategy,
986        dry_run: bool,
987        reason: Option<String>,
988    ) -> RuntimeResult<MergeSummary> {
989        self.merge_entity_with_validation(
990            token,
991            into_id,
992            from_id,
993            strategy,
994            content_strategy,
995            dry_run,
996            reason,
997            EntityMergeValidation::LegacyKind,
998            None,
999        )
1000        .await
1001    }
1002
1003    /// Merge two entities with an explicit override for the entity safety floor.
1004    ///
1005    /// Non-forced calls enforce entity kind, name similarity, and project compatibility
1006    /// against the rows reread inside the merge transaction. Legacy merge methods retain
1007    /// their historical same-kind-only policy.
1008    /// A non-dry-run override is recorded as `force: true` in the merge event.
1009    // REASON: these arguments mirror the merge verb's policy, content strategy,
1010    // dry-run, audit-reason, and force fields; a builder would only move that surface.
1011    #[allow(clippy::too_many_arguments)]
1012    pub async fn merge_entity_with_reason_and_force(
1013        &self,
1014        token: &NamespaceToken,
1015        into_id: Uuid,
1016        from_id: Uuid,
1017        strategy: EntityDedupMergePolicy,
1018        content_strategy: ContentMergeStrategy,
1019        dry_run: bool,
1020        reason: Option<String>,
1021        force: bool,
1022    ) -> RuntimeResult<MergeSummary> {
1023        self.merge_entity_with_key_disclosure(
1024            token,
1025            into_id,
1026            from_id,
1027            strategy,
1028            content_strategy,
1029            dry_run,
1030            reason,
1031            force,
1032            &|_: &str| false,
1033        )
1034        .await
1035    }
1036
1037    /// [`Self::merge_entity_with_reason_and_force`], naming in a
1038    /// `merge_key_conflict` (and in a dry run's `key_conflicts`) the live
1039    /// entity holding each conflicting key when `disclose` admits the kept
1040    /// entity's kind. The kind is read before the merge; if the merge reads a
1041    /// different kind no holder is named.
1042    // REASON: the merge verb's fields plus the disclosure rule restore uses.
1043    #[allow(clippy::too_many_arguments)]
1044    pub async fn merge_entity_with_key_disclosure(
1045        &self,
1046        token: &NamespaceToken,
1047        into_id: Uuid,
1048        from_id: Uuid,
1049        strategy: EntityDedupMergePolicy,
1050        content_strategy: ContentMergeStrategy,
1051        dry_run: bool,
1052        reason: Option<String>,
1053        force: bool,
1054        disclose: &(dyn Fn(&str) -> bool + Sync),
1055    ) -> RuntimeResult<MergeSummary> {
1056        let validation = if force {
1057            EntityMergeValidation::Forced
1058        } else {
1059            EntityMergeValidation::SafetyFloor
1060        };
1061        let disclosed_key_kind = match self.entities(token)?.get_entity(into_id).await? {
1062            Some(into) if disclose(&into.kind) => Some(into.kind),
1063            _ => None,
1064        };
1065        self.merge_entity_with_validation(
1066            token,
1067            into_id,
1068            from_id,
1069            strategy,
1070            content_strategy,
1071            dry_run,
1072            reason,
1073            validation,
1074            disclosed_key_kind,
1075        )
1076        .await
1077    }
1078
1079    #[allow(clippy::too_many_arguments)]
1080    async fn merge_entity_with_validation(
1081        &self,
1082        token: &NamespaceToken,
1083        into_id: Uuid,
1084        from_id: Uuid,
1085        strategy: EntityDedupMergePolicy,
1086        content_strategy: ContentMergeStrategy,
1087        dry_run: bool,
1088        reason: Option<String>,
1089        validation: EntityMergeValidation,
1090        disclosed_key_kind: Option<String>,
1091    ) -> RuntimeResult<MergeSummary> {
1092        if let Some(reason) = reason.as_deref() {
1093            crate::secret_gate::check_at(reason, "merge", "reason")?;
1094        }
1095        if into_id == from_id {
1096            return Err(RuntimeError::InvalidInput(
1097                "cannot merge an entity into itself".into(),
1098            ));
1099        }
1100        let ns = token.namespace().as_str().to_owned();
1101        let fts_table = "fts_entities".to_string();
1102        // One immutable registry view governs transactional deletion, table
1103        // preparation, and survivor reindex. A late model belongs to a later
1104        // write/backfill rather than only one leg of this merge.
1105        let embedding_plan = EmbeddingModelPlan::capture(self);
1106        let vec_tables = embedding_plan.vector_tables();
1107        // Loaded once here (sync, cheap) so the rewire loop can evaluate the
1108        // endpoint contract without an async round-trip per edge (khive#1216).
1109        let pack_rules = self.pack_edge_rules();
1110
1111        // Ensure all required tables exist (idempotent DDL) before the transaction.
1112        let _ = self.entities(token)?;
1113        let _ = self.graph(token)?;
1114        let _ = self.text(token)?;
1115        let _ = self.events(token)?;
1116        // vectors_for_model (not the default-model-only self.vectors()) so
1117        // custom-only runtimes (no default embedding_model) still get DDL primed.
1118        for model_name in embedding_plan.model_names() {
1119            let _ = self.vectors_for_model(token, model_name)?;
1120        }
1121
1122        let pool = self.backend().pool_arc();
1123        let writer_task = pool
1124            .writer_task_for_runtime_write(RuntimeWriteOperation::MergeEntity)
1125            .map_err(RuntimeError::Storage)?;
1126        // Minted before the transaction so the tombstone and its in-transaction
1127        // EntityMerged event carry the same id.
1128        let merge_event_id = Uuid::new_v4();
1129        let event_context = MergeEventContext {
1130            attribution: EventAttribution::from_token(token),
1131            reason,
1132            force: validation == EntityMergeValidation::Forced,
1133            strategy,
1134            content_strategy,
1135            kind: EventKind::EntityMerged,
1136            substrate: SubstrateKind::Entity,
1137            event_id: Some(merge_event_id),
1138        };
1139
1140        let (mut summary, updated_entity) = if let Some(writer_task) = writer_task {
1141            writer_task
1142                .send(move |conn| {
1143                    merge_entity_sql(
1144                        conn,
1145                        ns,
1146                        fts_table,
1147                        vec_tables,
1148                        into_id,
1149                        from_id,
1150                        strategy,
1151                        content_strategy,
1152                        dry_run,
1153                        pack_rules,
1154                        validation,
1155                        MergeTxLimits::default(),
1156                        merge_event_id,
1157                        Some(event_context),
1158                        disclosed_key_kind,
1159                    )
1160                    .map_err(|e| {
1161                        e.into_storage_error(
1162                            khive_storage::StorageCapability::Entities,
1163                            "merge_entity",
1164                        )
1165                    })
1166                })
1167                .await
1168                .inspect_err(|error| khive_storage::usage::account_event_write(Err(error)))
1169                .map_err(map_merge_entity_storage_error)?
1170        } else {
1171            tokio::task::spawn_blocking(move || {
1172                let guard = pool.writer()?;
1173                let mut refusal = None;
1174                let result = guard.transaction(|conn| {
1175                    merge_entity_sql(
1176                        conn,
1177                        ns,
1178                        fts_table,
1179                        vec_tables,
1180                        into_id,
1181                        from_id,
1182                        strategy,
1183                        content_strategy,
1184                        dry_run,
1185                        pack_rules,
1186                        validation,
1187                        MergeTxLimits::default(),
1188                        merge_event_id,
1189                        Some(event_context),
1190                        disclosed_key_kind,
1191                    )
1192                    .map_err(|error| match error {
1193                        MergeSqlError::Sqlite(error) => error,
1194                        MergeSqlError::Refusal(error) => {
1195                            refusal = Some(error);
1196                            SqliteError::InvalidData(
1197                                "entity merge refused by transactional policy".to_string(),
1198                            )
1199                        }
1200                    })
1201                });
1202                match refusal {
1203                    Some(error) => Err(error),
1204                    None => result.map_err(RuntimeError::from),
1205                }
1206            })
1207            .await
1208            .map_err(|e| RuntimeError::Internal(e.to_string()))??
1209        };
1210
1211        // Count only committed event rows; dry-run never inserts an event.
1212        if !dry_run {
1213            khive_storage::usage::account_event_write(Ok(1));
1214            tracing::info!(
1215                into_id = %summary.kept_id,
1216                from_id = %summary.removed_id,
1217                budget_rows = summary.tx_budget.rows_charged,
1218                budget_bytes = summary.tx_budget.bytes_charged,
1219                budget_max_rows = summary.tx_budget.max_rows,
1220                budget_max_bytes = summary.tx_budget.max_bytes,
1221                "merge_entity: transaction materialization budget"
1222            );
1223        }
1224
1225        // FTS and vec-deletes already committed inside the transaction above;
1226        // only the embedding re-insert needs an async step outside it.
1227        if !dry_run && !embedding_plan.is_empty() {
1228            match self
1229                .reindex_entity_with_plan(token, &updated_entity, &embedding_plan, None)
1230                .await
1231            {
1232                Ok(report) => summary.embedding_truncation = report,
1233                Err(error) => {
1234                    tracing::warn!(
1235                        into_id = %summary.kept_id,
1236                        from_id = %summary.removed_id,
1237                        error = %error,
1238                        "merge_entity: committed merge but survivor reindex failed"
1239                    );
1240                    summary.post_commit_reindex_error = Some(error.to_string());
1241                }
1242            }
1243        }
1244
1245        Ok(summary)
1246    }
1247
1248    // ---- Internal helpers ----
1249
1250    pub(crate) async fn apply_entity_index_revision(
1251        &self,
1252        entity: &Entity,
1253        statements: Vec<SqlStatement>,
1254    ) -> RuntimeResult<bool> {
1255        let namespace = entity.namespace.clone();
1256        let id = entity.id.to_string();
1257        let version = entity.version;
1258        let op: AtomicUnitOp = Box::new(move |writer| {
1259            Box::pin(async move {
1260                let current = writer
1261                    .query_scalar(SqlStatement {
1262                        sql: "SELECT version FROM entities \
1263                              WHERE namespace=?1 AND id=?2 AND deleted_at IS NULL"
1264                            .into(),
1265                        params: vec![SqlValue::Text(namespace), SqlValue::Text(id)],
1266                        label: Some("entity-index-revision".into()),
1267                    })
1268                    .await?;
1269                if !matches!(current, Some(SqlValue::Integer(current)) if current == version) {
1270                    return Ok(Box::new(false) as Box<dyn Any + Send>);
1271                }
1272                for statement in statements {
1273                    writer.execute(statement).await?;
1274                }
1275                Ok(Box::new(true) as Box<dyn Any + Send>)
1276            })
1277        });
1278        self.sql()
1279            .atomic_unit(op)
1280            .await?
1281            .downcast::<bool>()
1282            .map(|result| *result)
1283            .map_err(|_| RuntimeError::Internal("invalid entity index outcome".into()))
1284    }
1285
1286    pub(crate) fn entity_vector_insert_statements(
1287        table: &str,
1288        entity: &Entity,
1289        model_name: &str,
1290        vector: &[f32],
1291    ) -> Vec<SqlStatement> {
1292        let subject = entity.id.to_string();
1293        let model_key = table
1294            .strip_prefix("vec_")
1295            .expect("runtime vector tables use the vec_ prefix");
1296        let kind = SubstrateKind::Entity.to_string();
1297        let field = "entity.body";
1298        let blob = khive_storage::encode_f32_native(vector);
1299        vec![
1300            SqlStatement {
1301                sql: format!(
1302                    "INSERT INTO ann_write_log \
1303                     (namespace, embedding_model, kind, field, subject_id, op) \
1304                     SELECT namespace, embedding_model, kind, field, subject_id, 'delete' \
1305                     FROM {table} WHERE subject_id=?1 AND NOT \
1306                     (namespace=?2 AND embedding_model=?3 AND kind=?4 AND field=?5)"
1307                ),
1308                params: vec![
1309                    SqlValue::Text(subject.clone()),
1310                    SqlValue::Text(entity.namespace.clone()),
1311                    SqlValue::Text(model_name.to_string()),
1312                    SqlValue::Text(kind.clone()),
1313                    SqlValue::Text(field.into()),
1314                ],
1315                label: Some("entity-reindex-log-delete".into()),
1316            },
1317            SqlStatement {
1318                sql: format!("DELETE FROM {table} WHERE subject_id=?1"),
1319                params: vec![SqlValue::Text(subject.clone())],
1320                label: Some("entity-reindex-vector-delete".into()),
1321            },
1322            // This raw replacement cannot attest the embedded input. Clear the old
1323            // sidecar in the same atomic index revision even when the new BLOB is
1324            // byte-identical to the old one.
1325            SqlStatement {
1326                sql: "DELETE FROM vector_provenance \
1327                      WHERE model_key = ?1 AND subject_id = ?2"
1328                    .into(),
1329                params: vec![
1330                    SqlValue::Text(model_key.to_string()),
1331                    SqlValue::Text(subject.clone()),
1332                ],
1333                label: Some("entity-reindex-provenance-clear".into()),
1334            },
1335            SqlStatement {
1336                sql: format!(
1337                    "INSERT INTO {table} \
1338                     (subject_id, namespace, kind, field, embedding_model, embedding) \
1339                     VALUES (?1, ?2, ?3, ?4, ?5, ?6)"
1340                ),
1341                params: vec![
1342                    SqlValue::Text(subject.clone()),
1343                    SqlValue::Text(entity.namespace.clone()),
1344                    SqlValue::Text(kind.clone()),
1345                    SqlValue::Text(field.into()),
1346                    SqlValue::Text(model_name.to_string()),
1347                    SqlValue::Blob(blob),
1348                ],
1349                label: Some("entity-reindex-vector-insert".into()),
1350            },
1351            SqlStatement {
1352                sql: "INSERT INTO ann_write_log \
1353                      (namespace, embedding_model, kind, field, subject_id, op) \
1354                      VALUES (?1, ?2, ?3, ?4, ?5, 'upsert')"
1355                    .into(),
1356                params: vec![
1357                    SqlValue::Text(entity.namespace.clone()),
1358                    SqlValue::Text(model_name.to_string()),
1359                    SqlValue::Text(kind),
1360                    SqlValue::Text(field.into()),
1361                    SqlValue::Text(subject),
1362                ],
1363                label: Some("entity-reindex-log-upsert".into()),
1364            },
1365        ]
1366    }
1367
1368    pub(crate) async fn publish_entity_vector_revision(
1369        &self,
1370        token: &NamespaceToken,
1371        entity: &Entity,
1372        model_name: &str,
1373        vector: &[f32],
1374    ) -> RuntimeResult<bool> {
1375        self.vectors_for_model(token, model_name)?;
1376        let (storage_model, dimensions) = self.vector_model_metadata(model_name)?;
1377        if let Some(index) = crate::atomic_message::non_finite_index(vector) {
1378            return Err(RuntimeError::InvalidInput(format!(
1379                "non-finite entity vector at index {index}"
1380            )));
1381        }
1382        if vector.len() != dimensions {
1383            return Err(RuntimeError::InvalidInput(format!(
1384                "entity vector has {} dimensions; expected {dimensions}",
1385                vector.len()
1386            )));
1387        }
1388        let table = format!("vec_{}", crate::config::sanitize_key(&storage_model));
1389        let statements =
1390            Self::entity_vector_insert_statements(&table, entity, &storage_model, vector);
1391        #[cfg(test)]
1392        race_seam::pause_before_entity_vector_publish().await;
1393        self.apply_entity_index_revision(entity, statements).await
1394    }
1395
1396    /// Re-upsert FTS5 document and vector(s) for the entity across all registered models.
1397    ///
1398    /// Uses `entity.namespace` — the authoritative namespace stored on the record — rather
1399    /// than the caller-supplied `namespace` parameter. This prevents a cross-namespace
1400    /// reindex from writing the search document into the wrong namespace's FTS index.
1401    ///
1402    /// Best-effort for vectors: if embedding or inserting for a particular model fails,
1403    /// logs a warning and continues to the next model. The FTS step is fail-closed
1404    /// (propagates error). Callers (update_entity, merge_entity) have already committed
1405    /// the entity row, so a partial embed miss leaves a stale vector rather than
1406    /// rolling back the update. Each failed guarded vector replacement rolls back
1407    /// its own index writes, keeping the prior row searchable.
1408    pub(crate) async fn reindex_entity(
1409        &self,
1410        token: &NamespaceToken,
1411        entity: &Entity,
1412    ) -> RuntimeResult<crate::retrieval::EmbeddingTruncationReport> {
1413        let embedding_plan = EmbeddingModelPlan::capture(self);
1414        self.reindex_entity_with_plan(token, entity, &embedding_plan, None)
1415            .await
1416    }
1417
1418    pub(crate) async fn reindex_entity_with_precomputed(
1419        &self,
1420        token: &NamespaceToken,
1421        entity: &Entity,
1422        mut precomputed: HashMap<String, crate::retrieval::DocumentEmbeddingOutcome>,
1423    ) -> RuntimeResult<crate::retrieval::EmbeddingTruncationReport> {
1424        let embedding_plan = EmbeddingModelPlan::capture(self);
1425        self.reindex_entity_with_plan(token, entity, &embedding_plan, Some(&mut precomputed))
1426            .await
1427    }
1428
1429    pub(super) async fn reindex_entity_with_plan(
1430        &self,
1431        token: &NamespaceToken,
1432        entity: &Entity,
1433        embedding_plan: &EmbeddingModelPlan,
1434        mut precomputed: Option<&mut HashMap<String, crate::retrieval::DocumentEmbeddingOutcome>>,
1435    ) -> RuntimeResult<crate::retrieval::EmbeddingTruncationReport> {
1436        // Test-only fault seam: force the post-commit FTS leg to fail after a
1437        // merge or update has already persisted its entity row.
1438        #[cfg(test)]
1439        if crate::operations::consume_fts_fail_fault(&entity.namespace) {
1440            return Err(RuntimeError::Internal("injected FTS failure".to_string()));
1441        }
1442        // Use entity.namespace (authoritative) rather than token.namespace().as_str() (caller claim).
1443        let doc = entity_fts_document(entity);
1444        let embed_body = doc.body.clone();
1445        let _ = self.text(token)?;
1446        #[cfg(test)]
1447        race_seam::pause_before_entity_index_publish().await;
1448        let statements = khive_db::stores::text::delete_document_statements(
1449            "fts_entities",
1450            &entity.namespace,
1451            entity.id,
1452        )
1453        .into_iter()
1454        .chain(khive_db::stores::text::insert_document_statements(
1455            "fts_entities",
1456            &doc,
1457        ))
1458        .collect();
1459        if !self.apply_entity_index_revision(entity, statements).await? {
1460            return Ok(crate::retrieval::EmbeddingTruncationReport::default());
1461        }
1462
1463        let mut report = crate::retrieval::EmbeddingTruncationReport::default();
1464        for model_name in embedding_plan.model_names() {
1465            let embedding = match precomputed
1466                .as_mut()
1467                .and_then(|outcomes| outcomes.remove(model_name))
1468            {
1469                Some(outcome) => Ok(outcome),
1470                None => {
1471                    self.embed_document_with_model_outcome_for_token(token, model_name, &embed_body)
1472                        .await
1473                }
1474            };
1475            match embedding {
1476                Ok(outcome) => {
1477                    report.observe(&outcome);
1478                    match self
1479                        .publish_entity_vector_revision(token, entity, model_name, &outcome.vector)
1480                        .await
1481                    {
1482                        Ok(true) => {}
1483                        Ok(false) => break,
1484                        Err(error) => tracing::warn!(
1485                            model = model_name,
1486                            id = %entity.id,
1487                            "reindex_entity: vector insert failed, skipping model: {error}"
1488                        ),
1489                    }
1490                }
1491                Err(e) => {
1492                    tracing::warn!(
1493                        model = model_name,
1494                        id = %entity.id,
1495                        "reindex_entity: embed failed for model, skipping: {e}"
1496                    );
1497                }
1498            }
1499        }
1500
1501        Ok(report)
1502    }
1503}