khive-runtime 0.10.0

Composable Service API: entity/note CRUD, graph traversal, hybrid search, curation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
#[cfg(test)]
use super::race_seam;
use super::{
    entity_fts_document, map_merge_entity_storage_error, merge_entity_sql, merge_properties,
    stale_entity_snapshot_error, Any, AtomicUnitOp, ContentMergeStrategy, EmbeddingModelPlan,
    Entity, EntityDedupMergePolicy, EntityMergeValidation, EntityPatch, EventAttribution,
    EventKind, HashMap, KhiveRuntime, MergeEventContext, MergeSqlError, MergeSummary,
    MergeTxLimits, NamespaceToken, RuntimeError, RuntimeResult, RuntimeWriteOperation,
    SqlStatement, SqlValue, SqliteError, SubstrateKind, Uuid, Value,
};

impl KhiveRuntime {
    /// Patch-style entity update.
    ///
    /// Only fields set to `Some(_)` are changed. Re-indexes FTS5 (and vectors if configured)
    /// when `name`, `description`, or `entity_type` changes; skips re-indexing for
    /// property/tag-only patches.
    ///
    /// Returns `RuntimeError::NotFound` if the entity does not exist or belongs to a different
    /// namespace. Namespace isolation is enforced at the runtime layer.
    /// Computes the patched `Entity`, `reindex_required`, and `changed_fields` without
    /// writing anything, so both the normal write path and the atomic-prepare path
    /// share one source of truth for what a patched entity looks like.
    pub(crate) async fn prepare_update_entity(
        &self,
        token: &NamespaceToken,
        id: Uuid,
        patch: EntityPatch,
    ) -> RuntimeResult<(Entity, bool, Vec<&'static str>, i64, Option<i64>)> {
        self.prepare_guarded_entity_update(token, id, patch, None, &[])
            .await
    }

