inference_engine/reasoning/
conflict.rs1use 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#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
11#[serde(deny_unknown_fields)]
12pub struct DatatypeConflict<T> {
13 pub id: Rdf12DatatypeConflictId,
15 pub member: T,
17 pub premises: [[T; 3]; 2],
19}
20
21pub trait DatatypeConflictSink: Send {
23 type Term: Clone + Eq + Send + Sync;
25 type Error: Error + Send + Sync + 'static;
27 fn record(
30 &mut self,
31 conflict: DatatypeConflict<Self::Term>,
32 ) -> impl Future<Output = Result<(), Self::Error>> + Send;
33}
34
35#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
37#[serde(deny_unknown_fields)]
38pub struct DatatypeConflictLimits {
39 diagnostics: NonZeroU64,
40 matches: NonZeroU64,
41}
42impl DatatypeConflictLimits {
43 pub const fn new(diagnostics: NonZeroU64, matches: NonZeroU64) -> Self {
45 Self {
46 diagnostics,
47 matches,
48 }
49 }
50}
51
52#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
54#[serde(deny_unknown_fields)]
55pub struct DatatypeConflictReport {
56 pub matches: u64,
58 pub diagnostics: u64,
60}
61
62#[derive(Debug)]
64pub enum DatatypeConflictError<E> {
65 WrongRole,
67 DiagnosticsLimitExceeded,
69 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
99pub struct Rdf12DatatypeConflictChecker {
107 limits: DatatypeConflictLimits,
108}
109impl Rdf12DatatypeConflictChecker {
110 pub const fn new(limits: DatatypeConflictLimits) -> Self {
112 Self { limits }
113 }
114
115 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}