Skip to main content

inference_engine/shacl12/
controller.rs

1use super::{
2    ExecutionError, Limit, Limits, Plan, Report, Rule, RuleBackend, Work, plan::number_cmp,
3};
4use std::cmp::Ordering;
5
6/// Native scheduling controller for the pinned SHACL 1.2 execution contract.
7pub struct Controller {
8    limits: Limits,
9}
10impl Controller {
11    /// Construct a controller with explicit finite attempt bounds.
12    pub const fn new(limits: Limits) -> Self {
13        Self { limits }
14    }
15
16    /// Execute each layer's run-once phase, then iterate to a fixed point.
17    /// Same-order rules share one immutable snapshot and merge only afterward.
18    ///
19    /// # Errors
20    /// Any backend failure, cancellation or exhausted limit invalidates the
21    /// entire attempt, including all earlier staged phases. Never publish on error.
22    pub async fn run<B: RuleBackend>(
23        &self,
24        plan: &Plan<B::Rule>,
25        backend: &mut B,
26    ) -> Result<Report, ExecutionError<B::Error>> {
27        let mut report = Report::default();
28        let mut work = Work::new(self.limits.work);
29        let mut start = 0;
30        self.check(backend, &work)?;
31        while start < plan.rules.len() {
32            let end = start
33                + plan.rules[start..].partition_point(|rule| {
34                    number_cmp(rule.schedule.layer(), plan.rules[start].schedule.layer())
35                        == Ordering::Equal
36                });
37            work.charge()
38                .map_err(|_| ExecutionError::Limit(Limit::Work))?;
39            backend
40                .begin_layer(&plan.rules[start..end], &mut work)
41                .await
42                .map_err(ExecutionError::Backend)?;
43            self.check(backend, &work)?;
44            let rules = &plan.rules[start..end];
45            let once = rules.partition_point(|rule| rule.schedule.run_once() == Some(true));
46            self.iteration(&rules[..once], backend, &mut work, &mut report)
47                .await?;
48            let iterating = &rules[once..];
49            if !iterating.is_empty() {
50                let mut iteration = 0;
51                loop {
52                    if iteration == self.limits.iterations {
53                        return Err(ExecutionError::Limit(Limit::Iterations));
54                    }
55                    iteration += 1;
56                    report.iterations += 1;
57                    if !self
58                        .iteration(iterating, backend, &mut work, &mut report)
59                        .await?
60                    {
61                        break;
62                    }
63                }
64            }
65            backend
66                .finish_layer(rules, &mut work)
67                .await
68                .map_err(ExecutionError::Backend)?;
69            self.check(backend, &work)?;
70            start = end;
71        }
72        backend
73            .finish(&mut work)
74            .await
75            .map_err(ExecutionError::Backend)?;
76        self.check(backend, &work)?;
77        report.work = work.used();
78        Ok(report)
79    }
80
81    async fn iteration<B: RuleBackend>(
82        &self,
83        rules: &[Rule<B::Rule>],
84        backend: &mut B,
85        work: &mut Work,
86        report: &mut Report,
87    ) -> Result<bool, ExecutionError<B::Error>> {
88        let mut start = 0;
89        let mut changed = false;
90        while start < rules.len() {
91            self.check(backend, work)?;
92            work.charge()
93                .map_err(|_| ExecutionError::Limit(Limit::Work))?;
94            let end = start
95                + rules[start..].partition_point(|rule| {
96                    number_cmp(rule.schedule.order(), rules[start].schedule.order())
97                        == Ordering::Equal
98                });
99            let snapshot = backend.snapshot().await.map_err(ExecutionError::Backend)?;
100            self.check(backend, work)?;
101            report.phases += 1;
102            for rule in &rules[start..end] {
103                work.charge()
104                    .map_err(|_| ExecutionError::Limit(Limit::Work))?;
105                backend
106                    .execute(&rule.id, &snapshot, report.phases, work)
107                    .await
108                    .map_err(ExecutionError::Backend)?;
109                self.check(backend, work)?;
110                report.executions += 1;
111                crate::cooperative::checkpoint(report.executions).await;
112                self.check(backend, work)?;
113            }
114            let added = backend
115                .merge_phase(work)
116                .await
117                .map_err(ExecutionError::Backend)?;
118            self.check(backend, work)?;
119            report.inferred = report
120                .inferred
121                .checked_add(added)
122                .filter(|total| *total <= self.limits.inferred.get())
123                .ok_or(ExecutionError::Limit(Limit::Inferred))?;
124            changed |= added != 0;
125            start = end;
126        }
127        Ok(changed)
128    }
129    fn check<B: RuleBackend>(
130        &self,
131        backend: &B,
132        work: &Work,
133    ) -> Result<(), ExecutionError<B::Error>> {
134        if backend.is_cancelled() {
135            return Err(ExecutionError::Cancelled);
136        }
137        if work.exceeded() {
138            return Err(ExecutionError::Limit(Limit::Work));
139        }
140        Ok(())
141    }
142}