    async fn prepare_guarded_entity_update(
        &self,
        token: &NamespaceToken,
        id: Uuid,
        patch: EntityPatch,
        expected: Option<&Entity>,
        remove_properties: &[&str],
    ) -> RuntimeResult<(Entity, bool, Vec<&'static str>, i64, Option<i64>)> {
        crate::secret_gate::reject_reserved_secret_gate_property(patch.properties.as_ref())?;
        if !remove_properties.is_empty() {
            let removals = Value::Object(
                remove_properties
                    .iter()
                    .map(|key| ((*key).to_string(), Value::Null))
                    .collect(),
            );
            crate::secret_gate::reject_reserved_secret_gate_property(Some(&removals))?;
        }
        if let Some(ref name) = patch.name {
            crate::secret_gate::check_at(name, "entity", "name")?;
        }
        if let Some(Some(ref desc)) = patch.description {
            crate::secret_gate::check_at(desc, "entity", "description")?;
        }
        if let Some(ref props) = patch.properties {
            crate::secret_gate::check_json_at(props, "entity", "properties")?;
        }
        if let Some(ref tags) = patch.tags {
            crate::secret_gate::check_tags_at(tags, "entity", "tags")?;
        }
        let store = self.entities(token)?;
        let mut entity = store.get_entity(id).await?.ok_or_else(|| {
            if expected.is_some() {
                stale_entity_snapshot_error(id)
            } else {
                RuntimeError::NotFound(format!("entity {id}"))
            }
        })?;
        if let Some(expected) = expected {
            let actual = serde_json::to_value(&entity)
                .map_err(|error| RuntimeError::Internal(error.to_string()))?;
            let expected = serde_json::to_value(expected)
                .map_err(|error| RuntimeError::Internal(error.to_string()))?;
            if actual != expected {
                return Err(stale_entity_snapshot_error(id));
            }
        }
        let expected_updated_at = entity.updated_at;
        let expected_deleted_at = entity.deleted_at;
        #[cfg(test)]
        race_seam::pause_after_read().await;

        // ADR-014 tri-state: outer `None` = unchanged; `Some(None)` = explicit
        // clear (no vocabulary validation — there is no value to validate);
        // `Some(Some(raw))` = set, validated and normalized.
        let validated_entity_type = match &patch.entity_type {
            Some(None) => Some(None),
            Some(Some(raw)) => Some(Some(
                self.validate_entity_type_for_kind(&entity.kind, Some(raw))?
                    .expect("set branch always yields a normalized value"),
            )),
            None => None,
        };

        let mut reindex_required = false;
        let mut changed_fields: Vec<&'static str> = Vec::new();

        if let Some(name) = patch.name {
            reindex_required |= entity.name != name;
            entity.name = name;
            changed_fields.push("name");
        }
        if let Some(desc_patch) = patch.description {
            reindex_required |= entity.description != desc_patch;
            entity.description = desc_patch;
            changed_fields.push("description");
        }
        if let Some(props) = patch.properties {
            let (merged, _) = merge_properties(
                &entity.properties,
                &Some(props),
                EntityDedupMergePolicy::PreferFrom,
            );
            entity.properties = merged;
            changed_fields.push("properties");
        }
        if let Some(Value::Object(properties)) = entity.properties.as_mut() {
            let mut removed = false;
            for key in remove_properties {
                removed |= properties.remove(*key).is_some();
            }
            if removed && !changed_fields.contains(&"properties") {
                changed_fields.push("properties");
            }
        }
        if let Some(tags) = patch.tags {
            entity.tags = tags;
            changed_fields.push("tags");
        }
        if let Some(entity_type) = validated_entity_type {
            reindex_required |= entity.entity_type != entity_type;
            entity.entity_type = entity_type;
            changed_fields.push("entity_type");
        }

        // A patch may carry properties from the stored row into the full
        // replacement. Validate the final object, including that carry.
        crate::secret_gate::reject_reserved_secret_gate_property(entity.properties.as_ref())?;

        if expected.is_some() && changed_fields.is_empty() {
            return Ok((
                entity,
                reindex_required,
                changed_fields,
                expected_updated_at,
                expected_deleted_at,
            ));
        }

        // #2943: `entity.properties`, `entity.entity_type`, and `entity.tags`
        // are all final here — the owning pack's KindHook, if any, validates
        // the resulting record, mirroring `prepare_note_update_hook` on the
        // note side. `Ok(())` when no pack registered a hook for this entity
        // kind (the trait default, or the runtime-layer aggregate was never
        // installed). Placed after the no-op early return above so a
        // genuinely unchanged guarded update never re-runs the hook for
        // nothing; only `updated_at` remains to be bumped after this point.
        if let Some(hook) = self.entity_kind_hook(&entity.kind) {
            hook.validate_entity_update(self, token, &entity, entity.properties.as_ref())
                .await?;
        }

        // `updated_at` is also the optimistic-concurrency revision for
        // full-entity replacement. Make it strictly advance even when two
        // operations land inside one clock microsecond. Saturation is not a
        // valid fallback: reusing i64::MAX would make the CAS accept a write
        // without advancing its revision.
        let minimum_updated_at = expected_updated_at.checked_add(1).ok_or_else(|| {
            RuntimeError::Internal(format!(
                "entity {id} updated_at is already at i64::MAX and cannot advance"
            ))
        })?;
        entity.updated_at = chrono::Utc::now()
            .timestamp_micros()
            .max(minimum_updated_at);
        Ok((
            entity,
            reindex_required,
            changed_fields,
            expected_updated_at,
            expected_deleted_at,
        ))
    }

    #[cfg(test)]
    pub(crate) async fn update_entity(
        &self,
        token: &NamespaceToken,
        id: Uuid,
        patch: EntityPatch,
    ) -> RuntimeResult<Entity> {
        Ok(self
            .update_entity_with_embedding_report(token, id, patch)
            .await?
            .0)
    }

    pub async fn update_entity_with_embedding_report(
        &self,
        token: &NamespaceToken,
        id: Uuid,
        patch: EntityPatch,
    ) -> RuntimeResult<(Entity, crate::retrieval::EmbeddingTruncationReport)> {
        self.update_entity_with_expected_version_and_embedding_report(token, id, patch, None)
            .await
    }

