Skip to main content

inference_engine/reasoning/
types.rs

1use super::{LiteralOccurrence, TermOccurrence};
2use rdf_reasoning::{
3    Exclusion, Preset, Rdf12AxiomId, Rdf12DatatypeConflictId, Rdf12ExistentialAxiomId,
4    Rdf12LiteralRuleId, Rdf12OccurrenceRuleId, Rdf12PropositionRuleId, RuleId,
5};
6use serde::{Deserialize, Serialize};
7use std::{
8    error::Error,
9    fmt,
10    num::{NonZeroU32, NonZeroU64},
11    str::FromStr,
12};
13
14/// Precisely supported executable profile; distinct from compile-only presets.
15#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
16pub enum ExecutionProfile {
17    /// Only subclass transitivity and inherited membership, no axioms or other rules.
18    #[serde(rename = "rdfs-subclass")]
19    RdfsSubclass,
20    /// Fourteen shared RDF/RDFS rules, without axioms or datatype processing.
21    #[serde(rename = "rdfs-core")]
22    RdfsCore,
23}
24
25impl ExecutionProfile {
26    /// Stable profile name; this is not full RDFS support.
27    pub const fn name(self) -> &'static str {
28        self.preset().name()
29    }
30    /// Profile definition revision, independent of package implementation version.
31    pub const fn revision(self) -> u32 {
32        1
33    }
34    /// Shared semantic selection, independent of this executor's implementation.
35    pub const fn preset(self) -> Preset {
36        match self {
37            Self::RdfsSubclass => Preset::RdfsSubclass,
38            Self::RdfsCore => Preset::RdfsCore,
39        }
40    }
41    /// Exact rule identities from the shared catalogue, in execution order.
42    pub const fn rules(self) -> &'static [RuleId] {
43        self.preset().rules()
44    }
45    /// Obligations deliberately excluded by the shared semantic selection.
46    pub const fn exclusions(self) -> &'static [Exclusion] {
47        self.preset().exclusions()
48    }
49}
50
51impl FromStr for ExecutionProfile {
52    type Err = ProfileError;
53    fn from_str(value: &str) -> Result<Self, Self::Err> {
54        match value {
55            "rdfs-subclass" => Ok(Self::RdfsSubclass),
56            "rdfs-core" => Ok(Self::RdfsCore),
57            _ => Err(ProfileError(value.to_owned())),
58        }
59    }
60}
61
62/// Requested profile is not executable; no weaker profile was substituted.
63#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
64pub struct ProfileError(String);
65impl fmt::Display for ProfileError {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        write!(f, "unsupported executable profile: {}", self.0)
68    }
69}
70impl Error for ProfileError {}
71
72/// Explicit finite work/output limits; reaching a limit fails the attempt.
73#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
74#[serde(deny_unknown_fields)]
75pub struct RunLimits {
76    pub(super) rounds: NonZeroU32,
77    pub(super) inferred: NonZeroU64,
78    pub(super) matches: NonZeroU64,
79}
80impl RunLimits {
81    /// Set maximum rounds (including the final empty round), novel tuples and
82    /// examined cursor rows. The caller separately budgets scratch disk/I/O.
83    pub const fn new(rounds: NonZeroU32, inferred: NonZeroU64, matches: NonZeroU64) -> Self {
84        Self {
85            rounds,
86            inferred,
87            matches,
88        }
89    }
90}
91
92/// Exact bounded witness arity, without invented or repeated premise tuples.
93#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
94pub enum Premises<T> {
95    /// A unary rule used one matching body tuple.
96    One([T; 3]),
97    /// A join rule used two matching body tuples in shared definition order.
98    Two([[T; 3]; 2]),
99}
100impl<T> Premises<T> {
101    /// Iterate matching body tuples in rule order, preserving exact arity.
102    pub fn iter(&self) -> std::slice::Iter<'_, [T; 3]> {
103        match self {
104            Self::One(tuple) => std::slice::from_ref(tuple).iter(),
105            Self::Two(tuples) => tuples.iter(),
106        }
107    }
108}
109impl<T> From<[[T; 3]; 2]> for Premises<T> {
110    fn from(tuples: [[T; 3]; 2]) -> Self {
111        Self::Two(tuples)
112    }
113}
114
115/// Standard axiom authority; the inference tuple supplies the exact ground identity.
116#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
117pub enum AxiomFamily {
118    /// A finite family from RDF 1.2 Semantics CRD 2026-09-24.
119    Rdf12(Rdf12AxiomId),
120    /// A checked canonical container IRI's RDF/RDFS vocabulary axioms.
121    Rdf12Container,
122    /// Nonempty-class requirement, realized by a fresh scoped blank witness.
123    Rdf12Existential(Rdf12ExistentialAxiomId),
124}
125
126/// Exact derivation authority, distinguishing premises from ground axioms.
127#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
128#[serde(deny_unknown_fields)]
129pub enum Evidence<T> {
130    /// A shared rule fired on these exact body tuples.
131    Rule {
132        /// Catalogue rule identity.
133        rule: RuleId,
134        /// Body tuples in shared definition order.
135        premises: Premises<T>,
136    },
137    /// A ground standard axiom has no rule premises.
138    Axiom(AxiomFamily),
139    /// A shared literal-typing clause consumed validated semantic metadata.
140    Literal {
141        /// Exact parameterized shared clause identity.
142        rule: Rdf12LiteralRuleId,
143        /// Original selected root and literal key, including source/target role.
144        occurrence: LiteralOccurrence<T>,
145        /// Exact validated lexical byte count; not a lexical value replacement.
146        lexical_bytes: u64,
147    },
148    /// A shared rule consumed a trusted structural occurrence, not an RDF assertion.
149    Occurrence {
150        /// Exact shared occurrence clause identity.
151        rule: Rdf12OccurrenceRuleId,
152        /// Original root, actual parent, path and source/target role.
153        occurrence: TermOccurrence<T>,
154    },
155    /// A finite shared proposition constructor used three exact RDF premises.
156    Proposition {
157        /// Exact shared constructor identity.
158        rule: Rdf12PropositionRuleId,
159        /// Property, subject-resource and object-resource evidence in definition order.
160        premises: [[T; 3]; 3],
161    },
162}
163
164/// One novel tuple and its exact derivation authority.
165#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
166#[serde(deny_unknown_fields)]
167pub struct Inference<T> {
168    /// Derived subject, predicate and object, preserving caller term identity.
169    pub triple: [T; 3],
170    /// Rule and premise witness, or explicit standard axiom family.
171    pub evidence: Evidence<T>,
172}
173
174/// Completed work counters; returned only after successful fixpoint detection.
175#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
176pub struct RunReport {
177    /// Completed rounds, including the final round with no additions.
178    pub rounds: u32,
179    /// Examined cursor rows, including repeated probes across rounds.
180    pub matches: u64,
181    /// Novel inferred tuples, excluding asserted and inferred duplicates.
182    pub inferred: u64,
183}
184
185/// Resource budget that prevented complete inference.
186#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
187pub enum Limit {
188    /// Round count reached before proving a fixpoint.
189    Rounds,
190    /// Maximum number of novel inferred tuples.
191    Inferred,
192    /// Maximum examined cursor rows.
193    Matches,
194}
195
196/// Failure of the entire attempt; any staged output must remain unpublished.
197#[derive(Debug)]
198pub enum ReasoningError<E> {
199    /// Fallible backend read, resolution or write failed.
200    Storage(E),
201    /// Backend returned a tuple outside an exact requested premise probe.
202    InvalidProbe,
203    /// Caller cancelled or superseded the attempt.
204    Cancelled,
205    /// Explicit budget prevented complete closure.
206    LimitExceeded(Limit),
207    /// Shared rule does not have a supported flat one- or two-body form.
208    UnsupportedRule(RuleId),
209    /// A shared axiom is not an empty-body ground triple of IRI constants.
210    UnsupportedAxiom,
211    /// A shared literal clause does not have the admitted metadata-premise shape.
212    UnsupportedLiteralRule(Rdf12LiteralRuleId),
213    /// Shared proposition constructor has an unsupported body or head shape.
214    UnsupportedPropositionRule(Rdf12PropositionRuleId),
215    /// Shared datatype conflict has an unsupported diagnostic or premise shape.
216    UnsupportedDatatypeConflict(Rdf12DatatypeConflictId),
217    /// Shared occurrence clause has an unsupported virtual-premise or head shape.
218    UnsupportedOccurrenceRule(Rdf12OccurrenceRuleId),
219}
220impl<E: fmt::Display> fmt::Display for ReasoningError<E> {
221    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
222        match self {
223            Self::Storage(error) => write!(f, "reasoning storage failed: {error}"),
224            Self::InvalidProbe => {
225                f.write_str("reasoning snapshot returned a row outside an exact probe")
226            }
227            Self::Cancelled => f.write_str("reasoning cancelled"),
228            Self::LimitExceeded(limit) => write!(
229                f,
230                "reasoning {} limit exceeded",
231                match limit {
232                    Limit::Rounds => "rounds",
233                    Limit::Inferred => "inferred",
234                    Limit::Matches => "matches",
235                }
236            ),
237            Self::UnsupportedRule(rule) => {
238                write!(f, "unsupported shared rule definition: {rule:?}")
239            }
240            Self::UnsupportedAxiom => f.write_str("unsupported shared ground axiom definition"),
241            Self::UnsupportedLiteralRule(rule) => {
242                write!(f, "unsupported shared literal rule definition: {rule:?}")
243            }
244            Self::UnsupportedOccurrenceRule(id) => {
245                write!(f, "unsupported occurrence rule definition: {id:?}")
246            }
247            Self::UnsupportedDatatypeConflict(id) => {
248                write!(f, "unsupported datatype conflict definition: {id:?}")
249            }
250            Self::UnsupportedPropositionRule(rule) => {
251                write!(f, "unsupported proposition rule definition: {rule:?}")
252            }
253        }
254    }
255}
256impl<E: Error + 'static> Error for ReasoningError<E> {
257    fn source(&self) -> Option<&(dyn Error + 'static)> {
258        match self {
259            Self::Storage(error) => Some(error),
260            _ => None,
261        }
262    }
263}