Skip to main content

dive_eval/
inputs.rs

1//! Explicit host categories and bounded, source-ordered external input replay.
2//!
3//! Recorded values are assumptions supplied by the caller. Replay proves their
4//! use by source operations; it cannot prove what a past operating system held.
5
6use std::collections::BTreeMap;
7use std::sync::{Mutex, PoisonError};
8
9use dive_ir::{StdOp, StdSupport};
10
11use crate::HostError;
12
13/// Maximum total UTF-8 bytes retained by one external-input context.
14pub const MAX_INPUT_BYTES: usize = 1 << 20;
15/// Maximum source input operations retained by one context.
16pub const MAX_INPUT_RECORDS: usize = 256;
17/// Maximum entries in one captured environment.
18pub const MAX_ENV_ENTRIES: usize = 4096;
19
20/// Explicit host category grants. Every profile defaults to no grants.
21/// A grant never supplies an implementation or overrides a driver's refusal.
22#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
23pub struct HostAccess {
24    /// Read the process environment.
25    pub env: bool,
26    /// Read or write files, where the chosen driver implements the operation.
27    pub files: bool,
28    /// Execute processes, where implemented. Currently refused by the drivers.
29    pub exec: bool,
30}
31
32impl HostAccess {
33    /// No host access, including under TLC compatibility.
34    pub const NONE: Self = Self {
35        env: false,
36        files: false,
37        exec: false,
38    };
39
40    /// Parses the approved comma-separated category spelling.
41    ///
42    /// ```
43    /// let access = dive_eval::inputs::HostAccess::parse("env,files")?;
44    /// assert!(access.env && access.files && !access.exec);
45    /// # Ok::<(), &'static str>(())
46    /// ```
47    ///
48    /// # Errors
49    /// Empty, duplicate or unknown category names.
50    pub fn parse(text: &str) -> Result<Self, &'static str> {
51        let mut access = Self::NONE;
52        for name in text.split(',') {
53            let slot = match name {
54                "env" => &mut access.env,
55                "files" => &mut access.files,
56                "exec" => &mut access.exec,
57                _ => return Err("--allow-io expects comma-separated env,files,exec categories"),
58            };
59            if *slot {
60                return Err("--allow-io repeats a category");
61            }
62            *slot = true;
63        }
64        Ok(access)
65    }
66
67    /// Granted category names in stable report order.
68    #[must_use]
69    pub fn names(self) -> Vec<&'static str> {
70        [
71            (self.env, "env"),
72            (self.files, "files"),
73            (self.exec, "exec"),
74        ]
75        .into_iter()
76        .filter_map(|(yes, name)| yes.then_some(name))
77        .collect()
78    }
79
80    /// Whether no category was granted.
81    #[must_use]
82    pub const fn is_empty(self) -> bool {
83        !self.env && !self.files && !self.exec
84    }
85
86    /// Whether a native operator's host category is granted. Non-I/O operators
87    /// require no category; this says nothing about implementation support.
88    #[must_use]
89    pub fn allows(self, op: StdOp) -> bool {
90        self.denied(op).is_none()
91    }
92
93    pub(crate) fn denied(self, op: StdOp) -> Option<&'static str> {
94        let (allowed, category) = match op {
95            StdOp::IoUtilsIOEnv => (self.env, "env"),
96            StdOp::IoUtilsIOExec
97            | StdOp::IoUtilsIOEnvExec
98            | StdOp::IoUtilsIOExecTemplate
99            | StdOp::IoUtilsIOEnvExecTemplate => (self.exec, "exec"),
100            _ if op.support() == StdSupport::Io => (self.files, "files"),
101            _ => return None,
102        };
103        (!allowed).then_some(category)
104    }
105}
106
107/// A source operation's external request, after its real arguments evaluate.
108#[derive(Clone, Debug, PartialEq, Eq)]
109pub enum InputRequest {
110    /// `IOUtils!IOEnv`.
111    Environment,
112    /// `IOUtils!Deserialize` with admitted TXT/UTF-8 options.
113    TextFile(String),
114}
115
116/// External bytes interpreted by the evaluator, never an arbitrary TLA+ value.
117#[derive(Clone, Debug, PartialEq, Eq)]
118pub enum InputResponse {
119    /// The complete UTF-8 process environment, fixed for a run.
120    Environment(BTreeMap<String, String>),
121    /// Exact UTF-8 contents of one file read.
122    Text(String),
123}
124
125/// One actual source-ordered input operation and its assumed response.
126#[derive(Clone, Debug, PartialEq, Eq)]
127pub struct InputRecord {
128    /// The source operation and actual path argument.
129    pub request: InputRequest,
130    /// The recorded external input, not a producer state or proof flag.
131    pub response: InputResponse,
132}
133
134impl InputRecord {
135    /// Retained UTF-8 bytes, including names and path arguments.
136    #[must_use]
137    pub fn bytes(&self) -> usize {
138        let path = match &self.request {
139            InputRequest::Environment => 0,
140            InputRequest::TextFile(path) => path.len(),
141        };
142        path.saturating_add(match &self.response {
143            InputResponse::Environment(entries) => {
144                entries.iter().fold(0usize, |n, (key, value)| {
145                    n.saturating_add(key.len()).saturating_add(value.len())
146                })
147            }
148            InputResponse::Text(text) => text.len(),
149        })
150    }
151}
152
153/// Bounded external assumptions for a fresh source binding.
154#[derive(Clone, Debug, Default, PartialEq, Eq)]
155pub struct RecordedInputs {
156    /// Explicit categories used by the original request.
157    pub grants: HostAccess,
158    /// Operations in their actual source execution order.
159    pub records: Vec<InputRecord>,
160}
161
162/// Raw external input provider owned by one source-binding operation.
163pub trait InputSource: Send + Sync + std::fmt::Debug {
164    /// Executes or replays one exact source request.
165    ///
166    /// # Errors
167    /// A named unsupported request, resource bound or replay mismatch.
168    fn request(&self, request: &InputRequest) -> Result<InputResponse, HostError>;
169    /// Closes binding and checks all required source demand.
170    ///
171    /// # Errors
172    /// A remembered error or undemanded extra input records.
173    fn finish_binding(&self) -> Result<(), HostError>;
174    /// Captured assumptions as raw text, never evaluator-owned values.
175    fn recorded(&self) -> RecordedInputs;
176}
177
178impl RecordedInputs {
179    /// Checks resource bounds and response/request consistency without I/O.
180    ///
181    /// # Errors
182    /// Oversized, incorrectly typed, ungranted or inconsistent input records.
183    pub fn validate(&self) -> Result<(), HostError> {
184        if self.records.len() > MAX_INPUT_RECORDS
185            || self
186                .records
187                .iter()
188                .fold(0usize, |n, r| n.saturating_add(r.bytes()))
189                > MAX_INPUT_BYTES
190        {
191            return Err(input_error("recorded external input bounds"));
192        }
193        let mut environment = None;
194        for record in &self.records {
195            match (&record.request, &record.response) {
196                (InputRequest::Environment, InputResponse::Environment(entries))
197                    if self.grants.env =>
198                {
199                    if entries.len() > MAX_ENV_ENTRIES {
200                        return Err(input_error("environment entry limit"));
201                    }
202                    if environment.is_some_and(|previous| previous != entries) {
203                        return Err(input_error("recorded IOEnv must retain one environment"));
204                    }
205                    environment = Some(entries);
206                }
207                (InputRequest::TextFile(_), InputResponse::Text(_)) if self.grants.files => {}
208                _ => return Err(input_error("recorded input kind or category mismatch")),
209            }
210        }
211        Ok(())
212    }
213}
214
215/// A fresh ordered replay cursor. It has no operating-system access.
216#[derive(Debug)]
217pub struct InputReplay {
218    inputs: RecordedInputs,
219    cursor: Mutex<(usize, bool, Option<HostError>)>,
220}
221
222impl InputReplay {
223    /// Starts an independent cursor over explicit, bounded assumptions.
224    ///
225    /// ```
226    /// use dive_eval::inputs::{HostAccess, InputRecord, InputReplay,
227    ///     InputRequest, InputResponse, RecordedInputs};
228    /// let request = InputRequest::TextFile("input.txt".into());
229    /// let replay = InputReplay::new(RecordedInputs {
230    ///     grants: HostAccess::parse("files").unwrap(),
231    ///     records: vec![InputRecord { request: request.clone(),
232    ///         response: InputResponse::Text("hello".into()) }],
233    /// }).unwrap();
234    /// assert_eq!(replay.request(&request).unwrap(), InputResponse::Text("hello".into()));
235    /// replay.finish_binding().unwrap();
236    /// ```
237    ///
238    /// # Errors
239    /// Invalid recorded inputs; no source or host callback is executed.
240    pub fn new(inputs: RecordedInputs) -> Result<Self, HostError> {
241        inputs.validate()?;
242        Ok(Self {
243            inputs,
244            cursor: Mutex::new((0, false, None)),
245        })
246    }
247
248    /// Consumes the next exact source operation/argument pair.
249    ///
250    /// # Errors
251    /// Missing, mismatched, extra-phase or previously failed input requests.
252    pub fn request(&self, request: &InputRequest) -> Result<InputResponse, HostError> {
253        let mut cursor = self.cursor.lock().unwrap_or_else(PoisonError::into_inner);
254        if let Some(error) = &cursor.2 {
255            return Err(error.clone());
256        }
257        let record = self.inputs.records.get(cursor.0);
258        let result = if cursor.1 {
259            Err(input_error("external input outside source binding"))
260        } else if let Some(record) = record {
261            if &record.request == request {
262                Ok(record.response.clone())
263            } else {
264                Err(input_error(
265                    "recorded input does not match the next source operation and arguments",
266                ))
267            }
268        } else {
269            Err(input_error("missing recorded source input"))
270        };
271        match &result {
272            Ok(_) => cursor.0 += 1,
273            Err(error) => cursor.2 = Some(error.clone()),
274        }
275        result
276    }
277
278    /// Closes binding, requiring every supplied record to have been demanded.
279    ///
280    /// # Errors
281    /// A latched replay failure or extra input records.
282    pub fn finish_binding(&self) -> Result<(), HostError> {
283        let mut cursor = self.cursor.lock().unwrap_or_else(PoisonError::into_inner);
284        cursor.1 = true;
285        if let Some(error) = &cursor.2 {
286            return Err(error.clone());
287        }
288        if cursor.0 != self.inputs.records.len() {
289            let error = input_error("extra recorded inputs not demanded by source binding");
290            cursor.2 = Some(error.clone());
291            return Err(error);
292        }
293        Ok(())
294    }
295
296    /// A latched mismatch or request outside binding, even if source caught it.
297    #[must_use]
298    pub fn failure(&self) -> Option<HostError> {
299        self.cursor
300            .lock()
301            .unwrap_or_else(PoisonError::into_inner)
302            .2
303            .clone()
304    }
305}
306
307impl InputSource for InputReplay {
308    fn request(&self, request: &InputRequest) -> Result<InputResponse, HostError> {
309        Self::request(self, request)
310    }
311    fn finish_binding(&self) -> Result<(), HostError> {
312        Self::finish_binding(self)
313    }
314    fn recorded(&self) -> RecordedInputs {
315        self.inputs.clone()
316    }
317}
318
319impl crate::Host for InputReplay {
320    fn input(&self, request: &InputRequest) -> Option<Result<InputResponse, HostError>> {
321        Some(self.request(request))
322    }
323}
324
325/// A named external-input refusal; code zero never certifies a TLC exception.
326#[must_use]
327pub fn input_error(message: &str) -> HostError {
328    HostError {
329        code: 0,
330        message: format!("external inputs: {message}"),
331    }
332}