    /// Entity update with an optional caller revision, checked inside the writer transaction.
    pub async fn update_entity_with_expected_version_and_embedding_report(
        &self,
        token: &NamespaceToken,
        id: Uuid,
        patch: EntityPatch,
        expected_version: Option<i64>,
    ) -> RuntimeResult<(Entity, crate::retrieval::EmbeddingTruncationReport)> {
        crate::entity_write::validate_expected_version(expected_version)?;
        let (entity, reindex_required, changed_fields, expected_updated_at, expected_deleted_at) =
            self.prepare_update_entity(token, id, patch).await?;

        self.persist_prepared_entity_update(
            token,
            entity,
            reindex_required,
            changed_fields,
            expected_updated_at,
            expected_deleted_at,
            expected_version,
        )
        .await
    }

    /// Apply an admin patch only if the entity still matches the full read snapshot.
    /// Property removals apply after the normal merge and preserve all other keys.
    /// Missing keys alone are a no-op; reserved runtime-owned keys cannot be removed.
    /// A changed, deleted, or missing entity returns a conflict without writing.
    /// A bounded embedding returns a non-retryable error with the committed ID
    /// and truncation report; use the report-aware variant to retain the record.
    pub async fn update_entity_if_unchanged(
        &self,
        token: &NamespaceToken,
        expected: &Entity,
        patch: EntityPatch,
        remove_properties: &[&str],
    ) -> RuntimeResult<Entity> {
        let (entity, embedding) = self
            .update_entity_if_unchanged_with_embedding_report(
                token,
                expected,
                patch,
                remove_properties,
            )
            .await?;
        crate::operations::legacy_post_commit_result_with_embedding(
            "update_entity_if_unchanged",
            entity.id,
            entity,
            embedding,
            Vec::new(),
        )
    }

    /// Apply a guarded admin patch and retain embedding truncation accounting.
    pub async fn update_entity_if_unchanged_with_embedding_report(
        &self,
        token: &NamespaceToken,
        expected: &Entity,
        patch: EntityPatch,
        remove_properties: &[&str],
    ) -> RuntimeResult<(Entity, crate::retrieval::EmbeddingTruncationReport)> {
        let (entity, reindex_required, changed_fields, expected_updated_at, expected_deleted_at) =
            self.prepare_guarded_entity_update(
                token,
                expected.id,
                patch,
                Some(expected),
                remove_properties,
            )
            .await?;
        if changed_fields.is_empty() {
            return Ok((
                entity,
                crate::retrieval::EmbeddingTruncationReport::default(),
            ));
        }
        self.persist_prepared_entity_update(
            token,
            entity,
            reindex_required,
            changed_fields,
            expected_updated_at,
            expected_deleted_at,
            None,
        )
        .await
    }

