Skip to main content

inference_engine/reasoning/
types.rs

1use rdf_reasoning::RuleId;
2use serde::{Deserialize, Serialize};
3use std::{
4    error::Error,
5    fmt,
6    num::{NonZeroU32, NonZeroU64},
7    str::FromStr,
8};
9
10/// Precisely supported executable profile; distinct from compile-only presets.
11#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
12pub enum ExecutionProfile {
13    /// Only subclass transitivity and inherited membership, no axioms or other rules.
14    #[serde(rename = "rdfs-subclass")]
15    RdfsSubclass,
16}
17
18impl ExecutionProfile {
19    /// Stable profile name; this is not full RDFS support.
20    pub const fn name(self) -> &'static str {
21        "rdfs-subclass"
22    }
23    /// Profile definition revision, independent of package implementation version.
24    pub const fn revision(self) -> u32 {
25        1
26    }
27    /// Exact rule identities from `rdf-reasoning` 2.6.0, in execution order.
28    pub const fn rules(self) -> &'static [RuleId; 2] {
29        &[RuleId::Rdfs9, RuleId::Rdfs11]
30    }
31}
32
33impl FromStr for ExecutionProfile {
34    type Err = ProfileError;
35    fn from_str(value: &str) -> Result<Self, Self::Err> {
36        match value {
37            "rdfs-subclass" => Ok(Self::RdfsSubclass),
38            _ => Err(ProfileError(value.to_owned())),
39        }
40    }
41}
42
43/// Requested profile is not executable; no weaker profile was substituted.
44#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
45pub struct ProfileError(String);
46impl fmt::Display for ProfileError {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        write!(f, "unsupported executable profile: {}", self.0)
49    }
50}
51impl Error for ProfileError {}
52
53/// Explicit finite work/output limits; reaching a limit fails the attempt.
54#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
55#[serde(deny_unknown_fields)]
56pub struct RunLimits {
57    pub(super) rounds: NonZeroU32,
58    pub(super) inferred: NonZeroU64,
59    pub(super) matches: NonZeroU64,
60}
61impl RunLimits {
62    /// Set maximum rounds (including the final empty round), novel tuples and
63    /// examined cursor rows. The caller separately budgets scratch disk/I/O.
64    pub const fn new(rounds: NonZeroU32, inferred: NonZeroU64, matches: NonZeroU64) -> Self {
65        Self {
66            rounds,
67            inferred,
68            matches,
69        }
70    }
71}
72
73/// One novel tuple and a two-premise witness from the selected shared rule.
74#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
75#[serde(deny_unknown_fields)]
76pub struct Inference<T> {
77    /// Derived subject, predicate and object, preserving caller term identity.
78    pub triple: [T; 3],
79    /// Rule that produced this witness.
80    pub rule: RuleId,
81    /// Matching body tuples in shared rule order; either can itself be inferred.
82    pub premises: [[T; 3]; 2],
83}
84
85/// Completed work counters; returned only after successful fixpoint detection.
86#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
87pub struct RunReport {
88    /// Completed rounds, including the final round with no additions.
89    pub rounds: u32,
90    /// Examined cursor rows, including repeated probes across rounds.
91    pub matches: u64,
92    /// Novel inferred tuples, excluding asserted and inferred duplicates.
93    pub inferred: u64,
94}
95
96/// Resource budget that prevented complete inference.
97#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
98pub enum Limit {
99    /// Round count reached before proving a fixpoint.
100    Rounds,
101    /// Maximum number of novel inferred tuples.
102    Inferred,
103    /// Maximum examined cursor rows.
104    Matches,
105}
106
107/// Failure of the entire attempt; any staged output must remain unpublished.
108#[derive(Debug)]
109pub enum ReasoningError<E> {
110    /// Fallible backend read, resolution or write failed.
111    Storage(E),
112    /// Caller cancelled or superseded the attempt.
113    Cancelled,
114    /// Explicit budget prevented complete closure.
115    LimitExceeded(Limit),
116    /// Pinned shared rule no longer has the supported flat two-body form.
117    UnsupportedRule(RuleId),
118}
119impl<E: fmt::Display> fmt::Display for ReasoningError<E> {
120    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121        match self {
122            Self::Storage(error) => write!(f, "reasoning storage failed: {error}"),
123            Self::Cancelled => f.write_str("reasoning cancelled"),
124            Self::LimitExceeded(limit) => write!(
125                f,
126                "reasoning {} limit exceeded",
127                match limit {
128                    Limit::Rounds => "rounds",
129                    Limit::Inferred => "inferred",
130                    Limit::Matches => "matches",
131                }
132            ),
133            Self::UnsupportedRule(rule) => {
134                write!(f, "unsupported shared rule definition: {rule:?}")
135            }
136        }
137    }
138}
139impl<E: Error + 'static> Error for ReasoningError<E> {
140    fn source(&self) -> Option<&(dyn Error + 'static)> {
141        match self {
142            Self::Storage(error) => Some(error),
143            _ => None,
144        }
145    }
146}