Skip to main content

khive_runtime/graph_lint/
fix.rs

1use super::*;
2use crate::atomic_runner::{
3    run_prepared_atomic_unit, AtomicOpPlan, PreparedAtomicError, PreparedAtomicOp,
4    PreparedAtomicOutcome,
5};
6use crate::{KhiveRuntime, Namespace, NamespaceToken, RuntimeError, RuntimeResult, VerbRegistry};
7use khive_storage::{SqlStatement, StorageError};
8use serde_json::json;
9use uuid::Uuid;
10
11struct PreparedFix {
12    owner: KhiveRuntime,
13    token: NamespaceToken,
14    guards: Vec<SqlStatement>,
15    plan: AtomicOpPlan,
16    committed: CommittedFixAction,
17}
18enum ActionRefusal {
19    Conflict(String),
20    Failed(RuntimeError),
21}
22
23enum Candidate {
24    Ready(Box<PreparedFix>),
25    Unsupported(String),
26    Conflict(String),
27}
28impl LintCapture {
29    fn unique_owner(&self, ids: &[Uuid]) -> Option<usize> {
30        let owner = *self.record_owners.get(ids.first()?)?.first()?;
31        ids.iter()
32            .all(|id| {
33                self.record_owners
34                    .get(id)
35                    .is_some_and(|owners| owners.as_slice() == [owner])
36            })
37            .then_some(owner)
38    }
39    fn tombstone_guard(&self, id: Uuid) -> Option<SqlStatement> {
40        if let Some(entity) = self
41            .all_entities
42            .get(&id)
43            .filter(|entity| entity.deleted_at.is_some())
44        {
45            return Some(khive_db::graph_lint::entity_witness(entity));
46        }
47        if let Some(note) = self
48            .all_notes
49            .get(&id)
50            .filter(|note| note.deleted_at.is_some())
51        {
52            return Some(khive_db::graph_lint::note_witness(note));
53        }
54        self.all_edges
55            .get(&id)
56            .filter(|edge| edge.deleted_at.is_some())
57            .and_then(|_| self.edge_guards.get(&id).cloned())
58    }
59    async fn prepare_fix(
60        &self,
61        registry: &VerbRegistry,
62        token: &NamespaceToken,
63        identity: &ActionIdentity,
64        violation: &LintViolation,
65    ) -> RuntimeResult<Candidate> {
66        let id = violation.subject.id();
67        let captured_subject = match &violation.subject {
68            LintSubject::Entity {
69                namespace,
70                entity_id,
71                entity_name,
72                entity_kind,
73            } => self.entities.iter().any(|entity| {
74                entity.id == *entity_id
75                    && entity.namespace == *namespace
76                    && entity.name == *entity_name
77                    && entity.kind == *entity_kind
78            }),
79            LintSubject::Edge { namespace, edge_id } => self.edges.iter().any(|inspected| {
80                Uuid::from(inspected.edge.id) == *edge_id && inspected.edge.namespace == *namespace
81            }),
82            LintSubject::Note { .. } => false,
83        };
84        if !captured_subject {
85            return Err(RuntimeError::InvalidInput(
86                "lint action subject was not in the visible capture".into(),
87            ));
88        }
89
90        let unsupported = || {
91            Candidate::Unsupported(
92                "the observed action has no unique same-database guarded owner".into(),
93            )
94        };
95        let ns = Namespace::parse(violation.subject.namespace())
96            .map_err(|error| RuntimeError::InvalidInput(error.to_string()))?;
97        if !token.visible_namespaces().contains(&ns) {
98            return Err(RuntimeError::InvalidInput(
99                "lint action is outside its captured visible scope".into(),
100            ));
101        }
102        let write_token = token.with_namespace(ns).with_request_id(token.request_id());
103        let (owner, guards, verb, args) = match identity.action {
104            FixAction::SoftDeleteEdge => {
105                let Some(edge) = self
106                    .all_edges
107                    .get(&id)
108                    .filter(|edge| edge.deleted_at.is_none())
109                else {
110                    return Ok(Candidate::Conflict("captured edge is not live".into()));
111                };
112                let Some((owner, endpoint_guard)) = [edge.source_id, edge.target_id]
113                    .into_iter()
114                    .find_map(|endpoint| {
115                        let owner = self.unique_owner(&[id, endpoint])?;
116                        self.tombstone_guard(endpoint).map(|guard| (owner, guard))
117                    })
118                else {
119                    return Ok(unsupported());
120                };
121                (
122                    owner,
123                    vec![self.edge_guards[&id].clone(), endpoint_guard],
124                    "delete",
125                    json!({"id":id, "hard":false}),
126                )
127            }
128            FixAction::ProposeDuplicateMerge => {
129                let members = violation.member_ids.as_deref().ok_or_else(|| {
130                    RuntimeError::Internal("duplicate lint violation lacks members".into())
131                })?;
132                if members.len() < 2 {
133                    return Err(RuntimeError::Internal(
134                        "duplicate lint group needs two distinct members".into(),
135                    ));
136                }
137                let mut distinct = members.to_vec();
138                distinct.sort();
139                distinct.dedup();
140                let first = self.all_entities.get(&id).ok_or_else(|| {
141                    RuntimeError::Internal("duplicate representative was not captured".into())
142                })?;
143                if distinct.len() != members.len()
144                    || distinct.first() != Some(&id)
145                    || members.iter().any(|member| {
146                        self.all_entities.get(member).is_none_or(|entity| {
147                            entity.namespace != first.namespace
148                                || entity.kind != first.kind
149                                || entity.name != first.name
150                        })
151                    })
152                {
153                    return Err(RuntimeError::InvalidInput(
154                        "lint duplicate group does not match the captured identity".into(),
155                    ));
156                }
157                let Some(owner) = self.unique_owner(members) else {
158                    return Ok(unsupported());
159                };
160                let mut guards = Vec::new();
161                for member in members {
162                    let entity = self.all_entities.get(member).ok_or_else(|| {
163                        RuntimeError::Internal("lint duplicate member was not captured".into())
164                    })?;
165                    if entity.deleted_at.is_some() {
166                        return Ok(Candidate::Conflict(
167                            "captured duplicate member is not live".into(),
168                        ));
169                    }
170                    guards.push(khive_db::graph_lint::entity_witness(entity));
171                }
172                let content = format!("Possible duplicate entities in namespace {}: {}. Review these records before deciding whether to merge them; no winner has been selected.", violation.subject.namespace(), members.iter().map(Uuid::to_string).collect::<Vec<_>>().join(", "));
173                (
174                    owner,
175                    guards,
176                    "create",
177                    json!({"kind":"question", "content":content, "properties":{"lint_rule":"duplicate-name", "member_ids":members}}),
178                )
179            }
180            FixAction::MarkDeprecated => {
181                let Some(entity) = self.all_entities.get(&id).filter(|entity| {
182                    entity.deleted_at.is_none()
183                        && entity
184                            .properties
185                            .as_ref()
186                            .and_then(|properties| properties.get("status"))
187                            .and_then(serde_json::Value::as_str)
188                            != Some("deprecated")
189                }) else {
190                    return Ok(Candidate::Conflict(
191                        "captured entity is not an unmarked live target".into(),
192                    ));
193                };
194                let witness = self.edges.iter().find_map(|inspected| {
195                    let edge = &inspected.edge;
196                    if edge.target_id != id
197                        || edge.relation != khive_storage::EdgeRelation::Supersedes
198                        || !inspected.source_live
199                        || inspected.contract_valid != Some(true)
200                    {
201                        return None;
202                    }
203                    let source = self.all_entities.get(&edge.source_id)?;
204                    let owner = self.unique_owner(&[id, Uuid::from(edge.id), source.id])?;
205                    Some((owner, edge, source))
206                });
207                let Some((owner, edge, source)) = witness else {
208                    return Ok(unsupported());
209                };
210                (
211                    owner,
212                    vec![
213                        khive_db::graph_lint::entity_witness(entity),
214                        self.edge_guards[&Uuid::from(edge.id)].clone(),
215                        khive_db::graph_lint::entity_witness(source),
216                    ],
217                    "update",
218                    json!({"id":id,"properties":{"status":"deprecated"}}),
219                )
220            }
221        };
222        let runtime = &self.owners[owner];
223        {
224            let mut reader = runtime.sql().reader().await?;
225            for guard in &guards {
226                if reader.query_all(guard.clone()).await?.len() != 1 {
227                    return Ok(Candidate::Conflict(
228                        "an observed lint predicate changed before preparation".into(),
229                    ));
230                }
231            }
232        }
233        // Consult the normal verb gate with the effective target and original
234        // principal. Its ordinary audit obligations remain part of preparation.
235        registry
236            .authorize_effective_kg_read(&write_token, verb, args.clone(), id)
237            .await?;
238        let mut plan = match identity.action {
239            FixAction::SoftDeleteEdge => {
240                crate::atomic_prepare::prepare_delete(
241                    runtime,
242                    &write_token,
243                    &args,
244                    Some(crate::atomic_prepare::AtomicDeleteKind::Edge),
245                )
246                .await?
247            }
248            FixAction::ProposeDuplicateMerge => {
249                crate::atomic_prepare::prepare_add_note(runtime, &write_token, &args).await?
250            }
251            FixAction::MarkDeprecated => {
252                crate::atomic_prepare::prepare_update_entity_plan_with_version(
253                    runtime,
254                    &write_token,
255                    id,
256                    crate::curation::EntityPatch {
257                        properties: Some(json!({"status":"deprecated"})),
258                        ..Default::default()
259                    },
260                    // The patch sets a property and never a name, so no
261                    // rename alias can follow; the choice matches `update`.
262                    &crate::EntityAliasChange::default().keeping_old_name(true),
263                    Some(self.all_entities[&id].version),
264                )
265                .await?
266            }
267        };
268        if let AtomicOpPlan::AddNote(note) = &mut plan {
269            note.statements.extend(crate::atomic_prepare::event_append_statements(
270                &write_token, write_token.namespace().as_str(), "create",
271                khive_types::EventKind::NoteCreated, khive_types::SubstrateKind::Note,
272                note.note_id, json!({"id":note.note_id, "namespace":write_token.namespace().as_str(), "kind":"question", "salience":null}),
273            )?);
274        }
275        let committed = match &plan {
276            AtomicOpPlan::AddNote(plan) => CommittedFixAction::ProposeDuplicateMerge {
277                violation_index: identity.violation_index,
278                question_note_id: plan.note_id,
279            },
280            AtomicOpPlan::Delete(_) => CommittedFixAction::SoftDeleteEdge {
281                violation_index: identity.violation_index,
282            },
283            AtomicOpPlan::Update(_) => CommittedFixAction::MarkDeprecated {
284                violation_index: identity.violation_index,
285            },
286            _ => return Err(RuntimeError::Internal("unexpected graph lint plan".into())),
287        };
288        Ok(Candidate::Ready(Box::new(PreparedFix {
289            owner: runtime.clone(),
290            token: write_token,
291            guards,
292            plan,
293            committed,
294        })))
295    }
296
297    /// Prepare every candidate before the first domain write, then commit each
298    /// independent guarded action once. No failure is retried or replayed.
299    pub async fn apply_fixes(
300        &self,
301        registry: &VerbRegistry,
302        token: &NamespaceToken,
303        mut report: LintReport,
304    ) -> RuntimeResult<(LintReport, Vec<FixReceipt>)> {
305        if token.actor() != self.token.actor()
306            || token.namespace() != self.token.namespace()
307            || token.visible_namespaces() != self.token.visible_namespaces()
308            || token.request_id() != self.token.request_id()
309            || token.process_ref() != self.token.process_ref()
310        {
311            return Err(RuntimeError::InvalidInput(
312                "lint capture belongs to a different request scope".into(),
313            ));
314        }
315        let mut prepared = Vec::new();
316        for (index, violation) in report.violations.iter().enumerate() {
317            let action = match violation.rule {
318                LintRuleId::DanglingEdge => FixAction::SoftDeleteEdge,
319                LintRuleId::DuplicateName => FixAction::ProposeDuplicateMerge,
320                LintRuleId::SupersededNotMarked => FixAction::MarkDeprecated,
321                _ => continue,
322            };
323            let identity = ActionIdentity {
324                violation_index: index as u64,
325                action,
326            };
327            let candidate = self
328                .prepare_fix(registry, token, &identity, violation)
329                .await;
330            prepared.push((identity, candidate));
331        }
332        report.summary.fixed = Some(0);
333        let mut receipts = Vec::new();
334        for (identity, candidate) in prepared {
335            let candidate = candidate.map_err(|source| {
336                failure(
337                    source,
338                    LintFixOutcome::Failed,
339                    identity.clone(),
340                    &receipts,
341                    &report,
342                )
343            })?;
344            match candidate {
345                Candidate::Unsupported(reason) => {
346                    receipts.push(FixReceipt::Unsupported { identity, reason })
347                }
348                Candidate::Conflict(reason) => {
349                    receipts.push(FixReceipt::Conflict { identity, reason })
350                }
351                Candidate::Ready(prepared) => {
352                    let PreparedFix {
353                        owner,
354                        token,
355                        guards,
356                        plan,
357                        committed,
358                    } = *prepared;
359                    let operation: PreparedAtomicOp<(), ActionRefusal> = Box::new(move |writer| {
360                        Box::pin(async move {
361                            for guard in guards {
362                                if writer.query_all(guard).await?.len() != 1 {
363                                    return Err(PreparedAtomicError::Refused {
364                                        failure: ActionRefusal::Conflict(
365                                            "an observed lint predicate changed".into(),
366                                        ),
367                                        message: "graph lint witness conflict".into(),
368                                    });
369                                }
370                            }
371                            let applied = crate::atomic_runner::apply_plan_preserving_storage(
372                                writer, &plan, true,
373                            )
374                            .await
375                            .map_err(|failure| match failure {
376                                crate::atomic_runner::PlanExecutionFailure::Storage {
377                                    source,
378                                    ..
379                                } => PreparedAtomicError::Storage(source),
380                                crate::atomic_runner::PlanExecutionFailure::Operation(failure) => {
381                                    let failure = match failure {
382                                        crate::atomic_runner::AtomicOpFailure::SqlError {
383                                            message,
384                                            ..
385                                        } => ActionRefusal::Failed(RuntimeError::Internal(message)),
386                                        _ => ActionRefusal::Conflict(
387                                            "an ordinary prepared mutation guard changed".into(),
388                                        ),
389                                    };
390                                    PreparedAtomicError::Refused {
391                                        failure,
392                                        message: "graph lint plan refused".into(),
393                                    }
394                                }
395                            })?;
396                            Ok(((), applied.effect.into_iter().collect()))
397                        })
398                    });
399                    match run_prepared_atomic_unit(action_access(&owner).as_ref(), operation).await
400                    {
401                        Ok(PreparedAtomicOutcome::RolledBack(ActionRefusal::Conflict(reason))) => {
402                            receipts.push(FixReceipt::Conflict { identity, reason })
403                        }
404                        Ok(PreparedAtomicOutcome::RolledBack(ActionRefusal::Failed(source))) => {
405                            return Err(failure(
406                                source,
407                                LintFixOutcome::Failed,
408                                identity,
409                                &receipts,
410                                &report,
411                            ))
412                        }
413                        Ok(PreparedAtomicOutcome::Committed { post_commit, .. }) => {
414                            receipts.push(FixReceipt::Committed { action: committed });
415                            report.summary.fixed = Some(
416                                receipts
417                                    .iter()
418                                    .filter(|receipt| receipt.is_committed())
419                                    .count() as u64,
420                            );
421                            // Each prepared lint action has at most one ordinary
422                            // effect. Preserve its typed cause rather than the
423                            // multi-effect compatibility API's string aggregate.
424                            for effect in post_commit.into_effects() {
425                                if let Err(source) =
426                                    crate::atomic_prepare::apply_one_post_commit_effect(
427                                        &owner, &token, effect,
428                                    )
429                                    .await
430                                {
431                                    return Err(failure(
432                                        source,
433                                        LintFixOutcome::Failed,
434                                        identity,
435                                        &receipts,
436                                        &report,
437                                    ));
438                                }
439                            }
440                        }
441                        Err(source) => {
442                            let outcome = if unknown(&source) {
443                                LintFixOutcome::Unknown
444                            } else {
445                                LintFixOutcome::Failed
446                            };
447                            return Err(failure(
448                                source.into(),
449                                outcome,
450                                identity,
451                                &receipts,
452                                &report,
453                            ));
454                        }
455                    }
456                }
457            }
458        }
459        Ok((report, receipts))
460    }
461}
462fn unknown(error: &StorageError) -> bool {
463    if error
464        .sqlite_write_failure()
465        .is_some_and(|failure| failure.settlement_unknown)
466    {
467        return true;
468    }
469    error.writer_request_state() == Some(khive_storage::WriterTaskRequestState::SideEffectsUnknown)
470}
471fn failure(
472    source: RuntimeError,
473    outcome: LintFixOutcome,
474    failed_action: ActionIdentity,
475    receipts: &[FixReceipt],
476    report: &LintReport,
477) -> RuntimeError {
478    RuntimeError::LintFix {
479        source: Box::new(source),
480        detail: Box::new(LintFixFailureDetail {
481            outcome,
482            failed_action,
483            confirmed_receipts: receipts.to_vec(),
484            report: report.clone(),
485        }),
486    }
487}
488
489fn action_access(owner: &KhiveRuntime) -> std::sync::Arc<dyn khive_storage::SqlAccess> {
490    #[cfg(test)]
491    if let Ok(access) = TEST_ACTION_ACCESS.try_with(std::sync::Arc::clone) {
492        return access;
493    }
494    owner.sql()
495}
496#[cfg(test)]
497tokio::task_local! {
498    pub(super) static TEST_ACTION_ACCESS: std::sync::Arc<dyn khive_storage::SqlAccess>;
499}
500
501#[cfg(test)]
502mod outcome_tests {
503    use super::*;
504
505    #[test]
506    fn commit_reply_loss_is_unknown_but_known_outer_finality_wins() {
507        let lost = || StorageError::WriteOutcomeUnknown {
508            source: Box::new(std::io::Error::other("lost COMMIT reply")),
509        };
510        assert!(
511            unknown(&lost()),
512            "graph fix must not claim failed after COMMIT reply loss"
513        );
514        assert!(unknown(&lost().with_sqlite_write_failure(
515            khive_storage::error::SqliteWriteFailure {
516                stage: khive_storage::error::SqliteWriteStage::Commit,
517                primary_code: 10,
518                extended_code: 1034,
519                settlement_unknown: false,
520            }
521        )));
522        for state in [
523            khive_storage::WriterTaskRequestState::NotStarted,
524            khive_storage::WriterTaskRequestState::TransactionRolledBack,
525        ] {
526            assert!(
527                !unknown(&StorageError::WriterTaskRequestFailed {
528                    request_state: state,
529                    source: Box::new(lost()),
530                }),
531                "inner uncertainty must not override known outer finality"
532            );
533        }
534        assert!(!unknown(&StorageError::WriterRouteViolation {
535            operation: "lint fix".into()
536        }));
537    }
538}