oxdock_core/exec/state.rs
1use std::collections::{HashMap, HashSet};
2use std::marker::PhantomData;
3use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
4use std::sync::{Arc, Condvar, Mutex};
5
6use anyhow::Result;
7use oxdock_fs::{CargoScratch, GuardedPath, WorkspaceFs, WorkspaceSelection};
8use oxdock_parser::constants::KEYWORD_CONST;
9use oxdock_parser::{Field, GuardExpr, Step, TypeDescriptor, TypeTag, Value, sigil_var};
10use oxdock_process::{BackgroundHandle, CancelHub, CommandContext, ProcessManager};
11
12use super::exit::exit_code_of;
13use super::io::{ExactCapture, ExecIo, SlidingWindow, TeeStream};
14use super::native::FunctionRegistry;
15use oxdock_pipe::KeeperGuard;
16
17/// Maximum nested function-call depth. Guards the host thread stack against
18/// runaway recursion; the error names the function that overflowed.
19pub(super) const MAX_CALL_DEPTH: usize = 64;
20
21/// Retained finished-task cap. Bounds `named_tasks` tombstones plus
22/// their tail buffers in long-lived sessions: spawning past the cap
23/// evicts the oldest finished entry. Running entries are never evicted.
24pub(super) const MAX_RETAINED_FINISHED: usize = 128;
25
26/// Live-task concurrency cap. Enforced globally through the shared
27/// counter below: any ASYNC spawn, in any nested worker, sees the
28/// same count. Refusal is backpressure, not silent kills and not an
29/// unbounded queue.
30pub const MAX_RUNNING_TASKS: usize = 64;
31
32/// RAII slot for the global live-task count. Created first inside
33/// every ASYNC worker thread; dropping on return or unwind releases
34/// the slot. The count therefore tracks threads actually alive, never
35/// table entries, so un-awaited finished tasks cannot squat slots and
36/// nested workers cannot bypass the cap.
37pub(super) struct TaskSlotGuard {
38 counter: Arc<AtomicU64>,
39}
40
41impl TaskSlotGuard {
42 pub(super) fn new(counter: Arc<AtomicU64>) -> Self {
43 Self { counter }
44 }
45}
46
47impl Drop for TaskSlotGuard {
48 fn drop(&mut self) {
49 self.counter.fetch_sub(1, Ordering::SeqCst);
50 }
51}
52
53/// Per-stream live tail cap for background tasks. Matches the
54/// foreground capture scale: the same never-grows guarantee.
55const TASK_TAIL_CAP: usize = 64 * 1024;
56
57/// Single message shape for every refused `CONST` write: `$var = <expr>`
58/// reassignment, `LIST_APPEND`, `MAP_SET`/`MERGE_MAPS`, and frozen-buffer
59/// render this prefix, so tests and diagnostics match one string.
60/// Free function (not a method) so host-function extractors and
61/// macro-generated wrappers share it without a state handle.
62pub fn const_mutation_error(what: &str) -> anyhow::Error {
63 anyhow::anyhow!(
64 "cannot mutate {kw} {what}: {kw} bindings are deeply immutable",
65 kw = KEYWORD_CONST,
66 )
67}
68
69/// Execution state for one script run. Public so hosts can register
70/// functions and introspect listings; all fields stay crate-private so the
71/// scope, recursion-budget, and task invariants cannot be broken from outside.
72pub struct ExecState<P: ProcessManager> {
73 pub(super) fs: Box<dyn WorkspaceFs>,
74 /// Pre-reserved guarded scratch dir (session temp for child
75 /// writes). Opaque [`CargoScratch`]: renderable for the child
76 /// environment but not nameable as a `&GuardedPath`, so host code
77 /// cannot `ensure()` or `create_dir_all` it. The child `cargo` creates it on demand.
78 pub(super) cargo_scratch: CargoScratch,
79 /// Pure session seed from [`oxdock_process::seed_defaults`], stored at
80 /// init alongside the layered `envs`. `ISOLATED` resets clone this
81 /// (not the layered map), and transport sanitize diffs against it.
82 /// Built once: re-seeding would re-read host fallbacks and break
83 /// state stability.
84 pub(super) seed: Arc<HashMap<String, String>>,
85 pub(super) cwd: GuardedPath,
86 pub(super) envs: Arc<HashMap<String, String>>,
87 /// Each entry is the script env as it stood at that block's entry, so
88 /// the block allowlist resolves against the enclosing scope even as
89 /// the live envs are scrubbed underneath. Nesting snapshots the
90 /// already-scrubbed parent, so narrowing is monotonic by
91 /// construction. Cloned (not reset) by `fork()` so tasks spawned
92 /// inside a block inherit its scrub.
93 pub(super) isolated_stack: Vec<Arc<HashMap<String, String>>>,
94 pub(super) bg_children: Vec<BgChild>,
95 pub(super) scope_stack: Vec<ScopeSnapshot>,
96 pub(super) io: ExecIo,
97 /// Pre-registered SlidingWindow observers for stream assertion steps.
98 /// Keyed by (generation, step index). TeeWriter pushes every chunk to all windows.
99 pub(super) assert_windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
100 /// Same observer map fed by the stderr tee for `ASSERT_CONTAINS stderr`.
101 pub(super) assert_windows_stderr: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
102 /// Exact-match stdout accumulators for `ASSERT_EQ`/`ASSERT_NE stdout`, keyed by
103 /// generation and fed by the same tee. Entries allocated during
104 /// pre-registration observe bytes from scope entry; the common
105 /// top-level case therefore sees trial-cumulative output.
106 pub(super) exact_stdout: Arc<Mutex<HashMap<usize, ExactCapture>>>,
107 /// Variable scopes for $variable bindings (FOR loops, LET assignments).
108 /// Innermost scope is last. Variables are looked up from innermost to outermost.
109 /// Each entry carries its declared type name alongside the value.
110 pub(super) var_scopes: Vec<HashMap<String, (TypeTag, Value)>>,
111 /// `CONST` names per variable scope frame, pushed and popped in
112 /// lockstep with `var_scopes`. A name present here refuses `$var = <expr>`
113 /// reassignment, `LIST_APPEND`, and rebinding; the value-level frozen flag
114 /// additionally refuses writes through `LET`-bound aliases.
115 pub(super) const_scopes: Vec<HashSet<String>>,
116 /// Name directory for type resolution: startup descriptors plus the
117 /// run's host descriptors. Words carry their own vtables, so this map
118 /// serves only name queries (declarations, `TYPES()`, `TYPE_DESCRIBE`).
119 pub(super) types: HashMap<String, &'static TypeDescriptor>,
120 /// Named record schemas for shaped MAP bindings: schema name to its
121 /// field table. Populated from host modules alongside descriptors, so
122 /// `LET $s: SSH_SESSION_INFO` resolves exactly when the owning module
123 /// is registered. Impossible to reference an unregistered schema.
124 pub(super) record_schemas: HashMap<String, Arc<[Field]>>,
125 /// Module-shared state stashed at registration, keyed by owning
126 /// module name plus value type. Bodies fetch it through
127 /// `StepCtx::module_state` instead of hand-built closures, so
128 /// every entry can stay `#[oxdock_func]`.
129 pub(super) module_states:
130 HashMap<(String, std::any::TypeId), Arc<dyn std::any::Any + Send + Sync>>,
131 /// Script-level type aliases for this run: alias name to canonical
132 /// target spelling (`PERSON` to `MAP<name:STRING>`). Populated once
133 /// from top-level `TYPE` steps before the static pass, so forward
134 /// references resolve run-wide at first coercion.
135 pub(super) type_aliases: HashMap<String, String>,
136 /// Digest of the type environment above (aliases, schemas, custom
137 /// types), folded per mutation: interned rendered tags key on
138 /// spelling plus this digest, so one run's alias-dependent
139 /// shapes never share entries with another run's.
140 pub(super) type_env_digest: u64,
141 /// Cancellation token for background thread teardown.
142 #[allow(dead_code)]
143 pub(super) cancel_token: Arc<AtomicBool>,
144 /// Event hub fanning the same cancellation to pump supervisors.
145 /// Marked everywhere the token is stored, so blocking pumps wake
146 /// without polling. Forks get a fresh hub with their fresh token.
147 #[allow(dead_code)]
148 pub(super) cancel_hub: Arc<CancelHub>,
149 /// Handle to the currently executing foreground OS process, so
150 /// ThreadJoinHandle::kill() can interrupt a blocking wait().
151 #[allow(dead_code)]
152 pub(super) active_process: Arc<Mutex<Option<Box<dyn BackgroundHandle>>>>,
153 /// Named task registry for AWAIT/CANCEL support. Shared across subscopes
154 /// via Arc. Each entry is a synchronized state machine (`TaskEntry`):
155 /// the handle lives inside the entry so `CANCEL` can synchronously tear
156 /// down a task even while a concurrent `AWAIT` is waiting on it.
157 /// Entries are retained as `Cancelled`/`Completed` tombstones so later
158 /// `AWAIT`/`CANCEL` report precise errors instead of `TaskNotFound`.
159 #[allow(dead_code)]
160 pub(super) named_tasks: Arc<Mutex<HashMap<u64, Arc<TaskEntry>>>>,
161 /// Counter for generating unique task IDs. Shared across subscopes via Arc.
162 #[allow(dead_code)]
163 pub(super) next_task_id: Arc<AtomicU64>,
164 /// Shared live-task count across every forked worker. Forks clone
165 /// the `Arc`, so nested spawns see the same total: the cap is
166 /// global, not per scope. Incremented atomically at allocation,
167 /// released by the worker thread's slot guard on exit.
168 pub(super) live_tasks: Arc<AtomicU64>,
169 /// Whether we're inside an ASYNC block thread. When true, `handlers::run()`
170 /// spawns in background mode so the handle can be registered for cancellation.
171 pub(super) inside_async: bool,
172 /// Step-indexed keeper expiry for one `ASYNC` worker. Each guard pins a
173 /// pipe the worker produces to, bridging the spawn-to-first-attach
174 /// window and every transient gap between producer steps. Guards keyed
175 /// to step `k` drop when the worker completes its top-level step `k`
176 /// (matched by slice identity, so nested bodies never discharge them);
177 /// leftovers drop with the worker thread. Always `None` outside
178 /// workers; `fork` never inherits it.
179 pub(super) keeper_expiry: Option<KeeperExpiry>,
180 /// Whether `handlers::run()` must spawn in background mode so the handle
181 /// registers in `active_process` for cancellation. Set while a `TIMEOUT`
182 /// body executes on the current thread so the deadline watcher can kill
183 /// a blocking foreground process. Unlike `inside_async`, this does not
184 /// affect end-of-pipeline named-task reaping.
185 pub(super) cancellable: bool,
186 /// Scope floor for the end-of-body reaper: task ids at or above this
187 /// joined at scope end, older ones ignored. Set only by `TIMEOUT`
188 /// (snapshot of the task-id counter at scope entry), so a worker the
189 /// body leaves running gets up to the deadline while pre-existing
190 /// tasks keep running past the scope. `None` joins everything: the
191 /// pipeline top and every other scope.
192 pub(super) reap_floor: Option<u64>,
193 /// The single function registry: DSL `FUNC` definitions, builtins, and
194 /// host extensions. Script entries scope lexically through the
195 /// registry's own frames (managed by `push_scope`/`pop_scope`);
196 /// native entries persist. Shared across `fork()` via clone.
197 pub(super) functions: FunctionRegistry<P>,
198 /// Entry script file (#115), when the run started from a file: base
199 /// for top-level relative `IMPORT` paths. `None` for stdin and inline
200 /// runs (imports resolve against the workspace root).
201 pub(super) entry_file: Option<GuardedPath>,
202 /// Active file-import chain (#115), innermost last: cycle detection
203 /// names the full chain, and the importer dir is the top's parent.
204 pub(super) import_stack: Vec<GuardedPath>,
205 /// One file module per resolved import path (#115): parse once,
206 /// validate once, initialize once. Every alias is a view onto the
207 /// same record and the same shared state.
208 pub(super) modules: HashMap<String, ModuleRecord>,
209 pub(super) validated_modules: HashSet<String>,
210 /// Files the static closure pass already proved (#115): entry plus
211 /// every transitively imported file, checked with full nested
212 /// knowledge. Runtime re-validation of the same registry-cached
213 /// body would only false-positive on nested calls, so imports skip
214 /// the single-file re-proof when their key is present. Unseen
215 /// files (direct API use, no static pass) still validate here.
216 /// Active module context (#115), innermost last: `Some(key)` while
217 /// module-owned code runs (init body or module-owned `FUNC`),
218 /// `None` past an entry-function boundary (entry `FUNC`s stay
219 /// params-only and never see module state). Reads and mutations
220 /// consult the topmost `Some` store after lexical frames miss.
221 pub(super) module_stack: Vec<Option<String>>,
222 /// Executed file-import alias targets per unit (#115): alias to
223 /// defining file keys for imports that actually ran, keyed by the
224 /// importing unit (`"entry"` for entry steps, the file key for
225 /// module bodies). Unit-top layer only: unit-top-level imports
226 /// land here (anything executed without a live lexical scope);
227 /// function-local imports land on the innermost
228 /// [`ExecState::call_alias_frames`] entry instead, and block
229 /// imports on the innermost [`ExecState::scope_alias_frames`]
230 /// entry, so neither leaks past its boundary. Mirrors the static
231 /// per-unit `outbound_alias_targets` for the runtime placeholder
232 /// gate, so file-backed `EXPAND` templates (invisible to static
233 /// checking) classify known aliases identically: host harvests
234 /// record an explicit host branch, and module bodies resolve
235 /// against their own file's imports, never the importer's.
236 pub(super) executed_alias_targets: HashMap<String, super::native::AliasTargets>,
237 /// Block-scoped import frames, innermost last: one entry per
238 /// live lexical scope that executed an `IMPORT`, tagged with the
239 /// scope-stack depth at creation and the importing unit. Reads
240 /// merge every live frame for their unit (outer-to-inner) over
241 /// the unit-top map, so an `IMPORT` inside `IF`/`FOR`/`WHILE`/
242 /// `SWITCH`/`ISOLATED` resolves within its block and unwinds on
243 /// exit. `pop_scope` drops frames deeper than the surviving
244 /// stack; `fork` flattens live frames into the child's unit-top
245 /// map (the child manages its own scopes). Function bodies keep
246 /// using [`ExecState::call_alias_frames`], checked first.
247 pub(super) scope_alias_frames: Vec<ScopeAliasFrame>,
248 /// Active function-call import frames: one entry per live
249 /// [`call_func_value`](super::handlers::call_func_value) invocation,
250 /// holding that invocation's own local imports. The innermost frame
251 /// for the active unit shadows the unit-top map exactly like the
252 /// static per-function overlays shadow the unit imports; popping on
253 /// return (via an RAII guard) restores the caller's view. Each
254 /// frame records the scope-stack depth at call entry: imports
255 /// execute into the call frame only at that depth (the body's own
256 /// top level), while deeper block scopes record into
257 /// [`ExecState::scope_alias_frames`] so they unwind on block exit;
258 /// reads merge only scope frames deeper than the innermost live
259 /// call frame, so a caller block's imports never leak into a
260 /// same-unit callee.
261 pub(super) call_alias_frames: Vec<CallAliasFrame>,
262 /// Frame-2..N floor (#322): `functions.scopes` index at which the
263 /// current module call (or init) body starts. Nested-frame lookup
264 /// walks down to this floor and no further, so caller frames from
265 /// other units are unreachable by construction. Pushed alongside
266 /// `call_alias_frames` (and init scopes) on every path. Entry
267 /// calls walk all live frames: with inits popped, every live
268 /// frame is entry-owned by construction.
269 pub(super) func_floors: Vec<usize>,
270 /// Bare-harvest visibility per importing unit (#322): (unit, base)
271 /// to defining file key. Harvests persist through this map past
272 /// init pops, never through scope frames.
273 pub(super) harvest_map: HashMap<(String, String), String>,
274 /// Parse-time module table (#115): imported files parse with the same
275 /// table as the entry script.
276 pub(super) module_table: oxdock_parser::ModuleTable,
277 /// Current nested function-call depth on this thread. Enforced against
278 /// `MAX_CALL_DEPTH`; cloned (not reset) by `fork()` so async children
279 /// inherit the caller's depth budget.
280 pub(super) call_depth: usize,
281 /// Executed `INHERIT_ENV` keys per live module init, innermost last.
282 /// Pushed empty before the init body runs and popped after, so
283 /// `inherit_env` records keys as they actually execute under their
284 /// guards instead of re-scanning steps against final envs.
285 pub(super) init_inherit_stack: Vec<Vec<String>>,
286 /// Scope-stack depths that are module-init top levels, innermost
287 /// last: `ensure_module_init` (`super::import`) pushes its isolation
288 /// scope here so `record_executed_alias` can tell a module's own
289 /// top level (unit-top, like the entry's) from a lexical block
290 /// (scope frame, unwinds on exit). Nested inits nest strictly,
291 /// so depths never repeat while live; `fork` clears it (the
292 /// child's scopes restart empty).
293 pub(super) init_scope_depths: Vec<usize>,
294 /// Identity of the task this state executes (`0` = root flow).
295 /// Stamped onto pipe handles minted here and compared by the promotion
296 /// check: only the declaring task may promote its own pipes.
297 pub(super) task_id: u64,
298 /// Declared `--to-host` transfers recorded strictly at execution time:
299 /// each executed flagged `COPY` appends its evaluated
300 /// `(guest_src, host_dst)` pair. The guest serve loop packs exactly
301 /// these entries, so dead branches contribute nothing and dynamic
302 /// paths (`$var`, `{{ ... }}`) resolve normally. Shared with the sink
303 /// in [`ExecIo`] when staged.
304 pub(super) push_manifest: Vec<(String, String)>,
305 pub(super) _marker: PhantomData<P>,
306}
307
308pub(super) struct ScopeSnapshot {
309 pub(super) cwd: GuardedPath,
310 pub(super) selection: WorkspaceSelection,
311 pub(super) envs: Arc<HashMap<String, String>>,
312}
313
314/// One live block's imports: the scope-stack depth at creation plus
315/// the importing unit's alias targets. Single owner for the
316/// scope-frame shape; `record_executed_alias` writes it,
317/// `unit_alias_targets` merges it, `pop_scope` reaps it.
318#[derive(Clone, Default)]
319pub(super) struct ScopeAliasFrame {
320 pub(super) depth: usize,
321 pub(super) unit: String,
322 pub(super) targets: super::native::AliasTargets,
323}
324
325/// One live function call's imports: the importing unit, the
326/// scope-stack depth at call entry (right after the call scope
327/// pushes), and the call's own local imports. The depth tells
328/// `record_executed_alias` apart the body's own top level (records
329/// here) from nested blocks (record into [`ScopeAliasFrame`]), and
330/// tells `unit_alias_targets` which scope frames belong to this
331/// invocation (deeper ones) versus caller context. A forked child
332/// restarts its scope stack at zero, so a cloned frame whose depth
333/// exceeds the child's stack is stale: the child still merges its
334/// targets (inherited visibility) but applies no depth floor from
335/// it. Single owner for the call-frame shape.
336#[derive(Clone, Default)]
337pub(super) struct CallAliasFrame {
338 pub(super) unit: String,
339 pub(super) depth: usize,
340 pub(super) targets: super::native::AliasTargets,
341}
342
343/// One parsed file module (#115), keyed by resolved display path: parse
344/// once, validate once, initialize once. `init` is `None` until the
345/// first import executes the body; every alias is a view onto the
346/// same record and the same shared state.
347#[derive(Clone, Default)]
348pub(super) struct ModuleRecord {
349 pub(super) steps: Vec<Step>,
350 /// Single-file `EXPORT` metadata: `EXPORT` func names, `EXPORT TYPE`
351 /// names, and `EXPORT CONST` names, each in source order. One struct
352 /// (never three parallel lists) so the MCP server never confuses a
353 /// type for a tool, and only `CONST` names are readable through
354 /// `$ALIAS::NAME`.
355 pub(super) exports: oxdock_parser::Exports,
356 pub(super) init: Option<ModuleInit>,
357 /// Frame-1 file scope (#322): every top-level `FUNC` of the file
358 /// (exported, harvested, and private alike), indexed once at load
359 /// so calls resolve without scanning steps on every invocation.
360 /// Single owner for the defining-file view; the runtime walk and
361 /// the static home index read the same shape.
362 pub(super) top_funcs: HashMap<String, Vec<RawFuncDef>>,
363}
364
365impl ModuleInit {
366 /// Fresh entry-unit init store (#4): the session seed plus the
367 /// entry top-level's own `ENV` contributions, tracked as they
368 /// execute. Entry `FUNC` calls reset to this map (never caller
369 /// env), mirroring how module calls reset to `ModuleInit::envs`.
370 /// `vars`/`const_vars` hold the entry prelude `CONST`s seeded
371 /// into every entry call; `inherit_names` re-reads from the
372 /// engine per call. Single owner for the entry record shape, so
373 /// `new_state` and the test constructors can never drift.
374 pub(super) fn entry_seed(envs: HashMap<String, String>, cwd: GuardedPath) -> Self {
375 Self {
376 vars: HashMap::new(),
377 const_vars: HashSet::new(),
378 return_value: Value::string(String::new()),
379 envs,
380 inherit_names: Vec::new(),
381 selection: WorkspaceSelection::Snapshot,
382 cwd,
383 }
384 }
385}
386
387impl ModuleRecord {
388 /// Fresh entry-unit record (#4): empty steps/top-funcs plus the
389 /// seeded init store above. Single owner for the entry shape, so
390 /// every constructor seeds the same fields.
391 pub(super) fn entry_record(envs: HashMap<String, String>, cwd: GuardedPath) -> Self {
392 Self {
393 steps: Vec::new(),
394 exports: oxdock_parser::Exports::default(),
395 init: Some(ModuleInit::entry_seed(envs, cwd)),
396 top_funcs: HashMap::new(),
397 }
398 }
399}
400
401/// One top-level `FUNC` definition as parsed: the file frame of the
402/// unit scope stack (#322). Params and return stay in source spelling
403/// until a call resolves tags. Guards ride along and are evaluated
404/// with the live env at use time, mirroring the previous per-call
405/// step scan exactly (init-gated defs behave as before). `jail` is
406/// sealed at execution: the first top-level execution of this
407/// definition pins the live workspace selection and cwd, so later
408/// calls restore the definition site, never caller ambient. `None`
409/// for never-executed defs (forward refs, skipped harvests), which
410/// fall back to the defining file default at call time.
411#[derive(Clone, Debug, Default)]
412pub(super) struct RawFuncDef {
413 pub(super) params: Vec<(String, String, bool)>,
414 pub(super) return_spelling: String,
415 pub(super) is_async: bool,
416 pub(super) body: Vec<Step>,
417 pub(super) guard: Option<GuardExpr>,
418 pub(super) jail: Option<(WorkspaceSelection, GuardedPath)>,
419}
420
421/// Initialized module state (#115): the shared globals every alias of
422/// one file observes. `vars` holds the module body's top-level `LET`
423/// bindings, drained from the init frame when the first import runs;
424/// module-owned `FUNC`s resolve names against `vars` after lexical
425/// frames miss, so one file's functions share one global state instead
426/// of each alias getting a private copy. `return_value` caches the
427/// init body's `RETURN`, so repeated imports bind the same value.
428#[derive(Clone)]
429pub(super) struct ModuleInit {
430 pub(super) vars: HashMap<String, (TypeTag, Value)>,
431 /// Top-level `CONST` names drained with `vars`: rebinding,
432 /// `$var = <expr>` reassignment, and `LIST_APPEND` against these fail;
433 /// rebuilds fail on the value-level frozen flag.
434 pub(super) const_vars: HashSet<String>,
435 pub(super) return_value: Value,
436 /// Script env the module's functions execute with (#115): the
437 /// session seed plus the init body's own `ENV` contributions
438 /// (captured as a delta against the pre-init map, so
439 /// caller-established values stay out). `INHERIT_ENV` names are
440 /// re-read from the host at each call (see `inherit_names`),
441 /// since a re-inherit of an already-present value leaves no delta
442 /// yet must still admit the name.
443 pub(super) envs: HashMap<String, String>,
444 /// Top-level `INHERIT_ENV` names of the module file, re-established
445 /// from the host on every module-owned call. A module never
446 /// inherits its caller's environment; each file declares what it
447 /// reads, and the values flow from the host (or literals) at
448 /// init/call time.
449 pub(super) inherit_names: Vec<String>,
450 /// The module top-level jail (#322): the workspace selection and
451 /// cwd as the init body left them. Module-owned `FUNC`s restore
452 /// this on entry (unless the body overrides it), so a callee
453 /// executes in its defining file context no matter which
454 /// workspace the caller sits in. Captured before the init scope
455 /// pops; the pop restores the importer afterwards.
456 pub(super) selection: WorkspaceSelection,
457 pub(super) cwd: GuardedPath,
458}
459
460/// One anonymous background worker: the thread-join handle plus the
461/// task id drawn for the worker at spawn. Only `ThreadJoinHandle`s are
462/// ever pushed (a worker's own `RUN` steps wait inline); the id lets a
463/// `TIMEOUT` scope-end reaper join only the workers its own body
464/// spawned, leaving pre-existing ones alone.
465pub(super) struct BgChild {
466 pub(super) handle: Box<dyn BackgroundHandle>,
467 pub(super) task_id: u64,
468}
469
470/// Task completion record, written once by the first observer of a
471/// finished task and read by later polls. Never consumed: polls and a
472/// subsequent `AWAIT` all read the same record.
473#[derive(Clone)]
474pub(super) struct TaskCompletion {
475 pub(super) ok: bool,
476 pub(super) exit_code: i64,
477 pub(super) result: Option<Value>,
478 pub(super) error: String,
479}
480
481/// Point-in-time task view for `TASK_POLL`. Owned strings, bounded by
482/// the tail caps.
483pub(super) struct TaskObservation {
484 pub(super) running: bool,
485 pub(super) ok: bool,
486 pub(super) exit_code: i64,
487 pub(super) result: Option<Value>,
488 pub(super) error: String,
489}
490
491/// Bounded per-stream accumulator for one background task. Same
492/// drop-the-head discipline as the foreground tail rings.
493pub(super) struct TaskTails {
494 out: Vec<u8>,
495 err: Vec<u8>,
496 total_out: u64,
497 total_err: u64,
498}
499
500impl TaskTails {
501 pub(super) fn new() -> Self {
502 Self {
503 out: Vec::new(),
504 err: Vec::new(),
505 total_out: 0,
506 total_err: 0,
507 }
508 }
509
510 pub(super) fn push(&mut self, stream: TeeStream, bytes: &[u8]) {
511 let (buf, total) = match stream {
512 TeeStream::Stdout => (&mut self.out, &mut self.total_out),
513 TeeStream::Stderr => (&mut self.err, &mut self.total_err),
514 };
515 *total += bytes.len() as u64;
516 buf.extend_from_slice(bytes);
517 let excess = buf.len().saturating_sub(TASK_TAIL_CAP);
518 if excess > 0 {
519 buf.drain(..excess);
520 }
521 }
522
523 pub(super) fn snapshot(&self) -> (String, String, u64) {
524 let dropped = self.total_out.saturating_sub(self.out.len() as u64)
525 + self.total_err.saturating_sub(self.err.len() as u64);
526 (
527 String::from_utf8_lossy(&self.out).into_owned(),
528 String::from_utf8_lossy(&self.err).into_owned(),
529 dropped,
530 )
531 }
532}
533
534/// Lifecycle phase of a named background task (`LET $var: HANDLE<T> = ASYNC ...`).
535/// `Running` and `Awaiting` both hold the live handle inside the entry;
536/// `Cancelled` and `Completed` are terminal tombstones with no handle.
537pub(super) enum TaskPhase {
538 Running,
539 Awaiting,
540 Cancelled,
541 Completed,
542}
543
544pub(super) struct TaskEntryState {
545 pub(super) phase: TaskPhase,
546 pub(super) handle: Option<Box<dyn BackgroundHandle>>,
547 /// True once the handle has been consumed and its thread joined
548 /// (`kill()` for cancellations, `try_wait`-reap for natural completion).
549 /// Threads observing `Cancelled` must wait on `done` until `reaped`
550 /// before resuming, so no caller outruns OS process teardown.
551 pub(super) reaped: bool,
552 /// Explicit result of a background task, published by `RETURN` (block
553 /// bodies) or the function call itself (single-`CALL` bodies). Set
554 /// under the entry lock before `done.notify_all()`; read by
555 /// `LET $o: TYPE = AWAIT $t`. `None` for tasks that have not finished
556 /// or have fallen off the end. Task stdout is never captured: it
557 /// streams live to the shared parent writer.
558 pub(super) return_value: Option<Value>,
559 /// Completion record written once by the first observer of a
560 /// finished task (`TASK_POLL` or the teardown path). Read by later
561 /// polls and post-mortem rendering; never consumed.
562 pub(super) completion: Option<TaskCompletion>,
563 /// Whether this task's body can publish a value: single-`CALL` bodies
564 /// always can; block bodies can iff they contain a `RETURN` in their
565 /// own scope. A task that can return but falls off the end fails its
566 /// capture loudly; a task that cannot return yields `INT` 0.
567 pub(super) returns_value: bool,
568}
569
570/// Synchronized named-task entry shared by every scope that can observe the
571/// task (`AWAIT`, `CANCEL`, `TASK_POLL`, end-poll reaping). Exactly one
572/// thread ever takes the handle and performs teardown; all other
573/// observers rendezvous on `done`/`reaped`.
574pub(super) struct TaskEntry {
575 pub(super) state: Mutex<TaskEntryState>,
576 pub(super) done: Condvar,
577 /// Bounded live output. Fed by the worker tee, drained by
578 /// `TASK_POLL` without consuming, dropped with the entry.
579 pub(super) tails: Arc<Mutex<TaskTails>>,
580}
581
582impl TaskEntry {
583 /// Whether this entry occupies a live slot: awaiting a join, or
584 /// running with an unfinished thread. Terminal phases and reaped
585 /// joins are done. Un-awaited finished tasks report done via
586 /// `try_wait`, so ghosts never hold a slot. Never blocks: a
587 /// still-running thread reports `Ok(None)` without joining.
588 pub(super) fn is_live(&self) -> bool {
589 let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
590 match guard.phase {
591 TaskPhase::Running => match guard.handle.as_mut() {
592 Some(handle) => matches!(handle.try_wait(), Ok(None)),
593 None => false,
594 },
595 TaskPhase::Awaiting => true,
596 TaskPhase::Completed | TaskPhase::Cancelled => false,
597 }
598 }
599
600 pub(super) fn new(
601 handle: Box<dyn BackgroundHandle>,
602 returns_value: bool,
603 tails: Arc<Mutex<TaskTails>>,
604 ) -> Self {
605 Self {
606 state: Mutex::new(TaskEntryState {
607 phase: TaskPhase::Running,
608 handle: Some(handle),
609 reaped: false,
610 return_value: None,
611 completion: None,
612 returns_value,
613 }),
614 done: Condvar::new(),
615 tails,
616 }
617 }
618
619 /// Non-destructive snapshot of live tails plus dropped head count.
620 /// Never blocks execution: a poisoned lock reads through.
621 pub(super) fn snapshot_tails(&self) -> (String, String, u64) {
622 self.tails
623 .lock()
624 .map(|tails| tails.snapshot())
625 .unwrap_or_else(|e| e.into_inner().snapshot())
626 }
627
628 /// Observe completion without consuming the task. Never transitions
629 /// phase, never takes the handle, never notifies: a later `AWAIT`
630 /// still joins normally. First observation of a finished task
631 /// records the completion for later polls; the `try_wait` reap it
632 /// performs is the same one `AWAIT` would do, and the cached status
633 /// keeps that path consistent.
634 pub(super) fn observe_completion(&self) -> TaskObservation {
635 let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
636 if let Some(done) = guard.completion.clone() {
637 return TaskObservation {
638 running: false,
639 ok: done.ok,
640 exit_code: done.exit_code,
641 result: done.result,
642 error: done.error,
643 };
644 }
645 if !matches!(guard.phase, TaskPhase::Running) {
646 return TaskObservation {
647 running: false,
648 ok: false,
649 exit_code: -1,
650 result: None,
651 error: "task handle was not found or has already been awaited".to_string(),
652 };
653 }
654 match guard.handle.as_mut() {
655 None => TaskObservation {
656 running: true,
657 ok: true,
658 exit_code: -1,
659 result: None,
660 error: String::new(),
661 },
662 Some(handle) => match handle.try_wait() {
663 Ok(Some(status)) => {
664 let completion = TaskCompletion {
665 ok: status.success(),
666 exit_code: status.code().map(i64::from).unwrap_or(-1),
667 result: guard.return_value.clone(),
668 error: if status.success() {
669 String::new()
670 } else {
671 format!("task exited with status {status}")
672 },
673 };
674 guard.completion = Some(TaskCompletion {
675 ok: completion.ok,
676 exit_code: completion.exit_code,
677 result: completion.result.clone(),
678 error: completion.error.clone(),
679 });
680 TaskObservation {
681 running: false,
682 ok: completion.ok,
683 exit_code: completion.exit_code,
684 result: completion.result,
685 error: completion.error,
686 }
687 }
688 Ok(None) => TaskObservation {
689 running: true,
690 ok: true,
691 exit_code: -1,
692 result: None,
693 error: String::new(),
694 },
695 Err(err) => {
696 let completion = TaskCompletion {
697 ok: false,
698 exit_code: exit_code_of(&err).unwrap_or(1),
699 result: None,
700 error: format!("{err:#}"),
701 };
702 guard.completion = Some(TaskCompletion {
703 ok: completion.ok,
704 exit_code: completion.exit_code,
705 result: completion.result.clone(),
706 error: completion.error.clone(),
707 });
708 TaskObservation {
709 running: false,
710 ok: completion.ok,
711 exit_code: completion.exit_code,
712 result: completion.result,
713 error: completion.error,
714 }
715 }
716 },
717 }
718 }
719
720 /// Block until the teardown owner has consumed the handle and joined
721 /// the task thread. Lock-free for callers except the wait itself.
722 pub(super) fn wait_reaped(&self) {
723 let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
724 while !guard.reaped {
725 guard = self.done.wait(guard).unwrap_or_else(|e| e.into_inner());
726 }
727 }
728
729 /// Mark teardown complete and wake every rendezvous waiter.
730 pub(super) fn finish_teardown(&self) {
731 {
732 let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
733 guard.handle = None;
734 guard.reaped = true;
735 }
736 self.done.notify_all();
737 }
738}
739
740/// Step-indexed keeper expiry for one `ASYNC` worker thread. Guards are
741/// keyed by the top-level body index of the final producer step for each
742/// pipe: dropping the guards for step `k` once it completes keeps the
743/// pipe open across every transient gap between producers, then releases
744/// it so later consumer steps in the same task observe EOF.
745///
746/// Slice identity (`body_addr`/`body_len`) gates discharge: nested bodies
747/// (`FOR`/`IF`/`TIMEOUT`/inner `ASYNC`) execute through the same stepping
748/// code with different slices and must never consume the worker's
749/// top-level map.
750pub(super) struct KeeperExpiry {
751 body_addr: usize,
752 body_len: usize,
753 map: HashMap<usize, Vec<KeeperGuard>>,
754}
755
756impl KeeperExpiry {
757 pub(super) fn new(steps: &[Step], map: HashMap<usize, Vec<KeeperGuard>>) -> Self {
758 Self {
759 body_addr: steps.as_ptr() as usize,
760 body_len: steps.len(),
761 map,
762 }
763 }
764
765 pub(super) fn matches(&self, steps: &[Step]) -> bool {
766 self.body_addr == steps.as_ptr() as usize && self.body_len == steps.len()
767 }
768
769 /// Drop the guards expiring at top-level step `idx`. Returns true when
770 /// the map is drained and the expiry itself can be cleared.
771 pub(super) fn expire_step(&mut self, steps: &[Step], idx: usize) -> bool {
772 if self.matches(steps) {
773 drop(self.map.remove(&idx));
774 }
775 self.map.is_empty()
776 }
777}
778
779/// Defining-file call context (#322): (envs, inherit names,
780/// selection, cwd). One alias shared by the resolver and every call
781/// site, never a restated tuple.
782pub(super) type FileCallCtx = (
783 HashMap<String, String>,
784 Vec<String>,
785 WorkspaceSelection,
786 GuardedPath,
787);
788
789impl<P: ProcessManager> ExecState<P> {
790 /// Script-map environment lookup for DSL evaluation (`is_exec_name`,
791 /// `Expr::Env`, expansions): exact hit first, case-insensitive
792 /// fallback on Windows so `{{ env:Path }}` resolves the seeded
793 /// `PATH`. The map is seeded at init, so no fallback layer exists.
794 pub(super) fn get_env(&self, key: &str) -> Option<&str> {
795 if let Some(v) = self.envs.get(key) {
796 return Some(v.as_str());
797 }
798 #[allow(clippy::disallowed_macros)]
799 if cfg!(windows) {
800 return self
801 .envs
802 .iter()
803 .find(|(k, _)| oxdock_process::names_eq(k, key))
804 .map(|(_, v)| v.as_str());
805 }
806 None
807 }
808
809 pub(super) fn command_ctx(&self) -> Result<CommandContext> {
810 // Resolve the working directory through the snapshot choke point: a
811 // snapshot-rooted cwd materializes here (so `RUN` executes against a
812 // real directory) while a local cwd resolves purely lexically with
813 // zero I/O. The seeded scratch materializes alongside: `HOME` and
814 // `TMPDIR` point at it, so children writing temp or profile data
815 // must observe real directories, never lexical candidates.
816 let cwd = self.fs.resolve_write(&self.cwd, ".")?;
817 self.cargo_scratch.ensure_materialized()?;
818 Ok(CommandContext::new(
819 &cwd.into(),
820 Arc::clone(&self.envs),
821 &self.cargo_scratch,
822 self.fs.root(),
823 self.fs.build_context(),
824 ))
825 }
826
827 /// Draw the next task id, enforcing the global live-task cap and
828 /// sweeping retained finished entries. Every ASYNC allocation path
829 /// calls this, so named and anonymous tasks share one choke point.
830 /// The live count is atomic and shared across all forked workers,
831 /// so nested spawns cannot bypass the cap that a per-state scan
832 /// would miss. Refusal is backpressure: a full host fails the spawn
833 /// loudly instead of wedging.
834 pub(super) fn alloc_task_id(&mut self) -> anyhow::Result<u64> {
835 // Purge cleanly-finished anonymous children first: their threads
836 // are gone and a zero exit has no reporter, so retaining them
837 // only grows the vec. Failed handles stay for the end-pipeline
838 // reaper, which owns their error reporting.
839 self.bg_children
840 .retain_mut(|child| match child.handle.try_wait() {
841 Ok(None) => true,
842 Ok(Some(status)) => !status.success(),
843 Err(_) => true,
844 });
845 self.live_tasks
846 .try_update(Ordering::SeqCst, Ordering::SeqCst, |n| {
847 (n < MAX_RUNNING_TASKS as u64).then_some(n + 1)
848 })
849 .map_err(|_| {
850 anyhow::anyhow!(
851 "concurrency limit exceeded: maximum of {MAX_RUNNING_TASKS} running background tasks allowed"
852 )
853 })?;
854 let id = self.next_task_id.fetch_add(1, Ordering::SeqCst);
855 self.sweep_finished_tasks();
856 Ok(id)
857 }
858
859 /// Drop finished entries past `MAX_RETAINED_FINISHED`, oldest
860 /// first. Finished means a terminal phase or a completed join;
861 /// `Awaiting` entries always survive (a waiter is rendezvousing)
862 /// and running entries are never touched. Evicted ids read as
863 /// unknown/already-awaited afterwards, like an awaited task.
864 fn sweep_finished_tasks(&self) {
865 let mut finished: Vec<u64> = Vec::new();
866 {
867 let named = self.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
868 for (id, entry) in named.iter() {
869 // `is_live` already exempts awaiting entries: a waiter
870 // is rendezvousing on them.
871 if !entry.is_live() {
872 finished.push(*id);
873 }
874 }
875 }
876 if finished.len() <= MAX_RETAINED_FINISHED {
877 return;
878 }
879 finished.sort_unstable();
880 let mut named = self.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
881 for id in finished.iter().take(finished.len() - MAX_RETAINED_FINISHED) {
882 named.remove(id);
883 }
884 }
885
886 /// Fork the execution state for a child thread. The child gets:
887 /// - A cloned filesystem handle (shared snapshot backing, independent root selection)
888 /// - Cloned envs, cwd, cargo scratch name, var_scopes, const_scopes
889 /// - Fresh bg_children, scope_stack (empty -- child manages its own)
890 /// - Block imports flattened into the cloned unit-top map (the live
891 /// frames stay with the parent's scopes, so the child observes
892 /// what the parent saw at spawn without inheriting unwindable frames)
893 /// - Shared assert_windows, assert_windows_stderr, exact_stdout (Arc clones)
894 /// - Cloned io configuration
895 /// - Independent cancel_token, active_process (child manages its own)
896 /// - Shared named_tasks and next_task_id (via Arc clone)
897 #[allow(dead_code)]
898 pub(super) fn fork(&self) -> Self {
899 let mut executed_alias_targets = self.executed_alias_targets.clone();
900 for frame in &self.scope_alias_frames {
901 for (alias, targets) in &frame.targets {
902 executed_alias_targets
903 .entry(frame.unit.clone())
904 .or_default()
905 .entry(alias.clone())
906 .or_default()
907 .extend(targets.iter().cloned());
908 }
909 }
910 Self {
911 fs: self.fs.clone_box(),
912 cargo_scratch: self.cargo_scratch.clone(),
913 seed: Arc::clone(&self.seed),
914 cwd: self.cwd.clone(),
915 envs: Arc::clone(&self.envs),
916 bg_children: Vec::new(),
917 scope_stack: Vec::new(),
918 isolated_stack: self.isolated_stack.clone(),
919 io: self.io.clone(),
920 assert_windows: Arc::clone(&self.assert_windows),
921 assert_windows_stderr: Arc::clone(&self.assert_windows_stderr),
922 exact_stdout: Arc::clone(&self.exact_stdout),
923 var_scopes: self.var_scopes.clone(),
924 const_scopes: self.const_scopes.clone(),
925 cancel_token: Arc::new(AtomicBool::new(false)),
926 // Fresh cancellation, inherited telemetry: the fork's
927 // workers still attribute to the originating run.
928 cancel_hub: Arc::new(CancelHub::with_counter(self.cancel_hub.worker_counter())),
929 active_process: Arc::new(Mutex::new(None)),
930 named_tasks: Arc::clone(&self.named_tasks),
931 next_task_id: Arc::clone(&self.next_task_id),
932 // Shared live count, never reset: nested workers report into
933 // the same cap their spawner was admitted under.
934 live_tasks: Arc::clone(&self.live_tasks),
935 inside_async: true,
936 keeper_expiry: None,
937 cancellable: self.cancellable,
938 reap_floor: self.reap_floor,
939 functions: self.functions.clone(),
940 entry_file: self.entry_file.clone(),
941 import_stack: self.import_stack.clone(),
942 modules: self.modules.clone(),
943 validated_modules: self.validated_modules.clone(),
944 module_stack: self.module_stack.clone(),
945 executed_alias_targets,
946 call_alias_frames: self.call_alias_frames.clone(),
947 scope_alias_frames: Vec::new(),
948 init_scope_depths: Vec::new(),
949 func_floors: self.func_floors.clone(),
950 harvest_map: self.harvest_map.clone(),
951 module_table: self.module_table.clone(),
952 types: self.types.clone(),
953 record_schemas: self.record_schemas.clone(),
954 module_states: self.module_states.clone(),
955 type_aliases: self.type_aliases.clone(),
956 type_env_digest: self.type_env_digest,
957 call_depth: self.call_depth,
958 init_inherit_stack: self.init_inherit_stack.clone(),
959 task_id: self.task_id,
960 // Forks start with an empty manifest: async children record
961 // their own executions; the guest packs the root manifest.
962 push_manifest: Vec::new(),
963 _marker: PhantomData,
964 }
965 }
966
967 /// Whether `pipe` may promote to an OS kernel pair on behalf of
968 /// `task_id`: only when it was declared by that same task and no
969 /// spawned child can observe it. Anything else stays script-backed, so
970 /// concurrent tasks can never disagree about EOF propagation.
971 /// Spawning tasks pass their worker id (not the spawner's): promotion
972 /// is judged from the worker's perspective, since it is the worker's
973 /// bindings that will hold raw descriptors.
974 pub(super) fn can_promote_in_task(pipe: &oxdock_pipe::PipeHandle, task_id: u64) -> bool {
975 pipe.declaring_task() == task_id && !pipe.has_escaped()
976 }
977
978 /// Whether `pipe` may promote on the current thread (main flow and
979 /// inline resolves).
980 pub(super) fn can_promote_to_os(&self, pipe: &oxdock_pipe::PipeHandle) -> bool {
981 Self::can_promote_in_task(pipe, self.task_id)
982 }
983
984 /// Mark every pipe visible in scope as shared-with-a-child. Called
985 /// synchronously on the spawner before a worker thread starts: forking
986 /// copies the whole environment, so every visible pipe is capturable
987 /// whether or not the child body names it. Over-marking only costs
988 /// zero-copy opportunities, never correctness.
989 pub(super) fn mark_captured_pipes_escaped(&self) {
990 for scope in self.var_scopes.iter() {
991 for (_, value) in scope.values() {
992 mark_value_pipes_escaped(value);
993 }
994 }
995 for record in self.modules.values() {
996 if let Some(init) = record.init.as_ref() {
997 for entry in init.vars.values() {
998 mark_value_pipes_escaped(&entry.1);
999 }
1000 }
1001 }
1002 }
1003
1004 pub(super) fn push_var_scope(&mut self) {
1005 self.var_scopes.push(HashMap::new());
1006 self.const_scopes.push(HashSet::new());
1007 }
1008
1009 pub(super) fn pop_var_scope(&mut self) {
1010 self.var_scopes.pop();
1011 self.const_scopes.pop();
1012 }
1013
1014 /// Reset module-owned env (#115, #322): env to the module init
1015 /// stored map. Workspace and cwd are reset separately by the
1016 /// caller to the snapshot jail, so a module never observes the
1017 /// importer workspace. The surrounding `push_scope` restores the
1018 /// caller afterwards.
1019 pub(super) fn reset_module_env(&mut self, envs: HashMap<String, String>) {
1020 self.envs = Arc::new(envs);
1021 }
1022
1023 /// Entry top-level tracking (#322 follow-up): true only for the
1024 /// entry prelude itself, never inside any call, module, or
1025 /// lexical block. Blocks (`ISOLATED`, `IF`, `FOR`, `WHILE`,
1026 /// `SWITCH`, `WITH_IO`) push `scope_stack` so their env unwinds
1027 /// on exit; capturing those writes would leak block-scoped and
1028 /// isolated secrets into every later entry call. Guard-gated
1029 /// top-level statements execute without pushing a scope, so
1030 /// conditional configuration still seeds the prelude. Caller
1031 /// env must never flow into the entry prelude store: `INHERIT_ENV`
1032 /// inherits from the engine, never another script, ever.
1033 pub(super) fn is_entry_top_level(&self) -> bool {
1034 self.call_depth == 0 && self.module_stack.is_empty() && self.scope_stack.is_empty()
1035 }
1036
1037 /// Defining-file call context (#322): the single owner resolving
1038 /// what a `FUNC` body restores. The definition-site jail wins
1039 /// when the definition sealed one; otherwise the defining file
1040 /// fallback applies (module init jail, entry snapshot default).
1041 /// Env always resolves file-level (module init delta, entry
1042 /// prelude) with `INHERIT_ENV` re-read from the engine, never
1043 /// caller ambient. One lookup for every file, entry included:
1044 /// the entry record lives under the sentinel, so callers never
1045 /// restate a `Some`/`None` branch. Spelled once as [`FileCallCtx`].
1046 pub(super) fn callee_file_ctx(
1047 &self,
1048 module_key: Option<&str>,
1049 def_jail: Option<(WorkspaceSelection, GuardedPath)>,
1050 ) -> Option<FileCallCtx> {
1051 let unit = super::import::unit_key(module_key);
1052 if let Some((selection, cwd)) = def_jail {
1053 let (envs, inherit_names) = self.modules.get(unit).and_then(|record| {
1054 record
1055 .init
1056 .as_ref()
1057 .map(|init| (init.envs.clone(), init.inherit_names.clone()))
1058 })?;
1059 return Some((envs, inherit_names, selection, cwd));
1060 }
1061 self.modules.get(unit).and_then(|record| {
1062 record.init.as_ref().map(|init| {
1063 (
1064 init.envs.clone(),
1065 init.inherit_names.clone(),
1066 init.selection,
1067 init.cwd.clone(),
1068 )
1069 })
1070 })
1071 }
1072
1073 /// Enter a lexical scope: snapshot cwd/root/envs and open a fresh
1074 /// variable scope. Blocks scope everything (LET/ENV/WORKDIR/WORKSPACE);
1075 /// only pipes (ExecIo) and filesystem effects cross scope boundaries.
1076 /// Function definitions scope through the registry's own frames.
1077 pub(super) fn push_scope(&mut self) {
1078 self.scope_stack.push(ScopeSnapshot {
1079 cwd: self.cwd.clone(),
1080 selection: self.fs.selection(),
1081 envs: Arc::clone(&self.envs),
1082 });
1083 self.functions.push_scope();
1084 self.push_var_scope();
1085 }
1086
1087 /// Exit a lexical scope, restoring everything `push_scope` saved
1088 /// plus dropping block import frames deeper than the surviving
1089 /// stack, so block imports unwind with their block.
1090 pub(super) fn pop_scope(&mut self) -> Result<()> {
1091 let snapshot = self
1092 .scope_stack
1093 .pop()
1094 .ok_or_else(|| anyhow::anyhow!("scope stack underflow during pop"))?;
1095 self.fs.restore_selection(snapshot.selection);
1096 self.cwd = snapshot.cwd;
1097 self.envs = snapshot.envs;
1098 self.functions.pop_scope();
1099 self.pop_var_scope();
1100 let depth = self.scope_stack.len();
1101 self.scope_alias_frames.retain(|frame| frame.depth <= depth);
1102 Ok(())
1103 }
1104 pub(super) fn declare_var(&mut self, key: String, kind: TypeTag, value: Value) -> Result<()> {
1105 if self
1106 .var_scopes
1107 .last()
1108 .map(|s| s.contains_key(&key))
1109 .unwrap_or(false)
1110 {
1111 anyhow::bail!(
1112 "redeclaration error: ${} already declared in this scope; use ${} = ... to mutate",
1113 key,
1114 key
1115 );
1116 }
1117 let coerced = super::args::coerce_value(value, &kind)?;
1118 let scope = self
1119 .var_scopes
1120 .last_mut()
1121 .ok_or_else(|| anyhow::anyhow!("no variable scope for declaration"))?;
1122 scope.insert(key, (kind, coerced));
1123 Ok(())
1124 }
1125
1126 /// Declare a `CONST` binding: same namespace as
1127 /// [`declare_var`](Self::declare_var)
1128 /// (a `LET` and a `CONST` cannot share a name in one frame), then
1129 /// mark the frame const and deep-freeze the value, so nested
1130 /// containers freeze with the binding instead of aliasing a
1131 /// mutable buffer.
1132 pub(super) fn declare_const(&mut self, key: String, kind: TypeTag, value: Value) -> Result<()> {
1133 let at_entry_top = self.is_entry_top_level();
1134 if self
1135 .var_scopes
1136 .last()
1137 .map(|s| s.contains_key(&key))
1138 .unwrap_or(false)
1139 {
1140 anyhow::bail!(
1141 "redeclaration error: {key} already declared in this scope; {kw} bindings are immutable and cannot redeclare it",
1142 kw = KEYWORD_CONST,
1143 );
1144 }
1145 let coerced = super::args::coerce_value(value, &kind)?;
1146 let frozen = Value::deep_freeze(&coerced);
1147 let scope = self
1148 .var_scopes
1149 .last_mut()
1150 .ok_or_else(|| anyhow::anyhow!("no variable scope for declaration"))?;
1151 scope.insert(key.clone(), (kind.clone(), frozen.clone()));
1152 if let Some(frame) = self.const_scopes.last_mut() {
1153 frame.insert(key.clone());
1154 }
1155 if at_entry_top {
1156 // Entry prelude capture: the entry record's init store
1157 // holds the top-level `CONST`s seeded into every entry
1158 // call, mirroring how module inits drain theirs.
1159 if let Some(init) = self
1160 .modules
1161 .get_mut(super::import::ENTRY_UNIT)
1162 .and_then(|record| record.init.as_mut())
1163 {
1164 init.vars.insert(key.clone(), (kind, frozen));
1165 init.const_vars.insert(key);
1166 }
1167 }
1168 Ok(())
1169 }
1170
1171 /// Whether the entry-`CONST` fallback applies here: entry context
1172 /// (no owning module) whose caller is also entry (or top level).
1173 /// Entry callees called from module code stay params-only, so a
1174 /// module caller never observes entry file state. Single owner
1175 /// for the caller check every entry fallback reads.
1176 fn entry_fallback_allowed(&self) -> bool {
1177 if self.current_module().is_some() {
1178 return false;
1179 }
1180 match self.module_stack.len() {
1181 0 => true,
1182 1 => true,
1183 _ => matches!(
1184 self.module_stack.get(self.module_stack.len() - 2),
1185 None | Some(None)
1186 ),
1187 }
1188 }
1189
1190 /// Entry-`CONST` fallback init: the entry record's init when the
1191 /// fallback is allowed (entry context whose caller is also entry).
1192 /// Single owner for the caller check plus the init borrow, so
1193 /// every entry fallback reads hashes `ENTRY_UNIT` and checks the
1194 /// caller once. Call sites filter to `const_vars`, so `LET`s never
1195 /// cross.
1196 fn entry_const_init(&self) -> Option<&ModuleInit> {
1197 if !self.entry_fallback_allowed() {
1198 return None;
1199 }
1200 self.modules.get(super::import::ENTRY_UNIT)?.init.as_ref()
1201 }
1202
1203 /// Whether `key` names a `CONST` binding visible here: the
1204 /// innermost lexical frame holding the name decides (a local
1205 /// `LET` shadowing a module-level `CONST` stays mutable), exactly
1206 /// mirroring [`mutate_var`](Self::mutate_var)'s resolution; only
1207 /// when no lexical frame declares the name does the owning
1208 /// module's shared store answer. Single owner for the const check
1209 /// behind `$var = <expr>` reassignment and `LIST_APPEND`.
1210 pub(super) fn is_const_var(&self, key: &str) -> bool {
1211 for idx in (0..self.var_scopes.len()).rev() {
1212 if self.var_scopes[idx].contains_key(key) {
1213 return self
1214 .const_scopes
1215 .get(idx)
1216 .is_some_and(|frame| frame.contains(key));
1217 }
1218 }
1219 if let Some(module) = self.current_module()
1220 && let Some(record) = self.modules.get(&module)
1221 && let Some(init) = record.init.as_ref()
1222 && init.vars.contains_key(key)
1223 {
1224 return init.const_vars.contains(key);
1225 }
1226 // Entry `CONST`s are visible by fallback (#318): no synthetic
1227 // seed frame, just the init store filtered to consts.
1228 self.entry_const_init()
1229 .is_some_and(|init| init.vars.contains_key(key) && init.const_vars.contains(key))
1230 }
1231
1232 /// Shared declaration switch behind `LET` and `CONST` capture,
1233 /// async, and await paths: one call site per declare, so a new
1234 /// binding form cannot forget the const branch.
1235 pub(super) fn declare_binding(
1236 &mut self,
1237 key: String,
1238 kind: TypeTag,
1239 value: Value,
1240 is_const: bool,
1241 ) -> Result<()> {
1242 if is_const {
1243 self.declare_const(key, kind, value)
1244 } else {
1245 self.declare_var(key, kind, value)
1246 }
1247 }
1248
1249 pub(super) fn mutate_var(&mut self, key: &str, value: Value) -> Result<()> {
1250 if self.is_const_var(key) {
1251 return Err(const_mutation_error(key));
1252 }
1253 let kind = self
1254 .var_scopes
1255 .iter()
1256 .rev()
1257 .find_map(|s| s.get(key).map(|(k, _)| k.clone()))
1258 .or_else(|| self.module_var(key).map(|(k, _)| k.clone()))
1259 .ok_or_else(|| {
1260 anyhow::anyhow!(
1261 "undeclared variable ${key}: declare it first with LET ${key}: TYPE = ..."
1262 )
1263 })?;
1264 let coerced = super::args::coerce_value(value, &kind)?;
1265 for scope in self.var_scopes.iter_mut().rev() {
1266 if let Some(slot) = scope.get_mut(key) {
1267 slot.1 = coerced;
1268 return Ok(());
1269 }
1270 }
1271 // Not a lexical binding: update the owning module's shared
1272 // store in place, so every alias observes the mutation.
1273 if let Some((_, stored)) = self.module_var_mut(key) {
1274 *stored = coerced;
1275 return Ok(());
1276 }
1277 anyhow::bail!("undeclared variable ${key}");
1278 }
1279
1280 /// Append `item` to the LIST binding `key` in place. Copy-on-write:
1281 /// the buffer detaches only when shared, so aliases keep their
1282 /// contents; the sole owner mutates with no copy. Bails for
1283 /// undeclared names and non-list bindings. Shaped lists validate
1284 /// the item against the element tag, so a push can never silently
1285 /// corrupt the shape the declaration promises.
1286 pub(super) fn push_into_list(&mut self, key: &str, item: Value) -> Result<()> {
1287 if self.is_const_var(key) {
1288 return Err(const_mutation_error(key));
1289 }
1290 let kind = self
1291 .var_scopes
1292 .iter()
1293 .rev()
1294 .find_map(|s| s.get(key).map(|(k, _)| k.clone()))
1295 .or_else(|| self.module_var(key).map(|(k, _)| k.clone()))
1296 .ok_or_else(|| {
1297 anyhow::anyhow!(
1298 "undeclared variable ${key}: declare it first with LET ${key}: LIST<...> = ..."
1299 )
1300 })?;
1301 let element = match kind {
1302 TypeTag::List => None,
1303 TypeTag::ListOf(element) => Some(element.as_ref().clone()),
1304 _ => {
1305 anyhow::bail!("LIST_APPEND ${key}: variable is {}, not LIST", kind.name());
1306 }
1307 };
1308 for scope in self.var_scopes.iter_mut().rev() {
1309 if let Some(slot) = scope.get_mut(key) {
1310 if slot.1.is_frozen() {
1311 return Err(const_mutation_error(key));
1312 }
1313 let list = slot.1.as_list_mut().ok_or_else(|| {
1314 anyhow::anyhow!("LIST_APPEND ${key}: variable is not a LIST value")
1315 })?;
1316 if let Some(expected) = element {
1317 oxdock_parser::check_value_at(
1318 &expected,
1319 &item,
1320 &format!("{}[{}]", sigil_var(key), list.len()),
1321 )?;
1322 }
1323 list.push(item);
1324 return Ok(());
1325 }
1326 }
1327 // Not a lexical binding: append to the owning module's shared
1328 // store in place, so module-global lists stay appendable from
1329 // module-owned functions with no importer visibility.
1330 if let Some((_, value)) = self.module_var_mut(key) {
1331 if value.is_frozen() {
1332 return Err(const_mutation_error(key));
1333 }
1334 let list = value.as_list_mut().ok_or_else(|| {
1335 anyhow::anyhow!("LIST_APPEND ${key}: variable is not a LIST value")
1336 })?;
1337 if let Some(expected) = element {
1338 oxdock_parser::check_value_at(
1339 &expected,
1340 &item,
1341 &format!("{}[{}]", sigil_var(key), list.len()),
1342 )?;
1343 }
1344 list.push(item);
1345 return Ok(());
1346 }
1347 anyhow::bail!("undeclared variable ${key}");
1348 }
1349
1350 pub(super) fn get_var(&self, key: &str) -> Option<Value> {
1351 // Walk scopes from innermost to outermost
1352 for scope in self.var_scopes.iter().rev() {
1353 if let Some((_, value)) = scope.get(key) {
1354 return Some(value.clone());
1355 }
1356 }
1357 // Module-owned code falls back to the owning module's shared
1358 // store (#115): one file's functions share one global state.
1359 if let Some((_, value)) = self.module_var(key) {
1360 return Some(value.clone());
1361 }
1362 // Entry `CONST` fallback (#318): same init-store read the seed
1363 // frame copied, filtered to consts so `LET`s never cross.
1364 if let Some(init) = self.entry_const_init()
1365 && let Some((_, value)) = init.vars.get(key)
1366 && init.const_vars.contains(key)
1367 {
1368 return Some(value.clone());
1369 }
1370 None
1371 }
1372
1373 pub(super) fn get_var_typed(&self, key: &str) -> Option<(TypeTag, Value)> {
1374 for scope in self.var_scopes.iter().rev() {
1375 if let Some(entry) = scope.get(key) {
1376 return Some(entry.clone());
1377 }
1378 }
1379 if let Some(entry) = self.module_var(key) {
1380 return Some(entry.clone());
1381 }
1382 if let Some(init) = self.entry_const_init()
1383 && let Some(entry) = init.vars.get(key)
1384 && init.const_vars.contains(key)
1385 {
1386 return Some(entry.clone());
1387 }
1388 None
1389 }
1390
1391 /// Owning module of the executing code (#115): the top of the
1392 /// module stack when it names a module, `None` past an entry
1393 /// boundary or outside any module. Lookups stop at the first
1394 /// entry from the top, so entry functions called from module
1395 /// code stay params-only.
1396 pub(super) fn current_module(&self) -> Option<String> {
1397 match self.module_stack.last() {
1398 Some(Some(key)) => Some(key.clone()),
1399 _ => None,
1400 }
1401 }
1402
1403 /// Frame-1 file scope for one unit: entry and modules share this
1404 /// one lookup, so the runtime walk reads the same shape for both.
1405 /// `None` only when the unit record is absent (never after
1406 /// validation, which registers the entry record).
1407 pub(super) fn unit_top_funcs(&self, unit: &str) -> Option<&HashMap<String, Vec<RawFuncDef>>> {
1408 self.modules.get(unit).map(|record| &record.top_funcs)
1409 }
1410
1411 /// One lookup for the owning module's shared store (#115): the
1412 /// single fallback every variable accessor uses after its lexical
1413 /// walk misses, so module-global visibility lives in exactly one
1414 /// place. Entry code never reaches here (its boundary pushes
1415 /// `None`, and `current_module` yields nothing then).
1416 fn module_var(&self, key: &str) -> Option<&(TypeTag, Value)> {
1417 self.module_store()?.get(key)
1418 }
1419
1420 /// Mutable twin of [`ExecState::module_var`], for the two
1421 /// accessors that write through to the store in place.
1422 fn module_var_mut(&mut self, key: &str) -> Option<&mut (TypeTag, Value)> {
1423 self.module_store_mut()?.get_mut(key)
1424 }
1425
1426 /// Get a flattened view of all variables across all scopes.
1427 /// Inner scopes take precedence over outer scopes. Module-owned
1428 /// code additionally sees the owning module's shared store beneath
1429 /// every lexical frame; entry code sees the entry `CONST` fallback
1430 /// (filtered to consts) instead of a seed frame.
1431 pub(super) fn all_vars(&self) -> HashMap<String, Value> {
1432 let mut result = HashMap::new();
1433 for scope in self.var_scopes.iter().rev() {
1434 for (k, (_, v)) in scope {
1435 result.entry(k.clone()).or_insert_with(|| v.clone());
1436 }
1437 }
1438 if let Some(store) = self.module_store() {
1439 for (k, (_, v)) in store {
1440 result.entry(k.clone()).or_insert_with(|| v.clone());
1441 }
1442 }
1443 if let Some(init) = self.entry_const_init() {
1444 for (k, (_, v)) in &init.vars {
1445 if init.const_vars.contains(k) {
1446 result.entry(k.clone()).or_insert_with(|| v.clone());
1447 }
1448 }
1449 }
1450 result
1451 }
1452
1453 /// Borrow the owning module's shared store, if any. The single
1454 /// map behind [`ExecState::module_var`], exposed whole for the
1455 /// one accessor that flattens every binding.
1456 fn module_store(&self) -> Option<&HashMap<String, (TypeTag, Value)>> {
1457 let module = self.current_module()?;
1458 self.modules
1459 .get(&module)?
1460 .init
1461 .as_ref()
1462 .map(|init| &init.vars)
1463 }
1464
1465 /// Mutable twin of [`ExecState::module_store`], for the accessors
1466 /// that write through to the store in place.
1467 fn module_store_mut(&mut self) -> Option<&mut HashMap<String, (TypeTag, Value)>> {
1468 let module = self.current_module()?;
1469 self.modules
1470 .get_mut(&module)?
1471 .init
1472 .as_mut()
1473 .map(|init| &mut init.vars)
1474 }
1475}
1476
1477/// Mark every pipe handle reachable from `value` as shared-with-a-child.
1478/// Pipes travel inside lists and maps (`LET $bag: LIST = [$p]`), so a
1479/// shallow top-level check would miss them and let a later promotion
1480/// corrupt the shared EOF contract. Values form a tree, so recursion
1481/// terminates; host-opaque payloads cannot carry handles.
1482fn mark_value_pipes_escaped(value: &Value) {
1483 if let Some(handle) = value.as_pipe_handle() {
1484 handle.mark_escaped();
1485 return;
1486 }
1487 if let Some(items) = value.as_list() {
1488 for item in items {
1489 mark_value_pipes_escaped(item);
1490 }
1491 }
1492 if let Some(entries) = value.as_map() {
1493 for item in entries.values() {
1494 mark_value_pipes_escaped(item);
1495 }
1496 }
1497}