    #[allow(clippy::too_many_arguments)]
    pub(super) async fn persist_prepared_entity_update(
        &self,
        token: &NamespaceToken,
        mut entity: Entity,
        reindex_required: bool,
        changed_fields: Vec<&'static str>,
        expected_updated_at: i64,
        expected_deleted_at: Option<i64>,
        expected_version: Option<i64>,
    ) -> RuntimeResult<(Entity, crate::retrieval::EmbeddingTruncationReport)> {
        // This final whole-object replacement must reserve the complete
        // candidate, even if a future caller bypasses the patch preparer.
        crate::secret_gate::reject_reserved_secret_gate_property(entity.properties.as_ref())?;
        let id = entity.id;
        let _ = self.entities(token)?;
        let next_version = entity
            .version
            .checked_add(1)
            .ok_or_else(|| RuntimeError::InvalidInput("entity version overflow".into()))?;
        use crate::atomic_plan::{AffectedRowGuard, PlanStatement, PostCommitEffect, UpdatePlan};
        use crate::atomic_runner::{
            run_atomic_unit, AtomicOpFailure, AtomicOpPlan, AtomicRunOutcome,
        };
        let plan = UpdatePlan {
            target_id: id,
            statements: vec![PlanStatement {
                statement: khive_db::stores::entity::entity_replace_if_unchanged_statement(
                    &entity,
                    expected_updated_at,
                    expected_deleted_at,
                ),
                guard: Some(AffectedRowGuard::exactly(1)),
            }],
            post_commit: PostCommitEffect::None,
            edge_natural_key: None,
            idempotent_noop: false,
            entity_guard: expected_version.map(|expected_version| {
                crate::entity_write::EntityWriteGuard {
                    id,
                    expected_version,
                }
            }),
            note_guard: None,
            note_vector_purge: None,
            note_embedding_inheritance: None,
            graph_effects: Vec::new(),
        };
        match run_atomic_unit(
            self.sql().as_ref(),
            vec![AtomicOpPlan::Update(Box::new(plan))],
        )
        .await
        {
            Ok(AtomicRunOutcome::Committed { .. }) => entity.version = next_version,
            Ok(AtomicRunOutcome::RolledBack {
                failure: AtomicOpFailure::EntityConflict(conflict),
                ..
            }) => return Err(conflict.into_error().into()),
            Ok(AtomicRunOutcome::RolledBack {
                failure: AtomicOpFailure::GuardFailed { .. },
                ..
            }) => return Err(stale_entity_snapshot_error(id)),
            Ok(AtomicRunOutcome::RolledBack { failure, .. }) => {
                return Err(RuntimeError::Internal(format!(
                    "entity update rolled back: {failure:?}"
                )))
            }
            Err(error) => return Err(RuntimeError::Storage(error.0)),
        }

        let event_token =
            token.with_namespace(crate::Namespace::parse(&entity.namespace).map_err(|error| {
                RuntimeError::Internal(format!("entity namespace invalid: {error}"))
            })?);
        let event_store = self.events(&event_token)?;
        let event = khive_storage::event::Event::new(
            entity.namespace.clone(),
            "update",
            EventKind::EntityUpdated,
            SubstrateKind::Entity,
            "",
        )
        .with_target(entity.id)
        .with_payload(serde_json::json!({
            "id": entity.id,
            "namespace": entity.namespace,
            "changed_fields": changed_fields,
        }));
        let event_result = event_store.append_event(event).await.map_err(|e| {
            RuntimeError::Internal(format!("update_entity: event store write failed: {e}"))
        });

        let embedding_report = if reindex_required {
            self.reindex_entity(token, &entity).await?
        } else {
            crate::retrieval::EmbeddingTruncationReport::default()
        };

        event_result?;

        Ok((entity, embedding_report))
    }

    /// Merge `from_id` into `into_id`.
    ///
    /// All edges incident to `from_id` are rewired to `into_id`. Self-loops that would
    /// result from the rewire are dropped. Properties and tags are merged per `strategy`.
    /// `from_id` is tombstoned with merge provenance and removed from indexes. Returns a summary.
    ///
    /// If `dry_run` is true, computes and returns the planned summary without mutating any rows.
    ///
    /// Atomic: all SQL (entity reads/writes, edge rewires, FTS updates, vec-index
    /// delete, merge event with destructive edge preimages) runs on one pool
    /// connection inside one `BEGIN IMMEDIATE` transaction via
    /// `merge_entity_sql`. If embedding vectors are configured, the vector re-insert for
    /// `into_id` is performed after the transaction (requires async embedding computation).
    pub async fn merge_entity(
        &self,
        token: &NamespaceToken,
        into_id: Uuid,
        from_id: Uuid,
        strategy: EntityDedupMergePolicy,
        content_strategy: ContentMergeStrategy,
        dry_run: bool,
    ) -> RuntimeResult<MergeSummary> {
        self.merge_entity_with_reason(
            token,
            into_id,
            from_id,
            strategy,
            content_strategy,
            dry_run,
            None,
        )
        .await
    }

    /// Merge `from_id` into `into_id` and include an optional reason in the audit event.
    // REASON: these arguments mirror the merge verb's policy, content strategy,
    // dry-run, and audit-reason fields; a builder would only move that surface.
    #[allow(clippy::too_many_arguments)]
    pub async fn merge_entity_with_reason(
        &self,
        token: &NamespaceToken,
        into_id: Uuid,
        from_id: Uuid,
        strategy: EntityDedupMergePolicy,
        content_strategy: ContentMergeStrategy,
        dry_run: bool,
        reason: Option<String>,
    ) -> RuntimeResult<MergeSummary> {
        self.merge_entity_with_validation(
            token,
            into_id,
            from_id,
            strategy,
            content_strategy,
            dry_run,
            reason,
            EntityMergeValidation::LegacyKind,
        )
        .await
    }

