Skip to main content

qualia_core_db/semantic_instruments/execution/
runner.rs

1//! SI-06 generic demo & core semantic instrument runner.
2//!
3//! Dispatch is by entry-point name (`assess` / `recognise` only). Demo seeds perform a
4//! labelled identity transform; the 6 Core Semantic Instruments run bounded evaluators.
5
6use super::receipt::ExecutionReceipt;
7use crate::semantic_instruments::errors::InstrumentError;
8pub use crate::semantic_instruments::evaluators::{
9    evaluate_core_semantic_instrument, execute_reference_instrument, CoreInstrumentKind,
10    EvaluationOutcome,
11};
12use crate::semantic_instruments::resolve::{InstalledRelease, LocalRegistry};
13
14/// Entry points only. Anything else is [`InstrumentError::UnknownEntryPoint`].
15const DEMO_ENTRY_POINTS: &[&str] = &["assess", "recognise"];
16
17pub struct RunRequest<'a> {
18    pub release_id: &'a str,
19    pub entry_point: &'a str,
20    pub input: &'a [u8],
21    pub now: u32,
22    pub cancelled: bool,
23    pub max_input_bytes: usize,
24    pub max_steps: u32,
25    pub parent_receipt: Option<String>,
26}
27
28pub enum RunOutcome {
29    Completed { receipt: ExecutionReceipt },
30    Held { receipt: ExecutionReceipt },
31    Refused { error: InstrumentError },
32}
33
34/// Activate a closed install. Open records fail [`InstrumentError::NotClosed`].
35pub fn preflight<'a>(
36    registry: &'a LocalRegistry,
37    req: &RunRequest<'_>,
38) -> Result<&'a InstalledRelease, InstrumentError> {
39    registry.activate(req.release_id)
40}
41
42/// Run a preflighted install. Empty input is held; unknown entries are refused.
43pub fn run_entry(
44    registry: &LocalRegistry,
45    installed: &InstalledRelease,
46    req: &RunRequest<'_>,
47) -> RunOutcome {
48    if let Err(error) = registry.activate(req.release_id) {
49        return RunOutcome::Refused { error };
50    }
51    if req.cancelled {
52        return RunOutcome::Refused {
53            error: InstrumentError::Cancelled,
54        };
55    }
56    if !DEMO_ENTRY_POINTS.contains(&req.entry_point) {
57        return RunOutcome::Refused {
58            error: InstrumentError::UnknownEntryPoint,
59        };
60    }
61    if req.max_steps == 0 || req.input.len() > req.max_input_bytes {
62        return RunOutcome::Refused {
63            error: InstrumentError::ResourceLimit,
64        };
65    }
66    if req.input.is_empty() {
67        return RunOutcome::Held {
68            receipt: bind_receipt(installed, req, &[], "held"),
69        };
70    }
71    if let Some(kind) = CoreInstrumentKind::from_slug_or_id(installed.release_id.as_str())
72        .or_else(|| CoreInstrumentKind::from_slug_or_id(req.release_id))
73    {
74        return match execute_reference_instrument(kind, req.input, req.now) {
75            Ok(report) => {
76                let out_bytes = serde_json::to_vec(&report).unwrap_or_default();
77                if report.outcome == EvaluationOutcome::Held {
78                    RunOutcome::Held {
79                        receipt: bind_receipt(installed, req, &out_bytes, "held"),
80                    }
81                } else {
82                    RunOutcome::Completed {
83                        receipt: bind_receipt(installed, req, &out_bytes, report.outcome.as_str()),
84                    }
85                }
86            }
87            Err(error) => RunOutcome::Refused { error },
88        };
89    }
90    // Labelled demo: identity transform so callers can check I/O commitments.
91    RunOutcome::Completed {
92        receipt: bind_receipt(installed, req, req.input, "completed"),
93    }
94}
95
96fn bind_receipt(
97    installed: &InstalledRelease,
98    req: &RunRequest<'_>,
99    output: &[u8],
100    outcome: &str,
101) -> ExecutionReceipt {
102    ExecutionReceipt::bind(
103        installed.release_id.as_str(),
104        installed.content_digest.as_str(),
105        &installed.lock.digest(),
106        req.entry_point,
107        req.input,
108        output,
109        req.parent_receipt.clone(),
110        outcome,
111    )
112}
113
114#[cfg(test)]
115mod tests {
116    use super::*;
117    use crate::semantic_instruments::canonical::sha256_prefixed;
118    use crate::semantic_instruments::resolve::{DependencyLock, InstalledRelease, LocalRegistry};
119
120    const RELEASE: &str = "https://ns.webizen.org/demo/unit-convert/releases/1.0.0";
121    const DIGEST: &str = "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
122
123    fn empty_lock(release_id: &str) -> DependencyLock {
124        DependencyLock {
125            release_id: release_id.into(),
126            entries: Vec::new(),
127        }
128    }
129
130    fn demo_install(closed: bool) -> InstalledRelease {
131        InstalledRelease {
132            release_id: RELEASE.into(),
133            content_digest: DIGEST.into(),
134            lock: empty_lock(RELEASE),
135            closed,
136        }
137    }
138
139    fn request<'a>(entry_point: &'a str, input: &'a [u8]) -> RunRequest<'a> {
140        RunRequest {
141            release_id: RELEASE,
142            entry_point,
143            input,
144            now: 1,
145            cancelled: false,
146            max_input_bytes: 64,
147            max_steps: 8,
148            parent_receipt: None,
149        }
150    }
151
152    fn closed_registry() -> LocalRegistry {
153        let mut registry = LocalRegistry::new();
154        registry.install(demo_install(true)).unwrap();
155        registry
156    }
157
158    fn completed(outcome: RunOutcome) -> ExecutionReceipt {
159        match outcome {
160            RunOutcome::Completed { receipt } => receipt,
161            _ => panic!("expected Completed"),
162        }
163    }
164
165    fn held(outcome: RunOutcome) -> ExecutionReceipt {
166        match outcome {
167            RunOutcome::Held { receipt } => receipt,
168            _ => panic!("expected Held"),
169        }
170    }
171
172    fn refused(outcome: RunOutcome) -> InstrumentError {
173        match outcome {
174            RunOutcome::Refused { error } => error,
175            _ => panic!("expected Refused"),
176        }
177    }
178
179    #[test]
180    fn closed_assess_identity_completes() {
181        let registry = closed_registry();
182        let req = request("assess", b"demo-ok");
183        let installed = preflight(&registry, &req).unwrap();
184        let receipt = completed(run_entry(&registry, installed, &req));
185        assert_eq!(receipt.release_id, RELEASE);
186        assert_eq!(receipt.content_digest, DIGEST);
187        assert_eq!(receipt.lock_digest, installed.lock.digest());
188        assert_eq!(receipt.entry_point, "assess");
189        assert_eq!(receipt.outcome, "completed");
190        assert_eq!(receipt.input_commitment, sha256_prefixed(b"demo-ok"));
191        assert_eq!(receipt.output_commitment, sha256_prefixed(b"demo-ok"));
192        assert!(receipt.parent_receipt.is_none());
193    }
194
195    #[test]
196    fn empty_input_is_held() {
197        let registry = closed_registry();
198        let req = request("recognise", b"");
199        let installed = preflight(&registry, &req).unwrap();
200        let receipt = held(run_entry(&registry, installed, &req));
201        assert_eq!(receipt.outcome, "held");
202        assert_eq!(receipt.input_commitment, sha256_prefixed(b""));
203        assert_eq!(receipt.output_commitment, sha256_prefixed(b""));
204        assert_eq!(receipt.entry_point, "recognise");
205    }
206
207    #[test]
208    fn unknown_host_entry_is_refused() {
209        let registry = closed_registry();
210        let req = request("Host.ClinicalRisk.framingham", b"demo-ok");
211        let installed = preflight(&registry, &req).unwrap();
212        assert_eq!(
213            refused(run_entry(&registry, installed, &req)),
214            InstrumentError::UnknownEntryPoint
215        );
216    }
217
218    #[test]
219    fn cancelled_is_refused() {
220        let registry = closed_registry();
221        let mut req = request("assess", b"demo-ok");
222        req.cancelled = true;
223        let installed = preflight(&registry, &req).unwrap();
224        assert_eq!(
225            refused(run_entry(&registry, installed, &req)),
226            InstrumentError::Cancelled
227        );
228    }
229
230    #[test]
231    fn open_install_preflight_is_not_closed() {
232        let mut registry = LocalRegistry::new();
233        registry.install(demo_install(false)).unwrap();
234        let req = request("assess", b"demo-ok");
235        assert_eq!(preflight(&registry, &req), Err(InstrumentError::NotClosed));
236    }
237
238    #[test]
239    fn huge_input_is_resource_limit() {
240        let registry = closed_registry();
241        let mut req = request("assess", b"demo-ok");
242        req.max_input_bytes = 3;
243        let installed = preflight(&registry, &req).unwrap();
244        assert_eq!(
245            refused(run_entry(&registry, installed, &req)),
246            InstrumentError::ResourceLimit
247        );
248    }
249
250    #[test]
251    fn zero_steps_is_resource_limit() {
252        let registry = closed_registry();
253        let mut req = request("assess", b"demo-ok");
254        req.max_steps = 0;
255        let installed = preflight(&registry, &req).unwrap();
256        assert_eq!(
257            refused(run_entry(&registry, installed, &req)),
258            InstrumentError::ResourceLimit
259        );
260    }
261}