Skip to main content

khive_runtime/curation/
entity_pending_index.rs

1//! Durable publication protocol for deferred entity updates (ADR-014 Amendment 7).
2
3use std::any::Any;
4
5use khive_db::pending_index::{
6    self, PendingEntityIndex, PendingIndexTarget, PendingIndexTargetKind,
7};
8use khive_storage::{AtomicUnitOp, Entity, SqlStatement, StorageError, WriterTaskRequestState};
9use serde::Serialize;
10
11use crate::retrieval::EmbeddingTruncationReport;
12use crate::{KhiveRuntime, NamespaceToken, PostCommitDegradation, RuntimeError, RuntimeResult};
13
14#[cfg(test)]
15tokio::task_local! {
16    static UNKNOWN_AFTER_PUBLISH: bool;
17}
18
19/// One required index whose publication was not established by this update.
20#[derive(Clone, Debug, Serialize)]
21pub struct EntityIndexFailure {
22    pub target: PendingIndexTargetKind,
23    /// Sanitized stage; never entity content or provider error text.
24    pub stage: String,
25}
26
27/// The indexing outcome of the committed entity revision, not a backlog census.
28#[derive(Clone, Debug, Serialize)]
29pub struct EntityIndexReport {
30    pub status: &'static str,
31    pub unfinished: Vec<EntityIndexFailure>,
32}
33
34impl EntityIndexReport {
35    pub(super) fn complete(required: bool) -> Self {
36        Self {
37            status: if required {
38                "complete"
39            } else {
40                "not_requested"
41            },
42            unfinished: Vec::new(),
43        }
44    }
45
46    fn unfinished(&mut self, target: &PendingIndexTargetKind, stage: &str) {
47        self.status = "unfinished";
48        self.unfinished.push(EntityIndexFailure {
49            target: target.clone(),
50            stage: stage.into(),
51        });
52    }
53}
54
55/// Report-aware updates retain their committed entity even when indexes fail.
56#[derive(Clone, Debug, Serialize)]
57pub struct EntityUpdateReport {
58    pub embedding: EmbeddingTruncationReport,
59    pub indexing: EntityIndexReport,
60    pub post_commit_degradations: Vec<PostCommitDegradation>,
61    /// What the update's alias change asked for and did not do (ADR-221
62    /// section 2).
63    #[serde(skip_serializing_if = "crate::EntityAliasReport::is_empty")]
64    pub aliases: crate::EntityAliasReport,
65}
66
67impl EntityUpdateReport {
68    pub(super) fn complete(embedding: EmbeddingTruncationReport, required: bool) -> Self {
69        Self {
70            embedding,
71            indexing: EntityIndexReport::complete(required),
72            post_commit_degradations: Vec::new(),
73            aliases: crate::EntityAliasReport::default(),
74        }
75    }
76
77    /// Compatibility callers cannot silently discard committed-but-unfinished work.
78    pub(super) fn into_legacy(
79        self,
80        entity: Entity,
81    ) -> RuntimeResult<(Entity, EmbeddingTruncationReport)> {
82        let mut degradations = self.post_commit_degradations;
83        degradations.extend(self.indexing.unfinished.into_iter().map(|failure| {
84            PostCommitDegradation {
85                stage: "entity_index_unfinished",
86                error: serde_json::json!(failure).to_string(),
87            }
88        }));
89        crate::operations::legacy_post_commit_result(
90            "update_entity",
91            entity.id,
92            (entity, self.embedding),
93            degradations,
94        )
95    }
96}
97
98fn unsettled(error: &RuntimeError) -> bool {
99    error
100        .writer_task_failure_context()
101        .is_some_and(|context| context.request_state == WriterTaskRequestState::SideEffectsUnknown)
102        || matches!(error.refusal_source(), RuntimeError::Storage(error)
103        if error.sqlite_write_failure().is_some_and(|failure| failure.settlement_unknown))
104}
105
106impl KhiveRuntime {
107    /// The sole pending-target consumer, shared by inline work and future recovery.
108    /// The closure performs only synchronous-ready SQL under one writer transaction.
109    pub(super) async fn publish_pending_entity_target(
110        &self,
111        observed: &PendingEntityIndex,
112        target: &PendingIndexTargetKind,
113        statements: Vec<SqlStatement>,
114    ) -> RuntimeResult<bool> {
115        let observed = observed.clone();
116        let target = target.clone();
117        let op: AtomicUnitOp = Box::new(move |writer| {
118            Box::pin(async move {
119                let Some(current) = pending_index::read(writer, observed.entity_id).await? else {
120                    return Ok(Box::new(false) as Box<dyn Any + Send>);
121                };
122                if current.generation != observed.generation
123                    || current.namespace != observed.namespace
124                    || current.source_version != observed.source_version
125                    || !current.targets.iter().any(|entry| {
126                        entry.kind == target && !entry.done && !entry.kind.is_blocked()
127                    })
128                    || !pending_index::live_matches(writer, &current).await?
129                {
130                    return Ok(Box::new(false) as Box<dyn Any + Send>);
131                }
132                for statement in statements {
133                    writer.execute(statement).await?;
134                }
135                if !pending_index::finish(writer, current.entity_id, current.generation, &target)
136                    .await?
137                {
138                    // Never commit index writes without consuming the matching target.
139                    return Err(StorageError::Internal(
140                        "pending index consumption guard failed".into(),
141                    ));
142                }
143                Ok(Box::new(true) as Box<dyn Any + Send>)
144            })
145        });
146        let outcome = self.sql().atomic_unit(op).await?;
147        #[cfg(test)]
148        if UNKNOWN_AFTER_PUBLISH
149            .try_with(|enabled| *enabled)
150            .unwrap_or(false)
151        {
152            return Err(RuntimeError::Storage(StorageError::writer_task_terminated(
153                WriterTaskRequestState::SideEffectsUnknown,
154            )));
155        }
156        outcome
157            .downcast::<bool>()
158            .map(|result| *result)
159            .map_err(|_| RuntimeError::Internal("invalid pending index publication outcome".into()))
160    }
161
162    async fn record_pending_entity_failure(
163        &self,
164        observed: &PendingEntityIndex,
165        target: &PendingIndexTarget,
166        category: &'static str,
167    ) -> RuntimeResult<bool> {
168        let id = observed.entity_id;
169        let generation = observed.generation;
170        let kind = target.kind.clone();
171        // Slice 1 schedules no recovery. Preserve any existing delay; the later
172        // supervised recovery component owns its bounded backoff calculation.
173        let next_eligible_at = target.next_eligible_at;
174        let op: AtomicUnitOp = Box::new(move |writer| {
175            Box::pin(async move {
176                let recorded = pending_index::record_failure(
177                    writer,
178                    id,
179                    generation,
180                    &kind,
181                    category,
182                    next_eligible_at,
183                )
184                .await?;
185                Ok(Box::new(recorded) as Box<dyn Any + Send>)
186            })
187        });
188        self.sql()
189            .atomic_unit(op)
190            .await?
191            .downcast::<bool>()
192            .map(|result| *result)
193            .map_err(|_| RuntimeError::Internal("invalid pending index failure outcome".into()))
194    }
195
196    async fn prepare_pending_entity_target(
197        &self,
198        token: &NamespaceToken,
199        entity: &Entity,
200        target: &PendingIndexTargetKind,
201        snapshot: &[(String, usize)],
202        report: &mut EmbeddingTruncationReport,
203    ) -> Result<Vec<SqlStatement>, (&'static str, RuntimeError)> {
204        match target {
205            PendingIndexTargetKind::Fts => {
206                #[cfg(test)]
207                if crate::operations::consume_fts_fail_fault(&entity.namespace) {
208                    return Err((
209                        "fts_prepare",
210                        RuntimeError::Internal("injected FTS failure".into()),
211                    ));
212                }
213                self.text(token).map_err(|error| ("fts_prepare", error))?;
214                let doc = super::entity_fts_document(entity);
215                Ok(khive_db::stores::text::delete_document_statements(
216                    "fts_entities",
217                    &entity.namespace,
218                    entity.id,
219                )
220                .into_iter()
221                .chain(khive_db::stores::text::insert_document_statements(
222                    "fts_entities",
223                    &doc,
224                ))
225                .collect())
226            }
227            PendingIndexTargetKind::Vector { model, dimensions } => {
228                let Some((_, captured_dimensions)) =
229                    snapshot.iter().find(|(name, _)| name == model)
230                else {
231                    return Err((
232                        "blocked_model_missing",
233                        RuntimeError::UnknownModel(model.clone()),
234                    ));
235                };
236                if dimensions.as_slice() != [*captured_dimensions] {
237                    return Err((
238                        "blocked_dimensions",
239                        RuntimeError::InvalidInput("pending model dimensions conflict".into()),
240                    ));
241                }
242                let (storage_name, live_dimensions) = self
243                    .vector_model_metadata(model)
244                    .map_err(|error| ("blocked_model_missing", error))?;
245                if storage_name != *model || live_dimensions != *captured_dimensions {
246                    return Err((
247                        "blocked_dimensions",
248                        RuntimeError::InvalidInput("pending model dimensions changed".into()),
249                    ));
250                }
251                let outcome = self
252                    .embed_document_with_model_outcome_for_token(
253                        token,
254                        model,
255                        &super::entity_fts_document(entity).body,
256                    )
257                    .await
258                    .map_err(|error| ("embedding", error))?;
259                report.observe(&outcome);
260                if outcome.vector.len() != *captured_dimensions
261                    || crate::atomic_message::non_finite_index(&outcome.vector).is_some()
262                {
263                    return Err((
264                        "invalid_vector",
265                        RuntimeError::InvalidInput("invalid pending entity vector".into()),
266                    ));
267                }
268                // Provider resolution pins the serving registry entry. Recheck after
269                // it resolves so a concurrent setup replacement cannot change shape.
270                if self
271                    .vector_model_metadata(model)
272                    .map_err(|error| ("vector_prepare", error))?
273                    != (model.clone(), *captured_dimensions)
274                {
275                    return Err((
276                        "blocked_dimensions",
277                        RuntimeError::InvalidInput("pending model dimensions changed".into()),
278                    ));
279                }
280                self.vectors_for_model(token, model)
281                    .map_err(|error| ("vector_prepare", error))?;
282                let table = format!("vec_{}", crate::config::sanitize_key(model));
283                Ok(Self::entity_vector_insert_statements(
284                    &table,
285                    entity,
286                    model,
287                    &outcome.vector,
288                ))
289            }
290        }
291    }
292
293    pub(super) async fn publish_pending_entity_indexes(
294        &self,
295        token: &NamespaceToken,
296        entity: &Entity,
297        pending: &PendingEntityIndex,
298        snapshot: &[(String, usize)],
299    ) -> EntityUpdateReport {
300        let mut report = EntityUpdateReport::complete(EmbeddingTruncationReport::default(), true);
301        if entity.id != pending.entity_id
302            || entity.namespace != pending.namespace
303            || entity.version != pending.source_version
304            || entity.deleted_at.is_some()
305            || entity.merged_into.is_some()
306        {
307            for target in pending.targets.iter().filter(|target| !target.done) {
308                report.indexing.unfinished(&target.kind, "superseded");
309            }
310            return report;
311        }
312        let mut unsettled_attempt = false;
313        for target in &pending.targets {
314            if target.done {
315                continue;
316            }
317            if unsettled_attempt {
318                report
319                    .indexing
320                    .unfinished(&target.kind, "not_attempted_after_unknown");
321                continue;
322            }
323            if target.kind.is_blocked() {
324                report
325                    .indexing
326                    .unfinished(&target.kind, "blocked_dimensions");
327                continue;
328            }
329            if target.next_eligible_at > chrono::Utc::now().timestamp_micros() {
330                report.indexing.unfinished(&target.kind, "backoff");
331                continue;
332            }
333            let result = match self
334                .prepare_pending_entity_target(
335                    token,
336                    entity,
337                    &target.kind,
338                    snapshot,
339                    &mut report.embedding,
340                )
341                .await
342            {
343                Ok(statements) => {
344                    #[cfg(test)]
345                    match &target.kind {
346                        PendingIndexTargetKind::Fts => {
347                            super::race_seam::pause_before_entity_index_publish().await
348                        }
349                        PendingIndexTargetKind::Vector { .. } => {
350                            super::race_seam::pause_before_entity_vector_publish().await
351                        }
352                    }
353                    self.publish_pending_entity_target(pending, &target.kind, statements)
354                        .await
355                        .map_err(|error| ("index_publish", error))
356                }
357                Err(error) => Err(error),
358            };
359            match result {
360                Ok(true) => {}
361                Ok(false) => report.indexing.unfinished(&target.kind, "superseded"),
362                Err((_, error)) if unsettled(&error) => {
363                    // No reread, retry metadata write, or absence inference settles
364                    // a writer whose acknowledgement was lost.
365                    unsettled_attempt = true;
366                    report.indexing.unfinished(&target.kind, "outcome_unknown");
367                }
368                Err((stage, _)) => {
369                    match self
370                        .record_pending_entity_failure(pending, target, stage)
371                        .await
372                    {
373                        Ok(true) => report.indexing.unfinished(&target.kind, stage),
374                        Ok(false) => report.indexing.unfinished(&target.kind, "superseded"),
375                        Err(error) => {
376                            unsettled_attempt = unsettled(&error);
377                            report.indexing.unfinished(
378                                &target.kind,
379                                if unsettled_attempt {
380                                    "failure_record_outcome_unknown"
381                                } else {
382                                    "failure_record_failed"
383                                },
384                            );
385                        }
386                    }
387                }
388            }
389        }
390        report
391    }
392}
393
394#[cfg(test)]
395#[path = "entity_pending_index_tests.rs"]
396mod tests;