    /// Merge two entities with an explicit override for the entity safety floor.
    ///
    /// Non-forced calls enforce entity kind, name similarity, and project compatibility
    /// against the rows reread inside the merge transaction. Legacy merge methods retain
    /// their historical same-kind-only policy.
    /// A non-dry-run override is recorded as `force: true` in the merge event.
    // REASON: these arguments mirror the merge verb's policy, content strategy,
    // dry-run, audit-reason, and force fields; a builder would only move that surface.
    #[allow(clippy::too_many_arguments)]
    pub async fn merge_entity_with_reason_and_force(
        &self,
        token: &NamespaceToken,
        into_id: Uuid,
        from_id: Uuid,
        strategy: EntityDedupMergePolicy,
        content_strategy: ContentMergeStrategy,
        dry_run: bool,
        reason: Option<String>,
        force: bool,
    ) -> RuntimeResult<MergeSummary> {
        let validation = if force {
            EntityMergeValidation::Forced
        } else {
            EntityMergeValidation::SafetyFloor
        };
        self.merge_entity_with_validation(
            token,
            into_id,
            from_id,
            strategy,
            content_strategy,
            dry_run,
            reason,
            validation,
        )
        .await
    }

    #[allow(clippy::too_many_arguments)]
    async fn merge_entity_with_validation(
        &self,
        token: &NamespaceToken,
        into_id: Uuid,
        from_id: Uuid,
        strategy: EntityDedupMergePolicy,
        content_strategy: ContentMergeStrategy,
        dry_run: bool,
        reason: Option<String>,
        validation: EntityMergeValidation,
    ) -> RuntimeResult<MergeSummary> {
        if let Some(reason) = reason.as_deref() {
            crate::secret_gate::check_at(reason, "merge", "reason")?;
        }
        if into_id == from_id {
            return Err(RuntimeError::InvalidInput(
                "cannot merge an entity into itself".into(),
            ));
        }
        let ns = token.namespace().as_str().to_owned();
        let fts_table = "fts_entities".to_string();
        // One immutable registry view governs transactional deletion, table
        // preparation, and survivor reindex. A late model belongs to a later
        // write/backfill rather than only one leg of this merge.
        let embedding_plan = EmbeddingModelPlan::capture(self);
        let vec_tables = embedding_plan.vector_tables();
        // Loaded once here (sync, cheap) so the rewire loop can evaluate the
        // endpoint contract without an async round-trip per edge (khive#1216).
        let pack_rules = self.pack_edge_rules();

        // Ensure all required tables exist (idempotent DDL) before the transaction.
        let _ = self.entities(token)?;
        let _ = self.graph(token)?;
        let _ = self.text(token)?;
        let _ = self.events(token)?;
        // vectors_for_model (not the default-model-only self.vectors()) so
        // custom-only runtimes (no default embedding_model) still get DDL primed.
        for model_name in embedding_plan.model_names() {
            let _ = self.vectors_for_model(token, model_name)?;
        }

        let pool = self.backend().pool_arc();
        let writer_task = pool
            .writer_task_for_runtime_write(RuntimeWriteOperation::MergeEntity)
            .map_err(RuntimeError::Storage)?;
        // Minted before the transaction so the tombstone and its in-transaction
        // EntityMerged event carry the same id.
        let merge_event_id = Uuid::new_v4();
        let event_context = MergeEventContext {
            attribution: EventAttribution::from_token(token),
            reason,
            force: validation == EntityMergeValidation::Forced,
            strategy,
            content_strategy,
            kind: EventKind::EntityMerged,
            substrate: SubstrateKind::Entity,
            event_id: Some(merge_event_id),
        };

        let (mut summary, updated_entity) = if let Some(writer_task) = writer_task {
            writer_task
                .send(move |conn| {
                    merge_entity_sql(
                        conn,
                        ns,
                        fts_table,
                        vec_tables,
                        into_id,
                        from_id,
                        strategy,
                        content_strategy,
                        dry_run,
                        pack_rules,
                        validation,
                        MergeTxLimits::default(),
                        merge_event_id,
                        Some(event_context),
                    )
                    .map_err(|e| {
                        khive_storage::StorageError::driver(
                            khive_storage::StorageCapability::Entities,
                            "merge_entity",
                            e,
                        )
                    })
                })
                .await
                .inspect_err(|error| khive_storage::usage::account_event_write(Err(error)))
                .map_err(map_merge_entity_storage_error)?
        } else {
            tokio::task::spawn_blocking(move || {
                let guard = pool.writer()?;
                let mut refusal = None;
                let result = guard.transaction(|conn| {
                    merge_entity_sql(
                        conn,
                        ns,
                        fts_table,
                        vec_tables,
                        into_id,
                        from_id,
                        strategy,
                        content_strategy,
                        dry_run,
                        pack_rules,
                        validation,
                        MergeTxLimits::default(),
                        merge_event_id,
                        Some(event_context),
                    )
                    .map_err(|error| match error {
                        MergeSqlError::Sqlite(error) => error,
                        MergeSqlError::Refusal(error) => {
                            refusal = Some(error);
                            SqliteError::InvalidData(
                                "entity merge refused by transactional policy".to_string(),
                            )
                        }
                    })
                });
                match refusal {
                    Some(error) => Err(error),
                    None => result.map_err(RuntimeError::from),
                }
            })
            .await
            .map_err(|e| RuntimeError::Internal(e.to_string()))??
        };

        // Count only committed event rows; dry-run never inserts an event.
        if !dry_run {
            khive_storage::usage::account_event_write(Ok(1));
            tracing::info!(
                into_id = %summary.kept_id,
                from_id = %summary.removed_id,
                budget_rows = summary.tx_budget.rows_charged,
                budget_bytes = summary.tx_budget.bytes_charged,
                budget_max_rows = summary.tx_budget.max_rows,
                budget_max_bytes = summary.tx_budget.max_bytes,
                "merge_entity: transaction materialization budget"
            );
        }

        // FTS and vec-deletes already committed inside the transaction above;
        // only the embedding re-insert needs an async step outside it.
        if !dry_run && !embedding_plan.is_empty() {
            match self
                .reindex_entity_with_plan(token, &updated_entity, &embedding_plan, None)
                .await
            {
                Ok(report) => summary.embedding_truncation = report,
                Err(error) => {
                    tracing::warn!(
                        into_id = %summary.kept_id,
                        from_id = %summary.removed_id,
                        error = %error,
                        "merge_entity: committed merge but survivor reindex failed"
                    );
                    summary.post_commit_reindex_error = Some(error.to_string());
                }
            }
        }

        Ok(summary)
    }

