Skip to main content

inference_engine/reasoning/
conflict.rs

1use super::{
2    Limit, LiteralRole, ReasoningError, ReasoningStore, TripleCursor, TripleSource,
3    plan::ConflictClause,
4};
5use rdf_reasoning::Rdf12DatatypeConflictId;
6use serde::{Deserialize, Serialize};
7use std::{error::Error, fmt, future::Future, num::NonZeroU64};
8
9/// Non-RDF evidence that one exact member belongs to two disjoint default types.
10#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
11#[serde(deny_unknown_fields)]
12pub struct DatatypeConflict<T> {
13    /// Shared diagnostic identity; this is not a W3C entailment-rule name.
14    pub id: Rdf12DatatypeConflictId,
15    /// Exact caller-owned member key; no lexical/value identity is guessed.
16    pub member: T,
17    /// Both positive type premises in shared definition order.
18    pub premises: [[T; 3]; 2],
19}
20
21/// Caller-owned asynchronous diagnostics storage, separate from RDF scratch.
22pub trait DatatypeConflictSink: Send {
23    /// Exact source term identity.
24    type Term: Clone + Eq + Send + Sync;
25    /// Backend failure; errors abort the attempt rather than lose diagnostics.
26    type Error: Error + Send + Sync + 'static;
27    /// Retain one witness with this attempt's immutable source scope and snapshot.
28    /// Stream/spill records and discard partial output if the check fails.
29    fn record(
30        &mut self,
31        conflict: DatatypeConflict<Self::Term>,
32    ) -> impl Future<Output = Result<(), Self::Error>> + Send;
33}
34
35/// Strict caps on examined rows and emitted diagnostic records.
36#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
37#[serde(deny_unknown_fields)]
38pub struct DatatypeConflictLimits {
39    diagnostics: NonZeroU64,
40    matches: NonZeroU64,
41}
42impl DatatypeConflictLimits {
43    /// Set diagnostic output and total cursor-row limits independently.
44    pub const fn new(diagnostics: NonZeroU64, matches: NonZeroU64) -> Self {
45        Self {
46            diagnostics,
47            matches,
48        }
49    }
50}
51
52/// Completed counters for the three selected checks; not a consistency verdict.
53#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
54#[serde(deny_unknown_fields)]
55pub struct DatatypeConflictReport {
56    /// Examined rows, including repeated indexed probes across pairs.
57    pub matches: u64,
58    /// Recorded supported conflicts. Zero does not certify RDF/RDFS consistency.
59    pub diagnostics: u64,
60}
61
62/// Failure to finish the entire selected source diagnostic phase.
63#[derive(Debug)]
64pub enum DatatypeConflictError<E> {
65    /// Target augmentation must never participate in source consistency checks.
66    WrongRole,
67    /// Bounded diagnostic storage was exhausted; partial records are unpublished.
68    DiagnosticsLimitExceeded,
69    /// Compilation, backend, cancellation or cursor-work failure.
70    Execution(ReasoningError<E>),
71}
72impl<E> From<ReasoningError<E>> for DatatypeConflictError<E> {
73    fn from(error: ReasoningError<E>) -> Self {
74        Self::Execution(error)
75    }
76}
77impl<E: fmt::Display> fmt::Display for DatatypeConflictError<E> {
78    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79        match self {
80            Self::WrongRole => {
81                f.write_str("datatype conflict checking requires source-only context")
82            }
83            Self::DiagnosticsLimitExceeded => {
84                f.write_str("datatype conflict diagnostic limit exceeded")
85            }
86            Self::Execution(error) => error.fmt(f),
87        }
88    }
89}
90impl<E: Error + 'static> Error for DatatypeConflictError<E> {
91    fn source(&self) -> Option<&(dyn Error + 'static)> {
92        match self {
93            Self::Execution(error) => Some(error),
94            _ => None,
95        }
96    }
97}
98
99/// Execute shared default-map conflict clauses against one source-only closure.
100///
101/// The controller must first validate source literals and close source facts,
102/// including nonempty datatype witnesses, and must not add target context yet.
103/// The role guard rejects explicit target input; it cannot audit a caller's
104/// snapshot selection or certify completion of the preceding semantic phases.
105/// This operation does not assert negative membership or write RDF facts.
106pub struct Rdf12DatatypeConflictChecker {
107    limits: DatatypeConflictLimits,
108}
109impl Rdf12DatatypeConflictChecker {
110    /// Configure strict work and diagnostic limits.
111    pub const fn new(limits: DatatypeConflictLimits) -> Self {
112        Self { limits }
113    }
114
115    /// Stream all detected witnesses from one immutable selected source snapshot.
116    ///
117    /// At most two cursors and one fixed shared clause are retained. The sink
118    /// owns scope/snapshot provenance and durable/spilled storage. An empty
119    /// successful report only excludes these three witnessed default-map clashes
120    /// in the supplied closure; it does not prove overall consistency.
121    ///
122    /// # Errors
123    /// Wrong role, storage, cancellation and exhausted budgets abort the attempt.
124    /// A late cursor failure must invalidate any already staged diagnostics.
125    pub async fn run<S, D>(
126        &self,
127        store: &mut S,
128        role: LiteralRole,
129        sink: &mut D,
130    ) -> Result<DatatypeConflictReport, DatatypeConflictError<S::Error>>
131    where
132        S: ReasoningStore,
133        D: DatatypeConflictSink<Term = S::Term, Error = S::Error>,
134    {
135        if role != LiteralRole::Source {
136            return Err(DatatypeConflictError::WrongRole);
137        }
138        Self::cancel(store)?;
139        let source = store.snapshot().await.map_err(ReasoningError::Storage)?;
140        let mut report = DatatypeConflictReport::default();
141        for id in Rdf12DatatypeConflictId::ALL {
142            let clause = ConflictClause::compile(*id, store).await?;
143            let empty = std::array::from_fn(|_| None);
144            let mut first = source
145                .scan(clause.body[0].probe(&empty))
146                .await
147                .map_err(ReasoningError::Storage)?;
148            while let Some(a) = self.next(&mut first, store, &mut report).await? {
149                let Some(bindings) = clause.body[0].bind(&a, empty.clone()) else {
150                    continue;
151                };
152                let mut second = source
153                    .scan(clause.body[1].probe(&bindings))
154                    .await
155                    .map_err(ReasoningError::Storage)?;
156                while let Some(b) = self.next(&mut second, store, &mut report).await? {
157                    let Some(bindings) = clause.body[1].bind(&b, bindings.clone()) else {
158                        continue;
159                    };
160                    let [Some(member)] = clause.head.probe(&bindings) else {
161                        return Err(ReasoningError::UnsupportedDatatypeConflict(clause.id).into());
162                    };
163                    Self::cancel(store)?;
164                    if report.diagnostics == self.limits.diagnostics.get() {
165                        return Err(DatatypeConflictError::DiagnosticsLimitExceeded);
166                    }
167                    sink.record(DatatypeConflict {
168                        id: clause.id,
169                        member,
170                        premises: [a.clone(), b],
171                    })
172                    .await
173                    .map_err(ReasoningError::Storage)?;
174                    report.diagnostics += 1;
175                }
176            }
177        }
178        Self::cancel(store)?;
179        Ok(report)
180    }
181    async fn next<S: ReasoningStore, C: TripleCursor<Term = S::Term, Error = S::Error>>(
182        &self,
183        cursor: &mut C,
184        store: &mut S,
185        report: &mut DatatypeConflictReport,
186    ) -> Result<Option<[S::Term; 3]>, ReasoningError<S::Error>> {
187        Self::cancel(store)?;
188        let row = cursor.next().await.map_err(ReasoningError::Storage)?;
189        if row.is_some() {
190            if report.matches == self.limits.matches.get() {
191                return Err(ReasoningError::LimitExceeded(Limit::Matches));
192            }
193            report.matches += 1;
194            crate::cooperative::checkpoint(report.matches).await;
195            Self::cancel(store)?;
196        }
197        Ok(row)
198    }
199    fn cancel<S: ReasoningStore>(store: &S) -> Result<(), ReasoningError<S::Error>> {
200        if store.is_cancelled() {
201            Err(ReasoningError::Cancelled)
202        } else {
203            Ok(())
204        }
205    }
206}