Skip to main content

submilli_engine/runtime/
mod.rs

1//! Wasmtime engine configuration for Submilli.
2
3use crate::runtime::durable::RunId;
4pub mod agents;
5pub(crate) mod array_storage;
6pub mod blocking;
7pub mod call_log;
8pub mod decision;
9pub mod default_filesystem;
10pub mod disk_quota;
11pub mod durable;
12pub mod effects;
13mod effects_memory;
14pub mod embedding;
15pub mod exec;
16pub mod filesystem;
17pub mod finalizers;
18pub mod fs;
19pub mod fuel;
20pub mod gc_singleton;
21pub mod host;
22pub mod intrinsic_types;
23pub mod json;
24pub(crate) mod json_text;
25pub mod limits;
26pub mod llm;
27pub mod mcp;
28pub mod metrics;
29pub mod model_calls;
30pub mod number;
31pub mod prelude;
32pub mod secrets;
33pub mod security;
34pub mod session_finalizers;
35pub mod session_kv;
36pub mod skills;
37pub mod token_ledger;
38pub mod tools;
39pub mod vfs;
40pub mod watchdog;
41
42pub use agents::{
43    AGENTS_MODULE_NAME, AgentCallError, AgentInfo, AgentOutcome, AgentProvider, AgentRequest,
44    AgentUsage,
45};
46pub use call_log::{BodyCopy, CallOutcome, CallRecord, ModelUsage, PayloadRecord};
47pub use decision::{
48    CallOrigin, CallSite, CallTicket, ConsoleLine, DecisionAction, DecisionCause,
49    DecisionExplanation, DecisionLog, DecisionLogConfig, DecisionLogOutput, DecisionRecord,
50    DecisionRecorder, EntryPath, FailureReasonRecord, FailureRecord, NearMissRecord, PackageLine,
51    RecordObserver, RuleCitation, SourceLine,
52};
53pub use disk_quota::{DiskQuota, Holder, OpenFileGuard, QuotaCharge, QuotaExceeded};
54pub use embedding::{
55    DEFAULT_MAX_EMBEDDING_REQUESTS, DEFAULT_MAX_EXECUTION_EMBEDDING_TOKENS, EMBEDDING_MODULE_NAME,
56    EmbeddingBatch, EmbeddingBoundKind, EmbeddingError, EmbeddingFailureReason, EmbeddingLimitKind,
57    EmbeddingLimits, EmbeddingMalformedReason, EmbeddingModel, EmbeddingProvider,
58    EmbeddingShapeError, EmbeddingTokenBudget, Purpose, SubBatchSettlement,
59    estimate_embedding_tokens,
60};
61pub use exec::{RunResult, dispatch_main_async, instantiate_program_async};
62pub use finalizers::{FinalizerCall, FinalizerError, invoke_finalizer_async};
63pub use host::{
64    INTERNAL_MODULE_NAME, NUMBER_MODULE_NAME, host_package_declarations,
65    install_async as install_runtime_async, install_async_for as install_runtime_async_for,
66    install_host_functions as install_runtime_host_functions,
67    install_host_functions_for as install_runtime_host_functions_for,
68    install_store_bound as install_runtime_store_bound, internal_host_package_declarations,
69    stdlib_package_declarations,
70};
71pub use json::JSON_MODULE_NAME;
72pub use limits::{
73    DEFAULT_MAX_STORE_BYTES, MemoryCapExceeded, MemoryExhausted, TenantLimits,
74    install_tenant_limits, is_memory_exhausted,
75};
76pub use llm::{
77    DEFAULT_MAX_ALL_EXECUTIONS_TOKENS, DEFAULT_MAX_EXECUTION_TOKENS, ExecutionTokenBudget,
78    FailureReason, LLM_MODULE_NAME, LlmCallError, LlmFailure, LlmLimitKind, LlmLimits, LlmModel,
79    LlmOutcome, LlmProvider, PromptBoundKind, SharedTokenBudget,
80};
81pub use mcp::{
82    MCP_MODULE_NAME, McpCallError, McpOutcome, McpResponse, McpTransport, install_mcp_async,
83    mcp_call_package_declaration,
84};
85pub use metrics::{HttpMetric, MetricsSink, NoopMetricsSink};
86pub use model_calls::{AttributedUsage, ModelCallUsage};
87pub use prelude::bigint::ops::BIGINT_MODULE_NAME;
88pub use prelude::temporal::shared::TEMPORAL_MODULE_NAME;
89pub use secrets::{EncryptedSecret, NoopSecretProvider, SecretKeyId, SecretProvider};
90pub use security::{AllowAllCheck, AuditDecision, CheckOutcome, SecurityCheck};
91pub use session_kv::{
92    CURSOR_KEY_ID_LEN, CursorKey, CursorKeys, InMemorySessionKv, SessionKvEntry, SessionKvError,
93    SessionKvFuture, SessionKvLimitKind, SessionKvLimits, SessionKvPage, SessionKvStore,
94    SessionKvUsage, entry_bytes, render_key, value_bytes,
95};
96pub use skills::{SKILLS_MODULE_NAME, Skill, SkillError, SkillInfo, SkillProvider};
97pub use tools::{
98    TOOLS_CAPABILITY, TOOLS_MODULE_NAME, TOOLS_PACKAGE, ToolCallError, ToolProvider,
99    install_tools_async, tools_call_package_declaration,
100};
101pub use vfs::{
102    Access, CopyDirError, MAX_MEASURED_DEPTH, MountError, MountSpec, Vfs, VfsMode, copy_host_dir,
103    copy_host_subdir, measure_dir, measure_host_dir, measure_host_dir_skipping_vanished,
104    measure_host_subdir_skipping_vanished, open_host_subdir, regular_files,
105};
106pub use watchdog::Watchdog;
107
108pub use crate::stdlib::http::{
109    AuthProxy, AuthProxyError, HttpClient, HttpError, HttpRequest, HttpResponse, NetworkPolicy,
110    NoopAuthProxy, ReqwestHttpClient,
111};
112
113use std::cell::RefCell;
114use std::io::Write;
115use std::sync::{Arc, Mutex};
116use std::time::Duration;
117
118use wasmtime::{
119    ArrayRef, AsContextMut, Config, Engine, Instance, Linker, Module, OptLevel, Rooted, Store,
120    WasmBacktraceDetails,
121};
122
123use crate::{PackageDeclaration, TypeInfoTable};
124
125/// Filesystem metadata surfaced to scripts via `submilli:fs.info()`: the
126/// active mode and the byte cap the VFS enforces, so the script — and the LLM —
127/// can branch on the sandbox shape. Never exposes the host path.
128#[derive(Debug, Clone)]
129pub struct VfsInfo {
130    pub mode: VfsMode,
131    pub size_limit: Option<u64>,
132}
133
134/// The JSON properties host-backed values show, by backing struct.
135pub(crate) type HostViews = Vec<(wasmtime::StructType, crate::stdlib::abi::HostProperties)>;
136
137pub struct StoreData {
138    #[cfg(test)]
139    pub(crate) array_growth: array_storage::GrowthStats,
140    /// After cancelling a host call, the execution owner drains this before
141    /// reusing or releasing the store. Blocking work may still be cleaning up.
142    pub blocking_work: blocking::BlockingWork,
143    pub git: Option<crate::stdlib::git::GitConfig>,
144    pub(crate) git_history: Option<Arc<crate::stdlib::git::log_cache::Cache>>,
145    pub console: Box<dyn Write + Send>,
146    pub vfs: Vfs,
147    pub filesystem: Arc<dyn filesystem::Filesystem>,
148    /// Native outcome history, installed before any guest initializer runs.
149    pub effects: Option<Arc<dyn effects::EffectHistory>>,
150    pub vfs_info: VfsInfo,
151    pub security_check: Arc<dyn SecurityCheck>,
152    pub fs_max_read_size: u64,
153    pub http_client: Arc<dyn HttpClient>,
154    pub http_max_response_size: u64,
155    /// Operator ceiling for a download, including streaming its body.
156    pub http_max_download_timeout_ms: u64,
157    pub auth_proxy: Arc<dyn AuthProxy>,
158    /// Immutable configuration resolved by the trusted session creator.
159    pub variables: Arc<std::collections::BTreeMap<String, String>>,
160    pub secret_provider: Arc<dyn SecretProvider>,
161    /// The outbound `@mcp/<server>` transport the `submilli:mcp.call` host fn
162    /// dispatches through, present when the embedder wires one. `None` in the
163    /// pure-interpreter path, where MCP calls throw "transport not configured".
164    pub mcp_transport: Option<Arc<dyn McpTransport>>,
165    /// The application tools `submilli:tools.call` (`@tools`) dispatches
166    /// through, present only when the embedder wires one. `None` makes every
167    /// call a catchable "no application tools" error.
168    pub tool_provider: Option<Arc<dyn ToolProvider>>,
169    /// Time this execution spent waiting outside the program on a host call
170    /// that must not count against its time limit (an application tool call).
171    /// An embedder's execution timeout subtracts it from the elapsed time.
172    pub clock_paused: std::time::Duration,
173    /// The model provider `submilli:llm` dispatches through, present only when
174    /// the embedder wires one. Left `None` the runtime has no model access at
175    /// all rather than silently completing against some default — the guest
176    /// surface reports that as a catchable configuration error
177    /// ([`LlmCallError::NotConfigured`]), the same rule `session_kv` follows.
178    pub llm_provider: Option<Arc<dyn LlmProvider>>,
179    /// This execution's token budget, reserving against its own ceiling and the
180    /// server-wide one together. `None` in the pure-interpreter path, where
181    /// there is no aggregate to protect and nothing to charge against; the
182    /// prompt-count and prompt-size bounds still apply there, because they
183    /// bound pathological shapes rather than spend. The embedder installs one
184    /// per execution, and dropping it is what returns the reservation.
185    pub llm_budget: Option<Arc<ExecutionTokenBudget>>,
186    /// The provider `submilli:embedding` dispatches through, present only when
187    /// the embedder wires one. `None` means the guest sees a catchable
188    /// [`EmbeddingError::NotConfigured`], never a silent default.
189    pub embedding_provider: Option<Arc<dyn EmbeddingProvider>>,
190    /// This execution's embedding budget (tokens and outbound requests). `None`
191    /// in the pure-interpreter path; dropping it returns unspent reservation.
192    pub embedding_budget: Option<Arc<EmbeddingTokenBudget>>,
193    /// Live `submilli:llm` and `submilli:embedding` dispatches in this attempt.
194    /// The embedder reads [`Self::model_calls`] after guest code finishes.
195    model_calls: Vec<ModelCallUsage>,
196    /// Session-scoped key-value storage, present only when the embedder wires a
197    /// provider. Left `None` the store stays absent rather than silently
198    /// becoming per-execution scratch state that no later `execute` can read —
199    /// the guest surface reports that as a configuration error.
200    pub session_kv: Option<Arc<dyn SessionKvStore>>,
201    /// Durable package-owned resource cleanup supplied by the embedder.
202    pub session_finalizers: Option<Arc<dyn session_finalizers::SessionFinalizers>>,
203    pub finalizing: bool,
204    /// The keys `session.list` cursors are sealed with. `None` seals them with a
205    /// per-process key, so they stop working when the process restarts.
206    pub cursor_keys: Option<Arc<CursorKeys>>,
207    /// The harness `submilli:agents` runs sub-agents through, present only when
208    /// the embedder wires one. `None` makes every call a catchable
209    /// [`AgentCallError::NotConfigured`].
210    pub agent_provider: Option<Arc<dyn AgentProvider>>,
211    /// The harness `submilli:skills` reads skills through, present only when the
212    /// embedder wires one. `None` makes every call a catchable
213    /// [`SkillError::NotConfigured`].
214    pub skill_provider: Option<Arc<dyn SkillProvider>>,
215    /// Embedder sink for host-operation metrics (HTTP transport latencies).
216    /// Defaults to [`NoopMetricsSink`]; the server installs a Sentry-backed one.
217    pub metrics: Arc<dyn metrics::MetricsSink>,
218    pub tenant_limits: TenantLimits,
219    /// Fuel charged by host functions for their own work; the rest of the fuel
220    /// spent went to Wasm instructions. See [`fuel::charge_host_fuel`].
221    pub host_fuel: u64,
222    pub(crate) next_identity_hash: u64,
223    #[cfg(test)]
224    pub(crate) collection_index_reads: u64,
225    #[cfg(test)]
226    pub(crate) object_index_probes: u64,
227    /// Host charges not yet applied to the engine's fuel (see
228    /// [`fuel::HOST_FUEL_BATCH`]).
229    pub host_fuel_pending: u64,
230    /// The engine's fuel right after the last application of pending host
231    /// charges; `None` before the first.
232    pub host_fuel_applied_at: Option<u64>,
233    /// Test-segment labels recorded by `submilli:test.label`, in call order.
234    /// Only the test runner installs that host fn; an ordinary run leaves this
235    /// empty. The runner reads it after `main()` returns to attribute the
236    /// pass/fail outcome to the segment that was open at the time.
237    pub test_labels: RefCell<Vec<String>>,
238    /// Recovered runtime types + the prelude instance handle host functions use
239    /// to build *real* `$string`/`$Array` structs (vtable + payload) instead of
240    /// raw arrays. `None` until the prelude instantiates; set by
241    /// `install_prelude_async`. See [`crate::runtime::host::HostAbi`].
242    pub host_abi: Option<crate::runtime::host::HostAbi>,
243    /// This store's intrinsic types, built on first use; see
244    /// [`crate::runtime::intrinsic_types::intrinsic_types`].
245    pub(crate) intrinsic_types: Option<Arc<crate::runtime::intrinsic_types::IntrinsicTypes>>,
246    /// The JSON properties of each host-backed value's backing struct, built on
247    /// first use; see [`crate::stdlib::abi::json_properties`].
248    pub(crate) host_views: Option<HostViews>,
249    /// An immutable global keeps the store's undefined value rooted across calls.
250    pub(crate) undefined_value: Option<wasmtime::Global>,
251    /// The bound-receiver closure environment type, built on first use for the
252    /// same reason as [`Self::intrinsic_types`].
253    pub(crate) closure_receiver_type: Option<wasmtime::StructType>,
254    /// The call-metadata closure environment type, built on first use for the
255    /// same reason as [`Self::intrinsic_types`].
256    pub(crate) call_metadata_type: Option<wasmtime::StructType>,
257    pub(crate) iterator_functions: [Option<wasmtime::Func>; 13],
258    pub(crate) iterator_constants: [Option<wasmtime::Global>; 6],
259    /// The object each static-dispatch binding is as a value, by its string
260    /// form; see `prelude::object::static_value`.
261    pub(crate) static_values: std::collections::BTreeMap<Vec<u16>, wasmtime::Global>,
262    pub(crate) parameter_cache: prelude::arguments::ParameterCache,
263    pub(crate) regex_input: Option<prelude::regex::input::InputCache>,
264    /// Runtime type metadata keyed by package name.
265    pub type_info: std::collections::BTreeMap<String, TypeInfoTable>,
266    /// Depth of the in-flight universal-vtable walk; see
267    /// [`MAX_VTABLE_WALK_DEPTH`].
268    pub vtable_walk_depth: u32,
269    /// Hook entries in the current outer structural walk, including repeated
270    /// visits to shared children. Reset only when the outer walk finishes.
271    pub(crate) vtable_walk_nodes: u32,
272    /// Host-only result marshalling after an effect must not refuse for fuel.
273    pub(crate) settling_host_result: bool,
274    /// Denials the runtime threw, by thrown object; see [`host::ThrownDenials`].
275    pub(crate) thrown_denials: host::ThrownDenials,
276}
277
278/// The nesting the universal-vtable walk allows before it reports a runaway.
279///
280/// Pinned to `serde_json`'s own recursion limit, which is what bounds
281/// `JSON.parse`: a document the runtime is willing to parse must still be
282/// comparable and re-serializable, or `JSON.parse` would accept graphs that
283/// `JSON.stringify` then refuses. Measured headroom: a debug build on a 2 MB
284/// test-harness thread aborts between 160 and 200 levels, so the bound sits
285/// below the point where the native stack runs out.
286pub(crate) const MAX_VTABLE_WALK_DEPTH: u32 = 128;
287
288/// Bounds shared-substructure expansion independently of available fuel.
289pub(crate) const MAX_STRUCTURAL_WALK_NODES: u32 = 100_000;
290
291pub const DEFAULT_FS_MAX_READ_SIZE: u64 = 50 * 1024 * 1024;
292
293pub const DEFAULT_HTTP_MAX_RESPONSE_SIZE: u64 = 50 * 1024 * 1024;
294
295#[derive(Clone, Copy)]
296pub struct LinkedPackageModule<'a> {
297    pub module: &'a Module,
298    pub declaration: &'a PackageDeclaration,
299    pub type_info: &'a TypeInfoTable,
300}
301
302impl StoreData {
303    pub fn with_vfs(run_id: RunId, vfs: Vfs) -> Self {
304        Self::with_vfs_and_cap(run_id, vfs, DEFAULT_MAX_STORE_BYTES)
305    }
306
307    pub fn with_vfs_and_cap(run_id: RunId, vfs: Vfs, max_store_bytes: u64) -> Self {
308        let vfs_info = VfsInfo {
309            mode: vfs.mode(),
310            size_limit: None,
311        };
312        Self {
313            #[cfg(test)]
314            array_growth: array_storage::GrowthStats::default(),
315            console: Box::new(std::io::stderr()),
316            filesystem: Arc::new(default_filesystem::DefaultFilesystem::new(
317                vfs.clone(),
318                run_id,
319            )),
320            effects: None,
321            vfs,
322            vfs_info,
323            security_check: security::default_check(),
324            git: None,
325            git_history: None,
326            blocking_work: blocking::BlockingWork::default(),
327            fs_max_read_size: DEFAULT_FS_MAX_READ_SIZE,
328            http_client: crate::stdlib::http::default_http_client(),
329            http_max_response_size: DEFAULT_HTTP_MAX_RESPONSE_SIZE,
330            http_max_download_timeout_ms: 60_000,
331            auth_proxy: crate::stdlib::http::default_auth_proxy(),
332            variables: Arc::default(),
333            secret_provider: Arc::new(secrets::NoopSecretProvider),
334            mcp_transport: None,
335            tool_provider: None,
336            clock_paused: std::time::Duration::ZERO,
337            llm_provider: None,
338            llm_budget: None,
339            embedding_provider: None,
340            embedding_budget: None,
341            model_calls: Vec::new(),
342            session_kv: None,
343            session_finalizers: None,
344            finalizing: false,
345            cursor_keys: None,
346            agent_provider: None,
347            skill_provider: None,
348            metrics: Arc::new(metrics::NoopMetricsSink),
349            tenant_limits: TenantLimits::new(max_store_bytes),
350            host_fuel: 0,
351            #[cfg(test)]
352            collection_index_reads: 0,
353            #[cfg(test)]
354            object_index_probes: 0,
355            next_identity_hash: 0,
356            host_fuel_pending: 0,
357            host_fuel_applied_at: None,
358            test_labels: RefCell::new(Vec::new()),
359            host_abi: None,
360            intrinsic_types: None,
361            host_views: None,
362            undefined_value: None,
363            closure_receiver_type: None,
364            call_metadata_type: None,
365            iterator_functions: [None; 13],
366            iterator_constants: [None; 6],
367            static_values: std::collections::BTreeMap::new(),
368            parameter_cache: Default::default(),
369            regex_input: None,
370            type_info: std::collections::BTreeMap::new(),
371            vtable_walk_depth: 0,
372            vtable_walk_nodes: 0,
373            settling_host_result: false,
374            thrown_denials: host::ThrownDenials::default(),
375        }
376    }
377
378    pub fn install_type_info(&mut self, table: TypeInfoTable) {
379        self.type_info.insert(table.package_name.clone(), table);
380    }
381
382    /// Live model dispatches in this attempt, in call order.
383    ///
384    /// Empty when none ran. A guest trap does not clear it: a call that already
385    /// returned was billed. Read this after `dispatch_main_async`, before
386    /// dropping the store. [`ModelCallUsage::summed_by_model`] folds it per model.
387    pub fn model_calls(&self) -> &[ModelCallUsage] {
388        &self.model_calls
389    }
390
391    /// Append one live dispatch. Only the provider action may call this.
392    ///
393    /// Replay restores the recorded outcome without running that action.
394    /// Recording after `effects::execute` returns would bill the call again.
395    pub(crate) fn note_model_call(&mut self, call: ModelCallUsage) {
396        self.model_calls.push(call);
397    }
398
399    pub fn with_tempdir() -> std::io::Result<Self> {
400        Ok(Self::with_vfs(RunId::generate()?, Vfs::tempdir()?))
401    }
402}
403
404/// Instantiates each linked package module, running its module-level initializers.
405///
406/// Every thread polling this future must meet
407/// [`RuntimeConfig::native_stack_size`]'s caller contract.
408pub async fn install_package_modules_async(
409    linker: &mut Linker<StoreData>,
410    store: &mut Store<StoreData>,
411    packages: &[LinkedPackageModule<'_>],
412) -> wasmtime::Result<()> {
413    for package in packages {
414        let name = package.declaration.package_name.as_str();
415        if store.data().git.is_none()
416            && package
417                .module
418                .imports()
419                .any(|import| import.module() == "submilli:git")
420        {
421            wasmtime::bail!(
422                "package `{name}` imports submilli:git; configure the blueprint git block"
423            );
424        }
425        // The module's declared name *is* its principal at every gated call, so bind it to the
426        // name the package is being linked under. Without this, a prebuilt `pkg.wasm` naming
427        // itself `main` — or naming another package — would be granted that principal's
428        // permissions and, for `main`, the operator's injected credentials. The bytes are not
429        // necessarily ones this compiler produced: `submilli run` and the server both
430        // instantiate artifacts straight from the package store.
431        match package.module.name() {
432            Some(declared) if declared == name => {}
433            Some(declared) => wasmtime::bail!(
434                "package `{name}`: its module declares the name `{declared}`, which would give \
435                 it that principal's permissions. Rebuild the package."
436            ),
437            None => wasmtime::bail!(
438                "package `{name}`: its module declares no name, so its gated calls cannot be \
439                 attributed. Rebuild the package."
440            ),
441        }
442        store
443            .data_mut()
444            .install_type_info(package.type_info.clone());
445        // Instantiation runs the package's module-level initializers. They are the
446        // package's own code, executing in the package's own module, so identity read
447        // off the running frame names them without any bracketing here.
448        let instance = {
449            let outcome = linker.instantiate_async(&mut *store, package.module).await;
450            name_the_failing_initializer(&mut *store, name, outcome)?
451        };
452        linker.instance(&mut *store, name, instance)?;
453    }
454    Ok(())
455}
456
457/// Initializers run inside the Wasm start function, so anything they throw —
458/// a denial most of all — escapes instantiation as the engine's opaque
459/// `ThrownException`, whose Display is "wasm exception thrown". The thrown
460/// value is still on the store, so recover its text the way an uncaught throw
461/// from `main` is recovered and say which package it came from. Without this an
462/// operator who granted a capability under `main:` rather than the package's own
463/// block — the mistake this attribution makes easy — gets no package, no
464/// capability, and no reason.
465fn name_the_failing_initializer(
466    store: &mut Store<StoreData>,
467    package: &str,
468    outcome: wasmtime::Result<Instance>,
469) -> wasmtime::Result<Instance> {
470    let err = match outcome {
471        Ok(instance) => return Ok(instance),
472        Err(err) => err,
473    };
474    let recovered = exec::uncaught_error(store, err);
475    let Some(thrown) = recovered.downcast_ref::<crate::backtrace::ThrownError>() else {
476        return Err(recovered);
477    };
478    Err(wasmtime::Error::new(crate::backtrace::ThrownError {
479        message: format!(
480            "package `{package}` failed to initialize: {}",
481            thrown.message
482        ),
483        backtrace: thrown.backtrace.clone(),
484        denial: thrown.denial.clone(),
485    }))
486}
487
488/// Native stack bytes per byte of `max_wasm_stack`; see
489/// [`RuntimeConfig::native_stack_size`].
490const NATIVE_STACK_PER_WASM_BYTE: usize = 32;
491const MIN_NATIVE_STACK: usize = 8 * 1024 * 1024;
492
493#[derive(Clone, Debug)]
494pub struct RuntimeConfig {
495    pub fuel: u64,
496    pub max_wasm_stack: usize,
497    pub memory_reservation: u64,
498    pub memory_guard_size: u64,
499    pub memory_reservation_for_growth: u64,
500    pub max_store_bytes: u64,
501    pub timeout: Option<Duration>,
502    pub async_yield_fuel: Option<u64>,
503}
504
505impl Default for RuntimeConfig {
506    fn default() -> Self {
507        Self {
508            // Temporarily very high: large structural JSON.stringify and other
509            // per-code-unit Wasm work still burns fuel, and exhausting it mid-run
510            // is a worse failure than the loose runaway-loop bound this gives up.
511            // The real CPU cap belongs in a wall-clock timeout; revisit once the
512            // hot encoding paths are off the meter.
513            fuel: 1_000_000_000_000,
514            max_wasm_stack: 512 * 1024,
515            memory_reservation: 3 * 1024 * 1024,
516            memory_guard_size: 64 * 1024,
517            memory_reservation_for_growth: 16 * 1024 * 1024,
518            max_store_bytes: DEFAULT_MAX_STORE_BYTES,
519            timeout: None,
520            // 10K fuel ≈ ~10K wasm instructions. At the default fuel budget a
521            // CPU-bound full-budget call yields thousands of times before
522            // exhaustion — fine-grained enough for fair scheduling, coarse enough
523            // that yield overhead stays negligible.
524            async_yield_fuel: Some(10_000),
525        }
526    }
527}
528
529impl RuntimeConfig {
530    /// The native stack a thread running programs under this config needs.
531    ///
532    /// `max_wasm_stack` is an interpreter budget, but a host call that re-enters
533    /// Wasm (a callback passed to `map`, say) nests interpreter frames on the
534    /// thread's own stack. The engine charges each crossing 4 KiB of the budget;
535    /// this bounds re-entry depth, not the thread's available native stack. Debug
536    /// builds have measured about 64 KiB per crossing, so this reservation allows
537    /// 128 KiB per crossing, with an 8 MiB minimum for setup and shallow calls.
538    ///
539    /// Embedders must provide this stack on every thread that polls execution,
540    /// including after an async task migrates between workers. The runners do not
541    /// create a thread or inspect remaining stack space. Poll them near the root
542    /// of the thread, rather than underneath deep native recursion. Undersized
543    /// stacks can overflow and abort the process instead of returning a trap.
544    /// Custom host functions must also bound their own native recursion.
545    ///
546    /// Set a Tokio runtime's `thread_stack_size` for worker threads. Its
547    /// `block_on` caller runs on the calling thread, so size that thread separately
548    /// (also for a current-thread runtime or `pollster::block_on`). Compilation
549    /// separately requires [`crate::compiler_limits::COMPILER_STACK_BYTES`]; use
550    /// the larger requirement when a thread performs both operations.
551    pub fn native_stack_size(&self) -> usize {
552        self.max_wasm_stack
553            .saturating_mul(NATIVE_STACK_PER_WASM_BYTE)
554            .max(MIN_NATIVE_STACK)
555    }
556
557    pub fn engine(&self) -> wasmtime::Result<Engine> {
558        Engine::new(&self.wasmtime_config())
559    }
560
561    /// Same as [`engine`](Self::engine). `Config::async_support` is a no-op in
562    /// wasmtime 44+; this entry point exists so async embedders have a distinct
563    /// call site to evolve independently.
564    pub fn engine_async(&self) -> wasmtime::Result<Engine> {
565        Engine::new(&self.wasmtime_config())
566    }
567
568    pub fn wasmtime_config(&self) -> Config {
569        let mut config = Config::new();
570        // Winch lacks `wasm_gc` + `wasm_function_references`; Pulley is ~10× slower.
571        // Strategy::Auto → Cranelift JIT.
572        //
573        // No optimization passes: the per-request user script is compiled fresh by
574        // `Module::new` (it can't be AOT-cached — it's LLM-generated), and for
575        // short-lived scripts that compile cost dominates the run. The trade is
576        // global, though: precompiled prelude/stdlib share this engine, so they run
577        // unoptimized too. TODO: precompile stdlib + curated packages on a separate
578        // high-opt engine and `deserialize` the optimized artifacts here, so only the
579        // user script pays the unoptimized-codegen tax.
580        config.cranelift_opt_level(OptLevel::None);
581        config.consume_fuel(true);
582        config.max_wasm_stack(self.max_wasm_stack);
583
584        config.epoch_interruption(true);
585
586        config.memory_reservation(self.memory_reservation);
587        config.memory_guard_size(self.memory_guard_size);
588        config.memory_reservation_for_growth(self.memory_reservation_for_growth);
589        config.memory_may_move(true);
590        config.memory_init_cow(true);
591
592        // The engine grants this reservation without consulting the store limiter.
593        // Start at zero so every GC byte is charged to the tenant's aggregate cap,
594        // including stores whose cap differs from this engine's RuntimeConfig.
595        config.gc_heap_reservation(0);
596        config.gc_heap_guard_size(self.memory_guard_size);
597        config.gc_heap_reservation_for_growth(self.memory_reservation_for_growth);
598        config.gc_heap_may_move(true);
599
600        config.wasm_gc(true);
601        config.wasm_function_references(true);
602        config.wasm_exceptions(true);
603
604        config.wasm_backtrace_details(WasmBacktraceDetails::Enable);
605
606        config
607    }
608
609    pub fn store<T>(&self, engine: &Engine, data: T) -> wasmtime::Result<Store<T>> {
610        let mut store = Store::new(engine, data);
611        store.set_fuel(self.fuel)?;
612        // With epoch_interruption(true), an unset deadline traps immediately.
613        // Use 1 for watchdog-tripped timeouts, MAX to effectively disable.
614        let delta = if self.timeout.is_some() { 1 } else { u64::MAX };
615        store.set_epoch_deadline(delta);
616        store.epoch_deadline_trap();
617        Ok(store)
618    }
619
620    pub fn store_async<T>(&self, engine: &Engine, data: T) -> wasmtime::Result<Store<T>> {
621        let mut store = self.store(engine, data)?;
622        store.fuel_async_yield_interval(self.async_yield_fuel)?;
623        Ok(store)
624    }
625
626    /// Arm the configured timeout, failing setup if its thread cannot be created.
627    /// Keep the returned guard alive until guest execution finishes.
628    pub fn arm_timeout(&self, engine: &Engine) -> wasmtime::Result<Option<Watchdog>> {
629        self.timeout
630            .map(|duration| watchdog::arm(engine, duration))
631            .transpose()
632            .map_err(|error| {
633                wasmtime::Error::from(error).context("starting execution timeout watchdog")
634            })
635    }
636
637    /// One-shot runner: load compiled Wasm, instantiate, call `main`, return typed result
638    /// and captured console. Async like the rest of the runtime — a caller that
639    /// isn't on a runtime bridges it itself (`pollster::block_on` for pure
640    /// computation, a Tokio runtime for filesystem or HTTP operations). For
641    /// live console streaming, build a custom `Store<StoreData>` and call
642    /// [`dispatch_main_async`] directly.
643    ///
644    /// # Native stack
645    ///
646    /// Every thread polling this future must meet [`Self::native_stack_size`]'s
647    /// caller contract. This method does not provision a stack. Compilation
648    /// separately requires [`crate::compiler_limits::COMPILER_STACK_BYTES`].
649    pub async fn run(&self, wasm_bytes: &[u8]) -> wasmtime::Result<RunResult> {
650        self.run_with_type_info(wasm_bytes, None).await
651    }
652
653    /// Runs a compiled script with its result type information and captured console.
654    ///
655    /// # Native stack
656    ///
657    /// Every thread polling this future must meet [`Self::native_stack_size`]'s
658    /// caller contract, just as for [`Self::run`]. Compiling the script separately
659    /// requires [`crate::compiler_limits::COMPILER_STACK_BYTES`].
660    pub async fn run_compiled(
661        &self,
662        compiled: &crate::compile::CompiledScript,
663    ) -> wasmtime::Result<RunResult> {
664        self.run_with_type_info(&compiled.wasm, Some(compiled.type_info.clone()))
665            .await
666    }
667
668    async fn run_with_type_info(
669        &self,
670        wasm_bytes: &[u8],
671        type_info: Option<TypeInfoTable>,
672    ) -> wasmtime::Result<RunResult> {
673        let buf = Arc::new(Mutex::new(Vec::new()));
674        let mut data =
675            StoreData::with_vfs_and_cap(RunId::generate()?, Vfs::tempdir()?, self.max_store_bytes);
676        data.console = Box::new(ConsoleSink(Arc::clone(&buf)));
677        if let Some(type_info) = type_info {
678            data.install_type_info(type_info);
679        }
680        let engine = self.engine()?;
681        let mut store = self.store_async(&engine, data)?;
682        install_tenant_limits(&mut store);
683        let module = Module::new(&engine, wasm_bytes)?;
684        let mut linker = Linker::<StoreData>::new(&engine);
685        install_runtime_async(&mut linker, &mut store).await?;
686        let _watchdog = self.arm_timeout(&engine)?;
687        let inst = instantiate_program_async(&linker, &mut store, &module).await?;
688        let value = dispatch_main_async(&mut store, &inst).await?;
689        // A poisoned ConsoleSink may contain output from an interrupted write.
690        // AGENTS.md permits this poisoned-lock panic instead of recovering partial
691        // output; it does not permit the panic that caused poisoning.
692        let captured = buf.lock().expect("console buffer lock poisoned").clone();
693        let console = String::from_utf8(captured)
694            .map_err(|e| wasmtime::Error::msg(format!("console output not utf-8: {e}")))?;
695        Ok(RunResult { value, console })
696    }
697}
698
699// A panic during writing may leave partial console output. AGENTS.md permits
700// panicking on poisoned access instead of recovering it; the panic that caused
701// poisoning is still subject to the no-panic policy.
702struct ConsoleSink(Arc<Mutex<Vec<u8>>>);
703
704impl Write for ConsoleSink {
705    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
706        self.0
707            .lock()
708            .expect("console buffer lock poisoned")
709            .write(buf)
710    }
711
712    fn flush(&mut self) -> std::io::Result<()> {
713        Ok(())
714    }
715}
716
717/// Decode a Submilli `(ref $string)` (packed UTF-16) into a Rust `String`.
718pub(crate) fn read_submilli_string(
719    mut ctx: impl AsContextMut<Data = StoreData>,
720    msg: Rooted<ArrayRef>,
721) -> wasmtime::Result<String> {
722    let units = host::read_code_units(&mut ctx, msg, "string")?;
723    fuel::charge(ctx, fuel::SCAN, units.len() as u64)?;
724    Ok(String::from_utf16_lossy(&units))
725}