    // ---- Internal helpers ----

    async fn apply_entity_index_revision(
        &self,
        entity: &Entity,
        statements: Vec<SqlStatement>,
    ) -> RuntimeResult<bool> {
        let namespace = entity.namespace.clone();
        let id = entity.id.to_string();
        let version = entity.version;
        let op: AtomicUnitOp = Box::new(move |writer| {
            Box::pin(async move {
                let current = writer
                    .query_scalar(SqlStatement {
                        sql: "SELECT version FROM entities \
                              WHERE namespace=?1 AND id=?2 AND deleted_at IS NULL"
                            .into(),
                        params: vec![SqlValue::Text(namespace), SqlValue::Text(id)],
                        label: Some("entity-index-revision".into()),
                    })
                    .await?;
                if !matches!(current, Some(SqlValue::Integer(current)) if current == version) {
                    return Ok(Box::new(false) as Box<dyn Any + Send>);
                }
                for statement in statements {
                    writer.execute(statement).await?;
                }
                Ok(Box::new(true) as Box<dyn Any + Send>)
            })
        });
        self.sql()
            .atomic_unit(op)
            .await?
            .downcast::<bool>()
            .map(|result| *result)
            .map_err(|_| RuntimeError::Internal("invalid entity index outcome".into()))
    }

