Skip to main content

vibe/session/
mod.rs

1//! Bounded in-memory checked source sessions for the pinned 0.1 interpreter.
2//! This is not durable project recovery, live definition replacement, or a job API.
3use crate::ast::*;
4use crate::check::{check_submission, CheckEnv};
5use crate::{Budget, DiagCode, Diagnostic, Engine, Env, Host, Span, Value};
6use std::collections::HashSet;
7use std::sync::atomic::{AtomicU64, Ordering};
8mod prepare;
9mod source_limits;
10#[cfg(test)]
11mod tests;
12mod values;
13#[cfg(test)]
14mod validation_tests;
15#[cfg(test)]
16mod binding_validation_tests;
17
18static NEXT_SESSION: AtomicU64 = AtomicU64::new(1);
19
20#[derive(Clone, Debug)]
21pub struct SessionLimits {
22    pub submission_bytes: usize,
23    pub retained_source_bytes: usize,
24    pub declarations: usize,
25    pub bindings: usize,
26    /// Ceiling on retained values' Debug representation, measured without
27    /// allocating a serialization buffer. This is not an allocator hard limit.
28    pub retained_value_bytes: usize,
29    pub revisions: u64,
30    /// Source-session admitted range 1..=8 calls, clamped to that range.
31    pub call_depth: u32,
32    /// Total evaluation nesting across functions, admitted range 1..=64.
33    pub expression_depth: u32,
34}
35impl Default for SessionLimits {
36    fn default() -> Self {
37        Self {
38            submission_bytes: 64 * 1024,
39            retained_source_bytes: 1024 * 1024,
40            declarations: 1024,
41            bindings: 1024,
42            retained_value_bytes: crate::SENTINEL_BYTES as usize,
43            revisions: 1024,
44            call_depth: 8,
45            expression_depth: 64,
46        }
47    }
48}
49
50/// A runtime error preserves the original diagnostic. Host state is outside the
51/// tentative local frame: a dispatched operation may have committed or failed
52/// after committing. Reconcile authoritative receipts with the actual host.
53#[derive(Debug)]
54pub struct SubmissionError {
55    pub diagnostic: Diagnostic,
56    pub execution_attempted: bool,
57    pub host_reconciliation_required: bool,
58    pub active_revision: u64,
59}
60
61#[derive(Debug)]
62pub struct SubmissionResult {
63    pub value: Value,
64    pub revision: u64,
65}
66
67enum Body {
68    Program(Program),
69    Expression(Expr),
70}
71
72/// Checked candidates cannot be constructed or edited by the caller. They are
73/// bound to their originating session and active revision, consumed once.
74pub struct CheckedSubmission {
75    owner: u64,
76    base_revision: u64,
77    source: String,
78    definitions: Program,
79    checked: CheckEnv,
80    mutables: HashSet<String>,
81    body: Body,
82    replace_env: bool,
83}
84
85/// Read-only view of evaluated bindings before source-session promotion.
86/// Host effects remain governed by the actual host; rejection does not undo them.
87pub struct SessionBindings<'a> {
88    env: &'a Env,
89}
90impl SessionBindings<'_> {
91    pub fn value(&self, name: &str) -> Option<&Value> {
92        self.env.vars.get(name)
93    }
94}
95pub struct SourceSession {
96    owner: u64,
97    revision: u64,
98    limits: SessionLimits,
99    /// Actual grants are supplied by the host, never inferred from requests.
100    grants: Vec<String>,
101    definitions: Program,
102    checked: CheckEnv,
103    mutables: HashSet<String>,
104    env: Env,
105    sources: Vec<String>,
106    source_bytes: usize,
107}
108
109impl Default for SourceSession {
110    fn default() -> Self {
111        Self::new(Vec::new(), SessionLimits::default())
112    }
113}
114
115impl SourceSession {
116    pub fn new(grants: Vec<String>, limits: SessionLimits) -> Self {
117        Self {
118            owner: NEXT_SESSION.fetch_add(1, Ordering::Relaxed),
119            revision: 0,
120            limits,
121            grants,
122            definitions: Program {
123                span: Span::point(0),
124                module: None,
125                imports: Vec::new(),
126                prefixes: Vec::new(),
127                locales: Vec::new(),
128                requires: Vec::new(),
129                items: Vec::new(),
130            },
131            checked: CheckEnv::default(),
132            mutables: HashSet::new(),
133            env: Env::default(),
134            sources: Vec::new(),
135            source_bytes: 0,
136        }
137    }
138    pub fn revision(&self) -> u64 {
139        self.revision
140    }
141    /// Read-only accepted bindings, using the same view as tentative validation.
142    pub fn bindings(&self) -> SessionBindings<'_> {
143        SessionBindings { env: &self.env }
144    }
145    pub fn value(&self, name: &str) -> Option<&Value> {
146        self.env.vars.get(name)
147    }
148    pub fn is_mutable(&self, name: &str) -> bool {
149        self.mutables.contains(name)
150    }
151    pub fn sources(&self) -> &[String] {
152        &self.sources
153    }
154    pub fn binding_type(&self, name: &str) -> Option<String> {
155        self.checked.get(name).map(|t| format!("{t:?}"))
156    }
157    fn error(&self, diagnostic: Diagnostic, attempted: bool) -> SubmissionError {
158        SubmissionError {
159            diagnostic,
160            execution_attempted: attempted,
161            // No Value::Receipt/default host return is promoted to verified
162            // effect evidence. Even a statically Pure binding can call Host.
163            host_reconciliation_required: attempted,
164            active_revision: self.revision,
165        }
166    }
167    pub fn submit<H: Host>(
168        &mut self,
169        source: &str,
170        host: &mut H,
171        budget: Budget,
172    ) -> Result<SubmissionResult, SubmissionError> {
173        self.submit_validated(source, host, budget, |_| Ok(()))
174    }
175    /// Validate evaluated output before promoting any tentative local values,
176    /// definitions or source. Host effects already attempted are not rolled back.
177    pub fn submit_validated<H: Host, F: FnOnce(&Value) -> Result<(), Diagnostic>>(
178        &mut self,
179        source: &str,
180        host: &mut H,
181        budget: Budget,
182        validate: F,
183    ) -> Result<SubmissionResult, SubmissionError> {
184        let candidate = self.prepare(source).map_err(|e| self.error(e, false))?;
185        self.execute_validated(candidate, host, budget, validate)
186    }
187    /// Validate tentative bindings and result using the same host before local
188    /// promotion. Dispatched host effects are not automatically rolled back.
189    pub fn submit_validated_bindings<H: Host, F>(
190        &mut self,
191        source: &str,
192        host: &mut H,
193        budget: Budget,
194        validate: F,
195    ) -> Result<SubmissionResult, SubmissionError>
196    where
197        F: FnOnce(&Value, SessionBindings<'_>, &mut H) -> Result<(), Diagnostic>,
198    {
199        let candidate = self.prepare(source).map_err(|e| self.error(e, false))?;
200        self.execute_validated_bindings(candidate, host, budget, validate)
201    }
202    pub fn execute<H: Host>(
203        &mut self,
204        candidate: CheckedSubmission,
205        host: &mut H,
206        budget: Budget,
207    ) -> Result<SubmissionResult, SubmissionError> {
208        self.execute_validated(candidate, host, budget, |_| Ok(()))
209    }
210
211    /// Apply a structural `projectional::Edit` and re-evaluate the session.
212    /// Any parse, check, or evaluation failure rolls back all session state.
213    pub fn apply_edit<H: Host>(
214        &mut self,
215        edit: &crate::projectional::Edit,
216        host: &mut H,
217        budget: Budget,
218    ) -> Result<SubmissionResult, SubmissionError> {
219        let candidate = self.prepare_edit(edit).map_err(|e| self.error(e, false))?;
220        self.execute(candidate, host, budget)
221    }
222
223    /// Submit source with explicit replacement of matching top-level declarations.
224    /// Any check or evaluation failure rolls back all session state.
225    pub fn replace<H: Host>(
226        &mut self,
227        source: &str,
228        host: &mut H,
229        budget: Budget,
230    ) -> Result<SubmissionResult, SubmissionError> {
231        let candidate = self.prepare_replace(source).map_err(|e| self.error(e, false))?;
232        self.execute(candidate, host, budget)
233    }
234    /// The validator receives actual evaluated output once, after interpreter
235    /// checks and before promotion. It may recheck native authority while its
236    /// owner transaction is held; no JSON receipt is treated as authority.
237    pub fn execute_validated<H: Host, F: FnOnce(&Value) -> Result<(), Diagnostic>>(
238        &mut self,
239        candidate: CheckedSubmission,
240        host: &mut H,
241        budget: Budget,
242        validate: F,
243    ) -> Result<SubmissionResult, SubmissionError> {
244        self.execute_validated_bindings(candidate, host, budget, |value, _, _| validate(value))
245    }
246
247    /// Inspect tentative bindings and debit the actual host before promotion.
248    /// A rejected callback preserves local source/session state. Any already
249    /// dispatched external host effects still require reconciliation.
250    pub fn execute_validated_bindings<H: Host, F>(
251        &mut self,
252        candidate: CheckedSubmission,
253        host: &mut H,
254        budget: Budget,
255        validate: F,
256    ) -> Result<SubmissionResult, SubmissionError>
257    where
258        F: FnOnce(&Value, SessionBindings<'_>, &mut H) -> Result<(), Diagnostic>,
259    {
260        if candidate.owner != self.owner || candidate.base_revision != self.revision {
261            return Err(self.error(
262                Diagnostic::new(
263                    DiagCode::E701,
264                    Span::point(0),
265                    "checked submission belongs to another session or stale revision",
266                ),
267                false,
268            ));
269        }
270        let mut tentative = if candidate.replace_env {
271            Env::default()
272        } else {
273            self.env.clone()
274        };
275        crate::populate_import_aliases(&mut tentative, &candidate.definitions.imports)
276            .map_err(|e| self.error(e, false))?;
277        let mut budget = budget;
278        budget.workspace_left = budget
279            .workspace_left
280            .min(self.limits.retained_value_bytes as u64);
281        let mut engine = Engine::with_program(host, budget, &candidate.definitions);
282        engine.set_session_stack_limits(self.limits.call_depth, self.limits.expression_depth);
283        // Only this submission executes. Old top-level statements, constants,
284        // materials and cell initialization are absent from `body`.
285        let result = match &candidate.body {
286            Body::Program(program) => engine.eval_program(program, &mut tentative),
287            Body::Expression(expr) => engine.eval_expr(expr, &mut tentative),
288        };
289        drop(engine);
290        let value = result.map_err(|e| self.error(e, true))?;
291        if tentative.vars.len() > self.limits.bindings {
292            return Err(self.error(
293                Diagnostic::new(
294                    DiagCode::E400,
295                    Span::point(0),
296                    "session binding limit exceeded after evaluation",
297                ),
298                true,
299            ));
300        }
301        values::validate(&candidate.checked, &tentative).map_err(|e| self.error(e, true))?;
302        values::check_retained_size(&tentative, self.limits.retained_value_bytes)
303            .map_err(|e| self.error(e, true))?;
304        validate(&value, SessionBindings { env: &tentative }, host).map_err(|e| self.error(e, true))?;
305        self.env = tentative;
306        self.checked = candidate.checked;
307        self.mutables = candidate.mutables;
308        self.definitions = candidate.definitions;
309        if candidate.replace_env {
310            self.source_bytes = candidate.source.len();
311            self.sources = vec![candidate.source];
312        } else {
313            self.source_bytes += candidate.source.len();
314            self.sources.push(candidate.source);
315        }
316        self.revision += 1;
317        Ok(SubmissionResult {
318            value,
319            revision: self.revision,
320        })
321    }
322}