    pub(crate) fn entity_vector_insert_statements(
        table: &str,
        entity: &Entity,
        model_name: &str,
        vector: &[f32],
    ) -> Vec<SqlStatement> {
        let subject = entity.id.to_string();
        let model_key = table
            .strip_prefix("vec_")
            .expect("runtime vector tables use the vec_ prefix");
        let kind = SubstrateKind::Entity.to_string();
        let field = "entity.body";
        let blob = vector
            .iter()
            .flat_map(|value| value.to_ne_bytes())
            .collect();
        vec![
            SqlStatement {
                sql: format!(
                    "INSERT INTO ann_write_log \
                     (namespace, embedding_model, kind, field, subject_id, op) \
                     SELECT namespace, embedding_model, kind, field, subject_id, 'delete' \
                     FROM {table} WHERE subject_id=?1 AND NOT \
                     (namespace=?2 AND embedding_model=?3 AND kind=?4 AND field=?5)"
                ),
                params: vec![
                    SqlValue::Text(subject.clone()),
                    SqlValue::Text(entity.namespace.clone()),
                    SqlValue::Text(model_name.to_string()),
                    SqlValue::Text(kind.clone()),
                    SqlValue::Text(field.into()),
                ],
                label: Some("entity-reindex-log-delete".into()),
            },
            SqlStatement {
                sql: format!("DELETE FROM {table} WHERE subject_id=?1"),
                params: vec![SqlValue::Text(subject.clone())],
                label: Some("entity-reindex-vector-delete".into()),
            },
            // This raw replacement cannot attest the embedded input. Clear the old
            // sidecar in the same atomic index revision even when the new BLOB is
            // byte-identical to the old one.
            SqlStatement {
                sql: "DELETE FROM vector_provenance \
                      WHERE model_key = ?1 AND subject_id = ?2"
                    .into(),
                params: vec![
                    SqlValue::Text(model_key.to_string()),
                    SqlValue::Text(subject.clone()),
                ],
                label: Some("entity-reindex-provenance-clear".into()),
            },
            SqlStatement {
                sql: format!(
                    "INSERT INTO {table} \
                     (subject_id, namespace, kind, field, embedding_model, embedding) \
                     VALUES (?1, ?2, ?3, ?4, ?5, ?6)"
                ),
                params: vec![
                    SqlValue::Text(subject.clone()),
                    SqlValue::Text(entity.namespace.clone()),
                    SqlValue::Text(kind.clone()),
                    SqlValue::Text(field.into()),
                    SqlValue::Text(model_name.to_string()),
                    SqlValue::Blob(blob),
                ],
                label: Some("entity-reindex-vector-insert".into()),
            },
            SqlStatement {
                sql: "INSERT INTO ann_write_log \
                      (namespace, embedding_model, kind, field, subject_id, op) \
                      VALUES (?1, ?2, ?3, ?4, ?5, 'upsert')"
                    .into(),
                params: vec![
                    SqlValue::Text(entity.namespace.clone()),
                    SqlValue::Text(model_name.to_string()),
                    SqlValue::Text(kind),
                    SqlValue::Text(field.into()),
                    SqlValue::Text(subject),
                ],
                label: Some("entity-reindex-log-upsert".into()),
            },
        ]
    }

    pub(crate) async fn publish_entity_vector_revision(
        &self,
        token: &NamespaceToken,
        entity: &Entity,
        model_name: &str,
        vector: &[f32],
    ) -> RuntimeResult<bool> {
        self.vectors_for_model(token, model_name)?;
        let (storage_model, dimensions) = self.vector_model_metadata(model_name)?;
        if let Some(index) = vector.iter().position(|value| !value.is_finite()) {
            return Err(RuntimeError::InvalidInput(format!(
                "non-finite entity vector at index {index}"
            )));
        }
        if vector.len() != dimensions {
            return Err(RuntimeError::InvalidInput(format!(
                "entity vector has {} dimensions; expected {dimensions}",
                vector.len()
            )));
        }
        let table = format!("vec_{}", crate::config::sanitize_key(&storage_model));
        let statements =
            Self::entity_vector_insert_statements(&table, entity, &storage_model, vector);
        #[cfg(test)]
        race_seam::pause_before_entity_vector_publish().await;
        self.apply_entity_index_revision(entity, statements).await
    }

    /// Re-upsert FTS5 document and vector(s) for the entity across all registered models.
    ///
    /// Uses `entity.namespace` — the authoritative namespace stored on the record — rather
    /// than the caller-supplied `namespace` parameter. This prevents a cross-namespace
    /// reindex from writing the search document into the wrong namespace's FTS index.
    ///
    /// Best-effort for vectors: if embedding or inserting for a particular model fails,
    /// logs a warning and continues to the next model. The FTS step is fail-closed
    /// (propagates error). Callers (update_entity, merge_entity) have already committed
    /// the entity row, so a partial embed miss leaves a stale vector rather than
    /// rolling back the update. Each failed guarded vector replacement rolls back
    /// its own index writes, keeping the prior row searchable.
    pub(crate) async fn reindex_entity(
        &self,
        token: &NamespaceToken,
        entity: &Entity,
    ) -> RuntimeResult<crate::retrieval::EmbeddingTruncationReport> {
        let embedding_plan = EmbeddingModelPlan::capture(self);
        self.reindex_entity_with_plan(token, entity, &embedding_plan, None)
            .await
    }

    pub(crate) async fn reindex_entity_with_precomputed(
        &self,
        token: &NamespaceToken,
        entity: &Entity,
        mut precomputed: HashMap<String, crate::retrieval::DocumentEmbeddingOutcome>,
    ) -> RuntimeResult<crate::retrieval::EmbeddingTruncationReport> {
        let embedding_plan = EmbeddingModelPlan::capture(self);
        self.reindex_entity_with_plan(token, entity, &embedding_plan, Some(&mut precomputed))
            .await
    }

    pub(super) async fn reindex_entity_with_plan(
        &self,
        token: &NamespaceToken,
        entity: &Entity,
        embedding_plan: &EmbeddingModelPlan,
        mut precomputed: Option<&mut HashMap<String, crate::retrieval::DocumentEmbeddingOutcome>>,
    ) -> RuntimeResult<crate::retrieval::EmbeddingTruncationReport> {
        // Test-only fault seam: force the post-commit FTS leg to fail after a
        // merge or update has already persisted its entity row.
        #[cfg(test)]
        if crate::operations::consume_fts_fail_fault(&entity.namespace) {
            return Err(RuntimeError::Internal("injected FTS failure".to_string()));
        }
        // Use entity.namespace (authoritative) rather than token.namespace().as_str() (caller claim).
        let doc = entity_fts_document(entity);
        let embed_body = doc.body.clone();
        let _ = self.text(token)?;
        #[cfg(test)]
        race_seam::pause_before_entity_index_publish().await;
        let statements = khive_db::stores::text::delete_document_statements(
            "fts_entities",
            &entity.namespace,
            entity.id,
        )
        .into_iter()
        .chain(khive_db::stores::text::insert_document_statements(
            "fts_entities",
            &doc,
        ))
        .collect();
        if !self.apply_entity_index_revision(entity, statements).await? {
            return Ok(crate::retrieval::EmbeddingTruncationReport::default());
        }

        let mut report = crate::retrieval::EmbeddingTruncationReport::default();
        for model_name in embedding_plan.model_names() {
            let embedding = match precomputed
                .as_mut()
                .and_then(|outcomes| outcomes.remove(model_name))
            {
                Some(outcome) => Ok(outcome),
                None => {
                    self.embed_document_with_model_outcome_for_token(token, model_name, &embed_body)
                        .await
                }
            };
            match embedding {
                Ok(outcome) => {
                    report.observe(&outcome);
                    match self
                        .publish_entity_vector_revision(token, entity, model_name, &outcome.vector)
                        .await
                    {
                        Ok(true) => {}
                        Ok(false) => break,
                        Err(error) => tracing::warn!(
                            model = model_name,
                            id = %entity.id,
                            "reindex_entity: vector insert failed, skipping model: {error}"
                        ),
                    }
                }
                Err(e) => {
                    tracing::warn!(
                        model = model_name,
                        id = %entity.id,
                        "reindex_entity: embed failed for model, skipping: {e}"
                    );
                }
            }
        }

        Ok(report)
    }
}